forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

rules.rs188 lines, 6.6 KiBHistoryRawDownload
1//! Markdown-style input rules (the TS editor's `inputRules`), matched by hand:
2//! `# `..`### `, "```", `- `/`* `, `1. `, `> `, `---`, `**x**`, `*x*`, `` `x` ``.
3//! A rule replaces the typed text; Backspace right after it undoes the rule and
4//! types the text instead.
5
6use note_model::flat::Kind as Leaf;
7
8use crate::core::commands::{self as c, Cx};
9use crate::core::doc::Kind;
10use crate::core::marks::MarkType;
11use crate::core::model::Blk;
12use crate::core::pos::{Pos, Selection};
13use crate::editor::Editor;
14
15/// Whether typing `data` could complete a rule (such text is never left to the browser).
16pub fn may_trigger(data: &str) -> bool {
17 data.ends_with([' ', '\u{a0}', '`', '*', '-'])
18}
19
20fn is_ws(c: char) -> bool {
21 c.is_whitespace()
22}
23
24enum Rule {
25 Block(Kind),
26 Wrap(Kind, Option<i64>),
27 Rule,
28 Mark(MarkType, usize /* content start (utf16) */, usize /* content len */, usize /* delim */),
29}
30
31/// How far back (UTF-16 units) mark rules look for their opening delimiter.
32const RULE_WINDOW: usize = 2000;
33
34fn match_rule(s: &str, whole: bool) -> Option<Rule> {
35 let chars: Vec<char> = s.chars().collect();
36 let n = if whole { chars.len() } else { 0 };
37 // Block rules match the whole text before the caret.
38 if (2..=4).contains(&n) && is_ws(chars[n - 1]) && chars[..n - 1].iter().all(|&c| c == '#') {
39 return Some(Rule::Block(Kind::Heading((n - 1) as u8)));
40 }
41 if whole && s == "```" {
42 return Some(Rule::Block(Kind::CodeBlock));
43 }
44 if whole && s == "---" {
45 return Some(Rule::Rule);
46 }
47 if n >= 2 && is_ws(chars[n - 1]) {
48 let head = &chars[..n - 1];
49 let lead = head.iter().take_while(|c| is_ws(**c)).count();
50 let rest = &head[lead..];
51 if rest == ['-'] || rest == ['*'] {
52 return Some(Rule::Wrap(Kind::BulletList, None));
53 }
54 if rest == ['>'] {
55 return Some(Rule::Wrap(Kind::Blockquote, None));
56 }
57 if lead == 0 && rest.len() >= 2 && rest[rest.len() - 1] == '.' && rest[..rest.len() - 1].iter().all(char::is_ascii_digit) {
58 let num: String = rest[..rest.len() - 1].iter().collect();
59 let order = num.parse::<i64>().ok()?;
60 return Some(Rule::Wrap(Kind::OrderedList, Some(order)));
61 }
62 }
63 // Mark rules match the end.
64 let u: Vec<u16> = s.encode_utf16().collect();
65 let l = u.len();
66 let star = b'*' as u16;
67 let tick = b'`' as u16;
68 // Start of the run of non-delimiter units ending just before `end`.
69 let run_start = |end: usize, d: u16| (0..end).rev().take_while(|&i| u[i] != d).last();
70 if l >= 5 && u[l - 1] == star && u[l - 2] == star {
71 let ce = l - 2;
72 if let Some(cs) = run_start(ce, star)
73 && cs >= 2
74 && u[cs - 1] == star
75 && u[cs - 2] == star
76 && ce > cs
77 {
78 return Some(Rule::Mark(MarkType::Strong, cs, ce - cs, 2));
79 }
80 }
81 for (mark, d) in [(MarkType::Em, star), (MarkType::Code, tick)] {
82 if l >= 3 && u[l - 1] == d && u[l - 2] != d {
83 let ce = l - 1;
84 if let Some(cs) = run_start(ce, d)
85 && cs >= 1
86 && u[cs - 1] == d
87 && (mark != MarkType::Em || cs == 1 || u[cs - 2] != star)
88 {
89 return Some(Rule::Mark(mark, cs, ce - cs, 1));
90 }
91 }
92 }
93 None
94}
95
96/// Tries the rules for `data` typed at the caret. Applies one and returns true.
97pub fn apply(ed: &mut Editor, data: &str) -> bool {
98 let Some(p) = ed.sel.cursor() else { return false };
99 let b = ed.m.at(p);
100 if !b.kind().is_text() || b.kind() == Leaf::Code {
101 return false;
102 }
103 // Mark rules look back within one stretch of text; block rules need the whole
104 // text before the caret, which is short whenever one can match.
105 let from = p.saturating_sub(RULE_WINDOW).max(b.start);
106 let s = ed.m.plain(from, p) + data;
107 let Some(rule) = match_rule(&s, from == b.start) else { return false };
108 let rule = match rule {
109 Rule::Mark(m, cs, len, d) => Rule::Mark(m, cs + from, len, d),
110 r => r,
111 };
112 ed.checkpoint();
113 let ran = ed.run(|cx| run_rule(cx, &b, p, rule));
114 if ran {
115 ed.checkpoint();
116 ed.last_rule = Some((ed.doc.state_frontiers(), data.to_owned()));
117 }
118 ran
119}
120
121/// Whether `b` is the first block of a list item (where PM's rules don't apply).
122fn starts_item(cx: &Cx, b: &Blk) -> bool {
123 if !b.attrs.wrap.last().is_some_and(|w| w.is_list()) {
124 return false;
125 }
126 let prev = b.index.checked_sub(1).and_then(|i| cx.m.block(i));
127 c::keep(prev.as_ref().map(|p| &p.attrs), &b.attrs) < b.depth()
128}
129
130fn run_rule(cx: &mut Cx, b: &Blk, off: Pos, rule: Rule) -> bool {
131 match rule {
132 Rule::Block(kind) => {
133 if !c::can_retype(cx.m, b, kind.leaf().expect("a leaf kind")) {
134 return false;
135 }
136 cx.m.delete(b.start, off);
137 cx.sel = Selection::caret(b.start);
138 c::set_block_type(cx, kind, true)
139 }
140 Rule::Rule => {
141 if starts_item(cx, b) {
142 return false;
143 }
144 cx.m.delete(b.start, off);
145 cx.sel = Selection::caret(b.start);
146 if b.kind() != Leaf::Para {
147 c::set_block_type(cx, Kind::Paragraph, true);
148 }
149 c::insert_rule(cx, true)
150 }
151 Rule::Wrap(kind, start) => {
152 if starts_item(cx, b) {
153 return false;
154 }
155 cx.m.delete(b.start, off);
156 cx.sel = Selection::caret(b.start);
157 if kind == Kind::Blockquote { c::wrap_in(cx, kind, true) } else { c::wrap_in_list(cx, kind, start, true) }
158 }
159 Rule::Mark(mark, cs, len, delim) => {
160 // The closing delimiter is one character short in the doc: the last one was typed.
161 let close_in_doc = delim - 1;
162 let ce = cs + len;
163 cx.m.delete(ce, ce + close_in_doc);
164 cx.m.delete(cs - delim, cs);
165 let from = cs - delim;
166 c::add_mark(cx.m, from, from + len, mark);
167 cx.sel = Selection::caret(from + len);
168 cx.stored = None;
169 let mut m = c::pending_marks(cx);
170 m.set(mark, false);
171 cx.stored = Some(m);
172 true
173 }
174 }
175}
176
177/// Backspace right after a rule: undo it and type the text it consumed.
178pub fn undo_rule(ed: &mut Editor) -> bool {
179 let Some((frontiers, text)) = ed.last_rule.take() else { return false };
180 if ed.doc.state_frontiers() != frontiers || !ed.sel.is_empty() {
181 return false;
182 }
183 if !ed.undo() {
184 return false;
185 }
186 ed.run(|cx| c::insert_text(cx, &text));
187 true
188}