tread 0.4.3

A terminal reader for markdown, CSV, JSON and source code. Zero dependencies.
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
//! Painting: turn pager state into one buffered [`Frame`].
//!
//! Everything here is additive over the laid-out spans — search highlights, the
//! cursor row tint, fold summaries and the horizontal-cut indicators are
//! applied as cell edits so the layout engine stays unaware of them.
#![deny(unsafe_code)]

use super::{keys, search, Mode, Pager};
use crate::url::is_external;
use crate::render::{slice_spans, str_width, truncate_width, visible, Line, Span};
use crate::term::{Frame, Style};
use crate::theme;

mod cells;
use cells::Cells;

/// Left/right "content continues" markers for horizontally scrolled rows.
const CUT_LEFT: char = '\u{2039}';
const CUT_RIGHT: char = '\u{203a}';

/// Hint shown by the list overlays that jump somewhere on Enter.
const JUMP: &str = "j/k move, Enter jump, Esc close";
/// The detail overlay goes nowhere; it is a read-only expansion of one row.
const READ: &str = "j/k scroll, Esc close";

pub fn paint(p: &mut Pager, frame: &mut Frame) {
    frame.reset();
    let body = p.body_rows();
    match p.mode {
        Mode::Outline => overlay(p, frame, "Outline", JUMP, &outline_rows(p), p.outline_sel),
        Mode::Help => overlay(p, frame, "Keys", JUMP, &help_rows(), p.help_top),
        Mode::Index => overlay(p, frame, &index_title(p), JUMP, &index_rows(p), p.index_row_pos()),
        Mode::Detail => detail(p, frame),
        _ => document(p, frame, body),
    }
    if p.rows > 0 {
        frame.move_to(p.rows as u16, 1);
        status(p, frame);
    }
}

/// Paint the window the viewport is showing — and *only* that window: the
/// source is asked for `top..top + body` rows and nothing else, so a document
/// too large to hold renders one screen at a time (SPEC.md §The `Source` seam).
fn document(p: &mut Pager, frame: &mut Frame, body: usize) {
    let (top, pin) = (p.top, p.pinned());
    let head = p.src.lines(0..pin);
    let window = p.src.lines(top..top.saturating_add(body - pin));
    for r in 0..body {
        frame.move_to(r as u16 + 1, 1);
        // Rows 0..pin are frozen at the top of the viewport — a CSV's header
        // (SPEC.md §CSV). `pin` is 0 for a format that pins nothing, which
        // leaves this loop exactly what it was.
        let (row, line) = match r < pin {
            true => (r, head.get(r)),
            false => (top + r - pin, window.get(r - pin)),
        };
        if let Some(line) = line {
            let spans = compose(p, row, line);
            paint_spans(frame, &spans);
        }
        frame.reset_style();
        frame.clear_to_eol();
    }
}

/// The final spans of one row, fetched from the source. Used by the tests and
/// by anything outside the paint loop, which already holds the window.
#[cfg(test)]
pub(super) fn row_spans(p: &mut Pager, row: usize) -> Vec<Span> {
    match p.src.line(row) {
        Some(line) => compose(p, row, &line),
        None => Vec::new(),
    }
}

/// The final spans of one document row: folded-section summary, horizontal
/// window, search highlights, cursor tint and cut indicators.
fn compose(p: &Pager, row: usize, line: &Line) -> Vec<Span> {
    let width = p.cols.max(1);
    let scroll = super::scrollable(line, width);
    let off = if scroll { p.hoff } else { 0 };
    // Borrowed unless a fold summary rewrote the row: cloning the spans would
    // cost a copy of every cell of a 10k-column CSV row, on every frame.
    let summary = fold_summary(p, row, line, width, off);
    let base: &[Span] = summary.as_deref().unwrap_or(&line.spans);
    let full_width = base.iter().map(Span::width).sum::<usize>();
    let mut cells = Cells::from_spans(&slice_spans(base, off, width));
    focus_link(p, &mut cells, row, line, off);
    highlight(p, &mut cells, row, off);
    if p.cursor == row || selected(p, row) {
        cells.tint(theme::selection());
    }
    if scroll {
        if off > 0 {
            cells.set(0, CUT_LEFT, theme::muted());
        }
        if full_width > off + width {
            cells.set(width.saturating_sub(1), CUT_RIGHT, theme::muted());
        }
    }
    cells.into_spans()
}

/// True when the row is inside the visual selection (`v`).
fn selected(p: &Pager, row: usize) -> bool {
    let sel = match p.select {
        Some(s) => s,
        None => return false,
    };
    let (lo, hi) = sel.range();
    row >= lo && row <= hi.min(p.src.len().saturating_sub(1))
}

/// A folded section shows `\u{25b8} Title  (N lines)`.
fn fold_summary(
    p: &Pager,
    row: usize,
    line: &Line,
    width: usize,
    off: usize,
) -> Option<Vec<Span>> {
    let hidden = p.src.hidden_at(row)?;
    let mut spans = line.spans.clone();
    if let Some(first) = spans.first_mut() {
        if first.text.starts_with(theme::MARKER_OPEN) {
            first.text = format!("{} ", theme::MARKER_CLOSED);
        }
    }
    // A row that summarises its own contents says the count better than this
    // can; appending to it would be redundant.
    if line.heading.as_ref().is_some_and(|h| h.summarised) {
        return Some(spans);
    }
    // A source may describe what it hides better than a line count can.
    let note = match p.src.fold_note(row) {
        Some(note) => format!("  \u{b7} {note}"),
        None => {
            let unit = if hidden == 1 { "line" } else { "lines" };
            format!("  ({hidden} {unit})")
        }
    };
    Some(with_count(spans, note, width, off))
}

/// The row plus what it hides, with the text cut short when the two together
/// do not fit.
///
/// The count is the reason the row is folded, so it is the half that must
/// survive: a headline that filled the width used to push its `(49 lines)`
/// off the right edge, where only a sideways scroll would find it. The text
/// is cut to leave room and marked with [`CUT_RIGHT`], and because the *line*
/// is still the full one, scrolling right reads the rest of it as before —
/// this trims what is painted at rest, never what the row holds.
pub(super) fn with_count(spans: Vec<Span>, note: String, width: usize, off: usize) -> Vec<Span> {
    let text: usize = spans.iter().map(Span::width).sum();
    let note_width = crate::render::str_width(&note);
    // Scrolled sideways the reader is reading the text itself, and a cut that
    // moved with the window would fight them for the columns.
    if off > 0 || text + note_width <= width {
        let mut out = spans;
        out.push(Span::new(note, theme::muted()));
        return out;
    }
    // One column for the cut mark. A width with no room for both keeps the
    // count: a row that says only `(49 lines)` is still true.
    let keep = width.saturating_sub(note_width + 1);
    let mut out = crate::render::slice_spans(&spans, 0, keep);
    if keep > 0 {
        out.push(Span::new(CUT_RIGHT.to_string(), theme::muted()));
    }
    out.push(Span::new(note, theme::muted()));
    out
}

/// The focused link is drawn reversed, so it reads differently from the other
/// (underlined) links sharing the row — in *its own* link colour, so a focused
/// external link still says it leaves the reader (SPEC.md §Navigation: the
/// distinction applies "wherever links are painted, including the focused-link
/// style").
fn link_focus_style(url: &str) -> Style {
    Style::new()
        .fg(theme::link_fg(is_external(url)))
        .bold()
        .reverse()
}

/// Tint the focused link on this row, if it is here.
fn focus_link(p: &Pager, cells: &mut Cells, row: usize, line: &Line, off: usize) {
    let site = match p.focused_link() {
        Some(s) if p.src.row_of(s.anchor) == Some(row) => s,
        _ => return,
    };
    let width = link_width(line, &site.url, site.col);
    if width == 0 {
        return;
    }
    let start = site.col.saturating_sub(off);
    cells.restyle(start, start + width, link_focus_style(&site.url));
}

/// Display width of the run of spans carrying `url`, starting at column `col`.
fn link_width(line: &Line, url: &str, col: usize) -> usize {
    let mut x = 0;
    let mut w = 0;
    for s in &line.spans {
        if x >= col && s.link.as_deref() == Some(url) {
            w += s.width();
        } else if w > 0 {
            break;
        }
        x += s.width();
    }
    w
}

fn highlight(p: &Pager, cells: &mut Cells, row: usize, off: usize) {
    if p.query.is_empty() {
        return;
    }
    for m in p.src.matches_on(row) {
        let style = match m.current {
            true => theme::search_current(),
            false => theme::search(),
        };
        cells.restyle(m.start.saturating_sub(off), m.end.saturating_sub(off), style);
    }
}

// ---------------------------------------------------------------------------
// Overlays
// ---------------------------------------------------------------------------

pub(super) fn outline_rows(p: &Pager) -> Vec<Vec<Span>> {
    p.src
        .outline()
        .iter()
        .map(|e| {
            let indent = "  ".repeat((e.level as usize).saturating_sub(1));
            let marker = match e.folded {
                true => theme::MARKER_CLOSED,
                false => theme::MARKER_OPEN,
            };
            // The text is tinted like the heading it names, so a `[BLOCKED]`
            // section stands out in the list as it does in the body.
            let style = theme::heading(e.level);
            let mut row = vec![Span::new(format!("{indent}{marker} "), style)];
            row.extend(crate::render::tagged(&e.text, style));
            row
        })
        .collect()
}

/// `Index 106 docs` plus the live `/` filter, when one is being typed.
fn index_title(p: &Pager) -> String {
    let total = p.nav.as_ref().map(|n| n.entries().len()).unwrap_or(0);
    let shown = p.index_rows().len();
    let mut t = match shown == total {
        true => format!("Index \u{b7} {total} docs"),
        false => format!("Index \u{b7} {shown}/{total} docs"),
    };
    match p.index_typing || !p.index_filter.is_empty() {
        true => {
            t.push_str(&format!("  /{}", p.index_filter));
            if p.index_typing {
                t.push('\u{2588}');
            }
        }
        false => t.push_str("  (/ filters)"),
    }
    t
}

/// One row per linked document: section, title, trailing description.
fn index_rows(p: &Pager) -> Vec<Vec<Span>> {
    let nav = match &p.nav {
        Some(n) => n,
        None => return Vec::new(),
    };
    p.index_rows()
        .into_iter()
        .filter_map(|i| nav.entries().get(i))
        .map(|e| {
            let here = nav.is_current(&e.path);
            let style = if here { theme::heading(3) } else { theme::text() };
            vec![Span::new(e.row(), style)]
        })
        .collect()
}

fn help_rows() -> Vec<Vec<Span>> {
    let w = keys::help_key_width();
    keys::help_rows()
        .into_iter()
        .map(|(k, d)| {
            let pad = w.saturating_sub(str_width(k));
            vec![Span::new(format!("{k}{}  {d}", " ".repeat(pad)), theme::text())]
        })
        .collect()
}

/// A full-body list overlay with a title row and a scroll window on `sel`.
/// One row, read the other way round: a field per line, label beside value.
///
/// Labels are padded to the widest, so values line up into a column the eye can
/// run down — the point of the view is that a record is easier to read as a
/// form than as a row that runs off the screen.
fn detail(p: &Pager, frame: &mut Frame) {
    let Some(d) = &p.detail else { return };
    let label_w = d
        .fields
        .iter()
        .map(|(k, _)| str_width(k))
        .max()
        .unwrap_or(0);
    let rows: Vec<Vec<Span>> = d
        .fields
        .iter()
        .map(|(k, v)| {
            let pad = " ".repeat(label_w.saturating_sub(str_width(k)));
            let style = match v.is_empty() {
                true => theme::muted(),
                false => theme::text(),
            };
            vec![Span::new(format!(" {k}{pad}   {}", visible(v)), style)]
        })
        .collect();
    overlay(p, frame, &d.title, READ, &rows, p.detail_sel);
}

fn overlay(
    p: &Pager,
    frame: &mut Frame,
    title: &str,
    hint: &str,
    rows: &[Vec<Span>],
    sel: usize,
) {
    let body = p.body_rows();
    let width = p.cols.max(1);
    if body == 0 {
        return;
    }
    frame.move_to(1, 1);
    let head = format!(" {title} \u{2014} {hint}");
    frame.span(theme::status(), truncate_width(&head, width));
    frame.reset_style();
    frame.clear_to_eol();
    let list_rows = body.saturating_sub(1);
    let top = window_top(sel, rows.len(), list_rows);
    for r in 0..list_rows {
        frame.move_to(r as u16 + 2, 1);
        if let Some(row) = rows.get(top + r) {
            let mut row = slice_spans(row, 0, width);
            if top + r == sel {
                row.iter_mut().for_each(|s| s.style = s.style.reverse());
            }
            paint_spans(frame, &row);
        }
        frame.reset_style();
        frame.clear_to_eol();
    }
}

/// Scroll a list so `sel` stays inside a window of `rows` entries.
pub(crate) fn window_top(sel: usize, len: usize, rows: usize) -> usize {
    if rows == 0 || len <= rows {
        return 0;
    }
    let half = rows / 2;
    sel.saturating_sub(half).min(len - rows)
}

// ---------------------------------------------------------------------------
// Status bar
// ---------------------------------------------------------------------------

/// `file.md  ·  42%  ·  line 120/840` plus transient messages and the search
/// prompt (SPEC.md §Status bar).
pub(crate) fn status_text(p: &Pager) -> String {
    if let Mode::Search(dir) = p.mode {
        let lead = if dir == search::Dir::Forward { '/' } else { '?' };
        return format!("{lead}{}", p.query);
    }
    if let Some(m) = &p.message {
        return m.clone();
    }
    // Visual mode owns the bar: `-- VISUAL --  N lines selected`.
    if let Some(s) = &p.select {
        return s.status();
    }
    let total = p.src.len();
    let cur = if total == 0 { 0 } else { p.cursor + 1 };
    let pct = if total <= 1 { 100 } else { p.cursor * 100 / (total - 1) };
    // A format that counts in something other than rendered lines says so
    // itself — a CSV names the row, the total (or `\u{2265}N` while its index
    // is still lazy) and the column under the cursor (SPEC.md §CSV).
    let pos = p
        .src
        .position_text(p.cursor)
        .unwrap_or_else(|| format!("{pct}%  \u{b7}  line {cur}/{total}"));
    let mut s = format!("{}  \u{b7}  {pos}", p.label);
    let depth = p.nav.as_ref().map(|n| n.depth()).unwrap_or(0);
    if depth > 0 {
        s.push_str(&format!("  \u{b7}  [{depth} back]"));
    }
    // The focused link's target: resolved path for internal, raw URL for
    // external (SPEC.md §Status bar).
    if let Some(target) = p.link_status() {
        s.push_str("  \u{b7}  ");
        s.push_str(&target);
    }
    s
}

fn status(p: &Pager, frame: &mut Frame) {
    let width = p.cols.max(1);
    let text = status_text(p);
    let shown = truncate_width(&text, width);
    let pad = width.saturating_sub(str_width(shown));
    frame.span(theme::status(), shown);
    frame.span(theme::status(), &" ".repeat(pad));
    frame.reset_style();
}

// ---------------------------------------------------------------------------
// Span writing
// ---------------------------------------------------------------------------

fn paint_spans(frame: &mut Frame, spans: &[Span]) {
    let mut open: Option<String> = None;
    for span in spans {
        if open.as_deref() != span.link.as_deref() {
            if open.is_some() {
                frame.link_close();
            }
            if let Some(url) = &span.link {
                frame.link_open(url);
            }
            open = span.link.clone();
        }
        frame.span(span.style, &span.text);
    }
    if open.is_some() {
        frame.link_close();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn window_keeps_the_selection_inside() {
        assert_eq!(window_top(0, 10, 5), 0);
        assert_eq!(window_top(2, 10, 5), 0);
        assert_eq!(window_top(5, 10, 5), 3);
        assert_eq!(window_top(9, 10, 5), 5);
        assert_eq!(window_top(3, 3, 5), 0);
        assert_eq!(window_top(3, 10, 0), 0);
    }

    #[test]
    fn help_overlay_lists_every_binding() {
        let rows = help_rows();
        assert_eq!(rows.len(), keys::BINDINGS.len());
        assert!(rows.iter().any(|r| r[0].text.contains("quit")));
        assert!(rows.iter().any(|r| r[0].text.contains("collapse every section")));
    }
}