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