//! Markdown-style input rules (the TS editor's `inputRules`), matched by hand: //! `# `..`### `, "```", `- `/`* `, `1. `, `> `, `---`, `**x**`, `*x*`, `` `x` ``. //! A rule replaces the typed text; Backspace right after it undoes the rule and //! types the text instead. use note_model::flat::Kind as Leaf; use crate::core::commands::{self as c, Cx}; use crate::core::doc::Kind; use crate::core::marks::MarkType; use crate::core::model::Blk; use crate::core::pos::{Pos, Selection}; use crate::editor::Editor; /// Whether typing `data` could complete a rule (such text is never left to the browser). pub fn may_trigger(data: &str) -> bool { data.ends_with([' ', '\u{a0}', '`', '*', '-']) } fn is_ws(c: char) -> bool { c.is_whitespace() } enum Rule { Block(Kind), Wrap(Kind, Option), Rule, Mark(MarkType, usize /* content start (utf16) */, usize /* content len */, usize /* delim */), } /// How far back (UTF-16 units) mark rules look for their opening delimiter. const RULE_WINDOW: usize = 2000; fn match_rule(s: &str, whole: bool) -> Option { let chars: Vec = s.chars().collect(); let n = if whole { chars.len() } else { 0 }; // Block rules match the whole text before the caret. if (2..=4).contains(&n) && is_ws(chars[n - 1]) && chars[..n - 1].iter().all(|&c| c == '#') { return Some(Rule::Block(Kind::Heading((n - 1) as u8))); } if whole && s == "```" { return Some(Rule::Block(Kind::CodeBlock)); } if whole && s == "---" { return Some(Rule::Rule); } if n >= 2 && is_ws(chars[n - 1]) { let head = &chars[..n - 1]; let lead = head.iter().take_while(|c| is_ws(**c)).count(); let rest = &head[lead..]; if rest == ['-'] || rest == ['*'] { return Some(Rule::Wrap(Kind::BulletList, None)); } if rest == ['>'] { return Some(Rule::Wrap(Kind::Blockquote, None)); } if lead == 0 && rest.len() >= 2 && rest[rest.len() - 1] == '.' && rest[..rest.len() - 1].iter().all(char::is_ascii_digit) { let num: String = rest[..rest.len() - 1].iter().collect(); let order = num.parse::().ok()?; return Some(Rule::Wrap(Kind::OrderedList, Some(order))); } } // Mark rules match the end. let u: Vec = s.encode_utf16().collect(); let l = u.len(); let star = b'*' as u16; let tick = b'`' as u16; // Start of the run of non-delimiter units ending just before `end`. let run_start = |end: usize, d: u16| (0..end).rev().take_while(|&i| u[i] != d).last(); if l >= 5 && u[l - 1] == star && u[l - 2] == star { let ce = l - 2; if let Some(cs) = run_start(ce, star) && cs >= 2 && u[cs - 1] == star && u[cs - 2] == star && ce > cs { return Some(Rule::Mark(MarkType::Strong, cs, ce - cs, 2)); } } for (mark, d) in [(MarkType::Em, star), (MarkType::Code, tick)] { if l >= 3 && u[l - 1] == d && u[l - 2] != d { let ce = l - 1; if let Some(cs) = run_start(ce, d) && cs >= 1 && u[cs - 1] == d && (mark != MarkType::Em || cs == 1 || u[cs - 2] != star) { return Some(Rule::Mark(mark, cs, ce - cs, 1)); } } } None } /// Tries the rules for `data` typed at the caret. Applies one and returns true. pub fn apply(ed: &mut Editor, data: &str) -> bool { let Some(p) = ed.sel.cursor() else { return false }; let b = ed.m.at(p); if !b.kind().is_text() || b.kind() == Leaf::Code { return false; } // Mark rules look back within one stretch of text; block rules need the whole // text before the caret, which is short whenever one can match. let from = p.saturating_sub(RULE_WINDOW).max(b.start); let s = ed.m.plain(from, p) + data; let Some(rule) = match_rule(&s, from == b.start) else { return false }; let rule = match rule { Rule::Mark(m, cs, len, d) => Rule::Mark(m, cs + from, len, d), r => r, }; ed.checkpoint(); let ran = ed.run(|cx| run_rule(cx, &b, p, rule)); if ran { ed.checkpoint(); ed.last_rule = Some((ed.doc.state_frontiers(), data.to_owned())); } ran } /// Whether `b` is the first block of a list item (where PM's rules don't apply). fn starts_item(cx: &Cx, b: &Blk) -> bool { if !b.attrs.wrap.last().is_some_and(|w| w.is_list()) { return false; } let prev = b.index.checked_sub(1).and_then(|i| cx.m.block(i)); c::keep(prev.as_ref().map(|p| &p.attrs), &b.attrs) < b.depth() } fn run_rule(cx: &mut Cx, b: &Blk, off: Pos, rule: Rule) -> bool { match rule { Rule::Block(kind) => { if !c::can_retype(cx.m, b, kind.leaf().expect("a leaf kind")) { return false; } cx.m.delete(b.start, off); cx.sel = Selection::caret(b.start); c::set_block_type(cx, kind, true) } Rule::Rule => { if starts_item(cx, b) { return false; } cx.m.delete(b.start, off); cx.sel = Selection::caret(b.start); if b.kind() != Leaf::Para { c::set_block_type(cx, Kind::Paragraph, true); } c::insert_rule(cx, true) } Rule::Wrap(kind, start) => { if starts_item(cx, b) { return false; } cx.m.delete(b.start, off); cx.sel = Selection::caret(b.start); if kind == Kind::Blockquote { c::wrap_in(cx, kind, true) } else { c::wrap_in_list(cx, kind, start, true) } } Rule::Mark(mark, cs, len, delim) => { // The closing delimiter is one character short in the doc: the last one was typed. let close_in_doc = delim - 1; let ce = cs + len; cx.m.delete(ce, ce + close_in_doc); cx.m.delete(cs - delim, cs); let from = cs - delim; c::add_mark(cx.m, from, from + len, mark); cx.sel = Selection::caret(from + len); cx.stored = None; let mut m = c::pending_marks(cx); m.set(mark, false); cx.stored = Some(m); true } } } /// Backspace right after a rule: undo it and type the text it consumed. pub fn undo_rule(ed: &mut Editor) -> bool { let Some((frontiers, text)) = ed.last_rule.take() else { return false }; if ed.doc.state_frontiers() != frontiers || !ed.sel.is_empty() { return false; } if !ed.undo() { return false; } ed.run(|cx| c::insert_text(cx, &text)); true }