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