use std::ops::Range;
use std::sync::Arc;
use canvist_model::Attrs;
use canvist_model::BlockId;
use canvist_model::BlockTypeId;
use canvist_model::InlineText;
use canvist_model::Mark;
use canvist_model::MarkTypeId;
use canvist_model::Point;
use canvist_model::Schema;
use canvist_model::Selection;
use canvist_model::StepError;
use regex_lite::Regex;
use crate::CommandResult;
use crate::EditKind;
use crate::EditorError;
use crate::EditorState;
use crate::commands;
use crate::position::parent_of;
use crate::structure;
pub const RULE_CONTEXT: u32 = 500;
pub type RuleHandler = Arc<dyn Fn(&mut EditorState, &RuleMatch) -> CommandResult + Send + Sync>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleMatch {
pub block: BlockId,
pub start: u32,
pub caret: u32,
pub typed: String,
pub text: String,
pub groups: Vec<Option<Range<u32>>>,
}
impl RuleMatch {
#[must_use]
pub fn group(&self, index: usize) -> Option<&str> {
let range = self.groups.get(index)?.as_ref()?;
let start = (range.start - self.start) as usize;
let end = (range.end - self.start) as usize;
self.text.get(start..end)
}
#[must_use]
pub fn content_start(&self) -> u32 {
let leading = self.text.len() - self.text.trim_start().len();
self.start + leading as u32
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleInput {
pub block: BlockId,
pub window: u32,
pub caret: u32,
pub typed: String,
pub haystack: String,
}
impl RuleInput {
#[must_use]
pub fn new(state: &EditorState, caret: Point, typed: &str) -> Option<Self> {
let triggers = typed
.chars()
.next_back()
.is_some_and(|last| !last.is_alphanumeric());
let text = state.doc().inline(caret.block)?.as_str();
if !triggers {
return None;
}
let mut window = caret.offset.saturating_sub(RULE_CONTEXT) as usize;
while !text.is_char_boundary(window) {
window += 1;
}
let before = text.get(window..caret.offset as usize)?;
Some(Self {
block: caret.block,
window: window as u32,
caret: caret.offset,
typed: typed.to_owned(),
haystack: format!("{before}{typed}"),
})
}
}
#[derive(Clone)]
pub struct InputRule {
pattern: Regex,
trigger: Trigger,
on: Option<&'static str>,
anchored: bool,
uses_start: bool,
lookback: Lookback,
handler: RuleHandler,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lookback {
Bytes(u32),
Word,
}
pub const DEFAULT_LOOKBACK: Lookback = Lookback::Bytes(64);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Trigger {
Any,
Whitespace,
Char(char),
}
impl Trigger {
fn of(pattern: &str) -> Self {
let body = pattern.strip_suffix('$').unwrap_or(pattern);
let whitespace = body.ends_with(r"\s") && !body.ends_with(r"\\s");
if whitespace || body.ends_with(r"[\s\n]") {
return Self::Whitespace;
}
let mut tail = body.chars().rev();
let (Some(last), before) = (tail.next(), tail.next()) else {
return Self::Any;
};
let escaped = before == Some('\\');
match (escaped, last) {
(true, last) if last.is_ascii_punctuation() => Self::Char(last),
(false, last) if !"\\.^$*+?()[]{}|".contains(last) => Self::Char(last),
_ => Self::Any,
}
}
fn accepts(self, typed: char) -> bool {
match self {
Self::Any => true,
Self::Whitespace => typed.is_whitespace(),
Self::Char(expected) => typed == expected,
}
}
}
impl std::fmt::Debug for InputRule {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("InputRule")
.field("pattern", &self.pattern.as_str())
.finish_non_exhaustive()
}
}
fn compile(pattern: &str) -> Result<Regex, EditorError> {
Regex::new(pattern).map_err(|error| {
EditorError::InvalidPattern {
pattern: pattern.to_owned(),
reason: error.to_string(),
}
})
}
impl InputRule {
pub fn new(
pattern: &str,
handler: impl Fn(&mut EditorState, &RuleMatch) -> CommandResult + Send + Sync + 'static,
) -> Result<Self, EditorError> {
Self::with_handler(pattern, Arc::new(handler))
}
fn with_handler(pattern: &str, handler: RuleHandler) -> Result<Self, EditorError> {
if !pattern.ends_with('$') {
return Err(EditorError::InvalidPattern {
pattern: pattern.to_owned(),
reason: "input rules must be anchored to the caret with `$`".to_owned(),
});
}
Ok(Self {
pattern: compile(pattern)?,
trigger: Trigger::of(pattern),
on: None,
anchored: pattern.starts_with('^'),
uses_start: pattern.contains('^'),
lookback: DEFAULT_LOOKBACK,
handler,
})
}
#[must_use]
pub fn lookback(mut self, lookback: Lookback) -> Self {
self.lookback = lookback;
self
}
#[must_use]
pub fn on(mut self, chars: &'static str) -> Self {
self.on = Some(chars);
self
}
fn search_start(&self, input: &RuleInput) -> Option<usize> {
if self.anchored {
return (input.window == 0).then_some(0);
}
let before = &input.haystack[..input.haystack.len() - input.typed.len()];
let mut cut = match self.lookback {
Lookback::Word => before.rfind(char::is_whitespace).unwrap_or(0),
Lookback::Bytes(bytes) => before.len().saturating_sub(bytes as usize),
};
while !before.is_char_boundary(cut) {
cut += 1;
}
let at_block_start = cut == 0 && input.window == 0;
if at_block_start || !self.uses_start {
return Some(cut);
}
before[cut..]
.find(char::is_whitespace)
.map(|offset| cut + offset)
}
pub fn text(pattern: &str, replacement: &'static str) -> Result<Self, EditorError> {
Self::new(pattern, move |state, found| {
replace_text(state, found, replacement)
})
}
pub fn block_type(
pattern: &str,
kind: BlockTypeId,
attrs: impl Fn(&RuleMatch) -> Attrs + Send + Sync + 'static,
) -> Result<Self, EditorError> {
Self::new(pattern, move |state, found| {
set_type(state, found, kind, attrs(found))
})
}
pub fn wrap(
pattern: &str,
wrap: impl Fn(&mut EditorState, &RuleMatch) -> CommandResult + Send + Sync + 'static,
) -> Result<Self, EditorError> {
Self::new(pattern, move |state, found| {
let Some(wrapped) = wrap(state, found)? else {
return Ok(None);
};
let removed = remove_match(state, found)?;
Ok(Some(match removed {
Some(removed) => wrapped.then(removed),
None => wrapped,
}))
})
}
pub fn mark(pattern: &str, kind: MarkTypeId) -> Result<Self, EditorError> {
Self::new(pattern, move |state, found| apply_mark(state, found, kind))
}
pub fn leaf(pattern: &str, kind: BlockTypeId) -> Result<Self, EditorError> {
Self::new(pattern, move |state, found| insert_leaf(state, found, kind))
}
#[must_use]
pub fn find(&self, input: &RuleInput) -> Option<RuleMatch> {
let last = input.typed.chars().next_back()?;
let triggered = match self.on {
Some(chars) => chars.contains(last),
None => self.trigger.accepts(last),
};
if !triggered {
return None;
}
let start = self.search_start(input)?;
let haystack = &input.haystack[start..];
if !self.pattern.is_match(haystack) {
return None;
}
let captures = self.pattern.captures(haystack)?;
let whole = captures.get(0)?;
let offset = |at: usize| input.window + (start + at) as u32;
let groups = (0..captures.len())
.map(|index| {
captures
.get(index)
.map(|group| offset(group.start())..offset(group.end()))
})
.collect();
Some(RuleMatch {
block: input.block,
start: offset(whole.start()),
caret: input.caret,
typed: input.typed.clone(),
text: whole.as_str().to_owned(),
groups,
})
}
pub fn apply(&self, state: &mut EditorState, found: &RuleMatch) -> CommandResult {
(self.handler)(state, found)
}
}
fn caret_at(block: BlockId, offset: u32) -> Selection {
Selection::caret(Point::new(block, offset))
}
fn replace_text(state: &mut EditorState, found: &RuleMatch, replacement: &str) -> CommandResult {
let from = found.content_start().min(found.caret);
let marks = commands::marks_at(state.doc(), Point::new(found.block, from));
state.change(EditKind::InputRule, |tr| {
tr.delete_text(found.block, from..found.caret)?;
let end = tr.insert_text(Point::new(found.block, from), replacement, marks)?;
tr.set_selection(Selection::caret(end));
Ok(true)
})
}
fn set_type(
state: &mut EditorState,
found: &RuleMatch,
kind: BlockTypeId,
attrs: Attrs,
) -> CommandResult {
let doc = state.doc();
if !structure::allows(doc, parent_of(doc, found.block), kind) {
return Ok(None);
}
state.change(EditKind::InputRule, |tr| {
tr.delete_text(found.block, found.start..found.caret)?;
tr.set_block(found.block, kind, attrs)?;
tr.set_selection(caret_at(found.block, found.start));
Ok(true)
})
}
fn remove_match(state: &mut EditorState, found: &RuleMatch) -> CommandResult {
if found.start == found.caret {
return Ok(None);
}
state.change(EditKind::InputRule, |tr| {
tr.delete_text(found.block, found.start..found.caret)?;
tr.set_selection(caret_at(found.block, found.start));
Ok(true)
})
}
fn apply_mark(state: &mut EditorState, found: &RuleMatch, kind: MarkTypeId) -> CommandResult {
let Some(content) = found.groups.get(1).cloned().flatten() else {
return Ok(None);
};
let open = found.content_start();
if content.end > found.caret || content.is_empty() {
return Ok(None);
}
state.change(EditKind::InputRule, |tr| {
tr.delete_text(found.block, content.end..found.caret)?;
tr.add_mark(found.block, content.clone(), Mark::new(kind))?;
tr.delete_text(found.block, open..content.start)?;
let end = Point::new(found.block, content.end - (content.start - open));
let marks = commands::marks_at(tr.doc(), end).without(kind);
tr.set_selection(Selection::caret(end));
tr.set_stored_marks(Some(marks));
Ok(true)
})
}
fn insert_leaf(state: &mut EditorState, found: &RuleMatch, kind: BlockTypeId) -> CommandResult {
let doc = state.doc();
if !structure::allows(doc, parent_of(doc, found.block), kind) {
return Ok(None);
}
let removed = remove_match(state, found)?;
let inserted = commands::insert_leaf(state, kind, Attrs::new())?;
Ok(match (removed, inserted) {
(Some(removed), Some(inserted)) => Some(removed.then(inserted)),
(removed, inserted) => removed.or(inserted),
})
}
pub type MarkAttrs = Arc<dyn Fn(&str) -> Attrs + Send + Sync>;
#[derive(Clone)]
pub struct PasteRule {
pattern: Regex,
kind: MarkTypeId,
attrs: MarkAttrs,
}
impl std::fmt::Debug for PasteRule {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PasteRule")
.field("pattern", &self.pattern.as_str())
.field("kind", &self.kind)
.finish_non_exhaustive()
}
}
impl PasteRule {
pub fn mark(pattern: &str, kind: MarkTypeId) -> Result<Self, EditorError> {
Self::mark_with(pattern, kind, |_| Attrs::new())
}
pub fn mark_with(
pattern: &str,
kind: MarkTypeId,
attrs: impl Fn(&str) -> Attrs + Send + Sync + 'static,
) -> Result<Self, EditorError> {
Ok(Self {
pattern: compile(pattern)?,
kind,
attrs: Arc::new(attrs),
})
}
pub fn apply(&self, text: &mut InlineText, schema: &Schema) -> Result<(), EditorError> {
let source = text.as_str().to_owned();
let matches: Vec<(Range<u32>, Range<u32>)> = self
.pattern
.captures_iter(&source)
.filter_map(|captures| {
let whole = captures.get(0)?;
let content = captures.get(1).unwrap_or(whole);
let leading = whole.as_str().len() - whole.as_str().trim_start().len();
let open = (whole.start() + leading) as u32;
Some((
open..whole.end() as u32,
content.start() as u32..content.end() as u32,
))
})
.collect();
for (whole, content) in matches.into_iter().rev() {
let marked = &source[content.start as usize..content.end as usize];
let mark = Mark::with_attrs(self.kind, (self.attrs)(marked));
text.add_mark(content.clone(), &mark, schema)
.map_err(StepError::from)?;
text.remove(content.end..whole.end.max(content.end))
.map_err(StepError::from)?;
text.remove(whole.start.min(content.start)..content.start)
.map_err(StepError::from)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_triggers_from_the_end_of_patterns() {
assert_eq!(Trigger::of(r"^(#{1,6})\s$"), Trigger::Whitespace);
assert_eq!(Trigger::of(r"^```([a-z]+)?[\s\n]$"), Trigger::Whitespace);
assert_eq!(Trigger::of(r"(?:^|\s)\*\*([^*]+)\*\*$"), Trigger::Char('*'));
assert_eq!(Trigger::of(r"(?:^|\s)_([^_]+)_$"), Trigger::Char('_'));
assert_eq!(Trigger::of(r"->$"), Trigger::Char('>'));
assert_eq!(Trigger::of(r"^(?:---|___\s)$"), Trigger::Any);
assert_eq!(Trigger::of(r"a.$"), Trigger::Any);
}
}