| 1 | use std::ops::Range; |
| 2 | use std::sync::LazyLock; |
| 3 | |
| 4 | use regex::Regex; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | |
| 7 | use crate::markdown::escape_html; |
| 8 | use crate::spans::Span; |
| 9 | |
| 10 | pub const MAX_DEPTH: u8 = 2; |
| 11 | const BULLETS: [&str; 3] = ["•", "◦", "▪"]; |
| 12 | const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "]; |
| 13 | const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"]; |
| 14 | const FENCE: &str = "```"; |
| 15 | const MARKDOWN_INDENT: usize = 2; |
| 16 | |
| 17 | static TYPED_LINK: LazyLock<Regex> = |
| 18 | LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\(([^)\s]+)\)$").unwrap()); |
| 19 | static LINK_AT: LazyLock<Regex> = |
| 20 | LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap()); |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 23 | pub enum MarkKind { |
| 24 | Link(String), |
| 25 | Bold, |
| 26 | Italic, |
| 27 | Underline, |
| 28 | Strike, |
| 29 | Code, |
| 30 | } |
| 31 | |
| 32 | impl MarkKind { |
| 33 | pub fn same_format(&self, other: &MarkKind) -> bool { |
| 34 | std::mem::discriminant(self) == std::mem::discriminant(other) |
| 35 | } |
| 36 | |
| 37 | fn continues_at_end(&self) -> bool { |
| 38 | matches!( |
| 39 | self, |
| 40 | MarkKind::Bold | MarkKind::Italic | MarkKind::Underline | MarkKind::Strike |
| 41 | ) |
| 42 | } |
| 43 | |
| 44 | fn open_tag(&self) -> String { |
| 45 | match self { |
| 46 | MarkKind::Link(url) => format!("<a href=\"{}\">", escape_html(url)), |
| 47 | MarkKind::Bold => "<b>".to_owned(), |
| 48 | MarkKind::Italic => "<i>".to_owned(), |
| 49 | MarkKind::Underline => "<u>".to_owned(), |
| 50 | MarkKind::Strike => "<s>".to_owned(), |
| 51 | MarkKind::Code => "<code>".to_owned(), |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn close_tag(&self) -> &'static str { |
| 56 | match self { |
| 57 | MarkKind::Link(_) => "</a>", |
| 58 | MarkKind::Bold => "</b>", |
| 59 | MarkKind::Italic => "</i>", |
| 60 | MarkKind::Underline => "</u>", |
| 61 | MarkKind::Strike => "</s>", |
| 62 | MarkKind::Code => "</code>", |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 68 | pub struct Mark { |
| 69 | pub range: Range<usize>, |
| 70 | pub kind: MarkKind, |
| 71 | } |
| 72 | |
| 73 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 74 | pub enum LineKind { |
| 75 | Text, |
| 76 | Bullet(u8), |
| 77 | Numbered(u8), |
| 78 | Quote, |
| 79 | Code(Option<String>), |
| 80 | } |
| 81 | |
| 82 | impl LineKind { |
| 83 | pub fn is_list(&self) -> bool { |
| 84 | matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_)) |
| 85 | } |
| 86 | |
| 87 | pub fn depth(&self) -> u8 { |
| 88 | match self { |
| 89 | LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth, |
| 90 | _ => 0, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | pub fn same_format(&self, other: &LineKind) -> bool { |
| 95 | std::mem::discriminant(self) == std::mem::discriminant(other) |
| 96 | } |
| 97 | |
| 98 | fn with_depth(&self, depth: u8) -> LineKind { |
| 99 | match self { |
| 100 | LineKind::Bullet(_) => LineKind::Bullet(depth), |
| 101 | LineKind::Numbered(_) => LineKind::Numbered(depth), |
| 102 | other => other.clone(), |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 108 | pub enum FormatState { |
| 109 | Off, |
| 110 | Mixed, |
| 111 | On, |
| 112 | } |
| 113 | |
| 114 | /// Formats switched on or off for text typed at `at` before any is typed. |
| 115 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 116 | pub struct TypingStyle { |
| 117 | pub at: usize, |
| 118 | pub add: Vec<MarkKind>, |
| 119 | pub remove: Vec<MarkKind>, |
| 120 | } |
| 121 | |
| 122 | impl TypingStyle { |
| 123 | pub fn apply(&self, mut kinds: Vec<MarkKind>) -> Vec<MarkKind> { |
| 124 | kinds.retain(|kind| !self.remove.iter().any(|removed| removed.same_format(kind))); |
| 125 | for added in &self.add { |
| 126 | if !kinds.iter().any(|kind| kind.same_format(added)) { |
| 127 | kinds.push(added.clone()); |
| 128 | } |
| 129 | } |
| 130 | kinds |
| 131 | } |
| 132 | |
| 133 | pub fn toggle(&mut self, kind: MarkKind, active: &[MarkKind]) { |
| 134 | let is_active = self |
| 135 | .apply(active.to_vec()) |
| 136 | .iter() |
| 137 | .any(|existing| existing.same_format(&kind)); |
| 138 | self.add.retain(|added| !added.same_format(&kind)); |
| 139 | self.remove.retain(|removed| !removed.same_format(&kind)); |
| 140 | let inherited = active.iter().any(|existing| existing.same_format(&kind)); |
| 141 | match (is_active, inherited) { |
| 142 | (true, true) => self.remove.push(kind), |
| 143 | (false, false) => self.add.push(kind), |
| 144 | _ => {} |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn is_empty(&self) -> bool { |
| 149 | self.add.is_empty() && self.remove.is_empty() |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// One line without its marker: what the clipboard and `from_lines` carry. |
| 154 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 155 | pub struct DraftLine { |
| 156 | pub kind: LineKind, |
| 157 | pub number: Option<u32>, |
| 158 | pub content: String, |
| 159 | pub marks: Vec<Mark>, |
| 160 | } |
| 161 | |
| 162 | impl DraftLine { |
| 163 | fn text(content: &str) -> DraftLine { |
| 164 | DraftLine { |
| 165 | kind: LineKind::Text, |
| 166 | number: None, |
| 167 | content: content.to_owned(), |
| 168 | marks: Vec::new(), |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | fn trim_start(&mut self) { |
| 173 | let cut = self.content.len() - self.content.trim_start().len(); |
| 174 | self.content.drain(..cut); |
| 175 | for mark in &mut self.marks { |
| 176 | mark.range = mark.range.start.saturating_sub(cut)..mark.range.end.saturating_sub(cut); |
| 177 | } |
| 178 | self.marks.retain(|mark| !mark.range.is_empty()); |
| 179 | } |
| 180 | |
| 181 | fn trim_end(&mut self) { |
| 182 | let length = self.content.trim_end().len(); |
| 183 | self.content.truncate(length); |
| 184 | for mark in &mut self.marks { |
| 185 | mark.range = mark.range.start.min(length)..mark.range.end.min(length); |
| 186 | } |
| 187 | self.marks.retain(|mark| !mark.range.is_empty()); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | pub type Edit = (Range<usize>, String); |
| 192 | |
| 193 | /// Edits since the last `take_edits`, as disjoint ranges of the text at that point. |
| 194 | #[derive(Debug, Clone, Default)] |
| 195 | struct Journal(Vec<Edit>); |
| 196 | |
| 197 | impl PartialEq for Journal { |
| 198 | fn eq(&self, _: &Journal) -> bool { |
| 199 | true |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | impl Eq for Journal {} |
| 204 | |
| 205 | impl Journal { |
| 206 | fn record(&mut self, range: Range<usize>, inserted: usize, text: &str) { |
| 207 | if range.is_empty() && inserted == 0 { |
| 208 | return; |
| 209 | } |
| 210 | let mut delta = 0isize; |
| 211 | let mut delta_before = 0isize; |
| 212 | let mut position = self.0.len(); |
| 213 | let mut touching: Vec<(usize, usize, usize)> = Vec::new(); |
| 214 | for (index, (original, replacement)) in self.0.iter().enumerate() { |
| 215 | let current_start = (original.start as isize + delta) as usize; |
| 216 | let current_end = current_start + replacement.len(); |
| 217 | if current_end < range.start { |
| 218 | delta += replacement.len() as isize - original.len() as isize; |
| 219 | delta_before = delta; |
| 220 | continue; |
| 221 | } |
| 222 | if current_start > range.end { |
| 223 | position = position.min(index); |
| 224 | break; |
| 225 | } |
| 226 | position = position.min(index); |
| 227 | touching.push((index, current_start, current_end)); |
| 228 | delta += replacement.len() as isize - original.len() as isize; |
| 229 | } |
| 230 | let original_start = match touching.first() { |
| 231 | Some(&(index, current_start, _)) if current_start <= range.start => { |
| 232 | self.0[index].0.start |
| 233 | } |
| 234 | _ => (range.start as isize - delta_before) as usize, |
| 235 | }; |
| 236 | let original_end = match touching.last() { |
| 237 | Some(&(index, _, current_end)) if current_end >= range.end => self.0[index].0.end, |
| 238 | _ => (range.end as isize - delta) as usize, |
| 239 | }; |
| 240 | let merged_start = touching |
| 241 | .first() |
| 242 | .map_or(range.start, |&(_, current_start, _)| { |
| 243 | current_start.min(range.start) |
| 244 | }); |
| 245 | let merged_end = touching |
| 246 | .last() |
| 247 | .map_or(range.end, |&(_, _, current_end)| current_end.max(range.end)); |
| 248 | let merged_end_after = merged_end + inserted - range.len(); |
| 249 | let replacement = text[merged_start..merged_end_after].to_owned(); |
| 250 | if let (Some(&(first, ..)), Some(&(last, ..))) = (touching.first(), touching.last()) { |
| 251 | self.0.drain(first..=last); |
| 252 | } |
| 253 | self.0 |
| 254 | .insert(position, (original_start..original_end, replacement)); |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// Where `offset` of the text before `edits` ends up; an insertion at it pushes it along. |
| 259 | pub fn map_offset(edits: &[Edit], offset: usize) -> usize { |
| 260 | let mut delta = 0isize; |
| 261 | for (original, replacement) in edits { |
| 262 | if offset >= original.end { |
| 263 | delta += replacement.len() as isize - original.len() as isize; |
| 264 | } else if offset > original.start { |
| 265 | return (original.start as isize + delta) as usize + replacement.len(); |
| 266 | } else { |
| 267 | break; |
| 268 | } |
| 269 | } |
| 270 | (offset as isize + delta) as usize |
| 271 | } |
| 272 | |
| 273 | /// The edits that turn the text after `edits` back into `before`. |
| 274 | pub fn reverse_edits(edits: &[Edit], before: &str) -> Vec<Edit> { |
| 275 | let mut delta = 0isize; |
| 276 | edits |
| 277 | .iter() |
| 278 | .map(|(original, replacement)| { |
| 279 | let start = (original.start as isize + delta) as usize; |
| 280 | delta += replacement.len() as isize - original.len() as isize; |
| 281 | ( |
| 282 | start..start + replacement.len(), |
| 283 | before[original.clone()].to_owned(), |
| 284 | ) |
| 285 | }) |
| 286 | .collect() |
| 287 | } |
| 288 | |
| 289 | /// Composer text plus formatting. List and quote lines carry their marker in `text`. |
| 290 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 291 | pub struct Draft { |
| 292 | text: String, |
| 293 | marks: Vec<Mark>, |
| 294 | lines: Vec<LineKind>, |
| 295 | journal: Journal, |
| 296 | } |
| 297 | |
| 298 | impl Default for Draft { |
| 299 | fn default() -> Self { |
| 300 | Draft::plain("") |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | impl Draft { |
| 305 | pub fn plain(text: &str) -> Draft { |
| 306 | Draft { |
| 307 | text: text.to_owned(), |
| 308 | marks: Vec::new(), |
| 309 | lines: vec![LineKind::Text; text.matches('\n').count() + 1], |
| 310 | journal: Journal::default(), |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | pub fn from_lines(lines: &[DraftLine]) -> Draft { |
| 315 | let mut draft = Draft::plain(""); |
| 316 | draft.insert_lines(0..0, lines); |
| 317 | draft.journal = Journal::default(); |
| 318 | draft |
| 319 | } |
| 320 | |
| 321 | pub fn from_markdown(text: &str) -> Draft { |
| 322 | Draft::from_lines(&markdown_lines(text)) |
| 323 | } |
| 324 | |
| 325 | pub fn from_spans(spans: &[Span]) -> Draft { |
| 326 | let mut builder = SpanLines::default(); |
| 327 | builder.walk(spans, &LineKind::Text, &[]); |
| 328 | Draft::from_lines(&builder.finish()) |
| 329 | } |
| 330 | |
| 331 | pub fn text(&self) -> &str { |
| 332 | &self.text |
| 333 | } |
| 334 | |
| 335 | pub fn marks(&self) -> &[Mark] { |
| 336 | &self.marks |
| 337 | } |
| 338 | |
| 339 | pub fn lines(&self) -> &[LineKind] { |
| 340 | &self.lines |
| 341 | } |
| 342 | |
| 343 | pub fn take_edits(&mut self) -> Vec<Edit> { |
| 344 | std::mem::take(&mut self.journal.0) |
| 345 | } |
| 346 | |
| 347 | pub fn is_blank(&self) -> bool { |
| 348 | self.plain_text().trim().is_empty() |
| 349 | } |
| 350 | |
| 351 | /// The text without list and quote markers. |
| 352 | pub fn plain_text(&self) -> String { |
| 353 | self.slice(0..self.text.len()) |
| 354 | .into_iter() |
| 355 | .map(|line| line.content) |
| 356 | .collect::<Vec<_>>() |
| 357 | .join("\n") |
| 358 | } |
| 359 | |
| 360 | pub fn line_ranges(&self) -> Vec<Range<usize>> { |
| 361 | let mut ranges = Vec::with_capacity(self.lines.len()); |
| 362 | let mut start = 0; |
| 363 | for (index, _) in self.text.match_indices('\n') { |
| 364 | ranges.push(start..index); |
| 365 | start = index + 1; |
| 366 | } |
| 367 | ranges.push(start..self.text.len()); |
| 368 | ranges |
| 369 | } |
| 370 | |
| 371 | pub fn line_at(&self, offset: usize) -> usize { |
| 372 | let offset = offset.min(self.text.len()); |
| 373 | self.text.as_bytes()[..offset] |
| 374 | .iter() |
| 375 | .filter(|byte| **byte == b'\n') |
| 376 | .count() |
| 377 | } |
| 378 | |
| 379 | pub fn marker_range(&self, index: usize) -> Range<usize> { |
| 380 | let line = self.line_ranges()[index].clone(); |
| 381 | let length = marker_len(&self.lines[index], &self.text[line.clone()]); |
| 382 | line.start..line.start + length |
| 383 | } |
| 384 | |
| 385 | pub fn content_range(&self, index: usize) -> Range<usize> { |
| 386 | let line = self.line_ranges()[index].clone(); |
| 387 | self.marker_range(index).end..line.end |
| 388 | } |
| 389 | |
| 390 | /// Inside a code block line, or strictly inside inline code. |
| 391 | pub fn in_code(&self, offset: usize) -> bool { |
| 392 | matches!(self.lines[self.line_at(offset)], LineKind::Code(_)) |
| 393 | || self.marks.iter().any(|mark| { |
| 394 | mark.kind == MarkKind::Code && mark.range.start < offset && offset < mark.range.end |
| 395 | }) |
| 396 | } |
| 397 | |
| 398 | /// Formats that text typed at `offset` takes on. |
| 399 | pub fn style_at(&self, offset: usize) -> Vec<MarkKind> { |
| 400 | self.style_for_insertion(offset, offset) |
| 401 | } |
| 402 | |
| 403 | pub fn state(&self, range: Range<usize>, kind: &MarkKind) -> FormatState { |
| 404 | let parts = self.content_parts(range); |
| 405 | let total: usize = parts.iter().map(|part| part.len()).sum(); |
| 406 | if total == 0 { |
| 407 | return FormatState::Off; |
| 408 | } |
| 409 | let covered: usize = parts |
| 410 | .iter() |
| 411 | .map(|part| { |
| 412 | let mut ranges: Vec<Range<usize>> = self |
| 413 | .marks |
| 414 | .iter() |
| 415 | .filter(|mark| mark.kind.same_format(kind)) |
| 416 | .map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end)) |
| 417 | .filter(|range| !range.is_empty()) |
| 418 | .collect(); |
| 419 | ranges.sort_by_key(|range| range.start); |
| 420 | let mut end = part.start; |
| 421 | let mut sum = 0; |
| 422 | for range in ranges { |
| 423 | let start = range.start.max(end); |
| 424 | if range.end > start { |
| 425 | sum += range.end - start; |
| 426 | end = range.end; |
| 427 | } |
| 428 | } |
| 429 | sum |
| 430 | }) |
| 431 | .sum(); |
| 432 | match covered { |
| 433 | 0 => FormatState::Off, |
| 434 | covered if covered >= total => FormatState::On, |
| 435 | _ => FormatState::Mixed, |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// A line the selection only touches at its start does not count. |
| 440 | fn selected_lines(&self, range: &Range<usize>) -> std::ops::RangeInclusive<usize> { |
| 441 | let first = self.line_at(range.start); |
| 442 | let mut last = self.line_at(range.end); |
| 443 | if last > first && self.line_ranges()[last].start == range.end { |
| 444 | last -= 1; |
| 445 | } |
| 446 | first..=last |
| 447 | } |
| 448 | |
| 449 | pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState { |
| 450 | let lines = self.selected_lines(&range); |
| 451 | let count = lines.clone().count(); |
| 452 | let matching = lines |
| 453 | .filter(|index| self.lines[*index].same_format(kind)) |
| 454 | .count(); |
| 455 | match matching { |
| 456 | 0 => FormatState::Off, |
| 457 | matching if matching == count => FormatState::On, |
| 458 | _ => FormatState::Mixed, |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | pub fn link_in(&self, range: Range<usize>) -> Option<String> { |
| 463 | self.marks.iter().find_map(|mark| match &mark.kind { |
| 464 | MarkKind::Link(url) |
| 465 | if mark.range.start < range.end.max(range.start + 1) |
| 466 | && range.start < mark.range.end => |
| 467 | { |
| 468 | Some(url.clone()) |
| 469 | } |
| 470 | _ => None, |
| 471 | }) |
| 472 | } |
| 473 | |
| 474 | /// Mixed or off: the whole range gets `kind`. On: it loses it. |
| 475 | pub fn toggle(&mut self, range: Range<usize>, kind: MarkKind) { |
| 476 | self.journal = Journal::default(); |
| 477 | if self.state(range.clone(), &kind) == FormatState::On { |
| 478 | self.remove_marks(range, &kind); |
| 479 | } else { |
| 480 | for part in self.content_parts(range) { |
| 481 | self.add_mark(part, kind.clone()); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | /// An empty `url` removes the link; one `link_url` refuses changes nothing. |
| 487 | pub fn set_link(&mut self, range: Range<usize>, url: &str) { |
| 488 | self.journal = Journal::default(); |
| 489 | let url = url.trim(); |
| 490 | if !url.is_empty() && link_url(url).is_none() { |
| 491 | return; |
| 492 | } |
| 493 | let link = MarkKind::Link(url.to_owned()); |
| 494 | self.remove_marks(range.clone(), &link); |
| 495 | if !url.is_empty() { |
| 496 | for part in self.content_parts(range) { |
| 497 | self.add_mark(part, link.clone()); |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | /// Returns the offset after the inserted link text; plain text when `link_url` refuses `url`. |
| 503 | pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize { |
| 504 | self.journal = Journal::default(); |
| 505 | self.splice(offset..offset, text, &[]); |
| 506 | self.add_mark(offset..offset + text.len(), MarkKind::Link(url.to_owned())); |
| 507 | offset + text.len() |
| 508 | } |
| 509 | |
| 510 | /// Replaces `range`, the new text taking on the format of the text it replaces. |
| 511 | pub fn replace(&mut self, range: Range<usize>, text: &str) { |
| 512 | self.journal = Journal::default(); |
| 513 | let kinds = self.style_for_insertion(range.start, range.end); |
| 514 | self.splice(range, text, &kinds); |
| 515 | } |
| 516 | |
| 517 | /// Takes the composer text after an edit the user made. Returns the cursor, moved when a |
| 518 | /// marker had to be repaired or the typed text moved out of one. |
| 519 | pub fn apply_edit( |
| 520 | &mut self, |
| 521 | new_text: &str, |
| 522 | cursor: usize, |
| 523 | typing: Option<&TypingStyle>, |
| 524 | ) -> usize { |
| 525 | self.journal = Journal::default(); |
| 526 | if new_text == self.text { |
| 527 | return cursor; |
| 528 | } |
| 529 | let (start, old_end, new_end) = edit_span(&self.text, new_text, cursor); |
| 530 | let replacement = new_text[start..new_end].to_owned(); |
| 531 | let mut kinds = self.style_for_insertion(start, old_end); |
| 532 | if let Some(typing) = typing.filter(|typing| typing.at == start) { |
| 533 | kinds = typing.apply(kinds); |
| 534 | } |
| 535 | let marker = self.marker_range(self.line_at(start)); |
| 536 | self.splice(start..old_end, &replacement, &kinds); |
| 537 | self.journal = Journal::default(); |
| 538 | let mut cursor = cursor.min(self.text.len()); |
| 539 | let typed_into_marker = old_end == start |
| 540 | && !replacement.contains('\n') |
| 541 | && !marker.is_empty() |
| 542 | && (marker.start..marker.end).contains(&start); |
| 543 | if typed_into_marker { |
| 544 | self.splice(start..start + replacement.len(), "", &[]); |
| 545 | self.splice(marker.end..marker.end, &replacement, &kinds); |
| 546 | cursor = marker.end + replacement.len(); |
| 547 | } |
| 548 | self.repair(cursor) |
| 549 | } |
| 550 | |
| 551 | /// Markdown typed just before `cursor` turns into formatting. Returns the new cursor and |
| 552 | /// the style for what is typed next, so text after `**bold**` is not bold. |
| 553 | pub fn convert_typed(&mut self, cursor: usize) -> Option<(usize, TypingStyle)> { |
| 554 | self.journal = Journal::default(); |
| 555 | let index = self.line_at(cursor); |
| 556 | if matches!(self.lines[index], LineKind::Code(_)) { |
| 557 | return None; |
| 558 | } |
| 559 | let content = self.content_range(index); |
| 560 | if cursor < content.start || cursor > content.end { |
| 561 | return None; |
| 562 | } |
| 563 | let before = &self.text[content.start..cursor]; |
| 564 | if self.lines[index] == LineKind::Text |
| 565 | && let Some((kind, number)) = line_shortcut(before) |
| 566 | { |
| 567 | self.splice(content.start..cursor, &marker_text(&kind, number), &[]); |
| 568 | self.lines[index] = kind; |
| 569 | let after_marker = self.content_range(index).start; |
| 570 | let cursor = self.repair(after_marker); |
| 571 | return Some(( |
| 572 | cursor, |
| 573 | TypingStyle { |
| 574 | at: cursor, |
| 575 | ..TypingStyle::default() |
| 576 | }, |
| 577 | )); |
| 578 | } |
| 579 | let (open, close, kind) = typed_inline(before)?; |
| 580 | let open = content.start + open.start..content.start + open.end; |
| 581 | let close = content.start + close.start..content.start + close.end; |
| 582 | let inside_code = self.marks.iter().any(|mark| { |
| 583 | mark.kind == MarkKind::Code |
| 584 | && (overlaps(&mark.range, &open) || overlaps(&mark.range, &close)) |
| 585 | }); |
| 586 | if inside_code { |
| 587 | return None; |
| 588 | } |
| 589 | self.splice(close.clone(), "", &[]); |
| 590 | self.splice(open.clone(), "", &[]); |
| 591 | let inner = open.start..close.start - open.len(); |
| 592 | self.add_mark(inner, kind.clone()); |
| 593 | let cursor = cursor - open.len() - close.len(); |
| 594 | Some(( |
| 595 | cursor, |
| 596 | TypingStyle { |
| 597 | at: cursor, |
| 598 | add: Vec::new(), |
| 599 | remove: vec![kind], |
| 600 | }, |
| 601 | )) |
| 602 | } |
| 603 | |
| 604 | /// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence. |
| 605 | /// `None` leaves the key to the caller: send, or a plain newline. |
| 606 | pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> { |
| 607 | self.journal = Journal::default(); |
| 608 | let index = self.line_at(cursor); |
| 609 | let kind = self.lines[index].clone(); |
| 610 | let content = self.content_range(index); |
| 611 | let cursor = cursor.max(content.start); |
| 612 | match kind { |
| 613 | LineKind::Text => { |
| 614 | let language = fence_language(&self.text[content.clone()])?; |
| 615 | self.splice(content.clone(), "", &[]); |
| 616 | Some(self.set_line_kind(index, LineKind::Code(language), None, content.start)) |
| 617 | } |
| 618 | LineKind::Quote if !shift => None, |
| 619 | LineKind::Quote => { |
| 620 | self.splice(cursor..cursor, "\n", &[]); |
| 621 | self.lines[index] = LineKind::Quote; |
| 622 | self.lines[index + 1] = LineKind::Quote; |
| 623 | Some(cursor + 1) |
| 624 | } |
| 625 | LineKind::Code(_) => { |
| 626 | let last_of_block = self.lines.get(index + 1) != Some(&kind); |
| 627 | let block_continues_above = index > 0 && self.lines[index - 1] == kind; |
| 628 | if content.is_empty() && last_of_block && block_continues_above && !shift { |
| 629 | return Some(self.set_line_kind(index, LineKind::Text, None, cursor)); |
| 630 | } |
| 631 | self.splice(cursor..cursor, "\n", &[]); |
| 632 | Some(cursor + 1) |
| 633 | } |
| 634 | list => { |
| 635 | if self.text[content.clone()].trim().is_empty() { |
| 636 | let lifted = match list.depth() { |
| 637 | 0 => LineKind::Text, |
| 638 | depth => list.with_depth(depth - 1), |
| 639 | }; |
| 640 | let cursor = self.set_line_kind(index, lifted, None, cursor); |
| 641 | return Some(self.repair(cursor)); |
| 642 | } |
| 643 | self.splice(cursor..cursor, "\n", &[]); |
| 644 | self.lines[index + 1] = list; |
| 645 | let marker = self.expected_marker(index + 1, None); |
| 646 | self.splice(cursor + 1..cursor + 1, &marker, &[]); |
| 647 | Some(self.repair(cursor + 1 + marker.len())) |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | /// Forward Delete next to a marker: at a line end it joins the next line without its |
| 653 | /// marker; inside a marker it deletes the first character of the content instead. |
| 654 | pub fn delete_forward(&mut self, cursor: usize) -> Option<usize> { |
| 655 | self.journal = Journal::default(); |
| 656 | let index = self.line_at(cursor); |
| 657 | let line = self.line_ranges()[index].clone(); |
| 658 | let content = self.content_range(index); |
| 659 | if cursor >= line.start && cursor < content.start { |
| 660 | let next = self.text[content.start..] |
| 661 | .chars() |
| 662 | .next() |
| 663 | .filter(|character| *character != '\n'); |
| 664 | match next { |
| 665 | Some(character) => { |
| 666 | self.splice(content.start..content.start + character.len_utf8(), "", &[]); |
| 667 | } |
| 668 | None if index + 1 < self.lines.len() => { |
| 669 | let next_content = self.content_range(index + 1); |
| 670 | self.splice(content.end..next_content.start, "", &[]); |
| 671 | } |
| 672 | None => return Some(content.start), |
| 673 | } |
| 674 | return Some(self.repair(content.start)); |
| 675 | } |
| 676 | if cursor != line.end || index + 1 >= self.lines.len() { |
| 677 | return None; |
| 678 | } |
| 679 | let next_marker = self.marker_range(index + 1); |
| 680 | if next_marker.is_empty() { |
| 681 | return None; |
| 682 | } |
| 683 | self.splice(cursor..next_marker.end, "", &[]); |
| 684 | Some(self.repair(cursor)) |
| 685 | } |
| 686 | |
| 687 | /// Backspace at the start of a formatted line drops (or lifts) its format. |
| 688 | pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> { |
| 689 | self.journal = Journal::default(); |
| 690 | let index = self.line_at(cursor); |
| 691 | let kind = self.lines[index].clone(); |
| 692 | let line = self.line_ranges()[index].clone(); |
| 693 | let content = self.content_range(index); |
| 694 | match &kind { |
| 695 | LineKind::Text => None, |
| 696 | LineKind::Code(_) => { |
| 697 | let first_of_block = index == 0 || self.lines[index - 1] != kind; |
| 698 | (cursor == line.start && first_of_block).then(|| { |
| 699 | self.lines[index] = LineKind::Text; |
| 700 | cursor |
| 701 | }) |
| 702 | } |
| 703 | LineKind::Quote |
| 704 | if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) => |
| 705 | { |
| 706 | self.lines[index] = LineKind::Text; |
| 707 | Some(cursor) |
| 708 | } |
| 709 | _ if cursor == line.start && index > 0 => { |
| 710 | self.splice(line.start - 1..content.start, "", &[]); |
| 711 | Some(self.repair(line.start - 1)) |
| 712 | } |
| 713 | _ if cursor > line.start && cursor <= content.start => { |
| 714 | let lifted = match kind.depth() { |
| 715 | depth if depth > 0 => kind.with_depth(depth - 1), |
| 716 | _ => LineKind::Text, |
| 717 | }; |
| 718 | let cursor = self.set_line_kind(index, lifted, None, cursor); |
| 719 | Some(self.repair(cursor)) |
| 720 | } |
| 721 | _ => None, |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | /// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item. |
| 726 | pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool { |
| 727 | self.journal = Journal::default(); |
| 728 | let lines = self.selected_lines(&range); |
| 729 | if !lines.clone().all(|index| self.lines[index].is_list()) { |
| 730 | return false; |
| 731 | } |
| 732 | for index in lines { |
| 733 | let kind = self.lines[index].clone(); |
| 734 | let depth = kind.depth(); |
| 735 | let target = match (outdent, depth) { |
| 736 | (true, 0) => LineKind::Text, |
| 737 | (true, depth) => kind.with_depth(depth - 1), |
| 738 | (false, depth) => kind.with_depth((depth + 1).min(MAX_DEPTH)), |
| 739 | }; |
| 740 | self.set_line_kind(index, target, None, 0); |
| 741 | } |
| 742 | self.repair(0); |
| 743 | true |
| 744 | } |
| 745 | |
| 746 | /// All selected lines `kind` already: back to text. Otherwise all become `kind`. |
| 747 | pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) { |
| 748 | self.journal = Journal::default(); |
| 749 | let lines = self.selected_lines(&range); |
| 750 | let all = lines |
| 751 | .clone() |
| 752 | .all(|index| self.lines[index].same_format(&kind)); |
| 753 | for index in lines { |
| 754 | let current = self.lines[index].clone(); |
| 755 | let target = if all { |
| 756 | LineKind::Text |
| 757 | } else if current.same_format(&kind) { |
| 758 | current.clone() |
| 759 | } else if current.is_list() && kind.is_list() { |
| 760 | kind.with_depth(current.depth()) |
| 761 | } else { |
| 762 | kind.clone() |
| 763 | }; |
| 764 | if target != current { |
| 765 | self.set_line_kind(index, target, None, 0); |
| 766 | } |
| 767 | } |
| 768 | self.repair(0); |
| 769 | } |
| 770 | |
| 771 | pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> { |
| 772 | let mut lines = Vec::new(); |
| 773 | for (index, line) in self.line_ranges().into_iter().enumerate() { |
| 774 | if line.end < range.start || line.start > range.end { |
| 775 | continue; |
| 776 | } |
| 777 | let content = self.content_range(index); |
| 778 | let whole_start = range.start <= content.start; |
| 779 | let start = range.start.max(content.start); |
| 780 | let end = range.end.min(content.end).max(start); |
| 781 | let kind = if whole_start { |
| 782 | self.lines[index].clone() |
| 783 | } else { |
| 784 | LineKind::Text |
| 785 | }; |
| 786 | let number = match kind { |
| 787 | LineKind::Numbered(_) => { |
| 788 | numbered_marker(&self.text[line.clone()]).map(|(_, number)| number) |
| 789 | } |
| 790 | _ => None, |
| 791 | }; |
| 792 | let marks = self |
| 793 | .marks |
| 794 | .iter() |
| 795 | .filter_map(|mark| { |
| 796 | let clipped = mark.range.start.max(start)..mark.range.end.min(end); |
| 797 | (!clipped.is_empty()).then(|| Mark { |
| 798 | range: clipped.start - start..clipped.end - start, |
| 799 | kind: mark.kind.clone(), |
| 800 | }) |
| 801 | }) |
| 802 | .collect(); |
| 803 | lines.push(DraftLine { |
| 804 | kind, |
| 805 | number, |
| 806 | content: self.text[start..end].to_owned(), |
| 807 | marks, |
| 808 | }); |
| 809 | } |
| 810 | lines |
| 811 | } |
| 812 | |
| 813 | /// Puts `lines` in place of `range`. Returns the offset after the inserted content. |
| 814 | pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize { |
| 815 | self.journal = Journal::default(); |
| 816 | let index = self.line_at(range.start); |
| 817 | let content = self.content_range(index); |
| 818 | let start = range.start.max(content.start); |
| 819 | let range = start..range.end.max(start); |
| 820 | let tail_end = self.line_ranges()[self.line_at(range.end)].end; |
| 821 | let line_was_empty = self.lines[index] == LineKind::Text |
| 822 | && range.start == content.start |
| 823 | && range.end >= tail_end; |
| 824 | let joined = lines |
| 825 | .iter() |
| 826 | .map(|line| line.content.as_str()) |
| 827 | .collect::<Vec<_>>() |
| 828 | .join("\n"); |
| 829 | self.splice(range.clone(), &joined, &[]); |
| 830 | let mut offset = range.start; |
| 831 | for line in lines { |
| 832 | for mark in &line.marks { |
| 833 | self.add_mark( |
| 834 | offset + mark.range.start..offset + mark.range.end, |
| 835 | mark.kind.clone(), |
| 836 | ); |
| 837 | } |
| 838 | offset += line.content.len() + 1; |
| 839 | } |
| 840 | let length_before_markers = self.text.len(); |
| 841 | for (position, line) in lines.iter().enumerate() { |
| 842 | let first_and_kept = position == 0 && !line_was_empty; |
| 843 | if first_and_kept || line.kind == self.lines[index + position] { |
| 844 | continue; |
| 845 | } |
| 846 | self.set_line_kind(index + position, line.kind.clone(), line.number, 0); |
| 847 | } |
| 848 | let end = |
| 849 | (range.start + joined.len() + self.text.len()).saturating_sub(length_before_markers); |
| 850 | self.repair(end) |
| 851 | } |
| 852 | |
| 853 | /// Leading and trailing blank lines and spaces dropped. |
| 854 | pub fn trimmed(&self) -> Draft { |
| 855 | let mut lines = self.slice(0..self.text.len()); |
| 856 | let blank = |
| 857 | |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty(); |
| 858 | while lines.len() > 1 && lines.first().is_some_and(blank) { |
| 859 | lines.remove(0); |
| 860 | } |
| 861 | while lines.len() > 1 && lines.last().is_some_and(blank) { |
| 862 | lines.pop(); |
| 863 | } |
| 864 | if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) { |
| 865 | first.trim_start(); |
| 866 | } |
| 867 | if let Some(last) = lines |
| 868 | .last_mut() |
| 869 | .filter(|line| !matches!(line.kind, LineKind::Code(_))) |
| 870 | { |
| 871 | last.trim_end(); |
| 872 | } |
| 873 | Draft::from_lines(&lines) |
| 874 | } |
| 875 | |
| 876 | /// Teams chat HTML. |
| 877 | pub fn to_html(&self) -> String { |
| 878 | let lines = self.slice(0..self.text.len()); |
| 879 | let mut html = String::new(); |
| 880 | let mut index = 0; |
| 881 | while index < lines.len() { |
| 882 | let kind = &lines[index].kind; |
| 883 | let run_end = index |
| 884 | + lines[index..] |
| 885 | .iter() |
| 886 | .take_while(|line| match kind { |
| 887 | LineKind::Code(_) => line.kind == *kind, |
| 888 | _ if kind.is_list() => line.kind.is_list(), |
| 889 | _ => line.kind.same_format(kind), |
| 890 | }) |
| 891 | .count(); |
| 892 | let run = &lines[index..run_end]; |
| 893 | match kind { |
| 894 | LineKind::Text => html.push_str(&joined_inline(run)), |
| 895 | LineKind::Quote => { |
| 896 | html.push_str("<blockquote>"); |
| 897 | html.push_str(&joined_inline(run)); |
| 898 | html.push_str("</blockquote>"); |
| 899 | } |
| 900 | LineKind::Code(language) => { |
| 901 | match language { |
| 902 | Some(language) => html.push_str(&format!( |
| 903 | "<pre class=\"language-{}\">", |
| 904 | escape_html(language) |
| 905 | )), |
| 906 | None => html.push_str("<pre>"), |
| 907 | } |
| 908 | let code = run |
| 909 | .iter() |
| 910 | .map(|line| escape_html(&line.content)) |
| 911 | .collect::<Vec<_>>() |
| 912 | .join("\n"); |
| 913 | html.push_str(&code); |
| 914 | html.push_str("</pre>"); |
| 915 | } |
| 916 | _ => html.push_str(&list_html(run)), |
| 917 | } |
| 918 | index = run_end; |
| 919 | } |
| 920 | html |
| 921 | } |
| 922 | |
| 923 | fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec<MarkKind> { |
| 924 | let mut kinds: Vec<MarkKind> = self |
| 925 | .marks |
| 926 | .iter() |
| 927 | .filter(|mark| { |
| 928 | let range = &mark.range; |
| 929 | if old_end > start { |
| 930 | range.start <= start && start < range.end |
| 931 | } else { |
| 932 | (range.start < start && start < range.end) |
| 933 | || (range.start < start |
| 934 | && range.end == start |
| 935 | && mark.kind.continues_at_end()) |
| 936 | } |
| 937 | }) |
| 938 | .map(|mark| mark.kind.clone()) |
| 939 | .collect(); |
| 940 | kinds.sort(); |
| 941 | kinds.dedup(); |
| 942 | kinds |
| 943 | } |
| 944 | |
| 945 | fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> { |
| 946 | (self.line_at(range.start)..=self.line_at(range.end)) |
| 947 | .map(|index| { |
| 948 | let content = self.content_range(index); |
| 949 | content.start.max(range.start)..content.end.min(range.end) |
| 950 | }) |
| 951 | .filter(|part| !part.is_empty()) |
| 952 | .collect() |
| 953 | } |
| 954 | |
| 955 | /// Links with a scheme other than http, https or mailto stay plain text. |
| 956 | fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) { |
| 957 | let kind = match kind { |
| 958 | MarkKind::Link(url) => match link_url(&url) { |
| 959 | Some(url) => MarkKind::Link(url), |
| 960 | None => return, |
| 961 | }, |
| 962 | other => other, |
| 963 | }; |
| 964 | if !range.is_empty() { |
| 965 | self.marks.push(Mark { range, kind }); |
| 966 | self.normalize_marks(); |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | fn remove_marks(&mut self, range: Range<usize>, kind: &MarkKind) { |
| 971 | let mut kept = Vec::with_capacity(self.marks.len()); |
| 972 | for mark in std::mem::take(&mut self.marks) { |
| 973 | if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) { |
| 974 | kept.push(mark); |
| 975 | continue; |
| 976 | } |
| 977 | if mark.range.start < range.start { |
| 978 | kept.push(Mark { |
| 979 | range: mark.range.start..range.start, |
| 980 | kind: mark.kind.clone(), |
| 981 | }); |
| 982 | } |
| 983 | if mark.range.end > range.end { |
| 984 | kept.push(Mark { |
| 985 | range: range.end..mark.range.end, |
| 986 | kind: mark.kind, |
| 987 | }); |
| 988 | } |
| 989 | } |
| 990 | self.marks = kept; |
| 991 | self.normalize_marks(); |
| 992 | } |
| 993 | |
| 994 | fn normalize_marks(&mut self) { |
| 995 | let length = self.text.len(); |
| 996 | let mut marks: Vec<Mark> = std::mem::take(&mut self.marks) |
| 997 | .into_iter() |
| 998 | .map(|mark| Mark { |
| 999 | range: mark.range.start.min(length)..mark.range.end.min(length), |
| 1000 | kind: mark.kind, |
| 1001 | }) |
| 1002 | .filter(|mark| !mark.range.is_empty()) |
| 1003 | .collect(); |
| 1004 | marks.sort_by(|left, right| { |
| 1005 | left.kind |
| 1006 | .cmp(&right.kind) |
| 1007 | .then(left.range.start.cmp(&right.range.start)) |
| 1008 | }); |
| 1009 | let mut merged: Vec<Mark> = Vec::with_capacity(marks.len()); |
| 1010 | for mark in marks { |
| 1011 | match merged.last_mut() { |
| 1012 | Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => { |
| 1013 | last.range.end = last.range.end.max(mark.range.end); |
| 1014 | } |
| 1015 | _ => merged.push(mark), |
| 1016 | } |
| 1017 | } |
| 1018 | self.marks = merged; |
| 1019 | } |
| 1020 | |
| 1021 | fn splice(&mut self, range: Range<usize>, replacement: &str, kinds: &[MarkKind]) { |
| 1022 | let (start, old_end) = (range.start, range.end); |
| 1023 | let first_line = self.line_at(start); |
| 1024 | let last_line = self.line_at(old_end); |
| 1025 | let line_start = self.line_ranges()[first_line].start; |
| 1026 | let breaks = replacement.matches('\n').count(); |
| 1027 | let kind = self.lines[first_line].clone(); |
| 1028 | let mut new_kinds = Vec::with_capacity(breaks + 1); |
| 1029 | let pushes_line_down = breaks > 0 |
| 1030 | && start == line_start |
| 1031 | && old_end == start |
| 1032 | && !matches!(kind, LineKind::Code(_)) |
| 1033 | && self.text[start..] |
| 1034 | .chars() |
| 1035 | .next() |
| 1036 | .is_some_and(|next| next != '\n'); |
| 1037 | if pushes_line_down { |
| 1038 | new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks)); |
| 1039 | new_kinds.push(kind); |
| 1040 | } else { |
| 1041 | let continued = match &kind { |
| 1042 | LineKind::Code(language) => LineKind::Code(language.clone()), |
| 1043 | _ => LineKind::Text, |
| 1044 | }; |
| 1045 | new_kinds.push(kind); |
| 1046 | new_kinds.extend(std::iter::repeat_n(continued, breaks)); |
| 1047 | } |
| 1048 | self.lines.splice(first_line..=last_line, new_kinds); |
| 1049 | self.text.replace_range(range.clone(), replacement); |
| 1050 | |
| 1051 | let inserted = replacement.len(); |
| 1052 | let delta = inserted as isize - (old_end - start) as isize; |
| 1053 | let shift = |position: usize| (position as isize + delta) as usize; |
| 1054 | let map_start = |position: usize| { |
| 1055 | if position < start { |
| 1056 | position |
| 1057 | } else if position >= old_end { |
| 1058 | shift(position) |
| 1059 | } else { |
| 1060 | start + inserted |
| 1061 | } |
| 1062 | }; |
| 1063 | let map_end = |position: usize| { |
| 1064 | if position <= start { |
| 1065 | position |
| 1066 | } else if position >= old_end { |
| 1067 | shift(position) |
| 1068 | } else { |
| 1069 | start |
| 1070 | } |
| 1071 | }; |
| 1072 | for mark in &mut self.marks { |
| 1073 | mark.range = map_start(mark.range.start)..map_end(mark.range.end); |
| 1074 | } |
| 1075 | if inserted > 0 { |
| 1076 | let inserted_range = start..start + inserted; |
| 1077 | let mut kept = Vec::with_capacity(self.marks.len() + kinds.len()); |
| 1078 | for mark in std::mem::take(&mut self.marks) { |
| 1079 | if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) { |
| 1080 | kept.push(mark); |
| 1081 | continue; |
| 1082 | } |
| 1083 | if mark.range.start < inserted_range.start { |
| 1084 | kept.push(Mark { |
| 1085 | range: mark.range.start..inserted_range.start, |
| 1086 | kind: mark.kind.clone(), |
| 1087 | }); |
| 1088 | } |
| 1089 | if mark.range.end > inserted_range.end { |
| 1090 | kept.push(Mark { |
| 1091 | range: inserted_range.end..mark.range.end, |
| 1092 | kind: mark.kind, |
| 1093 | }); |
| 1094 | } |
| 1095 | } |
| 1096 | kept.extend(kinds.iter().map(|kind| Mark { |
| 1097 | range: inserted_range.clone(), |
| 1098 | kind: kind.clone(), |
| 1099 | })); |
| 1100 | self.marks = kept; |
| 1101 | } |
| 1102 | self.normalize_marks(); |
| 1103 | self.journal.record(range, inserted, &self.text); |
| 1104 | } |
| 1105 | |
| 1106 | fn previous_number(&self, index: usize, depth: u8) -> Option<u32> { |
| 1107 | let ranges = self.line_ranges(); |
| 1108 | for previous in (0..index).rev() { |
| 1109 | match &self.lines[previous] { |
| 1110 | LineKind::Numbered(previous_depth) if *previous_depth == depth => { |
| 1111 | return numbered_marker(&self.text[ranges[previous].clone()]) |
| 1112 | .map(|(_, number)| number); |
| 1113 | } |
| 1114 | kind if kind.is_list() && kind.depth() > depth => continue, |
| 1115 | _ => return None, |
| 1116 | } |
| 1117 | } |
| 1118 | None |
| 1119 | } |
| 1120 | |
| 1121 | fn expected_marker(&self, index: usize, own_number: Option<u32>) -> String { |
| 1122 | let kind = &self.lines[index]; |
| 1123 | let number = match kind { |
| 1124 | LineKind::Numbered(depth) => match self.previous_number(index, *depth) { |
| 1125 | Some(previous) => previous + 1, |
| 1126 | None => own_number |
| 1127 | .or_else(|| { |
| 1128 | let line = self.line_ranges()[index].clone(); |
| 1129 | numbered_marker(&self.text[line]).map(|(_, number)| number) |
| 1130 | }) |
| 1131 | .unwrap_or(1), |
| 1132 | }, |
| 1133 | _ => 1, |
| 1134 | }; |
| 1135 | marker_text(kind, number) |
| 1136 | } |
| 1137 | |
| 1138 | fn set_line_kind( |
| 1139 | &mut self, |
| 1140 | index: usize, |
| 1141 | kind: LineKind, |
| 1142 | number: Option<u32>, |
| 1143 | cursor: usize, |
| 1144 | ) -> usize { |
| 1145 | let marker = self.marker_range(index); |
| 1146 | self.lines[index] = kind; |
| 1147 | let expected = self.expected_marker(index, number); |
| 1148 | self.replace_marker(marker, &expected, cursor) |
| 1149 | } |
| 1150 | |
| 1151 | fn replace_marker(&mut self, marker: Range<usize>, expected: &str, cursor: usize) -> usize { |
| 1152 | if self.text[marker.clone()] == *expected { |
| 1153 | return cursor; |
| 1154 | } |
| 1155 | self.splice(marker.clone(), expected, &[]); |
| 1156 | if cursor >= marker.end { |
| 1157 | cursor + expected.len() - marker.len() |
| 1158 | } else if cursor > marker.start { |
| 1159 | marker.start + expected.len() |
| 1160 | } else { |
| 1161 | cursor |
| 1162 | } |
| 1163 | } |
| 1164 | |
| 1165 | /// List items whose marker was edited away become text; numbered items are renumbered. |
| 1166 | fn repair(&mut self, mut cursor: usize) -> usize { |
| 1167 | for index in 0..self.lines.len() { |
| 1168 | let kind = self.lines[index].clone(); |
| 1169 | if !kind.is_list() { |
| 1170 | continue; |
| 1171 | } |
| 1172 | let line = self.line_ranges()[index].clone(); |
| 1173 | let expected = self.expected_marker(index, None); |
| 1174 | let current = &self.text[line.clone()]; |
| 1175 | if current.starts_with(&expected) { |
| 1176 | continue; |
| 1177 | } |
| 1178 | match numbered_marker(current) { |
| 1179 | Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => { |
| 1180 | cursor = |
| 1181 | self.replace_marker(line.start..line.start + length, &expected, cursor); |
| 1182 | } |
| 1183 | _ => self.lines[index] = LineKind::Text, |
| 1184 | } |
| 1185 | } |
| 1186 | cursor |
| 1187 | } |
| 1188 | } |
| 1189 | |
| 1190 | fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool { |
| 1191 | left.start < right.end && right.start < left.end |
| 1192 | } |
| 1193 | |
| 1194 | fn bullet_marker(depth: u8) -> String { |
| 1195 | format!("{} ", BULLETS[depth as usize % BULLETS.len()]) |
| 1196 | } |
| 1197 | |
| 1198 | fn marker_text(kind: &LineKind, number: u32) -> String { |
| 1199 | match kind { |
| 1200 | LineKind::Bullet(depth) => bullet_marker(*depth), |
| 1201 | LineKind::Numbered(_) => format!("{number}. "), |
| 1202 | LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(), |
| 1203 | } |
| 1204 | } |
| 1205 | |
| 1206 | fn marker_len(kind: &LineKind, line: &str) -> usize { |
| 1207 | match kind { |
| 1208 | LineKind::Bullet(depth) => { |
| 1209 | let marker = bullet_marker(*depth); |
| 1210 | if line.starts_with(&marker) { |
| 1211 | marker.len() |
| 1212 | } else { |
| 1213 | 0 |
| 1214 | } |
| 1215 | } |
| 1216 | LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length), |
| 1217 | _ => 0, |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | /// Byte length and number of a `1. ` marker. |
| 1222 | fn numbered_marker(line: &str) -> Option<(usize, u32)> { |
| 1223 | let digits = line.bytes().take_while(u8::is_ascii_digit).count(); |
| 1224 | if digits == 0 || digits > 9 || !line[digits..].starts_with(". ") { |
| 1225 | return None; |
| 1226 | } |
| 1227 | Some((digits + 2, line[..digits].parse().ok()?)) |
| 1228 | } |
| 1229 | |
| 1230 | fn line_shortcut(before: &str) -> Option<(LineKind, u32)> { |
| 1231 | match before { |
| 1232 | "- " | "* " => Some((LineKind::Bullet(0), 1)), |
| 1233 | "> " => Some((LineKind::Quote, 1)), |
| 1234 | _ => { |
| 1235 | let digits = before.strip_suffix(". ")?; |
| 1236 | let all_digits = !digits.is_empty() |
| 1237 | && digits.len() <= 9 |
| 1238 | && digits.bytes().all(|byte| byte.is_ascii_digit()); |
| 1239 | all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1))) |
| 1240 | } |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | fn fence_language(line: &str) -> Option<Option<String>> { |
| 1245 | let info = line.trim().strip_prefix(FENCE)?; |
| 1246 | let valid = info |
| 1247 | .chars() |
| 1248 | .all(|character| character.is_alphanumeric() || "+#-_.".contains(character)); |
| 1249 | valid.then(|| (!info.is_empty()).then(|| info.to_lowercase())) |
| 1250 | } |
| 1251 | |
| 1252 | fn valid_inner(inner: &str) -> bool { |
| 1253 | !inner.is_empty() |
| 1254 | && !inner.starts_with(char::is_whitespace) |
| 1255 | && !inner.ends_with(char::is_whitespace) |
| 1256 | } |
| 1257 | |
| 1258 | fn word_before(text: &str) -> bool { |
| 1259 | text.chars() |
| 1260 | .next_back() |
| 1261 | .is_some_and(|character| character.is_alphanumeric()) |
| 1262 | } |
| 1263 | |
| 1264 | /// `https://` added when there is no scheme. `None` for any scheme but http, https and mailto. |
| 1265 | pub fn link_url(text: &str) -> Option<String> { |
| 1266 | let text = text.trim(); |
| 1267 | if text.is_empty() || text.contains(char::is_whitespace) { |
| 1268 | return None; |
| 1269 | } |
| 1270 | let lower = text.to_ascii_lowercase(); |
| 1271 | if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) { |
| 1272 | return Some(text.to_owned()); |
| 1273 | } |
| 1274 | let scheme = text.split_once(':').filter(|(scheme, rest)| { |
| 1275 | let host = scheme.contains('.') || scheme.eq_ignore_ascii_case("localhost"); |
| 1276 | let host_and_port = host && rest.starts_with(|character: char| character.is_ascii_digit()); |
| 1277 | !host_and_port |
| 1278 | && scheme.starts_with(|character: char| character.is_ascii_alphabetic()) |
| 1279 | && scheme |
| 1280 | .chars() |
| 1281 | .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character)) |
| 1282 | }); |
| 1283 | scheme.is_none().then(|| format!("https://{text}")) |
| 1284 | } |
| 1285 | |
| 1286 | /// The markers of a format closed by the last typed character, relative to `before`. |
| 1287 | fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> { |
| 1288 | let end = before.len(); |
| 1289 | if before.ends_with(')') { |
| 1290 | let captures = TYPED_LINK.captures(before)?; |
| 1291 | let whole = captures.get(0)?; |
| 1292 | let label = captures.get(1)?; |
| 1293 | return Some(( |
| 1294 | whole.start()..whole.start() + 1, |
| 1295 | label.end()..end, |
| 1296 | MarkKind::Link(link_url(&captures[2])?), |
| 1297 | )); |
| 1298 | } |
| 1299 | for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] { |
| 1300 | if let Some(body) = before.strip_suffix(marker) { |
| 1301 | let open = body.rfind(marker)?; |
| 1302 | return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind)); |
| 1303 | } |
| 1304 | } |
| 1305 | if let Some(body) = before.strip_suffix('`') { |
| 1306 | let open = body.rfind('`')?; |
| 1307 | let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`'); |
| 1308 | return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code)); |
| 1309 | } |
| 1310 | for marker in ['*', '_'] { |
| 1311 | if let Some(body) = before.strip_suffix(marker) { |
| 1312 | if body.ends_with(marker) { |
| 1313 | return None; |
| 1314 | } |
| 1315 | let open = body.rfind(marker)?; |
| 1316 | let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker); |
| 1317 | return (opening_ok && valid_inner(&body[open + 1..])) |
| 1318 | .then(|| (open..open + 1, body.len()..end, MarkKind::Italic)); |
| 1319 | } |
| 1320 | } |
| 1321 | None |
| 1322 | } |
| 1323 | |
| 1324 | pub fn changed_span(old: &str, new: &str) -> (usize, usize, usize) { |
| 1325 | edit_span(old, new, new.len()) |
| 1326 | } |
| 1327 | |
| 1328 | fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) { |
| 1329 | let prefix = old |
| 1330 | .char_indices() |
| 1331 | .zip(new.chars()) |
| 1332 | .find(|((_, left), right)| left != right) |
| 1333 | .map_or(old.len().min(new.len()), |((index, _), _)| index); |
| 1334 | let prefix = { |
| 1335 | let mut prefix = prefix.min(old.len()).min(new.len()); |
| 1336 | while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) { |
| 1337 | prefix -= 1; |
| 1338 | } |
| 1339 | prefix |
| 1340 | }; |
| 1341 | let suffix = old[prefix..] |
| 1342 | .chars() |
| 1343 | .rev() |
| 1344 | .zip(new[prefix..].chars().rev()) |
| 1345 | .take_while(|(left, right)| left == right) |
| 1346 | .map(|(character, _)| character.len_utf8()) |
| 1347 | .sum::<usize>(); |
| 1348 | let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix); |
| 1349 | let cursor = cursor.min(new.len()); |
| 1350 | let pure = old_end == start || new_end == start; |
| 1351 | if pure && new_end > cursor && new_end - cursor <= start { |
| 1352 | let slide = new_end - cursor; |
| 1353 | let (slid_start, slid_old_end, slid_new_end) = |
| 1354 | (start - slide, old_end - slide, new_end - slide); |
| 1355 | let boundaries = [slid_start, slid_old_end] |
| 1356 | .iter() |
| 1357 | .all(|offset| old.is_char_boundary(*offset)) |
| 1358 | && [slid_start, slid_new_end] |
| 1359 | .iter() |
| 1360 | .all(|offset| new.is_char_boundary(*offset)); |
| 1361 | if boundaries && new[slid_new_end..] == old[slid_old_end..] { |
| 1362 | return (slid_start, slid_old_end, slid_new_end); |
| 1363 | } |
| 1364 | } |
| 1365 | (start, old_end, new_end) |
| 1366 | } |
| 1367 | |
| 1368 | fn joined_inline(lines: &[DraftLine]) -> String { |
| 1369 | lines |
| 1370 | .iter() |
| 1371 | .map(|line| inline_html(&line.content, &line.marks)) |
| 1372 | .collect::<Vec<_>>() |
| 1373 | .join("<br>") |
| 1374 | } |
| 1375 | |
| 1376 | fn inline_html(content: &str, marks: &[Mark]) -> String { |
| 1377 | let mut boundaries: Vec<usize> = marks |
| 1378 | .iter() |
| 1379 | .flat_map(|mark| [mark.range.start, mark.range.end]) |
| 1380 | .chain([0, content.len()]) |
| 1381 | .filter(|offset| *offset <= content.len()) |
| 1382 | .collect(); |
| 1383 | boundaries.sort_unstable(); |
| 1384 | boundaries.dedup(); |
| 1385 | let mut html = String::new(); |
| 1386 | let mut open: Vec<&MarkKind> = Vec::new(); |
| 1387 | for window in boundaries.windows(2) { |
| 1388 | let segment = window[0]..window[1]; |
| 1389 | let mut active: Vec<&MarkKind> = marks |
| 1390 | .iter() |
| 1391 | .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end) |
| 1392 | .map(|mark| &mark.kind) |
| 1393 | .collect(); |
| 1394 | active.sort(); |
| 1395 | active.dedup(); |
| 1396 | let common = open |
| 1397 | .iter() |
| 1398 | .zip(active.iter()) |
| 1399 | .take_while(|(left, right)| left == right) |
| 1400 | .count(); |
| 1401 | for kind in open.drain(common..).rev() { |
| 1402 | html.push_str(kind.close_tag()); |
| 1403 | } |
| 1404 | for kind in &active[common..] { |
| 1405 | html.push_str(&kind.open_tag()); |
| 1406 | } |
| 1407 | open.extend(active[common..].iter().copied()); |
| 1408 | html.push_str(&escape_html(&content[segment])); |
| 1409 | } |
| 1410 | for kind in open.into_iter().rev() { |
| 1411 | html.push_str(kind.close_tag()); |
| 1412 | } |
| 1413 | html |
| 1414 | } |
| 1415 | |
| 1416 | fn list_html(lines: &[DraftLine]) -> String { |
| 1417 | let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" }; |
| 1418 | let mut html = String::new(); |
| 1419 | let mut open: Vec<(u8, bool)> = Vec::new(); |
| 1420 | for line in lines { |
| 1421 | let ordered = matches!(line.kind, LineKind::Numbered(_)); |
| 1422 | let depth = line |
| 1423 | .kind |
| 1424 | .depth() |
| 1425 | .min(open.last().map_or(0, |(depth, _)| depth + 1)); |
| 1426 | while open |
| 1427 | .last() |
| 1428 | .is_some_and(|(open_depth, _)| *open_depth > depth) |
| 1429 | { |
| 1430 | let (_, was_ordered) = open.pop().unwrap_or_default(); |
| 1431 | html.push_str(close(was_ordered)); |
| 1432 | } |
| 1433 | match open.last().copied() { |
| 1434 | Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => { |
| 1435 | html.push_str("</li>"); |
| 1436 | } |
| 1437 | Some((open_depth, open_ordered)) if open_depth == depth => { |
| 1438 | html.push_str(close(open_ordered)); |
| 1439 | open.pop(); |
| 1440 | html.push_str(&list_open(ordered, line.number)); |
| 1441 | open.push((depth, ordered)); |
| 1442 | } |
| 1443 | _ => { |
| 1444 | html.push_str(&list_open(ordered, line.number)); |
| 1445 | open.push((depth, ordered)); |
| 1446 | } |
| 1447 | } |
| 1448 | html.push_str("<li>"); |
| 1449 | html.push_str(&inline_html(&line.content, &line.marks)); |
| 1450 | } |
| 1451 | for (_, ordered) in open.into_iter().rev() { |
| 1452 | html.push_str(close(ordered)); |
| 1453 | } |
| 1454 | html |
| 1455 | } |
| 1456 | |
| 1457 | fn list_open(ordered: bool, number: Option<u32>) -> String { |
| 1458 | match (ordered, number) { |
| 1459 | (false, _) => "<ul>".to_owned(), |
| 1460 | (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"), |
| 1461 | (true, _) => "<ol>".to_owned(), |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | /// Text that `from_markdown` would format: pasting it converts. |
| 1466 | pub fn has_markdown(text: &str) -> bool { |
| 1467 | let draft = Draft::from_markdown(text); |
| 1468 | !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text) |
| 1469 | } |
| 1470 | |
| 1471 | fn markdown_lines(text: &str) -> Vec<DraftLine> { |
| 1472 | let mut lines = Vec::new(); |
| 1473 | let mut code: Option<Option<String>> = None; |
| 1474 | for raw in text.split('\n') { |
| 1475 | let raw = raw.strip_suffix('\r').unwrap_or(raw); |
| 1476 | let trimmed = raw.trim_start(); |
| 1477 | if let Some(language) = &code { |
| 1478 | if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE { |
| 1479 | code = None; |
| 1480 | } else { |
| 1481 | lines.push(DraftLine { |
| 1482 | kind: LineKind::Code(language.clone()), |
| 1483 | number: None, |
| 1484 | content: raw.to_owned(), |
| 1485 | marks: Vec::new(), |
| 1486 | }); |
| 1487 | } |
| 1488 | continue; |
| 1489 | } |
| 1490 | if trimmed.starts_with(FENCE) |
| 1491 | && !trimmed[FENCE.len()..].contains('`') |
| 1492 | && let Some(language) = fence_language(trimmed) |
| 1493 | { |
| 1494 | code = Some(language); |
| 1495 | continue; |
| 1496 | } |
| 1497 | let indent: usize = raw[..raw.len() - trimmed.len()] |
| 1498 | .chars() |
| 1499 | .map(|character| if character == '\t' { 4 } else { 1 }) |
| 1500 | .sum(); |
| 1501 | let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH); |
| 1502 | let (kind, number, content) = if let Some(rest) = PASTED_BULLETS |
| 1503 | .iter() |
| 1504 | .find_map(|bullet| trimmed.strip_prefix(bullet)) |
| 1505 | { |
| 1506 | (LineKind::Bullet(depth), None, rest) |
| 1507 | } else if let Some((length, number)) = numbered_marker(trimmed) { |
| 1508 | (LineKind::Numbered(depth), Some(number), &trimmed[length..]) |
| 1509 | } else if let Some(rest) = trimmed |
| 1510 | .strip_prefix("> ") |
| 1511 | .or_else(|| (trimmed == ">").then_some("")) |
| 1512 | { |
| 1513 | (LineKind::Quote, None, rest) |
| 1514 | } else { |
| 1515 | (LineKind::Text, None, raw) |
| 1516 | }; |
| 1517 | let (content, marks) = parse_inline(content); |
| 1518 | lines.push(DraftLine { |
| 1519 | kind, |
| 1520 | number, |
| 1521 | content, |
| 1522 | marks, |
| 1523 | }); |
| 1524 | } |
| 1525 | lines |
| 1526 | } |
| 1527 | |
| 1528 | fn parse_inline(source: &str) -> (String, Vec<Mark>) { |
| 1529 | let mut text = String::with_capacity(source.len()); |
| 1530 | let mut marks = Vec::new(); |
| 1531 | parse_into(source, &mut text, &mut marks); |
| 1532 | (text, marks) |
| 1533 | } |
| 1534 | |
| 1535 | fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) { |
| 1536 | let mut rest = source; |
| 1537 | let mut previous: Option<char> = None; |
| 1538 | while let Some(character) = rest.chars().next() { |
| 1539 | if let Some((inner, consumed, kind)) = inline_at(rest, previous) { |
| 1540 | let start = text.len(); |
| 1541 | if kind == MarkKind::Code { |
| 1542 | text.push_str(inner); |
| 1543 | } else { |
| 1544 | parse_into(inner, text, marks); |
| 1545 | } |
| 1546 | marks.push(Mark { |
| 1547 | range: start..text.len(), |
| 1548 | kind, |
| 1549 | }); |
| 1550 | previous = rest[..consumed].chars().next_back(); |
| 1551 | rest = &rest[consumed..]; |
| 1552 | continue; |
| 1553 | } |
| 1554 | text.push(character); |
| 1555 | previous = Some(character); |
| 1556 | rest = &rest[character.len_utf8()..]; |
| 1557 | } |
| 1558 | } |
| 1559 | |
| 1560 | /// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind. |
| 1561 | fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> { |
| 1562 | if let Some(after) = rest.strip_prefix('`') { |
| 1563 | let end = after.find('`')?; |
| 1564 | let inner = &after[..end]; |
| 1565 | return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code)); |
| 1566 | } |
| 1567 | if rest.starts_with('[') { |
| 1568 | let captures = LINK_AT.captures(rest)?; |
| 1569 | let label = captures.get(1)?; |
| 1570 | return Some(( |
| 1571 | label.as_str(), |
| 1572 | captures.get(0)?.end(), |
| 1573 | MarkKind::Link(link_url(&captures[2])?), |
| 1574 | )); |
| 1575 | } |
| 1576 | for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] { |
| 1577 | if let Some(after) = rest.strip_prefix(marker) { |
| 1578 | let end = after.find(marker)?; |
| 1579 | let inner = &after[..end]; |
| 1580 | return valid_inner(inner).then_some((inner, end + 4, kind)); |
| 1581 | } |
| 1582 | } |
| 1583 | for marker in ['*', '_'] { |
| 1584 | let Some(after) = rest.strip_prefix(marker) else { |
| 1585 | continue; |
| 1586 | }; |
| 1587 | if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) { |
| 1588 | return None; |
| 1589 | } |
| 1590 | let end = after.find(marker)?; |
| 1591 | let inner = &after[..end]; |
| 1592 | let followed_by_word = after[end + 1..] |
| 1593 | .chars() |
| 1594 | .next() |
| 1595 | .is_some_and(char::is_alphanumeric); |
| 1596 | return (valid_inner(inner) && !followed_by_word).then_some(( |
| 1597 | inner, |
| 1598 | end + 2, |
| 1599 | MarkKind::Italic, |
| 1600 | )); |
| 1601 | } |
| 1602 | None |
| 1603 | } |
| 1604 | |
| 1605 | #[derive(Default)] |
| 1606 | struct SpanLines { |
| 1607 | lines: Vec<DraftLine>, |
| 1608 | open: bool, |
| 1609 | } |
| 1610 | |
| 1611 | impl SpanLines { |
| 1612 | fn start_line(&mut self, kind: &LineKind, number: Option<u32>) { |
| 1613 | self.lines.push(DraftLine { |
| 1614 | kind: kind.clone(), |
| 1615 | number, |
| 1616 | content: String::new(), |
| 1617 | marks: Vec::new(), |
| 1618 | }); |
| 1619 | self.open = true; |
| 1620 | } |
| 1621 | |
| 1622 | fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) { |
| 1623 | for (index, piece) in text.split('\n').enumerate() { |
| 1624 | if index > 0 || !self.open { |
| 1625 | self.start_line(kind, None); |
| 1626 | } |
| 1627 | let Some(line) = self.lines.last_mut() else { |
| 1628 | continue; |
| 1629 | }; |
| 1630 | let start = line.content.len(); |
| 1631 | line.content.push_str(piece); |
| 1632 | let end = line.content.len(); |
| 1633 | if end > start { |
| 1634 | line.marks.extend(marks.iter().map(|kind| Mark { |
| 1635 | range: start..end, |
| 1636 | kind: kind.clone(), |
| 1637 | })); |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) { |
| 1643 | let with = |extra: MarkKind| { |
| 1644 | let mut marks = marks.to_vec(); |
| 1645 | marks.push(extra); |
| 1646 | marks |
| 1647 | }; |
| 1648 | for (index, span) in spans.iter().enumerate() { |
| 1649 | let block_follows = matches!( |
| 1650 | spans.get(index + 1), |
| 1651 | Some( |
| 1652 | Span::List { .. } |
| 1653 | | Span::BlockQuote(_) |
| 1654 | | Span::CodeBlock { .. } |
| 1655 | | Span::Heading { .. } |
| 1656 | | Span::Table { .. } |
| 1657 | ) |
| 1658 | ); |
| 1659 | match span { |
| 1660 | Span::Text(text) => self.append(text, kind, marks), |
| 1661 | Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)), |
| 1662 | Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)), |
| 1663 | Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)), |
| 1664 | Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)), |
| 1665 | Span::Colored { children, .. } => self.walk(children, kind, marks), |
| 1666 | Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)), |
| 1667 | Span::Link { url, children } => { |
| 1668 | self.walk(children, kind, &with(MarkKind::Link(url.clone()))) |
| 1669 | } |
| 1670 | Span::Mention { name, .. } => { |
| 1671 | self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks) |
| 1672 | } |
| 1673 | Span::LineBreak | Span::Rule if !self.open || block_follows => {} |
| 1674 | Span::LineBreak | Span::Rule => { |
| 1675 | let continued = match kind { |
| 1676 | LineKind::Quote | LineKind::Code(_) => kind.clone(), |
| 1677 | _ => LineKind::Text, |
| 1678 | }; |
| 1679 | self.start_line(&continued, None); |
| 1680 | } |
| 1681 | Span::Heading { children, .. } => { |
| 1682 | self.start_line(&LineKind::Text, None); |
| 1683 | self.walk(children, &LineKind::Text, &with(MarkKind::Bold)); |
| 1684 | self.open = false; |
| 1685 | } |
| 1686 | Span::CodeBlock { language, code } => { |
| 1687 | let code_kind = LineKind::Code(language.clone()); |
| 1688 | for line in code.trim_end_matches('\n').split('\n') { |
| 1689 | self.start_line(&code_kind, None); |
| 1690 | self.append(line, &code_kind, &[]); |
| 1691 | } |
| 1692 | self.open = false; |
| 1693 | } |
| 1694 | Span::BlockQuote(children) => { |
| 1695 | self.start_line(&LineKind::Quote, None); |
| 1696 | self.walk(children, &LineKind::Quote, marks); |
| 1697 | self.open = false; |
| 1698 | } |
| 1699 | Span::List { |
| 1700 | ordered, |
| 1701 | start, |
| 1702 | items, |
| 1703 | } => { |
| 1704 | let depth = if kind.is_list() { |
| 1705 | (kind.depth() + 1).min(MAX_DEPTH) |
| 1706 | } else { |
| 1707 | 0 |
| 1708 | }; |
| 1709 | let item_kind = if *ordered { |
| 1710 | LineKind::Numbered(depth) |
| 1711 | } else { |
| 1712 | LineKind::Bullet(depth) |
| 1713 | }; |
| 1714 | for (position, item) in items.iter().enumerate() { |
| 1715 | let number = (position == 0).then_some(*start); |
| 1716 | self.start_line(&item_kind, number); |
| 1717 | self.walk(item, &item_kind, marks); |
| 1718 | } |
| 1719 | self.open = false; |
| 1720 | } |
| 1721 | Span::Table { rows, .. } => { |
| 1722 | for row in rows { |
| 1723 | self.start_line(&LineKind::Text, None); |
| 1724 | for (position, cell) in row.iter().enumerate() { |
| 1725 | if position > 0 { |
| 1726 | self.append(" | ", &LineKind::Text, &[]); |
| 1727 | } |
| 1728 | self.walk(cell, &LineKind::Text, marks); |
| 1729 | } |
| 1730 | } |
| 1731 | self.open = false; |
| 1732 | } |
| 1733 | Span::Image { .. } | Span::Quote(_) => {} |
| 1734 | } |
| 1735 | } |
| 1736 | } |
| 1737 | |
| 1738 | fn finish(mut self) -> Vec<DraftLine> { |
| 1739 | let blank = |
| 1740 | |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty(); |
| 1741 | while self.lines.len() > 1 && self.lines.last().is_some_and(blank) { |
| 1742 | self.lines.pop(); |
| 1743 | } |
| 1744 | while self.lines.len() > 1 && self.lines.first().is_some_and(blank) { |
| 1745 | self.lines.remove(0); |
| 1746 | } |
| 1747 | if self.lines.is_empty() { |
| 1748 | self.lines.push(DraftLine::text("")); |
| 1749 | } |
| 1750 | self.lines |
| 1751 | } |
| 1752 | } |
| 1753 | |
| 1754 | #[cfg(test)] |
| 1755 | mod tests { |
| 1756 | use super::*; |
| 1757 | use crate::html_to_spans; |
| 1758 | |
| 1759 | fn typed(draft: &mut Draft, text: &str) { |
| 1760 | let mut typing: Option<TypingStyle> = None; |
| 1761 | for character in text.chars() { |
| 1762 | let cursor = draft.text().len(); |
| 1763 | let mut next = draft.text().to_owned(); |
| 1764 | next.push(character); |
| 1765 | let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref()); |
| 1766 | typing = draft.convert_typed(cursor).map(|(_, style)| style); |
| 1767 | draft.take_edits(); |
| 1768 | } |
| 1769 | } |
| 1770 | |
| 1771 | fn typed_draft(text: &str) -> Draft { |
| 1772 | let mut draft = Draft::default(); |
| 1773 | typed(&mut draft, text); |
| 1774 | draft |
| 1775 | } |
| 1776 | |
| 1777 | fn mark(range: Range<usize>, kind: MarkKind) -> Mark { |
| 1778 | Mark { range, kind } |
| 1779 | } |
| 1780 | |
| 1781 | #[test] |
| 1782 | fn typed_markdown_becomes_formatting() { |
| 1783 | let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`"); |
| 1784 | assert_eq!(draft.text(), "a bold and it or it gone code"); |
| 1785 | assert_eq!( |
| 1786 | draft.marks(), |
| 1787 | [ |
| 1788 | mark(2..6, MarkKind::Bold), |
| 1789 | mark(11..13, MarkKind::Italic), |
| 1790 | mark(17..19, MarkKind::Italic), |
| 1791 | mark(20..24, MarkKind::Strike), |
| 1792 | mark(25..29, MarkKind::Code), |
| 1793 | ] |
| 1794 | ); |
| 1795 | } |
| 1796 | |
| 1797 | #[test] |
| 1798 | fn typed_link_keeps_the_label_and_carries_the_url() { |
| 1799 | let draft = typed_draft("see [docs](https://example.com)"); |
| 1800 | assert_eq!(draft.text(), "see docs"); |
| 1801 | assert_eq!( |
| 1802 | draft.marks(), |
| 1803 | [mark(4..8, MarkKind::Link("https://example.com".into()))] |
| 1804 | ); |
| 1805 | } |
| 1806 | |
| 1807 | #[test] |
| 1808 | fn snake_case_and_spaced_stars_stay_text() { |
| 1809 | assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name"); |
| 1810 | assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4"); |
| 1811 | assert!(typed_draft("a** b**").marks().is_empty()); |
| 1812 | } |
| 1813 | |
| 1814 | #[test] |
| 1815 | fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() { |
| 1816 | let mut draft = Draft::plain("b"); |
| 1817 | draft.toggle(0..1, MarkKind::Bold); |
| 1818 | typed(&mut draft, "x"); |
| 1819 | assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]); |
| 1820 | let converted = typed_draft("**b**x"); |
| 1821 | assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]); |
| 1822 | let mut linked = typed_draft("[a](u)"); |
| 1823 | typed(&mut linked, "b"); |
| 1824 | assert_eq!( |
| 1825 | linked.marks(), |
| 1826 | [mark(0..1, MarkKind::Link("https://u".into()))] |
| 1827 | ); |
| 1828 | } |
| 1829 | |
| 1830 | #[test] |
| 1831 | fn typing_style_switches_bold_on_and_off_for_the_next_text() { |
| 1832 | let mut draft = Draft::plain("ab"); |
| 1833 | let typing = TypingStyle { |
| 1834 | at: 2, |
| 1835 | add: vec![MarkKind::Bold], |
| 1836 | remove: Vec::new(), |
| 1837 | }; |
| 1838 | draft.apply_edit("abc", 3, Some(&typing)); |
| 1839 | assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]); |
| 1840 | let off = TypingStyle { |
| 1841 | at: 3, |
| 1842 | add: Vec::new(), |
| 1843 | remove: vec![MarkKind::Bold], |
| 1844 | }; |
| 1845 | draft.apply_edit("abcd", 4, Some(&off)); |
| 1846 | assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]); |
| 1847 | } |
| 1848 | |
| 1849 | #[test] |
| 1850 | fn toggle_on_a_mixed_selection_formats_all_then_clears() { |
| 1851 | let mut draft = Draft::plain("hello world"); |
| 1852 | draft.toggle(0..5, MarkKind::Bold); |
| 1853 | assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed); |
| 1854 | draft.toggle(0..11, MarkKind::Bold); |
| 1855 | assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On); |
| 1856 | draft.toggle(0..11, MarkKind::Bold); |
| 1857 | assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off); |
| 1858 | assert!(draft.marks().is_empty()); |
| 1859 | } |
| 1860 | |
| 1861 | #[test] |
| 1862 | fn deleting_inside_and_across_marks_shifts_and_clips() { |
| 1863 | let mut draft = Draft::plain("aa bold cc"); |
| 1864 | draft.toggle(3..7, MarkKind::Bold); |
| 1865 | draft.apply_edit("aa bld cc", 4, None); |
| 1866 | assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]); |
| 1867 | draft.apply_edit("ald cc", 1, None); |
| 1868 | assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]); |
| 1869 | draft.apply_edit("XXald cc", 2, None); |
| 1870 | assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]); |
| 1871 | } |
| 1872 | |
| 1873 | #[test] |
| 1874 | fn repeated_characters_are_attributed_to_the_cursor() { |
| 1875 | let mut draft = Draft::plain("aa"); |
| 1876 | draft.toggle(0..1, MarkKind::Bold); |
| 1877 | draft.apply_edit("aaa", 2, None); |
| 1878 | assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]); |
| 1879 | } |
| 1880 | |
| 1881 | #[test] |
| 1882 | fn list_shortcuts_turn_lines_into_items() { |
| 1883 | let draft = typed_draft("- one"); |
| 1884 | assert_eq!(draft.text(), "• one"); |
| 1885 | assert_eq!(draft.lines(), [LineKind::Bullet(0)]); |
| 1886 | let numbered = typed_draft("1. one"); |
| 1887 | assert_eq!(numbered.text(), "1. one"); |
| 1888 | assert_eq!(numbered.lines(), [LineKind::Numbered(0)]); |
| 1889 | let quote = typed_draft("> said"); |
| 1890 | assert_eq!(quote.text(), "said"); |
| 1891 | assert_eq!(quote.lines(), [LineKind::Quote]); |
| 1892 | } |
| 1893 | |
| 1894 | #[test] |
| 1895 | fn enter_continues_a_list_and_ends_it_on_an_empty_item() { |
| 1896 | let mut draft = typed_draft("1. one"); |
| 1897 | let cursor = draft.break_line(draft.text().len(), false).unwrap(); |
| 1898 | assert_eq!(draft.text(), "1. one\n2. "); |
| 1899 | assert_eq!(cursor, draft.text().len()); |
| 1900 | typed(&mut draft, "two"); |
| 1901 | let cursor = draft.break_line(draft.text().len(), false).unwrap(); |
| 1902 | let cursor = draft.break_line(cursor, false).unwrap(); |
| 1903 | assert_eq!(draft.text(), "1. one\n2. two\n"); |
| 1904 | assert_eq!(cursor, draft.text().len()); |
| 1905 | assert_eq!(draft.lines()[2], LineKind::Text); |
| 1906 | assert_eq!(Draft::plain("x").break_line(1, false), None); |
| 1907 | } |
| 1908 | |
| 1909 | #[test] |
| 1910 | fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() { |
| 1911 | let mut draft = Draft::from_markdown("1. ab\n2. c"); |
| 1912 | draft.break_line(4, false).unwrap(); |
| 1913 | assert_eq!(draft.text(), "1. a\n2. b\n3. c"); |
| 1914 | let edits = draft.take_edits(); |
| 1915 | assert_eq!(map_offset(&edits, 4), 8); |
| 1916 | } |
| 1917 | |
| 1918 | #[test] |
| 1919 | fn tab_nests_and_shift_tab_lifts_list_items() { |
| 1920 | let mut draft = Draft::from_markdown("- a\n- b"); |
| 1921 | assert!(draft.indent(6..6, false)); |
| 1922 | assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]); |
| 1923 | assert_eq!(draft.text(), "• a\n◦ b"); |
| 1924 | assert!(draft.indent(draft.text().len()..draft.text().len(), true)); |
| 1925 | assert!(draft.indent(draft.text().len()..draft.text().len(), true)); |
| 1926 | assert_eq!(draft.text(), "• a\nb"); |
| 1927 | assert!(!Draft::plain("x").indent(0..0, false)); |
| 1928 | } |
| 1929 | |
| 1930 | #[test] |
| 1931 | fn nested_numbering_counts_per_level() { |
| 1932 | let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b"); |
| 1933 | assert_eq!(draft.text(), "1. a\n1. x\n2. y\n2. b"); |
| 1934 | } |
| 1935 | |
| 1936 | #[test] |
| 1937 | fn backspace_at_an_item_start_drops_the_bullet() { |
| 1938 | let mut draft = Draft::from_markdown("- a"); |
| 1939 | let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap(); |
| 1940 | assert_eq!((draft.text(), cursor), ("a", 0)); |
| 1941 | assert_eq!(draft.lines(), [LineKind::Text]); |
| 1942 | } |
| 1943 | |
| 1944 | #[test] |
| 1945 | fn typing_before_a_bullet_lands_after_it() { |
| 1946 | let mut draft = Draft::from_markdown("- a"); |
| 1947 | let marker = bullet_marker(0); |
| 1948 | let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None); |
| 1949 | assert_eq!(draft.text(), format!("{marker}xa")); |
| 1950 | assert_eq!(cursor, marker.len() + 1); |
| 1951 | assert_eq!( |
| 1952 | draft.take_edits(), |
| 1953 | [ |
| 1954 | (0..1, String::new()), |
| 1955 | (marker.len() + 1..marker.len() + 1, "x".to_owned()) |
| 1956 | ] |
| 1957 | ); |
| 1958 | } |
| 1959 | |
| 1960 | #[test] |
| 1961 | fn a_damaged_marker_turns_the_line_into_text() { |
| 1962 | let mut draft = Draft::from_markdown("- a"); |
| 1963 | draft.apply_edit("•a", 1, None); |
| 1964 | assert_eq!(draft.lines(), [LineKind::Text]); |
| 1965 | } |
| 1966 | |
| 1967 | #[test] |
| 1968 | fn fence_and_enter_open_a_code_block_that_enter_continues() { |
| 1969 | let mut draft = typed_draft("```rust"); |
| 1970 | let cursor = draft.break_line(draft.text().len(), false).unwrap(); |
| 1971 | assert_eq!((draft.text(), cursor), ("", 0)); |
| 1972 | assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]); |
| 1973 | typed(&mut draft, "fn x() {}"); |
| 1974 | let cursor = draft.break_line(draft.text().len(), false).unwrap(); |
| 1975 | assert_eq!(draft.lines().len(), 2); |
| 1976 | assert_eq!(draft.break_line(cursor, false), Some(cursor)); |
| 1977 | assert_eq!(draft.lines()[1], LineKind::Text); |
| 1978 | assert_eq!( |
| 1979 | draft.to_html(), |
| 1980 | "<pre class=\"language-rust\">fn x() {}</pre>" |
| 1981 | ); |
| 1982 | } |
| 1983 | |
| 1984 | #[test] |
| 1985 | fn markdown_inside_code_stays_literal() { |
| 1986 | let mut draft = typed_draft("```"); |
| 1987 | let cursor = draft.break_line(3, false).unwrap(); |
| 1988 | assert_eq!(cursor, 0); |
| 1989 | typed(&mut draft, "a **b**"); |
| 1990 | assert_eq!(draft.text(), "a **b**"); |
| 1991 | assert!(draft.marks().is_empty()); |
| 1992 | } |
| 1993 | |
| 1994 | #[test] |
| 1995 | fn html_nests_overlapping_marks_and_escapes() { |
| 1996 | let mut draft = Draft::plain("a<b & c"); |
| 1997 | draft.toggle(0..4, MarkKind::Bold); |
| 1998 | draft.toggle(2..7, MarkKind::Italic); |
| 1999 | assert_eq!(draft.to_html(), "<b>a<<i>b </i></b><i>& c</i>"); |
| 2000 | } |
| 2001 | |
| 2002 | #[test] |
| 2003 | fn html_covers_every_format() { |
| 2004 | let draft = Draft::from_markdown( |
| 2005 | "**b** *i* ~~s~~ `c` [l](https://x.test/?a=1&b=2)\n> q1\n> q2\n- a\n - b\n1. x\n2. y\n```py\nprint(1)\n```", |
| 2006 | ); |
| 2007 | let mut underlined = draft.clone(); |
| 2008 | underlined.toggle(0..1, MarkKind::Underline); |
| 2009 | assert_eq!( |
| 2010 | underlined.to_html(), |
| 2011 | "<b><u>b</u></b> <i>i</i> <s>s</s> <code>c</code> <a href=\"https://x.test/?a=1&b=2\">l</a>\ |
| 2012 | <blockquote>q1<br>q2</blockquote>\ |
| 2013 | <ul><li>a<ul><li>b</li></ul></li></ul>\ |
| 2014 | <ol><li>x</li><li>y</li></ol>\ |
| 2015 | <pre class=\"language-py\">print(1)</pre>" |
| 2016 | ); |
| 2017 | } |
| 2018 | |
| 2019 | #[test] |
| 2020 | fn ordered_lists_keep_their_start() { |
| 2021 | let draft = Draft::from_markdown("3. c\n4. d"); |
| 2022 | assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>"); |
| 2023 | } |
| 2024 | |
| 2025 | #[test] |
| 2026 | fn spans_round_trip_through_html() { |
| 2027 | let source = Draft::from_markdown( |
| 2028 | "hi **bold _both_** `c` [l](https://x.test)\n> quoted\n- a\n - b\n2. two\n3. three\n```rs\nlet x = 1;\n```\nend", |
| 2029 | ); |
| 2030 | let back = Draft::from_spans(&html_to_spans(&source.to_html())); |
| 2031 | assert_eq!(back.text(), source.text()); |
| 2032 | assert_eq!(back.lines(), source.lines()); |
| 2033 | assert_eq!(back.marks(), source.marks()); |
| 2034 | } |
| 2035 | |
| 2036 | #[test] |
| 2037 | fn mentions_from_html_come_back_as_at_text() { |
| 2038 | let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>")); |
| 2039 | assert_eq!(draft.text(), "hi @Ada now"); |
| 2040 | assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]); |
| 2041 | } |
| 2042 | |
| 2043 | #[test] |
| 2044 | fn pasted_markdown_is_detected() { |
| 2045 | assert!(has_markdown("see **this**")); |
| 2046 | assert!(has_markdown("- a\n- b")); |
| 2047 | assert!(has_markdown("```\nx\n```")); |
| 2048 | assert!(!has_markdown("plain text, 2*3=6 and snake_case")); |
| 2049 | } |
| 2050 | |
| 2051 | #[test] |
| 2052 | fn slices_carry_formatting_into_another_draft() { |
| 2053 | let source = Draft::from_markdown("intro **bold**\n- one\n- two"); |
| 2054 | let end = source.text().len(); |
| 2055 | let fragment = source.slice(6..end); |
| 2056 | assert_eq!(fragment[0].kind, LineKind::Text); |
| 2057 | assert_eq!(fragment[1].kind, LineKind::Bullet(0)); |
| 2058 | let mut target = Draft::plain("x "); |
| 2059 | let cursor = target.insert_lines(2..2, &fragment); |
| 2060 | assert_eq!(target.text(), "x bold\n• one\n• two"); |
| 2061 | assert_eq!(cursor, target.text().len()); |
| 2062 | assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]); |
| 2063 | assert_eq!( |
| 2064 | target.lines()[1..], |
| 2065 | [LineKind::Bullet(0), LineKind::Bullet(0)] |
| 2066 | ); |
| 2067 | } |
| 2068 | |
| 2069 | #[test] |
| 2070 | fn markdown_pasted_on_its_own_line_converts_from_the_first_line() { |
| 2071 | let raw = "- a\n- b"; |
| 2072 | let mut draft = Draft::plain(""); |
| 2073 | draft.apply_edit(raw, raw.len(), None); |
| 2074 | let lines = Draft::from_markdown(raw).slice(0..usize::MAX); |
| 2075 | let cursor = draft.insert_lines(0..raw.len(), &lines); |
| 2076 | assert_eq!(draft.text(), "• a\n• b"); |
| 2077 | assert_eq!(cursor, draft.text().len()); |
| 2078 | let mut inline = Draft::plain("x "); |
| 2079 | inline.apply_edit("x **b**", 7, None); |
| 2080 | let lines = Draft::from_markdown("**b**").slice(0..usize::MAX); |
| 2081 | inline.insert_lines(2..7, &lines); |
| 2082 | assert_eq!(inline.text(), "x b"); |
| 2083 | assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]); |
| 2084 | } |
| 2085 | |
| 2086 | #[test] |
| 2087 | fn a_paste_inside_a_line_puts_the_cursor_after_the_pasted_text() { |
| 2088 | let lines = Draft::from_markdown("**big**").slice(0..usize::MAX); |
| 2089 | let mut plain = Draft::plain("hello world"); |
| 2090 | assert_eq!(plain.insert_lines(6..6, &lines), 9); |
| 2091 | assert_eq!(plain.text(), "hello bigworld"); |
| 2092 | let mut item = Draft::from_markdown("- item one"); |
| 2093 | let before_one = bullet_marker(0).len() + "item ".len(); |
| 2094 | assert_eq!( |
| 2095 | item.insert_lines(before_one..before_one, &lines), |
| 2096 | before_one + 3 |
| 2097 | ); |
| 2098 | } |
| 2099 | |
| 2100 | #[test] |
| 2101 | fn a_selection_ending_at_the_next_line_start_leaves_that_line_alone() { |
| 2102 | let mut draft = Draft::plain("first\nsecond"); |
| 2103 | assert_eq!( |
| 2104 | draft.line_state(0..6, &LineKind::Bullet(0)), |
| 2105 | FormatState::Off |
| 2106 | ); |
| 2107 | draft.toggle_lines(0..6, LineKind::Bullet(0)); |
| 2108 | assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Text]); |
| 2109 | let end_of_first = draft.line_ranges()[1].start; |
| 2110 | assert_eq!( |
| 2111 | draft.line_state(0..end_of_first, &LineKind::Bullet(0)), |
| 2112 | FormatState::On |
| 2113 | ); |
| 2114 | assert!(draft.indent(0..end_of_first, false)); |
| 2115 | assert_eq!(draft.lines()[1], LineKind::Text); |
| 2116 | } |
| 2117 | |
| 2118 | #[test] |
| 2119 | fn links_only_take_http_https_and_mailto() { |
| 2120 | assert_eq!(link_url("example.com"), Some("https://example.com".into())); |
| 2121 | assert_eq!(link_url("mailto:a@b.test"), Some("mailto:a@b.test".into())); |
| 2122 | assert_eq!(link_url("javascript:alert(1)"), None); |
| 2123 | assert_eq!(link_url("data:text/html,x"), None); |
| 2124 | let typed = typed_draft("[x](javascript:alert)"); |
| 2125 | assert!(typed.marks().is_empty()); |
| 2126 | let pasted = Draft::from_markdown("[x](javascript:alert) [y](example.com)"); |
| 2127 | assert_eq!( |
| 2128 | pasted.marks(), |
| 2129 | [mark(22..23, MarkKind::Link("https://example.com".into()))] |
| 2130 | ); |
| 2131 | let mut set = Draft::plain("go"); |
| 2132 | set.set_link(0..2, "javascript:alert(1)"); |
| 2133 | assert!(set.marks().is_empty()); |
| 2134 | let spans = Draft::from_spans(&html_to_spans("<a href=\"javascript:x\">bad</a>")); |
| 2135 | assert!(spans.marks().is_empty()); |
| 2136 | } |
| 2137 | |
| 2138 | #[test] |
| 2139 | fn code_lines_hold_only_their_content() { |
| 2140 | let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```"); |
| 2141 | assert_eq!(draft.text(), "let a = 1;\n\u{2003}b"); |
| 2142 | assert_eq!(draft.to_html(), "<pre>let a = 1;\n\u{2003}b</pre>"); |
| 2143 | assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None); |
| 2144 | assert_eq!(draft.backspace_at_start(0), Some(0)); |
| 2145 | assert_eq!(draft.lines()[0], LineKind::Text); |
| 2146 | } |
| 2147 | |
| 2148 | #[test] |
| 2149 | fn in_code_covers_code_lines_and_the_inside_of_inline_code() { |
| 2150 | let draft = Draft::from_markdown("a `cd` e\n```\nx\n```"); |
| 2151 | assert!(!draft.in_code(2)); |
| 2152 | assert!(draft.in_code(3)); |
| 2153 | assert!(!draft.in_code(4)); |
| 2154 | assert!(draft.in_code(draft.text().len())); |
| 2155 | } |
| 2156 | |
| 2157 | #[test] |
| 2158 | fn code_indentation_is_kept_on_paste_split_and_send() { |
| 2159 | let mut draft = typed_draft("```py"); |
| 2160 | let cursor = draft.break_line(draft.text().len(), false).unwrap(); |
| 2161 | let pasted = "def f():\n return 1"; |
| 2162 | let mut next = draft.text().to_owned(); |
| 2163 | next.insert_str(cursor, pasted); |
| 2164 | draft.apply_edit(&next, cursor + pasted.len(), None); |
| 2165 | assert_eq!( |
| 2166 | draft.to_html(), |
| 2167 | "<pre class=\"language-py\">def f():\n return 1</pre>" |
| 2168 | ); |
| 2169 | let mut split = Draft::from_markdown("```\n a b\n```"); |
| 2170 | let after_a = " a".len(); |
| 2171 | split.break_line(after_a, false).unwrap(); |
| 2172 | assert_eq!(split.to_html(), "<pre> a\n b</pre>"); |
| 2173 | } |
| 2174 | |
| 2175 | #[test] |
| 2176 | fn delete_at_a_line_end_joins_the_next_item_without_its_bullet() { |
| 2177 | let mut draft = Draft::from_markdown("- a\n- b"); |
| 2178 | let end_of_first = draft.line_ranges()[0].end; |
| 2179 | assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first)); |
| 2180 | assert_eq!(draft.text(), "• ab"); |
| 2181 | assert_eq!(draft.delete_forward(0), Some(bullet_marker(0).len())); |
| 2182 | assert_eq!(draft.text(), "• b"); |
| 2183 | assert_eq!(Draft::plain("a\nb").delete_forward(1), None); |
| 2184 | } |
| 2185 | |
| 2186 | #[test] |
| 2187 | fn host_and_port_links_are_schemeless() { |
| 2188 | assert_eq!( |
| 2189 | link_url("localhost:3000"), |
| 2190 | Some("https://localhost:3000".into()) |
| 2191 | ); |
| 2192 | assert_eq!( |
| 2193 | link_url("example.com:8080/x"), |
| 2194 | Some("https://example.com:8080/x".into()) |
| 2195 | ); |
| 2196 | assert_eq!(link_url("javascript:alert(1)"), None); |
| 2197 | assert_eq!(link_url("tel:0123456"), None); |
| 2198 | } |
| 2199 | |
| 2200 | #[test] |
| 2201 | fn a_quote_stays_a_quote_when_split_or_joined() { |
| 2202 | let mut draft = Draft::from_markdown("> a\n> b"); |
| 2203 | let second = draft.line_ranges()[1].start; |
| 2204 | assert_eq!(draft.break_line(second, true), Some(second + 1)); |
| 2205 | assert_eq!( |
| 2206 | draft.lines(), |
| 2207 | [LineKind::Quote, LineKind::Quote, LineKind::Quote] |
| 2208 | ); |
| 2209 | let mut joined = Draft::from_markdown("> a\n> b"); |
| 2210 | let second = joined.line_ranges()[1].start; |
| 2211 | assert_eq!(joined.backspace_at_start(second), Some(second - 1)); |
| 2212 | assert_eq!( |
| 2213 | (joined.text(), joined.lines()), |
| 2214 | ("ab", &[LineKind::Quote][..]) |
| 2215 | ); |
| 2216 | assert_eq!(joined.backspace_at_start(0), Some(0)); |
| 2217 | assert_eq!(joined.lines(), [LineKind::Text]); |
| 2218 | } |
| 2219 | |
| 2220 | #[test] |
| 2221 | fn journal_merges_edits_into_ranges_of_the_old_text() { |
| 2222 | let mut draft = Draft::plain("a **b** c"); |
| 2223 | draft.splice(5..7, "", &[]); |
| 2224 | draft.splice(2..4, "", &[]); |
| 2225 | draft.splice(0..0, "X", &[]); |
| 2226 | let edits = draft.take_edits(); |
| 2227 | assert_eq!( |
| 2228 | edits, |
| 2229 | [ |
| 2230 | (0..0, "X".to_owned()), |
| 2231 | (2..4, String::new()), |
| 2232 | (5..7, String::new()) |
| 2233 | ] |
| 2234 | ); |
| 2235 | assert_eq!( |
| 2236 | reverse_edits(&edits, "a **b** c")[1], |
| 2237 | (3..3, "**".to_owned()) |
| 2238 | ); |
| 2239 | let mut touching = Draft::plain("abc"); |
| 2240 | touching.splice(1..2, "XY", &[]); |
| 2241 | touching.splice(3..3, "Z", &[]); |
| 2242 | assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]); |
| 2243 | } |
| 2244 | |
| 2245 | #[test] |
| 2246 | fn trimming_drops_blank_lines_and_outer_spaces() { |
| 2247 | let mut draft = Draft::plain("\n hi **x** \n\n"); |
| 2248 | draft.toggle(6..11, MarkKind::Bold); |
| 2249 | let trimmed = draft.trimmed(); |
| 2250 | assert_eq!(trimmed.text(), "hi **x**"); |
| 2251 | assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]); |
| 2252 | } |
| 2253 | |
| 2254 | #[test] |
| 2255 | fn toolbar_line_toggles_apply_to_every_selected_line() { |
| 2256 | let mut draft = Draft::plain("a\nb"); |
| 2257 | draft.toggle_lines(0..3, LineKind::Numbered(0)); |
| 2258 | assert_eq!(draft.text(), "1. a\n2. b"); |
| 2259 | assert_eq!( |
| 2260 | draft.line_state(0..4, &LineKind::Numbered(0)), |
| 2261 | FormatState::On |
| 2262 | ); |
| 2263 | draft.toggle_lines(0..9, LineKind::Bullet(0)); |
| 2264 | assert_eq!(draft.text(), "• a\n• b"); |
| 2265 | let end = draft.text().len(); |
| 2266 | draft.toggle_lines(0..end, LineKind::Bullet(0)); |
| 2267 | assert_eq!(draft.text(), "a\nb"); |
| 2268 | } |
| 2269 | |
| 2270 | #[test] |
| 2271 | fn links_are_set_replaced_and_removed() { |
| 2272 | let mut draft = Draft::plain("go here"); |
| 2273 | draft.set_link(3..7, "https://a.test"); |
| 2274 | assert_eq!(draft.link_in(4..4), Some("https://a.test".into())); |
| 2275 | draft.set_link(3..7, ""); |
| 2276 | assert!(draft.marks().is_empty()); |
| 2277 | let end = draft.insert_link(7, " https://b.test", "https://b.test"); |
| 2278 | assert_eq!(end, draft.text().len()); |
| 2279 | } |
| 2280 | } |