use std::ops::Range; use std::sync::LazyLock; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::markdown::escape_html; use crate::spans::{FontSize, Span}; use crate::table::{TABLE_MARK, Table, markdown_table}; pub const MAX_DEPTH: u8 = 2; pub const MAX_HEADING: u8 = 3; pub const OBJECT_MARK: char = '\u{FFFC}'; pub const RULE_MARK: char = '\u{FFFA}'; /// The marker of a code block's first line: the composer shows the block's header there. pub const CODE_HEADER_MARK: char = '\u{FFF9}'; pub const MAX_INDENT: u8 = 8; pub const INDENT_PIXELS: u32 = 40; pub const RULE_HTML: &str = "
"; const BULLETS: [&str; 3] = ["•", "◦", "▪"]; const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "]; const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"]; const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"]; const AUTOLINK_TRAILING: &str = ".,;:!?'\""; const FENCE: &str = "```"; const PLAIN_LANGUAGE: &str = "plaintext"; const MARKDOWN_INDENT: usize = 2; static TYPED_LINK: LazyLock = LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\(([^)\s]+)\)$").unwrap()); static LINK_AT: LazyLock = LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap()); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum SizeStep { Small, Large, } impl SizeStep { fn css(self) -> &'static str { match self { SizeStep::Small => "xx-small", SizeStep::Large => "x-large", } } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum MarkKind { Link(String), Bold, Italic, Underline, Strike, Superscript, Subscript, Size(SizeStep), Color(u32), Highlight(u32), Code, } impl MarkKind { pub fn same_format(&self, other: &MarkKind) -> bool { std::mem::discriminant(self) == std::mem::discriminant(other) } fn covers(&self, other: &MarkKind) -> bool { match (self, other) { (MarkKind::Size(left), MarkKind::Size(right)) => left == right, (MarkKind::Color(left), MarkKind::Color(right)) => left == right, (MarkKind::Highlight(left), MarkKind::Highlight(right)) => left == right, _ => self.same_format(other), } } fn opposite_script(&self) -> Option { match self { MarkKind::Superscript => Some(MarkKind::Subscript), MarkKind::Subscript => Some(MarkKind::Superscript), _ => None, } } fn continues_at_end(&self) -> bool { matches!( self, MarkKind::Bold | MarkKind::Italic | MarkKind::Underline | MarkKind::Strike | MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) | MarkKind::Color(_) | MarkKind::Highlight(_) ) } fn open_tag(&self) -> String { match self { MarkKind::Link(url) => format!("", escape_html(url)), MarkKind::Bold => "".to_owned(), MarkKind::Italic => "".to_owned(), MarkKind::Underline => "".to_owned(), MarkKind::Strike => "".to_owned(), MarkKind::Superscript => "".to_owned(), MarkKind::Subscript => "".to_owned(), MarkKind::Size(step) => format!("", step.css()), MarkKind::Color(color) => format!("", hex_color(*color)), MarkKind::Highlight(color) => { format!("", hex_color(*color)) } MarkKind::Code => "".to_owned(), } } fn close_tag(&self) -> &'static str { match self { MarkKind::Link(_) => "", MarkKind::Bold => "", MarkKind::Italic => "", MarkKind::Underline => "", MarkKind::Strike => "", MarkKind::Superscript => "", MarkKind::Subscript => "", MarkKind::Size(_) | MarkKind::Color(_) | MarkKind::Highlight(_) => "", MarkKind::Code => "", } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Mark { pub range: Range, pub kind: MarkKind, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum LineKind { Text, Indent(u8), Bullet(u8), Numbered(u8), Quote, Code(Option), Heading(u8), Table(Table), Rule, } impl LineKind { pub fn is_list(&self) -> bool { matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_)) } pub fn is_table(&self) -> bool { matches!(self, LineKind::Table(_)) } /// A line that holds one object mark alone: a table or a horizontal rule. pub fn object_mark(&self) -> Option { match self { LineKind::Table(_) => Some(TABLE_MARK), LineKind::Rule => Some(RULE_MARK), _ => None, } } pub fn depth(&self) -> u8 { match self { LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth, _ => 0, } } pub fn same_format(&self, other: &LineKind) -> bool { std::mem::discriminant(self) == std::mem::discriminant(other) } fn with_depth(&self, depth: u8) -> LineKind { match self { LineKind::Bullet(_) => LineKind::Bullet(depth), LineKind::Numbered(_) => LineKind::Numbered(depth), other => other.clone(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FormatState { Off, Mixed, On, } /// Formats switched on or off for text typed at `at` before any is typed. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct TypingStyle { pub at: usize, pub add: Vec, pub remove: Vec, } impl TypingStyle { pub fn apply(&self, mut kinds: Vec) -> Vec { kinds.retain(|kind| !self.remove.iter().any(|removed| removed.same_format(kind))); for added in &self.add { if !kinds.iter().any(|kind| kind.same_format(added)) { kinds.push(added.clone()); } } kinds } pub fn toggle(&mut self, kind: MarkKind, active: &[MarkKind]) { let is_active = self .apply(active.to_vec()) .iter() .any(|existing| existing.same_format(&kind)); self.add.retain(|added| !added.same_format(&kind)); self.remove.retain(|removed| !removed.same_format(&kind)); let inherited = active.iter().any(|existing| existing.same_format(&kind)); match (is_active, inherited) { (true, true) => self.remove.push(kind.clone()), (false, false) => self.add.push(kind.clone()), _ => {} } if let Some(opposite) = kind.opposite_script() && self.add.contains(&kind) { self.add.retain(|added| !added.same_format(&opposite)); self.remove .retain(|removed| !removed.same_format(&opposite)); if active .iter() .any(|existing| existing.same_format(&opposite)) { self.remove.push(opposite); } } } /// `None` is the normal size. pub fn set_size(&mut self, size: Option, active: &[MarkKind]) { self.set_exclusive( MarkKind::Size(SizeStep::Small), size.map(MarkKind::Size), active, ); } /// `None` is Automatic. pub fn set_color(&mut self, color: Option, active: &[MarkKind]) { self.set_exclusive(MarkKind::Color(0), color.map(MarkKind::Color), active); } /// `None` is No highlight. pub fn set_highlight(&mut self, color: Option, active: &[MarkKind]) { self.set_exclusive( MarkKind::Highlight(0), color.map(MarkKind::Highlight), active, ); } /// Text typed next drops every format but a link. pub fn clear(&mut self, active: &[MarkKind]) { self.add.clear(); self.remove = active .iter() .filter(|kind| !matches!(kind, MarkKind::Link(_))) .cloned() .collect(); } fn set_exclusive(&mut self, marker: MarkKind, value: Option, active: &[MarkKind]) { self.add.retain(|added| !added.same_format(&marker)); self.remove.retain(|removed| !removed.same_format(&marker)); if active.iter().any(|existing| existing.same_format(&marker)) { self.remove.push(marker); } self.add.extend(value); } pub fn is_empty(&self) -> bool { self.add.is_empty() && self.remove.is_empty() } } /// One line without its marker: what the clipboard and `from_lines` carry. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DraftLine { pub kind: LineKind, pub number: Option, pub content: String, pub marks: Vec, } impl DraftLine { fn text(content: &str) -> DraftLine { DraftLine { kind: LineKind::Text, number: None, content: content.to_owned(), marks: Vec::new(), } } fn trim_start(&mut self) { let cut = self.content.len() - self.content.trim_start().len(); self.content.drain(..cut); for mark in &mut self.marks { mark.range = mark.range.start.saturating_sub(cut)..mark.range.end.saturating_sub(cut); } self.marks.retain(|mark| !mark.range.is_empty()); } fn trim_end(&mut self) { let length = self.content.trim_end().len(); self.content.truncate(length); for mark in &mut self.marks { mark.range = mark.range.start.min(length)..mark.range.end.min(length); } self.marks.retain(|mark| !mark.range.is_empty()); } } pub type Edit = (Range, String); /// Edits since the last `take_edits`, as disjoint ranges of the text at that point. #[derive(Debug, Clone, Default)] struct Journal(Vec); impl PartialEq for Journal { fn eq(&self, _: &Journal) -> bool { true } } impl Eq for Journal {} impl Journal { fn record(&mut self, range: Range, inserted: usize, text: &str) { if range.is_empty() && inserted == 0 { return; } let mut delta = 0isize; let mut delta_before = 0isize; let mut position = self.0.len(); let mut touching: Vec<(usize, usize, usize)> = Vec::new(); for (index, (original, replacement)) in self.0.iter().enumerate() { let current_start = (original.start as isize + delta) as usize; let current_end = current_start + replacement.len(); if current_end < range.start { delta += replacement.len() as isize - original.len() as isize; delta_before = delta; continue; } if current_start > range.end { position = position.min(index); break; } position = position.min(index); touching.push((index, current_start, current_end)); delta += replacement.len() as isize - original.len() as isize; } let original_start = match touching.first() { Some(&(index, current_start, _)) if current_start <= range.start => { self.0[index].0.start } _ => (range.start as isize - delta_before) as usize, }; let original_end = match touching.last() { Some(&(index, _, current_end)) if current_end >= range.end => self.0[index].0.end, _ => (range.end as isize - delta) as usize, }; let merged_start = touching .first() .map_or(range.start, |&(_, current_start, _)| { current_start.min(range.start) }); let merged_end = touching .last() .map_or(range.end, |&(_, _, current_end)| current_end.max(range.end)); let merged_end_after = merged_end + inserted - range.len(); let replacement = text[merged_start..merged_end_after].to_owned(); if let (Some(&(first, ..)), Some(&(last, ..))) = (touching.first(), touching.last()) { self.0.drain(first..=last); } self.0 .insert(position, (original_start..original_end, replacement)); } } /// Where `offset` of the text before `edits` ends up; an insertion at it pushes it along. pub fn map_offset(edits: &[Edit], offset: usize) -> usize { let mut delta = 0isize; for (original, replacement) in edits { if offset >= original.end { delta += replacement.len() as isize - original.len() as isize; } else if offset > original.start { return (original.start as isize + delta) as usize + replacement.len(); } else { break; } } (offset as isize + delta) as usize } /// The edits that turn the text after `edits` back into `before`. pub fn reverse_edits(edits: &[Edit], before: &str) -> Vec { let mut delta = 0isize; edits .iter() .map(|(original, replacement)| { let start = (original.start as isize + delta) as usize; delta += replacement.len() as isize - original.len() as isize; ( start..start + replacement.len(), before[original.clone()].to_owned(), ) }) .collect() } /// Composer text plus formatting. List and quote lines carry their marker in `text`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Draft { text: String, marks: Vec, lines: Vec, journal: Journal, } impl Default for Draft { fn default() -> Self { Draft::plain("") } } impl Draft { pub fn plain(text: &str) -> Draft { Draft { text: text.to_owned(), marks: Vec::new(), lines: vec![LineKind::Text; text.matches('\n').count() + 1], journal: Journal::default(), } } pub fn from_lines(lines: &[DraftLine]) -> Draft { let mut draft = Draft::plain(""); draft.insert_lines(0..0, lines); draft.journal = Journal::default(); draft } pub fn to_lines(&self) -> Vec { self.slice(0..self.text.len()) } pub fn from_markdown(text: &str) -> Draft { Draft::from_lines(&markdown_lines(text)) } pub fn from_spans(spans: &[Span]) -> Draft { let mut builder = SpanLines::default(); builder.walk(spans, &LineKind::Text, &[]); Draft::from_lines(&builder.finish()) } pub fn text(&self) -> &str { &self.text } pub fn marks(&self) -> &[Mark] { &self.marks } pub fn lines(&self) -> &[LineKind] { &self.lines } pub fn take_edits(&mut self) -> Vec { std::mem::take(&mut self.journal.0) } pub fn is_blank(&self) -> bool { self.plain_text().trim().is_empty() } /// The text without list and quote markers and object marks. pub fn plain_text(&self) -> String { self.slice(0..self.text.len()) .into_iter() .map(|line| match &line.kind { LineKind::Table(table) => table.plain_text(), LineKind::Rule => String::new(), _ => line.content, }) .collect::>() .join("\n") .replace(&format!(" {OBJECT_MARK} "), " ") .replace(OBJECT_MARK, "") } pub fn line_ranges(&self) -> Vec> { let mut ranges = Vec::with_capacity(self.lines.len()); let mut start = 0; for (index, _) in self.text.match_indices('\n') { ranges.push(start..index); start = index + 1; } ranges.push(start..self.text.len()); ranges } pub fn line_at(&self, offset: usize) -> usize { let offset = offset.min(self.text.len()); self.text.as_bytes()[..offset] .iter() .filter(|byte| **byte == b'\n') .count() } pub fn marker_range(&self, index: usize) -> Range { let line = self.line_ranges()[index].clone(); let length = marker_len(&self.lines[index], &self.text[line.clone()]); line.start..line.start + length } pub fn content_range(&self, index: usize) -> Range { let line = self.line_ranges()[index].clone(); self.marker_range(index).end..line.end } /// Inside a code block line, or strictly inside inline code. pub fn in_code(&self, offset: usize) -> bool { matches!(self.lines[self.line_at(offset)], LineKind::Code(_)) || self.marks.iter().any(|mark| { mark.kind == MarkKind::Code && mark.range.start < offset && offset < mark.range.end }) } /// Formats that text typed at `offset` takes on. pub fn style_at(&self, offset: usize) -> Vec { self.style_for_insertion(offset, offset) } pub fn state(&self, range: Range, kind: &MarkKind) -> FormatState { let parts = self.content_parts(range); let total: usize = parts.iter().map(|part| part.len()).sum(); if total == 0 { return FormatState::Off; } let covered: usize = parts .iter() .map(|part| { let mut ranges: Vec> = self .marks .iter() .filter(|mark| mark.kind.covers(kind)) .map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end)) .filter(|range| !range.is_empty()) .collect(); ranges.sort_by_key(|range| range.start); let mut end = part.start; let mut sum = 0; for range in ranges { let start = range.start.max(end); if range.end > start { sum += range.end - start; end = range.end; } } sum }) .sum(); match covered { 0 => FormatState::Off, covered if covered >= total => FormatState::On, _ => FormatState::Mixed, } } /// A line the selection only touches at its start does not count. fn selected_lines(&self, range: &Range) -> std::ops::RangeInclusive { let first = self.line_at(range.start); let mut last = self.line_at(range.end); if last > first && self.line_ranges()[last].start == range.end { last -= 1; } first..=last } pub fn line_state(&self, range: Range, kind: &LineKind) -> FormatState { let lines = self.selected_lines(&range); let count = lines.clone().count(); let matching = lines .filter(|index| self.lines[*index].same_format(kind)) .count(); match matching { 0 => FormatState::Off, matching if matching == count => FormatState::On, _ => FormatState::Mixed, } } pub fn link_in(&self, range: Range) -> Option { self.marks.iter().find_map(|mark| match &mark.kind { MarkKind::Link(url) if mark.range.start < range.end.max(range.start + 1) && range.start < mark.range.end => { Some(url.clone()) } _ => None, }) } /// Mixed or off: the whole range gets `kind`. On: it loses it. pub fn toggle(&mut self, range: Range, kind: MarkKind) { self.journal = Journal::default(); if self.state(range.clone(), &kind) == FormatState::On { self.remove_marks(range, &kind); } else { if let Some(opposite) = kind.opposite_script() { self.remove_marks(range.clone(), &opposite); } for part in self.content_parts(range) { self.add_mark(part, kind.clone()); } } } /// `None` is the normal size: any size mark on `range` is removed. pub fn set_size(&mut self, range: Range, size: Option) { self.set_exclusive( range, &MarkKind::Size(SizeStep::Small), size.map(MarkKind::Size), ); } /// `None` is Automatic: the font colour on `range` is removed. pub fn set_color(&mut self, range: Range, color: Option) { self.set_exclusive(range, &MarkKind::Color(0), color.map(MarkKind::Color)); } /// `None` is No highlight. pub fn set_highlight(&mut self, range: Range, color: Option) { self.set_exclusive( range, &MarkKind::Highlight(0), color.map(MarkKind::Highlight), ); } /// The colour of `marker`'s kind that covers all of `range`. pub fn color_in(&self, range: Range, marker: &MarkKind) -> Option { self.marks .iter() .filter(|mark| mark.kind.same_format(marker)) .find(|mark| self.state(range.clone(), &mark.kind) == FormatState::On) .and_then(|mark| match mark.kind { MarkKind::Color(color) | MarkKind::Highlight(color) => Some(color), _ => None, }) } /// Teams' Clear all formatting: every inline format but links, and the block indent. pub fn clear_formatting(&mut self, range: Range) { self.journal = Journal::default(); let kinds: Vec = self .marks .iter() .filter(|mark| !matches!(mark.kind, MarkKind::Link(_)) && overlaps(&mark.range, &range)) .map(|mark| mark.kind.clone()) .collect(); for kind in kinds { self.remove_marks(range.clone(), &kind); } for index in self.selected_lines(&range) { if matches!(self.lines[index], LineKind::Indent(_)) { self.lines[index] = LineKind::Text; } } } fn set_exclusive(&mut self, range: Range, marker: &MarkKind, value: Option) { self.journal = Journal::default(); self.remove_marks(range.clone(), marker); if let Some(kind) = value { for part in self.content_parts(range) { self.add_mark(part, kind.clone()); } } } pub fn size_in(&self, range: Range) -> Option { [SizeStep::Small, SizeStep::Large] .into_iter() .find(|step| self.state(range.clone(), &MarkKind::Size(*step)) == FormatState::On) } /// An empty `url` removes the link; one `link_url` refuses changes nothing. pub fn set_link(&mut self, range: Range, url: &str) { self.journal = Journal::default(); let url = url.trim(); if !url.is_empty() && link_url(url).is_none() { return; } let link = MarkKind::Link(url.to_owned()); self.remove_marks(range.clone(), &link); if !url.is_empty() { for part in self.content_parts(range) { self.add_mark(part, link.clone()); } } } /// Returns the offset after the inserted link text; plain text when `link_url` refuses `url`. pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize { self.journal = Journal::default(); self.splice(offset..offset, text, &[]); self.add_mark(offset..offset + text.len(), MarkKind::Link(url.to_owned())); offset + text.len() } /// Replaces `range`, the new text taking on the format of the text it replaces. pub fn replace(&mut self, range: Range, text: &str) { self.journal = Journal::default(); let kinds = self.style_for_insertion(range.start, range.end); self.splice(range, text, &kinds); } /// Takes the composer text after an edit the user made. Returns the cursor, moved when a /// marker had to be repaired or the typed text moved out of one. pub fn apply_edit( &mut self, new_text: &str, cursor: usize, typing: Option<&TypingStyle>, ) -> usize { self.journal = Journal::default(); if new_text == self.text { return cursor; } let (start, old_end, new_end) = edit_span(&self.text, new_text, cursor); let replacement = new_text[start..new_end].to_owned(); let mut kinds = self.style_for_insertion(start, old_end); if let Some(typing) = typing.filter(|typing| typing.at == start) { kinds = typing.apply(kinds); } let marker = self.marker_range(self.line_at(start)); let auto_urls = self.auto_link_urls(&(start..old_end)); self.splice(start..old_end, &replacement, &kinds); self.retarget_links(&auto_urls, &(start..start + replacement.len())); self.journal = Journal::default(); let mut cursor = cursor.min(self.text.len()); let typed_into_marker = old_end == start && !replacement.contains('\n') && !marker.is_empty() && (marker.start..marker.end).contains(&start); if typed_into_marker { self.splice(start..start + replacement.len(), "", &[]); self.splice(marker.end..marker.end, &replacement, &kinds); cursor = marker.end + replacement.len(); } self.repair(cursor) } /// Markdown typed just before `cursor` turns into formatting. Returns the new cursor and /// the style for what is typed next, so text after `**bold**` is not bold. pub fn convert_typed(&mut self, cursor: usize) -> Option<(usize, TypingStyle)> { self.journal = Journal::default(); let index = self.line_at(cursor); if matches!(self.lines[index], LineKind::Code(_)) { return None; } let content = self.content_range(index); if cursor < content.start || cursor > content.end { return None; } let before = &self.text[content.start..cursor]; // Teams opens the block on the third backtick; undo gives back the fence for ```lang + Enter. if self.lines[index] == LineKind::Text && before == FENCE && cursor == content.end { self.splice(content.clone(), "", &[]); let cursor = self.set_line_kind(index, LineKind::Code(None), None, content.start); // A block of the same language right below joins this one under its header. let cursor = self.repair(cursor); return Some(( cursor, TypingStyle { at: cursor, ..TypingStyle::default() }, )); } if self.lines[index] == LineKind::Text && let Some((kind, number)) = line_shortcut(before) { self.splice(content.start..cursor, &marker_text(&kind, number), &[]); self.lines[index] = kind; let after_marker = self.content_range(index).start; let cursor = self.repair(after_marker); return Some(( cursor, TypingStyle { at: cursor, ..TypingStyle::default() }, )); } let (open, close, kind) = typed_inline(before)?; let open = content.start + open.start..content.start + open.end; let close = content.start + close.start..content.start + close.end; let inside_code = self.marks.iter().any(|mark| { mark.kind == MarkKind::Code && (overlaps(&mark.range, &open) || overlaps(&mark.range, &close)) }); if inside_code { return None; } self.splice(close.clone(), "", &[]); self.splice(open.clone(), "", &[]); let inner = open.start..close.start - open.len(); self.add_mark(inner, kind.clone()); let cursor = cursor - open.len() - close.len(); Some(( cursor, TypingStyle { at: cursor, add: Vec::new(), remove: vec![kind], }, )) } /// A URL typed just before the space or newline at `cursor - 1` becomes a link. pub fn autolink_typed(&mut self, cursor: usize) -> bool { self.journal = Journal::default(); let Some(end) = cursor.checked_sub(1) else { return false; }; if !matches!(self.text.get(end..cursor), Some(" " | "\n")) { return false; } self.link_word_ending_at(end) } /// Links the URL in the word that ends at `end`. Leaves the journal alone. pub fn link_word_ending_at(&mut self, end: usize) -> bool { let index = self.line_at(end); if matches!(self.lines[index], LineKind::Code(_)) { return false; } let content_start = self.content_range(index).start; let Some(before) = self.text.get(content_start..end) else { return false; }; let word_start = before.rfind(char::is_whitespace).map_or(0, |at| { at + before[at..].chars().next().map_or(1, char::len_utf8) }); let word = &before[word_start..]; let Some(found) = word.char_indices().find_map(|(offset, _)| { let previous = word[..offset].chars().next_back(); let length = bare_url_at(&word[offset..], previous)?; Some(offset..offset + length) }) else { return false; }; let range = content_start + word_start + found.start..content_start + word_start + found.end; let taken = self.marks.iter().any(|mark| { matches!(mark.kind, MarkKind::Code | MarkKind::Link(_)) && overlaps(&mark.range, &range) }); let Some(url) = link_url(&self.text[range.clone()]).filter(|_| !taken) else { return false; }; self.add_mark(range, MarkKind::Link(url)); true } /// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence. /// `None` leaves the key to the caller: send, or a plain newline. pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option { self.journal = Journal::default(); let index = self.line_at(cursor); let kind = self.lines[index].clone(); let content = self.content_range(index); let cursor = cursor.max(content.start); match kind { LineKind::Text => { let language = fence_language(&self.text[content.clone()])?; self.splice(content.clone(), "", &[]); let cursor = self.set_line_kind(index, LineKind::Code(language), None, content.start); Some(self.repair(cursor)) } LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None, LineKind::Indent(_) if !shift => None, LineKind::Indent(_) => { self.splice(cursor..cursor, "\n", &[]); self.lines[index + 1] = kind; Some(cursor + 1) } LineKind::Quote if content.is_empty() && !shift => { self.lines[index] = LineKind::Text; Some(cursor) } LineKind::Quote => { self.splice(cursor..cursor, "\n", &[]); self.lines[index] = LineKind::Quote; self.lines[index + 1] = LineKind::Quote; Some(cursor + 1) } LineKind::Code(_) => { // The third Enter leaves: two empty lines end the block, one stays code. let last_of_block = self.lines.get(index + 1) != Some(&kind); let empty_line_above = index >= 2 && self.lines[index - 1] == kind && self.lines[index - 2] == kind && self.content_range(index - 1).is_empty(); if content.is_empty() && last_of_block && empty_line_above && !shift { let above = self.line_ranges()[index - 1].start; self.splice(above..content.start, "", &[]); let cursor = self.set_line_kind(index - 1, LineKind::Text, None, above); return Some(self.repair(cursor)); } self.splice(cursor..cursor, "\n", &[]); Some(cursor + 1) } list => { if self.text[content.clone()].trim().is_empty() { let lifted = match list.depth() { 0 => LineKind::Text, depth => list.with_depth(depth - 1), }; let cursor = self.set_line_kind(index, lifted, None, cursor); return Some(self.repair(cursor)); } self.splice(cursor..cursor, "\n", &[]); self.lines[index + 1] = list; let marker = self.expected_marker(index + 1, None); self.splice(cursor + 1..cursor + 1, &marker, &[]); Some(self.repair(cursor + 1 + marker.len())) } } } /// Forward Delete next to a marker: at a line end it joins the next line without its /// marker; inside a marker it deletes the first character of the content instead. pub fn delete_forward(&mut self, cursor: usize) -> Option { self.journal = Journal::default(); let index = self.line_at(cursor); let line = self.line_ranges()[index].clone(); let content = self.content_range(index); if cursor >= line.start && cursor < content.start { let next = self.text[content.start..] .chars() .next() .filter(|character| *character != '\n'); match next { Some(character) => { self.splice(content.start..content.start + character.len_utf8(), "", &[]); } None if index + 1 < self.lines.len() => { let next_content = self.content_range(index + 1); self.splice(content.end..next_content.start, "", &[]); } None => return Some(content.start), } return Some(self.repair(content.start)); } if cursor != line.end || index + 1 >= self.lines.len() { return None; } if self.lines[index + 1].is_table() { return Some(cursor); } if self.lines[index + 1] == LineKind::Rule { let rule = self.line_ranges()[index + 1].clone(); self.splice(cursor..rule.end, "", &[]); return Some(self.repair(cursor)); } let next_marker = self.marker_range(index + 1); if next_marker.is_empty() { return None; } self.splice(cursor..next_marker.end, "", &[]); Some(self.repair(cursor)) } /// Backspace at the start of a formatted line drops (or lifts) its format. pub fn backspace_at_start(&mut self, cursor: usize) -> Option { self.journal = Journal::default(); let index = self.line_at(cursor); let kind = self.lines[index].clone(); let line = self.line_ranges()[index].clone(); let content = self.content_range(index); if cursor == line.start && index > 0 && self.lines[index - 1] == LineKind::Rule { let rule = self.line_ranges()[index - 1].clone(); self.splice(rule.start..line.start, "", &[]); self.lines[index - 1] = kind; return Some(self.repair(rule.start)); } match &kind { LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None, LineKind::Code(_) => { (cursor <= content.start && self.first_of_block(index)).then(|| { let cursor = self.set_line_kind(index, LineKind::Text, None, cursor); self.repair(cursor) }) } LineKind::Table(_) => None, LineKind::Heading(_) => (cursor == line.start).then(|| { self.lines[index] = LineKind::Text; cursor }), LineKind::Quote if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) => { let joins_previous = index > 0 && !content.is_empty() && !self.lines[index - 1].is_table(); if !joins_previous { self.lines[index] = LineKind::Text; return Some(cursor); } self.splice(line.start - 1..line.start, "", &[]); Some(self.repair(line.start - 1)) } _ if cursor == line.start && index > 0 => { self.splice(line.start - 1..content.start, "", &[]); Some(self.repair(line.start - 1)) } _ if cursor > line.start && cursor <= content.start => { let lifted = match kind.depth() { depth if depth > 0 => kind.with_depth(depth - 1), _ => LineKind::Text, }; let cursor = self.set_line_kind(index, lifted, None, cursor); Some(self.repair(cursor)) } _ => None, } } /// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item. pub fn indent(&mut self, range: Range, outdent: bool) -> bool { self.journal = Journal::default(); let lines = self.selected_lines(&range); if !lines.clone().all(|index| self.lines[index].is_list()) { return false; } for index in lines { let kind = self.lines[index].clone(); let depth = kind.depth(); let target = match (outdent, depth) { (true, 0) => LineKind::Text, (true, depth) => kind.with_depth(depth - 1), (false, depth) => kind.with_depth((depth + 1).min(MAX_DEPTH)), }; self.set_line_kind(index, target, None, 0); } self.repair(0); true } /// Teams' Increase / Decrease indent: list items nest or lift, paragraphs move by one /// block indent step. pub fn indent_blocks(&mut self, range: Range, outdent: bool) { self.journal = Journal::default(); for index in self.selected_lines(&range) { let kind = self.lines[index].clone(); let target = match (&kind, outdent) { (list, _) if list.is_list() => match (outdent, list.depth()) { (true, 0) => LineKind::Text, (true, depth) => list.with_depth(depth - 1), (false, depth) => list.with_depth((depth + 1).min(MAX_DEPTH)), }, (LineKind::Text, false) => LineKind::Indent(1), (LineKind::Indent(level), false) => LineKind::Indent((level + 1).min(MAX_INDENT)), (LineKind::Indent(1), true) => LineKind::Text, (LineKind::Indent(level), true) => LineKind::Indent(level - 1), _ => continue, }; self.set_line_kind(index, target, None, 0); } self.repair(0); } /// Decrease indent has something to lift: a list item or an indented paragraph. pub fn can_outdent(&self, range: Range) -> bool { self.selected_lines(&range).any(|index| { self.lines[index].is_list() || matches!(self.lines[index], LineKind::Indent(_)) }) } /// Teams' paragraph style: `None` is Paragraph, otherwise Heading 1 to 3. pub fn set_heading(&mut self, range: Range, level: Option) { self.journal = Journal::default(); let target = level.map_or(LineKind::Text, |level| { LineKind::Heading(level.clamp(1, MAX_HEADING)) }); for index in self.selected_lines(&range) { let current = &self.lines[index]; if current.object_mark().is_some() || matches!(current, LineKind::Code(_)) { continue; } if *current != target { self.set_line_kind(index, target.clone(), None, 0); } } self.repair(0); } /// The paragraph style of the cursor's line: `None` for Paragraph. pub fn heading_at(&self, offset: usize) -> Option { match self.lines[self.line_at(offset)] { LineKind::Heading(level) => Some(level), _ => None, } } /// The rule goes in place of an empty text line, otherwise below the cursor's line; the /// cursor goes to the text line after it, added when the rule ends the draft. pub fn insert_rule(&mut self, cursor: usize) -> usize { self.journal = Journal::default(); let index = self.line_at(cursor); let line = self.line_ranges()[index].clone(); let mark = RULE_MARK.to_string(); let replaces_line = self.lines[index] == LineKind::Text && line.is_empty(); let rule_index = if replaces_line { self.splice(line, &mark, &[]); index } else { self.splice(line.end..line.end, &format!("\n{mark}"), &[]); index + 1 }; self.lines[rule_index] = LineKind::Rule; if rule_index + 1 == self.lines.len() { let end = self.text.len(); self.splice(end..end, "\n", &[]); self.lines[rule_index + 1] = LineKind::Text; } self.line_ranges()[rule_index + 1].start } /// All selected lines `kind` already: back to text. Otherwise all become `kind`. pub fn toggle_lines(&mut self, range: Range, kind: LineKind) { self.journal = Journal::default(); let lines = self.selected_lines(&range); let all = lines .clone() .all(|index| self.lines[index].same_format(&kind)); for index in lines { let current = self.lines[index].clone(); if current.is_table() { continue; } let target = if all { LineKind::Text } else if current.same_format(&kind) { current.clone() } else if current.is_list() && kind.is_list() { kind.with_depth(current.depth()) } else { kind.clone() }; if target != current { self.set_line_kind(index, target, None, 0); } } self.repair(0); } /// The lines of the code block at `cursor`: the run of code lines with one language. pub fn code_block_at(&self, cursor: usize) -> Option> { let index = self.line_at(cursor); let kind = self.lines.get(index)?; if !matches!(kind, LineKind::Code(_)) { return None; } let start = self.lines[..index] .iter() .rposition(|other| other != kind) .map_or(0, |before| before + 1); let end = index + self.lines[index..] .iter() .take_while(|other| *other == kind) .count(); Some(start..end) } /// Only the header marks change: a block that now matches the next one merges with it. pub fn set_code_language(&mut self, cursor: usize, language: Option) { if let Some(block) = self.code_block_at(cursor) { self.journal = Journal::default(); for kind in &mut self.lines[block] { *kind = LineKind::Code(language.clone()); } self.repair(cursor); } } pub fn table(&self, index: usize) -> Option<&Table> { match self.lines.get(index)? { LineKind::Table(table) => Some(table), _ => None, } } /// Cell edits change no text, so the journal stays as it is. pub fn set_table(&mut self, index: usize, table: Table) { if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) { *kind = LineKind::Table(table); } } /// The table goes in place of an empty text line, otherwise below the cursor's line, and /// a text line follows it. Returns the table's line. pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize { self.journal = Journal::default(); let index = self.line_at(cursor); let line = self.line_ranges()[index].clone(); let mark = TABLE_MARK.to_string(); let replaces_line = self.lines[index] == LineKind::Text && line.is_empty(); let table_index = if replaces_line { self.splice(line, &mark, &[]); index } else { self.splice(line.end..line.end, &format!("\n{mark}"), &[]); index + 1 }; self.lines[table_index] = LineKind::Table(table); if table_index + 1 == self.lines.len() { let end = self.text.len(); self.splice(end..end, "\n", &[]); self.lines[table_index + 1] = LineKind::Text; } table_index } /// Returns where the cursor goes: the start of the line that took the table's place. pub fn remove_table(&mut self, index: usize) -> usize { self.journal = Journal::default(); let ranges = self.line_ranges(); let line = ranges[index].clone(); if let Some(next) = ranges.get(index + 1) { let next_kind = self.lines[index + 1].clone(); self.splice(line.start..next.start, "", &[]); self.lines[index] = next_kind; return self.repair(line.start); } if index > 0 { let start = ranges[index - 1].end; self.splice(start..line.end, "", &[]); return self.repair(start); } self.splice(line, "", &[]); self.lines[index] = LineKind::Text; 0 } /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line /// is added when the table is the last or the first line. pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize { self.journal = Journal::default(); let ranges = self.line_ranges(); if below { if let Some(next) = ranges.get(index + 1) { return next.start; } let end = self.text.len(); self.splice(end..end, "\n", &[]); self.lines[index + 1] = LineKind::Text; return end + 1; } if index > 0 { return ranges[index - 1].end; } self.splice(0..0, "\n", &[]); self.lines[0] = LineKind::Text; 0 } pub fn table_at(&self, offset: usize) -> Option { let index = self.line_at(offset); self.lines[index].is_table().then_some(index) } /// The table right above, when `cursor` is at the start of its line. pub fn table_before(&self, cursor: usize) -> Option { let index = self.line_at(cursor); let at_start = self.line_ranges()[index].start == cursor; (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1) } /// The table right below, when `cursor` is at the end of its line. pub fn table_after(&self, cursor: usize) -> Option { let index = self.line_at(cursor); let at_end = self.line_ranges()[index].end == cursor; (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1) } /// Down or Right at the very end of a quote that ends the draft: a text line below it, /// like the empty paragraph Teams keeps after a quote. pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option { self.journal = Journal::default(); let end = self.text.len(); let last = self.lines.len() - 1; if cursor != end || self.lines[last] != LineKind::Quote { return None; } self.splice(end..end, "\n", &[]); self.lines[last + 1] = LineKind::Text; Some(end + 1) } pub fn slice(&self, range: Range) -> Vec { let mut lines = Vec::new(); for (index, line) in self.line_ranges().into_iter().enumerate() { if line.end < range.start || line.start > range.end { continue; } let content = self.content_range(index); let whole_start = range.start <= content.start; let start = range.start.max(content.start); let end = range.end.min(content.end).max(start); let kind = if whole_start { self.lines[index].clone() } else { LineKind::Text }; let number = match kind { LineKind::Numbered(_) => { numbered_marker(&self.text[line.clone()]).map(|(_, number)| number) } _ => None, }; let marks = self .marks .iter() .filter_map(|mark| { let clipped = mark.range.start.max(start)..mark.range.end.min(end); (!clipped.is_empty()).then(|| Mark { range: clipped.start - start..clipped.end - start, kind: mark.kind.clone(), }) }) .collect(); lines.push(DraftLine { kind, number, content: self.text[start..end].to_owned(), marks, }); } lines } pub fn slice_without_objects(&self, range: Range) -> Vec { let mut copy = Draft::from_lines(&self.slice(range)); let marks: Vec = copy .text .match_indices(OBJECT_MARK) .map(|(index, _)| index) .collect(); for index in marks.into_iter().rev() { copy.replace(index..index + OBJECT_MARK.len_utf8(), ""); } copy.slice(0..usize::MAX) } /// Puts `lines` in place of `range`. Returns the offset after the inserted content. pub fn insert_lines(&mut self, range: Range, lines: &[DraftLine]) -> usize { self.journal = Journal::default(); let index = self.line_at(range.start); let content = self.content_range(index); let start = range.start.max(content.start); let range = start..range.end.max(start); let tail_end = self.line_ranges()[self.line_at(range.end)].end; let line_was_empty = self.lines[index] == LineKind::Text && range.start == content.start && range.end >= tail_end; let separated; let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) { separated = [&[DraftLine::text("")][..], lines].concat(); &separated[..] } else { lines }; let joined = lines .iter() .map(|line| line.content.as_str()) .collect::>() .join("\n"); self.splice(range.clone(), &joined, &[]); let mut offset = range.start; for line in lines { for mark in &line.marks { self.add_mark( offset + mark.range.start..offset + mark.range.end, mark.kind.clone(), ); } offset += line.content.len() + 1; } let length_before_markers = self.text.len(); for (position, line) in lines.iter().enumerate() { let first_and_kept = position == 0 && !line_was_empty; if first_and_kept || line.kind == self.lines[index + position] { continue; } self.set_line_kind(index + position, line.kind.clone(), line.number, 0); } let end = (range.start + joined.len() + self.text.len()).saturating_sub(length_before_markers); self.repair(end) } /// Leading and trailing blank lines and spaces dropped. pub fn trimmed(&self) -> Draft { let mut lines = self.slice(0..self.text.len()); let blank = |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty(); while lines.len() > 1 && lines.first().is_some_and(blank) { lines.remove(0); } while lines.len() > 1 && lines.last().is_some_and(blank) { lines.pop(); } if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) { first.trim_start(); } if let Some(last) = lines .last_mut() .filter(|line| !matches!(line.kind, LineKind::Code(_))) { last.trim_end(); } Draft::from_lines(&lines) } /// Teams chat HTML. pub fn to_html(&self) -> String { let lines = self.slice(0..self.text.len()); let mut html = String::new(); let mut index = 0; while index < lines.len() { let kind = &lines[index].kind; let run_end = index + lines[index..] .iter() .take_while(|line| match kind { LineKind::Code(_) => line.kind == *kind, _ if kind.is_list() => line.kind.is_list(), _ => line.kind.same_format(kind), }) .count(); let run = &lines[index..run_end]; match kind { LineKind::Text => html.push_str(&joined_inline(run)), LineKind::Quote => { html.push_str("
"); html.push_str(&joined_inline(run)); html.push_str("
"); } LineKind::Heading(_) => { for line in run { let level = match line.kind { LineKind::Heading(level) => level.clamp(1, MAX_HEADING), _ => 1, }; let inline = inline_html(&line.content, &line.marks); html.push_str(&format!("{inline}")); } } LineKind::Indent(_) => { for line in run { let level = match line.kind { LineKind::Indent(level) => u32::from(level.clamp(1, MAX_INDENT)), _ => 1, }; let inline = inline_html(&line.content, &line.marks); let margin = level * INDENT_PIXELS; html.push_str(&format!( "

{inline}

" )); } } LineKind::Table(_) => { for line in run { if let LineKind::Table(table) = &line.kind { html.push_str(&table.to_html()); } } } LineKind::Rule => html.push_str(&RULE_HTML.repeat(run.len())), LineKind::Code(language) => { let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE); html.push_str(&format!( "
",
                        // Teams' ids are case-sensitive: `dockerFile`.
                        escape_html(language)
                    ));
                    let code = run
                        .iter()
                        .map(|line| escape_html(&line.content))
                        .collect::>()
                        .join("
"); html.push_str(&code); html.push_str("
"); } _ => html.push_str(&list_html(run)), } index = run_end; } html } fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec { let mut kinds: Vec = self .marks .iter() .filter(|mark| { let range = &mark.range; if old_end > start { range.start <= start && start < range.end } else { (range.start < start && start < range.end) || (range.start < start && range.end == start && mark.kind.continues_at_end()) } }) .map(|mark| mark.kind.clone()) .collect(); kinds.sort(); kinds.dedup(); kinds } fn auto_link_urls(&self, range: &Range) -> Vec { self.marks .iter() .filter_map(|mark| match &mark.kind { MarkKind::Link(url) if mark.range.start <= range.end && range.start <= mark.range.end && autolink_prefix(&self.text[mark.range.clone()]).is_some() && link_url(&self.text[mark.range.clone()]).as_ref() == Some(url) => { Some(url.clone()) } _ => None, }) .collect() } fn retarget_links(&mut self, auto_urls: &[String], edited: &Range) { if auto_urls.is_empty() { return; } let mut kept = Vec::with_capacity(self.marks.len()); for mark in std::mem::take(&mut self.marks) { let touched = mark.range.start <= edited.end && edited.start <= mark.range.end; match &mark.kind { MarkKind::Link(url) if touched && auto_urls.contains(url) => { if let Some(new_url) = link_url(&self.text[mark.range.clone()]) { kept.push(Mark { range: mark.range, kind: MarkKind::Link(new_url), }); } } _ => kept.push(mark), } } self.marks = kept; self.normalize_marks(); } fn content_parts(&self, range: Range) -> Vec> { (self.line_at(range.start)..=self.line_at(range.end)) .map(|index| { let content = self.content_range(index); content.start.max(range.start)..content.end.min(range.end) }) .filter(|part| !part.is_empty()) .collect() } /// Links with a scheme other than http, https or mailto stay plain text. fn add_mark(&mut self, range: Range, kind: MarkKind) { let kind = match kind { MarkKind::Link(url) => match link_url(&url) { Some(url) => MarkKind::Link(url), None => return, }, other => other, }; if !range.is_empty() { self.marks.push(Mark { range, kind }); self.normalize_marks(); } } fn remove_marks(&mut self, range: Range, kind: &MarkKind) { let mut kept = Vec::with_capacity(self.marks.len()); for mark in std::mem::take(&mut self.marks) { if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) { kept.push(mark); continue; } if mark.range.start < range.start { kept.push(Mark { range: mark.range.start..range.start, kind: mark.kind.clone(), }); } if mark.range.end > range.end { kept.push(Mark { range: range.end..mark.range.end, kind: mark.kind, }); } } self.marks = kept; self.normalize_marks(); } fn normalize_marks(&mut self) { let length = self.text.len(); let mut marks: Vec = std::mem::take(&mut self.marks) .into_iter() .map(|mark| Mark { range: mark.range.start.min(length)..mark.range.end.min(length), kind: mark.kind, }) .filter(|mark| !mark.range.is_empty()) .collect(); marks.sort_by(|left, right| { left.kind .cmp(&right.kind) .then(left.range.start.cmp(&right.range.start)) }); let mut merged: Vec = Vec::with_capacity(marks.len()); for mark in marks { match merged.last_mut() { Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => { last.range.end = last.range.end.max(mark.range.end); } _ => merged.push(mark), } } self.marks = merged; } fn splice(&mut self, range: Range, replacement: &str, kinds: &[MarkKind]) { let (start, old_end) = (range.start, range.end); let first_line = self.line_at(start); let last_line = self.line_at(old_end); let line_start = self.line_ranges()[first_line].start; let breaks = replacement.matches('\n').count(); let kind = self.lines[first_line].clone(); let mut new_kinds = Vec::with_capacity(breaks + 1); let pushes_line_down = breaks > 0 && start == line_start && old_end == start && !matches!(kind, LineKind::Code(_)) && self.text[start..] .chars() .next() .is_some_and(|next| next != '\n'); if pushes_line_down { new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks)); new_kinds.push(kind); } else { let continued = match &kind { LineKind::Code(language) => LineKind::Code(language.clone()), _ => LineKind::Text, }; new_kinds.push(kind); new_kinds.extend(std::iter::repeat_n(continued, breaks)); } self.lines.splice(first_line..=last_line, new_kinds); self.text.replace_range(range.clone(), replacement); let inserted = replacement.len(); let delta = inserted as isize - (old_end - start) as isize; let shift = |position: usize| (position as isize + delta) as usize; let map_start = |position: usize| { if position < start { position } else if position >= old_end { shift(position) } else { start + inserted } }; let map_end = |position: usize| { if position <= start { position } else if position >= old_end { shift(position) } else { start } }; for mark in &mut self.marks { mark.range = map_start(mark.range.start)..map_end(mark.range.end); } if inserted > 0 { let inserted_range = start..start + inserted; let mut kept = Vec::with_capacity(self.marks.len() + kinds.len()); for mark in std::mem::take(&mut self.marks) { if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) { kept.push(mark); continue; } if mark.range.start < inserted_range.start { kept.push(Mark { range: mark.range.start..inserted_range.start, kind: mark.kind.clone(), }); } if mark.range.end > inserted_range.end { kept.push(Mark { range: inserted_range.end..mark.range.end, kind: mark.kind, }); } } kept.extend(kinds.iter().map(|kind| Mark { range: inserted_range.clone(), kind: kind.clone(), })); self.marks = kept; } self.normalize_marks(); self.journal.record(range, inserted, &self.text); } fn previous_number(&self, index: usize, depth: u8) -> Option { let ranges = self.line_ranges(); for previous in (0..index).rev() { match &self.lines[previous] { LineKind::Numbered(previous_depth) if *previous_depth == depth => { return numbered_marker(&self.text[ranges[previous].clone()]) .map(|(_, number)| number); } kind if kind.is_list() && kind.depth() > depth => continue, _ => return None, } } None } fn expected_marker(&self, index: usize, own_number: Option) -> String { let kind = &self.lines[index]; let number = match kind { LineKind::Numbered(depth) => match self.previous_number(index, *depth) { Some(previous) => previous + 1, None => own_number .or_else(|| { let line = self.line_ranges()[index].clone(); numbered_marker(&self.text[line]).map(|(_, number)| number) }) .unwrap_or(1), }, LineKind::Code(_) if self.first_of_block(index) => { return CODE_HEADER_MARK.to_string(); } _ => 1, }; marker_text(kind, number) } fn first_of_block(&self, index: usize) -> bool { index == 0 || self.lines[index - 1] != self.lines[index] } /// Only the first line of a code block holds the header mark. fn repair_code_headers(&mut self, mut cursor: usize) -> usize { let stray: Vec = self .text .match_indices(CODE_HEADER_MARK) .map(|(at, _)| at) .filter(|at| { let index = self.line_at(*at); !matches!(self.lines[index], LineKind::Code(_)) || !self.first_of_block(index) || self.line_ranges()[index].start != *at }) .collect(); for at in stray.into_iter().rev() { let mark = at..at + CODE_HEADER_MARK.len_utf8(); self.splice(mark.clone(), "", &[]); if cursor > at { cursor -= (cursor - at).min(mark.len()); } } for index in 0..self.lines.len() { if matches!(self.lines[index], LineKind::Code(_)) { let marker = self.marker_range(index); let expected = self.expected_marker(index, None); cursor = self.replace_marker(marker, &expected, cursor); } } cursor } fn set_line_kind( &mut self, index: usize, kind: LineKind, number: Option, cursor: usize, ) -> usize { let marker = self.marker_range(index); self.lines[index] = kind; let expected = self.expected_marker(index, number); self.replace_marker(marker, &expected, cursor) } fn replace_marker(&mut self, marker: Range, expected: &str, cursor: usize) -> usize { if self.text[marker.clone()] == *expected { return cursor; } self.splice(marker.clone(), expected, &[]); if cursor >= marker.end { cursor + expected.len() - marker.len() } else if cursor > marker.start { marker.start + expected.len() } else { cursor } } /// A table or rule line holds its mark alone: text typed next to it moves to its own /// line, a mark without its line kind is dropped and a line without its mark becomes text. fn repair_objects(&mut self, mut cursor: usize) -> usize { let mut index = 0; while index < self.lines.len() { let line = self.line_ranges()[index].clone(); let kind = self.lines[index].clone(); let expected = kind.object_mark(); let stray = self.text[line.clone()] .char_indices() .find(|(_, character)| { [TABLE_MARK, RULE_MARK].contains(character) && Some(*character) != expected }); if let Some((at, character)) = stray { let mark = line.start + at..line.start + at + character.len_utf8(); self.splice(mark.clone(), "", &[]); cursor = map_offset(&[(mark, String::new())], cursor); continue; } let Some(object_mark) = expected else { index += 1; continue; }; let mark_length = object_mark.len_utf8(); match self.text[line.clone()].find(object_mark) { None => self.lines[index] = LineKind::Text, Some(at) if at > 0 => { let split = line.start + at; self.splice(split..split, "\n", &[]); self.lines[index] = LineKind::Text; self.lines[index + 1] = kind; cursor += usize::from(cursor > split); } Some(_) if line.len() > mark_length => { let split = line.start + mark_length; self.splice(split..split, "\n", &[]); cursor += usize::from(cursor > split); } Some(_) => {} } index += 1; } cursor } /// List items whose marker was edited away become text; numbered items are renumbered. fn repair(&mut self, cursor: usize) -> usize { let mut cursor = self.repair_objects(cursor); cursor = self.repair_code_headers(cursor); for index in 0..self.lines.len() { let kind = self.lines[index].clone(); if !kind.is_list() { continue; } let line = self.line_ranges()[index].clone(); let expected = self.expected_marker(index, None); let current = &self.text[line.clone()]; if current.starts_with(&expected) { continue; } match numbered_marker(current) { Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => { cursor = self.replace_marker(line.start..line.start + length, &expected, cursor); } _ => self.lines[index] = LineKind::Text, } } cursor } } fn hex_color(color: u32) -> String { format!("#{:06X}", color & 0xFF_FFFF) } fn overlaps(left: &Range, right: &Range) -> bool { left.start < right.end && right.start < left.end } fn bullet_marker(depth: u8) -> String { format!("{} ", BULLETS[depth as usize % BULLETS.len()]) } fn marker_text(kind: &LineKind, number: u32) -> String { match kind { LineKind::Bullet(depth) => bullet_marker(*depth), LineKind::Numbered(_) => format!("{number}. "), LineKind::Text | LineKind::Indent(_) | LineKind::Quote | LineKind::Code(_) | LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => String::new(), } } fn marker_len(kind: &LineKind, line: &str) -> usize { match kind { LineKind::Bullet(depth) => { let marker = bullet_marker(*depth); if line.starts_with(&marker) { marker.len() } else { 0 } } LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length), LineKind::Code(_) if line.starts_with(CODE_HEADER_MARK) => CODE_HEADER_MARK.len_utf8(), _ => 0, } } /// Byte length and number of a `1. ` marker. fn numbered_marker(line: &str) -> Option<(usize, u32)> { let digits = line.bytes().take_while(u8::is_ascii_digit).count(); if digits == 0 || digits > 9 || !line[digits..].starts_with(". ") { return None; } Some((digits + 2, line[..digits].parse().ok()?)) } fn line_shortcut(before: &str) -> Option<(LineKind, u32)> { match before { "- " | "* " => Some((LineKind::Bullet(0), 1)), ">" => Some((LineKind::Quote, 1)), _ if before.starts_with('#') => heading_prefix(before) .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))), _ => { let digits = before.strip_suffix(". ")?; let all_digits = !digits.is_empty() && digits.len() <= 9 && digits.bytes().all(|byte| byte.is_ascii_digit()); all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1))) } } } fn fence_language(line: &str) -> Option> { let info = line.trim().strip_prefix(FENCE)?; let valid = info .chars() .all(|character| character.is_alphanumeric() || "+#-_.".contains(character)); valid.then(|| teams_language(info)) } /// The id Teams knows for a typed language, so ```py sends `language-python`; Plain Text is none. fn teams_language(info: &str) -> Option { let id = crate::code_language(info) .map_or_else(|| info.to_lowercase(), |language| language.id.to_owned()); (!info.is_empty() && id != crate::PLAIN_LANGUAGE).then_some(id) } fn valid_inner(inner: &str) -> bool { !inner.is_empty() && !inner.starts_with(char::is_whitespace) && !inner.ends_with(char::is_whitespace) } fn word_before(text: &str) -> bool { text.chars() .next_back() .is_some_and(|character| character.is_alphanumeric()) } /// `https://` added when there is no scheme. `None` for any scheme but http, https and mailto. pub fn link_url(text: &str) -> Option { let text = text.trim(); if text.is_empty() || text.contains(char::is_whitespace) { return None; } let lower = text.to_ascii_lowercase(); if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) { return Some(text.to_owned()); } let scheme = text.split_once(':').filter(|(scheme, rest)| { let host = scheme.contains('.') || scheme.eq_ignore_ascii_case("localhost"); let host_and_port = host && rest.starts_with(|character: char| character.is_ascii_digit()); !host_and_port && scheme.starts_with(|character: char| character.is_ascii_alphabetic()) && scheme .chars() .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character)) }); scheme.is_none().then(|| format!("https://{text}")) } fn autolink_prefix(text: &str) -> Option<&'static str> { AUTOLINK_PREFIXES.into_iter().find(|prefix| { text.get(..prefix.len()) .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) }) } /// Length of the URL at the start of `rest`, when `previous` does not continue a word. fn bare_url_at(rest: &str, previous: Option) -> Option { if previous.is_some_and(char::is_alphanumeric) { return None; } bare_url_len(rest) } /// Length of the URL a word starts with, without trailing punctuation. fn bare_url_len(rest: &str) -> Option { let word = &rest[..rest.find(char::is_whitespace).unwrap_or(rest.len())]; let prefix = autolink_prefix(word)?; let mut end = word.len(); while let Some(last) = word[..end].chars().next_back() { let trailing = match last { ')' => word[..end].matches(')').count() > word[..end].matches('(').count(), other => AUTOLINK_TRAILING.contains(other), }; if !trailing { break; } end -= last.len_utf8(); } (end > prefix.len()).then_some(end) } /// The markers of a format closed by the last typed character, relative to `before`. fn typed_inline(before: &str) -> Option<(Range, Range, MarkKind)> { let end = before.len(); if before.ends_with(')') { let captures = TYPED_LINK.captures(before)?; let whole = captures.get(0)?; let label = captures.get(1)?; return Some(( whole.start()..whole.start() + 1, label.end()..end, MarkKind::Link(link_url(&captures[2])?), )); } for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] { if let Some(body) = before.strip_suffix(marker) { let open = body.rfind(marker)?; return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind)); } } if let Some(body) = before.strip_suffix('`') { let open = body.rfind('`')?; let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`'); return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code)); } for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] { if let Some(body) = before.strip_suffix(marker) { if body.ends_with(marker) { return None; } let open = body.rfind(marker)?; let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker); return (opening_ok && valid_inner(&body[open + 1..])) .then(|| (open..open + 1, body.len()..end, kind)); } } None } pub fn changed_span(old: &str, new: &str) -> (usize, usize, usize) { edit_span(old, new, new.len()) } fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) { let prefix = old .char_indices() .zip(new.chars()) .find(|((_, left), right)| left != right) .map_or(old.len().min(new.len()), |((index, _), _)| index); let prefix = { let mut prefix = prefix.min(old.len()).min(new.len()); while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) { prefix -= 1; } prefix }; let suffix = old[prefix..] .chars() .rev() .zip(new[prefix..].chars().rev()) .take_while(|(left, right)| left == right) .map(|(character, _)| character.len_utf8()) .sum::(); let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix); let cursor = cursor.min(new.len()); let pure = old_end == start || new_end == start; if pure && new_end > cursor && new_end - cursor <= start { let slide = new_end - cursor; let (slid_start, slid_old_end, slid_new_end) = (start - slide, old_end - slide, new_end - slide); let boundaries = [slid_start, slid_old_end] .iter() .all(|offset| old.is_char_boundary(*offset)) && [slid_start, slid_new_end] .iter() .all(|offset| new.is_char_boundary(*offset)); if boundaries && new[slid_new_end..] == old[slid_old_end..] { return (slid_start, slid_old_end, slid_new_end); } } (start, old_end, new_end) } fn joined_inline(lines: &[DraftLine]) -> String { lines .iter() .map(|line| inline_html(&line.content, &line.marks)) .collect::>() .join("
") } /// The official client sends a link whose text is its own URL with the text cut to this many /// characters, the last one an ellipsis; the full URL stays in `href` and `title`. const LINK_TEXT_LIMIT: usize = 100; const LINK_ELLIPSIS: char = '…'; struct ShortenedLinks { content: String, marks: Vec, urls: Vec, } /// Shortens the text of each link that spells out its own URL past `LINK_TEXT_LIMIT`. fn shortened_links(content: &str, marks: &[Mark]) -> Option { let mut long: Vec<(Range, &String)> = marks .iter() .filter_map(|mark| match &mark.kind { MarkKind::Link(url) => { let text = content.get(mark.range.clone())?; let spells_url = text == url || link_url(text).as_ref() == Some(url); (spells_url && text.chars().count() > LINK_TEXT_LIMIT) .then(|| (mark.range.clone(), url)) } _ => None, }) .collect(); if long.is_empty() { return None; } long.sort_by_key(|(range, _)| range.start); long.dedup(); let urls = long.iter().map(|(_, url)| (*url).clone()).collect(); let mut text = content.to_owned(); let mut marks = marks.to_vec(); for (range, _) in long.into_iter().rev() { let kept = content[range.clone()] .char_indices() .nth(LINK_TEXT_LIMIT - 1) .map_or(range.len(), |(offset, _)| offset); let cut = range.start + kept; let end = cut + LINK_ELLIPSIS.len_utf8(); text.replace_range(cut..range.end, &LINK_ELLIPSIS.to_string()); let moved = |offset: usize| { if offset <= cut { offset } else if offset >= range.end { offset - range.end + end } else { end } }; for mark in &mut marks { mark.range = moved(mark.range.start)..moved(mark.range.end); } } marks.retain(|mark| !mark.range.is_empty()); Some(ShortenedLinks { content: text, marks, urls, }) } fn inline_html(content: &str, marks: &[Mark]) -> String { if let Some(shortened) = shortened_links(content, marks) { return inline_html_exact(&shortened.content, &shortened.marks, &shortened.urls); } inline_html_exact(content, marks, &[]) } /// `titled` links carry their URL in `title` too, for the hover a shortened text needs. fn inline_html_exact(content: &str, marks: &[Mark], titled: &[String]) -> String { let mut boundaries: Vec = marks .iter() .flat_map(|mark| [mark.range.start, mark.range.end]) .chain([0, content.len()]) .filter(|offset| *offset <= content.len()) .collect(); boundaries.sort_unstable(); boundaries.dedup(); let mut html = String::new(); let mut open: Vec<&MarkKind> = Vec::new(); for window in boundaries.windows(2) { let segment = window[0]..window[1]; let mut active: Vec<&MarkKind> = marks .iter() .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end) .map(|mark| &mark.kind) .collect(); active.sort(); active.dedup(); let common = open .iter() .zip(active.iter()) .take_while(|(left, right)| left == right) .count(); for kind in open.drain(common..).rev() { html.push_str(kind.close_tag()); } for kind in &active[common..] { match kind { MarkKind::Link(url) if titled.contains(url) => { let url = escape_html(url); html.push_str(&format!("")); } _ => html.push_str(&kind.open_tag()), } } open.extend(active[common..].iter().copied()); html.push_str(&escape_html(&content[segment])); } for kind in open.into_iter().rev() { html.push_str(kind.close_tag()); } html } fn list_html(lines: &[DraftLine]) -> String { let close = |ordered: bool| if ordered { "" } else { "" }; let mut html = String::new(); let mut open: Vec<(u8, bool)> = Vec::new(); for line in lines { let ordered = matches!(line.kind, LineKind::Numbered(_)); let depth = line .kind .depth() .min(open.last().map_or(0, |(depth, _)| depth + 1)); while open .last() .is_some_and(|(open_depth, _)| *open_depth > depth) { let (_, was_ordered) = open.pop().unwrap_or_default(); html.push_str(close(was_ordered)); } match open.last().copied() { Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => { html.push_str(""); } Some((open_depth, open_ordered)) if open_depth == depth => { html.push_str(close(open_ordered)); open.pop(); html.push_str(&list_open(ordered, line.number)); open.push((depth, ordered)); } _ => { html.push_str(&list_open(ordered, line.number)); open.push((depth, ordered)); } } html.push_str("
  • "); html.push_str(&inline_html(&line.content, &line.marks)); } for (_, ordered) in open.into_iter().rev() { html.push_str(close(ordered)); } html } fn list_open(ordered: bool, number: Option) -> String { match (ordered, number) { (false, _) => "