| 1 | //! Markdown rendering for TUI transcript lines. |
| 2 | //! |
| 3 | //! ## Width-independent parse vs width-dependent render (CX#6) |
| 4 | //! |
| 5 | //! The previous renderer was a single function `render_markdown(content, width)` |
| 6 | //! that scanned the source, classified each line (heading / list / code-fence / |
| 7 | //! paragraph / link), and word-wrapped to `Line<'static>` in one pass. That meant |
| 8 | //! every terminal resize forced a full re-parse of the source for every visible |
| 9 | //! cell — wasted work on the streaming cell whose content is changing anyway. |
| 10 | //! |
| 11 | //! The codex tui solves this by splitting parse from render. We mirror that: |
| 12 | //! |
| 13 | //! * [`parse`] turns the markdown source into a [`ParsedMarkdown`] AST: a vector |
| 14 | //! of width-independent [`Block`]s. The block kind already records all the |
| 15 | //! classification decisions (heading level, list bullet, code block membership) |
| 16 | //! that don't depend on width. |
| 17 | //! * `render_parsed` takes a `ParsedMarkdown` plus a width and a base style and |
| 18 | //! produces `Vec<Line<'static>>`. It only does word-wrap and span styling. |
| 19 | //! |
| 20 | //! The transcript cache layer (see `tui/transcript.rs`) caches the parsed AST per |
| 21 | //! cell and re-runs only the render step on width changes. That makes resize a |
| 22 | //! re-flow operation rather than a re-parse + re-flow operation. |
| 23 | |
| 24 | use std::borrow::Cow; |
| 25 | #[cfg(any(test, feature = "test-support"))] |
| 26 | use std::cell::Cell; |
| 27 | use std::cell::RefCell; |
| 28 | use std::sync::OnceLock; |
| 29 | |
| 30 | use ratatui::style::{Color, Modifier, Style}; |
| 31 | use ratatui::text::{Line, Span}; |
| 32 | use syntect::easy::HighlightLines; |
| 33 | use syntect::highlighting::{FontStyle, HighlightState, Theme, ThemeSet}; |
| 34 | use syntect::parsing::{ParseState as SyntectParseState, SyntaxSet}; |
| 35 | use unicode_segmentation::UnicodeSegmentation; |
| 36 | use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; |
| 37 | |
| 38 | use crate::osc8; |
| 39 | use crate::ui_text::CopyLineSeparator; |
| 40 | use codewhale_palette as palette; |
| 41 | |
| 42 | // Thread-local counter incremented every time `parse` runs. Used by tests to |
| 43 | // prove that width-only changes hit the cached-AST path and skip parsing. |
| 44 | // Thread-local (not global atomic) so concurrent tests calling `parse()` can't |
| 45 | // pollute each other's counters. |
| 46 | #[cfg(any(test, feature = "test-support"))] |
| 47 | thread_local! { |
| 48 | static PARSE_INVOCATIONS: Cell<u64> = const { Cell::new(0) }; |
| 49 | } |
| 50 | |
| 51 | #[cfg(any(test, feature = "test-support"))] |
| 52 | #[must_use] |
| 53 | pub fn parse_invocation_count() -> u64 { |
| 54 | PARSE_INVOCATIONS.with(|c| c.get()) |
| 55 | } |
| 56 | |
| 57 | #[cfg(any(test, feature = "test-support"))] |
| 58 | pub fn reset_parse_invocation_count() { |
| 59 | PARSE_INVOCATIONS.with(|c| c.set(0)); |
| 60 | } |
| 61 | |
| 62 | /// One classified line of markdown source, width-independent. |
| 63 | /// |
| 64 | /// All decisions that depend only on the source text (heading level, bullet |
| 65 | /// kind, whether we're inside a fenced code block, paragraph text) are made at |
| 66 | /// parse time. Width-dependent layout (word-wrap, prefix indent) is deferred to |
| 67 | /// the render step. |
| 68 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 69 | pub enum Block { |
| 70 | /// `# heading text`. Includes the heading level (1..6). |
| 71 | Heading { level: usize, text: String }, |
| 72 | /// A horizontal rule emitted under a level-1 heading. |
| 73 | HeadingRule, |
| 74 | /// A standalone `---` / `***` / `___` horizontal rule. |
| 75 | HorizontalRule, |
| 76 | /// A bullet (`-`/`*`) or ordered (`1.`) list item with its source |
| 77 | /// indent, prefix and body. |
| 78 | ListItem { |
| 79 | indent: usize, |
| 80 | bullet: String, |
| 81 | text: String, |
| 82 | }, |
| 83 | /// A `>` quote line with its nesting depth (1 = single `>`). The text has |
| 84 | /// the quote markers stripped; depth is capped at `MAX_QUOTE_DEPTH`. |
| 85 | Quote { depth: usize, text: String }, |
| 86 | /// A line inside a fenced code block. Fences themselves are dropped, but |
| 87 | /// their language token and block identity stay available to syntect. |
| 88 | Code { |
| 89 | line: String, |
| 90 | language: Option<String>, |
| 91 | block_id: usize, |
| 92 | }, |
| 93 | /// A table row: cells split on `|`. |
| 94 | TableRow(Vec<String>), |
| 95 | /// A table separator row (`|---|---|`). Kept so the renderer can draw |
| 96 | /// horizontal rules at the correct positions. |
| 97 | TableSeparator, |
| 98 | /// A non-empty paragraph line that may contain inline links. |
| 99 | Paragraph { text: String }, |
| 100 | /// An empty source line, preserved so paragraph spacing survives. |
| 101 | Blank, |
| 102 | } |
| 103 | |
| 104 | /// Width-independent parsed-markdown AST for one cell's source. |
| 105 | /// |
| 106 | /// Wrapped in `Arc` at the cache layer so the cache can hand the same AST to |
| 107 | /// many render calls without copying. |
| 108 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 109 | pub struct ParsedMarkdown { |
| 110 | blocks: Vec<Block>, |
| 111 | } |
| 112 | |
| 113 | /// Width-dependent rendered line plus the source block kind that produced it. |
| 114 | /// |
| 115 | /// Most callers only need styled terminal lines, but transcript rendering also |
| 116 | /// needs to avoid adding its conversational continuation rail in front of code |
| 117 | /// blocks. Keeping this metadata here avoids guessing from styled spans. |
| 118 | #[derive(Debug, Clone)] |
| 119 | pub struct RenderedMarkdownLine { |
| 120 | pub line: Line<'static>, |
| 121 | /// Hyperlinks aligned to display columns in `line`. Targets stay |
| 122 | /// out-of-band; `Span::content` always contains visible text only. |
| 123 | pub links: Vec<osc8::LineLink>, |
| 124 | pub is_code: bool, |
| 125 | pub copy_prefix_width: usize, |
| 126 | pub copy_separator_after: CopyLineSeparator, |
| 127 | } |
| 128 | |
| 129 | static SYNTAX_SET: OnceLock<SyntaxSet> = OnceLock::new(); |
| 130 | static THEME_SET: OnceLock<ThemeSet> = OnceLock::new(); |
| 131 | static COLOR_DEPTH: OnceLock<palette::ColorDepth> = OnceLock::new(); |
| 132 | static PALETTE_MODE: OnceLock<palette::PaletteMode> = OnceLock::new(); |
| 133 | |
| 134 | fn syntax_set() -> &'static SyntaxSet { |
| 135 | SYNTAX_SET.get_or_init(SyntaxSet::load_defaults_newlines) |
| 136 | } |
| 137 | |
| 138 | fn theme_set() -> &'static ThemeSet { |
| 139 | THEME_SET.get_or_init(ThemeSet::load_defaults) |
| 140 | } |
| 141 | |
| 142 | /// Load the syntect syntax and theme sets ahead of the first fenced code |
| 143 | /// block, so that render does not pay the one-time deserialization cost. |
| 144 | /// Idempotent; intended to run once on a background thread at TUI boot. |
| 145 | pub fn prewarm_syntax_highlighting() { |
| 146 | let _ = syntax_set(); |
| 147 | let _ = theme_set(); |
| 148 | } |
| 149 | |
| 150 | fn syntax_color_depth() -> palette::ColorDepth { |
| 151 | *COLOR_DEPTH.get_or_init(palette::ColorDepth::detect) |
| 152 | } |
| 153 | |
| 154 | pub fn detected_palette_mode() -> palette::PaletteMode { |
| 155 | *PALETTE_MODE.get_or_init(palette::PaletteMode::detect) |
| 156 | } |
| 157 | |
| 158 | /// Parse markdown source into a width-independent block AST. |
| 159 | /// |
| 160 | /// This is a small line-oriented parser tuned for the patterns we render: |
| 161 | /// fenced code blocks, ATX headings, dash/star/numbered list items, and plain |
| 162 | /// paragraphs with optional links. It does not attempt to handle every CommonMark |
| 163 | /// edge case — that's intentional. The renderer will treat anything we don't |
| 164 | /// classify as `Block::Paragraph`. |
| 165 | #[must_use] |
| 166 | pub fn parse(content: &str) -> ParsedMarkdown { |
| 167 | #[cfg(any(test, feature = "test-support"))] |
| 168 | PARSE_INVOCATIONS.with(|c| c.set(c.get() + 1)); |
| 169 | |
| 170 | STREAM_PARSE_MEMO.with(|memo| { |
| 171 | let mut memo = memo.borrow_mut(); |
| 172 | // Reuse the committed prefix when this call continues the same source |
| 173 | // (the streaming case). Anything else — a different cell, a shrunk |
| 174 | // buffer, an edit to earlier bytes — fails the check and starts clean. |
| 175 | let state = memo.get_or_insert_with(ParseState::default); |
| 176 | if !state.can_resume_from(content) { |
| 177 | *state = ParseState::default(); |
| 178 | } |
| 179 | state.commit_complete_lines(content); |
| 180 | let parsed = state.snapshot(content); |
| 181 | // Don't hold a whole large message alive between unrelated renders. |
| 182 | if state.consumed > MAX_MEMOIZED_PREFIX_BYTES { |
| 183 | *state = ParseState::default(); |
| 184 | } |
| 185 | parsed |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | /// Upper bound on the source we keep memoized between `parse` calls. Streaming |
| 190 | /// messages are the reason this exists; past this size the memory cost of |
| 191 | /// holding the prefix outweighs the re-parse it saves. |
| 192 | const MAX_MEMOIZED_PREFIX_BYTES: usize = 1024 * 1024; |
| 193 | |
| 194 | thread_local! { |
| 195 | /// Single-entry resume memo for the streaming re-parse (#3897). |
| 196 | /// |
| 197 | /// Deliberately one entry and thread-local: the hot path is one cell |
| 198 | /// growing chunk by chunk on the render thread. A miss costs exactly what |
| 199 | /// the old code always paid, so this can only make things faster or |
| 200 | /// identical — never wrong, because [`ParseState::can_resume_from`] |
| 201 | /// verifies the prefix byte-for-byte before reusing anything. |
| 202 | static STREAM_PARSE_MEMO: RefCell<Option<ParseState>> = const { RefCell::new(None) }; |
| 203 | } |
| 204 | |
| 205 | /// Resumable parser state. |
| 206 | /// |
| 207 | /// The parser is strictly line-oriented: each source line maps to blocks using |
| 208 | /// only a four-field carry (`open_fence`, `code_language`, |
| 209 | /// `code_block_id`, `in_list`). That is what makes resuming *exact* rather than |
| 210 | /// approximate — appending text can never change how an earlier complete line |
| 211 | /// parsed, so committed blocks never need revisiting. |
| 212 | /// |
| 213 | /// Streaming is the case that matters (#3897): the renderer re-parses the whole |
| 214 | /// growing message on every chunk, which is quadratic over message length. |
| 215 | #[derive(Debug, Clone, Default)] |
| 216 | pub struct ParseState { |
| 217 | blocks: Vec<Block>, |
| 218 | /// The exact source bytes already folded into `blocks`. Kept verbatim so |
| 219 | /// resumption is *verified* against the new content rather than assumed — |
| 220 | /// a caller that hands over unrelated text gets a full re-parse, not |
| 221 | /// silently wrong output. |
| 222 | prefix: String, |
| 223 | /// FNV-1a digest of every byte committed since the last reset. The live |
| 224 | /// incremental cache drops `prefix` to bound memory, so the |
| 225 | /// verified-append resume path compares this digest against the incoming |
| 226 | /// content instead of retaining a second copy of the source. |
| 227 | committed_digest: u64, |
| 228 | /// Length of `prefix`. Always ends just past a newline, so only whole |
| 229 | /// lines are ever committed. |
| 230 | consumed: usize, |
| 231 | /// Character (backtick or tilde) and length of the opening code fence |
| 232 | /// while inside a fenced code block (`None` outside). A closing fence must |
| 233 | /// use the same character and be at least this long per CommonMark; |
| 234 | /// shorter fence lines and fences of the other character are code content. |
| 235 | open_fence: Option<(char, usize)>, |
| 236 | code_language: Option<String>, |
| 237 | code_block_id: usize, |
| 238 | in_list: bool, |
| 239 | } |
| 240 | |
| 241 | impl ParseState { |
| 242 | /// Fold every *complete* line after `consumed` into `blocks`. |
| 243 | /// |
| 244 | /// The trailing partial line is deliberately left uncommitted: streaming |
| 245 | /// can still extend it, and committing it early would be the one way this |
| 246 | /// could diverge from a full re-parse. |
| 247 | fn commit_complete_lines(&mut self, content: &str) { |
| 248 | let Some(rest) = content.get(self.consumed..) else { |
| 249 | return; |
| 250 | }; |
| 251 | let Some(last_newline) = rest.rfind('\n') else { |
| 252 | return; |
| 253 | }; |
| 254 | let complete = &rest[..=last_newline]; |
| 255 | for raw_line in complete.lines() { |
| 256 | push_parsed_line( |
| 257 | raw_line, |
| 258 | &mut self.blocks, |
| 259 | &mut self.open_fence, |
| 260 | &mut self.code_language, |
| 261 | &mut self.code_block_id, |
| 262 | &mut self.in_list, |
| 263 | ); |
| 264 | } |
| 265 | let mut digest = if self.consumed == 0 { |
| 266 | committed_prefix_digest(&[]) |
| 267 | } else { |
| 268 | self.committed_digest |
| 269 | }; |
| 270 | for &byte in complete.as_bytes() { |
| 271 | digest ^= u64::from(byte); |
| 272 | digest = digest.wrapping_mul(FNV_1A_PRIME); |
| 273 | } |
| 274 | self.committed_digest = digest; |
| 275 | self.prefix.push_str(complete); |
| 276 | self.consumed += complete.len(); |
| 277 | } |
| 278 | |
| 279 | /// The full AST: committed blocks plus the trailing partial line, parsed |
| 280 | /// against a throwaway copy of the carry so `self` stays resumable. |
| 281 | fn snapshot(&self, content: &str) -> ParsedMarkdown { |
| 282 | let tail = content.get(self.consumed..).unwrap_or_default(); |
| 283 | if tail.is_empty() { |
| 284 | return ParsedMarkdown { |
| 285 | blocks: self.blocks.clone(), |
| 286 | }; |
| 287 | } |
| 288 | let mut blocks = self.blocks.clone(); |
| 289 | let mut open_fence = self.open_fence; |
| 290 | let mut code_language = self.code_language.clone(); |
| 291 | let mut code_block_id = self.code_block_id; |
| 292 | let mut in_list = self.in_list; |
| 293 | for raw_line in tail.lines() { |
| 294 | push_parsed_line( |
| 295 | raw_line, |
| 296 | &mut blocks, |
| 297 | &mut open_fence, |
| 298 | &mut code_language, |
| 299 | &mut code_block_id, |
| 300 | &mut in_list, |
| 301 | ); |
| 302 | } |
| 303 | ParsedMarkdown { blocks } |
| 304 | } |
| 305 | |
| 306 | /// True when `content` still starts with everything already committed. |
| 307 | /// |
| 308 | /// Streaming only ever appends, so this is the common case. An edit that |
| 309 | /// rewrites earlier bytes (a re-render of a different cell, a retry) fails |
| 310 | /// here and the caller falls back to a full parse — correctness never |
| 311 | /// depends on the caller guessing right. |
| 312 | fn can_resume_from(&self, content: &str) -> bool { |
| 313 | content.len() >= self.consumed |
| 314 | && content.is_char_boundary(self.consumed) |
| 315 | && self.committed_prefix_matches(content) |
| 316 | } |
| 317 | |
| 318 | /// Resume after the caller has proved that the raw source mutation was an |
| 319 | /// append. The live transcript obtains that proof at the `push_str` seam. |
| 320 | /// |
| 321 | /// The receipt covers the *raw* stream, but this cache consumes the |
| 322 | /// latex-rendered projection of it, and a math block that closes late |
| 323 | /// rewrites already-committed bytes: an open `\[` is committed as literal |
| 324 | /// text and only becomes its rendered form once the closing `\]` arrives |
| 325 | /// (#6196). A length check cannot see that rewrite, so the committed |
| 326 | /// prefix is verified by digest. FNV-1a over hot cache lines costs orders |
| 327 | /// of magnitude less per beat than the render it guards, while retaining |
| 328 | /// the prefix itself would pin the whole message in memory. |
| 329 | fn can_resume_verified_append(&self, content: &str) -> bool { |
| 330 | content.len() >= self.consumed |
| 331 | && content.is_char_boundary(self.consumed) |
| 332 | && self.committed_digest |
| 333 | == committed_prefix_digest(&content.as_bytes()[..self.consumed]) |
| 334 | } |
| 335 | |
| 336 | fn committed_prefix_matches(&self, content: &str) -> bool { |
| 337 | self.prefix == content[..self.consumed] |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | /// FNV-1a constants. Chosen for speed and zero dependencies: the |
| 342 | /// verified-append resume check hashes the whole committed prefix on every |
| 343 | /// streaming beat, so the guard must stay far below the render cost it |
| 344 | /// protects. |
| 345 | const FNV_1A_PRIME: u64 = 0x0000_0100_0000_01b3; |
| 346 | |
| 347 | fn committed_prefix_digest(bytes: &[u8]) -> u64 { |
| 348 | const FNV_1A_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; |
| 349 | let mut digest = FNV_1A_OFFSET_BASIS; |
| 350 | for &byte in bytes { |
| 351 | digest ^= u64::from(byte); |
| 352 | digest = digest.wrapping_mul(FNV_1A_PRIME); |
| 353 | } |
| 354 | digest |
| 355 | } |
| 356 | |
| 357 | /// Deterministic work receipts for the live incremental renderer. |
| 358 | /// |
| 359 | /// These count source lines classified and stable/tail blocks rendered. They |
| 360 | /// deliberately do not use wall-clock time, allocator counters, or sampling, |
| 361 | /// so regression tests are stable on every machine. |
| 362 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 363 | pub struct MarkdownRenderWork { |
| 364 | pub classified_lines: u64, |
| 365 | pub stable_blocks_rendered: u64, |
| 366 | pub tail_blocks_rendered: u64, |
| 367 | pub invalidations: u64, |
| 368 | } |
| 369 | |
| 370 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 371 | struct IncrementalRenderKey { |
| 372 | width: u16, |
| 373 | base_style: Style, |
| 374 | palette_mode: palette::PaletteMode, |
| 375 | } |
| 376 | |
| 377 | #[derive(Debug, Clone)] |
| 378 | struct IncrementalCodeHighlighter { |
| 379 | block_id: usize, |
| 380 | language: Option<String>, |
| 381 | state: Option<(HighlightState, SyntectParseState)>, |
| 382 | } |
| 383 | |
| 384 | /// Persistent state for the one changing Markdown cell in the transcript. |
| 385 | /// |
| 386 | /// Stable rendered lines live in the owning `CachedCell`; this object retains |
| 387 | /// only parser/highlighter carry plus the line index at which its replaceable |
| 388 | /// tail begins. That lets each append truncate and replace the old tail without |
| 389 | /// cloning or re-rendering the committed prefix. |
| 390 | #[derive(Debug, Default)] |
| 391 | pub struct IncrementalMarkdownRenderCache { |
| 392 | parser: ParseState, |
| 393 | key: Option<IncrementalRenderKey>, |
| 394 | source_len: usize, |
| 395 | stable_rendered_line_count: usize, |
| 396 | code_highlighter: Option<IncrementalCodeHighlighter>, |
| 397 | work: MarkdownRenderWork, |
| 398 | } |
| 399 | |
| 400 | pub struct IncrementalMarkdownRenderDelta { |
| 401 | pub replace_from: usize, |
| 402 | pub lines: Vec<RenderedMarkdownLine>, |
| 403 | } |
| 404 | |
| 405 | impl IncrementalMarkdownRenderCache { |
| 406 | #[cfg(any(test, feature = "test-support"))] |
| 407 | #[must_use] |
| 408 | pub fn work(&self) -> MarkdownRenderWork { |
| 409 | self.work |
| 410 | } |
| 411 | |
| 412 | #[cfg(test)] |
| 413 | #[must_use] |
| 414 | pub fn retained_source_bytes(&self) -> usize { |
| 415 | self.parser.prefix.len() |
| 416 | } |
| 417 | |
| 418 | /// Update from a source mutation whose append-only provenance was recorded |
| 419 | /// by the live event loop. `verified_append` must be false for edits, |
| 420 | /// replacement text, cell reuse, or any unknown mutation. |
| 421 | pub fn update( |
| 422 | &mut self, |
| 423 | content: &str, |
| 424 | width: u16, |
| 425 | base_style: Style, |
| 426 | palette_mode: palette::PaletteMode, |
| 427 | verified_append: bool, |
| 428 | ) -> IncrementalMarkdownRenderDelta { |
| 429 | let key = IncrementalRenderKey { |
| 430 | width: width.max(1), |
| 431 | base_style, |
| 432 | palette_mode, |
| 433 | }; |
| 434 | |
| 435 | let can_resume = self.key == Some(key) |
| 436 | && verified_append |
| 437 | && content.len() >= self.source_len |
| 438 | && self.parser.can_resume_verified_append(content); |
| 439 | let replace_from = if can_resume { |
| 440 | self.stable_rendered_line_count |
| 441 | } else { |
| 442 | self.reset_for_invalidation(); |
| 443 | self.work.invalidations = self.work.invalidations.saturating_add(1); |
| 444 | 0 |
| 445 | }; |
| 446 | self.key = Some(key); |
| 447 | |
| 448 | let before_consumed = self.parser.consumed; |
| 449 | self.parser.commit_complete_lines(content); |
| 450 | self.work.classified_lines = self.work.classified_lines.saturating_add( |
| 451 | content[before_consumed..self.parser.consumed] |
| 452 | .lines() |
| 453 | .count() as u64, |
| 454 | ); |
| 455 | self.source_len = content.len(); |
| 456 | // Append provenance is carried by the event-loop receipt, so the live |
| 457 | // cache does not need a second copy of already committed source. The |
| 458 | // absolute byte offset and parser carry are enough to resume. |
| 459 | self.parser.prefix.clear(); |
| 460 | |
| 461 | let stable_end = stable_block_prefix_len(&self.parser.blocks); |
| 462 | let mut lines = self.render_stable_prefix(stable_end, key); |
| 463 | self.stable_rendered_line_count = |
| 464 | self.stable_rendered_line_count.saturating_add(lines.len()); |
| 465 | |
| 466 | let mut tail_blocks = self.parser.blocks.clone(); |
| 467 | tail_blocks.extend(self.parser.snapshot_tail(content)); |
| 468 | if !tail_blocks.is_empty() { |
| 469 | self.work.tail_blocks_rendered = self |
| 470 | .work |
| 471 | .tail_blocks_rendered |
| 472 | .saturating_add(tail_blocks.len() as u64); |
| 473 | let mut tail_highlighter = self.code_highlighter.clone(); |
| 474 | lines.extend(render_incremental_blocks( |
| 475 | &tail_blocks, |
| 476 | key, |
| 477 | &mut tail_highlighter, |
| 478 | )); |
| 479 | } |
| 480 | |
| 481 | if lines.is_empty() && self.stable_rendered_line_count == 0 { |
| 482 | lines.push(empty_rendered_markdown_line()); |
| 483 | } |
| 484 | |
| 485 | IncrementalMarkdownRenderDelta { |
| 486 | replace_from, |
| 487 | lines, |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | fn render_stable_prefix( |
| 492 | &mut self, |
| 493 | end: usize, |
| 494 | key: IncrementalRenderKey, |
| 495 | ) -> Vec<RenderedMarkdownLine> { |
| 496 | if end == 0 { |
| 497 | return Vec::new(); |
| 498 | } |
| 499 | self.work.stable_blocks_rendered = |
| 500 | self.work.stable_blocks_rendered.saturating_add(end as u64); |
| 501 | let lines = |
| 502 | render_incremental_blocks(&self.parser.blocks[..end], key, &mut self.code_highlighter); |
| 503 | self.parser.blocks.drain(..end); |
| 504 | lines |
| 505 | } |
| 506 | |
| 507 | fn reset_for_invalidation(&mut self) { |
| 508 | self.parser = ParseState::default(); |
| 509 | self.key = None; |
| 510 | self.source_len = 0; |
| 511 | self.stable_rendered_line_count = 0; |
| 512 | self.code_highlighter = None; |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | impl ParseState { |
| 517 | fn snapshot_tail(&self, content: &str) -> Vec<Block> { |
| 518 | let tail = content.get(self.consumed..).unwrap_or_default(); |
| 519 | let mut blocks = Vec::new(); |
| 520 | let mut open_fence = self.open_fence; |
| 521 | let mut code_language = self.code_language.clone(); |
| 522 | let mut code_block_id = self.code_block_id; |
| 523 | let mut in_list = self.in_list; |
| 524 | for raw_line in tail.lines() { |
| 525 | push_parsed_line( |
| 526 | raw_line, |
| 527 | &mut blocks, |
| 528 | &mut open_fence, |
| 529 | &mut code_language, |
| 530 | &mut code_block_id, |
| 531 | &mut in_list, |
| 532 | ); |
| 533 | } |
| 534 | blocks |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | fn stable_block_prefix_len(blocks: &[Block]) -> usize { |
| 539 | let Some(last_non_table) = blocks |
| 540 | .iter() |
| 541 | .rposition(|block| !matches!(block, Block::TableRow(_) | Block::TableSeparator)) |
| 542 | else { |
| 543 | return 0; |
| 544 | }; |
| 545 | if last_non_table + 1 == blocks.len() { |
| 546 | blocks.len() |
| 547 | } else { |
| 548 | last_non_table + 1 |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | /// Classify one source line into blocks, advancing the fenced-code carry. |
| 553 | /// |
| 554 | /// Extracted from the original loop body unchanged so the batch and streaming |
| 555 | /// paths cannot drift: both call exactly this. |
| 556 | fn expand_tabs(line: &str) -> Cow<'_, str> { |
| 557 | if !line.contains('\t') { |
| 558 | return Cow::Borrowed(line); |
| 559 | } |
| 560 | let mut expanded = String::with_capacity(line.len()); |
| 561 | let mut column = 0; |
| 562 | for grapheme in line.graphemes(true) { |
| 563 | let width = markdown_grapheme_width(grapheme, column); |
| 564 | if grapheme == "\t" { |
| 565 | expanded.extend(std::iter::repeat_n(' ', width)); |
| 566 | } else { |
| 567 | expanded.push_str(grapheme); |
| 568 | } |
| 569 | column += width; |
| 570 | } |
| 571 | Cow::Owned(expanded) |
| 572 | } |
| 573 | |
| 574 | fn push_parsed_line( |
| 575 | raw_line: &str, |
| 576 | blocks: &mut Vec<Block>, |
| 577 | open_fence: &mut Option<(char, usize)>, |
| 578 | code_language: &mut Option<String>, |
| 579 | code_block_id: &mut usize, |
| 580 | in_list: &mut bool, |
| 581 | ) { |
| 582 | let raw_line = expand_tabs(raw_line); |
| 583 | let raw_line = raw_line.as_ref(); |
| 584 | let trimmed = raw_line.trim_start(); |
| 585 | let fence_char = if trimmed.starts_with('~') { '~' } else { '`' }; |
| 586 | let fence_len = trimmed.chars().take_while(|c| *c == fence_char).count(); |
| 587 | if fence_len >= 3 { |
| 588 | match *open_fence { |
| 589 | // Inside a code block: a fence of the same character and at least |
| 590 | // as long as the opener closes it; a shorter fence line, or one of |
| 591 | // the other character, is code content per CommonMark and must |
| 592 | // not flip the state or escape the block. |
| 593 | Some((open_char, open_len)) |
| 594 | if fence_char == open_char |
| 595 | && fence_len >= open_len |
| 596 | && trimmed[fence_len..].trim().is_empty() => |
| 597 | { |
| 598 | *open_fence = None; |
| 599 | *code_language = None; |
| 600 | } |
| 601 | Some(_) => { |
| 602 | blocks.push(Block::Code { |
| 603 | line: raw_line.to_string(), |
| 604 | language: code_language.clone(), |
| 605 | block_id: *code_block_id, |
| 606 | }); |
| 607 | } |
| 608 | None => { |
| 609 | *open_fence = Some((fence_char, fence_len)); |
| 610 | *code_block_id = code_block_id.saturating_add(1); |
| 611 | *code_language = normalized_fence_language(&trimmed[fence_len..]); |
| 612 | } |
| 613 | } |
| 614 | return; |
| 615 | } |
| 616 | |
| 617 | if open_fence.is_some() { |
| 618 | blocks.push(Block::Code { |
| 619 | line: raw_line.to_string(), |
| 620 | language: code_language.clone(), |
| 621 | block_id: *code_block_id, |
| 622 | }); |
| 623 | return; |
| 624 | } |
| 625 | |
| 626 | if let Some((depth, text)) = parse_blockquote(trimmed) { |
| 627 | *in_list = false; |
| 628 | blocks.push(Block::Quote { |
| 629 | depth, |
| 630 | text: text.to_string(), |
| 631 | }); |
| 632 | return; |
| 633 | } |
| 634 | |
| 635 | if let Some((level, text)) = parse_heading(trimmed) { |
| 636 | *in_list = false; |
| 637 | blocks.push(Block::Heading { |
| 638 | level, |
| 639 | text: text.to_string(), |
| 640 | }); |
| 641 | if level == 1 { |
| 642 | blocks.push(Block::HeadingRule); |
| 643 | } |
| 644 | return; |
| 645 | } |
| 646 | |
| 647 | if is_horizontal_rule(trimmed) { |
| 648 | *in_list = false; |
| 649 | blocks.push(Block::HorizontalRule); |
| 650 | return; |
| 651 | } |
| 652 | |
| 653 | if let Some((bullet, text)) = parse_list_item(trimmed) { |
| 654 | *in_list = true; |
| 655 | blocks.push(Block::ListItem { |
| 656 | indent: raw_line[..raw_line.len() - trimmed.len()].chars().count(), |
| 657 | bullet, |
| 658 | text: text.to_string(), |
| 659 | }); |
| 660 | return; |
| 661 | } |
| 662 | |
| 663 | match parse_table_row(trimmed) { |
| 664 | Some(cells) => { |
| 665 | *in_list = false; |
| 666 | blocks.push(Block::TableRow(cells)); |
| 667 | return; |
| 668 | } |
| 669 | None if trimmed.starts_with('|') => { |
| 670 | *in_list = false; |
| 671 | blocks.push(Block::TableSeparator); |
| 672 | return; |
| 673 | } |
| 674 | None => {} |
| 675 | } |
| 676 | |
| 677 | if trimmed.is_empty() { |
| 678 | // Whitespace-only lines are blank paragraphs. |
| 679 | blocks.push(Block::Blank); |
| 680 | return; |
| 681 | } |
| 682 | |
| 683 | *in_list &= trimmed.len() < raw_line.len(); |
| 684 | blocks.push(Block::Paragraph { |
| 685 | text: if *in_list { raw_line } else { trimmed }.to_string(), |
| 686 | }); |
| 687 | } |
| 688 | |
| 689 | /// Render a parsed-markdown AST at the given terminal width. |
| 690 | /// |
| 691 | /// This is the width-dependent half: word-wrapping, link styling, code-block |
| 692 | /// formatting. The AST is owned by the caller (typically the transcript cache), |
| 693 | /// so width-only changes can call `render_parsed` again with the same AST and |
| 694 | /// skip the parse step entirely. |
| 695 | #[cfg(test)] |
| 696 | #[must_use] |
| 697 | pub fn render_parsed(parsed: &ParsedMarkdown, width: u16, base_style: Style) -> Vec<Line<'static>> { |
| 698 | render_parsed_tagged_with_palette(parsed, width, base_style, detected_palette_mode()) |
| 699 | .into_iter() |
| 700 | .map(|line| line.line) |
| 701 | .collect() |
| 702 | } |
| 703 | |
| 704 | /// Render a parsed-markdown AST and preserve per-line source metadata. |
| 705 | #[cfg(any(test, feature = "test-support"))] |
| 706 | #[must_use] |
| 707 | pub fn render_parsed_tagged( |
| 708 | parsed: &ParsedMarkdown, |
| 709 | width: u16, |
| 710 | base_style: Style, |
| 711 | ) -> Vec<RenderedMarkdownLine> { |
| 712 | render_parsed_tagged_with_palette(parsed, width, base_style, detected_palette_mode()) |
| 713 | } |
| 714 | |
| 715 | /// Render parsed markdown using the caller's resolved UI palette mode. |
| 716 | /// |
| 717 | /// The live transcript uses this entry point so an explicit theme selection |
| 718 | /// wins over terminal/OS auto-detection and participates in cache invalidation. |
| 719 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 720 | pub enum InlineCodeKind { |
| 721 | Url, |
| 722 | Path, |
| 723 | } |
| 724 | |
| 725 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 726 | pub struct ResolvedLink { |
| 727 | pub target: String, |
| 728 | pub line: Option<u32>, |
| 729 | } |
| 730 | |
| 731 | pub type WorkspaceLinkResolver<'a> = dyn FnMut(&str) -> Option<ResolvedLink> + 'a; |
| 732 | |
| 733 | #[must_use] |
| 734 | pub fn classify_inline_code(text: &str) -> Option<InlineCodeKind> { |
| 735 | if text.is_empty() || text.chars().any(char::is_whitespace) { |
| 736 | return None; |
| 737 | } |
| 738 | if text |
| 739 | .get(..7) |
| 740 | .is_some_and(|prefix| prefix.eq_ignore_ascii_case("http://")) |
| 741 | || text |
| 742 | .get(..8) |
| 743 | .is_some_and(|prefix| prefix.eq_ignore_ascii_case("https://")) |
| 744 | { |
| 745 | return Some(InlineCodeKind::Url); |
| 746 | } |
| 747 | if has_uri_scheme(text) { |
| 748 | return None; |
| 749 | } |
| 750 | if text.chars().any(|ch| { |
| 751 | matches!( |
| 752 | ch, |
| 753 | '{' | '}' | '<' | '>' | '"' | '\'' | '`' | ';' | '=' | '|' | '&' | '*' | ',' |
| 754 | ) |
| 755 | }) { |
| 756 | return None; |
| 757 | } |
| 758 | if text.starts_with("//") |
| 759 | || text.starts_with("\\\\") |
| 760 | || text.starts_with("/\\") |
| 761 | || text.starts_with("\\/") |
| 762 | { |
| 763 | return None; |
| 764 | } |
| 765 | let path_part = strip_inline_path_line_suffix(text); |
| 766 | if is_known_extensionless_filename(path_part) { |
| 767 | return Some(InlineCodeKind::Path); |
| 768 | } |
| 769 | if path_part.contains(['.', '/', '\\']) && path_part.chars().any(|ch| ch.is_ascii_alphabetic()) |
| 770 | { |
| 771 | return Some(InlineCodeKind::Path); |
| 772 | } |
| 773 | None |
| 774 | } |
| 775 | |
| 776 | fn has_uri_scheme(text: &str) -> bool { |
| 777 | let Some(scheme_end) = text.find("://") else { |
| 778 | return false; |
| 779 | }; |
| 780 | let scheme = &text[..scheme_end]; |
| 781 | let mut chars = scheme.chars(); |
| 782 | let Some(first) = chars.next() else { |
| 783 | return false; |
| 784 | }; |
| 785 | first.is_ascii_alphabetic() |
| 786 | && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '.' | '-')) |
| 787 | } |
| 788 | |
| 789 | fn strip_inline_path_line_suffix(text: &str) -> &str { |
| 790 | if let Some((path, fragment)) = text.rsplit_once('#') |
| 791 | && !path.is_empty() |
| 792 | && let Some(rest) = fragment |
| 793 | .strip_prefix('L') |
| 794 | .or_else(|| fragment.strip_prefix('l')) |
| 795 | { |
| 796 | let (start, end) = match rest.split_once('-') { |
| 797 | Some((s, e)) => ( |
| 798 | s, |
| 799 | Some( |
| 800 | e.strip_prefix('L') |
| 801 | .or_else(|| e.strip_prefix('l')) |
| 802 | .unwrap_or(e), |
| 803 | ), |
| 804 | ), |
| 805 | None => (rest, None), |
| 806 | }; |
| 807 | if !start.is_empty() |
| 808 | && start.chars().all(|c| c.is_ascii_digit()) |
| 809 | && end.is_none_or(|e| !e.is_empty() && e.chars().all(|c| c.is_ascii_digit())) |
| 810 | { |
| 811 | return path; |
| 812 | } |
| 813 | } |
| 814 | if let Some((before_last, last)) = text.rsplit_once(':') |
| 815 | && !last.is_empty() |
| 816 | && last.chars().all(|c| c.is_ascii_digit()) |
| 817 | { |
| 818 | if let Some((before_prev, prev)) = before_last.rsplit_once(':') |
| 819 | && !before_prev.is_empty() |
| 820 | && !prev.is_empty() |
| 821 | && prev.chars().all(|c| c.is_ascii_digit()) |
| 822 | { |
| 823 | return before_prev; |
| 824 | } |
| 825 | if !before_last.is_empty() { |
| 826 | return before_last; |
| 827 | } |
| 828 | } |
| 829 | text |
| 830 | } |
| 831 | |
| 832 | fn is_known_extensionless_filename(path: &str) -> bool { |
| 833 | matches!( |
| 834 | path, |
| 835 | "CHANGELOG" |
| 836 | | "CODEOWNERS" |
| 837 | | "Containerfile" |
| 838 | | "Dockerfile" |
| 839 | | "Gemfile" |
| 840 | | "Justfile" |
| 841 | | "LICENSE" |
| 842 | | "Makefile" |
| 843 | | "Procfile" |
| 844 | | "README" |
| 845 | | "Rakefile" |
| 846 | | "Vagrantfile" |
| 847 | ) |
| 848 | } |
| 849 | |
| 850 | #[must_use] |
| 851 | pub fn render_parsed_tagged_with_palette( |
| 852 | parsed: &ParsedMarkdown, |
| 853 | width: u16, |
| 854 | base_style: Style, |
| 855 | palette_mode: palette::PaletteMode, |
| 856 | ) -> Vec<RenderedMarkdownLine> { |
| 857 | render_parsed_tagged_with_palette_and_links(parsed, width, base_style, palette_mode, None) |
| 858 | } |
| 859 | |
| 860 | #[must_use] |
| 861 | pub fn render_parsed_tagged_with_palette_and_links( |
| 862 | parsed: &ParsedMarkdown, |
| 863 | width: u16, |
| 864 | base_style: Style, |
| 865 | palette_mode: palette::PaletteMode, |
| 866 | mut link_resolver: Option<&mut WorkspaceLinkResolver<'_>>, |
| 867 | ) -> Vec<RenderedMarkdownLine> { |
| 868 | let width = width.max(1) as usize; |
| 869 | let mut out: Vec<RenderedMarkdownLine> = Vec::with_capacity(parsed.blocks.len()); |
| 870 | |
| 871 | let mut i = 0; |
| 872 | while i < parsed.blocks.len() { |
| 873 | if matches!( |
| 874 | &parsed.blocks[i], |
| 875 | Block::TableRow(_) | Block::TableSeparator |
| 876 | ) { |
| 877 | let start = i; |
| 878 | while i < parsed.blocks.len() |
| 879 | && matches!( |
| 880 | &parsed.blocks[i], |
| 881 | Block::TableRow(_) | Block::TableSeparator |
| 882 | ) |
| 883 | { |
| 884 | i += 1; |
| 885 | } |
| 886 | out.extend(render_table_group( |
| 887 | &parsed.blocks[start..i], |
| 888 | width, |
| 889 | base_style, |
| 890 | &mut link_resolver, |
| 891 | )); |
| 892 | continue; |
| 893 | } |
| 894 | |
| 895 | if let Block::Code { |
| 896 | language, block_id, .. |
| 897 | } = &parsed.blocks[i] |
| 898 | { |
| 899 | let start = i; |
| 900 | while i < parsed.blocks.len() |
| 901 | && matches!( |
| 902 | &parsed.blocks[i], |
| 903 | Block::Code { |
| 904 | block_id: candidate, |
| 905 | .. |
| 906 | } if candidate == block_id |
| 907 | ) |
| 908 | { |
| 909 | i += 1; |
| 910 | } |
| 911 | let source_lines = parsed.blocks[start..i] |
| 912 | .iter() |
| 913 | .filter_map(|block| match block { |
| 914 | Block::Code { line, .. } => Some(line.as_str()), |
| 915 | _ => None, |
| 916 | }) |
| 917 | .collect::<Vec<_>>(); |
| 918 | let highlighted = |
| 919 | highlight_code_block(language.as_deref(), &source_lines, base_style, palette_mode); |
| 920 | for spans in highlighted { |
| 921 | out.extend(render_wrapped_code_spans_tagged(spans, width)); |
| 922 | } |
| 923 | continue; |
| 924 | } |
| 925 | |
| 926 | match &parsed.blocks[i] { |
| 927 | Block::Heading { text, .. } => { |
| 928 | let style = Style::default() |
| 929 | .fg(palette::WHALE_ACTION) |
| 930 | .add_modifier(Modifier::BOLD); |
| 931 | out.extend(render_line_with_links_tagged( |
| 932 | text, |
| 933 | width, |
| 934 | style, |
| 935 | link_style(), |
| 936 | &mut link_resolver, |
| 937 | )); |
| 938 | } |
| 939 | Block::HeadingRule => { |
| 940 | out.push(RenderedMarkdownLine { |
| 941 | line: Line::from(Span::styled( |
| 942 | "─".repeat(width.min(40)), |
| 943 | Style::default().fg(palette::TEXT_DIM), |
| 944 | )), |
| 945 | links: Vec::new(), |
| 946 | is_code: false, |
| 947 | copy_prefix_width: 0, |
| 948 | copy_separator_after: CopyLineSeparator::Newline, |
| 949 | }); |
| 950 | } |
| 951 | Block::HorizontalRule => { |
| 952 | out.push(RenderedMarkdownLine { |
| 953 | line: Line::from(Span::styled( |
| 954 | "─".repeat(width.min(60)), |
| 955 | Style::default().fg(palette::TEXT_DIM), |
| 956 | )), |
| 957 | links: Vec::new(), |
| 958 | is_code: false, |
| 959 | copy_prefix_width: 0, |
| 960 | copy_separator_after: CopyLineSeparator::Newline, |
| 961 | }); |
| 962 | } |
| 963 | Block::ListItem { |
| 964 | indent, |
| 965 | bullet, |
| 966 | text, |
| 967 | } => { |
| 968 | let bullet_style = Style::default().fg(palette::WHALE_ACTION); |
| 969 | out.extend(render_list_line_tagged( |
| 970 | *indent, |
| 971 | bullet, |
| 972 | text, |
| 973 | width, |
| 974 | bullet_style, |
| 975 | base_style, |
| 976 | &mut link_resolver, |
| 977 | )); |
| 978 | } |
| 979 | Block::Code { .. } => unreachable!(), |
| 980 | Block::Quote { depth, text } => { |
| 981 | let rail_style = Style::default().fg(palette::WHALE_ACTION); |
| 982 | let text_style = Style::default().fg(palette::TEXT_DIM); |
| 983 | out.extend(render_quote_line_tagged( |
| 984 | text, |
| 985 | *depth, |
| 986 | width, |
| 987 | rail_style, |
| 988 | text_style, |
| 989 | &mut link_resolver, |
| 990 | )); |
| 991 | } |
| 992 | Block::Paragraph { text } => { |
| 993 | let link_style = Style::default() |
| 994 | .fg(palette::WHALE_ACTION) |
| 995 | .add_modifier(Modifier::UNDERLINED); |
| 996 | out.extend(render_paragraph_tagged( |
| 997 | text, |
| 998 | width, |
| 999 | base_style, |
| 1000 | link_style, |
| 1001 | &mut link_resolver, |
| 1002 | )); |
| 1003 | } |
| 1004 | Block::Blank => { |
| 1005 | out.push(RenderedMarkdownLine { |
| 1006 | line: Line::from(""), |
| 1007 | links: Vec::new(), |
| 1008 | is_code: false, |
| 1009 | copy_prefix_width: 0, |
| 1010 | copy_separator_after: CopyLineSeparator::Newline, |
| 1011 | }); |
| 1012 | } |
| 1013 | Block::TableRow(_) | Block::TableSeparator => unreachable!(), |
| 1014 | } |
| 1015 | i += 1; |
| 1016 | } |
| 1017 | |
| 1018 | if out.is_empty() { |
| 1019 | out.push(RenderedMarkdownLine { |
| 1020 | line: Line::from(""), |
| 1021 | links: Vec::new(), |
| 1022 | is_code: false, |
| 1023 | copy_prefix_width: 0, |
| 1024 | copy_separator_after: CopyLineSeparator::Newline, |
| 1025 | }); |
| 1026 | } |
| 1027 | |
| 1028 | out |
| 1029 | } |
| 1030 | |
| 1031 | fn empty_rendered_markdown_line() -> RenderedMarkdownLine { |
| 1032 | RenderedMarkdownLine { |
| 1033 | line: Line::from(""), |
| 1034 | links: Vec::new(), |
| 1035 | is_code: false, |
| 1036 | copy_prefix_width: 0, |
| 1037 | copy_separator_after: CopyLineSeparator::Newline, |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | /// Render a block suffix while carrying syntax state across calls. |
| 1042 | /// |
| 1043 | /// Non-code blocks use the canonical batch renderer unchanged. Code lines are |
| 1044 | /// the only group whose styling depends on preceding blocks, so their syntect |
| 1045 | /// parse/highlight state is retained explicitly and cloned for the replaceable |
| 1046 | /// tail. This keeps an open fence incremental without sacrificing exact final |
| 1047 | /// highlighting. |
| 1048 | fn render_incremental_blocks( |
| 1049 | blocks: &[Block], |
| 1050 | key: IncrementalRenderKey, |
| 1051 | code_highlighter: &mut Option<IncrementalCodeHighlighter>, |
| 1052 | ) -> Vec<RenderedMarkdownLine> { |
| 1053 | let mut out = Vec::new(); |
| 1054 | let mut index = 0; |
| 1055 | while index < blocks.len() { |
| 1056 | if let Block::Code { |
| 1057 | line, |
| 1058 | language, |
| 1059 | block_id, |
| 1060 | } = &blocks[index] |
| 1061 | { |
| 1062 | let spans = highlight_incremental_code_line( |
| 1063 | *block_id, |
| 1064 | language.as_deref(), |
| 1065 | line, |
| 1066 | key.base_style, |
| 1067 | key.palette_mode, |
| 1068 | code_highlighter, |
| 1069 | ); |
| 1070 | out.extend(render_wrapped_code_spans_tagged( |
| 1071 | spans, |
| 1072 | usize::from(key.width), |
| 1073 | )); |
| 1074 | index += 1; |
| 1075 | continue; |
| 1076 | } |
| 1077 | |
| 1078 | let start = index; |
| 1079 | while index < blocks.len() && !matches!(blocks[index], Block::Code { .. }) { |
| 1080 | index += 1; |
| 1081 | } |
| 1082 | out.extend(render_parsed_tagged_with_palette( |
| 1083 | &ParsedMarkdown { |
| 1084 | blocks: blocks[start..index].to_vec(), |
| 1085 | }, |
| 1086 | key.width, |
| 1087 | key.base_style, |
| 1088 | key.palette_mode, |
| 1089 | )); |
| 1090 | } |
| 1091 | out |
| 1092 | } |
| 1093 | |
| 1094 | fn highlight_incremental_code_line( |
| 1095 | block_id: usize, |
| 1096 | language: Option<&str>, |
| 1097 | line: &str, |
| 1098 | base_style: Style, |
| 1099 | palette_mode: palette::PaletteMode, |
| 1100 | cache: &mut Option<IncrementalCodeHighlighter>, |
| 1101 | ) -> Vec<Span<'static>> { |
| 1102 | let language_owned = language.map(str::to_owned); |
| 1103 | let needs_reset = cache |
| 1104 | .as_ref() |
| 1105 | .is_none_or(|current| current.block_id != block_id || current.language != language_owned); |
| 1106 | if needs_reset { |
| 1107 | let state = language |
| 1108 | .and_then(find_code_syntax) |
| 1109 | .map(|syntax| HighlightLines::new(syntax, selected_syntax_theme(palette_mode)).state()); |
| 1110 | *cache = Some(IncrementalCodeHighlighter { |
| 1111 | block_id, |
| 1112 | language: language_owned, |
| 1113 | state, |
| 1114 | }); |
| 1115 | } |
| 1116 | |
| 1117 | let plain_style = base_style.fg(palette::TEXT_TOOL_OUTPUT); |
| 1118 | let Some(current) = cache.as_mut() else { |
| 1119 | return vec![Span::styled(line.to_string(), plain_style)]; |
| 1120 | }; |
| 1121 | let Some((highlight_state, parse_state)) = current.state.take() else { |
| 1122 | return vec![Span::styled(line.to_string(), plain_style)]; |
| 1123 | }; |
| 1124 | let mut highlighter = HighlightLines::from_state( |
| 1125 | selected_syntax_theme(palette_mode), |
| 1126 | highlight_state, |
| 1127 | parse_state, |
| 1128 | ); |
| 1129 | let highlighted = match highlighter.highlight_line(line, syntax_set()) { |
| 1130 | Ok(ranges) if !ranges.is_empty() => ranges |
| 1131 | .into_iter() |
| 1132 | .map(|(style, text)| { |
| 1133 | Span::styled( |
| 1134 | text.to_string(), |
| 1135 | syntax_style_to_ratatui(style, base_style, palette_mode), |
| 1136 | ) |
| 1137 | }) |
| 1138 | .collect(), |
| 1139 | _ => vec![Span::styled(line.to_string(), plain_style)], |
| 1140 | }; |
| 1141 | current.state = Some(highlighter.state()); |
| 1142 | highlighted |
| 1143 | } |
| 1144 | |
| 1145 | /// Convenience wrapper: parse + render in one call. |
| 1146 | /// |
| 1147 | /// Equivalent to `render_parsed(&parse(content), width, base_style)`. |
| 1148 | #[cfg(test)] |
| 1149 | #[must_use] |
| 1150 | pub fn render_markdown(content: &str, width: u16, base_style: Style) -> Vec<Line<'static>> { |
| 1151 | let parsed = parse(content); |
| 1152 | render_parsed(&parsed, width, base_style) |
| 1153 | } |
| 1154 | |
| 1155 | /// Convenience wrapper: parse + render while keeping per-line source metadata. |
| 1156 | #[cfg(any(test, feature = "test-support"))] |
| 1157 | #[must_use] |
| 1158 | pub fn render_markdown_tagged( |
| 1159 | content: &str, |
| 1160 | width: u16, |
| 1161 | base_style: Style, |
| 1162 | ) -> Vec<RenderedMarkdownLine> { |
| 1163 | let parsed = parse(content); |
| 1164 | render_parsed_tagged(&parsed, width, base_style) |
| 1165 | } |
| 1166 | |
| 1167 | /// Parse and render markdown using an already-resolved UI palette mode. |
| 1168 | #[must_use] |
| 1169 | pub fn render_markdown_tagged_with_palette( |
| 1170 | content: &str, |
| 1171 | width: u16, |
| 1172 | base_style: Style, |
| 1173 | palette_mode: palette::PaletteMode, |
| 1174 | ) -> Vec<RenderedMarkdownLine> { |
| 1175 | let parsed = parse(content); |
| 1176 | render_parsed_tagged_with_palette(&parsed, width, base_style, palette_mode) |
| 1177 | } |
| 1178 | |
| 1179 | #[must_use] |
| 1180 | pub fn render_markdown_tagged_with_palette_and_links( |
| 1181 | content: &str, |
| 1182 | width: u16, |
| 1183 | base_style: Style, |
| 1184 | palette_mode: palette::PaletteMode, |
| 1185 | link_resolver: Option<&mut WorkspaceLinkResolver<'_>>, |
| 1186 | ) -> Vec<RenderedMarkdownLine> { |
| 1187 | let parsed = parse(content); |
| 1188 | render_parsed_tagged_with_palette_and_links( |
| 1189 | &parsed, |
| 1190 | width, |
| 1191 | base_style, |
| 1192 | palette_mode, |
| 1193 | link_resolver, |
| 1194 | ) |
| 1195 | } |
| 1196 | |
| 1197 | /// Render plain text: split on newlines, word-wrap each line independently, |
| 1198 | /// preserve leading whitespace and blank lines. No markdown interpretation. |
| 1199 | #[must_use] |
| 1200 | pub fn render_plain_text(content: &str, width: u16, base_style: Style) -> Vec<Line<'static>> { |
| 1201 | let width = width.max(1) as usize; |
| 1202 | let mut lines = Vec::new(); |
| 1203 | for raw_line in content.split('\n') { |
| 1204 | if raw_line.is_empty() { |
| 1205 | lines.push(Line::from("")); |
| 1206 | } else { |
| 1207 | lines.extend(wrap_plain_line(&expand_tabs(raw_line), width, base_style)); |
| 1208 | } |
| 1209 | } |
| 1210 | if lines.is_empty() { |
| 1211 | lines.push(Line::from("")); |
| 1212 | } |
| 1213 | lines |
| 1214 | } |
| 1215 | |
| 1216 | /// Word-wrap a single line at `width`, preserving leading whitespace. |
| 1217 | /// Handles over-long words by char-breaking (same strategy as the markdown |
| 1218 | /// line renderer). |
| 1219 | fn wrap_plain_line(line: &str, width: usize, style: Style) -> Vec<Line<'static>> { |
| 1220 | if width == 0 || line.is_empty() { |
| 1221 | return vec![Line::from("")]; |
| 1222 | } |
| 1223 | |
| 1224 | let mut chunks = Vec::new(); |
| 1225 | let mut current = String::new(); |
| 1226 | let mut current_width = 0usize; |
| 1227 | let mut last_break_pos = None; |
| 1228 | |
| 1229 | for grapheme in line.graphemes(true) { |
| 1230 | loop { |
| 1231 | let grapheme_width = markdown_grapheme_width(grapheme, current_width); |
| 1232 | if current_width + grapheme_width <= width || current.is_empty() { |
| 1233 | break; |
| 1234 | } |
| 1235 | |
| 1236 | if let Some(pos) = last_break_pos { |
| 1237 | if pos == current.len() { |
| 1238 | chunks.push(std::mem::take(&mut current)); |
| 1239 | current_width = 0; |
| 1240 | last_break_pos = None; |
| 1241 | break; |
| 1242 | } |
| 1243 | |
| 1244 | if current[..pos].chars().any(|c| !c.is_whitespace()) { |
| 1245 | let tail = current.split_off(pos); |
| 1246 | chunks.push(std::mem::take(&mut current)); |
| 1247 | current = tail; |
| 1248 | current_width = plain_display_width(¤t); |
| 1249 | last_break_pos = last_plain_break_pos(¤t); |
| 1250 | continue; |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | chunks.push(std::mem::take(&mut current)); |
| 1255 | current_width = 0; |
| 1256 | last_break_pos = None; |
| 1257 | break; |
| 1258 | } |
| 1259 | |
| 1260 | let grapheme_width = markdown_grapheme_width(grapheme, current_width); |
| 1261 | current.push_str(grapheme); |
| 1262 | current_width += grapheme_width; |
| 1263 | if grapheme.chars().all(char::is_whitespace) { |
| 1264 | last_break_pos = Some(current.len()); |
| 1265 | } |
| 1266 | } |
| 1267 | |
| 1268 | if !current.is_empty() { |
| 1269 | chunks.push(current); |
| 1270 | } |
| 1271 | |
| 1272 | if chunks.is_empty() { |
| 1273 | return vec![Line::from("")]; |
| 1274 | } |
| 1275 | |
| 1276 | chunks |
| 1277 | .into_iter() |
| 1278 | .map(|chunk| Line::from(vec![Span::styled(chunk, style)])) |
| 1279 | .collect() |
| 1280 | } |
| 1281 | |
| 1282 | fn plain_display_width(text: &str) -> usize { |
| 1283 | let mut width = 0usize; |
| 1284 | for grapheme in text.graphemes(true) { |
| 1285 | width += markdown_grapheme_width(grapheme, width); |
| 1286 | } |
| 1287 | width |
| 1288 | } |
| 1289 | |
| 1290 | fn last_plain_break_pos(text: &str) -> Option<usize> { |
| 1291 | text.char_indices() |
| 1292 | .rev() |
| 1293 | .find_map(|(idx, ch)| ch.is_whitespace().then_some(idx + ch.len_utf8())) |
| 1294 | } |
| 1295 | |
| 1296 | fn parse_heading(line: &str) -> Option<(usize, &str)> { |
| 1297 | let trimmed = line.trim_start(); |
| 1298 | let hashes = trimmed.chars().take_while(|c| *c == '#').count(); |
| 1299 | let rest = &trimmed[hashes..]; |
| 1300 | if !(1..=6).contains(&hashes) || !(rest.is_empty() || rest.starts_with(char::is_whitespace)) { |
| 1301 | return None; |
| 1302 | } |
| 1303 | let text = rest.trim(); |
| 1304 | if text.is_empty() { |
| 1305 | None |
| 1306 | } else { |
| 1307 | Some((hashes, text)) |
| 1308 | } |
| 1309 | } |
| 1310 | |
| 1311 | fn parse_list_item(line: &str) -> Option<(String, &str)> { |
| 1312 | let trimmed = line.trim_start(); |
| 1313 | if trimmed.starts_with("- ") || trimmed.starts_with("* ") { |
| 1314 | return Some(("-".to_string(), trimmed[2..].trim())); |
| 1315 | } |
| 1316 | let bytes = trimmed.as_bytes(); |
| 1317 | let mut idx = 0; |
| 1318 | while idx < bytes.len() && bytes[idx].is_ascii_digit() { |
| 1319 | idx += 1; |
| 1320 | } |
| 1321 | if idx == 0 || idx >= bytes.len() || bytes[idx] != b'.' { |
| 1322 | return None; |
| 1323 | } |
| 1324 | let rest = &trimmed[idx + 1..]; |
| 1325 | if !rest.starts_with(' ') { |
| 1326 | return None; |
| 1327 | } |
| 1328 | Some((format!("{}.", &trimmed[..idx]), rest.trim_start())) |
| 1329 | } |
| 1330 | |
| 1331 | /// Upper bound on the nesting depth rendered for a `>` quote. Deeper quotes |
| 1332 | /// are clamped and the extra markers dropped from the rendered text; capping |
| 1333 | /// stops a pathological input like `>>>>>>>>>>>> text` from consuming the |
| 1334 | /// whole line width in rails. |
| 1335 | const MAX_QUOTE_DEPTH: usize = 4; |
| 1336 | |
| 1337 | /// Parse a `>` blockquote line, returning `(depth, text)`. |
| 1338 | /// |
| 1339 | /// CommonMark nests with `>>` or `> >`; we count every leading `>` regardless |
| 1340 | /// of interleaved spaces, then trim the remaining content. A lone `>` yields |
| 1341 | /// an empty quote line. Deliberately lenient about missing space after `>` so |
| 1342 | /// model output like `>note` still renders as a quote. |
| 1343 | fn parse_blockquote(line: &str) -> Option<(usize, &str)> { |
| 1344 | let trimmed = line.trim_start(); |
| 1345 | if !trimmed.starts_with('>') { |
| 1346 | return None; |
| 1347 | } |
| 1348 | let mut rest = trimmed; |
| 1349 | let mut depth = 0usize; |
| 1350 | while rest.starts_with('>') { |
| 1351 | depth = depth.saturating_add(1); |
| 1352 | rest = rest[1..].trim_start_matches([' ', '\t']); |
| 1353 | } |
| 1354 | Some((depth.clamp(1, MAX_QUOTE_DEPTH), rest.trim())) |
| 1355 | } |
| 1356 | |
| 1357 | fn normalized_fence_language(info: &str) -> Option<String> { |
| 1358 | let token = info |
| 1359 | .trim() |
| 1360 | .split(|ch: char| ch.is_whitespace() || ch == ',') |
| 1361 | .next() |
| 1362 | .unwrap_or("") |
| 1363 | .trim_matches(['{', '}', '.']) |
| 1364 | .to_ascii_lowercase(); |
| 1365 | if token.is_empty() || matches!(token.as_str(), "text" | "txt" | "plain" | "plaintext") { |
| 1366 | return None; |
| 1367 | } |
| 1368 | let normalized = match token.as_str() { |
| 1369 | "rs" => "rust", |
| 1370 | "js" | "jsx" | "node" => "javascript", |
| 1371 | "ts" | "tsx" => "typescript", |
| 1372 | "py" => "python", |
| 1373 | "rb" => "ruby", |
| 1374 | "sh" | "shell" | "zsh" => "bash", |
| 1375 | "yml" => "yaml", |
| 1376 | "md" => "markdown", |
| 1377 | other => other, |
| 1378 | }; |
| 1379 | Some(normalized.to_string()) |
| 1380 | } |
| 1381 | |
| 1382 | fn selected_syntax_theme(mode: palette::PaletteMode) -> &'static Theme { |
| 1383 | let themes = theme_set(); |
| 1384 | let preferred = match mode { |
| 1385 | palette::PaletteMode::Dark | palette::PaletteMode::Grayscale => "base16-ocean.dark", |
| 1386 | palette::PaletteMode::Light => "InspiredGitHub", |
| 1387 | palette::PaletteMode::SolarizedLight => "Solarized (light)", |
| 1388 | }; |
| 1389 | themes |
| 1390 | .themes |
| 1391 | .get(preferred) |
| 1392 | .or_else(|| themes.themes.values().next()) |
| 1393 | .expect("syntect ships at least one default theme") |
| 1394 | } |
| 1395 | |
| 1396 | fn syntax_style_to_ratatui( |
| 1397 | style: syntect::highlighting::Style, |
| 1398 | base_style: Style, |
| 1399 | palette_mode: palette::PaletteMode, |
| 1400 | ) -> Style { |
| 1401 | let fg = syntax_rgb_to_terminal_color( |
| 1402 | style.foreground.r, |
| 1403 | style.foreground.g, |
| 1404 | style.foreground.b, |
| 1405 | palette_mode, |
| 1406 | syntax_color_depth(), |
| 1407 | ); |
| 1408 | let mut modifiers = Modifier::empty(); |
| 1409 | if style.font_style.contains(FontStyle::BOLD) { |
| 1410 | modifiers |= Modifier::BOLD; |
| 1411 | } |
| 1412 | if style.font_style.contains(FontStyle::ITALIC) { |
| 1413 | modifiers |= Modifier::ITALIC; |
| 1414 | } |
| 1415 | if style.font_style.contains(FontStyle::UNDERLINE) { |
| 1416 | modifiers |= Modifier::UNDERLINED; |
| 1417 | } |
| 1418 | base_style.fg(fg).add_modifier(modifiers) |
| 1419 | } |
| 1420 | |
| 1421 | fn syntax_rgb_to_terminal_color( |
| 1422 | r: u8, |
| 1423 | g: u8, |
| 1424 | b: u8, |
| 1425 | mode: palette::PaletteMode, |
| 1426 | depth: palette::ColorDepth, |
| 1427 | ) -> Color { |
| 1428 | let (r, g, b) = if mode == palette::PaletteMode::Grayscale { |
| 1429 | let luma = |
| 1430 | ((u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114 + 500) / 1000) as u8; |
| 1431 | let readable = luma.clamp(96, 232); |
| 1432 | (readable, readable, readable) |
| 1433 | } else { |
| 1434 | (r, g, b) |
| 1435 | }; |
| 1436 | let mut color = Color::Rgb(r, g, b); |
| 1437 | if matches!( |
| 1438 | color, |
| 1439 | reserved if reserved == palette::WHALE_HUMAN |
| 1440 | || reserved == palette::WHALE_LIVE |
| 1441 | || reserved == palette::WHALE_ACTION |
| 1442 | || reserved == palette::WHALE_ERROR |
| 1443 | ) { |
| 1444 | // Syntax colors are content, not brand/attention/work/danger state. |
| 1445 | // Shift exact collisions before terminal-depth reduction so the cell |
| 1446 | // cannot acquire a reserved semantic role in the color backend. |
| 1447 | color = Color::Rgb(r, g, b.saturating_add(1)); |
| 1448 | } |
| 1449 | let color = palette::adapt_color(color, depth); |
| 1450 | let reserved = [ |
| 1451 | palette::WHALE_HUMAN, |
| 1452 | palette::WHALE_LIVE, |
| 1453 | palette::WHALE_ACTION, |
| 1454 | palette::WHALE_ERROR, |
| 1455 | ] |
| 1456 | .map(|semantic| palette::adapt_color(semantic, depth)); |
| 1457 | if !reserved.contains(&color) { |
| 1458 | return color; |
| 1459 | } |
| 1460 | |
| 1461 | // Quantization can make distinct RGB values collide again. Walk a small, |
| 1462 | // deterministic neutral ramp until the terminal-level color no longer |
| 1463 | // impersonates one of the four reserved semantic lanes. |
| 1464 | for delta in [17_u8, 34, 51, 68, 85, 102, 119, 136] { |
| 1465 | let candidate = palette::adapt_color( |
| 1466 | Color::Rgb( |
| 1467 | r.wrapping_add(delta), |
| 1468 | g.wrapping_add(delta / 2), |
| 1469 | b.wrapping_add(delta / 3), |
| 1470 | ), |
| 1471 | depth, |
| 1472 | ); |
| 1473 | if !reserved.contains(&candidate) { |
| 1474 | return candidate; |
| 1475 | } |
| 1476 | } |
| 1477 | // All supported depths have more than four colors, so this is only a |
| 1478 | // defensive fallback for a future adapter with a narrower gamut. |
| 1479 | Color::Reset |
| 1480 | } |
| 1481 | |
| 1482 | fn highlight_code_block( |
| 1483 | language: Option<&str>, |
| 1484 | lines: &[&str], |
| 1485 | base_style: Style, |
| 1486 | palette_mode: palette::PaletteMode, |
| 1487 | ) -> Vec<Vec<Span<'static>>> { |
| 1488 | let plain_style = base_style.fg(palette::TEXT_TOOL_OUTPUT); |
| 1489 | let Some(language) = language else { |
| 1490 | return lines |
| 1491 | .iter() |
| 1492 | .map(|line| vec![Span::styled((*line).to_string(), plain_style)]) |
| 1493 | .collect(); |
| 1494 | }; |
| 1495 | let syntaxes = syntax_set(); |
| 1496 | let Some(syntax) = find_code_syntax(language) else { |
| 1497 | return lines |
| 1498 | .iter() |
| 1499 | .map(|line| vec![Span::styled((*line).to_string(), plain_style)]) |
| 1500 | .collect(); |
| 1501 | }; |
| 1502 | |
| 1503 | let mut highlighter = HighlightLines::new(syntax, selected_syntax_theme(palette_mode)); |
| 1504 | lines |
| 1505 | .iter() |
| 1506 | .map(|line| match highlighter.highlight_line(line, syntaxes) { |
| 1507 | Ok(ranges) if !ranges.is_empty() => ranges |
| 1508 | .into_iter() |
| 1509 | .map(|(style, text)| { |
| 1510 | Span::styled( |
| 1511 | text.to_string(), |
| 1512 | syntax_style_to_ratatui(style, base_style, palette_mode), |
| 1513 | ) |
| 1514 | }) |
| 1515 | .collect(), |
| 1516 | _ => vec![Span::styled((*line).to_string(), plain_style)], |
| 1517 | }) |
| 1518 | .collect() |
| 1519 | } |
| 1520 | |
| 1521 | fn find_code_syntax(language: &str) -> Option<&'static syntect::parsing::SyntaxReference> { |
| 1522 | let syntaxes = syntax_set(); |
| 1523 | syntaxes |
| 1524 | .find_syntax_by_token(language) |
| 1525 | .or_else(|| syntaxes.find_syntax_by_extension(language)) |
| 1526 | .or_else(|| { |
| 1527 | syntaxes |
| 1528 | .syntaxes() |
| 1529 | .iter() |
| 1530 | .find(|syntax| syntax.name.eq_ignore_ascii_case(language)) |
| 1531 | }) |
| 1532 | } |
| 1533 | |
| 1534 | fn render_wrapped_code_spans_tagged( |
| 1535 | spans: Vec<Span<'static>>, |
| 1536 | width: usize, |
| 1537 | ) -> Vec<RenderedMarkdownLine> { |
| 1538 | let prefix = " "; |
| 1539 | let prefix_width = prefix.width(); |
| 1540 | let available = width.saturating_sub(prefix_width).max(1); |
| 1541 | let mut rows: Vec<Vec<(String, Style)>> = vec![Vec::new()]; |
| 1542 | let mut current_width = 0usize; |
| 1543 | |
| 1544 | for span in spans { |
| 1545 | for grapheme in span.content.graphemes(true) { |
| 1546 | let grapheme_width = markdown_grapheme_width(grapheme, current_width); |
| 1547 | if current_width + grapheme_width > available && current_width > 0 { |
| 1548 | rows.push(Vec::new()); |
| 1549 | current_width = 0; |
| 1550 | } |
| 1551 | let row = rows.last_mut().expect("code rows are never empty"); |
| 1552 | if let Some((text, style)) = row.last_mut() |
| 1553 | && *style == span.style |
| 1554 | { |
| 1555 | text.push_str(grapheme); |
| 1556 | } else { |
| 1557 | row.push((grapheme.to_string(), span.style)); |
| 1558 | } |
| 1559 | current_width += markdown_grapheme_width(grapheme, current_width); |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | let last_index = rows.len().saturating_sub(1); |
| 1564 | rows.into_iter() |
| 1565 | .enumerate() |
| 1566 | .map(|(idx, row)| { |
| 1567 | let mut rendered = vec![Span::raw(prefix)]; |
| 1568 | rendered.extend( |
| 1569 | row.into_iter() |
| 1570 | .map(|(text, style)| Span::styled(text, style)), |
| 1571 | ); |
| 1572 | RenderedMarkdownLine { |
| 1573 | line: Line::from(rendered), |
| 1574 | links: Vec::new(), |
| 1575 | is_code: true, |
| 1576 | copy_prefix_width: prefix_width, |
| 1577 | copy_separator_after: if idx == last_index { |
| 1578 | CopyLineSeparator::Newline |
| 1579 | } else { |
| 1580 | CopyLineSeparator::None |
| 1581 | }, |
| 1582 | } |
| 1583 | }) |
| 1584 | .collect() |
| 1585 | } |
| 1586 | |
| 1587 | fn render_paragraph_tagged( |
| 1588 | text: &str, |
| 1589 | width: usize, |
| 1590 | base_style: Style, |
| 1591 | link_style: Style, |
| 1592 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 1593 | ) -> Vec<RenderedMarkdownLine> { |
| 1594 | let body = text.trim_start(); |
| 1595 | let indent = text[..text.len() - body.len()] |
| 1596 | .chars() |
| 1597 | .count() |
| 1598 | .min(width / 2); |
| 1599 | let mut rows = render_line_with_links_tagged( |
| 1600 | body, |
| 1601 | width.saturating_sub(indent).max(1), |
| 1602 | base_style, |
| 1603 | link_style, |
| 1604 | resolver, |
| 1605 | ); |
| 1606 | if indent == 0 { |
| 1607 | return rows; |
| 1608 | } |
| 1609 | for (idx, row) in rows.iter_mut().enumerate() { |
| 1610 | row.line.spans.insert(0, Span::raw(" ".repeat(indent))); |
| 1611 | row.links = row.links.iter().map(|link| link.shifted(indent)).collect(); |
| 1612 | if idx > 0 { |
| 1613 | row.copy_prefix_width = indent; |
| 1614 | } |
| 1615 | } |
| 1616 | rows |
| 1617 | } |
| 1618 | |
| 1619 | fn render_list_line_tagged( |
| 1620 | indent: usize, |
| 1621 | bullet: &str, |
| 1622 | text: &str, |
| 1623 | width: usize, |
| 1624 | bullet_style: Style, |
| 1625 | text_style: Style, |
| 1626 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 1627 | ) -> Vec<RenderedMarkdownLine> { |
| 1628 | let bullet_prefix = format!("{}{bullet} ", " ".repeat(indent.min(width / 2))); |
| 1629 | let bullet_width = bullet_prefix.width(); |
| 1630 | let available = width.saturating_sub(bullet_width).max(1); |
| 1631 | let wrapped = |
| 1632 | render_line_with_links_tagged(text, available, text_style, link_style(), resolver); |
| 1633 | |
| 1634 | let mut out = Vec::new(); |
| 1635 | for (idx, rendered) in wrapped.into_iter().enumerate() { |
| 1636 | let links = rendered |
| 1637 | .links |
| 1638 | .iter() |
| 1639 | .map(|link| link.shifted(bullet_width)) |
| 1640 | .collect(); |
| 1641 | if idx == 0 { |
| 1642 | let mut spans = vec![Span::styled(bullet_prefix.clone(), bullet_style)]; |
| 1643 | spans.extend(rendered.line.spans); |
| 1644 | out.push(RenderedMarkdownLine { |
| 1645 | line: Line::from(spans), |
| 1646 | links, |
| 1647 | is_code: false, |
| 1648 | copy_prefix_width: 0, |
| 1649 | copy_separator_after: rendered.copy_separator_after, |
| 1650 | }); |
| 1651 | } else { |
| 1652 | let mut spans = vec![Span::raw(" ".repeat(bullet_width))]; |
| 1653 | spans.extend(rendered.line.spans); |
| 1654 | out.push(RenderedMarkdownLine { |
| 1655 | line: Line::from(spans), |
| 1656 | links, |
| 1657 | is_code: false, |
| 1658 | copy_prefix_width: bullet_width, |
| 1659 | copy_separator_after: rendered.copy_separator_after, |
| 1660 | }); |
| 1661 | } |
| 1662 | } |
| 1663 | out |
| 1664 | } |
| 1665 | |
| 1666 | /// Render a `>` quote line: a vertical-rule rail per nesting depth plus the |
| 1667 | /// quote text with inline formatting (bold, code, links). |
| 1668 | /// |
| 1669 | /// The rail is display chrome, not source markup. On every row the |
| 1670 | /// transcript rail-scan (`compute_rail_prefix_width`) already strips it along |
| 1671 | /// with the assistant glyph, so `copy_prefix_width` must be `0` or selection |
| 1672 | /// copy would strip the rail twice and lose quote text. |
| 1673 | fn render_quote_line_tagged( |
| 1674 | text: &str, |
| 1675 | depth: usize, |
| 1676 | width: usize, |
| 1677 | rail_style: Style, |
| 1678 | text_style: Style, |
| 1679 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 1680 | ) -> Vec<RenderedMarkdownLine> { |
| 1681 | let depth = depth.clamp(1, MAX_QUOTE_DEPTH); |
| 1682 | let rail = "│ ".repeat(depth); |
| 1683 | let rail_width = rail.width(); |
| 1684 | let available = width.saturating_sub(rail_width).max(1); |
| 1685 | let wrapped = |
| 1686 | render_line_with_links_tagged(text, available, text_style, link_style(), resolver); |
| 1687 | |
| 1688 | let mut out = Vec::new(); |
| 1689 | for rendered in wrapped { |
| 1690 | let links = rendered |
| 1691 | .links |
| 1692 | .iter() |
| 1693 | .map(|link| link.shifted(rail_width)) |
| 1694 | .collect(); |
| 1695 | let mut spans: Vec<_> = (0..depth).map(|_| Span::styled("│ ", rail_style)).collect(); |
| 1696 | spans.extend(rendered.line.spans); |
| 1697 | out.push(RenderedMarkdownLine { |
| 1698 | line: Line::from(spans), |
| 1699 | links, |
| 1700 | is_code: false, |
| 1701 | copy_prefix_width: 0, |
| 1702 | copy_separator_after: rendered.copy_separator_after, |
| 1703 | }); |
| 1704 | } |
| 1705 | out |
| 1706 | } |
| 1707 | |
| 1708 | #[cfg(test)] |
| 1709 | fn render_line_with_links( |
| 1710 | line: &str, |
| 1711 | width: usize, |
| 1712 | base_style: Style, |
| 1713 | link_style: Style, |
| 1714 | ) -> Vec<Line<'static>> { |
| 1715 | render_line_with_links_tagged(line, width, base_style, link_style, &mut None) |
| 1716 | .into_iter() |
| 1717 | .map(|rendered| rendered.line) |
| 1718 | .collect() |
| 1719 | } |
| 1720 | |
| 1721 | fn render_line_with_links_tagged( |
| 1722 | line: &str, |
| 1723 | width: usize, |
| 1724 | base_style: Style, |
| 1725 | link_style: Style, |
| 1726 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 1727 | ) -> Vec<RenderedMarkdownLine> { |
| 1728 | if line.trim().is_empty() { |
| 1729 | return vec![RenderedMarkdownLine { |
| 1730 | line: Line::from(""), |
| 1731 | links: Vec::new(), |
| 1732 | is_code: false, |
| 1733 | copy_prefix_width: 0, |
| 1734 | copy_separator_after: CopyLineSeparator::Newline, |
| 1735 | }]; |
| 1736 | } |
| 1737 | |
| 1738 | // Flatten inline tokens into (word, style) pairs preserving inter-token spaces. |
| 1739 | let tokens = parse_inline_spans_with_links(line, base_style, link_style, resolver); |
| 1740 | let mut words: Vec<InlineToken> = Vec::new(); |
| 1741 | for token in tokens { |
| 1742 | let mut first = true; |
| 1743 | for part in token.text.split(' ') { |
| 1744 | if !first { |
| 1745 | // The space consumed by split remains part of a markdown-link |
| 1746 | // label when the surrounding token is linked. It is still a |
| 1747 | // wrap opportunity and is dropped at a row boundary. |
| 1748 | words.push(InlineToken::with_line( |
| 1749 | " ".to_string(), |
| 1750 | token.style, |
| 1751 | token.link_url.clone(), |
| 1752 | token.link_line, |
| 1753 | )); |
| 1754 | } |
| 1755 | if !part.is_empty() { |
| 1756 | words.push(InlineToken::with_line( |
| 1757 | part.to_string(), |
| 1758 | token.style, |
| 1759 | token.link_url.clone(), |
| 1760 | token.link_line, |
| 1761 | )); |
| 1762 | } |
| 1763 | first = false; |
| 1764 | } |
| 1765 | } |
| 1766 | |
| 1767 | let mut lines: Vec<RenderedMarkdownLine> = Vec::new(); |
| 1768 | let mut current_spans: Vec<Span<'static>> = Vec::new(); |
| 1769 | let mut current_links: Vec<osc8::LineLink> = Vec::new(); |
| 1770 | let mut current_width = 0usize; |
| 1771 | |
| 1772 | for word in words { |
| 1773 | if word.text == "\n" { |
| 1774 | push_inline_line( |
| 1775 | &mut lines, |
| 1776 | &mut current_spans, |
| 1777 | &mut current_links, |
| 1778 | CopyLineSeparator::Newline, |
| 1779 | ); |
| 1780 | current_width = 0; |
| 1781 | continue; |
| 1782 | } |
| 1783 | let ww = word.text.width(); |
| 1784 | if word.text == " " { |
| 1785 | // Space: emit only if we're mid-line and it fits; otherwise drop |
| 1786 | // (it's a potential wrap point, not content). |
| 1787 | if !current_spans.is_empty() && current_width < width { |
| 1788 | current_spans.push(word.span_for(" ".to_string())); |
| 1789 | record_inline_link(&mut current_links, &word, current_width, 1); |
| 1790 | current_width += 1; |
| 1791 | } |
| 1792 | continue; |
| 1793 | } |
| 1794 | // If the word itself is wider than an entire line, hard-break it at |
| 1795 | // grapheme boundaries so wrapping always makes progress (#1344, |
| 1796 | // #1351). Without this, long URLs / paths / hashes were placed on |
| 1797 | // their own line whole and silently overflowed the right edge of |
| 1798 | // the transcript. |
| 1799 | if ww > width && width > 0 { |
| 1800 | // Flush the in-progress line first. |
| 1801 | if !current_spans.is_empty() { |
| 1802 | push_inline_line( |
| 1803 | &mut lines, |
| 1804 | &mut current_spans, |
| 1805 | &mut current_links, |
| 1806 | CopyLineSeparator::Space, |
| 1807 | ); |
| 1808 | current_width = 0; |
| 1809 | } |
| 1810 | // Char-break the word into width-sized chunks. Each full chunk |
| 1811 | // becomes its own line; the final partial chunk continues the |
| 1812 | // current line so the next word can pack onto it. |
| 1813 | let mut chunk = String::new(); |
| 1814 | let mut chunk_w = 0usize; |
| 1815 | for grapheme in word.text.graphemes(true) { |
| 1816 | let grapheme_width = grapheme.width(); |
| 1817 | if chunk_w + grapheme_width > width && chunk_w > 0 { |
| 1818 | let chunk = std::mem::take(&mut chunk); |
| 1819 | let mut links = Vec::new(); |
| 1820 | record_inline_link(&mut links, &word, 0, chunk_w); |
| 1821 | lines.push(RenderedMarkdownLine { |
| 1822 | line: Line::from(vec![word.span_for(chunk)]), |
| 1823 | links, |
| 1824 | is_code: false, |
| 1825 | copy_prefix_width: 0, |
| 1826 | copy_separator_after: CopyLineSeparator::None, |
| 1827 | }); |
| 1828 | chunk_w = 0; |
| 1829 | } |
| 1830 | chunk.push_str(grapheme); |
| 1831 | chunk_w += grapheme_width; |
| 1832 | } |
| 1833 | if !chunk.is_empty() { |
| 1834 | record_inline_link(&mut current_links, &word, 0, chunk_w); |
| 1835 | current_spans.push(word.span_for(chunk)); |
| 1836 | current_width = chunk_w; |
| 1837 | } |
| 1838 | continue; |
| 1839 | } |
| 1840 | // Wrap before this word if it doesn't fit. |
| 1841 | if current_width > 0 && current_width + ww > width { |
| 1842 | // Trim trailing space span before breaking. |
| 1843 | push_inline_line( |
| 1844 | &mut lines, |
| 1845 | &mut current_spans, |
| 1846 | &mut current_links, |
| 1847 | CopyLineSeparator::Space, |
| 1848 | ); |
| 1849 | current_width = 0; |
| 1850 | } |
| 1851 | record_inline_link(&mut current_links, &word, current_width, ww); |
| 1852 | current_spans.push(word.into_span()); |
| 1853 | current_width += ww; |
| 1854 | } |
| 1855 | |
| 1856 | if !current_spans.is_empty() { |
| 1857 | push_inline_line( |
| 1858 | &mut lines, |
| 1859 | &mut current_spans, |
| 1860 | &mut current_links, |
| 1861 | CopyLineSeparator::Newline, |
| 1862 | ); |
| 1863 | } else if let Some(last) = lines.last_mut() { |
| 1864 | last.copy_separator_after = CopyLineSeparator::Newline; |
| 1865 | } |
| 1866 | if lines.is_empty() { |
| 1867 | lines.push(RenderedMarkdownLine { |
| 1868 | line: Line::from(""), |
| 1869 | links: Vec::new(), |
| 1870 | is_code: false, |
| 1871 | copy_prefix_width: 0, |
| 1872 | copy_separator_after: CopyLineSeparator::Newline, |
| 1873 | }); |
| 1874 | } |
| 1875 | lines |
| 1876 | } |
| 1877 | |
| 1878 | fn push_inline_line( |
| 1879 | lines: &mut Vec<RenderedMarkdownLine>, |
| 1880 | spans: &mut Vec<Span<'static>>, |
| 1881 | links: &mut Vec<osc8::LineLink>, |
| 1882 | copy_separator_after: CopyLineSeparator, |
| 1883 | ) { |
| 1884 | if let Some(last) = spans.last() |
| 1885 | && last.content.as_ref() == " " |
| 1886 | { |
| 1887 | spans.pop(); |
| 1888 | } |
| 1889 | let visible_width = spans |
| 1890 | .iter() |
| 1891 | .map(|span| span.content.as_ref().width()) |
| 1892 | .sum::<usize>(); |
| 1893 | links.retain(|link| link.col_start < visible_width); |
| 1894 | for link in links.iter_mut() { |
| 1895 | link.col_end = link.col_end.min(visible_width.saturating_sub(1)); |
| 1896 | } |
| 1897 | lines.push(RenderedMarkdownLine { |
| 1898 | line: Line::from(std::mem::take(spans)), |
| 1899 | links: std::mem::take(links), |
| 1900 | is_code: false, |
| 1901 | copy_prefix_width: 0, |
| 1902 | copy_separator_after, |
| 1903 | }); |
| 1904 | } |
| 1905 | |
| 1906 | fn record_inline_link( |
| 1907 | links: &mut Vec<osc8::LineLink>, |
| 1908 | token: &InlineToken, |
| 1909 | col_start: usize, |
| 1910 | width: usize, |
| 1911 | ) { |
| 1912 | let Some(target) = token.link_url.as_ref() else { |
| 1913 | return; |
| 1914 | }; |
| 1915 | if width == 0 { |
| 1916 | return; |
| 1917 | } |
| 1918 | let col_end = col_start.saturating_add(width).saturating_sub(1); |
| 1919 | if let Some(last) = links.last_mut() |
| 1920 | && last.target == *target |
| 1921 | && last.line == token.link_line |
| 1922 | && last.col_end.saturating_add(1) == col_start |
| 1923 | { |
| 1924 | last.col_end = col_end; |
| 1925 | return; |
| 1926 | } |
| 1927 | links.push(osc8::LineLink { |
| 1928 | col_start, |
| 1929 | col_end, |
| 1930 | target: target.clone(), |
| 1931 | line: token.link_line, |
| 1932 | }); |
| 1933 | } |
| 1934 | |
| 1935 | #[derive(Clone)] |
| 1936 | struct InlineToken { |
| 1937 | text: String, |
| 1938 | style: Style, |
| 1939 | link_url: Option<String>, |
| 1940 | link_line: Option<u32>, |
| 1941 | } |
| 1942 | |
| 1943 | impl InlineToken { |
| 1944 | fn new(text: String, style: Style, link_url: Option<String>) -> Self { |
| 1945 | Self::with_line(text, style, link_url, None) |
| 1946 | } |
| 1947 | |
| 1948 | fn with_line( |
| 1949 | text: String, |
| 1950 | style: Style, |
| 1951 | link_url: Option<String>, |
| 1952 | link_line: Option<u32>, |
| 1953 | ) -> Self { |
| 1954 | Self { |
| 1955 | text, |
| 1956 | style, |
| 1957 | link_url, |
| 1958 | link_line, |
| 1959 | } |
| 1960 | } |
| 1961 | |
| 1962 | fn span_for(&self, text: String) -> Span<'static> { |
| 1963 | Span::styled(text, self.style) |
| 1964 | } |
| 1965 | |
| 1966 | fn into_span(self) -> Span<'static> { |
| 1967 | Span::styled(self.text, self.style) |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | /// Parse an entire line into (text, style) segments, handling **bold**, |
| 1972 | /// *italic*, `code`, ~~strikethrough~~, `[text](url)` links, bare URLs, and |
| 1973 | /// `<br>`, which comes out as a token holding only a newline. |
| 1974 | #[cfg(test)] |
| 1975 | fn parse_inline_spans(line: &str, base_style: Style, link_style: Style) -> Vec<InlineToken> { |
| 1976 | parse_inline_spans_with_links(line, base_style, link_style, &mut None) |
| 1977 | } |
| 1978 | |
| 1979 | fn parse_inline_spans_with_links( |
| 1980 | line: &str, |
| 1981 | base_style: Style, |
| 1982 | link_style: Style, |
| 1983 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 1984 | ) -> Vec<InlineToken> { |
| 1985 | let bold_style = base_style.add_modifier(Modifier::BOLD); |
| 1986 | let italic_style = base_style.add_modifier(Modifier::ITALIC); |
| 1987 | let code_style = base_style |
| 1988 | .add_modifier(Modifier::ITALIC) |
| 1989 | .bg(palette::SURFACE_ELEVATED); |
| 1990 | let code_link_style = code_style.fg(link_style.fg.unwrap_or(palette::WHALE_ACTION)); |
| 1991 | let strike_style = base_style.add_modifier(Modifier::CROSSED_OUT); |
| 1992 | let mut out = Vec::new(); |
| 1993 | let mut rest = line; |
| 1994 | |
| 1995 | while !rest.is_empty() { |
| 1996 | // Backslash escape (CommonMark §2.4): `\` before ASCII punctuation |
| 1997 | // yields the literal character. Producers escape untrusted text |
| 1998 | // (plugin names, paths) this way so it cannot open markup; without |
| 1999 | // this arm the backslash itself reached the terminal |
| 2000 | // (`computer\-use`, `0\.1\.0` — 0.9.12 defect #21). |
| 2001 | if let Some(escaped) = rest.strip_prefix('\\') |
| 2002 | && let Some(ch) = escaped.chars().next() |
| 2003 | && ch.is_ascii_punctuation() |
| 2004 | { |
| 2005 | // Carry any combining marks that extend the escaped character into |
| 2006 | // one grapheme cluster: `\*️⃣` escapes the `*` of a keycap, and |
| 2007 | // emitting that `*` alone left the two marks in a span of their own. |
| 2008 | let cluster = escaped.graphemes(true).next().unwrap_or_default(); |
| 2009 | out.push(InlineToken::new(cluster.to_string(), base_style, None)); |
| 2010 | rest = &escaped[cluster.len()..]; |
| 2011 | continue; |
| 2012 | } |
| 2013 | // **bold** |
| 2014 | if let Some(end) = rest.strip_prefix("**").and_then(|s| s.find("**")) { |
| 2015 | let inner = &rest[2..2 + end]; |
| 2016 | if !inner.starts_with(char::is_whitespace) && !inner.ends_with(char::is_whitespace) { |
| 2017 | out.extend(parse_inline_spans_with_links( |
| 2018 | inner, bold_style, link_style, resolver, |
| 2019 | )); |
| 2020 | rest = &rest[2 + end + 2..]; |
| 2021 | continue; |
| 2022 | } |
| 2023 | } |
| 2024 | // __bold__ |
| 2025 | if let Some(end) = rest.strip_prefix("__").and_then(|s| s.find("__")) { |
| 2026 | let inner = &rest[2..2 + end]; |
| 2027 | out.extend(parse_inline_spans_with_links( |
| 2028 | inner, bold_style, link_style, resolver, |
| 2029 | )); |
| 2030 | rest = &rest[2 + end + 2..]; |
| 2031 | continue; |
| 2032 | } |
| 2033 | // *italic* |
| 2034 | if rest.starts_with('*') |
| 2035 | && !rest.starts_with("**") |
| 2036 | // The first grapheme has to be a lone `*`. When it is the base of a |
| 2037 | // cluster (`*️⃣` is U+002A U+FE0F U+20E3) it is not a delimiter, so |
| 2038 | // treating it as one ate the `*` and split the marks off. |
| 2039 | && rest.graphemes(true).next() == Some("*") |
| 2040 | && let Some(end) = rest[1..].find('*') |
| 2041 | { |
| 2042 | let inner = &rest[1..1 + end]; |
| 2043 | let after = &rest[1 + end + 1..]; |
| 2044 | // Closing delimiter must not be immediately followed by a |
| 2045 | // letter, digit, or underscore (otherwise it's part of an |
| 2046 | // identifier like `codewhale_tui`, not italic markup). |
| 2047 | if !inner.starts_with(char::is_whitespace) |
| 2048 | && !inner.ends_with(char::is_whitespace) |
| 2049 | && !after.starts_with(|c: char| c.is_alphanumeric() || c == '_') |
| 2050 | { |
| 2051 | out.extend(parse_inline_spans_with_links( |
| 2052 | inner, |
| 2053 | italic_style, |
| 2054 | link_style, |
| 2055 | resolver, |
| 2056 | )); |
| 2057 | rest = after; |
| 2058 | continue; |
| 2059 | } |
| 2060 | } |
| 2061 | // _italic_ |
| 2062 | if rest.starts_with('_') |
| 2063 | && !rest.starts_with("__") |
| 2064 | && rest.graphemes(true).next() == Some("_") |
| 2065 | && let Some(end) = rest[1..].find('_') |
| 2066 | { |
| 2067 | let inner = &rest[1..1 + end]; |
| 2068 | let after = &rest[1 + end + 1..]; |
| 2069 | // CommonMark forbids an intraword `_` from opening emphasis and |
| 2070 | // requires the opener to be left-flanking (not followed by |
| 2071 | // whitespace). Guarding only the closer let `b_p … t_?` italicize |
| 2072 | // the prose between two math subscripts (#6042). |
| 2073 | let preceded_by_word = line[..line.len() - rest.len()] |
| 2074 | .chars() |
| 2075 | .next_back() |
| 2076 | .is_some_and(char::is_alphanumeric); |
| 2077 | let openable = |
| 2078 | !preceded_by_word && inner.chars().next().is_some_and(|c| !c.is_whitespace()); |
| 2079 | // Closing delimiter must not be immediately followed by a |
| 2080 | // letter, digit, or underscore. |
| 2081 | if openable && !after.starts_with(|c: char| c.is_alphanumeric() || c == '_') { |
| 2082 | out.extend(parse_inline_spans_with_links( |
| 2083 | inner, |
| 2084 | italic_style, |
| 2085 | link_style, |
| 2086 | resolver, |
| 2087 | )); |
| 2088 | rest = after; |
| 2089 | continue; |
| 2090 | } |
| 2091 | } |
| 2092 | // `inline code` |
| 2093 | let ticks = rest.bytes().take_while(|byte| *byte == b'`').count(); |
| 2094 | if ticks > 0 { |
| 2095 | let body = &rest[ticks..]; |
| 2096 | let Some(end) = closing_backtick_run(body, ticks) else { |
| 2097 | out.push(InlineToken::new( |
| 2098 | rest[..ticks].to_string(), |
| 2099 | base_style, |
| 2100 | None, |
| 2101 | )); |
| 2102 | rest = body; |
| 2103 | continue; |
| 2104 | }; |
| 2105 | let inner = &body[..end]; |
| 2106 | let inner = match inner.strip_prefix(' ').and_then(|s| s.strip_suffix(' ')) { |
| 2107 | Some(padded) if !inner.trim_matches(' ').is_empty() => padded, |
| 2108 | _ => inner, |
| 2109 | }; |
| 2110 | let trimmed = inner.trim(); |
| 2111 | let (style, target, link_line) = match classify_inline_code(trimmed) { |
| 2112 | Some(InlineCodeKind::Url) => { |
| 2113 | if let Some(target) = normalized_http_link_target(trimmed) { |
| 2114 | (code_link_style, Some(target), None) |
| 2115 | } else { |
| 2116 | (code_style, None, None) |
| 2117 | } |
| 2118 | } |
| 2119 | Some(InlineCodeKind::Path) => { |
| 2120 | if let Some(resolver_fn) = resolver.as_deref_mut() |
| 2121 | && let Some(resolved) = resolver_fn(trimmed) |
| 2122 | && let Some(target) = normalized_link_target(&resolved.target) |
| 2123 | { |
| 2124 | (code_link_style, Some(target), resolved.line) |
| 2125 | } else { |
| 2126 | (code_style, None, None) |
| 2127 | } |
| 2128 | } |
| 2129 | None => (code_style, None, None), |
| 2130 | }; |
| 2131 | out.push(InlineToken::with_line( |
| 2132 | inner.to_string(), |
| 2133 | style, |
| 2134 | target, |
| 2135 | link_line, |
| 2136 | )); |
| 2137 | rest = &body[end + ticks..]; |
| 2138 | continue; |
| 2139 | } |
| 2140 | // ~~strikethrough~~ |
| 2141 | if let Some(end) = rest.strip_prefix("~~").and_then(|s| s.find("~~")) { |
| 2142 | let inner = &rest[2..2 + end]; |
| 2143 | out.extend(parse_inline_spans_with_links( |
| 2144 | inner, |
| 2145 | strike_style, |
| 2146 | link_style, |
| 2147 | resolver, |
| 2148 | )); |
| 2149 | rest = &rest[2 + end + 2..]; |
| 2150 | continue; |
| 2151 | } |
| 2152 | // [text](url),  and [](href) |
| 2153 | let image = usize::from(rest.starts_with("![")); |
| 2154 | if let Some((text, url, link_len)) = split_markdown_link(&rest[image..]) { |
| 2155 | // The runtime toggle gates backend emission, not layout. |
| 2156 | // Keeping the same visible label and metadata in both modes |
| 2157 | // prevents toggling OSC 8 from reflowing the transcript. |
| 2158 | let (target, link_line) = match normalized_link_target(&url) { |
| 2159 | Some(target) => (Some(target), None), |
| 2160 | None => { |
| 2161 | if let Some(resolver_fn) = resolver.as_deref_mut() |
| 2162 | && let Some(resolved) = resolver_fn(&url) |
| 2163 | && let Some(target) = normalized_link_target(&resolved.target) |
| 2164 | { |
| 2165 | (Some(target), resolved.line) |
| 2166 | } else { |
| 2167 | (None, None) |
| 2168 | } |
| 2169 | } |
| 2170 | }; |
| 2171 | out.push(InlineToken::with_line( |
| 2172 | decode_html_references(text), |
| 2173 | link_style, |
| 2174 | target, |
| 2175 | link_line, |
| 2176 | )); |
| 2177 | rest = &rest[image + link_len..]; |
| 2178 | continue; |
| 2179 | } |
| 2180 | // Keep trailing punctuation visible but outside the hyperlink target. |
| 2181 | if rest.starts_with("http://") || rest.starts_with("https://") { |
| 2182 | let token_end = rest |
| 2183 | .char_indices() |
| 2184 | .find_map(|(offset, ch)| { |
| 2185 | (ch.is_whitespace() |
| 2186 | || "。,、;:!?()「」『』【】《》〈〉“”‘’".contains(ch) |
| 2187 | || (ch == '<' && line_break_tag_len(&rest[offset..]).is_some())) |
| 2188 | .then_some(offset) |
| 2189 | }) |
| 2190 | .unwrap_or(rest.len()); |
| 2191 | let token = &rest[..token_end]; |
| 2192 | let url_end = trailing_url_end(token); |
| 2193 | let url = decode_html_references(&token[..url_end]); |
| 2194 | let target = normalized_http_link_target(&url); |
| 2195 | out.push(InlineToken::new(url, link_style, target)); |
| 2196 | if url_end < token_end { |
| 2197 | out.push(InlineToken::new( |
| 2198 | decode_html_references(&token[url_end..]), |
| 2199 | base_style, |
| 2200 | None, |
| 2201 | )); |
| 2202 | } |
| 2203 | rest = &rest[token_end..]; |
| 2204 | continue; |
| 2205 | } |
| 2206 | if let Some(len) = line_break_tag_len(rest) { |
| 2207 | out.push(InlineToken::new("\n".to_string(), base_style, None)); |
| 2208 | rest = rest[len..].trim_start_matches(' '); |
| 2209 | continue; |
| 2210 | } |
| 2211 | // Plain text: consume until next marker or URL; always advance at least 1 char. |
| 2212 | let next = find_next_marker(rest).max(rest.chars().next().map_or(1, |c| c.len_utf8())); |
| 2213 | // Never split a grapheme cluster. A marker character can be the base of |
| 2214 | // one: the `*` keycap is U+002A U+FE0F U+20E3, a single cluster, and |
| 2215 | // `*` alone is not emphasis here (no closing `*`), so the marker search |
| 2216 | // stops right after it. Cutting there left the two zero-width marks in |
| 2217 | // a span of their own; the terminal then drew the cluster two columns |
| 2218 | // wide while the spans reported one, and every separator after the cell |
| 2219 | // moved off the box. A digit keycap never hit this because a digit is |
| 2220 | // not a marker, which is why only `*` broke. |
| 2221 | let next = rest |
| 2222 | .grapheme_indices(true) |
| 2223 | .map(|(start, grapheme)| start + grapheme.len()) |
| 2224 | .find(|end| *end >= next) |
| 2225 | // `grapheme_indices` ends at `rest.len()`, so the find always |
| 2226 | // succeeds. Clamp rather than reuse `next` so a future change to |
| 2227 | // `find_next_marker` cannot slice out of bounds here. |
| 2228 | .unwrap_or(rest.len()); |
| 2229 | out.push(InlineToken::new( |
| 2230 | decode_html_references(&rest[..next]), |
| 2231 | base_style, |
| 2232 | None, |
| 2233 | )); |
| 2234 | rest = &rest[next..]; |
| 2235 | } |
| 2236 | out |
| 2237 | } |
| 2238 | |
| 2239 | /// Normalize an explicit markdown link destination, the only construct the |
| 2240 | /// renderer treats as a structured reference. Prose is never scanned for |
| 2241 | /// path-shaped text: that linkifies identifiers and version strings, and points |
| 2242 | /// at files that do not exist. |
| 2243 | fn normalized_link_target(target: &str) -> Option<String> { |
| 2244 | normalized_http_link_target(target).or_else(|| normalized_file_link_target(target)) |
| 2245 | } |
| 2246 | |
| 2247 | /// A destination that is already an absolute path, with or without the `file:` |
| 2248 | /// scheme. Relative destinations stay inert because this layer has no workspace |
| 2249 | /// root to resolve them against, and a `file://host/...` form is rejected rather |
| 2250 | /// than reinterpreted as local. Windows paths must therefore arrive pre-formed |
| 2251 | /// as `file:///C:/…`. |
| 2252 | fn normalized_file_link_target(target: &str) -> Option<String> { |
| 2253 | let path = match target.get(..7) { |
| 2254 | Some(prefix) if prefix.eq_ignore_ascii_case("file://") => &target[7..], |
| 2255 | _ => target, |
| 2256 | }; |
| 2257 | if !path.starts_with('/') || path.chars().any(|ch| ch.is_whitespace() || ch.is_control()) { |
| 2258 | return None; |
| 2259 | } |
| 2260 | Some(format!("file://{path}")) |
| 2261 | } |
| 2262 | |
| 2263 | /// OSC 8 targets produced by markdown are deliberately limited to ordinary |
| 2264 | /// web URLs. The browser-opening gesture is user-initiated, but accepting |
| 2265 | /// arbitrary schemes here would still turn untrusted model output into a |
| 2266 | /// `javascript:` or application-protocol link. Normalize the scheme and reject |
| 2267 | /// whitespace/control characters before metadata reaches a frame. |
| 2268 | fn normalized_http_link_target(target: &str) -> Option<String> { |
| 2269 | let (scheme, rest) = if target |
| 2270 | .get(..8) |
| 2271 | .is_some_and(|prefix| prefix.eq_ignore_ascii_case("https://")) |
| 2272 | { |
| 2273 | ("https://", &target[8..]) |
| 2274 | } else if target |
| 2275 | .get(..7) |
| 2276 | .is_some_and(|prefix| prefix.eq_ignore_ascii_case("http://")) |
| 2277 | { |
| 2278 | ("http://", &target[7..]) |
| 2279 | } else { |
| 2280 | return None; |
| 2281 | }; |
| 2282 | if rest.is_empty() |
| 2283 | || rest.chars().any(|ch| ch.is_whitespace() || ch.is_control()) |
| 2284 | || rest.split(['/', '?', '#']).next().is_none_or(str::is_empty) |
| 2285 | { |
| 2286 | return None; |
| 2287 | } |
| 2288 | Some(format!("{scheme}{rest}")) |
| 2289 | } |
| 2290 | |
| 2291 | fn trailing_url_end(candidate: &str) -> usize { |
| 2292 | let mut end = candidate.len(); |
| 2293 | while end > 0 { |
| 2294 | let remaining = &candidate[..end]; |
| 2295 | if let Some(start) = remaining |
| 2296 | .as_bytes() |
| 2297 | .iter() |
| 2298 | .enumerate() |
| 2299 | .rev() |
| 2300 | .take(10) |
| 2301 | .find_map(|(index, byte)| (*byte == b'&').then_some(index)) |
| 2302 | && html_character_reference(&remaining[start..]) |
| 2303 | .is_some_and(|(_, len)| start + len == end) |
| 2304 | { |
| 2305 | end = start; |
| 2306 | continue; |
| 2307 | } |
| 2308 | let Some(ch) = remaining.chars().next_back() else { |
| 2309 | break; |
| 2310 | }; |
| 2311 | let trim = matches!(ch, ',' | '.' | ';' | '!' | '\'' | '"') |
| 2312 | || matches!(ch, ')' | ']' | '}' | '>') |
| 2313 | && has_unmatched_closing_delimiter(remaining, ch); |
| 2314 | if !trim { |
| 2315 | break; |
| 2316 | } |
| 2317 | end -= ch.len_utf8(); |
| 2318 | } |
| 2319 | end |
| 2320 | } |
| 2321 | |
| 2322 | fn split_markdown_link(source: &str) -> Option<(&str, String, usize)> { |
| 2323 | let label = source.strip_prefix('[')?; |
| 2324 | if let Some(image) = label.strip_prefix('!') |
| 2325 | && let Some(alt_end) = image.strip_prefix('[').and_then(|alt| alt.find(']')) |
| 2326 | && let Some((_, image_tail)) = split_link_destination(&image[1 + alt_end..]) |
| 2327 | && let Some((href, tail)) = split_link_destination(&image[1 + alt_end + image_tail..]) |
| 2328 | { |
| 2329 | return Some(( |
| 2330 | &image[1..1 + alt_end], |
| 2331 | href, |
| 2332 | 3 + alt_end + image_tail + tail, |
| 2333 | )); |
| 2334 | } |
| 2335 | let label_end = label.find(']')?; |
| 2336 | let (url, tail) = split_link_destination(&label[label_end..])?; |
| 2337 | Some((&label[..label_end], url, 1 + label_end + tail)) |
| 2338 | } |
| 2339 | |
| 2340 | fn split_link_destination(after_label: &str) -> Option<(String, usize)> { |
| 2341 | let destination = after_label.strip_prefix("](")?; |
| 2342 | if let Some((target, rest)) = split_angle_link_destination(destination) { |
| 2343 | return Some((target, after_label.len() - rest.len())); |
| 2344 | } |
| 2345 | let end = destination |
| 2346 | .match_indices(')') |
| 2347 | .map(|(index, _)| index) |
| 2348 | .find(|&index| has_unmatched_closing_delimiter(&destination[..=index], ')'))?; |
| 2349 | Some((decode_html_references(&destination[..end]), end + 3)) |
| 2350 | } |
| 2351 | |
| 2352 | fn split_angle_link_destination(destination: &str) -> Option<(String, &str)> { |
| 2353 | let mut rest = destination |
| 2354 | .trim_start_matches([' ', '\t']) |
| 2355 | .strip_prefix('<')?; |
| 2356 | let mut target = String::new(); |
| 2357 | while let Some(index) = rest.find(['\\', '&', '<', '>', '\r', '\n']) { |
| 2358 | target.push_str(&rest[..index]); |
| 2359 | rest = &rest[index..]; |
| 2360 | let (ch, len) = match rest.as_bytes()[0] { |
| 2361 | b'>' => { |
| 2362 | let tail = rest[1..] |
| 2363 | .trim_start_matches([' ', '\t']) |
| 2364 | .strip_prefix(')')?; |
| 2365 | return Some((target, tail)); |
| 2366 | } |
| 2367 | b'\\' => rest |
| 2368 | .as_bytes() |
| 2369 | .get(1) |
| 2370 | .copied() |
| 2371 | .filter(u8::is_ascii_punctuation) |
| 2372 | .map_or(('\\', 1), |byte| (char::from(byte), 2)), |
| 2373 | b'&' => html_character_reference(rest).unwrap_or(('&', 1)), |
| 2374 | _ => return None, |
| 2375 | }; |
| 2376 | target.push(ch); |
| 2377 | rest = &rest[len..]; |
| 2378 | } |
| 2379 | None |
| 2380 | } |
| 2381 | |
| 2382 | fn has_unmatched_closing_delimiter(candidate: &str, closing: char) -> bool { |
| 2383 | let opening = match closing { |
| 2384 | ')' => '(', |
| 2385 | ']' => '[', |
| 2386 | '}' => '{', |
| 2387 | '>' => '<', |
| 2388 | _ => return false, |
| 2389 | }; |
| 2390 | candidate.chars().filter(|ch| *ch == closing).count() |
| 2391 | > candidate.chars().filter(|ch| *ch == opening).count() |
| 2392 | } |
| 2393 | |
| 2394 | fn html_character_reference(source: &str) -> Option<(char, usize)> { |
| 2395 | let end = source.bytes().take(10).position(|byte| byte == b';')?; |
| 2396 | let name = source.get(..end)?.strip_prefix('&')?; |
| 2397 | let ch = match name { |
| 2398 | "amp" => '&', |
| 2399 | "lt" => '<', |
| 2400 | "gt" => '>', |
| 2401 | "quot" => '"', |
| 2402 | "apos" => '\'', |
| 2403 | "nbsp" => '\u{00A0}', |
| 2404 | "copy" => '\u{00A9}', |
| 2405 | "reg" => '\u{00AE}', |
| 2406 | "mdash" => '\u{2014}', |
| 2407 | "ndash" => '\u{2013}', |
| 2408 | "lsquo" => '\u{2018}', |
| 2409 | "rsquo" => '\u{2019}', |
| 2410 | "ldquo" => '\u{201C}', |
| 2411 | "rdquo" => '\u{201D}', |
| 2412 | "hellip" => '\u{2026}', |
| 2413 | _ => { |
| 2414 | let number = name.strip_prefix('#')?; |
| 2415 | let (digits, radix) = match number.strip_prefix(['x', 'X']) { |
| 2416 | Some(hex) => (hex, 16), |
| 2417 | None => (number, 10), |
| 2418 | }; |
| 2419 | if !digits.chars().all(|digit| digit.is_digit(radix)) { |
| 2420 | return None; |
| 2421 | } |
| 2422 | char::from_u32(u32::from_str_radix(digits, radix).ok()?).filter(|ch| { |
| 2423 | !ch.is_control() |
| 2424 | && codewhale_sanitize::sanitize::hidden_chars(ch.encode_utf8(&mut [0; 4])) |
| 2425 | .is_empty() |
| 2426 | })? |
| 2427 | } |
| 2428 | }; |
| 2429 | Some((ch, end + 1)) |
| 2430 | } |
| 2431 | |
| 2432 | fn decode_html_references(text: &str) -> String { |
| 2433 | let mut decoded = String::with_capacity(text.len()); |
| 2434 | let mut rest = text; |
| 2435 | while let Some(start) = rest.find('&') { |
| 2436 | decoded.push_str(&rest[..start]); |
| 2437 | rest = &rest[start..]; |
| 2438 | let (ch, len) = html_character_reference(rest).unwrap_or(('&', 1)); |
| 2439 | decoded.push(ch); |
| 2440 | rest = &rest[len..]; |
| 2441 | } |
| 2442 | decoded.push_str(rest); |
| 2443 | decoded |
| 2444 | } |
| 2445 | |
| 2446 | fn closing_backtick_run(body: &str, ticks: usize) -> Option<usize> { |
| 2447 | let mut start = 0; |
| 2448 | while let Some(offset) = body[start..].find('`') { |
| 2449 | let run_start = start + offset; |
| 2450 | let run = body[run_start..] |
| 2451 | .bytes() |
| 2452 | .take_while(|byte| *byte == b'`') |
| 2453 | .count(); |
| 2454 | if run == ticks { |
| 2455 | return Some(run_start); |
| 2456 | } |
| 2457 | start = run_start + run; |
| 2458 | } |
| 2459 | None |
| 2460 | } |
| 2461 | |
| 2462 | /// Find the index of the next inline marker (`**`, `__`, `*`, `_`, `http`) |
| 2463 | /// in `s`, or `s.len()` if none found. |
| 2464 | fn find_next_marker(s: &str) -> usize { |
| 2465 | let mut i = 0; |
| 2466 | let bytes = s.as_bytes(); |
| 2467 | while i < bytes.len() { |
| 2468 | let ch_len = s[i..].chars().next().map_or(1, |c| c.len_utf8()); |
| 2469 | let slice = &s[i..]; |
| 2470 | if slice.starts_with('\\') |
| 2471 | || slice.starts_with("**") |
| 2472 | || slice.starts_with("__") |
| 2473 | || slice.starts_with("~~") |
| 2474 | || slice.starts_with('`') |
| 2475 | || slice.starts_with('[') |
| 2476 | || slice.starts_with("![") |
| 2477 | || (slice.starts_with('*') && !slice.starts_with("**")) |
| 2478 | || (slice.starts_with('_') && !slice.starts_with("__")) |
| 2479 | || slice.starts_with("http://") |
| 2480 | || slice.starts_with("https://") |
| 2481 | || line_break_tag_len(slice).is_some() |
| 2482 | { |
| 2483 | return i; |
| 2484 | } |
| 2485 | i += ch_len; |
| 2486 | } |
| 2487 | s.len() |
| 2488 | } |
| 2489 | |
| 2490 | fn line_break_tag_len(text: &str) -> Option<usize> { |
| 2491 | let rest = text.strip_prefix('<')?; |
| 2492 | if !rest.get(..2)?.eq_ignore_ascii_case("br") { |
| 2493 | return None; |
| 2494 | } |
| 2495 | let tail = rest[2..].trim_start_matches(' '); |
| 2496 | let close = tail.strip_prefix('/').unwrap_or(tail); |
| 2497 | close.strip_prefix('>')?; |
| 2498 | Some(text.len() - close.len() + 1) |
| 2499 | } |
| 2500 | |
| 2501 | fn is_horizontal_rule(line: &str) -> bool { |
| 2502 | let stripped: String = line.chars().filter(|c| !c.is_whitespace()).collect(); |
| 2503 | (stripped.chars().all(|c| c == '-') |
| 2504 | || stripped.chars().all(|c| c == '*') |
| 2505 | || stripped.chars().all(|c| c == '_')) |
| 2506 | && stripped.len() >= 3 |
| 2507 | } |
| 2508 | |
| 2509 | /// Parse a markdown table row like `| foo | bar |` into trimmed cell strings. |
| 2510 | /// Returns `None` for separator rows (`|---|---|`). |
| 2511 | fn parse_table_row(line: &str) -> Option<Vec<String>> { |
| 2512 | if !line.starts_with('|') { |
| 2513 | return None; |
| 2514 | } |
| 2515 | let inner = line.trim_matches('|'); |
| 2516 | let cells = split_table_cells(inner); |
| 2517 | // Separator row: every non-empty cell is only dashes/colons/spaces |
| 2518 | if cells |
| 2519 | .iter() |
| 2520 | .all(|c| c.is_empty() || c.chars().all(|ch| ch == '-' || ch == ':' || ch == ' ')) |
| 2521 | { |
| 2522 | return None; |
| 2523 | } |
| 2524 | Some(cells) |
| 2525 | } |
| 2526 | |
| 2527 | fn split_table_cells(inner: &str) -> Vec<String> { |
| 2528 | let mut cells = Vec::new(); |
| 2529 | let mut current = String::new(); |
| 2530 | let mut in_code = false; |
| 2531 | let mut chars = inner.chars().peekable(); |
| 2532 | |
| 2533 | while let Some(ch) = chars.next() { |
| 2534 | match ch { |
| 2535 | '\\' => { |
| 2536 | if matches!(chars.peek(), Some('|')) { |
| 2537 | current.push('|'); |
| 2538 | let _ = chars.next(); |
| 2539 | } else { |
| 2540 | current.push(ch); |
| 2541 | } |
| 2542 | } |
| 2543 | '`' => { |
| 2544 | in_code = !in_code; |
| 2545 | current.push(ch); |
| 2546 | } |
| 2547 | '|' if !in_code => { |
| 2548 | cells.push(current.trim().to_string()); |
| 2549 | current.clear(); |
| 2550 | } |
| 2551 | _ => current.push(ch), |
| 2552 | } |
| 2553 | } |
| 2554 | |
| 2555 | cells.push(current.trim().to_string()); |
| 2556 | cells |
| 2557 | } |
| 2558 | |
| 2559 | fn render_table_row( |
| 2560 | cells: &[String], |
| 2561 | widths: &[usize], |
| 2562 | base_style: Style, |
| 2563 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 2564 | ) -> Vec<RenderedMarkdownLine> { |
| 2565 | let sep_style = Style::default().fg(palette::TEXT_DIM); |
| 2566 | |
| 2567 | // Wrap each cell into one or more visual segments. The row's visual |
| 2568 | // height equals the tallest column. Cells that wrap to fewer segments |
| 2569 | // get blank-padded continuation lines so column separators stay aligned. |
| 2570 | let mut wrapped: Vec<Vec<RenderedMarkdownLine>> = widths |
| 2571 | .iter() |
| 2572 | .enumerate() |
| 2573 | .map(|(i, &col_width)| { |
| 2574 | let cell = cells.get(i).map_or("", String::as_str); |
| 2575 | let mut tokens = |
| 2576 | parse_inline_spans_with_links(cell, base_style, link_style(), resolver); |
| 2577 | if tokens.last().is_some_and(|token| token.text == "\n") { |
| 2578 | tokens.pop(); |
| 2579 | } |
| 2580 | let rows: Vec<&[InlineToken]> = tokens.split(|token| token.text == "\n").collect(); |
| 2581 | if rows |
| 2582 | .iter() |
| 2583 | .any(|row| row.iter().map(|token| token.text.width()).sum::<usize>() > col_width) |
| 2584 | { |
| 2585 | return render_line_with_links_tagged( |
| 2586 | cell, |
| 2587 | col_width, |
| 2588 | base_style, |
| 2589 | link_style(), |
| 2590 | resolver, |
| 2591 | ); |
| 2592 | } |
| 2593 | rows.into_iter() |
| 2594 | .map(|row| { |
| 2595 | let mut spans = Vec::with_capacity(row.len()); |
| 2596 | let mut links = Vec::new(); |
| 2597 | let mut column = 0; |
| 2598 | for token in row { |
| 2599 | let token_width = token.text.width(); |
| 2600 | record_inline_link(&mut links, token, column, token_width); |
| 2601 | column += token_width; |
| 2602 | spans.push(token.span_for(token.text.clone())); |
| 2603 | } |
| 2604 | RenderedMarkdownLine { |
| 2605 | line: Line::from(spans), |
| 2606 | links, |
| 2607 | is_code: false, |
| 2608 | copy_prefix_width: 0, |
| 2609 | copy_separator_after: CopyLineSeparator::Newline, |
| 2610 | } |
| 2611 | }) |
| 2612 | .collect() |
| 2613 | }) |
| 2614 | .collect(); |
| 2615 | let row_height = wrapped.iter().map(Vec::len).max().unwrap_or(1).max(1); |
| 2616 | |
| 2617 | let mut lines = Vec::with_capacity(row_height); |
| 2618 | for row in 0..row_height { |
| 2619 | let border = "│ "; |
| 2620 | let mut spans = vec![Span::styled(border, sep_style)]; |
| 2621 | let mut column = border.width(); |
| 2622 | let mut links = Vec::new(); |
| 2623 | for (i, cell_segments) in wrapped.iter_mut().enumerate() { |
| 2624 | let mut cell_width = 0; |
| 2625 | if let Some(segment) = cell_segments.get_mut(row) { |
| 2626 | cell_width = segment.line.width(); |
| 2627 | links.extend(segment.links.iter().map(|link| link.shifted(column))); |
| 2628 | spans.append(&mut segment.line.spans); |
| 2629 | } |
| 2630 | let pad = widths[i].saturating_sub(cell_width); |
| 2631 | spans.push(Span::raw(" ".repeat(pad))); |
| 2632 | let separator = if i + 1 < widths.len() { |
| 2633 | " │ " |
| 2634 | } else { |
| 2635 | " │" |
| 2636 | }; |
| 2637 | column += cell_width + pad + separator.width(); |
| 2638 | spans.push(Span::styled(separator, sep_style)); |
| 2639 | } |
| 2640 | lines.push(RenderedMarkdownLine { |
| 2641 | line: Line::from(spans), |
| 2642 | links, |
| 2643 | is_code: false, |
| 2644 | copy_prefix_width: 0, |
| 2645 | copy_separator_after: CopyLineSeparator::Newline, |
| 2646 | }); |
| 2647 | } |
| 2648 | lines |
| 2649 | } |
| 2650 | |
| 2651 | fn table_col_widths(blocks: &[Block], num_cols: usize, term_width: usize) -> Vec<usize> { |
| 2652 | let mut wanted = vec![0; num_cols]; |
| 2653 | for block in blocks { |
| 2654 | if let Block::TableRow(cells) = block { |
| 2655 | for (col_wanted, cell) in wanted.iter_mut().zip(cells) { |
| 2656 | let tokens = parse_inline_spans_with_links( |
| 2657 | cell, |
| 2658 | Style::default(), |
| 2659 | Style::default(), |
| 2660 | &mut None, |
| 2661 | ); |
| 2662 | for row in tokens.split(|token| token.text == "\n") { |
| 2663 | let row_width = row.iter().map(|token| token.text.width()).sum(); |
| 2664 | *col_wanted = (*col_wanted).max(row_width); |
| 2665 | } |
| 2666 | } |
| 2667 | } |
| 2668 | } |
| 2669 | |
| 2670 | let mut narrowest_first: Vec<usize> = (0..num_cols).collect(); |
| 2671 | narrowest_first.sort_by_key(|&col| wanted[col]); |
| 2672 | let mut room = term_width.saturating_sub(3 * num_cols + 1); |
| 2673 | let mut widths = vec![0; num_cols]; |
| 2674 | for (placed, &col) in narrowest_first.iter().enumerate() { |
| 2675 | let share = room / (num_cols - placed); |
| 2676 | widths[col] = wanted[col].min(share.max(4)); |
| 2677 | room = room.saturating_sub(widths[col]); |
| 2678 | } |
| 2679 | widths |
| 2680 | } |
| 2681 | |
| 2682 | fn render_table_border( |
| 2683 | widths: &[usize], |
| 2684 | sep_style: Style, |
| 2685 | left: &str, |
| 2686 | mid: &str, |
| 2687 | right: &str, |
| 2688 | ) -> RenderedMarkdownLine { |
| 2689 | let mut s = String::new(); |
| 2690 | s.push_str(left); |
| 2691 | for (i, &col_width) in widths.iter().enumerate() { |
| 2692 | s.push_str(&"\u{2500}".repeat(col_width)); |
| 2693 | if i + 1 < widths.len() { |
| 2694 | s.push_str(mid); |
| 2695 | } else { |
| 2696 | s.push_str(right); |
| 2697 | } |
| 2698 | } |
| 2699 | RenderedMarkdownLine { |
| 2700 | line: Line::from(Span::styled(s, sep_style)), |
| 2701 | links: Vec::new(), |
| 2702 | is_code: false, |
| 2703 | copy_prefix_width: 0, |
| 2704 | copy_separator_after: CopyLineSeparator::Newline, |
| 2705 | } |
| 2706 | } |
| 2707 | |
| 2708 | fn render_table_group( |
| 2709 | blocks: &[Block], |
| 2710 | width: usize, |
| 2711 | base_style: Style, |
| 2712 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 2713 | ) -> Vec<RenderedMarkdownLine> { |
| 2714 | let sep_style = Style::default().fg(palette::TEXT_DIM); |
| 2715 | |
| 2716 | let num_cols = blocks |
| 2717 | .iter() |
| 2718 | .filter_map(|b| match b { |
| 2719 | Block::TableRow(cells) => Some(cells.len()), |
| 2720 | _ => None, |
| 2721 | }) |
| 2722 | .max() |
| 2723 | .unwrap_or(1); |
| 2724 | |
| 2725 | let widths = table_col_widths(blocks, num_cols, width); |
| 2726 | if widths.iter().sum::<usize>() + 3 * num_cols + 1 > width { |
| 2727 | return render_stacked_table(blocks, width, base_style, resolver); |
| 2728 | } |
| 2729 | |
| 2730 | let mut lines = Vec::new(); |
| 2731 | |
| 2732 | // Top border |
| 2733 | lines.push(render_table_border( |
| 2734 | &widths, |
| 2735 | sep_style, |
| 2736 | "\u{250C}\u{2500}", |
| 2737 | "\u{2500}\u{252C}\u{2500}", |
| 2738 | "\u{2500}\u{2510}", |
| 2739 | )); |
| 2740 | |
| 2741 | let mid_border = || { |
| 2742 | render_table_border( |
| 2743 | &widths, |
| 2744 | sep_style, |
| 2745 | "\u{251C}\u{2500}", |
| 2746 | "\u{2500}\u{253C}\u{2500}", |
| 2747 | "\u{2500}\u{2524}", |
| 2748 | ) |
| 2749 | }; |
| 2750 | |
| 2751 | let header_end = blocks |
| 2752 | .iter() |
| 2753 | .position(|b| matches!(b, Block::TableSeparator)) |
| 2754 | .unwrap_or(0); |
| 2755 | |
| 2756 | for (i, block) in blocks.iter().enumerate() { |
| 2757 | match block { |
| 2758 | Block::TableRow(cells) => { |
| 2759 | let style = if i < header_end { |
| 2760 | base_style.add_modifier(Modifier::BOLD) |
| 2761 | } else { |
| 2762 | base_style |
| 2763 | }; |
| 2764 | lines.extend(render_table_row(cells, &widths, style, resolver)); |
| 2765 | } |
| 2766 | Block::TableSeparator => { |
| 2767 | lines.push(mid_border()); |
| 2768 | } |
| 2769 | _ => {} |
| 2770 | } |
| 2771 | } |
| 2772 | |
| 2773 | // Bottom border |
| 2774 | lines.push(render_table_border( |
| 2775 | &widths, |
| 2776 | sep_style, |
| 2777 | "\u{2514}\u{2500}", |
| 2778 | "\u{2500}\u{2534}\u{2500}", |
| 2779 | "\u{2500}\u{2518}", |
| 2780 | )); |
| 2781 | |
| 2782 | lines |
| 2783 | } |
| 2784 | |
| 2785 | fn render_stacked_table( |
| 2786 | blocks: &[Block], |
| 2787 | width: usize, |
| 2788 | base_style: Style, |
| 2789 | resolver: &mut Option<&mut WorkspaceLinkResolver<'_>>, |
| 2790 | ) -> Vec<RenderedMarkdownLine> { |
| 2791 | let header_end = blocks |
| 2792 | .iter() |
| 2793 | .position(|b| matches!(b, Block::TableSeparator)) |
| 2794 | .unwrap_or(0); |
| 2795 | let has_data = blocks[header_end..] |
| 2796 | .iter() |
| 2797 | .any(|b| matches!(b, Block::TableRow(_))); |
| 2798 | let (headers, rows) = if has_data { |
| 2799 | let headers = blocks[..header_end].iter().find_map(|b| match b { |
| 2800 | Block::TableRow(cells) => Some(cells.as_slice()), |
| 2801 | _ => None, |
| 2802 | }); |
| 2803 | (headers.unwrap_or(&[]), &blocks[header_end..]) |
| 2804 | } else { |
| 2805 | (&[][..], blocks) |
| 2806 | }; |
| 2807 | |
| 2808 | let mut lines = Vec::new(); |
| 2809 | for block in rows { |
| 2810 | let Block::TableRow(cells) = block else { |
| 2811 | continue; |
| 2812 | }; |
| 2813 | if !lines.is_empty() { |
| 2814 | lines.extend(render_line_with_links_tagged( |
| 2815 | "", |
| 2816 | width, |
| 2817 | base_style, |
| 2818 | link_style(), |
| 2819 | resolver, |
| 2820 | )); |
| 2821 | } |
| 2822 | for (col, cell) in cells.iter().enumerate() { |
| 2823 | let text = match headers.get(col) { |
| 2824 | Some(header) if !header.is_empty() => format!("{header}: {cell}"), |
| 2825 | _ => cell.clone(), |
| 2826 | }; |
| 2827 | lines.extend(render_line_with_links_tagged( |
| 2828 | &text, |
| 2829 | width, |
| 2830 | base_style, |
| 2831 | link_style(), |
| 2832 | resolver, |
| 2833 | )); |
| 2834 | } |
| 2835 | } |
| 2836 | lines |
| 2837 | } |
| 2838 | |
| 2839 | fn link_style() -> Style { |
| 2840 | Style::default() |
| 2841 | .fg(palette::WHALE_ACTION) |
| 2842 | .add_modifier(Modifier::UNDERLINED) |
| 2843 | } |
| 2844 | |
| 2845 | /// Display-column width of one extended grapheme for terminal line-wrap |
| 2846 | /// calculations. |
| 2847 | /// |
| 2848 | /// A tab advances to the next 8-column tab stop. Single-codepoint characters |
| 2849 | /// retain the previous one-column fallback (with an override for enclosed |
| 2850 | /// alphanumerics that render as 2 columns in CJK terminals). Multi-codepoint |
| 2851 | /// emoji, keycaps, and combining sequences use the same string-level width |
| 2852 | /// contract as Ratatui, with an override for keycap sequences containing |
| 2853 | /// U+20E3 that unicode-width undercounts. (#4479) |
| 2854 | fn markdown_grapheme_width(grapheme: &str, col: usize) -> usize { |
| 2855 | if grapheme == "\t" { |
| 2856 | return 8 - (col % 8); // advance to next 8-column tab stop |
| 2857 | } |
| 2858 | if let Some(ch) = grapheme.chars().next() |
| 2859 | && ch.len_utf8() == grapheme.len() |
| 2860 | { |
| 2861 | return match ch { |
| 2862 | // Enclosed alphanumerics, dingbat circled digits, and circled |
| 2863 | // numbers on black square render as 2 columns in CJK terminals |
| 2864 | // even though unicode-width reports 1. (#4479) |
| 2865 | '\u{2460}'..='\u{24FF}' | '\u{2776}'..='\u{2793}' | '\u{3248}'..='\u{324F}' => 2, |
| 2866 | _ => ch.width().unwrap_or(1), |
| 2867 | }; |
| 2868 | } |
| 2869 | // Keycap sequences (with or without FE0F) render as 2 columns. |
| 2870 | if grapheme.contains('\u{20e3}') { |
| 2871 | return 2; |
| 2872 | } |
| 2873 | grapheme.width() |
| 2874 | } |
| 2875 | |
| 2876 | #[cfg(test)] |
| 2877 | mod tests { |
| 2878 | use super::*; |
| 2879 | use ratatui::style::Style; |
| 2880 | |
| 2881 | fn visible_lines(lines: &[Line<'static>]) -> Vec<String> { |
| 2882 | lines |
| 2883 | .iter() |
| 2884 | .map(|line| { |
| 2885 | line.spans |
| 2886 | .iter() |
| 2887 | .map(|span| span.content.as_ref()) |
| 2888 | .collect() |
| 2889 | }) |
| 2890 | .collect() |
| 2891 | } |
| 2892 | |
| 2893 | /// Render `lines` into a fresh ratatui buffer at the given size. |
| 2894 | fn buffer_of(lines: &[Line<'static>], width: u16, height: u16) -> ratatui::buffer::Buffer { |
| 2895 | use ratatui::widgets::{Paragraph, Widget}; |
| 2896 | |
| 2897 | let area = ratatui::layout::Rect::new(0, 0, width, height); |
| 2898 | let mut buf = ratatui::buffer::Buffer::empty(area); |
| 2899 | Paragraph::new(lines.to_vec()).render(area, &mut buf); |
| 2900 | buf |
| 2901 | } |
| 2902 | |
| 2903 | /// True column indices in `buf` whose symbol is the `|` box-drawing |
| 2904 | /// separator. Scanning columns (not string chars) matters: a wide grapheme |
| 2905 | /// such as a keycap fills one cell and leaves the next empty, so a char |
| 2906 | /// index over a flattened row would not be a column index. |
| 2907 | fn border_columns(buf: &ratatui::buffer::Buffer, width: u16, y: u16) -> Vec<usize> { |
| 2908 | (0..width) |
| 2909 | .filter(|x| buf[(*x, y)].symbol() == "\u{2502}") |
| 2910 | .map(|x| x as usize) |
| 2911 | .collect() |
| 2912 | } |
| 2913 | |
| 2914 | /// Flatten one buffer row for assertion messages. |
| 2915 | fn row_text(buf: &ratatui::buffer::Buffer, width: u16, y: u16) -> String { |
| 2916 | (0..width).map(|x| buf[(x, y)].symbol()).collect() |
| 2917 | } |
| 2918 | |
| 2919 | #[test] |
| 2920 | fn keycap_table_puts_every_border_in_the_same_column() { |
| 2921 | // A cell that holds a keycap must not shift the separators after it. |
| 2922 | // `Line::width()` cannot see the drift because it sums span widths, |
| 2923 | // so compare the columns the buffer actually filled. |
| 2924 | let md = "| A | B |\n| --- | --- |\n\ |
| 2925 | | 1\u{fe0f}\u{20e3} | x |\n| *\u{fe0f}\u{20e3} | y |\n\ |
| 2926 | | #\u{fe0f}\u{20e3} | z |\n| plain | w |"; |
| 2927 | let lines = render_markdown(md, 80, Style::default()); |
| 2928 | let height = lines.len() as u16; |
| 2929 | let buf = buffer_of(&lines, 80, height); |
| 2930 | |
| 2931 | // Top and bottom borders use corner and tee glyphs, so compare only the |
| 2932 | // rows that carry a `|` separator against each other. |
| 2933 | let separated: Vec<(u16, Vec<usize>)> = (0..height) |
| 2934 | .map(|y| (y, border_columns(&buf, 80, y))) |
| 2935 | .filter(|(_, cols)| !cols.is_empty()) |
| 2936 | .collect(); |
| 2937 | assert!( |
| 2938 | separated.len() >= 3, |
| 2939 | "expected a header and data rows with separators" |
| 2940 | ); |
| 2941 | let expected = separated[0].1.clone(); |
| 2942 | for (y, cols) in &separated { |
| 2943 | assert_eq!( |
| 2944 | cols, |
| 2945 | &expected, |
| 2946 | "row {y} separators drifted: {:?}", |
| 2947 | row_text(&buf, 80, *y) |
| 2948 | ); |
| 2949 | } |
| 2950 | |
| 2951 | // The separators alone cannot tell the two shapes apart: both the split |
| 2952 | // form (`*` plus a zero-width mark span) and the joined form advance the |
| 2953 | // buffer by the same number of columns, so assert the symbol too. Before |
| 2954 | // the fix this cell held a bare `*` and the keycap never reached the |
| 2955 | // terminal at all. |
| 2956 | let row_with_keycap = (0..height) |
| 2957 | .map(|y| (y, row_text(&buf, 80, y))) |
| 2958 | .find(|(_, text)| text.contains('*')) |
| 2959 | .map(|(y, _)| y); |
| 2960 | if let Some(y) = row_with_keycap { |
| 2961 | let symbols: Vec<&str> = (0..80).map(|x| buf[(x, y)].symbol()).collect(); |
| 2962 | assert!( |
| 2963 | symbols.iter().any(|s| s.contains("\u{20e3}")), |
| 2964 | "row {y} lost the keycap: the cell holds {:?} instead of the \ |
| 2965 | whole cluster, so the terminal would draw a bare `*`", |
| 2966 | symbols |
| 2967 | .iter() |
| 2968 | .filter(|s| !s.trim().is_empty()) |
| 2969 | .collect::<Vec<_>>() |
| 2970 | ); |
| 2971 | } |
| 2972 | } |
| 2973 | |
| 2974 | #[test] |
| 2975 | fn escaped_star_keycap_stays_in_one_token() { |
| 2976 | // `\*️⃣` escapes the `*` of a keycap. Emitting that `*` on its own left |
| 2977 | // the two combining marks in a second span, which is the same split the |
| 2978 | // plain-text path had. |
| 2979 | let tokens = parse_inline_spans("\\*\u{fe0f}\u{20e3}", Style::default(), Style::default()); |
| 2980 | assert_eq!( |
| 2981 | tokens.len(), |
| 2982 | 1, |
| 2983 | "escaped keycap split into {:?}", |
| 2984 | tokens.iter().map(|t| t.text.as_str()).collect::<Vec<_>>() |
| 2985 | ); |
| 2986 | assert_eq!(tokens[0].text, "*\u{fe0f}\u{20e3}"); |
| 2987 | } |
| 2988 | |
| 2989 | #[test] |
| 2990 | fn a_star_keycap_does_not_open_emphasis() { |
| 2991 | // `*️⃣abc*` must not italicise `abc`: the leading `*` belongs to the |
| 2992 | // keycap, so it cannot be an emphasis delimiter. |
| 2993 | let tokens = |
| 2994 | parse_inline_spans("*\u{fe0f}\u{20e3}abc*", Style::default(), Style::default()); |
| 2995 | assert!( |
| 2996 | tokens |
| 2997 | .iter() |
| 2998 | .all(|t| !t.style.add_modifier.contains(Modifier::ITALIC)), |
| 2999 | "keycap `*` opened emphasis: {:?}", |
| 3000 | tokens.iter().map(|t| t.text.as_str()).collect::<Vec<_>>() |
| 3001 | ); |
| 3002 | assert_eq!(tokens[0].text, "*\u{fe0f}\u{20e3}"); |
| 3003 | } |
| 3004 | |
| 3005 | #[test] |
| 3006 | fn backslash_escapes_yield_the_literal_punctuation() { |
| 3007 | let lines = render_markdown( |
| 3008 | "ID: computer\\-use 0\\.1\\.0 \\*not italic\\* trailing\\", |
| 3009 | 80, |
| 3010 | Style::default(), |
| 3011 | ); |
| 3012 | assert_eq!( |
| 3013 | visible_lines(&lines), |
| 3014 | vec!["ID: computer-use 0.1.0 *not italic* trailing\\"] |
| 3015 | ); |
| 3016 | } |
| 3017 | |
| 3018 | fn rendered_fingerprint(lines: &[RenderedMarkdownLine]) -> Vec<String> { |
| 3019 | lines |
| 3020 | .iter() |
| 3021 | .map(|line| { |
| 3022 | format!( |
| 3023 | "{:?}|{:?}|{}|{}|{:?}", |
| 3024 | line.line, |
| 3025 | line.links, |
| 3026 | line.is_code, |
| 3027 | line.copy_prefix_width, |
| 3028 | line.copy_separator_after |
| 3029 | ) |
| 3030 | }) |
| 3031 | .collect() |
| 3032 | } |
| 3033 | |
| 3034 | fn update_incremental_render( |
| 3035 | cache: &mut IncrementalMarkdownRenderCache, |
| 3036 | rendered: &mut Vec<RenderedMarkdownLine>, |
| 3037 | source: &str, |
| 3038 | width: u16, |
| 3039 | palette_mode: palette::PaletteMode, |
| 3040 | verified_append: bool, |
| 3041 | ) { |
| 3042 | update_incremental_render_with_style( |
| 3043 | cache, |
| 3044 | rendered, |
| 3045 | source, |
| 3046 | width, |
| 3047 | Style::default(), |
| 3048 | palette_mode, |
| 3049 | verified_append, |
| 3050 | ); |
| 3051 | } |
| 3052 | |
| 3053 | fn update_incremental_render_with_style( |
| 3054 | cache: &mut IncrementalMarkdownRenderCache, |
| 3055 | rendered: &mut Vec<RenderedMarkdownLine>, |
| 3056 | source: &str, |
| 3057 | width: u16, |
| 3058 | base_style: Style, |
| 3059 | palette_mode: palette::PaletteMode, |
| 3060 | verified_append: bool, |
| 3061 | ) { |
| 3062 | let delta = cache.update(source, width, base_style, palette_mode, verified_append); |
| 3063 | rendered.truncate(delta.replace_from); |
| 3064 | rendered.extend(delta.lines); |
| 3065 | } |
| 3066 | |
| 3067 | #[test] |
| 3068 | fn incremental_render_is_exact_and_linear_for_unicode_fences_and_tables() { |
| 3069 | let mut cache = IncrementalMarkdownRenderCache::default(); |
| 3070 | let mut rendered = Vec::new(); |
| 3071 | let mut source = String::new(); |
| 3072 | let chunks = 80usize; |
| 3073 | |
| 3074 | for index in 0..chunks { |
| 3075 | source.push_str(&format!( |
| 3076 | "## 段落 {index}\nUnicode e\u{301} 世界 🚀\n```rust\nlet 値_{index}: usize = {index}; // 注釈\n```\n| key | value |\n|---|---|\n| {index} | 世界 |\n\n" |
| 3077 | )); |
| 3078 | update_incremental_render( |
| 3079 | &mut cache, |
| 3080 | &mut rendered, |
| 3081 | &source, |
| 3082 | 96, |
| 3083 | palette::PaletteMode::Dark, |
| 3084 | index > 0, |
| 3085 | ); |
| 3086 | let cold = render_markdown_tagged_with_palette( |
| 3087 | &source, |
| 3088 | 96, |
| 3089 | Style::default(), |
| 3090 | palette::PaletteMode::Dark, |
| 3091 | ); |
| 3092 | assert_eq!( |
| 3093 | rendered_fingerprint(&rendered), |
| 3094 | rendered_fingerprint(&cold), |
| 3095 | "incremental output diverged after chunk {index}" |
| 3096 | ); |
| 3097 | } |
| 3098 | |
| 3099 | let work = cache.work(); |
| 3100 | let parsed = reference_parse(&source); |
| 3101 | assert_eq!(work.classified_lines as usize, source.lines().count()); |
| 3102 | assert_eq!(work.stable_blocks_rendered as usize, parsed.blocks.len()); |
| 3103 | assert_eq!(work.tail_blocks_rendered, 0); |
| 3104 | assert_eq!(work.invalidations, 1); |
| 3105 | } |
| 3106 | |
| 3107 | #[test] |
| 3108 | fn incremental_render_invalidates_on_mutation_width_theme_and_style() { |
| 3109 | let mut cache = IncrementalMarkdownRenderCache::default(); |
| 3110 | let mut rendered = Vec::new(); |
| 3111 | let mut source = "alpha\n```rust\nlet value = 1;\n```\n".to_string(); |
| 3112 | update_incremental_render( |
| 3113 | &mut cache, |
| 3114 | &mut rendered, |
| 3115 | &source, |
| 3116 | 80, |
| 3117 | palette::PaletteMode::Dark, |
| 3118 | false, |
| 3119 | ); |
| 3120 | |
| 3121 | source.push_str("tail 世界\n"); |
| 3122 | update_incremental_render( |
| 3123 | &mut cache, |
| 3124 | &mut rendered, |
| 3125 | &source, |
| 3126 | 80, |
| 3127 | palette::PaletteMode::Dark, |
| 3128 | true, |
| 3129 | ); |
| 3130 | |
| 3131 | source.replace_range(..5, "ALPHA"); |
| 3132 | update_incremental_render( |
| 3133 | &mut cache, |
| 3134 | &mut rendered, |
| 3135 | &source, |
| 3136 | 80, |
| 3137 | palette::PaletteMode::Dark, |
| 3138 | false, |
| 3139 | ); |
| 3140 | let mutated = render_markdown_tagged_with_palette( |
| 3141 | &source, |
| 3142 | 80, |
| 3143 | Style::default(), |
| 3144 | palette::PaletteMode::Dark, |
| 3145 | ); |
| 3146 | assert_eq!( |
| 3147 | rendered_fingerprint(&rendered), |
| 3148 | rendered_fingerprint(&mutated) |
| 3149 | ); |
| 3150 | |
| 3151 | update_incremental_render( |
| 3152 | &mut cache, |
| 3153 | &mut rendered, |
| 3154 | &source, |
| 3155 | 37, |
| 3156 | palette::PaletteMode::Dark, |
| 3157 | true, |
| 3158 | ); |
| 3159 | update_incremental_render( |
| 3160 | &mut cache, |
| 3161 | &mut rendered, |
| 3162 | &source, |
| 3163 | 37, |
| 3164 | palette::PaletteMode::Light, |
| 3165 | true, |
| 3166 | ); |
| 3167 | |
| 3168 | let changed_style = Style::default().add_modifier(Modifier::ITALIC); |
| 3169 | update_incremental_render_with_style( |
| 3170 | &mut cache, |
| 3171 | &mut rendered, |
| 3172 | &source, |
| 3173 | 37, |
| 3174 | changed_style, |
| 3175 | palette::PaletteMode::Light, |
| 3176 | true, |
| 3177 | ); |
| 3178 | let rethemed = render_markdown_tagged_with_palette( |
| 3179 | &source, |
| 3180 | 37, |
| 3181 | changed_style, |
| 3182 | palette::PaletteMode::Light, |
| 3183 | ); |
| 3184 | assert_eq!( |
| 3185 | rendered_fingerprint(&rendered), |
| 3186 | rendered_fingerprint(&rethemed) |
| 3187 | ); |
| 3188 | assert_eq!(cache.work().invalidations, 5); |
| 3189 | } |
| 3190 | |
| 3191 | #[test] |
| 3192 | fn incremental_render_drops_committed_source_without_a_large_answer_cliff() { |
| 3193 | let line = format!("{}\n", "x".repeat(16 * 1024)); |
| 3194 | let mut source = String::new(); |
| 3195 | let mut cache = IncrementalMarkdownRenderCache::default(); |
| 3196 | let mut rendered = Vec::new(); |
| 3197 | |
| 3198 | for index in 0..80 { |
| 3199 | source.push_str(&line); |
| 3200 | update_incremental_render( |
| 3201 | &mut cache, |
| 3202 | &mut rendered, |
| 3203 | &source, |
| 3204 | u16::MAX, |
| 3205 | palette::PaletteMode::Dark, |
| 3206 | index > 0, |
| 3207 | ); |
| 3208 | assert_eq!(cache.retained_source_bytes(), 0); |
| 3209 | } |
| 3210 | |
| 3211 | assert!(source.len() > 1024 * 1024); |
| 3212 | assert_eq!(cache.retained_source_bytes(), 0); |
| 3213 | assert_eq!(cache.work().classified_lines, 80); |
| 3214 | assert_eq!(cache.work().stable_blocks_rendered, 80); |
| 3215 | assert_eq!(cache.work().invalidations, 1); |
| 3216 | } |
| 3217 | |
| 3218 | #[test] |
| 3219 | fn verified_append_resume_rejects_a_rewritten_committed_prefix() { |
| 3220 | // #6196: the streaming cache consumes the latex-rendered projection |
| 3221 | // of the raw stream. While a `\[` display block is open, |
| 3222 | // `render_latex_in_text` passes it through as literal text and the |
| 3223 | // incremental cache commits those lines. When the closing `\]` |
| 3224 | // finally arrives the rendered form rewrites the *committed* bytes |
| 3225 | // even though the raw stream only appended, so the append receipt |
| 3226 | // stays valid and only a content-aware committed-prefix check can |
| 3227 | // see the rewrite. A length-only check resumed from the stale lines |
| 3228 | // and the un-rendered opener stuck in the cell forever. The strings |
| 3229 | // below are the projections the latex layer produces for that |
| 3230 | // sequence. |
| 3231 | let mut cache = IncrementalMarkdownRenderCache::default(); |
| 3232 | let mut rendered = Vec::new(); |
| 3233 | // Beat 1: raw stream `para\n\[ \alpha\n` — the open block passes |
| 3234 | // through literally and its complete line is committed. |
| 3235 | update_incremental_render( |
| 3236 | &mut cache, |
| 3237 | &mut rendered, |
| 3238 | "para\n\\[ \\alpha\n", |
| 3239 | 80, |
| 3240 | palette::PaletteMode::Dark, |
| 3241 | false, |
| 3242 | ); |
| 3243 | assert_eq!(cache.work().invalidations, 1); |
| 3244 | |
| 3245 | // Beat 2: the raw stream appended `\]` plus more prose; the |
| 3246 | // projection rewrites the committed line and grows past its old |
| 3247 | // length, so the resume guard cannot rely on length alone. |
| 3248 | let closed = "para\nα\nthe identity holds for every pair of terms\n"; |
| 3249 | update_incremental_render( |
| 3250 | &mut cache, |
| 3251 | &mut rendered, |
| 3252 | closed, |
| 3253 | 80, |
| 3254 | palette::PaletteMode::Dark, |
| 3255 | true, |
| 3256 | ); |
| 3257 | assert_eq!( |
| 3258 | cache.work().invalidations, |
| 3259 | 2, |
| 3260 | "rewriting committed bytes must invalidate the resume" |
| 3261 | ); |
| 3262 | let cold = render_markdown_tagged_with_palette( |
| 3263 | closed, |
| 3264 | 80, |
| 3265 | Style::default(), |
| 3266 | palette::PaletteMode::Dark, |
| 3267 | ); |
| 3268 | assert_eq!( |
| 3269 | rendered_fingerprint(&rendered), |
| 3270 | rendered_fingerprint(&cold), |
| 3271 | "the re-render must match a cold render of the closed form" |
| 3272 | ); |
| 3273 | assert!( |
| 3274 | !rendered.iter().any(|line| { |
| 3275 | line.line |
| 3276 | .spans |
| 3277 | .iter() |
| 3278 | .any(|span| span.content.contains("\\[")) |
| 3279 | }), |
| 3280 | "the stale literal latex opener must not survive the close" |
| 3281 | ); |
| 3282 | } |
| 3283 | |
| 3284 | #[test] |
| 3285 | fn underscores_inside_identifiers_render_as_literal_text() { |
| 3286 | // Regression for PR #1455 / @tiger-dog: previously the inline |
| 3287 | // markdown parser ate the underscore in `codewhale_tui` because |
| 3288 | // it matched the `_italic_` pattern without a CommonMark-style |
| 3289 | // boundary check. The closing `_` followed by `t` (a letter) |
| 3290 | // must now be treated as part of the identifier, not as |
| 3291 | // markup. The same rule applies to `*` so identifiers like |
| 3292 | // `crate*foo` round-trip cleanly. |
| 3293 | let cases = [ |
| 3294 | "crate codewhale_tui handles approvals", |
| 3295 | "see foo_bar_baz for details", |
| 3296 | "look at *not_emphasised*tail", |
| 3297 | ]; |
| 3298 | for source in cases { |
| 3299 | let parsed = parse(source); |
| 3300 | let rendered: String = render_parsed(&parsed, 80, Style::default()) |
| 3301 | .iter() |
| 3302 | .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref())) |
| 3303 | .collect(); |
| 3304 | // The original identifier (with underscores intact) must |
| 3305 | // appear in the rendered output. We don't assert on style |
| 3306 | // here — that's an implementation detail; we assert on |
| 3307 | // the user-visible character sequence. |
| 3308 | for token in source.split_whitespace().filter(|t| t.contains('_')) { |
| 3309 | assert!( |
| 3310 | rendered.contains(token), |
| 3311 | "identifier {token:?} must survive markdown rendering of {source:?}; got {rendered:?}" |
| 3312 | ); |
| 3313 | } |
| 3314 | } |
| 3315 | } |
| 3316 | |
| 3317 | #[test] |
| 3318 | fn underscore_emphasis_does_not_open_mid_word_across_math_subscripts() { |
| 3319 | // #6042: the closing-side guard alone let `b_p` open emphasis and |
| 3320 | // `t_?` close it, italicizing 60 characters of prose. CommonMark |
| 3321 | // forbids an intraword `_` from opening emphasis. |
| 3322 | let source = "[t_, b_p]. Actually — hold on, do we even tile all the way from t_?"; |
| 3323 | let lines = render_parsed(&parse(source), 200, Style::default()); |
| 3324 | let italic: Vec<&str> = lines |
| 3325 | .iter() |
| 3326 | .flat_map(|line| line.spans.iter()) |
| 3327 | .filter(|span| span.style.add_modifier.contains(Modifier::ITALIC)) |
| 3328 | .map(|span| span.content.as_ref()) |
| 3329 | .collect(); |
| 3330 | assert!( |
| 3331 | italic.is_empty(), |
| 3332 | "math subscripts must not open emphasis; italic spans: {italic:?}" |
| 3333 | ); |
| 3334 | |
| 3335 | // A properly flanked `_italic_` run still renders italic… |
| 3336 | let flanked = render_parsed(&parse("an _emphasised_ word"), 80, Style::default()); |
| 3337 | assert!( |
| 3338 | flanked |
| 3339 | .iter() |
| 3340 | .flat_map(|line| line.spans.iter()) |
| 3341 | .any(|span| span.style.add_modifier.contains(Modifier::ITALIC) |
| 3342 | && span.content.as_ref() == "emphasised"), |
| 3343 | "a flanked _italic_ run must still render italic" |
| 3344 | ); |
| 3345 | // …and after punctuation it still opens. |
| 3346 | let after_punct = render_parsed(&parse("word (_also_)"), 80, Style::default()); |
| 3347 | assert!( |
| 3348 | after_punct |
| 3349 | .iter() |
| 3350 | .flat_map(|line| line.spans.iter()) |
| 3351 | .any(|span| span.style.add_modifier.contains(Modifier::ITALIC) |
| 3352 | && span.content.as_ref() == "also"), |
| 3353 | "a _ run after punctuation must still open" |
| 3354 | ); |
| 3355 | } |
| 3356 | |
| 3357 | #[test] |
| 3358 | fn render_markdown_matches_parse_then_render() { |
| 3359 | let source = "# Title\n\nA paragraph with a https://example.com link.\n\n- one\n- two\n```\ncode\n```"; |
| 3360 | let direct = render_markdown(source, 80, Style::default()) |
| 3361 | .iter() |
| 3362 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 3363 | .collect::<String>(); |
| 3364 | let parsed = parse(source); |
| 3365 | let two_step = render_parsed(&parsed, 80, Style::default()) |
| 3366 | .iter() |
| 3367 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 3368 | .collect::<String>(); |
| 3369 | assert_eq!(direct, two_step); |
| 3370 | } |
| 3371 | |
| 3372 | #[test] |
| 3373 | fn render_plain_text_preserves_literal_markdown_and_spacing() { |
| 3374 | let source = " # heading\n- item\n \nhello world\n"; |
| 3375 | let lines = render_plain_text(source, 80, Style::default()); |
| 3376 | |
| 3377 | assert_eq!( |
| 3378 | visible_lines(&lines), |
| 3379 | vec![" # heading", "- item", " ", "hello world", ""] |
| 3380 | ); |
| 3381 | } |
| 3382 | |
| 3383 | #[test] |
| 3384 | fn render_plain_text_wraps_without_collapsing_spaces() { |
| 3385 | let source = "alpha beta gamma"; |
| 3386 | let lines = render_plain_text(source, 12, Style::default()); |
| 3387 | for width in rendered_widths(&lines) { |
| 3388 | assert!(width <= 12, "rendered width {width} exceeds budget"); |
| 3389 | } |
| 3390 | |
| 3391 | let combined = visible_lines(&lines).join(""); |
| 3392 | assert_eq!(combined, source); |
| 3393 | } |
| 3394 | |
| 3395 | #[test] |
| 3396 | fn render_plain_text_breaks_overlong_words() { |
| 3397 | let source = "x".repeat(40); |
| 3398 | let lines = render_plain_text(&source, 9, Style::default()); |
| 3399 | for width in rendered_widths(&lines) { |
| 3400 | assert!(width <= 9, "rendered width {width} exceeds budget"); |
| 3401 | } |
| 3402 | |
| 3403 | let combined = visible_lines(&lines).join(""); |
| 3404 | assert_eq!(combined, source); |
| 3405 | } |
| 3406 | |
| 3407 | #[test] |
| 3408 | fn parse_is_width_independent() { |
| 3409 | // Same source, two parses, must produce identical AST. (Sanity: |
| 3410 | // parse must not depend on hidden global state like terminal width.) |
| 3411 | let source = "Hello\n\n## Heading\n- list\n"; |
| 3412 | let a = parse(source); |
| 3413 | let b = parse(source); |
| 3414 | assert_eq!(a, b); |
| 3415 | } |
| 3416 | |
| 3417 | #[test] |
| 3418 | fn render_parsed_word_wrap_changes_with_width() { |
| 3419 | // The same AST must produce different layouts at different widths; |
| 3420 | // otherwise the split is decorative, not functional. |
| 3421 | let parsed = parse("alpha beta gamma delta epsilon zeta"); |
| 3422 | let wide = render_parsed(&parsed, 80, Style::default()); |
| 3423 | let narrow = render_parsed(&parsed, 10, Style::default()); |
| 3424 | assert!( |
| 3425 | narrow.len() > wide.len(), |
| 3426 | "narrow should produce more lines" |
| 3427 | ); |
| 3428 | } |
| 3429 | |
| 3430 | #[test] |
| 3431 | fn parse_invocations_increment() { |
| 3432 | // Counter is thread-local, so concurrent tests calling `parse()` |
| 3433 | // can't pollute each other. |
| 3434 | reset_parse_invocation_count(); |
| 3435 | let _ = parse("hello\n"); |
| 3436 | let _ = parse("world\n"); |
| 3437 | assert_eq!(parse_invocation_count(), 2); |
| 3438 | } |
| 3439 | |
| 3440 | #[test] |
| 3441 | fn render_parsed_does_not_call_parse() { |
| 3442 | // Width-only changes must hit only the render path. This is the |
| 3443 | // perf invariant CX#6 was filed for. |
| 3444 | let parsed = parse("multiline\nsource\nwith several\nlines\n"); |
| 3445 | reset_parse_invocation_count(); |
| 3446 | let _ = render_parsed(&parsed, 80, Style::default()); |
| 3447 | let _ = render_parsed(&parsed, 40, Style::default()); |
| 3448 | let _ = render_parsed(&parsed, 20, Style::default()); |
| 3449 | assert_eq!( |
| 3450 | parse_invocation_count(), |
| 3451 | 0, |
| 3452 | "render_parsed must not call parse" |
| 3453 | ); |
| 3454 | } |
| 3455 | |
| 3456 | // ----------------------------------------------------------------- |
| 3457 | // #3897 — streaming re-parse is incremental, not quadratic |
| 3458 | // ----------------------------------------------------------------- |
| 3459 | |
| 3460 | /// Markdown corpus chosen to hit every carry-state transition the parser |
| 3461 | /// has: fences opened and closed across chunk boundaries, an unterminated |
| 3462 | /// fence, headings, nested lists, tables, rules, blanks, CRLF, and CJK. |
| 3463 | fn streaming_corpus() -> Vec<&'static str> { |
| 3464 | vec![ |
| 3465 | "# Title\n\nSome prose that wraps.\n\n- alpha\n- beta\n", |
| 3466 | "text\n```rust\nlet x = 1;\nlet y = 2;\n```\nafter\n", |
| 3467 | "```\nunterminated fence never closes\nstill inside\n", |
| 3468 | "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n\ndone\n", |
| 3469 | "1. one\n2. two\n * nested\n\n## Sub\n\n***\n", |
| 3470 | "混合 CJK 内容\n\n```python\nprint(\"中文\")\n```\n尾部\n", |
| 3471 | "crlf lines\r\nsecond\r\n\r\n```go\nfmt.Println()\r\n```\r\n", |
| 3472 | "no trailing newline at all", |
| 3473 | "", |
| 3474 | ] |
| 3475 | } |
| 3476 | |
| 3477 | /// The acceptance guarantee: streaming a message chunk by chunk produces, |
| 3478 | /// at every intermediate prefix, exactly what a full re-parse of that |
| 3479 | /// prefix produces. Byte-for-byte on the AST, so a divergence in any field |
| 3480 | /// of any block fails here rather than showing up as a render artifact. |
| 3481 | #[test] |
| 3482 | fn incremental_parse_matches_a_full_reparse_at_every_prefix() { |
| 3483 | for source in streaming_corpus() { |
| 3484 | // Grow one byte at a time (respecting char boundaries) — the |
| 3485 | // worst case for a parser that commits too eagerly. |
| 3486 | for end in 0..=source.len() { |
| 3487 | if !source.is_char_boundary(end) { |
| 3488 | continue; |
| 3489 | } |
| 3490 | let prefix = &source[..end]; |
| 3491 | let streamed = parse(prefix); |
| 3492 | |
| 3493 | // A cold parser is the reference: no memo, no resumption. |
| 3494 | let mut cold = ParseState::default(); |
| 3495 | cold.commit_complete_lines(prefix); |
| 3496 | let reference = cold.snapshot(prefix); |
| 3497 | |
| 3498 | assert_eq!( |
| 3499 | streamed, reference, |
| 3500 | "prefix {end} of {source:?} diverged from a full re-parse" |
| 3501 | ); |
| 3502 | } |
| 3503 | } |
| 3504 | } |
| 3505 | |
| 3506 | /// The performance guarantee: work per chunk must not grow with the |
| 3507 | /// message. Counted in lines actually classified, which is the quantity |
| 3508 | /// that was quadratic — the old code re-classified every line on every |
| 3509 | /// chunk. |
| 3510 | #[test] |
| 3511 | fn streaming_does_not_reclassify_committed_lines() { |
| 3512 | let chunk = "a line of prose\n"; |
| 3513 | let chunks = 400; |
| 3514 | |
| 3515 | let mut content = String::new(); |
| 3516 | let mut state = ParseState::default(); |
| 3517 | let mut total_committed = 0usize; |
| 3518 | |
| 3519 | for _ in 0..chunks { |
| 3520 | content.push_str(chunk); |
| 3521 | assert!( |
| 3522 | state.can_resume_from(&content), |
| 3523 | "an append-only stream must always be resumable" |
| 3524 | ); |
| 3525 | let before = state.blocks.len(); |
| 3526 | state.commit_complete_lines(&content); |
| 3527 | total_committed += state.blocks.len() - before; |
| 3528 | } |
| 3529 | |
| 3530 | // Quadratic would be chunks * (chunks + 1) / 2 = 80,200 classifications. |
| 3531 | assert_eq!( |
| 3532 | total_committed, chunks, |
| 3533 | "each line must be classified exactly once across the whole stream" |
| 3534 | ); |
| 3535 | assert_eq!(state.blocks.len(), chunks); |
| 3536 | } |
| 3537 | |
| 3538 | /// Resumption is verified, never assumed. Content that does not extend the |
| 3539 | /// committed prefix must fall back to a full parse rather than splice |
| 3540 | /// unrelated blocks together. |
| 3541 | #[test] |
| 3542 | fn a_changed_prefix_is_not_resumable() { |
| 3543 | let mut state = ParseState::default(); |
| 3544 | state.commit_complete_lines("first line\nsecond line\n"); |
| 3545 | |
| 3546 | assert!(state.can_resume_from("first line\nsecond line\nthird\n")); |
| 3547 | // Earlier bytes rewritten. |
| 3548 | assert!(!state.can_resume_from("FIRST line\nsecond line\nthird\n")); |
| 3549 | // Buffer shrank (a different, shorter cell). |
| 3550 | assert!(!state.can_resume_from("first line\n")); |
| 3551 | // Entirely unrelated content. |
| 3552 | assert!(!state.can_resume_from("something else\n")); |
| 3553 | } |
| 3554 | |
| 3555 | /// Interleaving two different sources through the shared memo must not |
| 3556 | /// contaminate either — this is the multi-cell render-loop case. |
| 3557 | #[test] |
| 3558 | fn interleaved_sources_do_not_contaminate_each_other() { |
| 3559 | let a = "# Alpha\n\nalpha body\n"; |
| 3560 | let b = "```rust\nlet b = 1;\n```\n"; |
| 3561 | for _ in 0..5 { |
| 3562 | assert_eq!(parse(a), reference_parse(a)); |
| 3563 | assert_eq!(parse(b), reference_parse(b)); |
| 3564 | } |
| 3565 | } |
| 3566 | |
| 3567 | fn reference_parse(content: &str) -> ParsedMarkdown { |
| 3568 | let mut cold = ParseState::default(); |
| 3569 | cold.commit_complete_lines(content); |
| 3570 | cold.snapshot(content) |
| 3571 | } |
| 3572 | |
| 3573 | #[test] |
| 3574 | fn fenced_code_block_collected_in_parse() { |
| 3575 | let parsed = parse("text\n```rust\ncode line one\ncode line two\n```\nmore\n"); |
| 3576 | let blocks = &parsed.blocks; |
| 3577 | // text paragraph, two code lines, more paragraph (fences are dropped) |
| 3578 | let code_lines: Vec<_> = blocks |
| 3579 | .iter() |
| 3580 | .filter_map(|b| match b { |
| 3581 | Block::Code { |
| 3582 | line, |
| 3583 | language, |
| 3584 | block_id, |
| 3585 | } => Some((line.as_str(), language.as_deref(), *block_id)), |
| 3586 | _ => None, |
| 3587 | }) |
| 3588 | .collect(); |
| 3589 | assert_eq!( |
| 3590 | code_lines, |
| 3591 | vec![ |
| 3592 | ("code line one", Some("rust"), 1), |
| 3593 | ("code line two", Some("rust"), 1), |
| 3594 | ] |
| 3595 | ); |
| 3596 | } |
| 3597 | |
| 3598 | #[test] |
| 3599 | fn adjacent_code_fences_keep_distinct_highlighter_state() { |
| 3600 | let parsed = parse("```rust\n/* open\n```\n```rust\nlet x = 1;\n```\n"); |
| 3601 | let ids = parsed |
| 3602 | .blocks |
| 3603 | .iter() |
| 3604 | .filter_map(|block| match block { |
| 3605 | Block::Code { block_id, .. } => Some(*block_id), |
| 3606 | _ => None, |
| 3607 | }) |
| 3608 | .collect::<Vec<_>>(); |
| 3609 | assert_eq!(ids, vec![1, 2]); |
| 3610 | } |
| 3611 | |
| 3612 | #[test] |
| 3613 | fn rust_fence_respects_terminal_color_depth_without_reserved_rgb() { |
| 3614 | let rendered = render_markdown_tagged( |
| 3615 | "```rust\nfn main() {\n let answer: u32 = 42; // comment\n}\n```", |
| 3616 | 100, |
| 3617 | Style::default(), |
| 3618 | ); |
| 3619 | let colors = rendered |
| 3620 | .iter() |
| 3621 | .flat_map(|line| line.line.spans.iter()) |
| 3622 | .filter_map(|span| span.style.fg) |
| 3623 | .collect::<std::collections::HashSet<_>>(); |
| 3624 | if syntax_color_depth() == palette::ColorDepth::Monochrome { |
| 3625 | assert_eq!(colors, [Color::Reset].into(), "NO_COLOR: {colors:?}"); |
| 3626 | } else { |
| 3627 | assert!(colors.len() > 1, "expected syntax colors, got: {colors:?}"); |
| 3628 | } |
| 3629 | for color in colors { |
| 3630 | assert_ne!(color, palette::WHALE_HUMAN); |
| 3631 | assert_ne!(color, palette::WHALE_LIVE); |
| 3632 | assert_ne!(color, palette::WHALE_ACTION); |
| 3633 | assert_ne!(color, palette::WHALE_ERROR); |
| 3634 | } |
| 3635 | } |
| 3636 | |
| 3637 | #[test] |
| 3638 | fn syntax_colors_use_existing_depth_quantizer_and_grayscale_path() { |
| 3639 | assert!(matches!( |
| 3640 | syntax_rgb_to_terminal_color( |
| 3641 | 120, |
| 3642 | 80, |
| 3643 | 200, |
| 3644 | palette::PaletteMode::Dark, |
| 3645 | palette::ColorDepth::Ansi256, |
| 3646 | ), |
| 3647 | Color::Indexed(_) |
| 3648 | )); |
| 3649 | assert!(matches!( |
| 3650 | syntax_rgb_to_terminal_color( |
| 3651 | 120, |
| 3652 | 80, |
| 3653 | 200, |
| 3654 | palette::PaletteMode::Dark, |
| 3655 | palette::ColorDepth::Ansi16, |
| 3656 | ), |
| 3657 | Color::Black |
| 3658 | | Color::Red |
| 3659 | | Color::Green |
| 3660 | | Color::Yellow |
| 3661 | | Color::Blue |
| 3662 | | Color::Magenta |
| 3663 | | Color::Cyan |
| 3664 | | Color::Gray |
| 3665 | | Color::DarkGray |
| 3666 | | Color::LightRed |
| 3667 | | Color::LightGreen |
| 3668 | | Color::LightYellow |
| 3669 | | Color::LightBlue |
| 3670 | | Color::LightMagenta |
| 3671 | | Color::LightCyan |
| 3672 | | Color::White |
| 3673 | )); |
| 3674 | let gray = syntax_rgb_to_terminal_color( |
| 3675 | 120, |
| 3676 | 80, |
| 3677 | 200, |
| 3678 | palette::PaletteMode::Grayscale, |
| 3679 | palette::ColorDepth::TrueColor, |
| 3680 | ); |
| 3681 | assert!(matches!(gray, Color::Rgb(r, g, b) if r == g && g == b)); |
| 3682 | } |
| 3683 | |
| 3684 | #[test] |
| 3685 | fn syntax_assets_are_lazy_singletons_and_explicit_modes_select_themes() { |
| 3686 | assert!(std::ptr::eq(syntax_set(), syntax_set())); |
| 3687 | assert!(std::ptr::eq(theme_set(), theme_set())); |
| 3688 | assert!(!std::ptr::eq( |
| 3689 | selected_syntax_theme(palette::PaletteMode::Dark), |
| 3690 | selected_syntax_theme(palette::PaletteMode::Light), |
| 3691 | )); |
| 3692 | } |
| 3693 | |
| 3694 | #[test] |
| 3695 | fn depth_quantization_cannot_reintroduce_reserved_semantic_colors() { |
| 3696 | let reserved = [ |
| 3697 | palette::WHALE_HUMAN, |
| 3698 | palette::WHALE_LIVE, |
| 3699 | palette::WHALE_ACTION, |
| 3700 | palette::WHALE_ERROR, |
| 3701 | ]; |
| 3702 | for depth in [ |
| 3703 | palette::ColorDepth::TrueColor, |
| 3704 | palette::ColorDepth::Ansi256, |
| 3705 | palette::ColorDepth::Ansi16, |
| 3706 | ] { |
| 3707 | let reserved_at_depth = reserved.map(|color| palette::adapt_color(color, depth)); |
| 3708 | for semantic in reserved { |
| 3709 | let Color::Rgb(r, g, b) = semantic else { |
| 3710 | panic!("reserved syntax guard expects RGB semantic colors"); |
| 3711 | }; |
| 3712 | let syntax = |
| 3713 | syntax_rgb_to_terminal_color(r, g, b, palette::PaletteMode::Dark, depth); |
| 3714 | assert!( |
| 3715 | !reserved_at_depth.contains(&syntax), |
| 3716 | "{syntax:?} reintroduced a reserved color at {depth:?}" |
| 3717 | ); |
| 3718 | } |
| 3719 | } |
| 3720 | } |
| 3721 | |
| 3722 | #[test] |
| 3723 | fn code_block_indentation_is_preserved_in_render() { |
| 3724 | // Leading whitespace in code blocks is semantic — indented lines must |
| 3725 | // not be stripped to column zero when rendered. |
| 3726 | let md = "```\nfn main() {\n println!(\"hi\");\n}\n```\n"; |
| 3727 | let lines = render_markdown(md, 80, Style::default()); |
| 3728 | let text: Vec<String> = lines |
| 3729 | .iter() |
| 3730 | .map(|l| { |
| 3731 | l.spans |
| 3732 | .iter() |
| 3733 | .map(|s| s.content.as_ref()) |
| 3734 | .collect::<String>() |
| 3735 | }) |
| 3736 | .collect(); |
| 3737 | // The indented line must start with spaces (the 2-space code prefix |
| 3738 | // plus the 4-space source indentation). |
| 3739 | let indented = text |
| 3740 | .iter() |
| 3741 | .find(|t| t.contains("println")) |
| 3742 | .expect("should find println line"); |
| 3743 | assert!( |
| 3744 | indented.starts_with(" "), |
| 3745 | "expected 6+ leading spaces (2 block prefix + 4 indent), got: {indented:?}" |
| 3746 | ); |
| 3747 | } |
| 3748 | |
| 3749 | #[test] |
| 3750 | fn markdown_grapheme_width_uses_tab_stop_and_string_width() { |
| 3751 | // At column 0 a tab fills to column 8. |
| 3752 | assert_eq!(markdown_grapheme_width("\t", 0), 8); |
| 3753 | // At column 4 a tab fills to column 8 (4 remaining). |
| 3754 | assert_eq!(markdown_grapheme_width("\t", 4), 4); |
| 3755 | // At column 8 a tab fills to the next stop at 16 (8 columns). |
| 3756 | assert_eq!(markdown_grapheme_width("\t", 8), 8); |
| 3757 | // Regular ASCII is 1. |
| 3758 | assert_eq!(markdown_grapheme_width("a", 0), 1); |
| 3759 | // A fully-qualified keycap is one two-column grapheme. |
| 3760 | assert_eq!(markdown_grapheme_width("1\u{fe0f}\u{20e3}", 0), 2); |
| 3761 | } |
| 3762 | |
| 3763 | #[test] |
| 3764 | fn ordered_and_unordered_list_items_parse() { |
| 3765 | let parsed = parse("- alpha\n* beta\n1. gamma\n"); |
| 3766 | let items: Vec<_> = parsed |
| 3767 | .blocks |
| 3768 | .iter() |
| 3769 | .filter_map(|b| match b { |
| 3770 | Block::ListItem { bullet, text, .. } => Some((bullet.as_str(), text.as_str())), |
| 3771 | _ => None, |
| 3772 | }) |
| 3773 | .collect(); |
| 3774 | assert_eq!(items, vec![("-", "alpha"), ("-", "beta"), ("1.", "gamma")]); |
| 3775 | } |
| 3776 | |
| 3777 | #[test] |
| 3778 | fn blockquote_lines_parse_with_depth() { |
| 3779 | let parsed = |
| 3780 | parse("> hello\n>\n>> nested\n> > spaced\n>no-space\n>\t tabbed\nlone > arrow\n"); |
| 3781 | let quotes: Vec<_> = parsed |
| 3782 | .blocks |
| 3783 | .iter() |
| 3784 | .filter_map(|b| match b { |
| 3785 | Block::Quote { depth, text } => Some((*depth, text.as_str())), |
| 3786 | _ => None, |
| 3787 | }) |
| 3788 | .collect(); |
| 3789 | assert_eq!( |
| 3790 | quotes, |
| 3791 | vec![ |
| 3792 | (1, "hello"), |
| 3793 | (1, ""), |
| 3794 | (2, "nested"), |
| 3795 | (2, "spaced"), |
| 3796 | (1, "no-space"), |
| 3797 | (1, "tabbed"), |
| 3798 | ] |
| 3799 | ); |
| 3800 | // `lone > arrow` starts with prose, so it stays a paragraph. |
| 3801 | assert_eq!(parsed.blocks.len(), 7); |
| 3802 | } |
| 3803 | |
| 3804 | #[test] |
| 3805 | fn code_fence_contains_quote_lines_untouched() { |
| 3806 | // Fenced-code lines are collected before blockquote classification, so |
| 3807 | // `>` inside a fence must stay literal code content. |
| 3808 | let parsed = parse("```\n> not a quote\n\n> but this is\n```\n"); |
| 3809 | let code: Vec<_> = parsed |
| 3810 | .blocks |
| 3811 | .iter() |
| 3812 | .filter_map(|b| match b { |
| 3813 | Block::Code { line, .. } => Some(line.as_str()), |
| 3814 | _ => None, |
| 3815 | }) |
| 3816 | .collect(); |
| 3817 | assert_eq!(code, vec!["> not a quote", "", "> but this is"]); |
| 3818 | assert!( |
| 3819 | parsed |
| 3820 | .blocks |
| 3821 | .iter() |
| 3822 | .all(|b| !matches!(b, Block::Quote { .. })), |
| 3823 | "lines inside a fence must stay code, never quotes" |
| 3824 | ); |
| 3825 | } |
| 3826 | |
| 3827 | #[test] |
| 3828 | fn four_backtick_fence_keeps_shorter_fence_and_quotes_as_code() { |
| 3829 | // A ```` opener must not be closed by a shorter ``` line: the shorter |
| 3830 | // fence and any `>` lines after it stay code content (CommonMark |
| 3831 | // fence-length rule), and the block only closes on a fence >= opener. |
| 3832 | let parsed = parse("````\n```\n> still code\n`````\n> now a quote\n"); |
| 3833 | let code: Vec<_> = parsed |
| 3834 | .blocks |
| 3835 | .iter() |
| 3836 | .filter_map(|b| match b { |
| 3837 | Block::Code { line, .. } => Some(line.as_str()), |
| 3838 | _ => None, |
| 3839 | }) |
| 3840 | .collect(); |
| 3841 | assert_eq!(code, vec!["```", "> still code"]); |
| 3842 | let quotes: Vec<_> = parsed |
| 3843 | .blocks |
| 3844 | .iter() |
| 3845 | .filter_map(|b| match b { |
| 3846 | Block::Quote { text, .. } => Some(text.as_str()), |
| 3847 | _ => None, |
| 3848 | }) |
| 3849 | .collect(); |
| 3850 | assert_eq!(quotes, vec!["now a quote"]); |
| 3851 | } |
| 3852 | |
| 3853 | #[test] |
| 3854 | fn longer_fence_closes_shorter_opener() { |
| 3855 | // CommonMark: a closing fence may be longer than the opener; only the |
| 3856 | // opener's length is the minimum. |
| 3857 | let parsed = parse("```\ncode\n````\nplain\n"); |
| 3858 | let code: Vec<_> = parsed |
| 3859 | .blocks |
| 3860 | .iter() |
| 3861 | .filter_map(|b| match b { |
| 3862 | Block::Code { line, .. } => Some(line.as_str()), |
| 3863 | _ => None, |
| 3864 | }) |
| 3865 | .collect(); |
| 3866 | assert_eq!(code, vec!["code"]); |
| 3867 | let paragraphs: Vec<_> = parsed |
| 3868 | .blocks |
| 3869 | .iter() |
| 3870 | .filter_map(|b| match b { |
| 3871 | Block::Paragraph { text } => Some(text.as_str()), |
| 3872 | _ => None, |
| 3873 | }) |
| 3874 | .collect(); |
| 3875 | assert_eq!(paragraphs, vec!["plain"]); |
| 3876 | } |
| 3877 | |
| 3878 | #[test] |
| 3879 | fn backticks_with_info_do_not_close_an_open_fence() { |
| 3880 | let parsed = parse("```\n```rust\n> still code\n```\n"); |
| 3881 | let code: Vec<_> = parsed |
| 3882 | .blocks |
| 3883 | .iter() |
| 3884 | .filter_map(|block| match block { |
| 3885 | Block::Code { line, .. } => Some(line.as_str()), |
| 3886 | _ => None, |
| 3887 | }) |
| 3888 | .collect(); |
| 3889 | |
| 3890 | assert_eq!(code, vec!["```rust", "> still code"]); |
| 3891 | assert!( |
| 3892 | parsed |
| 3893 | .blocks |
| 3894 | .iter() |
| 3895 | .all(|block| !matches!(block, Block::Quote { .. })) |
| 3896 | ); |
| 3897 | } |
| 3898 | |
| 3899 | #[test] |
| 3900 | fn blockquote_renders_rail_and_inline_formatting() { |
| 3901 | let rendered = render_markdown_tagged( |
| 3902 | "> **bold** `code` and see https://example.com", |
| 3903 | 80, |
| 3904 | Style::default(), |
| 3905 | ); |
| 3906 | assert_eq!( |
| 3907 | tagged_visible(&rendered), |
| 3908 | vec!["│ bold code and see https://example.com"] |
| 3909 | ); |
| 3910 | let spans = &rendered[0].line.spans; |
| 3911 | assert_eq!(spans[0].content, "│ "); |
| 3912 | assert!( |
| 3913 | spans |
| 3914 | .iter() |
| 3915 | .any(|span| span.content == "bold" |
| 3916 | && span.style.add_modifier.contains(Modifier::BOLD)), |
| 3917 | "inline bold must survive inside a quote" |
| 3918 | ); |
| 3919 | assert!( |
| 3920 | spans |
| 3921 | .iter() |
| 3922 | .any(|span| span.content == "code" |
| 3923 | && span.style.bg == Some(palette::SURFACE_ELEVATED)), |
| 3924 | "inline code is styled distinctly from plain text" |
| 3925 | ); |
| 3926 | // First-row rail is stripped by the transcript rail-scan along with |
| 3927 | // the assistant glyph, so copy must report 0 here (mirror list items) |
| 3928 | // — reporting the rail width would strip it twice and lose text. |
| 3929 | assert_eq!(rendered[0].copy_prefix_width, 0); |
| 3930 | assert_eq!( |
| 3931 | rendered[0].links, |
| 3932 | vec![osc8::LineLink { |
| 3933 | col_start: 20, |
| 3934 | col_end: 38, |
| 3935 | target: "https://example.com".to_string(), |
| 3936 | line: None, |
| 3937 | }] |
| 3938 | ); |
| 3939 | } |
| 3940 | |
| 3941 | #[test] |
| 3942 | fn nested_blockquote_renders_multiple_rails_capped() { |
| 3943 | let rendered = |
| 3944 | render_markdown_tagged(">>> deep\n>>>>>>>>>> too deep\n", 80, Style::default()); |
| 3945 | assert_eq!( |
| 3946 | tagged_visible(&rendered), |
| 3947 | vec!["│ │ │ deep", "│ │ │ │ too deep"] |
| 3948 | ); |
| 3949 | assert_eq!( |
| 3950 | rendered[0] |
| 3951 | .line |
| 3952 | .spans |
| 3953 | .iter() |
| 3954 | .take(3) |
| 3955 | .map(|span| span.content.as_ref()) |
| 3956 | .collect::<Vec<_>>(), |
| 3957 | vec!["│ ", "│ ", "│ "], |
| 3958 | "each rail must remain independently discoverable by selection copy" |
| 3959 | ); |
| 3960 | } |
| 3961 | |
| 3962 | #[test] |
| 3963 | fn blockquote_wraps_with_continuation_rail_indent() { |
| 3964 | let source = "> alpha beta gamma delta epsilon zeta"; |
| 3965 | let rendered = render_markdown_tagged(source, 12, Style::default()); |
| 3966 | let visible = tagged_visible(&rendered); |
| 3967 | assert!(visible.len() > 1, "fixture must wrap: {visible:?}"); |
| 3968 | for row in &visible { |
| 3969 | assert!( |
| 3970 | row.starts_with("│ "), |
| 3971 | "every row starts with the rail: {row:?}" |
| 3972 | ); |
| 3973 | } |
| 3974 | for row in &rendered { |
| 3975 | assert_eq!(row.copy_prefix_width, 0); |
| 3976 | } |
| 3977 | for width in rendered.iter().map(|row| { |
| 3978 | row.line |
| 3979 | .spans |
| 3980 | .iter() |
| 3981 | .map(|span| span.content.as_ref().width()) |
| 3982 | .sum::<usize>() |
| 3983 | }) { |
| 3984 | assert!(width <= 12, "rendered width {width} exceeds budget"); |
| 3985 | } |
| 3986 | // Rows re-join into the quote content (rail and alignment stripped). |
| 3987 | let combined = visible |
| 3988 | .iter() |
| 3989 | .map(|row| row.trim_start_matches('│').trim_start()) |
| 3990 | .collect::<Vec<_>>() |
| 3991 | .join(" "); |
| 3992 | assert_eq!(combined, &source[2..]); |
| 3993 | } |
| 3994 | |
| 3995 | fn tagged_visible(lines: &[RenderedMarkdownLine]) -> Vec<String> { |
| 3996 | lines |
| 3997 | .iter() |
| 3998 | .map(|rendered| { |
| 3999 | rendered |
| 4000 | .line |
| 4001 | .spans |
| 4002 | .iter() |
| 4003 | .map(|span| span.content.as_ref()) |
| 4004 | .collect() |
| 4005 | }) |
| 4006 | .collect() |
| 4007 | } |
| 4008 | |
| 4009 | #[test] |
| 4010 | fn http_links_keep_visible_text_and_out_of_band_metadata() { |
| 4011 | let source = "see https://example.com for details"; |
| 4012 | let rendered = render_markdown_tagged(source, 80, Style::default()); |
| 4013 | assert_eq!(tagged_visible(&rendered), vec![source]); |
| 4014 | assert!( |
| 4015 | rendered |
| 4016 | .iter() |
| 4017 | .flat_map(|line| &line.line.spans) |
| 4018 | .all(|span| { !span.content.contains('\x1b') && !span.content.contains("]8;;") }), |
| 4019 | "escape payloads must never enter visible spans" |
| 4020 | ); |
| 4021 | assert_eq!( |
| 4022 | rendered[0].links, |
| 4023 | vec![osc8::LineLink { |
| 4024 | col_start: 4, |
| 4025 | col_end: 22, |
| 4026 | target: "https://example.com".to_string(), |
| 4027 | line: None, |
| 4028 | }] |
| 4029 | ); |
| 4030 | } |
| 4031 | |
| 4032 | #[test] |
| 4033 | fn bare_http_links_exclude_surrounding_punctuation_from_target() { |
| 4034 | let source = "see (https://example.com/path)."; |
| 4035 | let rendered = render_markdown_tagged(source, 80, Style::default()); |
| 4036 | assert_eq!(tagged_visible(&rendered), vec![source]); |
| 4037 | assert_eq!(rendered[0].links.len(), 1); |
| 4038 | let link = &rendered[0].links[0]; |
| 4039 | assert_eq!(link.target, "https://example.com/path"); |
| 4040 | assert_eq!(link.col_start, 5); |
| 4041 | assert_eq!(link.col_end, 28); |
| 4042 | } |
| 4043 | |
| 4044 | #[test] |
| 4045 | fn bare_http_links_preserve_balanced_parentheses_in_target() { |
| 4046 | let url = "https://en.wikipedia.org/wiki/Function_(mathematics)"; |
| 4047 | let source = format!("see {url}."); |
| 4048 | let rendered = render_markdown_tagged(&source, 100, Style::default()); |
| 4049 | assert_eq!(tagged_visible(&rendered), vec![source]); |
| 4050 | assert_eq!(rendered[0].links.len(), 1); |
| 4051 | assert_eq!(rendered[0].links[0].target, url); |
| 4052 | } |
| 4053 | |
| 4054 | #[test] |
| 4055 | fn wrapped_url_chunks_keep_visible_label_and_full_target() { |
| 4056 | let url = "https://raw.githubusercontent.com/Hmbown/deepseek-skills/main/index.json"; |
| 4057 | let rendered = render_markdown_tagged(url, 34, Style::default()); |
| 4058 | let visible = tagged_visible(&rendered); |
| 4059 | assert!(visible.len() > 1, "fixture must wrap: {visible:?}"); |
| 4060 | assert_eq!(visible.concat(), url); |
| 4061 | for (line, text) in rendered.iter().zip(&visible) { |
| 4062 | assert_eq!(line.links.len(), 1, "each wrapped chunk is linked"); |
| 4063 | assert_eq!(line.links[0].target, url); |
| 4064 | assert_eq!(line.links[0].col_start, 0); |
| 4065 | assert_eq!(line.links[0].col_end, text.width().saturating_sub(1)); |
| 4066 | assert!(!text.contains('\x1b') && !text.contains("]8;;")); |
| 4067 | } |
| 4068 | } |
| 4069 | |
| 4070 | #[test] |
| 4071 | fn named_link_shows_only_label_and_keeps_target_in_metadata() { |
| 4072 | let rendered = render_markdown_tagged( |
| 4073 | "read [the docs](https://example.com/guide) now", |
| 4074 | 80, |
| 4075 | Style::default(), |
| 4076 | ); |
| 4077 | assert_eq!(tagged_visible(&rendered), vec!["read the docs now"]); |
| 4078 | assert_eq!( |
| 4079 | rendered[0].links, |
| 4080 | vec![osc8::LineLink { |
| 4081 | col_start: 5, |
| 4082 | col_end: 12, |
| 4083 | target: "https://example.com/guide".to_string(), |
| 4084 | line: None, |
| 4085 | }] |
| 4086 | ); |
| 4087 | } |
| 4088 | |
| 4089 | #[test] |
| 4090 | fn named_links_keep_angle_bracketed_destinations() { |
| 4091 | let wiki = "https://en.wikipedia.org/wiki/Function_(mathematics)"; |
| 4092 | let bracketed = format!("[link](<{wiki}>)"); |
| 4093 | let padded = format!("[link]( <{wiki}> )"); |
| 4094 | for (markup, target) in [ |
| 4095 | (bracketed.as_str(), Some(wiki)), |
| 4096 | (padded.as_str(), Some(wiki)), |
| 4097 | ( |
| 4098 | r"[link](<https://example.com/a\>)b>)", |
| 4099 | Some("https://example.com/a>)b"), |
| 4100 | ), |
| 4101 | ( |
| 4102 | r"[link](<https://example.com/a\<b?x=1&y=2\©>)", |
| 4103 | Some("https://example.com/a<b?x=1&y=2©"), |
| 4104 | ), |
| 4105 | (r"[link](<https://example.com/a\>)", None), |
| 4106 | (r#"[link](<https://example.com/a> "title")"#, None), |
| 4107 | ( |
| 4108 | "", |
| 4109 | Some("https://example.com/image.png"), |
| 4110 | ), |
| 4111 | ( |
| 4112 | "[](https://example.com/docs)", |
| 4113 | Some("https://example.com/docs"), |
| 4114 | ), |
| 4115 | ( |
| 4116 | "[](<https://example.com/docs>)", |
| 4117 | Some("https://example.com/docs"), |
| 4118 | ), |
| 4119 | ] { |
| 4120 | let rendered = |
| 4121 | render_markdown_tagged(&format!("read {markup} now"), 80, Style::default()); |
| 4122 | assert_eq!(tagged_visible(&rendered), vec!["read link now"], "{markup}"); |
| 4123 | let links: Vec<_> = target |
| 4124 | .map(|target| osc8::LineLink { |
| 4125 | col_start: 5, |
| 4126 | col_end: 8, |
| 4127 | target: target.to_string(), |
| 4128 | line: None, |
| 4129 | }) |
| 4130 | .into_iter() |
| 4131 | .collect(); |
| 4132 | assert_eq!(rendered[0].links, links, "{markup}"); |
| 4133 | } |
| 4134 | } |
| 4135 | |
| 4136 | #[test] |
| 4137 | fn named_links_reject_non_web_schemes_and_normalize_http_scheme() { |
| 4138 | let unsafe_link = render_markdown_tagged("[run](javascript:alert)", 80, Style::default()); |
| 4139 | assert_eq!(tagged_visible(&unsafe_link), vec!["run"]); |
| 4140 | assert!(unsafe_link.iter().all(|line| line.links.is_empty())); |
| 4141 | |
| 4142 | let web_link = |
| 4143 | render_markdown_tagged("[docs](HTTPS://example.com/guide)", 80, Style::default()); |
| 4144 | assert_eq!(tagged_visible(&web_link), vec!["docs"]); |
| 4145 | assert_eq!(web_link[0].links[0].target, "https://example.com/guide"); |
| 4146 | } |
| 4147 | |
| 4148 | #[test] |
| 4149 | fn named_links_target_absolute_paths_with_the_file_scheme() { |
| 4150 | let rendered = render_markdown_tagged( |
| 4151 | "edit [main.rs](/repo/src/main.rs) now", |
| 4152 | 80, |
| 4153 | Style::default(), |
| 4154 | ); |
| 4155 | assert_eq!(tagged_visible(&rendered), vec!["edit main.rs now"]); |
| 4156 | assert_eq!( |
| 4157 | rendered[0].links, |
| 4158 | vec![osc8::LineLink { |
| 4159 | col_start: 5, |
| 4160 | col_end: 11, |
| 4161 | target: "file:///repo/src/main.rs".to_string(), |
| 4162 | line: None, |
| 4163 | }] |
| 4164 | ); |
| 4165 | |
| 4166 | let explicit = |
| 4167 | render_markdown_tagged("[main.rs](FILE:///repo/src/main.rs)", 80, Style::default()); |
| 4168 | assert_eq!(explicit[0].links[0].target, "file:///repo/src/main.rs"); |
| 4169 | } |
| 4170 | |
| 4171 | #[test] |
| 4172 | fn resolver_links_inline_code_paths_dirs_urls_and_relative_markdown_links() { |
| 4173 | let mut resolver = |candidate: &str| match candidate { |
| 4174 | "src/main.rs:42" => Some(ResolvedLink { |
| 4175 | target: "file:///repo/src/main.rs".to_string(), |
| 4176 | line: Some(42), |
| 4177 | }), |
| 4178 | "dynamis/build/support-final/" => Some(ResolvedLink { |
| 4179 | target: "file:///repo/dynamis/build/support-final".to_string(), |
| 4180 | line: None, |
| 4181 | }), |
| 4182 | "docs/guide.md#L7" => Some(ResolvedLink { |
| 4183 | target: "file:///repo/docs/guide.md".to_string(), |
| 4184 | line: Some(7), |
| 4185 | }), |
| 4186 | _ => None, |
| 4187 | }; |
| 4188 | let rendered = render_markdown_tagged_with_palette_and_links( |
| 4189 | "check `src/main.rs:42` and `dynamis/build/support-final/` and `https://example.com` and [guide](docs/guide.md#L7) plus src/main.rs", |
| 4190 | 200, |
| 4191 | Style::default(), |
| 4192 | palette::PaletteMode::Dark, |
| 4193 | Some(&mut resolver), |
| 4194 | ); |
| 4195 | assert_eq!(rendered[0].links.len(), 4); |
| 4196 | assert_eq!(rendered[0].links[0].target, "file:///repo/src/main.rs"); |
| 4197 | assert_eq!(rendered[0].links[0].line, Some(42)); |
| 4198 | assert_eq!( |
| 4199 | rendered[0].links[1].target, |
| 4200 | "file:///repo/dynamis/build/support-final" |
| 4201 | ); |
| 4202 | assert_eq!(rendered[0].links[1].line, None); |
| 4203 | assert_eq!(rendered[0].links[2].target, "https://example.com"); |
| 4204 | assert_eq!(rendered[0].links[2].line, None); |
| 4205 | assert_eq!(rendered[0].links[3].target, "file:///repo/docs/guide.md"); |
| 4206 | assert_eq!(rendered[0].links[3].line, Some(7)); |
| 4207 | } |
| 4208 | |
| 4209 | #[test] |
| 4210 | fn classify_inline_code_accepts_urls_and_paths_and_rejects_code_globs_and_unc() { |
| 4211 | assert_eq!( |
| 4212 | classify_inline_code("https://example.com/docs"), |
| 4213 | Some(InlineCodeKind::Url) |
| 4214 | ); |
| 4215 | assert_eq!( |
| 4216 | classify_inline_code("http://localhost:8080"), |
| 4217 | Some(InlineCodeKind::Url) |
| 4218 | ); |
| 4219 | assert_eq!( |
| 4220 | classify_inline_code("src/main.rs:42"), |
| 4221 | Some(InlineCodeKind::Path) |
| 4222 | ); |
| 4223 | assert_eq!( |
| 4224 | classify_inline_code("dynamis/build/support-final/"), |
| 4225 | Some(InlineCodeKind::Path) |
| 4226 | ); |
| 4227 | assert_eq!(classify_inline_code("Makefile"), Some(InlineCodeKind::Path)); |
| 4228 | assert_eq!( |
| 4229 | classify_inline_code("Dockerfile"), |
| 4230 | Some(InlineCodeKind::Path) |
| 4231 | ); |
| 4232 | |
| 4233 | for rejected in [ |
| 4234 | "", |
| 4235 | "src/a.rs src/b.rs", |
| 4236 | "ftp://example.com/file", |
| 4237 | "javascript:alert(1)", |
| 4238 | "src/*.rs", |
| 4239 | "a=b.c", |
| 4240 | "foo<T>", |
| 4241 | "a|b", |
| 4242 | "a;b", |
| 4243 | "//server/share/file.txt", |
| 4244 | "\\\\server\\share\\file.txt", |
| 4245 | "1.2.3", |
| 4246 | "justword", |
| 4247 | ] { |
| 4248 | assert_eq!(classify_inline_code(rejected), None, "{rejected:?}"); |
| 4249 | } |
| 4250 | } |
| 4251 | |
| 4252 | #[test] |
| 4253 | fn inline_code_path_with_no_resolver_stays_plain_code() { |
| 4254 | let rendered = render_markdown_tagged("see `src/main.rs:42`", 80, Style::default()); |
| 4255 | assert!(rendered[0].links.is_empty()); |
| 4256 | } |
| 4257 | |
| 4258 | #[test] |
| 4259 | fn named_links_reject_relative_paths_and_smuggled_control_bytes() { |
| 4260 | // Nothing here resolves a relative path against a workspace root, so a |
| 4261 | // relative destination would link to whatever the terminal's cwd is. |
| 4262 | let relative = render_markdown_tagged("[main.rs](src/main.rs)", 80, Style::default()); |
| 4263 | assert_eq!(tagged_visible(&relative), vec!["main.rs"]); |
| 4264 | assert!(relative.iter().all(|line| line.links.is_empty())); |
| 4265 | |
| 4266 | let hostile = render_markdown_tagged( |
| 4267 | "[log](/tmp/a\x07b\x1b]8;;https://evil.test\x1b\\c)", |
| 4268 | 80, |
| 4269 | Style::default(), |
| 4270 | ); |
| 4271 | assert!( |
| 4272 | hostile.iter().all(|line| line.links.is_empty()), |
| 4273 | "control bytes must not reach a link target: {hostile:?}" |
| 4274 | ); |
| 4275 | |
| 4276 | // A `file://host/share` destination is a remote reference, not a local |
| 4277 | // path, and must not be rewritten into one. |
| 4278 | let host = render_markdown_tagged("[share](file://evil.test/etc)", 80, Style::default()); |
| 4279 | assert!(host.iter().all(|line| line.links.is_empty())); |
| 4280 | } |
| 4281 | |
| 4282 | #[test] |
| 4283 | fn bare_paths_in_prose_are_never_linkified() { |
| 4284 | let rendered = render_markdown_tagged( |
| 4285 | "the fix landed in /repo/src/main.rs today", |
| 4286 | 80, |
| 4287 | Style::default(), |
| 4288 | ); |
| 4289 | assert!(rendered.iter().all(|line| line.links.is_empty())); |
| 4290 | } |
| 4291 | |
| 4292 | #[test] |
| 4293 | fn table_separator_row_is_kept() { |
| 4294 | // Separator rows are now kept as TableSeparator blocks so the |
| 4295 | // renderer can draw horizontal rules at the correct positions. |
| 4296 | let src = "| 项目属性 | 详情 |\n|----------|------|\n| **语言** | Rust 1.88+ |\n"; |
| 4297 | let parsed = parse(src); |
| 4298 | let blocks: Vec<_> = parsed.blocks.iter().collect(); |
| 4299 | // Should have 2 TableRow blocks (header + data) + 1 TableSeparator |
| 4300 | let table_rows: Vec<_> = blocks |
| 4301 | .iter() |
| 4302 | .filter(|b| matches!(b, Block::TableRow(_))) |
| 4303 | .collect(); |
| 4304 | assert_eq!(table_rows.len(), 2, "expected 2 table rows: {blocks:?}"); |
| 4305 | let separators: Vec<_> = blocks |
| 4306 | .iter() |
| 4307 | .filter(|b| matches!(b, Block::TableSeparator)) |
| 4308 | .collect(); |
| 4309 | assert_eq!( |
| 4310 | separators.len(), |
| 4311 | 1, |
| 4312 | "expected 1 table separator: {blocks:?}" |
| 4313 | ); |
| 4314 | } |
| 4315 | |
| 4316 | #[test] |
| 4317 | fn bold_markers_stripped_in_render() { |
| 4318 | let src = "这是一个 **Rust 工作区项目**,包含多个 crate。\n"; |
| 4319 | let lines = render_markdown(src, 80, Style::default()); |
| 4320 | let text: String = lines |
| 4321 | .iter() |
| 4322 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 4323 | .collect(); |
| 4324 | assert!( |
| 4325 | !text.contains("**"), |
| 4326 | "bold markers leaked into output: {text:?}" |
| 4327 | ); |
| 4328 | assert!(text.contains("Rust"), "bold content missing: {text:?}"); |
| 4329 | } |
| 4330 | |
| 4331 | #[test] |
| 4332 | fn table_renders_with_box_drawing_borders() { |
| 4333 | let src = "| 文件 | 改动 |\n|---|---|\n| foo.rs | 重写 |\n"; |
| 4334 | let lines = render_markdown(src, 60, Style::default()); |
| 4335 | let text: String = lines |
| 4336 | .iter() |
| 4337 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 4338 | .collect(); |
| 4339 | // Column pipes still present |
| 4340 | assert!(text.contains('│'), "table pipe separator missing: {text:?}"); |
| 4341 | // Separator row rendered as middle border, not raw markdown |
| 4342 | assert!( |
| 4343 | !text.contains("|---|"), |
| 4344 | "raw separator row leaked: {text:?}" |
| 4345 | ); |
| 4346 | // Top and bottom borders present |
| 4347 | assert!( |
| 4348 | text.contains('\u{250C}'), |
| 4349 | "top-left corner missing: {text:?}" |
| 4350 | ); |
| 4351 | assert!( |
| 4352 | text.contains('\u{2510}'), |
| 4353 | "top-right corner missing: {text:?}" |
| 4354 | ); |
| 4355 | assert!( |
| 4356 | text.contains('\u{2514}'), |
| 4357 | "bottom-left corner missing: {text:?}" |
| 4358 | ); |
| 4359 | assert!( |
| 4360 | text.contains('\u{2518}'), |
| 4361 | "bottom-right corner missing: {text:?}" |
| 4362 | ); |
| 4363 | // Middle separator present (at the |---|---| position) |
| 4364 | assert!( |
| 4365 | text.contains('\u{251C}'), |
| 4366 | "middle-left junction missing: {text:?}" |
| 4367 | ); |
| 4368 | assert!( |
| 4369 | text.contains('\u{2524}'), |
| 4370 | "middle-right junction missing: {text:?}" |
| 4371 | ); |
| 4372 | } |
| 4373 | |
| 4374 | #[test] |
| 4375 | fn table_pipes_inside_inline_code_stay_in_the_cell() { |
| 4376 | let src = "| Check | Result |\n\ |
| 4377 | |---|---|\n\ |
| 4378 | | `strings ~/.cargo/bin/codewhale-tui | grep -c \"legacy marker\"` | 0 matches |\n"; |
| 4379 | let parsed = parse(src); |
| 4380 | |
| 4381 | let rows: Vec<&Vec<String>> = parsed |
| 4382 | .blocks |
| 4383 | .iter() |
| 4384 | .filter_map(|block| match block { |
| 4385 | Block::TableRow(cells) => Some(cells), |
| 4386 | _ => None, |
| 4387 | }) |
| 4388 | .collect(); |
| 4389 | |
| 4390 | assert_eq!(rows.len(), 2, "expected header + data row: {rows:?}"); |
| 4391 | assert_eq!( |
| 4392 | rows[1], |
| 4393 | &vec![ |
| 4394 | "`strings ~/.cargo/bin/codewhale-tui | grep -c \"legacy marker\"`".to_string(), |
| 4395 | "0 matches".to_string(), |
| 4396 | ] |
| 4397 | ); |
| 4398 | |
| 4399 | let rendered_lines = visible_lines(&render_markdown(src, 200, Style::default())); |
| 4400 | let rendered = rendered_lines.join("\n"); |
| 4401 | assert!( |
| 4402 | rendered.contains("grep -c"), |
| 4403 | "inline-code command was lost: {rendered}" |
| 4404 | ); |
| 4405 | let data_line = rendered_lines |
| 4406 | .iter() |
| 4407 | .find(|line| line.contains("strings ~/.cargo/bin/codewhale-tui")) |
| 4408 | .expect("data row should render"); |
| 4409 | assert_eq!( |
| 4410 | data_line.matches('│').count(), |
| 4411 | 3, |
| 4412 | "two-column table row should have left, middle, and right separators: {data_line:?}" |
| 4413 | ); |
| 4414 | } |
| 4415 | |
| 4416 | /// Cells longer than the per-column width must word-wrap to multiple |
| 4417 | /// lines instead of getting truncated with `…`. Truncation silently |
| 4418 | /// drops content the user can never see — particularly bad in narrow |
| 4419 | /// Windows terminals or with verbose English/Chinese instructional |
| 4420 | /// tables (the common LLM-output case). |
| 4421 | #[test] |
| 4422 | fn table_cell_wider_than_column_wraps_instead_of_truncating() { |
| 4423 | let src = "| Feature | How to verify |\n\ |
| 4424 | |---|---|\n\ |
| 4425 | | Workspace-local commands | Drop a .deepseek/commands/foo.md in any project, run deepseek from there, type /foo — should dispatch |\n"; |
| 4426 | let lines = render_markdown(src, 80, Style::default()); |
| 4427 | let combined: String = lines |
| 4428 | .iter() |
| 4429 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 4430 | .collect(); |
| 4431 | |
| 4432 | assert!( |
| 4433 | !combined.contains('…'), |
| 4434 | "table cell was truncated with `…` instead of wrapping; got: {combined:?}" |
| 4435 | ); |
| 4436 | assert!( |
| 4437 | combined.contains("type /foo"), |
| 4438 | "tail of long cell was lost; got: {combined:?}" |
| 4439 | ); |
| 4440 | assert!( |
| 4441 | combined.contains("Workspace-local commands"), |
| 4442 | "short cell content lost; got: {combined:?}" |
| 4443 | ); |
| 4444 | } |
| 4445 | |
| 4446 | /// Wrapped table rows must keep column separators on every visual |
| 4447 | /// line so the columns remain visually aligned across all wrapped |
| 4448 | /// segments. A wrapped row's continuation lines should still show |
| 4449 | /// the `│` separator pipes at the same column positions. |
| 4450 | #[test] |
| 4451 | fn wrapped_table_row_preserves_column_separators() { |
| 4452 | let src = "| A | B |\n\ |
| 4453 | |---|---|\n\ |
| 4454 | | short | this is a very very long second cell that absolutely must wrap to a new visual line because it cannot fit in the column allocated to it at this terminal width |\n"; |
| 4455 | let lines = render_markdown(src, 60, Style::default()); |
| 4456 | let rendered: Vec<String> = lines |
| 4457 | .iter() |
| 4458 | .map(|l| { |
| 4459 | l.spans |
| 4460 | .iter() |
| 4461 | .map(|s| s.content.as_ref()) |
| 4462 | .collect::<String>() |
| 4463 | }) |
| 4464 | .collect(); |
| 4465 | |
| 4466 | // Every line in the rendered table — including wrapped continuation |
| 4467 | // lines — must show the pipe column separator. We identify table |
| 4468 | // body lines as ones that start with the row separator `│`. |
| 4469 | let body_lines: Vec<&String> = rendered.iter().filter(|s| s.starts_with('│')).collect(); |
| 4470 | |
| 4471 | assert!( |
| 4472 | body_lines.len() >= 3, |
| 4473 | "expected at least header + multi-line data row (3+ body lines), got {}: {:?}", |
| 4474 | body_lines.len(), |
| 4475 | body_lines |
| 4476 | ); |
| 4477 | |
| 4478 | for line in &body_lines { |
| 4479 | assert!( |
| 4480 | line.matches('│').count() >= 3, |
| 4481 | "every wrapped table line should have N+1 column separators \ |
| 4482 | for N columns; got fewer in: {line:?}" |
| 4483 | ); |
| 4484 | } |
| 4485 | |
| 4486 | // All of the long cell's content must appear across the wrapped lines. |
| 4487 | let combined: String = rendered.join("\n"); |
| 4488 | for fragment in ["this is a very very long", "must wrap", "terminal width"] { |
| 4489 | assert!( |
| 4490 | combined.contains(fragment), |
| 4491 | "fragment {fragment:?} missing from wrapped output:\n{combined}" |
| 4492 | ); |
| 4493 | } |
| 4494 | let target = "https://example.com/guide"; |
| 4495 | let label = "y".repeat(120); |
| 4496 | let table = format!("| A | B |\n|---|---|\n| 界 | [{label}]({target}) |"); |
| 4497 | let rows = render_markdown_tagged(&table, 36, Style::default()); |
| 4498 | let mut linked_width = 0; |
| 4499 | for row in rows.iter().filter(|row| !row.links.is_empty()) { |
| 4500 | let visible = row.line.to_string(); |
| 4501 | let start = visible.find('y').unwrap(); |
| 4502 | assert_eq!(row.links.len(), 1); |
| 4503 | let link = &row.links[0]; |
| 4504 | assert_eq!(link.target, target); |
| 4505 | assert_eq!(link.col_start, visible[..start].width()); |
| 4506 | let width = link.col_end - link.col_start + 1; |
| 4507 | assert_eq!(width, visible.matches('y').count()); |
| 4508 | assert!(link.col_end < row.line.width()); |
| 4509 | linked_width += width; |
| 4510 | } |
| 4511 | assert_eq!(linked_width, label.len()); |
| 4512 | } |
| 4513 | |
| 4514 | // ─── Paragraph wrap regression suite (#1344, #1351) ──────────────────── |
| 4515 | // |
| 4516 | // The bug: paragraph wrap (render_line_with_links) is word-based. A |
| 4517 | // single word wider than the available width was placed alone on a line |
| 4518 | // and silently overflowed the right edge of the transcript. Long URLs / |
| 4519 | // paths / hashes / no-whitespace CJK runs all hit this. The fix |
| 4520 | // hard-breaks overlong words at grapheme boundaries; these tests pin |
| 4521 | // that across widths 40/60/80/120. |
| 4522 | |
| 4523 | fn rendered_widths(rendered: &[Line<'static>]) -> Vec<usize> { |
| 4524 | rendered |
| 4525 | .iter() |
| 4526 | .map(|l| { |
| 4527 | l.spans |
| 4528 | .iter() |
| 4529 | .map(|s| s.content.as_ref().width()) |
| 4530 | .sum::<usize>() |
| 4531 | }) |
| 4532 | .collect() |
| 4533 | } |
| 4534 | |
| 4535 | fn render_paragraph_for_test(text: &str, width: usize) -> Vec<Line<'static>> { |
| 4536 | render_line_with_links(text, width, Style::default(), Style::default()) |
| 4537 | } |
| 4538 | |
| 4539 | #[test] |
| 4540 | fn paragraph_wrap_breaks_overlong_word_at_width_40() { |
| 4541 | // 200-char no-whitespace token must not exceed the 40-col window. |
| 4542 | let long = "a".repeat(200); |
| 4543 | let rendered = render_paragraph_for_test(&long, 40); |
| 4544 | for w in rendered_widths(&rendered) { |
| 4545 | assert!(w <= 40, "rendered width {w} exceeds 40-col window"); |
| 4546 | } |
| 4547 | // And the full content must still be present across the wrapped lines. |
| 4548 | let combined: String = rendered |
| 4549 | .iter() |
| 4550 | .flat_map(|l| l.spans.iter().map(|s| s.content.to_string())) |
| 4551 | .collect(); |
| 4552 | assert_eq!(combined.matches('a').count(), 200); |
| 4553 | } |
| 4554 | |
| 4555 | #[test] |
| 4556 | fn paragraph_wrap_breaks_no_whitespace_cjk_at_width_40() { |
| 4557 | // #963: long CJK runs without whitespace must wrap by display width |
| 4558 | // instead of overflowing or truncating. Each Han character is 2 cols. |
| 4559 | let long = "界".repeat(300); |
| 4560 | let rendered = render_paragraph_for_test(&long, 40); |
| 4561 | for w in rendered_widths(&rendered) { |
| 4562 | assert!(w <= 40, "rendered width {w} exceeds 40-col window"); |
| 4563 | } |
| 4564 | let combined: String = rendered |
| 4565 | .iter() |
| 4566 | .flat_map(|l| l.spans.iter().map(|s| s.content.to_string())) |
| 4567 | .collect(); |
| 4568 | assert_eq!(combined.chars().filter(|&ch| ch == '界').count(), 300); |
| 4569 | assert!( |
| 4570 | rendered.len() >= 15, |
| 4571 | "300 double-width chars should wrap into many rows, got {}", |
| 4572 | rendered.len() |
| 4573 | ); |
| 4574 | } |
| 4575 | |
| 4576 | #[test] |
| 4577 | fn paragraph_wrap_breaks_overlong_word_at_widths_60_80_120() { |
| 4578 | let long = format!("https://example.com/{}", "p".repeat(180)); |
| 4579 | for &width in &[60usize, 80, 120] { |
| 4580 | let rendered = render_paragraph_for_test(&long, width); |
| 4581 | for w in rendered_widths(&rendered) { |
| 4582 | assert!( |
| 4583 | w <= width, |
| 4584 | "width={width}: rendered line width {w} exceeds budget" |
| 4585 | ); |
| 4586 | } |
| 4587 | assert!(rendered.len() >= 2, "width={width}: expected wrap"); |
| 4588 | } |
| 4589 | } |
| 4590 | |
| 4591 | #[test] |
| 4592 | fn paragraph_wrap_keeps_short_words_unbroken() { |
| 4593 | // Regression guard: short words must still be broken at whitespace, |
| 4594 | // not mid-word. Width 40, only short words, expect zero mid-word |
| 4595 | // breaks (each line reads as natural English). |
| 4596 | let text = "the quick brown fox jumps over the lazy dog and then it stops moving"; |
| 4597 | let rendered = render_paragraph_for_test(text, 40); |
| 4598 | for line in &rendered { |
| 4599 | let s: String = line.spans.iter().map(|s| s.content.to_string()).collect(); |
| 4600 | // Heuristic: trimmed line should not start with a partial word |
| 4601 | // (i.e. should start with a real English start) — every line in |
| 4602 | // this fixture starts with a word in our short list. |
| 4603 | let first = s.split_whitespace().next().unwrap_or(""); |
| 4604 | assert!( |
| 4605 | [ |
| 4606 | "the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog", "and", "then", |
| 4607 | "it", "stops", "moving" |
| 4608 | ] |
| 4609 | .contains(&first), |
| 4610 | "line {s:?} appears to start with a partial word" |
| 4611 | ); |
| 4612 | } |
| 4613 | } |
| 4614 | |
| 4615 | #[test] |
| 4616 | fn paragraph_wrap_mixed_short_and_overlong_word() { |
| 4617 | // The overlong word must wrap; the trailing short words must pack |
| 4618 | // onto subsequent lines. The combined content is preserved. |
| 4619 | let long = "x".repeat(150); |
| 4620 | let text = format!("intro {long} tail words go here"); |
| 4621 | let rendered = render_paragraph_for_test(&text, 80); |
| 4622 | for w in rendered_widths(&rendered) { |
| 4623 | assert!(w <= 80, "rendered width {w} exceeds 80-col window"); |
| 4624 | } |
| 4625 | let combined: String = rendered |
| 4626 | .iter() |
| 4627 | .flat_map(|l| l.spans.iter().map(|s| s.content.to_string())) |
| 4628 | .collect(); |
| 4629 | for fragment in ["intro", "tail", "words", "go", "here"] { |
| 4630 | assert!( |
| 4631 | combined.contains(fragment), |
| 4632 | "fragment {fragment:?} missing from wrapped output:\n{combined}" |
| 4633 | ); |
| 4634 | } |
| 4635 | assert_eq!(combined.matches('x').count(), 150); |
| 4636 | } |
| 4637 | |
| 4638 | #[test] |
| 4639 | fn paragraph_wrap_handles_zero_width_gracefully() { |
| 4640 | // Width 0 should not panic or hang; it returns the input as-is or |
| 4641 | // empty, but never produces a line wider than 0 (when 0 means "no |
| 4642 | // budget at all"). This pins the early-return path against future |
| 4643 | // regressions. |
| 4644 | let rendered = render_paragraph_for_test("hello world", 0); |
| 4645 | // Any output is acceptable (the path is degenerate); assert no panic. |
| 4646 | let _ = rendered; |
| 4647 | } |
| 4648 | |
| 4649 | fn rendered_text(rendered: &[Line<'static>]) -> String { |
| 4650 | rendered |
| 4651 | .iter() |
| 4652 | .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref())) |
| 4653 | .collect() |
| 4654 | } |
| 4655 | |
| 4656 | fn assert_rendered_widths_fit(rendered: &[Line<'static>], width: usize, label: &str) { |
| 4657 | for line_width in rendered_widths(rendered) { |
| 4658 | assert!( |
| 4659 | line_width <= width, |
| 4660 | "{label} width={width}: rendered line width {line_width} exceeds budget" |
| 4661 | ); |
| 4662 | } |
| 4663 | } |
| 4664 | |
| 4665 | // ── Unicode / CJK / emoji / combining-char width QA (#3488) ──────────── |
| 4666 | |
| 4667 | #[test] |
| 4668 | fn paragraph_wrap_keeps_unicode_runs_within_qa_widths() { |
| 4669 | let cases = [ |
| 4670 | ("cjk", "界".repeat(300)), |
| 4671 | ("emoji", "😀".repeat(200)), |
| 4672 | ("mixed-cjk-emoji", "界😀世🚀".repeat(90)), |
| 4673 | ]; |
| 4674 | |
| 4675 | for (label, text) in cases { |
| 4676 | for &width in &[80usize, 100, 120] { |
| 4677 | let rendered = render_paragraph_for_test(&text, width); |
| 4678 | assert_rendered_widths_fit(&rendered, width, label); |
| 4679 | assert_eq!( |
| 4680 | rendered_text(&rendered), |
| 4681 | text, |
| 4682 | "{label} width={width}: content changed while wrapping" |
| 4683 | ); |
| 4684 | |
| 4685 | let min_lines = text.width().div_ceil(width); |
| 4686 | assert!( |
| 4687 | rendered.len() >= min_lines, |
| 4688 | "{label} width={width}: expected at least {min_lines} lines, got {}", |
| 4689 | rendered.len() |
| 4690 | ); |
| 4691 | } |
| 4692 | } |
| 4693 | } |
| 4694 | |
| 4695 | #[test] |
| 4696 | fn paragraph_wrap_preserves_mixed_unicode_and_ascii_fragments() { |
| 4697 | let cjk = "这是一个测试字符串".repeat(10); // 80 Han chars = 160 cols |
| 4698 | let emoji = "🚀".repeat(12); |
| 4699 | let text = format!("Note: {cjk} done {emoji}"); |
| 4700 | |
| 4701 | for &width in &[80usize, 100, 120] { |
| 4702 | let rendered = render_paragraph_for_test(&text, width); |
| 4703 | assert_rendered_widths_fit(&rendered, width, "mixed unicode/ascii"); |
| 4704 | |
| 4705 | let visible = visible_lines(&rendered).join("\n"); |
| 4706 | for fragment in ["Note:", "测试", "done"] { |
| 4707 | assert!( |
| 4708 | visible.contains(fragment), |
| 4709 | "width={width}: fragment {fragment:?} missing from output:\n{visible}" |
| 4710 | ); |
| 4711 | } |
| 4712 | assert_eq!( |
| 4713 | visible.matches('🚀').count(), |
| 4714 | 12, |
| 4715 | "width={width}: emoji content lost" |
| 4716 | ); |
| 4717 | } |
| 4718 | } |
| 4719 | |
| 4720 | #[test] |
| 4721 | fn narrow_table_stacks_rows_as_header_value_lines() { |
| 4722 | let target = "https://example.com/x"; |
| 4723 | let src = |
| 4724 | format!("| Key | Link |\n|---|---|\n| a | [go]({target}) |\n| b | longer value |\n"); |
| 4725 | let rows = render_markdown_tagged(&src, 8, Style::default()); |
| 4726 | let text: Vec<String> = rows.iter().map(|row| row.line.to_string()).collect(); |
| 4727 | for row in &rows { |
| 4728 | assert!(row.line.width() <= 8, "row overflows width 8: {text:?}"); |
| 4729 | } |
| 4730 | assert!( |
| 4731 | !text.concat().contains('│'), |
| 4732 | "narrow table kept columns: {text:?}" |
| 4733 | ); |
| 4734 | assert_eq!(text[0], "Key: a"); |
| 4735 | let link_row = rows.iter().find(|row| !row.links.is_empty()).unwrap(); |
| 4736 | assert_eq!(link_row.links[0].target, target); |
| 4737 | assert!(text.contains(&"Key: b".to_string()), "{text:?}"); |
| 4738 | } |
| 4739 | |
| 4740 | #[test] |
| 4741 | fn table_render_keeps_cjk_cells_within_qa_widths() { |
| 4742 | let cjk = "界".repeat(80); |
| 4743 | let src = format!("| Name | Value |\n|---|---|\n| CJK | {cjk} |\n"); |
| 4744 | |
| 4745 | for &width in &[80usize, 100, 120] { |
| 4746 | let rendered = render_markdown(&src, width as u16, Style::default()); |
| 4747 | assert_rendered_widths_fit(&rendered, width, "table cjk"); |
| 4748 | assert_eq!( |
| 4749 | rendered_text(&rendered).matches('界').count(), |
| 4750 | 80, |
| 4751 | "width={width}: CJK table cell content lost" |
| 4752 | ); |
| 4753 | } |
| 4754 | } |
| 4755 | |
| 4756 | #[test] |
| 4757 | fn paragraph_wrap_keeps_cjk_transcript_within_narrow_widths() { |
| 4758 | // The seed cases cover 80/100/120; narrow terminals (resize / small |
| 4759 | // panes) are the other half of #3488's terminal-width lane. A CJK |
| 4760 | // transcript paragraph must still wrap inside tiny windows without |
| 4761 | // overflowing the border or dropping content. |
| 4762 | let text = "实时输出结果显示正常".repeat(6); // 60 Han glyphs, 120 cols |
| 4763 | for &width in &[20usize, 40] { |
| 4764 | let rendered = render_paragraph_for_test(&text, width); |
| 4765 | assert_rendered_widths_fit(&rendered, width, "narrow cjk transcript"); |
| 4766 | assert_eq!( |
| 4767 | rendered_text(&rendered), |
| 4768 | text, |
| 4769 | "width={width}: CJK transcript content changed while wrapping" |
| 4770 | ); |
| 4771 | } |
| 4772 | } |
| 4773 | |
| 4774 | // A deliberate measurement probe, not an assertion: run it with |
| 4775 | // `--nocapture` to read the per-append cost. Printing is the whole point, |
| 4776 | // so the module-wide stdout ban is lifted here the same way |
| 4777 | // `core/engine/tests.rs` lifts it for its probes. |
| 4778 | #[allow(clippy::print_stdout)] |
| 4779 | #[test] |
| 4780 | fn probe_incremental_stream_cost() { |
| 4781 | // Faithful to one streaming message: the document grows a word at a |
| 4782 | // time and the render path re-parses and re-renders the whole visible |
| 4783 | // text on every tick. Reports the cost per 250 appends so growth with |
| 4784 | // message size is visible. |
| 4785 | use std::time::Instant; |
| 4786 | let words: Vec<&str> = |
| 4787 | "the quick brown fox jumps over a lazy dog and then keeps going for a while" |
| 4788 | .split(' ') |
| 4789 | .collect(); |
| 4790 | let mut doc = String::new(); |
| 4791 | let width = 100u16; |
| 4792 | let mut window_start = Instant::now(); |
| 4793 | for i in 0..2000usize { |
| 4794 | doc.push_str(words[i % words.len()]); |
| 4795 | doc.push(' '); |
| 4796 | let parsed = parse(&doc); |
| 4797 | let lines = render_parsed(&parsed, width, Style::default()); |
| 4798 | std::hint::black_box(&lines); |
| 4799 | if (i + 1) % 250 == 0 { |
| 4800 | let elapsed = window_start.elapsed(); |
| 4801 | println!( |
| 4802 | "PROBE bytes={} per_append={:?} total={:?}", |
| 4803 | doc.len(), |
| 4804 | elapsed / 250, |
| 4805 | elapsed |
| 4806 | ); |
| 4807 | window_start = Instant::now(); |
| 4808 | } |
| 4809 | } |
| 4810 | } |
| 4811 | } |
| 4812 |