plannotator-tui 0.15.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Per-block rendering and the row map.
//!
//! Each block is rendered in isolation through `tui-markdown` (cached, width-independent),
//! aligned back to its source bytes, and wrapped to the current column width. List and quote
//! blocks are decorated in between (`decorate`), definition lists indented (`definitions`),
//! and top-level code drawn beside a bar and coloured when shown (`code`). Every screen cell
//! therefore knows its block and, where it shows real text, its source byte. A long document
//! lays out its first screens before the first frame and the rest in the background
//! (`layout::background`).

mod code;
mod definitions;
mod nested;
#[cfg(test)]
mod tests;

use std::borrow::Cow;
use std::ops::Range;

use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Text};
use tui_markdown::{Options, StyleSheet};

use crate::cjk_emphasis::{protect, strip_marks};
use crate::decorate::{self, Decorated, RULE, Syntax};
use crate::doc::{BlockKind, Document, Opening};
use crate::srcmap::{LineOffsets, align};
use crate::theme::palette;
use crate::wrap::{Hang, Row, Table, clip_line, rule_row, wrap_line, wrap_line_hanging, wrap_table};
use code::Code;
use nested::Nested;

mod background;
mod worker_panic;

use background::{Rest, each_in_parallel, lay_out, lay_out_unit, units};
pub(crate) use worker_panic::keep_hook_off_layout_threads;

/// Rows of vertical space between blocks.
const BLOCK_GAP: usize = 1;
/// Further rows above a level one or two heading, so a section reads as one.
const SECTION_GAP: usize = 1;
/// Drawn under a level one heading, across the reading column.
pub(crate) const TITLE_RULE: char = '╍';

/// Rows [`DocLayout::start`] lays out before the first frame: more than any terminal shows.
const FIRST_ROWS: usize = 500;

/// House style: no `#` markers, headings carry weight through bold and colour rather than
/// background color, so the palette stays available for selection and annotations.
#[derive(Debug, Clone)]
struct Styles {
    /// Whether code shows the fences it was written with. A top-level code block draws a bar
    /// instead; code inside a list or quote has nothing else to set it apart.
    fences: bool,
}

impl StyleSheet for Styles {
    fn heading(&self, level: u8) -> Style {
        match level {
            1 | 2 => Style::new().fg(palette().heading).add_modifier(Modifier::BOLD),
            _ => Style::new().fg(palette().subheading).add_modifier(Modifier::BOLD),
        }
    }
    fn heading_marker(&self, _level: u8) -> &'static str {
        ""
    }
    fn code(&self) -> Style {
        Style::new().fg(palette().code)
    }
    fn code_block_fence(&self) -> &str {
        if self.fences { "```" } else { "" }
    }
    fn link(&self) -> Style {
        Style::new().fg(Color::Blue).add_modifier(Modifier::UNDERLINED)
    }
    fn blockquote(&self) -> Style {
        Style::new().fg(Color::Green).add_modifier(Modifier::ITALIC)
    }
}

#[derive(Debug)]
pub(crate) struct RenderedBlock {
    /// Width-independent styled lines from the renderer (owned, cached).
    text: Text<'static>,
    /// Per line, per char: absolute source byte offset (cached with `text`).
    offsets: Vec<LineOffsets>,
    kind: BlockKind,
    /// Per line, how its wrapped rows start; empty when nothing hangs.
    hangs: Vec<Hang>,
    /// A heading's level.
    heading: Option<u8>,
    /// Drawn right under the block before it, with no gap row: an item of a list or a term of
    /// a definition list after the first.
    joined: bool,
    /// The top-level Markdown block it is, or is an item of.
    top: usize,
    /// A top-level code block's language and colours.
    code: Option<Code>,
    /// Fenced code inside a list or quote.
    nested: Vec<Nested>,
    /// A table's columns, the same in every row of a table cut into rows.
    table: Option<Table>,
    /// Rows for the current width.
    pub(crate) rows: Vec<Row>,
    /// First screen row of this block in document coordinates.
    pub(crate) first_row: usize,
}

/// A document laid out for one width. A long one opened with [`DocLayout::start`] holds
/// only its first blocks until [`DocLayout::finish`] adds the rest from the background.
#[derive(Debug)]
pub(crate) struct DocLayout {
    pub(crate) width: usize,
    pub(crate) blocks: Vec<RenderedBlock>,
    pub(crate) total_rows: usize,
    /// The blocks after `blocks`, still being laid out on another thread.
    rest: Option<Rest>,
}

impl RenderedBlock {
    /// Render block `index` of `doc` (the expensive part) and lay it out `width` columns wide.
    fn new(doc: &Document, index: usize, width: usize) -> Self {
        let mut block = render_block(doc, index);
        block.wrap(width);
        block
    }

    /// Lay the block out `width` columns wide.
    fn wrap(&mut self, width: usize) {
        let lines = || self.text.lines.iter().zip(&self.offsets);
        self.rows = if self.kind == BlockKind::Rule {
            let offset = self.offsets.iter().flatten().flatten().next().copied();
            vec![rule_row(RULE, Style::new().fg(palette().idle_fg), offset, width)]
        } else if let Some(code) = &self.code {
            code.rows(&self.text.lines, &self.offsets, width)
        } else if let Some(table) = &self.table {
            wrap_table(&self.text.lines, &self.offsets, table, width)
        } else if self.kind.preserves_columns() {
            lines().map(|(l, o)| clip_line(l, o, width)).collect()
        } else if self.hangs.is_empty() {
            lines().flat_map(|(l, o)| wrap_line(l, o, width)).collect()
        } else {
            lines().zip(&self.hangs).flat_map(|((l, o), h)| wrap_line_hanging(l, o, h, width)).collect()
        };
        if self.heading == Some(1) {
            self.rows.push(rule_row(TITLE_RULE, Style::new().fg(palette().heading), None, width));
        }
    }
}

/// `source`, the text of a block of `kind`, through the Markdown renderer. With `sibling`,
/// the line of an empty list item, `source` is rendered after it and a blank line, and the
/// sibling's line is dropped.
fn markdown(source: &str, kind: BlockKind, sibling: Option<&str>) -> Text<'static> {
    let protected = protect(source);
    let options = Options::new(Styles { fences: kind != BlockKind::CodeBlock });
    let text = match sibling {
        Some(sibling) => {
            let mut text =
                own(tui_markdown::from_str_with_options(&format!("{sibling}\n\n{protected}"), &options));
            if !text.lines.is_empty() {
                text.lines.remove(0);
            }
            text
        }
        None => own(tui_markdown::from_str_with_options(&protected, &options)),
    };
    if matches!(protected, Cow::Owned(_)) { strip_marks(text) } else { text }
}

fn render_block(doc: &Document, index: usize) -> RenderedBlock {
    let source = doc.block_text(index);
    let kind = doc.blocks.get(index).map_or(BlockKind::Other, |b| b.kind);
    let base = doc.blocks.get(index).map_or(0, |b| b.range.start);
    let opening = doc.blocks.get(index).map(|b| &b.opening);
    // An item of a loose list is drawn as the second item of a loose list, after an empty
    // one whose line is then dropped: alone it may parse as a tight list of one.
    let sibling = doc.blocks.get(index).filter(|b| b.loose).and_then(|_| loose_sibling(source));
    let text = markdown(source, kind, sibling.as_deref());
    let plain: Vec<String> = text.lines.iter().map(ToString::to_string).collect();
    let block = |Decorated { text, offsets, hangs }, nested| RenderedBlock {
        text,
        offsets,
        kind,
        hangs,
        heading: match opening {
            Some(Opening::Heading(level)) => Some(*level),
            _ => None,
        },
        code: match opening {
            Some(Opening::Code(info)) => Some(Code::new(info)),
            _ => None,
        },
        nested,
        table: None,
        joined: doc.blocks.get(index).is_some_and(|b| b.joined),
        top: doc.blocks.get(index).map_or(0, |b| b.top),
        rows: Vec::new(),
        first_row: 0,
    };
    match kind {
        BlockKind::List | BlockKind::BlockQuote => {
            let mut syntax = Syntax::parse(source, base);
            if let Some(&Opening::Number(number)) = opening {
                syntax.number_first_item(number);
            }
            let offsets = align(&plain, &syntax.aligned_source(source, base), base);
            let decorated = decorate::decorate(&syntax, source, base, text, offsets);
            let nested = nested::find(source, base);
            // An item the next item of its list follows keeps the row its last code leaves,
            // as the whole list draws it.
            let continues = doc.blocks.get(index + 1).is_some_and(|b| b.joined);
            if nested.is_empty() {
                block(decorated, nested)
            } else {
                block(nested::restyle(decorated, &nested, continues), nested)
            }
        }
        BlockKind::DefinitionList => {
            let offsets = align(&plain, source, base);
            let definitions = definitions::ranges(source, base);
            let (lines, offsets, hangs) = definitions::indent(text.lines, offsets, &definitions);
            block(Decorated { text: Text::from(lines).style(text.style), offsets, hangs }, Vec::new())
        }
        _ => {
            let offsets = align(&plain, source, base);
            let mut rendered = block(Decorated { text, offsets, hangs: Vec::new() }, Vec::new());
            if kind == BlockKind::Table {
                rendered.table = Some(Table::of(&rendered.text.lines, &rendered.offsets));
            }
            rendered
        }
    }
}

/// The rows of a table cut into them, `parts` of `doc`, laid out `width` columns wide. The
/// whole table is rendered once and its lines dealt out in order, a border going with the
/// row above it and the top border with the header, so the parts draw the whole table.
fn table_rows(doc: &Document, parts: Range<usize>, width: usize) -> Vec<RenderedBlock> {
    let parts = doc.blocks.get(parts).unwrap_or_default();
    let (Some(first), Some(last)) = (parts.first(), parts.last()) else { return Vec::new() };
    let base = first.range.start;
    let source = doc.source.get(base..last.range.end).unwrap_or_default();
    let text = markdown(source, BlockKind::Table, None);
    let plain: Vec<String> = text.lines.iter().map(ToString::to_string).collect();
    let offsets = align(&plain, source, base);
    let table = Table::of(&text.lines, &offsets);
    let mut dealt: Vec<(Vec<Line<'static>>, Vec<LineOffsets>)> =
        parts.iter().map(|_| Default::default()).collect();
    let mut part = None;
    for ((line, offsets), plain) in text.lines.into_iter().zip(offsets).zip(&plain) {
        if !plain.starts_with(['┌', '├', '└']) {
            part = Some(part.map_or(0, |part: usize| (part + 1).min(parts.len() - 1)));
        }
        if let Some((lines, map)) = dealt.get_mut(part.unwrap_or(0)) {
            lines.push(line);
            map.push(offsets);
        }
    }
    let style = text.style;
    parts
        .iter()
        .zip(dealt)
        .enumerate()
        .map(|(index, (block, (lines, offsets)))| {
            let mut table = table.clone();
            table.continues = index + 1 < parts.len();
            let mut rendered = RenderedBlock {
                text: Text::from(lines).style(style),
                offsets,
                kind: BlockKind::Table,
                hangs: Vec::new(),
                heading: None,
                joined: block.joined,
                top: block.top,
                code: None,
                nested: Vec::new(),
                table: Some(table),
                rows: Vec::new(),
                first_row: 0,
            };
            rendered.wrap(width);
            rendered
        })
        .collect()
}

/// The line of an empty list item that, a blank line before `item`, makes `item` the second
/// item of a loose list of its kind: the same bullet, or the number before the item's own
/// with the same `.` or `)`, so the item keeps its number. `None` for an item numbered 0.
fn loose_sibling(item: &str) -> Option<String> {
    let line = item.lines().next()?.trim_start_matches(' ');
    let bullet = line.chars().next().filter(|c| matches!(c, '-' | '*' | '+'));
    if let Some(bullet) = bullet {
        return Some(bullet.to_string());
    }
    let digits = line.chars().take_while(char::is_ascii_digit).count();
    let delimiter = line.get(digits..)?.chars().next().filter(|c| matches!(c, '.' | ')'))?;
    let number: u64 = line.get(..digits)?.parse().ok()?;
    Some(format!("{}{delimiter}", number.checked_sub(1)?))
}

/// Languages a reader meets first: the info string and code of the first few code blocks
/// that name different ones.
fn first_code(doc: &Document) -> Vec<(String, String)> {
    const LANGUAGES: usize = 4;
    let mut samples: Vec<(String, String)> = Vec::new();
    for (index, block) in doc.blocks.iter().enumerate() {
        let Opening::Code(info) = &block.opening else { continue };
        if info.is_empty() || samples.iter().any(|(seen, _)| **seen == **info) {
            continue;
        }
        let code = doc.block_text(index).split_once('\n').map_or("", |(_, code)| code);
        let end = code.match_indices('\n').nth(crate::highlight::WARM_LINES).map_or(code.len(), |(at, _)| at);
        samples.push((info.to_string(), code.get(..end).unwrap_or(code).to_owned()));
        if samples.len() == LANGUAGES {
            break;
        }
    }
    samples
}

pub(crate) fn own(text: Text<'_>) -> Text<'static> {
    let lines = text
        .lines
        .into_iter()
        .map(|line| {
            let spans =
                line.spans.into_iter().map(|s| ratatui::text::Span::styled(s.content.into_owned(), s.style));
            Line::from(spans.collect::<Vec<_>>()).style(line.style)
        })
        .collect::<Vec<_>>();
    Text::from(lines).style(text.style)
}

impl DocLayout {
    /// Render and lay out every block for `width` before returning.
    pub(crate) fn build(doc: &Document, width: usize) -> Self {
        crate::highlight::warm_up(first_code(doc));
        let width = width.max(1);
        let mut layout =
            Self { width, blocks: lay_out(doc, 0..doc.blocks.len(), width), total_rows: 0, rest: None };
        layout.place();
        layout
    }

    /// Lay out the first screens of `doc` now and the rest on a background thread, so a
    /// long document shows without waiting for its last block. Rows already laid out never
    /// move when the rest arrives: each block's rows depend on that block alone, or on the
    /// table it is a row of, which is laid out in one go.
    pub(crate) fn start(doc: &Document, width: usize) -> Self {
        crate::highlight::warm_up(first_code(doc));
        let width = width.max(1);
        let mut blocks = Vec::new();
        let mut rows = 0;
        for unit in units(doc, 0..doc.blocks.len()) {
            if rows >= FIRST_ROWS {
                break;
            }
            for block in lay_out_unit(doc, unit, width) {
                rows += block.rows.len() + BLOCK_GAP;
                blocks.push(block);
            }
        }
        let rest = (blocks.len() < doc.blocks.len()).then(|| Rest::spawn(doc, blocks.len(), width));
        let mut layout = Self { width, blocks, total_rows: 0, rest };
        layout.place();
        layout
    }

    /// Whether every block is laid out.
    pub(crate) fn is_complete(&self) -> bool {
        self.rest.is_none()
    }

    /// Wait for the blocks still being laid out and add them. Anything that needs the whole
    /// document (its last row, a block far down, the text under a range) calls this first.
    pub(crate) fn finish(&mut self) {
        let Some(rest) = self.rest.take() else { return };
        let (mut blocks, width) = rest.join();
        if width != self.width {
            each_in_parallel(&mut blocks, |block| block.wrap(self.width));
        }
        self.blocks.append(&mut blocks);
        self.place();
    }

    /// Add the background blocks if they are ready, without waiting. True when they were added.
    pub(crate) fn poll(&mut self) -> bool {
        let ready = self.rest.as_ref().is_some_and(Rest::is_finished);
        if ready {
            self.finish();
        }
        ready
    }

    /// [`DocLayout::finish`] when document row `end` lies past the rows laid out so far.
    pub(crate) fn finish_through(&mut self, end: usize) {
        if end > self.total_rows {
            self.finish();
        }
    }

    /// Re-wrap for a new width without re-rendering markdown. Blocks still in the
    /// background are re-wrapped when they arrive.
    pub(crate) fn reflow(&mut self, width: usize) {
        let width = width.max(1);
        self.width = width;
        each_in_parallel(&mut self.blocks, |block| block.wrap(width));
        self.place();
    }

    /// Give each block its first row: one gap row apart unless joined to the one before, and
    /// more above a section heading.
    fn place(&mut self) {
        let mut row = 0usize;
        for (index, block) in self.blocks.iter_mut().enumerate() {
            if index > 0 && !block.joined {
                row += BLOCK_GAP;
            }
            if index > 0 && block.heading.is_some_and(|level| level <= 2) {
                row += SECTION_GAP;
            }
            block.first_row = row;
            row += block.rows.len();
        }
        self.total_rows = row;
    }

    /// Which block owns a document row (gap rows belong to nobody).
    pub(crate) fn block_at_row(&self, row: usize) -> Option<usize> {
        let idx = self.blocks.partition_point(|b| b.first_row <= row);
        let i = idx.checked_sub(1)?;
        let block = self.blocks.get(i)?;
        (row < block.first_row + block.rows.len()).then_some(i)
    }

    /// The row at document coordinate `row`, if it exists (None for gap rows).
    pub(crate) fn row(&self, row: usize) -> Option<&Row> {
        let block = self.blocks.get(self.block_at_row(row)?)?;
        block.rows.get(row - block.first_row)
    }

    /// The row at document coordinate `row` as it is drawn: code in its language's colours.
    /// Colouring is worked out here, for the rows asked for, and kept.
    pub(crate) fn drawn_line(&self, row: usize) -> Option<Cow<'_, Line<'static>>> {
        let block = self.blocks.get(self.block_at_row(row)?)?;
        let index = row - block.first_row;
        let laid_out = block.rows.get(index)?;
        let painted = match &block.code {
            Some(code) => code.paint(&block.text.lines, &block.offsets, index, laid_out),
            None if !block.nested.is_empty() => nested::paint(&block.nested, laid_out),
            None => None,
        };
        Some(painted.map_or(Cow::Borrowed(&laid_out.line), Cow::Owned))
    }

    /// Every shown line as the renderer produced it, before wrapping, with each char's
    /// source byte. Width-independent, so whatever is built from it survives a resize. A
    /// thematic break is drawn, not rendered, so it has no line here.
    pub(crate) fn rendered_lines(&self) -> impl Iterator<Item = (&Line<'static>, &LineOffsets)> {
        self.blocks
            .iter()
            .filter(|block| block.kind != BlockKind::Rule)
            .flat_map(|block| block.text.lines.iter().zip(&block.offsets))
    }

    /// The first cell, in reading order, that shows a source byte inside `range`.
    pub(crate) fn first_cell_in_range(&self, block: usize, range: &Range<usize>) -> Option<(usize, usize)> {
        let b = self.blocks.get(block)?;
        b.rows.iter().enumerate().find_map(|(i, row)| {
            let col = row.cells.iter().position(|c| c.is_some_and(|o| range.contains(&o)))?;
            Some((b.first_row + i, col))
        })
    }

    /// First document row on which any cell falls inside `range`.
    pub(crate) fn first_row_in_range(&self, block: usize, range: &Range<usize>) -> Option<usize> {
        let b = self.blocks.get(block)?;
        b.rows
            .iter()
            .position(|r| r.cells.iter().any(|c| c.is_some_and(|o| range.contains(&o))))
            .map(|i| b.first_row + i)
    }

    /// The rendered text under a source range, in the web client's form: rendered
    /// characters whose source offset falls in `range`, top-level blocks joined with no
    /// separator.
    ///
    /// The renderer maps a soft line break to nothing, so a break inside a wrapping block
    /// is recovered from the source: when consecutive rendered characters skip over
    /// whitespace in the source, one space is emitted (the DOM renders a soft break as a
    /// space). Code and tables keep their newlines. Items of one top-level block are read
    /// as one, so the text is the same however [`Blocks`](crate::doc::Blocks) cuts them.
    pub(crate) fn rendered_in_range(&self, source: &str, range: &Range<usize>) -> String {
        let mut out = String::new();
        let mut last_offset: Option<usize> = None;
        let mut top = None;
        for block in &self.blocks {
            let break_char = if block.kind.preserves_columns() { '\n' } else { ' ' };
            if top != Some(block.top) {
                last_offset = None;
                top = Some(block.top);
            }
            let chars = block.text.lines.iter().zip(&block.offsets).flat_map(|(line, offsets)| {
                line.spans.iter().flat_map(|s| s.content.chars()).zip(offsets.iter())
            });
            for (ch, offset) in chars {
                let Some(offset) = offset.filter(|o| range.contains(o)) else { continue };
                if let Some(prev) = last_offset
                    && let Some(skipped) = source.get(prev..offset)
                    && skipped.chars().any(char::is_whitespace)
                    && !out.ends_with(char::is_whitespace)
                {
                    out.push(break_char);
                }
                out.push(ch);
                last_offset = Some(offset + ch.len_utf8());
            }
        }
        out
    }
}