| 1 | use std::{collections::BTreeMap, ops::Range, sync::Arc}; |
| 2 | |
| 3 | use gpui::SharedString; |
| 4 | use markdown::{ |
| 5 | ParseOptions, |
| 6 | mdast::{self, Node}, |
| 7 | unist::Point, |
| 8 | }; |
| 9 | |
| 10 | use crate::text::{ |
| 11 | document::ParsedDocument, |
| 12 | markdown_ext::MarkdownParseContext, |
| 13 | node::{ |
| 14 | self, BlockNode, CodeBlock, ImageNode, InlineNode, LinkMark, NodeContext, Paragraph, |
| 15 | SourceSegment, Span, Table, TableRow, TextMark, |
| 16 | }, |
| 17 | }; |
| 18 | |
| 19 | /// Parse Markdown into a tree of nodes. |
| 20 | pub(crate) fn parse(source: &str, cx: &mut NodeContext) -> Result<ParsedDocument, SharedString> { |
| 21 | let options = cx.markdown_extensions.parse_options(); |
| 22 | let mut root = |
| 23 | markdown::to_mdast(source, &options).map_err(|e| SharedString::from(e.to_string()))?; |
| 24 | let mut prose = options; |
| 25 | prose.constructs.math_text = false; |
| 26 | prose.constructs.math_flow = false; |
| 27 | flatten_unclaimed_math(&mut root, source, &prose, cx); |
| 28 | Ok(ast_to_document(source, root, cx)) |
| 29 | } |
| 30 | |
| 31 | /// Math parsing is on by default, so prose that merely contains two dollar |
| 32 | /// signs ("$5 and $10") parses as an inline math node. When no plugin claims |
| 33 | /// such a node, the text between the dollars must stay ordinary Markdown: |
| 34 | /// emphasis, inline HTML and links inside it render as they would anywhere |
| 35 | /// else, and inline HTML tags may pair with tags outside the span. Re-parse |
| 36 | /// the node's source without the math constructs and, when it holds any |
| 37 | /// markup, splice the result into its parent with positions shifted back into |
| 38 | /// the document. Plain prose keeps the literal node, whose atomic source |
| 39 | /// mapping the selection tests rely on. |
| 40 | fn flatten_unclaimed_math(node: &mut Node, source: &str, options: &ParseOptions, cx: &NodeContext) { |
| 41 | let Some(children) = node.children_mut() else { |
| 42 | return; |
| 43 | }; |
| 44 | let mut ix = 0; |
| 45 | while ix < children.len() { |
| 46 | let prose = match &children[ix] { |
| 47 | Node::InlineMath(_) => { |
| 48 | let parse_cx = MarkdownParseContext::new(source, cx.offset); |
| 49 | if cx |
| 50 | .markdown_extensions |
| 51 | .parse_inline(&children[ix], &parse_cx) |
| 52 | .is_some() |
| 53 | { |
| 54 | None |
| 55 | } else { |
| 56 | reparse_as_prose(&children[ix], source, options) |
| 57 | } |
| 58 | } |
| 59 | _ => None, |
| 60 | }; |
| 61 | if let Some(prose) = prose { |
| 62 | let count = prose.len(); |
| 63 | children.splice(ix..=ix, prose); |
| 64 | ix += count; |
| 65 | continue; |
| 66 | } |
| 67 | flatten_unclaimed_math(&mut children[ix], source, options, cx); |
| 68 | ix += 1; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn reparse_as_prose(node: &Node, source: &str, options: &ParseOptions) -> Option<Vec<Node>> { |
| 73 | let position = node.position()?.clone(); |
| 74 | let literal = source.get(position.start.offset..position.end.offset)?; |
| 75 | if !may_hold_inline_markup(literal) { |
| 76 | return None; |
| 77 | } |
| 78 | let Ok(Node::Root(mut root)) = markdown::to_mdast(literal, options) else { |
| 79 | return None; |
| 80 | }; |
| 81 | let [Node::Paragraph(paragraph)] = root.children.as_mut_slice() else { |
| 82 | return None; |
| 83 | }; |
| 84 | if paragraph |
| 85 | .children |
| 86 | .iter() |
| 87 | .all(|child| matches!(child, Node::Text(_))) |
| 88 | { |
| 89 | return None; |
| 90 | } |
| 91 | let mut children = std::mem::take(&mut paragraph.children); |
| 92 | for child in &mut children { |
| 93 | shift_positions(child, &position.start); |
| 94 | } |
| 95 | Some(children) |
| 96 | } |
| 97 | |
| 98 | /// A cheap gate before re-parsing: every inline construct starts with one of |
| 99 | /// these bytes (tags, emphasis, code, links, images, escapes, entities, |
| 100 | /// strikethrough) or is a GFM autolink literal. |
| 101 | fn may_hold_inline_markup(literal: &str) -> bool { |
| 102 | literal.bytes().any(|byte| { |
| 103 | matches!( |
| 104 | byte, |
| 105 | b'<' | b'*' | b'_' | b'[' | b'`' | b'~' | b'\\' | b'!' | b'&' |
| 106 | ) |
| 107 | }) || literal.contains("://") |
| 108 | || literal.contains("www.") |
| 109 | } |
| 110 | |
| 111 | fn shift_positions(node: &mut Node, origin: &Point) { |
| 112 | if let Some(position) = node.position_mut() { |
| 113 | for point in [&mut position.start, &mut position.end] { |
| 114 | let first_line = point.line == 1; |
| 115 | point.offset += origin.offset; |
| 116 | point.line += origin.line - 1; |
| 117 | if first_line { |
| 118 | point.column += origin.column - 1; |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | if let Some(children) = node.children_mut() { |
| 123 | for child in children { |
| 124 | shift_positions(child, origin); |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | enum InlineGroup<'a> { |
| 130 | Node(&'a Node), |
| 131 | Marked(TextMark, &'a [Node]), |
| 132 | } |
| 133 | |
| 134 | /// CommonMark hands each raw inline tag over as its own `Html` node, so |
| 135 | /// `<strong>x</strong>` arrives as three siblings and the tags alone carry no |
| 136 | /// text. Pair the formatting tags this renderer knows with their closing tag |
| 137 | /// among the siblings and treat what lies between as a marked run, the same |
| 138 | /// way `**x**` is handled. |
| 139 | fn inline_groups(children: &[Node]) -> Vec<InlineGroup<'_>> { |
| 140 | let mut groups = Vec::with_capacity(children.len()); |
| 141 | let mut ix = 0; |
| 142 | while ix < children.len() { |
| 143 | if let Some((false, name)) = inline_html_tag(&children[ix]) |
| 144 | && let Some(mark) = inline_html_mark(&name) |
| 145 | && let Some(close) = matching_close_tag(children, ix, &name) |
| 146 | { |
| 147 | groups.push(InlineGroup::Marked(mark, &children[ix + 1..close])); |
| 148 | ix = close + 1; |
| 149 | continue; |
| 150 | } |
| 151 | groups.push(InlineGroup::Node(&children[ix])); |
| 152 | ix += 1; |
| 153 | } |
| 154 | groups |
| 155 | } |
| 156 | |
| 157 | fn inline_html_tag(node: &Node) -> Option<(bool, String)> { |
| 158 | let Node::Html(html) = node else { |
| 159 | return None; |
| 160 | }; |
| 161 | let inner = html.value.trim().strip_prefix('<')?.strip_suffix('>')?; |
| 162 | if inner.ends_with('/') { |
| 163 | return None; |
| 164 | } |
| 165 | let (closing, rest) = match inner.strip_prefix('/') { |
| 166 | Some(rest) => (true, rest), |
| 167 | None => (false, inner), |
| 168 | }; |
| 169 | let name = rest |
| 170 | .chars() |
| 171 | .take_while(char::is_ascii_alphanumeric) |
| 172 | .collect::<String>() |
| 173 | .to_ascii_lowercase(); |
| 174 | (!name.is_empty()).then_some((closing, name)) |
| 175 | } |
| 176 | |
| 177 | fn inline_html_mark(name: &str) -> Option<TextMark> { |
| 178 | Some(match name { |
| 179 | "strong" | "b" => TextMark::default().bold(), |
| 180 | "em" | "i" => TextMark::default().italic(), |
| 181 | "u" => TextMark::default().underline(), |
| 182 | "s" | "del" | "strike" => TextMark::default().strikethrough(), |
| 183 | _ => return None, |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | fn matching_close_tag(children: &[Node], open: usize, name: &str) -> Option<usize> { |
| 188 | let mut depth = 0usize; |
| 189 | for (ix, child) in children.iter().enumerate().skip(open + 1) { |
| 190 | match inline_html_tag(child) { |
| 191 | Some((false, tag)) if tag == name => depth += 1, |
| 192 | Some((true, tag)) if tag == name => { |
| 193 | if depth == 0 { |
| 194 | return Some(ix); |
| 195 | } |
| 196 | depth -= 1; |
| 197 | } |
| 198 | _ => {} |
| 199 | } |
| 200 | } |
| 201 | None |
| 202 | } |
| 203 | |
| 204 | fn parse_inline_children( |
| 205 | source: &str, |
| 206 | paragraph: &mut Paragraph, |
| 207 | children: &[Node], |
| 208 | cx: &mut NodeContext, |
| 209 | ) -> String { |
| 210 | let mut text = String::new(); |
| 211 | for group in inline_groups(children) { |
| 212 | match group { |
| 213 | InlineGroup::Node(child) => { |
| 214 | text.push_str(&parse_paragraph(source, paragraph, child, cx)); |
| 215 | } |
| 216 | InlineGroup::Marked(mark, nodes) => { |
| 217 | text.push_str(&merge_children_with_mark( |
| 218 | source, paragraph, nodes, mark, cx, |
| 219 | )); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | text |
| 224 | } |
| 225 | |
| 226 | fn parse_table_row(source: &str, table: &mut Table, node: &mdast::TableRow, cx: &mut NodeContext) { |
| 227 | let mut row = TableRow::default(); |
| 228 | node.children.iter().for_each(|c| { |
| 229 | match c { |
| 230 | Node::TableCell(cell) => { |
| 231 | parse_table_cell(source, &mut row, cell, cx); |
| 232 | } |
| 233 | _ => {} |
| 234 | }; |
| 235 | }); |
| 236 | // GFM fixes the column count with the header/delimiter, not each body row. |
| 237 | // Padding/truncation keeps every row on the same measured column grid. |
| 238 | row.children |
| 239 | .resize_with(table.column_aligns.len(), Default::default); |
| 240 | table.children.push(row); |
| 241 | } |
| 242 | |
| 243 | fn parse_table_cell( |
| 244 | source: &str, |
| 245 | row: &mut node::TableRow, |
| 246 | node: &mdast::TableCell, |
| 247 | cx: &mut NodeContext, |
| 248 | ) { |
| 249 | let mut paragraph = Paragraph::default(); |
| 250 | parse_inline_children(source, &mut paragraph, &node.children, cx); |
| 251 | let table_cell = node::TableCell { |
| 252 | children: paragraph, |
| 253 | ..Default::default() |
| 254 | }; |
| 255 | row.children.push(table_cell); |
| 256 | } |
| 257 | |
| 258 | /// Push a text run with its existing `marks` plus `new_mark` across the full |
| 259 | /// run. |
| 260 | /// |
| 261 | /// If the last mark already covers the full run, merge into it. Otherwise add a |
| 262 | /// new full-run mark. Empty runs are skipped so callers can flush freely. |
| 263 | fn push_merged( |
| 264 | paragraph: &mut Paragraph, |
| 265 | text: String, |
| 266 | marks: Vec<(Range<usize>, TextMark)>, |
| 267 | source_segments: Vec<SourceSegment>, |
| 268 | new_mark: TextMark, |
| 269 | ) { |
| 270 | if text.is_empty() { |
| 271 | return; |
| 272 | } |
| 273 | |
| 274 | let mut node = InlineNode::new(text) |
| 275 | .marks(marks) |
| 276 | .source_segments(source_segments); |
| 277 | let len = node.text.len(); |
| 278 | if let Some(last) = node.marks.last_mut() |
| 279 | && last.0.start == 0 |
| 280 | && last.0.end == len |
| 281 | { |
| 282 | last.1.merge(new_mark); |
| 283 | } else { |
| 284 | node.marks.push((0..len, new_mark)); |
| 285 | } |
| 286 | paragraph.push(node); |
| 287 | } |
| 288 | |
| 289 | /// Parse `children` and apply `mark` across each emitted text run. |
| 290 | /// |
| 291 | /// Nested child marks are kept and shifted to match the combined text for the |
| 292 | /// current run, which lets nested emphasis like `**_x_**` render as both bold |
| 293 | /// and italic. Inline images split the run and are emitted as sibling image |
| 294 | /// nodes. The return value is the plain text from all children, for callers that |
| 295 | /// need to pass text back to their parent node. |
| 296 | fn merge_children_with_mark( |
| 297 | source: &str, |
| 298 | paragraph: &mut Paragraph, |
| 299 | children: &[mdast::Node], |
| 300 | mark: TextMark, |
| 301 | cx: &mut NodeContext, |
| 302 | ) -> String { |
| 303 | let mut text = String::new(); |
| 304 | let mut merged_text = String::new(); |
| 305 | let mut merged_marks = Vec::new(); |
| 306 | let mut merged_source_segments = Vec::new(); |
| 307 | |
| 308 | for group in inline_groups(children) { |
| 309 | let mut child_paragraph = Paragraph::default(); |
| 310 | let child_text = match group { |
| 311 | InlineGroup::Node(child) => parse_paragraph(source, &mut child_paragraph, child, cx), |
| 312 | InlineGroup::Marked(child_mark, nodes) => { |
| 313 | merge_children_with_mark(source, &mut child_paragraph, nodes, child_mark, cx) |
| 314 | } |
| 315 | }; |
| 316 | text.push_str(&child_text); |
| 317 | |
| 318 | for mut node in child_paragraph.children { |
| 319 | if node.custom.is_some() { |
| 320 | push_merged( |
| 321 | paragraph, |
| 322 | std::mem::take(&mut merged_text), |
| 323 | std::mem::take(&mut merged_marks), |
| 324 | std::mem::take(&mut merged_source_segments), |
| 325 | mark.clone(), |
| 326 | ); |
| 327 | if let Some((_, existing)) = node.marks.first_mut() { |
| 328 | existing.merge(mark.clone()); |
| 329 | } else { |
| 330 | node.marks.push((0..node.text.len(), mark.clone())); |
| 331 | } |
| 332 | paragraph.push(node); |
| 333 | continue; |
| 334 | } |
| 335 | let merged_offset = merged_text.len(); |
| 336 | merged_text.push_str(&node.text); |
| 337 | merged_source_segments.extend(node.source_segments.drain(..).map(|mut segment| { |
| 338 | segment.rendered.start += merged_offset; |
| 339 | segment.rendered.end += merged_offset; |
| 340 | segment |
| 341 | })); |
| 342 | |
| 343 | for (range, child_mark) in node.marks { |
| 344 | merged_marks.push(( |
| 345 | range.start + merged_offset..range.end + merged_offset, |
| 346 | child_mark, |
| 347 | )); |
| 348 | } |
| 349 | |
| 350 | if let Some(mut image) = node.image { |
| 351 | if let Some(link_mark) = mark.link.clone() { |
| 352 | image.link = Some(link_mark); |
| 353 | } |
| 354 | |
| 355 | // GPUI InteractiveText does not support inline images, so |
| 356 | // flush the accumulated text run and emit the image as its |
| 357 | // own sibling InlineNode. |
| 358 | push_merged( |
| 359 | paragraph, |
| 360 | std::mem::take(&mut merged_text), |
| 361 | std::mem::take(&mut merged_marks), |
| 362 | std::mem::take(&mut merged_source_segments), |
| 363 | mark.clone(), |
| 364 | ); |
| 365 | paragraph.push(InlineNode::image(image)); |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | push_merged( |
| 371 | paragraph, |
| 372 | merged_text, |
| 373 | merged_marks, |
| 374 | merged_source_segments, |
| 375 | mark, |
| 376 | ); |
| 377 | text |
| 378 | } |
| 379 | |
| 380 | fn source_segments( |
| 381 | source: &str, |
| 382 | rendered: &str, |
| 383 | span: Option<Span>, |
| 384 | source_offset: usize, |
| 385 | include_preceding_escape: bool, |
| 386 | ) -> Vec<SourceSegment> { |
| 387 | let Some(span) = span else { |
| 388 | return Vec::new(); |
| 389 | }; |
| 390 | let local_start = span.start.saturating_sub(source_offset); |
| 391 | let local_end = span.end.saturating_sub(source_offset); |
| 392 | let Some(raw) = source.get(local_start..local_end) else { |
| 393 | return Vec::new(); |
| 394 | }; |
| 395 | |
| 396 | let mut segments = aligned_source_segments(raw, rendered, span.start, true, true); |
| 397 | |
| 398 | // The text node of an escaped character starts after its backslash. The |
| 399 | // backslash and the character map as a whole; the rest of the run stays |
| 400 | // linear. |
| 401 | if include_preceding_escape |
| 402 | && let Some(previous) = local_start.checked_sub(1) |
| 403 | && source.as_bytes().get(previous) == Some(&b'\\') |
| 404 | && let Some(first) = segments.first_mut() |
| 405 | { |
| 406 | let first_char_len = rendered[first.rendered.start..] |
| 407 | .chars() |
| 408 | .next() |
| 409 | .map_or(0, char::len_utf8); |
| 410 | if first.linear && first.rendered.len() > first_char_len { |
| 411 | let rest = SourceSegment { |
| 412 | rendered: first.rendered.start + first_char_len..first.rendered.end, |
| 413 | source: first.source.start + first_char_len..first.source.end, |
| 414 | linear: true, |
| 415 | }; |
| 416 | first.rendered.end = rest.rendered.start; |
| 417 | first.source.end = rest.source.start; |
| 418 | segments.insert(1, rest); |
| 419 | } |
| 420 | let first = &mut segments[0]; |
| 421 | first.source.start -= 1; |
| 422 | first.linear = false; |
| 423 | } |
| 424 | segments |
| 425 | } |
| 426 | |
| 427 | fn aligned_source_segments( |
| 428 | raw: &str, |
| 429 | rendered: &str, |
| 430 | source_offset: usize, |
| 431 | decode_entities: bool, |
| 432 | decode_escapes: bool, |
| 433 | ) -> Vec<SourceSegment> { |
| 434 | let mut segments = Vec::new(); |
| 435 | let mut raw_cursor = 0; |
| 436 | let mut rendered_start = 0; |
| 437 | let mut whitespace_end = 0; |
| 438 | let mut source_positions = None; |
| 439 | let mut entity_cursor = None; |
| 440 | let mut entity = None; |
| 441 | // Only the final LF may absorb source-only text before it. Find the |
| 442 | // preceding line boundary once instead of recounting the suffix per LF. |
| 443 | let final_line_start = raw |
| 444 | .strip_suffix('\n') |
| 445 | .and_then(|prefix| prefix.rfind('\n')) |
| 446 | .map_or(0, |newline| newline + 1); |
| 447 | |
| 448 | while rendered_start < rendered.len() { |
| 449 | if decode_entities && entity_cursor != Some(raw_cursor) { |
| 450 | entity = decoded_entity(&raw[raw_cursor..]); |
| 451 | entity_cursor = Some(raw_cursor); |
| 452 | } |
| 453 | if let Some((decoded, source_len)) = &entity |
| 454 | && rendered[rendered_start..].starts_with(decoded.as_str()) |
| 455 | { |
| 456 | let rendered_end = rendered_start + decoded.len(); |
| 457 | push_source_segment( |
| 458 | &mut segments, |
| 459 | SourceSegment { |
| 460 | rendered: rendered_start..rendered_end, |
| 461 | source: (source_offset + raw_cursor) |
| 462 | ..(source_offset + raw_cursor + *source_len), |
| 463 | // Even when the decoded characters take as many bytes as the |
| 464 | // entity, as `∾̳` and `∾̳` do, they are not one for one. |
| 465 | linear: false, |
| 466 | }, |
| 467 | ); |
| 468 | rendered_start = rendered_end; |
| 469 | raw_cursor += *source_len; |
| 470 | continue; |
| 471 | } |
| 472 | |
| 473 | let rendered_char = rendered[rendered_start..] |
| 474 | .chars() |
| 475 | .next() |
| 476 | .expect("rendered cursor must be on a character boundary"); |
| 477 | let rendered_end = rendered_start + rendered_char.len_utf8(); |
| 478 | let remainder = &raw[raw_cursor..]; |
| 479 | if rendered_char == ' ' && raw_cursor >= whitespace_end { |
| 480 | // Reuse this boundary while consuming a run of literal spaces. |
| 481 | // Otherwise a long horizontal-whitespace run also costs O(n^2). |
| 482 | whitespace_end = raw_cursor |
| 483 | + remainder |
| 484 | .bytes() |
| 485 | .position(|byte| !matches!(byte, b' ' | b'\t')) |
| 486 | .unwrap_or(remainder.len()); |
| 487 | } |
| 488 | let (relative_start, source_len) = if rendered_char == ' ' |
| 489 | && matches!(raw.as_bytes().get(whitespace_end), Some(b'\n' | b'\r')) |
| 490 | { |
| 491 | let newline_len = if raw[whitespace_end..].starts_with("\r\n") { |
| 492 | 2 |
| 493 | } else { |
| 494 | 1 |
| 495 | }; |
| 496 | (whitespace_end - raw_cursor, newline_len) |
| 497 | } else if rendered_char == '\n' |
| 498 | && remainder.ends_with('\n') |
| 499 | && raw_cursor >= final_line_start |
| 500 | { |
| 501 | (0, remainder.len()) |
| 502 | } else if decode_escapes |
| 503 | && let Some(escaped) = remainder.strip_prefix('\\') |
| 504 | && escaped.starts_with(rendered_char) |
| 505 | { |
| 506 | (0, 1 + rendered_char.len_utf8()) |
| 507 | } else if remainder.starts_with(rendered_char) { |
| 508 | (0, rendered_char.len_utf8()) |
| 509 | } else if let Some(source_start) = |
| 510 | source_char_offset(raw, raw_cursor, rendered_char, &mut source_positions) |
| 511 | { |
| 512 | (source_start - raw_cursor, rendered_char.len_utf8()) |
| 513 | } else { |
| 514 | // Decoded entities and other source-only syntax have no exact |
| 515 | // rendered-byte mapping. Leave a rendered gap for this |
| 516 | // character, but keep aligning later characters in the node. |
| 517 | rendered_start = rendered_end; |
| 518 | continue; |
| 519 | }; |
| 520 | let source_start = raw_cursor + relative_start; |
| 521 | let source_end = source_start + source_len; |
| 522 | push_source_segment( |
| 523 | &mut segments, |
| 524 | SourceSegment { |
| 525 | rendered: rendered_start..rendered_end, |
| 526 | source: (source_offset + source_start)..(source_offset + source_end), |
| 527 | linear: source_len == rendered_char.len_utf8(), |
| 528 | }, |
| 529 | ); |
| 530 | raw_cursor = source_end; |
| 531 | rendered_start = rendered_end; |
| 532 | } |
| 533 | segments |
| 534 | } |
| 535 | |
| 536 | fn source_char_offset( |
| 537 | raw: &str, |
| 538 | raw_cursor: usize, |
| 539 | character: char, |
| 540 | positions: &mut Option<BTreeMap<char, Vec<usize>>>, |
| 541 | ) -> Option<usize> { |
| 542 | if let Some(positions) = positions.as_ref() { |
| 543 | let offsets = positions.get(&character)?; |
| 544 | return offsets |
| 545 | .get(offsets.partition_point(|&offset| offset < raw_cursor)) |
| 546 | .copied(); |
| 547 | } |
| 548 | if let Some(offset) = raw[raw_cursor..].find(character) { |
| 549 | return Some(raw_cursor + offset); |
| 550 | } |
| 551 | |
| 552 | // Successful searches advance raw_cursor, so their scans do not overlap. |
| 553 | // A missing character does not advance it. Index the remaining source only |
| 554 | // after the first miss so later gaps cannot repeatedly scan that suffix. |
| 555 | let mut indexed = BTreeMap::<char, Vec<usize>>::new(); |
| 556 | for (offset, character) in raw[raw_cursor..].char_indices() { |
| 557 | indexed |
| 558 | .entry(character) |
| 559 | .or_default() |
| 560 | .push(raw_cursor + offset); |
| 561 | } |
| 562 | *positions = Some(indexed); |
| 563 | None |
| 564 | } |
| 565 | |
| 566 | /// Pushes `segment`, merging it into the previous one when both are linear and |
| 567 | /// adjacent, so that a merged run still maps byte for byte. Any other segment |
| 568 | /// is kept whole on its own. |
| 569 | fn push_source_segment(segments: &mut Vec<SourceSegment>, segment: SourceSegment) { |
| 570 | if let Some(previous) = segments.last_mut() |
| 571 | && previous.linear |
| 572 | && segment.linear |
| 573 | && previous.rendered.end == segment.rendered.start |
| 574 | && previous.source.end == segment.source.start |
| 575 | { |
| 576 | previous.rendered.end = segment.rendered.end; |
| 577 | previous.source.end = segment.source.end; |
| 578 | } else { |
| 579 | segments.push(segment); |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | fn decoded_entity(source: &str) -> Option<(String, usize)> { |
| 584 | let candidate = source.strip_prefix('&')?; |
| 585 | let candidate_end = candidate |
| 586 | .bytes() |
| 587 | .position(|byte| byte == b';' || !(byte.is_ascii_alphanumeric() || byte == b'#'))?; |
| 588 | if candidate.as_bytes()[candidate_end] != b';' { |
| 589 | return None; |
| 590 | } |
| 591 | let semicolon = candidate_end + 1; |
| 592 | let name = &source[1..=semicolon]; |
| 593 | let decoded = if let Some(number) = name.strip_prefix("#x").or_else(|| name.strip_prefix("#X")) |
| 594 | { |
| 595 | char::from_u32(u32::from_str_radix(number.strip_suffix(';')?, 16).ok()?)?.to_string() |
| 596 | } else if let Some(number) = name.strip_prefix('#') { |
| 597 | char::from_u32(number.strip_suffix(';')?.parse().ok()?)?.to_string() |
| 598 | } else { |
| 599 | let &(first, second) = html5ever::data::NAMED_ENTITIES.get(name)?; |
| 600 | let mut decoded = char::from_u32(first)?.to_string(); |
| 601 | if second != 0 { |
| 602 | decoded.push(char::from_u32(second)?); |
| 603 | } |
| 604 | decoded |
| 605 | }; |
| 606 | Some((decoded, semicolon + 1)) |
| 607 | } |
| 608 | |
| 609 | fn code_source_segments( |
| 610 | source: &str, |
| 611 | code: &str, |
| 612 | span: Option<Span>, |
| 613 | source_offset: usize, |
| 614 | ) -> Vec<SourceSegment> { |
| 615 | let Some(span) = span else { |
| 616 | return Vec::new(); |
| 617 | }; |
| 618 | let Some(raw) = source |
| 619 | .get(span.start.saturating_sub(source_offset)..span.end.saturating_sub(source_offset)) |
| 620 | else { |
| 621 | return Vec::new(); |
| 622 | }; |
| 623 | let trimmed = raw.trim_start(); |
| 624 | let fence = trimmed |
| 625 | .chars() |
| 626 | .next() |
| 627 | .filter(|character| matches!(character, '`' | '~')) |
| 628 | .map(|character| { |
| 629 | let len = trimmed |
| 630 | .chars() |
| 631 | .take_while(|candidate| candidate == &character) |
| 632 | .count(); |
| 633 | (character, len) |
| 634 | }) |
| 635 | .filter(|(_, len)| *len >= 3); |
| 636 | let (body_start, body_end) = if let Some((fence, fence_len)) = fence { |
| 637 | let start = raw.find('\n').map_or(raw.len(), |newline| newline + 1); |
| 638 | let last_line = raw.rfind('\n').map_or(start, |newline| newline + 1); |
| 639 | let closing = raw[last_line..].trim(); |
| 640 | let is_closing = closing.chars().count() >= fence_len |
| 641 | && closing.chars().all(|character| character == fence); |
| 642 | (start, if is_closing { last_line } else { raw.len() }) |
| 643 | } else { |
| 644 | (0, raw.len()) |
| 645 | }; |
| 646 | |
| 647 | aligned_source_segments( |
| 648 | &raw[body_start..body_end], |
| 649 | code, |
| 650 | span.start + body_start, |
| 651 | false, |
| 652 | false, |
| 653 | ) |
| 654 | } |
| 655 | |
| 656 | fn mapped_inline( |
| 657 | source: &str, |
| 658 | text: impl Into<SharedString>, |
| 659 | node: &mdast::Node, |
| 660 | cx: &NodeContext, |
| 661 | ) -> InlineNode { |
| 662 | let text = text.into(); |
| 663 | let span = node.position().map(|position| Span { |
| 664 | start: cx.offset + position.start.offset, |
| 665 | end: cx.offset + position.end.offset, |
| 666 | }); |
| 667 | let segments = source_segments( |
| 668 | source, |
| 669 | &text, |
| 670 | span, |
| 671 | cx.offset, |
| 672 | matches!(node, Node::Text(_)), |
| 673 | ); |
| 674 | InlineNode::new(text).source_segments(segments) |
| 675 | } |
| 676 | |
| 677 | fn append_inline_html_blocks(paragraph: &mut Paragraph, blocks: Vec<BlockNode>) -> Option<String> { |
| 678 | let mut text = String::new(); |
| 679 | |
| 680 | for block in blocks { |
| 681 | match block { |
| 682 | BlockNode::Root { children, .. } => { |
| 683 | text.push_str(&append_inline_html_blocks(paragraph, children)?); |
| 684 | } |
| 685 | BlockNode::Paragraph(html_paragraph) => { |
| 686 | text.push_str(&html_paragraph.text()); |
| 687 | for child in html_paragraph.children { |
| 688 | paragraph.push(child); |
| 689 | } |
| 690 | } |
| 691 | BlockNode::Break { .. } => { |
| 692 | text.push('\n'); |
| 693 | paragraph.push(InlineNode::new("\n")); |
| 694 | } |
| 695 | _ => return None, |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | Some(text) |
| 700 | } |
| 701 | |
| 702 | fn parse_paragraph( |
| 703 | source: &str, |
| 704 | paragraph: &mut Paragraph, |
| 705 | node: &mdast::Node, |
| 706 | cx: &mut NodeContext, |
| 707 | ) -> String { |
| 708 | let span = node.position().map(|pos| Span { |
| 709 | start: cx.offset + pos.start.offset, |
| 710 | end: cx.offset + pos.end.offset, |
| 711 | }); |
| 712 | if let Some(span) = span { |
| 713 | paragraph.set_span(span); |
| 714 | } |
| 715 | |
| 716 | let parse_cx = MarkdownParseContext::new(source, cx.offset); |
| 717 | if let Some(mut custom) = cx.markdown_extensions.parse_inline(node, &parse_cx) { |
| 718 | custom.set_span(span); |
| 719 | let custom = custom.with_inline_source(parse_cx.node_source(node).unwrap_or_default()); |
| 720 | let text = custom.as_text().to_string(); |
| 721 | paragraph.push(InlineNode::custom(custom)); |
| 722 | return text; |
| 723 | } |
| 724 | |
| 725 | let mut text = String::new(); |
| 726 | |
| 727 | match node { |
| 728 | Node::Paragraph(val) => { |
| 729 | text.push_str(&parse_inline_children(source, paragraph, &val.children, cx)); |
| 730 | } |
| 731 | Node::Text(val) => { |
| 732 | // A CommonMark *soft* break lives inside this value as a plain |
| 733 | // line ending. The renderer treats a newline in a text run as a |
| 734 | // line break, so a paragraph hard-wrapped in the source would |
| 735 | // render one visual line per source line instead of reflowing to |
| 736 | // the available width. Collapse soft breaks to spaces; *hard* |
| 737 | // breaks never reach here, they arrive as their own Node::Break. |
| 738 | // |
| 739 | // mdast hands the line ending over exactly as the source wrote it, |
| 740 | // so a CRLF document still carries its carriage return here. Take |
| 741 | // the CR with the newline: dropping only the newline would strand |
| 742 | // the CR in the middle of the reflowed line. |
| 743 | text = val.value.replace("\r\n", " ").replace(['\n', '\r'], " "); |
| 744 | paragraph.push(mapped_inline(source, text.clone(), node, cx)) |
| 745 | } |
| 746 | Node::Emphasis(val) => { |
| 747 | text = merge_children_with_mark( |
| 748 | source, |
| 749 | paragraph, |
| 750 | &val.children, |
| 751 | TextMark::default().italic(), |
| 752 | cx, |
| 753 | ); |
| 754 | } |
| 755 | Node::Strong(val) => { |
| 756 | text = merge_children_with_mark( |
| 757 | source, |
| 758 | paragraph, |
| 759 | &val.children, |
| 760 | TextMark::default().bold(), |
| 761 | cx, |
| 762 | ); |
| 763 | } |
| 764 | Node::Delete(val) => { |
| 765 | text = merge_children_with_mark( |
| 766 | source, |
| 767 | paragraph, |
| 768 | &val.children, |
| 769 | TextMark::default().strikethrough(), |
| 770 | cx, |
| 771 | ); |
| 772 | } |
| 773 | Node::InlineCode(val) => { |
| 774 | text = val.value.clone(); |
| 775 | let span = node.position().map(|position| Span { |
| 776 | start: cx.offset + position.start.offset, |
| 777 | end: cx.offset + position.end.offset, |
| 778 | }); |
| 779 | paragraph.push( |
| 780 | InlineNode::new(text.clone()) |
| 781 | .source_segments(code_source_segments(source, &text, span, cx.offset)) |
| 782 | .marks(vec![(0..text.len(), TextMark::default().code())]), |
| 783 | ); |
| 784 | } |
| 785 | Node::Link(val) => { |
| 786 | let link_mark = Some(LinkMark { |
| 787 | url: val.url.clone().into(), |
| 788 | title: val.title.clone().map(|s| s.into()), |
| 789 | ..Default::default() |
| 790 | }); |
| 791 | |
| 792 | text = merge_children_with_mark( |
| 793 | source, |
| 794 | paragraph, |
| 795 | &val.children, |
| 796 | TextMark { |
| 797 | link: link_mark, |
| 798 | ..Default::default() |
| 799 | }, |
| 800 | cx, |
| 801 | ); |
| 802 | } |
| 803 | Node::Image(raw) => { |
| 804 | paragraph.push_image(ImageNode { |
| 805 | url: raw.url.clone().into(), |
| 806 | title: raw.title.clone().map(|t| t.into()), |
| 807 | alt: Some(raw.alt.clone().into()), |
| 808 | span: raw.position.as_ref().map(|position| Span { |
| 809 | start: cx.offset + position.start.offset, |
| 810 | end: cx.offset + position.end.offset, |
| 811 | }), |
| 812 | ..Default::default() |
| 813 | }); |
| 814 | } |
| 815 | Node::Break(_) => { |
| 816 | // Hard line break (trailing two spaces / backslash). Mirror the |
| 817 | // inline-HTML <br> path: emit a newline inline node so the break |
| 818 | // renders instead of silently concatenating adjacent lines. |
| 819 | text.push('\n'); |
| 820 | paragraph.push(mapped_inline(source, "\n", node, cx)); |
| 821 | } |
| 822 | Node::InlineMath(raw) => { |
| 823 | // Math parsing is on by default, so ordinary prose that merely |
| 824 | // contains dollar signs ("spent $5 and $10") arrives here as a |
| 825 | // math node whenever no inline plugin claimed it. Emitting |
| 826 | // `raw.value` would drop the delimiters and restyle the run as |
| 827 | // code, silently rewriting what the author typed. Fall back to the |
| 828 | // original source so unclaimed math stays literal. |
| 829 | text = parse_cx |
| 830 | .node_source(node) |
| 831 | .map(str::to_string) |
| 832 | .unwrap_or_else(|| raw.value.clone()); |
| 833 | paragraph.push(mapped_inline(source, text.clone(), node, cx)); |
| 834 | } |
| 835 | Node::MdxTextExpression(raw) => { |
| 836 | text = raw.value.clone(); |
| 837 | let span = node.position().map(|position| Span { |
| 838 | start: cx.offset + position.start.offset, |
| 839 | end: cx.offset + position.end.offset, |
| 840 | }); |
| 841 | paragraph.push( |
| 842 | InlineNode::new(text.clone()) |
| 843 | .source_segments(code_source_segments(source, &text, span, cx.offset)) |
| 844 | .marks(vec![(0..text.len(), TextMark::default())]), |
| 845 | ); |
| 846 | } |
| 847 | Node::Html(val) => match super::html::parse(&val.value, cx) { |
| 848 | Ok(el) => { |
| 849 | if let Some(inline_text) = |
| 850 | append_inline_html_blocks(paragraph, Arc::unwrap_or_clone(el.blocks)) |
| 851 | { |
| 852 | text = inline_text; |
| 853 | } else { |
| 854 | if cfg!(debug_assertions) { |
| 855 | tracing::warn!("unsupported inline html tag: {:#?}", val.value); |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 | Err(err) => { |
| 860 | if cfg!(debug_assertions) { |
| 861 | tracing::warn!("failed parsing html: {:#?}", err); |
| 862 | } |
| 863 | |
| 864 | text.push_str(&val.value); |
| 865 | } |
| 866 | }, |
| 867 | Node::FootnoteReference(foot) => { |
| 868 | let prefix = format!("[{}]", foot.identifier); |
| 869 | paragraph.push(mapped_inline(source, prefix.clone(), node, cx).marks(vec![( |
| 870 | 0..prefix.len(), |
| 871 | TextMark { |
| 872 | italic: true, |
| 873 | ..Default::default() |
| 874 | }, |
| 875 | )])); |
| 876 | } |
| 877 | Node::LinkReference(link) => { |
| 878 | let link_mark = LinkMark { |
| 879 | url: "".into(), |
| 880 | title: link.label.clone().map(Into::into), |
| 881 | identifier: Some(link.identifier.clone().into()), |
| 882 | }; |
| 883 | |
| 884 | text = merge_children_with_mark( |
| 885 | source, |
| 886 | paragraph, |
| 887 | &link.children, |
| 888 | TextMark { |
| 889 | link: Some(link_mark), |
| 890 | ..Default::default() |
| 891 | }, |
| 892 | cx, |
| 893 | ); |
| 894 | } |
| 895 | _ => { |
| 896 | if cfg!(debug_assertions) { |
| 897 | tracing::warn!("unsupported inline node: {:#?}", node); |
| 898 | } |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | text |
| 903 | } |
| 904 | |
| 905 | fn ast_to_document(source: &str, root: mdast::Node, cx: &mut NodeContext) -> ParsedDocument { |
| 906 | let root = match root { |
| 907 | Node::Root(r) => r, |
| 908 | _ => panic!("expected root node"), |
| 909 | }; |
| 910 | |
| 911 | let blocks = root |
| 912 | .children |
| 913 | .into_iter() |
| 914 | .map(|c| ast_to_node(source, c, cx)) |
| 915 | .collect(); |
| 916 | ParsedDocument { |
| 917 | source: source.to_string().into(), |
| 918 | blocks: Arc::new(blocks), |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | fn new_span(pos: Option<markdown::unist::Position>, cx: &NodeContext) -> Option<Span> { |
| 923 | let pos = pos?; |
| 924 | |
| 925 | Some(Span { |
| 926 | start: cx.offset + pos.start.offset, |
| 927 | end: cx.offset + pos.end.offset, |
| 928 | }) |
| 929 | } |
| 930 | |
| 931 | fn ast_to_node(source: &str, value: mdast::Node, cx: &mut NodeContext) -> BlockNode { |
| 932 | let span = new_span(value.position().cloned(), cx); |
| 933 | let parse_cx = MarkdownParseContext::new(source, cx.offset); |
| 934 | if let Some(mut node) = cx.markdown_extensions.parse_block(&value, &parse_cx) { |
| 935 | node.set_span(span); |
| 936 | return BlockNode::Custom(node); |
| 937 | } |
| 938 | |
| 939 | match value { |
| 940 | Node::Root(_) => unreachable!("node::Root should be handled separately"), |
| 941 | Node::Paragraph(val) => { |
| 942 | let mut paragraph = Paragraph::default(); |
| 943 | parse_inline_children(source, &mut paragraph, &val.children, cx); |
| 944 | paragraph.span = new_span(val.position, cx); |
| 945 | BlockNode::Paragraph(paragraph) |
| 946 | } |
| 947 | Node::Blockquote(val) => { |
| 948 | let children = val |
| 949 | .children |
| 950 | .into_iter() |
| 951 | .map(|c| ast_to_node(source, c, cx)) |
| 952 | .collect(); |
| 953 | BlockNode::Blockquote { |
| 954 | children, |
| 955 | span: new_span(val.position, cx), |
| 956 | } |
| 957 | } |
| 958 | Node::List(list) => { |
| 959 | let children = list |
| 960 | .children |
| 961 | .into_iter() |
| 962 | .map(|c| ast_to_node(source, c, cx)) |
| 963 | .collect(); |
| 964 | BlockNode::List { |
| 965 | ordered: list.ordered, |
| 966 | start: list.start, |
| 967 | children, |
| 968 | span: new_span(list.position, cx), |
| 969 | } |
| 970 | } |
| 971 | Node::ListItem(val) => { |
| 972 | let children = val |
| 973 | .children |
| 974 | .into_iter() |
| 975 | .map(|c| ast_to_node(source, c, cx)) |
| 976 | .collect(); |
| 977 | BlockNode::ListItem { |
| 978 | children, |
| 979 | spread: val.spread, |
| 980 | checked: val.checked, |
| 981 | span: new_span(val.position, cx), |
| 982 | } |
| 983 | } |
| 984 | Node::Break(val) => BlockNode::Break { |
| 985 | html: false, |
| 986 | span: new_span(val.position, cx), |
| 987 | }, |
| 988 | Node::Code(raw) => { |
| 989 | let span = new_span(raw.position, cx); |
| 990 | let segments = code_source_segments(source, &raw.value, span, cx.offset); |
| 991 | BlockNode::CodeBlock( |
| 992 | CodeBlock::new(raw.value.into(), raw.lang.map(Into::into), span) |
| 993 | .source_segments(segments), |
| 994 | ) |
| 995 | } |
| 996 | Node::Heading(val) => { |
| 997 | let mut paragraph = Paragraph::default(); |
| 998 | parse_inline_children(source, &mut paragraph, &val.children, cx); |
| 999 | |
| 1000 | BlockNode::Heading { |
| 1001 | level: val.depth, |
| 1002 | children: paragraph, |
| 1003 | span: new_span(val.position, cx), |
| 1004 | } |
| 1005 | } |
| 1006 | Node::Math(val) => { |
| 1007 | let span = new_span(val.position, cx); |
| 1008 | let segments = code_source_segments(source, &val.value, span, cx.offset); |
| 1009 | BlockNode::CodeBlock( |
| 1010 | CodeBlock::new(val.value.into(), None, span).source_segments(segments), |
| 1011 | ) |
| 1012 | } |
| 1013 | Node::Html(val) => match super::html::parse(&val.value, cx) { |
| 1014 | Ok(el) => BlockNode::Root { |
| 1015 | children: Arc::unwrap_or_clone(el.blocks), |
| 1016 | span: new_span(val.position, cx), |
| 1017 | }, |
| 1018 | Err(err) => { |
| 1019 | if cfg!(debug_assertions) { |
| 1020 | tracing::warn!("error parsing html: {:#?}", err); |
| 1021 | } |
| 1022 | |
| 1023 | BlockNode::Paragraph(Paragraph::new(val.value)) |
| 1024 | } |
| 1025 | }, |
| 1026 | Node::MdxFlowExpression(val) => { |
| 1027 | let span = new_span(val.position, cx); |
| 1028 | let segments = code_source_segments(source, &val.value, span, cx.offset); |
| 1029 | BlockNode::CodeBlock( |
| 1030 | CodeBlock::new(val.value.into(), Some("mdx".into()), span) |
| 1031 | .source_segments(segments), |
| 1032 | ) |
| 1033 | } |
| 1034 | Node::Yaml(val) => BlockNode::CodeBlock(CodeBlock::new( |
| 1035 | val.value.into(), |
| 1036 | Some("yml".into()), |
| 1037 | new_span(val.position, cx), |
| 1038 | )), |
| 1039 | Node::Toml(val) => BlockNode::CodeBlock(CodeBlock::new( |
| 1040 | val.value.into(), |
| 1041 | Some("toml".into()), |
| 1042 | new_span(val.position, cx), |
| 1043 | )), |
| 1044 | Node::MdxJsxTextElement(val) => { |
| 1045 | let mut paragraph = Paragraph::default(); |
| 1046 | parse_inline_children(source, &mut paragraph, &val.children, cx); |
| 1047 | paragraph.span = new_span(val.position, cx); |
| 1048 | BlockNode::Paragraph(paragraph) |
| 1049 | } |
| 1050 | Node::MdxJsxFlowElement(val) => { |
| 1051 | let mut paragraph = Paragraph::default(); |
| 1052 | parse_inline_children(source, &mut paragraph, &val.children, cx); |
| 1053 | paragraph.span = new_span(val.position, cx); |
| 1054 | BlockNode::Paragraph(paragraph) |
| 1055 | } |
| 1056 | Node::ThematicBreak(val) => BlockNode::HorizontalRule { |
| 1057 | span: new_span(val.position, cx), |
| 1058 | }, |
| 1059 | Node::Table(val) => { |
| 1060 | let mut table = Table::default(); |
| 1061 | table.column_aligns = val |
| 1062 | .align |
| 1063 | .clone() |
| 1064 | .into_iter() |
| 1065 | .map(|align| align.into()) |
| 1066 | .collect(); |
| 1067 | val.children.iter().for_each(|c| { |
| 1068 | if let Node::TableRow(row) = c { |
| 1069 | parse_table_row(source, &mut table, row, cx); |
| 1070 | } |
| 1071 | }); |
| 1072 | table.span = new_span(val.position, cx); |
| 1073 | |
| 1074 | BlockNode::Table(table) |
| 1075 | } |
| 1076 | Node::FootnoteDefinition(def) => { |
| 1077 | let mut paragraph = Paragraph::default(); |
| 1078 | let prefix = format!("[{}]: ", def.identifier); |
| 1079 | paragraph.push(InlineNode::new(&prefix).marks(vec![( |
| 1080 | 0..prefix.len(), |
| 1081 | TextMark { |
| 1082 | italic: true, |
| 1083 | ..Default::default() |
| 1084 | }, |
| 1085 | )])); |
| 1086 | |
| 1087 | parse_inline_children(source, &mut paragraph, &def.children, cx); |
| 1088 | paragraph.span = new_span(def.position, cx); |
| 1089 | BlockNode::Paragraph(paragraph) |
| 1090 | } |
| 1091 | Node::Definition(def) => { |
| 1092 | cx.add_ref( |
| 1093 | def.identifier.clone().into(), |
| 1094 | LinkMark { |
| 1095 | url: def.url.clone().into(), |
| 1096 | identifier: Some(def.identifier.clone().into()), |
| 1097 | title: def.title.clone().map(Into::into), |
| 1098 | }, |
| 1099 | ); |
| 1100 | |
| 1101 | BlockNode::Definition { |
| 1102 | identifier: def.identifier.clone().into(), |
| 1103 | url: def.url.clone().into(), |
| 1104 | title: def.title.clone().map(|s| s.into()), |
| 1105 | span: new_span(def.position, cx), |
| 1106 | } |
| 1107 | } |
| 1108 | _ => { |
| 1109 | if cfg!(debug_assertions) { |
| 1110 | tracing::warn!("unsupported node: {:#?}", value); |
| 1111 | } |
| 1112 | BlockNode::Unknown |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | #[cfg(test)] |
| 1118 | mod tests { |
| 1119 | use super::*; |
| 1120 | use gpui::ParentElement; |
| 1121 | |
| 1122 | use crate::text::{MarkdownExtensions, MarkdownNode, MarkdownPlugin}; |
| 1123 | |
| 1124 | fn first_paragraph(block: &BlockNode) -> Option<&Paragraph> { |
| 1125 | match block { |
| 1126 | BlockNode::Paragraph(paragraph) |
| 1127 | | BlockNode::Heading { |
| 1128 | children: paragraph, |
| 1129 | .. |
| 1130 | } => Some(paragraph), |
| 1131 | BlockNode::Root { children, .. } |
| 1132 | | BlockNode::Blockquote { children, .. } |
| 1133 | | BlockNode::List { children, .. } |
| 1134 | | BlockNode::ListItem { children, .. } => children.iter().find_map(first_paragraph), |
| 1135 | _ => None, |
| 1136 | } |
| 1137 | } |
| 1138 | |
| 1139 | fn first_code_block(block: &BlockNode) -> Option<&CodeBlock> { |
| 1140 | match block { |
| 1141 | BlockNode::CodeBlock(code) => Some(code), |
| 1142 | BlockNode::Root { children, .. } |
| 1143 | | BlockNode::Blockquote { children, .. } |
| 1144 | | BlockNode::List { children, .. } |
| 1145 | | BlockNode::ListItem { children, .. } => children.iter().find_map(first_code_block), |
| 1146 | _ => None, |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | fn selected_rendered_range(source: &str, selection: Range<usize>) -> Option<Range<usize>> { |
| 1151 | let mut cx = NodeContext::default(); |
| 1152 | let document = parse(source, &mut cx).unwrap(); |
| 1153 | let paragraph = document |
| 1154 | .blocks |
| 1155 | .iter() |
| 1156 | .find_map(first_paragraph) |
| 1157 | .expect("expected paragraph"); |
| 1158 | let rendered = paragraph.text(); |
| 1159 | let mut state = paragraph.state.lock().unwrap(); |
| 1160 | state.set_text(rendered.into()); |
| 1161 | state.selection = Some(selection.into()); |
| 1162 | drop(state); |
| 1163 | document.selected_source_range() |
| 1164 | } |
| 1165 | |
| 1166 | fn select_rendered_range(source: &str, selection: Range<usize>) -> Range<usize> { |
| 1167 | selected_rendered_range(source, selection).expect("source range") |
| 1168 | } |
| 1169 | |
| 1170 | fn selected_code_range(source: &str, selection: Range<usize>) -> Option<Range<usize>> { |
| 1171 | let mut cx = NodeContext::default(); |
| 1172 | let document = parse(source, &mut cx).unwrap(); |
| 1173 | let code = document |
| 1174 | .blocks |
| 1175 | .iter() |
| 1176 | .find_map(first_code_block) |
| 1177 | .expect("expected code block"); |
| 1178 | code.set_selection(selection); |
| 1179 | document.selected_source_range() |
| 1180 | } |
| 1181 | |
| 1182 | fn selected_mdx_rendered_range(source: &str, selection: Range<usize>) -> Option<Range<usize>> { |
| 1183 | let mut cx = NodeContext { |
| 1184 | markdown_extensions: Arc::new(MarkdownExtensions::default().mdx()), |
| 1185 | ..Default::default() |
| 1186 | }; |
| 1187 | let document = parse(source, &mut cx).unwrap(); |
| 1188 | let paragraph = document |
| 1189 | .blocks |
| 1190 | .iter() |
| 1191 | .find_map(first_paragraph) |
| 1192 | .expect("expected MDX paragraph"); |
| 1193 | let rendered = paragraph.text(); |
| 1194 | let mut state = paragraph.state.lock().unwrap(); |
| 1195 | state.set_text(rendered.into()); |
| 1196 | state.selection = Some(selection.into()); |
| 1197 | drop(state); |
| 1198 | document.selected_source_range() |
| 1199 | } |
| 1200 | |
| 1201 | fn selected_mdx_code(source: &str, selected_text: &str) -> Option<Range<usize>> { |
| 1202 | let mut cx = NodeContext { |
| 1203 | markdown_extensions: Arc::new(MarkdownExtensions::default().mdx()), |
| 1204 | ..Default::default() |
| 1205 | }; |
| 1206 | let document = parse(source, &mut cx).unwrap(); |
| 1207 | let code = document |
| 1208 | .blocks |
| 1209 | .iter() |
| 1210 | .find_map(first_code_block) |
| 1211 | .expect("expected MDX code block"); |
| 1212 | let code_text = code.code(); |
| 1213 | let start = code_text.find(selected_text).expect("selected MDX code"); |
| 1214 | code.set_selection(start..start + selected_text.len()); |
| 1215 | document.selected_source_range() |
| 1216 | } |
| 1217 | |
| 1218 | #[test] |
| 1219 | fn table_rows_use_header_column_count() { |
| 1220 | let mut cx = NodeContext::default(); |
| 1221 | let document = parse( |
| 1222 | "| A | B | C |\n| --- | --- | --- |\n| one |\n| two | three | four | ignored |\n", |
| 1223 | &mut cx, |
| 1224 | ) |
| 1225 | .unwrap(); |
| 1226 | let BlockNode::Table(table) = &document.blocks[0] else { |
| 1227 | panic!("expected table"); |
| 1228 | }; |
| 1229 | assert_eq!(table.column_aligns.len(), 3); |
| 1230 | assert!(table.children.iter().all(|row| row.children.len() == 3)); |
| 1231 | assert_eq!(table.children[1].children[0].children.text(), "one"); |
| 1232 | assert!(table.children[1].children[1].children.text().is_empty()); |
| 1233 | assert_eq!(table.children[2].children[2].children.text(), "four"); |
| 1234 | } |
| 1235 | |
| 1236 | #[test] |
| 1237 | fn selected_source_range_uses_the_selected_identical_styled_occurrence() { |
| 1238 | let source = "**same** then **same**"; |
| 1239 | assert_eq!(select_rendered_range(source, 10..14), 16..20); |
| 1240 | } |
| 1241 | |
| 1242 | #[test] |
| 1243 | fn selected_source_range_maps_partial_styled_text() { |
| 1244 | let source = "**same** then **same**"; |
| 1245 | assert_eq!(select_rendered_range(source, 11..13), 17..19); |
| 1246 | } |
| 1247 | |
| 1248 | #[test] |
| 1249 | fn source_segments_compact_contiguous_one_to_one_mappings() { |
| 1250 | let source = "plain text"; |
| 1251 | let mut cx = NodeContext::default(); |
| 1252 | let document = parse(source, &mut cx).unwrap(); |
| 1253 | let paragraph = first_paragraph(&document.blocks[0]).unwrap(); |
| 1254 | assert_eq!( |
| 1255 | paragraph.children[0].source_segments, |
| 1256 | vec![SourceSegment { |
| 1257 | rendered: 0..source.len(), |
| 1258 | source: 0..source.len(), |
| 1259 | linear: true, |
| 1260 | }] |
| 1261 | ); |
| 1262 | |
| 1263 | assert_eq!(select_rendered_range(source, 2..7), 2..7); |
| 1264 | } |
| 1265 | |
| 1266 | #[test] |
| 1267 | fn source_alignment_compacts_long_whitespace_runs() { |
| 1268 | for raw in [ |
| 1269 | "a ".repeat(16_384), |
| 1270 | format!("a{}b", " ".repeat(32_768)), |
| 1271 | format!("a{}b\n", " \t".repeat(16_384)), |
| 1272 | ] { |
| 1273 | let segments = aligned_source_segments(&raw, &raw, 7, true, true); |
| 1274 | assert_eq!( |
| 1275 | segments, |
| 1276 | vec![SourceSegment { |
| 1277 | rendered: 0..raw.len(), |
| 1278 | source: 7..7 + raw.len(), |
| 1279 | linear: true, |
| 1280 | }] |
| 1281 | ); |
| 1282 | assert!( |
| 1283 | segments.capacity() < 64, |
| 1284 | "compaction must not retain a per-character allocation" |
| 1285 | ); |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | #[test] |
| 1290 | fn source_alignment_preserves_multiline_code_and_final_newline() { |
| 1291 | let raw = "x\n".repeat(16_384); |
| 1292 | let rendered = &raw[..raw.len() - 1]; |
| 1293 | assert_eq!( |
| 1294 | aligned_source_segments(&raw, rendered, 4, false, false), |
| 1295 | vec![SourceSegment { |
| 1296 | rendered: 0..rendered.len(), |
| 1297 | source: 4..4 + rendered.len(), |
| 1298 | linear: true, |
| 1299 | }] |
| 1300 | ); |
| 1301 | assert_eq!( |
| 1302 | aligned_source_segments("a\n> \n", "a\n\n", 0, false, false), |
| 1303 | vec![ |
| 1304 | SourceSegment { |
| 1305 | rendered: 0..2, |
| 1306 | source: 0..2, |
| 1307 | linear: true, |
| 1308 | }, |
| 1309 | SourceSegment { |
| 1310 | rendered: 2..3, |
| 1311 | source: 2..5, |
| 1312 | linear: false, |
| 1313 | }, |
| 1314 | ] |
| 1315 | ); |
| 1316 | } |
| 1317 | |
| 1318 | #[test] |
| 1319 | fn source_alignment_keeps_soft_breaks_and_entities_atomic() { |
| 1320 | assert_eq!( |
| 1321 | aligned_source_segments("a \r\nb", "a b", 9, true, true), |
| 1322 | vec![ |
| 1323 | SourceSegment { |
| 1324 | rendered: 0..1, |
| 1325 | source: 9..10, |
| 1326 | linear: true, |
| 1327 | }, |
| 1328 | SourceSegment { |
| 1329 | rendered: 1..2, |
| 1330 | source: 11..13, |
| 1331 | linear: false, |
| 1332 | }, |
| 1333 | SourceSegment { |
| 1334 | rendered: 2..3, |
| 1335 | source: 13..14, |
| 1336 | linear: true, |
| 1337 | }, |
| 1338 | ] |
| 1339 | ); |
| 1340 | let entity = "≂̸"; |
| 1341 | let decoded = "\u{2242}\u{338}"; |
| 1342 | assert_eq!( |
| 1343 | aligned_source_segments(entity, decoded, 3, true, true), |
| 1344 | vec![SourceSegment { |
| 1345 | rendered: 0..decoded.len(), |
| 1346 | source: 3..3 + entity.len(), |
| 1347 | linear: false, |
| 1348 | }] |
| 1349 | ); |
| 1350 | } |
| 1351 | |
| 1352 | #[test] |
| 1353 | fn source_alignment_resumes_after_unmapped_characters() { |
| 1354 | let raw = "abc".repeat(4_096); |
| 1355 | let mut positions = None; |
| 1356 | assert_eq!(source_char_offset(&raw, 0, 'b', &mut positions), Some(1)); |
| 1357 | assert!(positions.is_none(), "successful scans need no index"); |
| 1358 | assert_eq!( |
| 1359 | source_char_offset(&raw, 0, '\u{fffd}', &mut positions), |
| 1360 | None |
| 1361 | ); |
| 1362 | assert!(positions.is_some(), "failed scans must not be repeated"); |
| 1363 | assert_eq!(source_char_offset(&raw, 2, 'b', &mut positions), Some(4)); |
| 1364 | assert_eq!( |
| 1365 | source_char_offset(&raw, raw.len(), 'a', &mut positions), |
| 1366 | None |
| 1367 | ); |
| 1368 | |
| 1369 | let missing = "\u{fffd}".repeat(4_096); |
| 1370 | assert_eq!( |
| 1371 | aligned_source_segments(&raw, &format!("{missing}abc"), 5, true, true), |
| 1372 | vec![SourceSegment { |
| 1373 | rendered: missing.len()..missing.len() + 3, |
| 1374 | source: 5..8, |
| 1375 | linear: true, |
| 1376 | }] |
| 1377 | ); |
| 1378 | assert_eq!( |
| 1379 | aligned_source_segments("&z", &format!("{missing}&z"), 0, true, true), |
| 1380 | vec![ |
| 1381 | SourceSegment { |
| 1382 | rendered: missing.len()..missing.len() + 1, |
| 1383 | source: 0..5, |
| 1384 | linear: false, |
| 1385 | }, |
| 1386 | SourceSegment { |
| 1387 | rendered: missing.len() + 1..missing.len() + 2, |
| 1388 | source: 5..6, |
| 1389 | linear: true, |
| 1390 | }, |
| 1391 | ] |
| 1392 | ); |
| 1393 | } |
| 1394 | |
| 1395 | #[test] |
| 1396 | fn source_alignment_parses_long_text_and_code_without_selection() { |
| 1397 | let source = format!("{}end", "a ".repeat(4_096)); |
| 1398 | let mut cx = NodeContext::default(); |
| 1399 | let document = parse(&source, &mut cx).unwrap(); |
| 1400 | let paragraph = first_paragraph(&document.blocks[0]).unwrap(); |
| 1401 | assert_eq!(paragraph.text(), source); |
| 1402 | let segments = ¶graph.children[0].source_segments; |
| 1403 | assert_eq!(segments.len(), 1); |
| 1404 | assert!(segments.capacity() < 64); |
| 1405 | assert_eq!(segments[0].source, 0..source.len()); |
| 1406 | assert_eq!( |
| 1407 | selected_rendered_range(&source, source.len() - 3..source.len()), |
| 1408 | Some(source.len() - 3..source.len()) |
| 1409 | ); |
| 1410 | |
| 1411 | let body = "x\n".repeat(4_096); |
| 1412 | let source = format!("```\n{body}```"); |
| 1413 | let document = parse(&source, &mut cx).unwrap(); |
| 1414 | assert!(first_code_block(&document.blocks[0]).is_some()); |
| 1415 | assert_eq!( |
| 1416 | selected_code_range(&source, body.len() - 2..body.len() - 1), |
| 1417 | Some(body.len() + 2..body.len() + 3) |
| 1418 | ); |
| 1419 | } |
| 1420 | |
| 1421 | #[test] |
| 1422 | fn source_segments_keep_non_linear_mappings_atomic() { |
| 1423 | let source = r"a\* & b"; |
| 1424 | let mut cx = NodeContext::default(); |
| 1425 | let document = parse(source, &mut cx).unwrap(); |
| 1426 | let paragraph = first_paragraph(&document.blocks[0]).unwrap(); |
| 1427 | let segments = ¶graph.children[0].source_segments; |
| 1428 | |
| 1429 | assert!( |
| 1430 | segments.len() < paragraph.children[0].text.chars().count(), |
| 1431 | "ordinary characters should be compacted into runs" |
| 1432 | ); |
| 1433 | assert!(segments.contains(&SourceSegment { |
| 1434 | rendered: 1..2, |
| 1435 | source: 1..3, |
| 1436 | linear: false, |
| 1437 | })); |
| 1438 | assert!(segments.contains(&SourceSegment { |
| 1439 | rendered: 3..4, |
| 1440 | source: 4..9, |
| 1441 | linear: false, |
| 1442 | })); |
| 1443 | |
| 1444 | assert_eq!(select_rendered_range(source, 1..2), 1..3); |
| 1445 | assert_eq!(select_rendered_range(source, 3..4), 4..9); |
| 1446 | } |
| 1447 | |
| 1448 | #[test] |
| 1449 | fn source_segments_keep_an_entity_as_long_as_its_characters_atomic() { |
| 1450 | // `∾̳` decodes to `∾̳`: five bytes each, but not one for one. |
| 1451 | let source = "a ∾̳ b"; |
| 1452 | let mut cx = NodeContext::default(); |
| 1453 | let document = parse(source, &mut cx).unwrap(); |
| 1454 | let paragraph = first_paragraph(&document.blocks[0]).unwrap(); |
| 1455 | assert_eq!(paragraph.children[0].text.as_ref(), "a ∾̳ b"); |
| 1456 | assert_eq!( |
| 1457 | paragraph.children[0].source_segments, |
| 1458 | vec![ |
| 1459 | SourceSegment { |
| 1460 | rendered: 0..2, |
| 1461 | source: 0..2, |
| 1462 | linear: true, |
| 1463 | }, |
| 1464 | SourceSegment { |
| 1465 | rendered: 2..7, |
| 1466 | source: 2..7, |
| 1467 | linear: false, |
| 1468 | }, |
| 1469 | SourceSegment { |
| 1470 | rendered: 7..9, |
| 1471 | source: 7..9, |
| 1472 | linear: true, |
| 1473 | }, |
| 1474 | ] |
| 1475 | ); |
| 1476 | // Selecting the combining mark alone reports the whole entity. |
| 1477 | assert_eq!(select_rendered_range(source, 5..7), 2..7); |
| 1478 | } |
| 1479 | |
| 1480 | #[test] |
| 1481 | fn selected_source_range_crosses_style_boundaries() { |
| 1482 | let source = "left **bold** right"; |
| 1483 | assert_eq!(select_rendered_range(source, 2..12), 2..16); |
| 1484 | } |
| 1485 | |
| 1486 | #[test] |
| 1487 | fn selected_source_range_maps_inline_code_in_merged_styled_node() { |
| 1488 | let source = "**left `code` right**"; |
| 1489 | assert_eq!(selected_rendered_range(source, 5..9), Some(8..12)); |
| 1490 | } |
| 1491 | |
| 1492 | #[test] |
| 1493 | fn selected_source_range_maps_inline_code_delimiters_and_boundaries() { |
| 1494 | let source = "`code` x"; |
| 1495 | assert_eq!(selected_rendered_range(source, 0..4), Some(1..5)); |
| 1496 | assert_eq!(selected_rendered_range(source, 5..6), Some(7..8)); |
| 1497 | assert_eq!(selected_rendered_range(source, 3..6), Some(4..8)); |
| 1498 | |
| 1499 | let padded = "`` code ` value ``"; |
| 1500 | assert_eq!(selected_rendered_range(padded, 0..4), Some(3..7)); |
| 1501 | assert_eq!(selected_rendered_range(padded, 5..6), Some(8..9)); |
| 1502 | |
| 1503 | let literal_entity = "`&`"; |
| 1504 | assert_eq!(selected_rendered_range(literal_entity, 0..5), Some(1..6)); |
| 1505 | } |
| 1506 | |
| 1507 | #[test] |
| 1508 | fn selected_source_range_keeps_inline_code_escapes_literal() { |
| 1509 | assert_eq!(select_rendered_range("`a\\\\b`", 1..2), 2..3); |
| 1510 | assert_eq!(select_rendered_range("`a\\\\b`", 2..3), 3..4); |
| 1511 | assert_eq!(select_rendered_range(r"`a\*b`", 1..2), 2..3); |
| 1512 | assert_eq!(select_rendered_range(r"`a\*b`", 2..3), 3..4); |
| 1513 | // The same punctuation is still an escape outside code. |
| 1514 | assert_eq!(select_rendered_range(r"a\*b", 1..2), 1..3); |
| 1515 | } |
| 1516 | |
| 1517 | #[test] |
| 1518 | fn selected_source_range_maps_footnote_reference_syntax() { |
| 1519 | let source = "before[^note] after\n\n[^note]: body"; |
| 1520 | assert_eq!(selected_rendered_range(source, 0..6), Some(0..6)); |
| 1521 | assert_eq!(selected_rendered_range(source, 6..12), Some(6..13)); |
| 1522 | assert_eq!(selected_rendered_range(source, 13..18), Some(14..19)); |
| 1523 | assert_eq!(selected_rendered_range(source, 4..15), Some(4..16)); |
| 1524 | } |
| 1525 | |
| 1526 | #[test] |
| 1527 | fn selected_source_range_maps_mdx_text_expression_body() { |
| 1528 | let source = "before {value + 1} after"; |
| 1529 | assert_eq!(selected_mdx_rendered_range(source, 7..16), Some(8..17)); |
| 1530 | assert_eq!(selected_mdx_rendered_range(source, 4..19), Some(4..21)); |
| 1531 | } |
| 1532 | |
| 1533 | #[test] |
| 1534 | fn selected_source_range_maps_mdx_flow_expression_body() { |
| 1535 | let source = "{\n value + 1\n}"; |
| 1536 | assert_eq!(selected_mdx_code(source, "value + 1"), Some(4..13)); |
| 1537 | assert_eq!(selected_mdx_code(source, "lue +"), Some(6..11)); |
| 1538 | } |
| 1539 | |
| 1540 | #[test] |
| 1541 | fn selected_source_range_maps_math_block_body() { |
| 1542 | let source = "$$\nx + y\n$$"; |
| 1543 | assert_eq!(selected_code_range(source, 0..5), Some(3..8)); |
| 1544 | assert_eq!(selected_code_range(source, 2..3), Some(5..6)); |
| 1545 | } |
| 1546 | |
| 1547 | #[test] |
| 1548 | fn selected_source_range_rejects_mapped_block_plus_unmappable_entity() { |
| 1549 | let source = "mapped\n\nA & B"; |
| 1550 | let mut cx = NodeContext::default(); |
| 1551 | let document = parse(source, &mut cx).unwrap(); |
| 1552 | let [BlockNode::Paragraph(mapped), BlockNode::Paragraph(entity)] = |
| 1553 | document.blocks.as_slice() |
| 1554 | else { |
| 1555 | panic!("expected two paragraphs"); |
| 1556 | }; |
| 1557 | mapped.state.lock().unwrap().selection = Some((0..6).into()); |
| 1558 | |
| 1559 | entity.state.lock().unwrap().selection = Some((2..2).into()); |
| 1560 | assert_eq!(document.selected_source_range(), Some(0..6)); |
| 1561 | |
| 1562 | entity.state.lock().unwrap().selection = Some((2..3).into()); |
| 1563 | assert_eq!(document.selected_source_range(), Some(0..15)); |
| 1564 | } |
| 1565 | |
| 1566 | #[test] |
| 1567 | fn selected_source_range_maps_fenced_code_body_after_matching_info_string() { |
| 1568 | let source = "```rust\nrust\n```"; |
| 1569 | let mut cx = NodeContext::default(); |
| 1570 | let document = parse(source, &mut cx).unwrap(); |
| 1571 | let BlockNode::CodeBlock(code) = &document.blocks[0] else { |
| 1572 | panic!("expected code block"); |
| 1573 | }; |
| 1574 | code.set_selection(0..4); |
| 1575 | |
| 1576 | assert_eq!(document.selected_source_range(), Some(8..12)); |
| 1577 | } |
| 1578 | |
| 1579 | #[test] |
| 1580 | fn selected_source_range_maps_each_literal_backslash_in_fenced_code() { |
| 1581 | let source = "```\na\\\\b\n```"; |
| 1582 | assert_eq!(selected_code_range(source, 1..2), Some(5..6)); |
| 1583 | assert_eq!(selected_code_range(source, 2..3), Some(6..7)); |
| 1584 | assert_eq!(selected_code_range(source, 1..3), Some(5..7)); |
| 1585 | let punctuation = "```\na\\*b\n```"; |
| 1586 | assert_eq!(selected_code_range(punctuation, 1..2), Some(5..6)); |
| 1587 | assert_eq!(selected_code_range(punctuation, 2..3), Some(6..7)); |
| 1588 | assert_eq!(selected_code_range("```\na\\\\b\r\n```", 1..3), Some(5..7)); |
| 1589 | let multiline = "```\na\\\\\nb\n```"; |
| 1590 | assert_eq!(selected_code_range(multiline, 1..2), Some(5..6)); |
| 1591 | assert_eq!(selected_code_range(multiline, 2..3), Some(6..7)); |
| 1592 | assert_eq!(selected_code_range(multiline, 3..4), Some(7..8)); |
| 1593 | assert_eq!(selected_code_range(multiline, 4..5), Some(8..9)); |
| 1594 | } |
| 1595 | |
| 1596 | #[test] |
| 1597 | fn selected_source_range_excludes_closing_fence_candidate() { |
| 1598 | let source = "````text\n```\n````"; |
| 1599 | let mut cx = NodeContext::default(); |
| 1600 | let document = parse(source, &mut cx).unwrap(); |
| 1601 | let BlockNode::CodeBlock(code) = &document.blocks[0] else { |
| 1602 | panic!("expected code block"); |
| 1603 | }; |
| 1604 | code.set_selection(0..3); |
| 1605 | |
| 1606 | assert_eq!(document.selected_source_range(), Some(9..12)); |
| 1607 | } |
| 1608 | |
| 1609 | #[test] |
| 1610 | fn selected_source_range_maps_indented_code_content() { |
| 1611 | let source = " rust"; |
| 1612 | let mut cx = NodeContext::default(); |
| 1613 | let document = parse(source, &mut cx).unwrap(); |
| 1614 | let BlockNode::CodeBlock(code) = &document.blocks[0] else { |
| 1615 | panic!("expected code block"); |
| 1616 | }; |
| 1617 | code.set_selection(0..4); |
| 1618 | |
| 1619 | assert_eq!(document.selected_source_range(), Some(4..8)); |
| 1620 | } |
| 1621 | |
| 1622 | #[test] |
| 1623 | fn selected_source_range_maps_multiline_indented_code() { |
| 1624 | let source = " one\n two\n three"; |
| 1625 | assert_eq!(selected_code_range(source, 0..3), Some(4..7)); |
| 1626 | assert_eq!(selected_code_range(source, 4..7), Some(12..15)); |
| 1627 | assert_eq!(selected_code_range(source, 0..13), Some(4..25)); |
| 1628 | } |
| 1629 | |
| 1630 | #[test] |
| 1631 | fn selected_source_range_maps_literal_backslashes_in_indented_code() { |
| 1632 | let source = " one\n a\\\\b"; |
| 1633 | assert_eq!(selected_code_range(source, 5..6), Some(13..14)); |
| 1634 | assert_eq!(selected_code_range(source, 6..7), Some(14..15)); |
| 1635 | assert_eq!(selected_code_range(source, 5..7), Some(13..15)); |
| 1636 | } |
| 1637 | |
| 1638 | #[test] |
| 1639 | fn selected_source_range_maps_fenced_code_nested_in_a_list() { |
| 1640 | let source = "- ```rust\n one\n two\n ```"; |
| 1641 | assert_eq!(selected_code_range(source, 0..3), Some(12..15)); |
| 1642 | assert_eq!(selected_code_range(source, 4..7), Some(18..21)); |
| 1643 | assert_eq!(selected_code_range(source, 0..7), Some(12..21)); |
| 1644 | } |
| 1645 | |
| 1646 | #[test] |
| 1647 | fn selected_source_range_maps_literal_backslashes_in_nested_fences() { |
| 1648 | for source in ["- ```\n a\\\\b\n ```", "> ```\n> a\\\\b\n> ```"] { |
| 1649 | assert_eq!(selected_code_range(source, 1..2), Some(9..10)); |
| 1650 | assert_eq!(selected_code_range(source, 2..3), Some(10..11)); |
| 1651 | } |
| 1652 | } |
| 1653 | |
| 1654 | #[test] |
| 1655 | fn selected_source_range_maps_fenced_code_nested_in_a_blockquote() { |
| 1656 | let source = "> ```\n> one\n> two\n> ```"; |
| 1657 | assert_eq!(selected_code_range(source, 0..3), Some(8..11)); |
| 1658 | assert_eq!(selected_code_range(source, 4..7), Some(14..17)); |
| 1659 | assert_eq!(selected_code_range(source, 0..7), Some(8..17)); |
| 1660 | } |
| 1661 | |
| 1662 | #[test] |
| 1663 | fn selected_source_range_maps_fenced_code_with_blank_lines_and_repeated_text() { |
| 1664 | let source = "```\nsame\n\nsame\n```"; |
| 1665 | assert_eq!(selected_code_range(source, 0..4), Some(4..8)); |
| 1666 | assert_eq!(selected_code_range(source, 6..10), Some(10..14)); |
| 1667 | assert_eq!(selected_code_range(source, 0..10), Some(4..14)); |
| 1668 | } |
| 1669 | |
| 1670 | #[test] |
| 1671 | fn selected_source_range_maps_the_whole_markdown_escape() { |
| 1672 | assert_eq!(selected_rendered_range(r"\*", 0..1), Some(0..2)); |
| 1673 | } |
| 1674 | |
| 1675 | #[test] |
| 1676 | fn selected_source_range_maps_text_after_an_escape_character_for_character() { |
| 1677 | let source = r"\*abc"; |
| 1678 | assert_eq!(select_rendered_range(source, 0..1), 0..2); |
| 1679 | assert_eq!(select_rendered_range(source, 2..3), 3..4); |
| 1680 | assert_eq!(select_rendered_range(source, 0..2), 0..3); |
| 1681 | // Only punctuation escapes, so a backslash before a letter is text. |
| 1682 | let source = r"\été"; |
| 1683 | assert_eq!(select_rendered_range(source, 0..1), 0..1); |
| 1684 | assert_eq!(select_rendered_range(source, 1..3), 1..3); |
| 1685 | } |
| 1686 | |
| 1687 | #[test] |
| 1688 | fn selected_source_range_maps_after_an_escaped_backslash() { |
| 1689 | let source = r"a\\b"; |
| 1690 | assert_eq!(select_rendered_range(source, 1..2), 1..3); |
| 1691 | assert_eq!(select_rendered_range(source, 2..3), 3..4); |
| 1692 | assert_eq!(select_rendered_range(source, 1..3), 1..4); |
| 1693 | |
| 1694 | let repeated = r"\\\\b"; |
| 1695 | assert_eq!(select_rendered_range(repeated, 2..3), 4..5); |
| 1696 | } |
| 1697 | |
| 1698 | #[test] |
| 1699 | fn selected_source_range_does_not_borrow_an_escape_from_the_previous_node() { |
| 1700 | let source = r"a\\$x$"; |
| 1701 | assert_eq!(select_rendered_range(source, 2..3), 3..4); |
| 1702 | assert_eq!(select_rendered_range(source, 1..3), 1..4); |
| 1703 | } |
| 1704 | |
| 1705 | #[test] |
| 1706 | fn selected_source_range_does_not_shift_a_hard_break_after_an_escape() { |
| 1707 | let source = "a\\\\ \nb"; |
| 1708 | assert_eq!(select_rendered_range(source, 2..3), 3..6); |
| 1709 | assert_eq!(select_rendered_range(source, 1..3), 1..6); |
| 1710 | } |
| 1711 | |
| 1712 | #[test] |
| 1713 | fn selected_source_range_includes_a_trailing_inline_image() { |
| 1714 | let source = "before "; |
| 1715 | let mut cx = NodeContext::default(); |
| 1716 | let document = parse(source, &mut cx).unwrap(); |
| 1717 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1718 | panic!("expected paragraph"); |
| 1719 | }; |
| 1720 | let image = paragraph |
| 1721 | .children |
| 1722 | .iter() |
| 1723 | .find(|child| child.image.is_some()) |
| 1724 | .expect("expected image"); |
| 1725 | let mut state = image.state.lock().unwrap(); |
| 1726 | state.set_text("before ".into()); |
| 1727 | state.selection = Some((0..7).into()); |
| 1728 | drop(state); |
| 1729 | |
| 1730 | assert_eq!(document.selected_source_range(), Some(0..source.len())); |
| 1731 | } |
| 1732 | |
| 1733 | #[test] |
| 1734 | fn selected_source_range_includes_a_leading_inline_image() { |
| 1735 | let source = " after"; |
| 1736 | let mut cx = NodeContext::default(); |
| 1737 | let document = parse(source, &mut cx).unwrap(); |
| 1738 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1739 | panic!("expected paragraph"); |
| 1740 | }; |
| 1741 | let mut state = paragraph.state.lock().unwrap(); |
| 1742 | state.set_text(" after".into()); |
| 1743 | state.selection = Some((0..6).into()); |
| 1744 | drop(state); |
| 1745 | |
| 1746 | assert_eq!(document.selected_source_range(), Some(0..source.len())); |
| 1747 | } |
| 1748 | |
| 1749 | #[test] |
| 1750 | fn selected_source_range_includes_an_enclosed_inline_image() { |
| 1751 | let source = "before  after"; |
| 1752 | let mut cx = NodeContext::default(); |
| 1753 | let document = parse(source, &mut cx).unwrap(); |
| 1754 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1755 | panic!("expected paragraph"); |
| 1756 | }; |
| 1757 | let image = paragraph |
| 1758 | .children |
| 1759 | .iter() |
| 1760 | .find(|child| child.image.is_some()) |
| 1761 | .expect("expected image"); |
| 1762 | let mut before = image.state.lock().unwrap(); |
| 1763 | before.set_text("before ".into()); |
| 1764 | before.selection = Some((0..7).into()); |
| 1765 | drop(before); |
| 1766 | let mut after = paragraph.state.lock().unwrap(); |
| 1767 | after.set_text(" after".into()); |
| 1768 | after.selection = Some((0..6).into()); |
| 1769 | drop(after); |
| 1770 | |
| 1771 | assert_eq!(document.selected_source_range(), Some(0..source.len())); |
| 1772 | } |
| 1773 | |
| 1774 | #[test] |
| 1775 | fn selected_source_range_excludes_an_unreached_inline_image() { |
| 1776 | let source = "before  after"; |
| 1777 | let mut cx = NodeContext::default(); |
| 1778 | let document = parse(source, &mut cx).unwrap(); |
| 1779 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1780 | panic!("expected paragraph"); |
| 1781 | }; |
| 1782 | let image = paragraph |
| 1783 | .children |
| 1784 | .iter() |
| 1785 | .find(|child| child.image.is_some()) |
| 1786 | .expect("expected image"); |
| 1787 | let mut before = image.state.lock().unwrap(); |
| 1788 | before.set_text("before ".into()); |
| 1789 | before.selection = Some((0..3).into()); |
| 1790 | drop(before); |
| 1791 | |
| 1792 | assert_eq!(document.selected_source_range(), Some(0..3)); |
| 1793 | |
| 1794 | image.state.lock().unwrap().selection = None; |
| 1795 | let after_start = source.find("after").unwrap(); |
| 1796 | let mut after = paragraph.state.lock().unwrap(); |
| 1797 | after.set_text(" after".into()); |
| 1798 | after.selection = Some((2..6).into()); |
| 1799 | drop(after); |
| 1800 | |
| 1801 | assert_eq!( |
| 1802 | document.selected_source_range(), |
| 1803 | Some(after_start + 1..source.len()) |
| 1804 | ); |
| 1805 | } |
| 1806 | |
| 1807 | #[test] |
| 1808 | fn selected_source_range_includes_consecutive_inline_images() { |
| 1809 | let source = " after"; |
| 1810 | let mut cx = NodeContext::default(); |
| 1811 | let document = parse(source, &mut cx).unwrap(); |
| 1812 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1813 | panic!("expected paragraph"); |
| 1814 | }; |
| 1815 | let mut state = paragraph.state.lock().unwrap(); |
| 1816 | state.set_text(" after".into()); |
| 1817 | state.selection = Some((0..6).into()); |
| 1818 | drop(state); |
| 1819 | |
| 1820 | assert_eq!(document.selected_source_range(), Some(0..source.len())); |
| 1821 | } |
| 1822 | |
| 1823 | #[test] |
| 1824 | fn selected_source_range_maps_decoded_entity_to_its_source_syntax() { |
| 1825 | let source = "A & B"; |
| 1826 | let mut cx = NodeContext::default(); |
| 1827 | let document = parse(source, &mut cx).unwrap(); |
| 1828 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1829 | panic!("expected paragraph"); |
| 1830 | }; |
| 1831 | assert_eq!(paragraph.text(), "A & B"); |
| 1832 | |
| 1833 | assert_eq!(selected_rendered_range(source, 2..3), Some(2..7)); |
| 1834 | } |
| 1835 | |
| 1836 | #[test] |
| 1837 | fn selected_source_range_maps_around_named_and_numeric_entities() { |
| 1838 | let source = "Copyright © 😀 © 2024"; |
| 1839 | assert_eq!(selected_rendered_range(source, 0..9), Some(0..9)); |
| 1840 | assert_eq!(selected_rendered_range(source, 10..12), Some(10..16)); |
| 1841 | assert_eq!(selected_rendered_range(source, 13..17), Some(17..26)); |
| 1842 | assert_eq!(selected_rendered_range(source, 18..20), Some(27..33)); |
| 1843 | assert_eq!(selected_rendered_range(source, 21..25), Some(34..38)); |
| 1844 | assert_eq!(selected_rendered_range(source, 8..22), Some(8..35)); |
| 1845 | } |
| 1846 | |
| 1847 | #[test] |
| 1848 | fn selected_source_range_maps_soft_breaks_with_source_prefixes() { |
| 1849 | assert_eq!(selected_rendered_range("a\n b", 0..1), Some(0..1)); |
| 1850 | assert_eq!(selected_rendered_range("a\n b", 2..3), Some(5..6)); |
| 1851 | assert_eq!(selected_rendered_range("a\n b", 0..3), Some(0..6)); |
| 1852 | |
| 1853 | assert_eq!(selected_rendered_range("> a\n> b", 0..1), Some(2..3)); |
| 1854 | assert_eq!(selected_rendered_range("> a\n> b", 2..3), Some(6..7)); |
| 1855 | assert_eq!(selected_rendered_range("> a\n> b", 0..3), Some(2..7)); |
| 1856 | |
| 1857 | assert_eq!(selected_rendered_range("- a\n b", 0..1), Some(2..3)); |
| 1858 | assert_eq!(selected_rendered_range("- a\n b", 2..3), Some(6..7)); |
| 1859 | assert_eq!(selected_rendered_range("- a\n b", 0..3), Some(2..7)); |
| 1860 | } |
| 1861 | |
| 1862 | #[test] |
| 1863 | fn selected_source_range_maps_soft_breaks_with_trailing_spaces_and_crlf() { |
| 1864 | assert_eq!(selected_rendered_range("a \nb", 0..1), Some(0..1)); |
| 1865 | assert_eq!(selected_rendered_range("a \nb", 1..2), Some(2..3)); |
| 1866 | assert_eq!(selected_rendered_range("a \nb", 2..3), Some(3..4)); |
| 1867 | assert_eq!(selected_rendered_range("a \nb", 0..3), Some(0..4)); |
| 1868 | |
| 1869 | assert_eq!(selected_rendered_range("a \r\nb", 1..2), Some(2..4)); |
| 1870 | assert_eq!(selected_rendered_range("a \r\nb", 2..3), Some(4..5)); |
| 1871 | |
| 1872 | assert_eq!(selected_rendered_range("a\r\nb", 0..1), Some(0..1)); |
| 1873 | assert_eq!(selected_rendered_range("a\r\nb", 2..3), Some(3..4)); |
| 1874 | assert_eq!(selected_rendered_range("a\r\nb", 0..3), Some(0..4)); |
| 1875 | } |
| 1876 | |
| 1877 | #[test] |
| 1878 | fn test_nested_emphasis_merges_text_marks() { |
| 1879 | let mut cx = NodeContext::default(); |
| 1880 | let document = parse("This has **_bold and italic_** text.", &mut cx).unwrap(); |
| 1881 | |
| 1882 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1883 | panic!("expected paragraph"); |
| 1884 | }; |
| 1885 | |
| 1886 | let bold_italic = paragraph |
| 1887 | .children |
| 1888 | .iter() |
| 1889 | .find(|child| child.text.as_ref() == "bold and italic") |
| 1890 | .expect("expected emphasized text"); |
| 1891 | |
| 1892 | assert!( |
| 1893 | bold_italic |
| 1894 | .marks |
| 1895 | .iter() |
| 1896 | .any(|(_, mark)| mark.bold && mark.italic), |
| 1897 | "nested emphasis should produce a bold and italic mark" |
| 1898 | ); |
| 1899 | } |
| 1900 | |
| 1901 | #[test] |
| 1902 | fn test_inline_html_image_stays_in_markdown_paragraph() { |
| 1903 | let mut cx = NodeContext::default(); |
| 1904 | let document = parse( |
| 1905 | r#"Before <img src="https://example.com/avatar.png" alt="Avatar" width="32" height="32" /> after."#, |
| 1906 | &mut cx, |
| 1907 | ) |
| 1908 | .unwrap(); |
| 1909 | |
| 1910 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1911 | panic!("expected paragraph"); |
| 1912 | }; |
| 1913 | |
| 1914 | assert_eq!(paragraph.children.len(), 3); |
| 1915 | assert_eq!(paragraph.children[0].text.as_ref(), "Before "); |
| 1916 | assert_eq!(paragraph.children[2].text.as_ref(), " after."); |
| 1917 | |
| 1918 | let image = paragraph.children[1] |
| 1919 | .image |
| 1920 | .as_ref() |
| 1921 | .expect("expected inline html image"); |
| 1922 | assert_eq!(image.url.as_ref(), "https://example.com/avatar.png"); |
| 1923 | assert_eq!(image.width, Some(gpui::px(32.).into())); |
| 1924 | assert_eq!(image.height, Some(gpui::px(32.).into())); |
| 1925 | } |
| 1926 | |
| 1927 | #[test] |
| 1928 | fn test_inline_html_image_without_size_stays_in_markdown_paragraph() { |
| 1929 | let mut cx = NodeContext::default(); |
| 1930 | let document = parse( |
| 1931 | r#"Before <img src="https://avatars.githubusercontent.com/u/5518"> after."#, |
| 1932 | &mut cx, |
| 1933 | ) |
| 1934 | .unwrap(); |
| 1935 | |
| 1936 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1937 | panic!("expected paragraph"); |
| 1938 | }; |
| 1939 | |
| 1940 | assert_eq!(paragraph.children.len(), 3); |
| 1941 | assert_eq!(paragraph.children[0].text.as_ref(), "Before "); |
| 1942 | assert_eq!(paragraph.children[2].text.as_ref(), " after."); |
| 1943 | |
| 1944 | let image = paragraph.children[1] |
| 1945 | .image |
| 1946 | .as_ref() |
| 1947 | .expect("expected inline html image"); |
| 1948 | assert_eq!( |
| 1949 | image.url.as_ref(), |
| 1950 | "https://avatars.githubusercontent.com/u/5518" |
| 1951 | ); |
| 1952 | assert_eq!(image.width, None); |
| 1953 | assert_eq!(image.height, None); |
| 1954 | } |
| 1955 | |
| 1956 | /// A CommonMark soft break — a bare line ending inside a paragraph — |
| 1957 | /// reflows to a space, so prose hard-wrapped in the source fills the |
| 1958 | /// available width instead of keeping the source's line structure. |
| 1959 | /// |
| 1960 | /// Every line ending CommonMark recognises has to collapse, not just LF: |
| 1961 | /// mdast passes the source's bytes through, so a CRLF document would |
| 1962 | /// otherwise strand its carriage return in the middle of the line. |
| 1963 | #[test] |
| 1964 | fn test_soft_break_reflows_to_space() { |
| 1965 | for source in [ |
| 1966 | "this sentence\ncontinues as a soft wrap", |
| 1967 | "this sentence\r\ncontinues as a soft wrap", |
| 1968 | "this sentence\rcontinues as a soft wrap", |
| 1969 | ] { |
| 1970 | let mut cx = NodeContext::default(); |
| 1971 | let document = parse(source, &mut cx).unwrap(); |
| 1972 | |
| 1973 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1974 | panic!("expected paragraph"); |
| 1975 | }; |
| 1976 | |
| 1977 | assert_eq!(paragraph.children.len(), 1, "source: {source:?}"); |
| 1978 | assert_eq!( |
| 1979 | paragraph.children[0].text.as_ref(), |
| 1980 | "this sentence continues as a soft wrap", |
| 1981 | "source: {source:?}" |
| 1982 | ); |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | /// The two breaks stay distinguishable in one paragraph: the soft one |
| 1987 | /// reflows into the run, the hard one keeps its own newline node. |
| 1988 | /// |
| 1989 | /// This is the invariant the soft-break collapse rests on — a hard break |
| 1990 | /// arrives as `Node::Break` and never as a newline inside `Node::Text`. |
| 1991 | #[test] |
| 1992 | fn test_soft_break_reflows_while_hard_break_survives() { |
| 1993 | let mut cx = NodeContext::default(); |
| 1994 | let document = parse("a\nb \nc", &mut cx).unwrap(); |
| 1995 | |
| 1996 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 1997 | panic!("expected paragraph"); |
| 1998 | }; |
| 1999 | |
| 2000 | let texts: Vec<_> = paragraph |
| 2001 | .children |
| 2002 | .iter() |
| 2003 | .map(|child| child.text.as_ref()) |
| 2004 | .collect(); |
| 2005 | assert_eq!(texts, ["a b", "\n", "c"]); |
| 2006 | } |
| 2007 | |
| 2008 | /// A CommonMark hard break — two trailing spaces or a trailing backslash — |
| 2009 | /// renders as a newline, instead of joining the two lines. |
| 2010 | #[test] |
| 2011 | fn test_hard_break_renders_newline() { |
| 2012 | for source in [ |
| 2013 | "Owner: Jane \nPersona: assistant", |
| 2014 | "Owner: Jane\\\nPersona: assistant", |
| 2015 | ] { |
| 2016 | let mut cx = NodeContext::default(); |
| 2017 | let document = parse(source, &mut cx).unwrap(); |
| 2018 | |
| 2019 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2020 | panic!("expected paragraph"); |
| 2021 | }; |
| 2022 | |
| 2023 | assert_eq!(paragraph.children.len(), 3, "source: {source:?}"); |
| 2024 | assert_eq!(paragraph.children[0].text.as_ref(), "Owner: Jane"); |
| 2025 | assert_eq!(paragraph.children[1].text.as_ref(), "\n"); |
| 2026 | assert_eq!(paragraph.children[2].text.as_ref(), "Persona: assistant"); |
| 2027 | } |
| 2028 | } |
| 2029 | |
| 2030 | #[test] |
| 2031 | fn yaml_frontmatter_is_disabled_by_default() { |
| 2032 | let source = "---\nSome text\n---"; |
| 2033 | let mut cx = NodeContext::default(); |
| 2034 | let document = parse(source, &mut cx).unwrap(); |
| 2035 | |
| 2036 | assert!(matches!( |
| 2037 | document.blocks[0], |
| 2038 | BlockNode::HorizontalRule { .. } |
| 2039 | )); |
| 2040 | let BlockNode::Heading { |
| 2041 | level, children, .. |
| 2042 | } = &document.blocks[1] |
| 2043 | else { |
| 2044 | panic!("expected setext heading"); |
| 2045 | }; |
| 2046 | assert_eq!(*level, 2); |
| 2047 | assert_eq!(children.text(), "Some text"); |
| 2048 | } |
| 2049 | |
| 2050 | #[test] |
| 2051 | fn non_mapping_yaml_frontmatter_falls_back_to_code_block() { |
| 2052 | let extensions = MarkdownExtensions::default().frontmatter(); |
| 2053 | let mut cx = NodeContext { |
| 2054 | markdown_extensions: extensions.into(), |
| 2055 | ..NodeContext::default() |
| 2056 | }; |
| 2057 | let document = parse("---\n- name: example\n---", &mut cx).unwrap(); |
| 2058 | |
| 2059 | let BlockNode::CodeBlock(code_block) = &document.blocks[0] else { |
| 2060 | panic!("expected YAML code block fallback"); |
| 2061 | }; |
| 2062 | assert_eq!(code_block.lang().as_deref(), Some("yml")); |
| 2063 | assert_eq!(code_block.code().as_ref(), "- name: example"); |
| 2064 | } |
| 2065 | |
| 2066 | #[test] |
| 2067 | fn fenced_yaml_remains_a_code_block() { |
| 2068 | let mut cx = NodeContext::default(); |
| 2069 | let document = parse("```yaml\nname: example\n```", &mut cx).unwrap(); |
| 2070 | |
| 2071 | let BlockNode::CodeBlock(code_block) = &document.blocks[0] else { |
| 2072 | panic!("expected fenced YAML code block"); |
| 2073 | }; |
| 2074 | assert_eq!(code_block.lang().as_deref(), Some("yaml")); |
| 2075 | assert_eq!(code_block.code().as_ref(), "name: example"); |
| 2076 | } |
| 2077 | |
| 2078 | #[derive(Debug, Clone, PartialEq)] |
| 2079 | struct Ticker { |
| 2080 | symbol: String, |
| 2081 | } |
| 2082 | |
| 2083 | fn parse_ticker_block(node: &Node, cx: &MarkdownParseContext<'_>) -> Option<MarkdownNode> { |
| 2084 | let Node::Paragraph(paragraph) = node else { |
| 2085 | return None; |
| 2086 | }; |
| 2087 | let [Node::Text(text)] = paragraph.children.as_slice() else { |
| 2088 | return None; |
| 2089 | }; |
| 2090 | let symbol = text.value.strip_prefix('$')?.to_string(); |
| 2091 | let node_text = format!("${symbol}"); |
| 2092 | |
| 2093 | Some( |
| 2094 | MarkdownNode::new("ticker", Ticker { symbol }) |
| 2095 | .text(node_text) |
| 2096 | .markdown(cx.node_source(node).unwrap_or_default()), |
| 2097 | ) |
| 2098 | } |
| 2099 | |
| 2100 | #[test] |
| 2101 | fn custom_block_parser_converts_ticker_syntax_to_custom_node() { |
| 2102 | let extensions = MarkdownExtensions::default().block_parser(parse_ticker_block); |
| 2103 | |
| 2104 | let mut cx = NodeContext { |
| 2105 | markdown_extensions: extensions.into(), |
| 2106 | ..NodeContext::default() |
| 2107 | }; |
| 2108 | let document = parse("$TSLA.US", &mut cx).unwrap(); |
| 2109 | |
| 2110 | let BlockNode::Custom(node) = &document.blocks[0] else { |
| 2111 | panic!("expected custom markdown node"); |
| 2112 | }; |
| 2113 | assert_eq!(node.name(), "ticker"); |
| 2114 | assert_eq!(node.as_text(), "$TSLA.US"); |
| 2115 | assert_eq!(node.as_markdown(), "$TSLA.US"); |
| 2116 | assert_eq!( |
| 2117 | node.data::<Ticker>(), |
| 2118 | Some(&Ticker { |
| 2119 | symbol: "TSLA.US".to_string() |
| 2120 | }) |
| 2121 | ); |
| 2122 | assert_eq!(document.text(), "$TSLA.US\n"); |
| 2123 | assert_eq!(document.to_markdown(), "$TSLA.US"); |
| 2124 | } |
| 2125 | |
| 2126 | struct TickerPlugin { |
| 2127 | name: &'static str, |
| 2128 | } |
| 2129 | |
| 2130 | #[test] |
| 2131 | fn inline_math_is_enabled_by_default_and_respects_code_and_escapes() { |
| 2132 | let extensions = MarkdownExtensions::default().plugin( |
| 2133 | crate::text::markdown_ext::TestInlinePlugin::new("formula").parse_with(|node, _| { |
| 2134 | let Node::InlineMath(math) = node else { |
| 2135 | return None; |
| 2136 | }; |
| 2137 | assert_eq!(math.value, "x"); |
| 2138 | Some(MarkdownNode::new("formula", ()).text("formula")) |
| 2139 | }), |
| 2140 | ); |
| 2141 | let mut cx = NodeContext { |
| 2142 | markdown_extensions: extensions.into(), |
| 2143 | ..Default::default() |
| 2144 | }; |
| 2145 | let document = parse(r"$x$ `$code$` \$escaped\$", &mut cx).unwrap(); |
| 2146 | assert_eq!(document.text(), "formula $code$ $escaped$\n"); |
| 2147 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2148 | panic!() |
| 2149 | }; |
| 2150 | assert_eq!( |
| 2151 | paragraph |
| 2152 | .children |
| 2153 | .iter() |
| 2154 | .filter(|node| node.custom.is_some()) |
| 2155 | .count(), |
| 2156 | 1 |
| 2157 | ); |
| 2158 | } |
| 2159 | |
| 2160 | #[test] |
| 2161 | fn inline_extensions_preserve_nodes_inside_marks_and_global_source_ranges() { |
| 2162 | let source = "中文 **before $x^2$ after** and `$ignored$`"; |
| 2163 | let extensions = MarkdownExtensions::default().plugin( |
| 2164 | crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(|node, cx| { |
| 2165 | let Node::InlineMath(math) = node else { |
| 2166 | return None; |
| 2167 | }; |
| 2168 | assert_eq!(cx.node_source(node), Some("$x^2$")); |
| 2169 | Some(MarkdownNode::new("formula", math.value.clone()).text("x²")) |
| 2170 | }), |
| 2171 | ); |
| 2172 | let mut cx = NodeContext { |
| 2173 | offset: 50, |
| 2174 | markdown_extensions: extensions.into(), |
| 2175 | ..Default::default() |
| 2176 | }; |
| 2177 | let document = parse(source, &mut cx).unwrap(); |
| 2178 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2179 | panic!() |
| 2180 | }; |
| 2181 | let objects: Vec<_> = paragraph |
| 2182 | .children |
| 2183 | .iter() |
| 2184 | .filter_map(|node| node.custom.as_ref()) |
| 2185 | .collect(); |
| 2186 | assert_eq!(objects.len(), 1); |
| 2187 | let object = objects[0]; |
| 2188 | let start = source.find("$x^2$").unwrap() + 50; |
| 2189 | assert_eq!(object.source_range(), Some(start..start + 5)); |
| 2190 | assert_eq!(object.as_text(), "x²"); |
| 2191 | assert_eq!(object.as_markdown(), "$x^2$"); |
| 2192 | assert_eq!(object.accessibility_name(), "x²"); |
| 2193 | assert_eq!(document.text(), "中文 before x² after and $ignored$\n"); |
| 2194 | assert!(document.to_markdown().contains("**before $x^2$ after**")); |
| 2195 | } |
| 2196 | |
| 2197 | #[test] |
| 2198 | fn block_math_parses_as_a_block_and_falls_back_to_a_code_block() { |
| 2199 | // `$$` is a block fence. With only the inline construct enabled it was |
| 2200 | // swallowed as one long inline formula, so a block plugin matching |
| 2201 | // `Node::Math` never fired. |
| 2202 | let source = "$$\n\\sum_{i=1}^{n} i\n$$"; |
| 2203 | let mut cx = NodeContext::default(); |
| 2204 | let document = parse(source, &mut cx).unwrap(); |
| 2205 | let BlockNode::CodeBlock(code) = &document.blocks[0] else { |
| 2206 | panic!("expected a code block fallback") |
| 2207 | }; |
| 2208 | assert_eq!(code.code(), "\\sum_{i=1}^{n} i"); |
| 2209 | assert!(document.to_markdown().contains("\\sum_{i=1}^{n} i")); |
| 2210 | } |
| 2211 | |
| 2212 | fn bold_runs(paragraph: &Paragraph) -> Vec<String> { |
| 2213 | paragraph |
| 2214 | .children |
| 2215 | .iter() |
| 2216 | .flat_map(|node| { |
| 2217 | node.marks |
| 2218 | .iter() |
| 2219 | .filter(|(_, mark)| mark.bold) |
| 2220 | .map(|(range, _)| node.text[range.clone()].to_string()) |
| 2221 | .collect::<Vec<_>>() |
| 2222 | }) |
| 2223 | .collect() |
| 2224 | } |
| 2225 | |
| 2226 | #[test] |
| 2227 | fn unclaimed_inline_math_parses_its_span_as_prose() { |
| 2228 | // Two dollar amounts pair up into an unclaimed math span. What lies |
| 2229 | // between them is ordinary prose: inline HTML there must still pair |
| 2230 | // with the tags outside the span, and emphasis inside it must render. |
| 2231 | let source = |
| 2232 | "EPS of <strong>$1.56</strong> beat the <strong>$1.50</strong> consensus, *up $2*"; |
| 2233 | let mut cx = NodeContext::default(); |
| 2234 | let document = parse(source, &mut cx).unwrap(); |
| 2235 | assert_eq!( |
| 2236 | document.text(), |
| 2237 | "EPS of $1.56 beat the $1.50 consensus, up $2\n" |
| 2238 | ); |
| 2239 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2240 | panic!() |
| 2241 | }; |
| 2242 | assert_eq!(bold_runs(paragraph), ["$1.56", "$1.50"]); |
| 2243 | assert!(paragraph.children.iter().any(|node| { |
| 2244 | node.marks |
| 2245 | .iter() |
| 2246 | .any(|(range, mark)| mark.italic && node.text[range.clone()] == *"up $2") |
| 2247 | })); |
| 2248 | assert!(document.to_markdown().contains("$1.56")); |
| 2249 | } |
| 2250 | |
| 2251 | #[test] |
| 2252 | fn claimed_inline_math_survives_prose_flattening() { |
| 2253 | let extensions = MarkdownExtensions::default().plugin( |
| 2254 | crate::text::markdown_ext::TestInlinePlugin::new("formula").parse_with(|node, _| { |
| 2255 | let Node::InlineMath(math) = node else { |
| 2256 | return None; |
| 2257 | }; |
| 2258 | Some(MarkdownNode::new("formula", ()).text(format!("[{}]", math.value))) |
| 2259 | }), |
| 2260 | ); |
| 2261 | let mut cx = NodeContext { |
| 2262 | markdown_extensions: extensions.into(), |
| 2263 | ..Default::default() |
| 2264 | }; |
| 2265 | let document = parse("area $x^2$ costs $5 and $10", &mut cx).unwrap(); |
| 2266 | assert_eq!(document.text(), "area [x^2] costs [5 and ]10\n"); |
| 2267 | } |
| 2268 | |
| 2269 | #[test] |
| 2270 | fn inline_html_formatting_tags_pair_across_siblings() { |
| 2271 | let source = "a <strong>b *c* <em>d</em></strong> e <b>f</b> <i>g</i> <del>h</del> <br> <strong>unclosed"; |
| 2272 | let mut cx = NodeContext::default(); |
| 2273 | let document = parse(source, &mut cx).unwrap(); |
| 2274 | assert_eq!(document.text(), "a b c d e f g h \n unclosed\n"); |
| 2275 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2276 | panic!() |
| 2277 | }; |
| 2278 | assert_eq!(bold_runs(paragraph), ["b c d", "f"]); |
| 2279 | let marked = |predicate: fn(&TextMark) -> bool| -> Vec<String> { |
| 2280 | paragraph |
| 2281 | .children |
| 2282 | .iter() |
| 2283 | .flat_map(|node| { |
| 2284 | node.marks |
| 2285 | .iter() |
| 2286 | .filter(|(_, mark)| predicate(mark)) |
| 2287 | .map(|(range, _)| node.text[range.clone()].to_string()) |
| 2288 | .collect::<Vec<_>>() |
| 2289 | }) |
| 2290 | .collect() |
| 2291 | }; |
| 2292 | assert_eq!(marked(|mark| mark.italic), ["c", "d", "g"]); |
| 2293 | assert_eq!(marked(|mark| mark.strikethrough), ["h"]); |
| 2294 | } |
| 2295 | |
| 2296 | #[test] |
| 2297 | fn unclaimed_inline_math_keeps_its_literal_source() { |
| 2298 | // Math parsing is on by default, so prose that merely contains dollar |
| 2299 | // signs parses as a math node. With no plugin to render it, the text |
| 2300 | // must survive display and a Markdown round trip untouched. |
| 2301 | let source = "spent $5 and $10 today"; |
| 2302 | let mut cx = NodeContext::default(); |
| 2303 | let document = parse(source, &mut cx).unwrap(); |
| 2304 | assert_eq!(document.text(), "spent $5 and $10 today\n"); |
| 2305 | assert!(document.to_markdown().contains("spent $5 and $10 today")); |
| 2306 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2307 | panic!() |
| 2308 | }; |
| 2309 | assert!(paragraph.children.iter().all(|node| node.custom.is_none())); |
| 2310 | } |
| 2311 | |
| 2312 | #[test] |
| 2313 | fn inline_object_markdown_roundtrip_preserves_nested_emphasis() { |
| 2314 | for source in [ |
| 2315 | "*before $x$ after*", |
| 2316 | "*before **$x$** after*", |
| 2317 | "**before *$x$* after**", |
| 2318 | ] { |
| 2319 | let mut cx = NodeContext { |
| 2320 | markdown_extensions: MarkdownExtensions::default() |
| 2321 | .plugin( |
| 2322 | crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with( |
| 2323 | |node, _| match node { |
| 2324 | Node::InlineMath(math) => { |
| 2325 | Some(MarkdownNode::new("math", ()).text(math.value.clone())) |
| 2326 | } |
| 2327 | _ => None, |
| 2328 | }, |
| 2329 | ), |
| 2330 | ) |
| 2331 | .into(), |
| 2332 | ..Default::default() |
| 2333 | }; |
| 2334 | let original = parse(source, &mut cx).unwrap(); |
| 2335 | let markdown = original.to_markdown(); |
| 2336 | let reparsed = parse(&markdown, &mut cx).unwrap(); |
| 2337 | let BlockNode::Paragraph(before) = &original.blocks[0] else { |
| 2338 | panic!() |
| 2339 | }; |
| 2340 | let BlockNode::Paragraph(after) = &reparsed.blocks[0] else { |
| 2341 | panic!() |
| 2342 | }; |
| 2343 | let before_object = before |
| 2344 | .children |
| 2345 | .iter() |
| 2346 | .find(|node| node.custom.is_some()) |
| 2347 | .unwrap(); |
| 2348 | let after_object = after |
| 2349 | .children |
| 2350 | .iter() |
| 2351 | .find(|node| node.custom.is_some()) |
| 2352 | .unwrap(); |
| 2353 | assert_eq!(before.text(), after.text(), "{source} -> {markdown}"); |
| 2354 | assert_eq!( |
| 2355 | before_object.marks, after_object.marks, |
| 2356 | "{source} -> {markdown}" |
| 2357 | ); |
| 2358 | } |
| 2359 | } |
| 2360 | |
| 2361 | #[test] |
| 2362 | fn inline_parser_without_metadata_falls_back_to_original_source() { |
| 2363 | let mut cx = NodeContext { |
| 2364 | markdown_extensions: MarkdownExtensions::default() |
| 2365 | .plugin( |
| 2366 | crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with( |
| 2367 | |node, _| { |
| 2368 | matches!(node, Node::InlineCode(_)) |
| 2369 | .then(|| MarkdownNode::new("opaque", ())) |
| 2370 | }, |
| 2371 | ), |
| 2372 | ) |
| 2373 | .into(), |
| 2374 | ..Default::default() |
| 2375 | }; |
| 2376 | let document = parse("`原子`", &mut cx).unwrap(); |
| 2377 | let BlockNode::Paragraph(paragraph) = &document.blocks[0] else { |
| 2378 | panic!() |
| 2379 | }; |
| 2380 | let node = paragraph.children[0].custom.as_ref().unwrap(); |
| 2381 | assert_eq!(node.as_text(), "`原子`"); |
| 2382 | assert_eq!(node.as_markdown(), "`原子`"); |
| 2383 | assert_eq!(node.accessibility_name(), "`原子`"); |
| 2384 | } |
| 2385 | |
| 2386 | impl TickerPlugin { |
| 2387 | fn new(name: &'static str) -> Self { |
| 2388 | Self { name } |
| 2389 | } |
| 2390 | } |
| 2391 | |
| 2392 | impl MarkdownPlugin for TickerPlugin { |
| 2393 | fn is_block(&self) -> bool { |
| 2394 | true |
| 2395 | } |
| 2396 | |
| 2397 | fn name(&self) -> &str { |
| 2398 | self.name |
| 2399 | } |
| 2400 | |
| 2401 | fn parse(&self, node: &Node, cx: &MarkdownParseContext<'_>) -> Option<MarkdownNode> { |
| 2402 | parse_ticker_block(node, cx) |
| 2403 | } |
| 2404 | |
| 2405 | fn render( |
| 2406 | &self, |
| 2407 | node: &MarkdownNode, |
| 2408 | _window: &mut gpui::Window, |
| 2409 | _cx: &mut gpui::App, |
| 2410 | ) -> impl gpui::IntoElement { |
| 2411 | gpui::div().child(node.as_text().to_string()) |
| 2412 | } |
| 2413 | } |
| 2414 | |
| 2415 | #[test] |
| 2416 | fn custom_block_plugin_registers_parser_and_renderer() { |
| 2417 | let extensions = MarkdownExtensions::default().plugin(TickerPlugin::new("ticker")); |
| 2418 | |
| 2419 | let mut cx = NodeContext { |
| 2420 | markdown_extensions: extensions.into(), |
| 2421 | ..NodeContext::default() |
| 2422 | }; |
| 2423 | let document = parse("$TSLA.US", &mut cx).unwrap(); |
| 2424 | |
| 2425 | let BlockNode::Custom(node) = &document.blocks[0] else { |
| 2426 | panic!("expected custom markdown node"); |
| 2427 | }; |
| 2428 | assert_eq!(node.name(), "ticker"); |
| 2429 | assert_eq!( |
| 2430 | node.data::<Ticker>(), |
| 2431 | Some(&Ticker { |
| 2432 | symbol: "TSLA.US".to_string() |
| 2433 | }) |
| 2434 | ); |
| 2435 | } |
| 2436 | } |