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