Skip to main content

tui/keymap/
help.rs

1//! The Help text: the keys of the focused chain, then the `:` commands.
2
3use super::scopes::{SCOPES, chain};
4use super::shown::{Shown, chord_text, here};
5use crate::app::App;
6use crate::event::Intent;
7use crate::palette;
8
9const KEYS_WIDTH: usize = 16;
10const NAME_WIDTH: usize = 26;
11
12/// One row per action of a scope, its chords gathered.
13fn rows<'a>(entries: impl Iterator<Item = &'a Shown<'a>>) -> Vec<(Intent, Vec<String>)> {
14    let mut rows: Vec<(Intent, Vec<String>)> = Vec::new();
15    for entry in entries {
16        let keys = chord_text(entry.chords);
17        match rows.iter_mut().find(|(intent, _)| *intent == entry.intent) {
18            Some((_, all)) => all.push(keys),
19            None => rows.push((entry.intent, vec![keys])),
20        }
21    }
22    rows
23}
24
25/// The action name as a keymap file writes it: `select-tab accounts`.
26fn action_name(intent: Intent) -> String {
27    match intent.name() {
28        Some((name, Some(arg))) => format!("{name} {arg}"),
29        Some((name, None)) => name.to_string(),
30        None => String::new(),
31    }
32}
33
34/// The innermost scope of the context `app` is in: what a Help window is about.
35#[must_use]
36pub fn help_topic(app: &App) -> &'static str {
37    chain(app).innermost
38}
39
40/// The lines of Help for the context `app` is in now.
41#[must_use]
42pub fn help_lines(app: &App) -> Vec<String> {
43    let names = chain(app).names;
44    let view = here(app);
45    let mut lines = vec![
46        format!("Keys here ({})", app.keys.indicator()),
47        "Rebind them in the tui-keymap-overrides config key.".to_string(),
48    ];
49    for scope in names {
50        let rows = rows(view.shown.iter().filter(|entry| entry.scope == scope));
51        let title = SCOPES
52            .iter()
53            .find(|known| known.name == scope)
54            .map(|known| known.title);
55        let Some(title) = title.filter(|_| !rows.is_empty()) else {
56            continue;
57        };
58        lines.push(String::new());
59        lines.push(title.to_string());
60        lines.extend(rows.into_iter().map(|(intent, keys)| {
61            let text = intent.description().unwrap_or_default();
62            let (keys, name) = (keys.join(", "), action_name(intent));
63            format!("  {keys:<KEYS_WIDTH$}{name:<NAME_WIDTH$}{text}")
64        }));
65    }
66    lines.push(String::new());
67    lines.push(match view.key(Intent::OpenCommandLine) {
68        Some(key) => format!("Commands, after {key}"),
69        None => "Commands".to_string(),
70    });
71    lines.extend(palette::command_lines());
72    lines
73}