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