rmut-front 2.14.0

the part of an rmut front end that is not a toolkit: keys, keymaps, layout and formatting shared by the terminal and window front ends
Documentation
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The pager's rows and the index's scroll math: what a message looks
//! like as lines of text at a width, and where the cursor lands. No
//! toolkit; both front ends draw from this.

use rmut_core::message::MessageView;

pub fn humanize_size(bytes: u64) -> String {
    match bytes {
        0..=999 => format!("{bytes}"),
        1000..=10_239 => format!("{:.1}K", bytes as f64 / 1024.0),
        10_240..=1_048_575 => format!("{}K", bytes / 1024),
        1_048_576..=10_485_759 => format!("{:.1}M", bytes as f64 / 1_048_576.0),
        _ => format!("{}M", bytes / 1_048_576),
    }
}

// ---- pager ----

/// How one pager display row gets colored.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum RowKind {
    Header,
    /// `[-- ... --]` notices (PGP verdicts, missing parts).
    Marker,
    /// Quoted body text, 1-based nesting depth.
    Quoted(usize),
    Text,
}

pub struct Row {
    pub text: String,
    pub kind: RowKind,
    /// The URLs on this row, in chars of `text`. A URL the wrap broke
    /// across rows is a link on each of them, all to the whole URL.
    pub links: Vec<RowLink>,
}

/// Where a URL sits on a pager row: chars `start..end` of its text,
/// and the whole URL they belong to.
#[derive(Clone, Debug, PartialEq)]
pub struct RowLink {
    pub start: usize,
    pub end: usize,
    pub url: String,
}

/// The URLs of a line as char ranges of it.
fn url_ranges(line: &str) -> Vec<(usize, usize, String)> {
    let mut at = 0;
    let mut out = Vec::new();
    for (text, url) in link_spans(line) {
        let n = text.chars().count();
        if let Some(url) = url {
            out.push((at, at + n, url));
        }
        at += n;
    }
    out
}

/// The links of the row holding chars `from..to` of a line whose URLs
/// are `urls`, shifted right by `offset` (a wrap marker).
fn row_links(
    urls: &[(usize, usize, String)],
    from: usize,
    to: usize,
    offset: usize,
) -> Vec<RowLink> {
    urls.iter()
        .filter(|(start, end, _)| *start < to && *end > from)
        .map(|(start, end, url)| RowLink {
            start: (*start).max(from) - from + offset,
            end: (*end).min(to) - from + offset,
            url: url.clone(),
        })
        .collect()
}

/// Every URL of a message, headers first, each once, in the order
/// they appear: what the URL list offers.
pub fn view_urls(view: &MessageView) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let headers = view
        .brief
        .iter()
        .map(|(name, value)| format!("{name}: {value}"));
    for line in headers.chain(view.body.lines().map(String::from)) {
        for (_, _, url) in url_ranges(&line) {
            if !out.contains(&url) {
                out.push(url);
            }
        }
    }
    out
}

/// Quote depth of a body line under $quote_regexp: the number of
/// quote characters in the prefix match, 0 for unquoted text.
pub fn quote_depth(line: &str, re: &regex_lite::Regex) -> usize {
    match re.find(line) {
        Some(m) if m.start() == 0 => m
            .as_str()
            .chars()
            .filter(|c| !c.is_whitespace())
            .count()
            .max(1),
        _ => 0,
    }
}

/// The pager display: header block, separator, wrapped body (with
/// mutt's `+` continuation markers), each row classified for
/// coloring. The scroll math, the body search, and the drawing all
/// share this; T (hide_quoted) drops quoted rows here, so every
/// consumer agrees on what a line number means.
/// What the config says about drawing a message: which lines count as
/// quoted, whether a wrapped line is marked, and whether it breaks at
/// a word.
pub struct PagerStyle<'a> {
    pub quote_re: &'a regex_lite::Regex,
    /// mutt's $markers.
    pub markers: bool,
    /// mutt's $smart_wrap.
    pub smart_wrap: bool,
}

impl<'a> PagerStyle<'a> {
    pub fn of(config: &'a rmut_core::config::Config, quote_re: &'a regex_lite::Regex) -> Self {
        PagerStyle {
            quote_re,
            markers: config.pager.markers.unwrap_or(true),
            smart_wrap: config.pager.smart_wrap.unwrap_or(true),
        }
    }
}

/// The rows of the message on show, built once per layout. The pager
/// draws every frame, its status line counts the rows, and each
/// motion key needs the count too: rebuilt from the text each time, a
/// big patch or log (tens of thousands of lines) cost tens of
/// milliseconds a keystroke. A front end keeps one beside the view it
/// shows and drops it with that view; anything that changes the rows
/// (the width, a toggle, a `:set`) is in the key.
#[derive(Default)]
pub struct RowCache {
    built: std::cell::RefCell<Option<(RowKey, std::rc::Rc<Vec<Row>>)>>,
}

#[derive(PartialEq)]
struct RowKey {
    width: usize,
    full_headers: bool,
    hide_quoted: bool,
    markers: bool,
    smart_wrap: bool,
    quote_re: String,
}

impl RowCache {
    /// [`pager_rows`], from the cache when nothing it depends on moved.
    pub fn rows(
        &self,
        view: &MessageView,
        width: usize,
        full_headers: bool,
        style: &PagerStyle,
        hide_quoted: bool,
    ) -> std::rc::Rc<Vec<Row>> {
        let key = RowKey {
            width,
            full_headers,
            hide_quoted,
            markers: style.markers,
            smart_wrap: style.smart_wrap,
            quote_re: style.quote_re.as_str().to_string(),
        };
        let mut built = self.built.borrow_mut();
        if let Some((k, rows)) = built.as_ref()
            && *k == key
        {
            return rows.clone();
        }
        let rows = std::rc::Rc::new(pager_rows(view, width, full_headers, style, hide_quoted));
        *built = Some((key, rows.clone()));
        rows
    }
}

pub fn pager_rows(
    view: &MessageView,
    width: usize,
    full_headers: bool,
    style: &PagerStyle,
    hide_quoted: bool,
) -> Vec<Row> {
    let quote_re = style.quote_re;
    let headers = if full_headers { &view.all } else { &view.brief };
    let mut rows: Vec<Row> = headers
        .iter()
        .map(|(name, value)| {
            let text = format!("{name}: {value}");
            let links = row_links(&url_ranges(&text), 0, usize::MAX, 0);
            Row {
                text,
                kind: RowKind::Header,
                links,
            }
        })
        .collect();
    rows.push(Row {
        text: String::new(),
        kind: RowKind::Text,
        links: Vec::new(),
    });
    for line in view.body.lines() {
        // Marker lines like the PGP verdict get the header treatment.
        let marker = line.starts_with("[-- ") && line.ends_with(" --]");
        let depth = if marker {
            0
        } else {
            quote_depth(line, quote_re)
        };
        if hide_quoted && depth > 0 {
            continue;
        }
        let kind = if marker {
            RowKind::Marker
        } else if depth > 0 {
            RowKind::Quoted(depth)
        } else {
            RowKind::Text
        };
        let expanded = line.replace('\t', "    ");
        let chars: Vec<char> = expanded.chars().collect();
        let urls = url_ranges(&expanded);
        for (i, (from, to)) in wrap_ranges(&chars, width.saturating_sub(1), style.smart_wrap)
            .into_iter()
            .enumerate()
        {
            let wrapped: String = chars[from..to].iter().collect();
            // mutt's $markers: a wrapped line says it is one.
            let marker = i > 0 && style.markers;
            let text = match marker {
                true => format!("+{wrapped}"),
                false => wrapped,
            };
            let links = row_links(&urls, from, to, usize::from(marker));
            rows.push(Row { text, kind, links });
        }
    }
    rows
}

/// The pager's display as plain text: what the body search runs over.
pub fn pager_text_lines(
    view: &MessageView,
    width: usize,
    full_headers: bool,
    style: &PagerStyle,
    hide_quoted: bool,
) -> Vec<String> {
    pager_rows(view, width, full_headers, style, hide_quoted)
        .into_iter()
        .map(|row| row.text)
        .collect()
}

/// Total pager lines at the given width.
pub fn pager_line_count(
    view: &MessageView,
    width: usize,
    full_headers: bool,
    style: &PagerStyle,
    hide_quoted: bool,
) -> usize {
    pager_rows(view, width, full_headers, style, hide_quoted).len()
}

/// Word-wrap one body line to `width` columns (hard break when a single
/// word is longer than the line). Tabs are expanded first.
/// The same, with mutt's $smart_wrap: without it a long line breaks
/// at the column rather than at the last space before it.
pub fn wrap_line_with(line: &str, width: usize, smart: bool) -> Vec<String> {
    let expanded = line.replace('\t', "    ");
    let chars: Vec<char> = expanded.chars().collect();
    wrap_ranges(&chars, width, smart)
        .into_iter()
        .map(|(from, to)| chars[from..to].iter().collect())
        .collect()
}

/// The wrap as char ranges of the (tab-expanded) line, one per row,
/// each at most `width` display columns: a CJK ideograph or an emoji
/// takes two, a combining mark none.
fn wrap_ranges(chars: &[char], width: usize, smart: bool) -> Vec<(usize, usize)> {
    use unicode_width::UnicodeWidthChar as _;
    let width = width.max(4);
    let cols = |c: char| c.width().unwrap_or(0);
    if chars.iter().map(|&c| cols(c)).sum::<usize>() <= width {
        return vec![(0, chars.len())];
    }
    let mut out = Vec::new();
    let mut start = 0;
    while start < chars.len() {
        // As many chars as fit, one at least.
        let mut window_end = start;
        let mut used = 0;
        while window_end < chars.len() && used + cols(chars[window_end]) <= width {
            used += cols(chars[window_end]);
            window_end += 1;
        }
        let window_end = window_end.max(start + 1);
        if window_end >= chars.len() {
            out.push((start, chars.len()));
            break;
        }
        let brk = match smart {
            true => (start + 1..window_end)
                .rev()
                .find(|&i| chars[i] == ' ')
                .unwrap_or(window_end),
            false => window_end,
        };
        out.push((start, brk));
        start = if chars.get(brk) == Some(&' ') {
            brk + 1
        } else {
            brk
        };
    }
    out
}

/// mutt's $menu_scroll, $menu_context and $menu_move_off, as the
/// index's recentering reads them.
#[derive(Clone, Copy)]
pub struct Menu {
    pub scroll: bool,
    pub context: usize,
    pub move_off: bool,
}

/// Where the index's first row goes so the cursor stays on screen:
/// mutt's menu_check_recenter, line for line. `top` is the row now at
/// the top, `sel` the cursor, `rows` the screen, `max` the entries.
/// With `scroll` the view moves just far enough (keeping `context`
/// lines beyond the cursor); without it a whole page turns. Unless
/// `move_off`, the last entry never scrolls up past the bottom.
pub fn recenter(top: usize, sel: usize, rows: usize, max: usize, menu: Menu) -> usize {
    let (mut top, sel, rows, max) = (top as i64, sel as i64, rows as i64, max as i64);
    let c = (menu.context as i64).min(rows / 2);
    if !menu.move_off && max <= rows {
        top = 0;
    } else if menu.scroll || rows <= 0 || c < menu.context as i64 {
        if sel < top + c {
            top = sel - c;
        } else if sel >= top + rows - c {
            top = sel - rows + c + 1;
        }
    } else if sel < top + c {
        top -= (rows - c) * ((top + rows - 1 - sel) / (rows - c)) - c;
    } else if sel >= top + rows - c {
        top += (rows - c) * ((sel - top) / (rows - c)) - c;
    }
    if !menu.move_off {
        top = top.min(max - rows);
    }
    top.max(0) as usize
}

pub use rmut_core::links::link_spans;

/// The pager's text search: the next line matching `m` from `from`,
/// wrapping around, and whether it wrapped. Both front ends step
/// their pagers with this.
pub fn search_lines<S: AsRef<str>>(
    lines: &[S],
    m: &rmut_core::pattern::Matcher,
    from: usize,
    forward: bool,
) -> Option<(usize, bool)> {
    rmut_session::wrap_order(lines.len(), from, forward)
        .into_iter()
        .find(|&(idx, _)| m.is_match(lines[idx].as_ref()))
}

#[cfg(test)]
mod tests {
    use super::{
        Menu, PagerStyle, RowKind, humanize_size, pager_rows, quote_depth, recenter, wrap_line_with,
    };
    use rmut_core::message::MessageView;
    use rmut_session::default_quote_re;

    #[test]
    fn quote_depth_counts_prefix_marks() {
        let re = default_quote_re();
        assert_eq!(quote_depth("plain text", &re), 0);
        assert_eq!(quote_depth("> quoted", &re), 1);
        assert_eq!(quote_depth("> > deeper", &re), 2);
        assert_eq!(quote_depth(">>tight", &re), 2);
        assert_eq!(quote_depth("  | indented pipe", &re), 1);
        // A > later in the line is not a quote.
        assert_eq!(quote_depth("2 > 1", &re), 0);
    }

    #[test]
    fn wide_characters_wrap_by_the_columns_they_take() {
        use unicode_width::UnicodeWidthStr as _;
        // Ten ideographs are twenty columns: two rows at twelve.
        let rows = wrap_line_with("日本語のテキストです", 12, false);
        assert_eq!(rows, ["日本語のテキ", "ストです"]);
        assert!(rows.iter().all(|r| r.width() <= 12));
        // Latin text with accents is one column a char, as before.
        assert_eq!(
            wrap_line_with("Schůzka zítra ráno", 12, true),
            ["Schůzka", "zítra ráno"]
        );
        // A combining mark adds no width.
        assert_eq!(
            wrap_line_with("e\u{301}e\u{301}e\u{301}e\u{301}", 4, false).len(),
            1
        );
    }

    #[test]
    fn a_wrapped_url_links_every_row_to_the_whole_url() {
        use super::{Row, view_urls};
        let url = "https://example.com/a/very/long/path/that/wraps";
        let view = MessageView {
            brief: vec![("List-Help".into(), "<https://lists.example/help>".into())],
            all: vec![],
            body: format!("see {url} now\nsee {url} again"),
        };
        let re = default_quote_re();
        let style = PagerStyle {
            quote_re: &re,
            markers: true,
            smart_wrap: false,
        };
        let rows = pager_rows(&view, 21, false, &style, false);
        let header = &rows[0].links;
        assert_eq!(header.len(), 1);
        assert_eq!(
            &rows[0].text[header[0].start..header[0].end],
            "https://lists.example/help"
        );
        // Every row the URL touches links to all of it; the text the
        // link covers is what is on the row, after the "+" marker.
        let body: Vec<&Row> = rows[2..].iter().filter(|r| !r.links.is_empty()).collect();
        assert!(body.len() >= 4, "{}", body.len());
        assert!(body.iter().all(|r| r.links.iter().all(|l| l.url == url)));
        // The first line's rows run up to the one holding " now".
        let end = rows.iter().position(|r| r.text.contains("now")).unwrap();
        let covered: String = rows[2..=end]
            .iter()
            .flat_map(|r| {
                r.links.iter().map(|l| {
                    r.text
                        .chars()
                        .skip(l.start)
                        .take(l.end - l.start)
                        .collect::<String>()
                })
            })
            .collect();
        assert_eq!(covered, url);
        assert_eq!(
            rows[3].links[0].start, 1,
            "after the marker: {:?}",
            rows[3].text
        );
        assert_eq!(
            view_urls(&view),
            vec!["https://lists.example/help".to_string(), url.to_string()]
        );
    }

    #[test]
    fn rows_classify_and_hide_quoted() {
        let view = MessageView {
            brief: vec![("From".into(), "jane@example.com".into())],
            all: vec![("From".into(), "jane@example.com".into())],
            body: "top\n> one\n> > two\n[-- marker --]\ntail".into(),
        };
        let re = default_quote_re();
        let style = PagerStyle {
            quote_re: &re,
            markers: true,
            smart_wrap: true,
        };
        let rows = pager_rows(&view, 80, false, &style, false);
        let kinds: Vec<RowKind> = rows.iter().map(|r| r.kind).collect();
        assert_eq!(
            kinds,
            vec![
                RowKind::Header,
                RowKind::Text, // separator
                RowKind::Text,
                RowKind::Quoted(1),
                RowKind::Quoted(2),
                RowKind::Marker,
                RowKind::Text,
            ]
        );
        // T drops the quoted rows for every consumer at once.
        let hidden = pager_rows(&view, 80, false, &style, true);
        assert_eq!(hidden.len(), rows.len() - 2);
        assert!(hidden.iter().all(|r| !matches!(r.kind, RowKind::Quoted(_))));
    }

    #[test]
    fn wrap_short_line_untouched() {
        assert_eq!(wrap_line_with("hello", 10, true), vec!["hello"]);
        assert_eq!(wrap_line_with("", 10, true), vec![""]);
    }

    #[test]
    fn wrap_breaks_at_word_boundary() {
        assert_eq!(
            wrap_line_with("the quick brown fox", 10, true),
            vec!["the quick", "brown fox"]
        );
    }

    #[test]
    fn without_smart_wrap_a_line_breaks_at_the_column() {
        // mutt's $smart_wrap off: the break lands on the width, not
        // on the last space before it.
        assert_eq!(
            wrap_line_with("alpha beta gamma", 10, false),
            vec!["alpha beta", "gamma"]
        );
        assert_eq!(
            wrap_line_with("alpha beta gamma", 10, true),
            vec!["alpha", "beta gamma"]
        );
    }

    #[test]
    fn wrap_hard_breaks_long_words() {
        assert_eq!(
            wrap_line_with("abcdefghij", 4, true),
            vec!["abcd", "efgh", "ij"]
        );
    }

    #[test]
    fn humanize_size_ranges() {
        assert_eq!(humanize_size(0), "0");
        assert_eq!(humanize_size(999), "999");
        assert_eq!(humanize_size(2048), "2.0K");
        assert_eq!(humanize_size(204800), "200K");
        assert_eq!(humanize_size(2 * 1024 * 1024), "2.0M");
    }

    #[test]
    fn recenter_scrolls_a_line_or_turns_a_page() {
        let scroll = Menu {
            scroll: true,
            context: 0,
            move_off: true,
        };
        let page = Menu {
            scroll: false,
            context: 0,
            move_off: true,
        };
        // Moving down off a 10-row screen: scrolling shows one more
        // line, paging turns the whole page (mutt's default).
        assert_eq!(recenter(0, 10, 10, 100, scroll), 1);
        assert_eq!(recenter(0, 10, 10, 100, page), 10);
        // Moving up off the top is symmetrical.
        assert_eq!(recenter(20, 19, 10, 100, scroll), 19);
        assert_eq!(recenter(20, 19, 10, 100, page), 10);
        // On screen already: nothing moves.
        assert_eq!(recenter(20, 25, 10, 100, scroll), 20);
        assert_eq!(recenter(20, 25, 10, 100, page), 20);
    }

    #[test]
    fn recenter_keeps_context_lines() {
        let m = Menu {
            scroll: true,
            context: 3,
            move_off: true,
        };
        // The cursor stays three rows clear of the bottom edge.
        assert_eq!(recenter(0, 7, 10, 100, m), 1);
        // And of the top edge.
        assert_eq!(recenter(20, 22, 10, 100, m), 19);
        // Context is capped at half the screen (a 4-row screen: 2).
        let big = Menu {
            scroll: true,
            context: 9,
            move_off: true,
        };
        assert_eq!(recenter(0, 2, 4, 100, big), 1);
    }

    #[test]
    fn recenter_move_off_pins_the_bottom() {
        let stuck = Menu {
            scroll: true,
            context: 0,
            move_off: false,
        };
        // Fewer entries than rows: the top is always the top.
        assert_eq!(recenter(3, 4, 10, 5, stuck), 0);
        // The last page stays full: top never passes max - rows.
        assert_eq!(recenter(95, 99, 10, 100, stuck), 90);
        // With move_off (the default) it may.
        let free = Menu {
            scroll: true,
            context: 0,
            move_off: true,
        };
        assert_eq!(recenter(95, 99, 10, 100, free), 95);
    }

    #[test]
    fn search_lines_steps_and_wraps() {
        use super::search_lines;
        use rmut_core::pattern::Matcher;
        let lines: Vec<String> = ["alpha", "the needle", "beta", "a Needle too"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let m = Matcher::new("needle");
        // Forward from the top: the next hit, no wrap; case-insensitive.
        assert_eq!(search_lines(&lines, &m, 0, true), Some((1, false)));
        assert_eq!(search_lines(&lines, &m, 1, true), Some((3, false)));
        // Past the last hit it wraps to the first.
        assert_eq!(search_lines(&lines, &m, 3, true), Some((1, true)));
        // Backwards, with and without the wrap.
        assert_eq!(search_lines(&lines, &m, 3, false), Some((1, false)));
        assert_eq!(search_lines(&lines, &m, 1, false), Some((3, true)));
        // No match, and the empty pager.
        assert_eq!(search_lines(&lines, &Matcher::new("zzz"), 0, true), None);
        assert_eq!(search_lines::<&str>(&[], &m, 0, true), None);
        // A regex argument works like the patterns do.
        let re = Matcher::new("^bet.");
        assert_eq!(search_lines(&lines, &re, 0, true), Some((2, false)));
    }
}