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