Skip to main content

datui_cli/
keys.rs

1//! The key registry: every key of every screen, in one table.
2//!
3//! Each [`Key`] is what is typed, a short label (for hints), a one-line description
4//! (the in-app help), an optional longer description (the manpage and the docs),
5//! and the key the help's Enter presses for it. Keys sit in task [`Group`]s on a
6//! [`Screen`]; [`GLOBAL`] holds the keys every screen takes.
7//!
8//! What shows keys reads them from here: the help overlay `?` opens in `datui-lib`,
9//! `docs/reference/keyboard-shortcuts.md` ([`render_markdown`]) and `datui-keys(7)`.
10//! A key added to the app is an entry here; a test in `datui-lib` presses each
11//! entry's key in its screen and fails when nothing takes it.
12
13/// Where the keys are typed: one in-app help screen each.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Context {
16    Table,
17    Home,
18    Documentation,
19    Query,
20    Find,
21    GoToColumn,
22    Inspector,
23    Info,
24    ValueCounts,
25    SortFilter,
26    PivotMelt,
27    Chart,
28    Describe,
29    Distribution,
30    DistributionDetail,
31    Correlation,
32    CorrelationDetail,
33    DataQuality,
34    Export,
35    Copy,
36    Views,
37    FormatPicker,
38    Retype,
39    Combine,
40    TablePicker,
41    Sample,
42    Hex,
43    /// The keys every screen takes: [`GLOBAL`].
44    Global,
45    /// The help overlay: [`HELP`].
46    Help,
47    /// A question datui asks before acting: [`QUESTION`].
48    Question,
49}
50
51/// One screen's keys.
52#[derive(Debug, Clone, Copy)]
53pub struct Screen {
54    pub context: Context,
55    /// Its heading in the help, the reference and the manpage: `Table`.
56    pub title: &'static str,
57    /// How the screen is reached, as markdown.
58    pub reached: &'static str,
59    /// Its keys, by task, in the order the help shows them.
60    pub groups: &'static [Group],
61}
62
63/// Keys that do one kind of task: `Explore`, `Shape`, `Analyze`, `Output`, or a
64/// screen's own (`Fields`, `Picker`).
65#[derive(Debug, Clone, Copy)]
66pub struct Group {
67    pub name: &'static str,
68    pub keys: &'static [Key],
69}
70
71/// One key, or a few that do one thing in turn (`n / N`).
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct Key {
74    /// What is typed, as the help writes it: `↑ / ↓ (j/k)`, `Ctrl+O`, `(type)`.
75    pub keys: &'static str,
76    /// A word or two for a hint beside the key: `Filter`, `Next match`.
77    pub label: &'static str,
78    /// Other words a hint may give the key where what it does turns on the screen's
79    /// state: Enter's `Show rows` beside `Read rows`. A hint says one of these or
80    /// [`Key::label`], never a word of its own.
81    pub also: &'static [&'static str],
82    /// One line: the in-app help, and the man page and docs without [`Key::more`].
83    pub line: &'static str,
84    /// The whole description, where it says more than the line: the manpage and the
85    /// docs print it in place of the line.
86    pub more: Option<&'static str>,
87    pub run: Run,
88}
89
90/// What Enter on a key's help line presses, in the screen help was opened from.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Run {
93    /// The first key of [`Key::keys`].
94    First,
95    /// This key, as [`chord`] reads it.
96    Key(&'static str),
97    /// Nothing: typing, the mouse, a range of digits.
98    Never,
99}
100
101/// A key entry: `keys`, a hint `label` and the help's `line`.
102pub const fn k(keys: &'static str, label: &'static str, line: &'static str) -> Key {
103    Key {
104        keys,
105        label,
106        also: &[],
107        line,
108        more: None,
109        run: Run::First,
110    }
111}
112
113impl Key {
114    /// With the whole description for the manpage and the docs.
115    pub const fn more(self, more: &'static str) -> Self {
116        Key {
117            more: Some(more),
118            ..self
119        }
120    }
121
122    /// With other words a hint may say for it; see [`Key::also`].
123    pub const fn also(self, also: &'static [&'static str]) -> Self {
124        Key { also, ..self }
125    }
126
127    /// Whether a hint may give this key `label`.
128    pub fn says(&self, label: &str) -> bool {
129        self.label == label || self.also.contains(&label)
130    }
131
132    /// Enter in the help presses `spec` rather than the first key.
133    pub const fn run(self, spec: &'static str) -> Self {
134        Key {
135            run: Run::Key(spec),
136            ..self
137        }
138    }
139
140    /// Enter in the help presses nothing for this entry.
141    pub const fn no_run(self) -> Self {
142        Key {
143            run: Run::Never,
144            ..self
145        }
146    }
147
148    /// The description the manpage and the docs print.
149    pub fn long(&self) -> &'static str {
150        self.more.unwrap_or(self.line)
151    }
152
153    /// The key Enter on this line presses, if any.
154    pub fn action(&self) -> Option<Chord> {
155        match self.run {
156            Run::First => chord(first_key(self.keys)),
157            Run::Key(spec) => chord(spec),
158            Run::Never => None,
159        }
160    }
161}
162
163/// A key as the app receives it, without the terminal library: `datui-lib` turns it
164/// into a key event.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub struct Chord {
167    pub code: Code,
168    pub ctrl: bool,
169    pub alt: bool,
170    pub shift: bool,
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum Code {
175    Char(char),
176    Enter,
177    Esc,
178    Tab,
179    BackTab,
180    Backspace,
181    Delete,
182    Insert,
183    Up,
184    Down,
185    Left,
186    Right,
187    PageUp,
188    PageDown,
189    Home,
190    End,
191    F(u8),
192}
193
194/// Every key a `keys` text names, in order: `↑ / ↓ (j/k)` is ↑, ↓, j and k. Text that
195/// is not a key (`(type)`, `Click`) names none.
196pub fn chords(keys: &str) -> Vec<Chord> {
197    let spaced = keys.replace(['(', ')'], " / ");
198    spaced
199        .split(" / ")
200        .flat_map(|part| part.split(", "))
201        .flat_map(|part| part.split(" or "))
202        .map(str::trim)
203        .flat_map(|token| {
204            // `PgUp/PgDn`, `h/l`; a lone `/` is the slash key.
205            if token.len() > 1 && token.contains('/') {
206                token
207                    .split('/')
208                    .filter(|t| !t.is_empty())
209                    .collect::<Vec<_>>()
210            } else {
211                vec![token]
212            }
213        })
214        .filter_map(chord)
215        .collect()
216}
217
218/// The first key a `keys` text names: `↑` of `↑ / ↓ (j/k)`, `Ctrl+D` of
219/// `Ctrl+D/Ctrl+U`.
220pub fn first_key(keys: &str) -> &str {
221    let mut end = keys.len();
222    for sep in [" / ", ", ", " (", " or ", " "] {
223        if let Some(at) = keys.find(sep)
224            && at > 0
225        {
226            end = end.min(at);
227        }
228    }
229    let first = &keys[..end];
230    // `PgUp/PgDn`, `Ctrl+D/Ctrl+U`; a lone `/` is the slash key.
231    match first.find('/') {
232        Some(at) if at > 0 && first.len() > 1 => &first[..at],
233        _ => first,
234    }
235}
236
237/// Read one key: `j`, `G`, `Enter`, `Ctrl+O`, `Shift+Tab`, `F1`, `↑`. `None` for text
238/// that is not one key.
239pub fn chord(spec: &str) -> Option<Chord> {
240    let mut chord = Chord {
241        code: Code::Esc,
242        ctrl: false,
243        alt: false,
244        shift: false,
245    };
246    let mut rest = spec;
247    loop {
248        if let Some(r) = rest.strip_prefix("Ctrl+").filter(|r| !r.is_empty()) {
249            chord.ctrl = true;
250            rest = r;
251        } else if let Some(r) = rest.strip_prefix("Alt+").filter(|r| !r.is_empty()) {
252            chord.alt = true;
253            rest = r;
254        } else if let Some(r) = rest.strip_prefix("Shift+").filter(|r| !r.is_empty()) {
255            chord.shift = true;
256            rest = r;
257        } else {
258            break;
259        }
260    }
261    chord.code = match rest {
262        "Enter" => Code::Enter,
263        "Esc" => Code::Esc,
264        "Tab" if chord.shift => Code::BackTab,
265        "Tab" => Code::Tab,
266        "Space" => Code::Char(' '),
267        "Backspace" => Code::Backspace,
268        "Delete" | "Del" => Code::Delete,
269        "Insert" => Code::Insert,
270        "PgUp" | "PageUp" => Code::PageUp,
271        "PgDn" | "PageDown" => Code::PageDown,
272        "Home" => Code::Home,
273        "End" => Code::End,
274        "↑" | "↑↓" => Code::Up,
275        "↓" => Code::Down,
276        "←" | "←→" => Code::Left,
277        "→" => Code::Right,
278        _ => {
279            let mut chars = rest.chars();
280            match (chars.next(), chars.next()) {
281                // Ctrl+O is the letter o with Ctrl; a capital alone comes with Shift,
282                // as a terminal reports it.
283                (Some(c), None) if c.is_ascii_alphabetic() && chord.ctrl => {
284                    Code::Char(c.to_ascii_lowercase())
285                }
286                (Some(c), None) if !c.is_whitespace() => {
287                    if c.is_ascii_uppercase() {
288                        chord.shift = true;
289                    }
290                    Code::Char(c)
291                }
292                (Some('F'), Some(_)) => Code::F(rest[1..].parse().ok().filter(|n| *n <= 12)?),
293                _ => return None,
294            }
295        }
296    };
297    Some(chord)
298}
299
300/// The keys every screen takes. Every screen's help lists them last.
301pub const GLOBAL: Group = Group {
302    name: "Everywhere",
303    keys: &[
304        k("? / F1", "Help", "This screen's keys (F1 in text fields)")
305            .more("This screen's keys. In a text field ? types, and F1 opens the help")
306            .run("F1"),
307        k("Ctrl+O", "Home", "The home screen; abandons a load")
308            .more("The home screen, on the dataset left, its filter kept and selected (typing replaces it); abandons a load"),
309        k(
310            "Ctrl+Q / Ctrl+C",
311            "Quit",
312            "Quit (Ctrl+C in a text field too)",
313        )
314        .more("Quit from anywhere; Ctrl+C quits from a text field too, where Alt+W copies"),
315        k("Click a field", "Act", "Focus a form's field and act as Space")
316            .more("Focus a form's field and act as Space: a checkbox flips, a choice steps, a picker opens, a button runs; a text field takes the cursor. A row of a list (a sort, a filter, a column) takes focus on the first click and acts on the second. A click on a picker's line chooses it, on a tab switches to it, and on a key in the footer presses it. A click outside a dialog does nothing. The mouse is the terminal's with display.mouse = false (or --mouse false); in most terminals Shift+drag selects text either way")
317            .no_run(),
318        k("Right-click a field", "Back", "Step a choice back, as ← does; else focus it").no_run(),
319    ],
320};
321
322/// The keys of the help overlay itself, for its footer and the reference.
323pub const HELP: Group = Group {
324    name: "Help",
325    keys: &[
326        k("↑ / ↓ (j/k)", "Move", "Move between the keys"),
327        k("Enter", "Run", "Close the help and press the key")
328            .more("Close the help and press the key on the line, where help was opened"),
329        k("/", "Filter", "Narrow to the keys whose text matches"),
330        k("Esc", "Close", "Clear the filter, then close").also(&["Clear"]),
331    ],
332};
333
334/// The keys of a question datui asks before acting: overwrite a file, delete a view,
335/// read a whole dataset.
336pub const QUESTION: Group = Group {
337    name: "Question",
338    keys: &[
339        k("← / →", "Switch", "Choose the other answer").also(&["Pick"]),
340        k(
341            "Enter",
342            "Confirm",
343            "Give the answer chosen, or close an error",
344        )
345        .also(&["Close"]),
346        k("Esc", "Cancel", "Leave it as it was").also(&["No"]),
347    ],
348};
349
350/// Where the whole reference is, the help's last line.
351pub const REFERENCE_URL: &str =
352    "https://derekwisong.github.io/datui/reference/keyboard-shortcuts.html";
353
354/// The q language in a few lines, for the query screen's help and `datui-query(7)`:
355/// an example and what it shows.
356pub const Q_SUMMARY: &[(&str, &str)] = &[
357    (
358        "select [cols] [by groups] [where conds]",
359        "Each part optional",
360    ),
361    (
362        "select a, b where a > 10, b < 5",
363        "In where, , is and; | is or",
364    ),
365    (
366        "select avg price, n:count id by region",
367        "Aggregate by group",
368    ),
369    (
370        "total:a+b  col[\"first name\"]",
371        "Name a column; a name with spaces",
372    ),
373    ("1/c+a is 1/(c+a)", "Right to left: 100 < (a+b)*2"),
374    (
375        "date.year  2024.01.31  city.contains[\"York\"]",
376        "Accessors and dates",
377    ),
378    (
379        "name in [\"Ann\", \"Bo\"]  item like \"*ham*\"",
380        "Membership and patterns",
381    ),
382];
383
384/// The analysis tools' sample keys, the same on each.
385const SAMPLE_KEYS: &[Key] = &[
386    k("s", "Sample", "Choose the sample every tool reads").more(
387        "Choose the sample every tool reads: which rows, how they are picked, how many (typed, like 50000, 50k or 2m), the seed. Enter applies the form",
388    ),
389    k(
390        "v",
391        "Sample rows",
392        "View the sample's rows as a table; Esc comes back",
393    ),
394    k(
395        "r",
396        "Resample",
397        "Draw another sample (when the result is a sample)",
398    ),
399    k("a", "All rows", "Read every row instead, after confirming"),
400    k("t", "New rows", "Read again with rows that arrived since")
401        .also(&["Refresh"])
402        .more(
403        "While following a file, read again with the rows that arrived since the results were read",
404    ),
405];
406
407/// Every screen, as the reference lists them.
408pub const SCREENS: &[Screen] = &[
409    Screen {
410        context: Context::Table,
411        title: "Table",
412        reached: "Where a dataset opens.",
413        groups: &[
414            Group {
415                name: "Explore",
416                keys: &[
417                    k("↑ / ↓ (j/k)", "Move", "Move the row cursor"),
418                    k("← / → (h/l)", "Column", "Move the column cursor")
419                        .more("Move the column cursor, frozen columns included; the columns scroll only when it would leave the screen"),
420                    k("Shift+← / Shift+→", "Page columns", "A page of columns left or right")
421                        .more("A page of columns left or right, the cursor on the page's first column"),
422                    k("{ / }", "First, last", "First column, last column"),
423                    k("PgUp / PgDn", "Page", "A page up or down (Ctrl+B / Ctrl+F too)"),
424                    k("Ctrl+D / Ctrl+U", "Half page", "Half a page down or up"),
425                    k("Home / End", "Top, end", "First or last row (G = End)"),
426                    k(":", "Command line", "Go to a row, or run SQL or q")
427                        .more("The command line: digits go to that row (the prefix says row:), anything else runs as SQL or q, as the prefix says; Ctrl+T switches. With a query in effect it opens on the query's text"),
428                    k("g", "Go to column", "Go to a column by name"),
429                    k("/ (f)", "Find", "Find text, a regex, or letters in order")
430                        .more("Find text, a regex, or letters in order in the view; matches on screen light up as you type, and Enter takes the cursor, column cursor and all, to the first at or after its row. f opens it too"),
431                    k("n / N", "Next", "Next or previous match")
432                        .more("Next / previous match from the cursor's cell, wrapping round the view"),
433                    k("Enter", "Drill", "Drill down to a group's rows, or inspect")
434                        .more("On a row of a by query or a SQL GROUP BY, drill down to its rows (Esc comes back); elsewhere, inspect the row"),
435                    k("Space", "Inspect", "Inspect the row: every field, whole")
436                        .more("Inspect the row: every field, each value whole and exact (Esc or Space closes)"),
437                ],
438            },
439            Group {
440                name: "Shape",
441                keys: &[
442                    k("[ / ]", "Sort", "Sort by the cursor's column, up or down")
443                        .more("Sort by the cursor's column, [ ascending and ] descending, replacing the sort in effect; the same key again on that column removes it. The s sidebar adds secondary sorts"),
444                    k("s", "Sort & Filter", "Sort & Filter sidebar, on the cursor's column")
445                        .more("Open the Sort & Filter sidebar (tabs: Columns, Filters), on the cursor's column"),
446                    k("+ / -", "Filter", "Keep (+) or drop (-) rows with this cell's value")
447                        .more("Filter on the cursor's cell: + keeps the rows with its value, - drops them (a null cell: the nulls). Each adds a filter to the Sort & Filter sidebar, joined with \"and\"; the value is the cell's exactly as stored"),
448                    k("r", "Reverse", "Reverse the sort, or the row order")
449                        .more("Reverse sort order (sorted columns carry a direction mark in the header); with no sort, reverse the row order"),
450                    k("H / L", "Move column", "Move the cursor's column left or right")
451                        .more("Move the cursor's column one place left or right, the cursor with it; a frozen column moves among the frozen ones. R puts the order back"),
452                    k("p", "Pivot & Melt", "Pivot or melt"),
453                    k("S", "Sample", "Draw a sample into memory; the view works on it")
454                        .more("Draw a sample of the source into memory: the step under the query, filters and sort, which then run over it. The rows show as they arrive (Esc stops, keeping them); the footer says sample 100,000 of 36.8M. Analysis, charts and export read the sample. S again edits it; Method No sample, or R, takes it away"),
455                    k("R", "Reset", "Clear query, filters, sort, layout, view")
456                        .more("Reset table: clear the sample, query, filters, sort, column order, hidden columns and widths, frozen columns, pivot/melt, drill-down and the applied view"),
457                ],
458            },
459            Group {
460                name: "Analyze",
461                keys: &[
462                    k("F", "Counts", "Value counts of the cursor's column")
463                        .more("Value counts of the cursor's column: each value's rows, percent and a bar, with a summary"),
464                    k("a", "Analysis", "Describe, distributions, correlation, quality")
465                        .more("Open Analysis. In a Data Quality evidence drill a is disabled; Esc returns to the observation"),
466                    k("c", "Chart", "Chart the view"),
467                    k("i", "Info", "Schema, resources, partitions, notes")
468                    .also(&["Notes"])
469                        .more("Open the Info panel (tabs: Schema, Resources, Partitions, Notes). H on its Schema tab reads a CSV's first row as data, or as column names"),
470                ],
471            },
472            Group {
473                name: "Output",
474                keys: &[
475                    k("e", "Export", "Export the view to a file"),
476                    k("y", "Copy", "Copy a cell, row, view or table")
477                        .more("Copy to the clipboard (cell, row, view or table); a cell is the cursor's"),
478                    k("v", "Views", "The saved views list"),
479                    k("V", "Apply view", "Apply the best-matching view")
480                        .more("Apply the best-matching view (or open the list)"),
481                ],
482            },
483            Group {
484                name: "Display",
485                keys: &[
486                    k("#", "Row numbers", "Row numbers on or off")
487                        .more("Row numbers on or off: each row's place in the source, kept through a sort or a filter (a text file's line numbers). On for text and logs; display.row_numbers sets it"),
488                    k(",", "Grouping", "Number formatting (digit grouping) on or off"),
489                    k("D", "Types", "The type row under the headers on or off"),
490                    k("< / >", "Width", "The cursor's column 4 cells narrower or wider"),
491                    k("= / w", "Fit, auto", "Fit the column to the rows on screen; automatic")
492                        .more("Fit the cursor's column to the rows on screen; w puts it back to automatic width"),
493                    k("b", "Format spec", "Read a binary file with another format spec")
494                        .more("A binary file read through a format spec: read it again with another spec. Clears the query, filters and sort"),
495                    k("T", "Table", "Open another table of the file")
496                        .more("A file of several tables (a workbook's worksheets, a database's tables, a format spec's record types, a Hugging Face cache's splits): pick another to open in place of this one, as --table names it. Clears the query, filters and sort; a saved view for the table applies. On a file of one table, says so"),
497                    k("t", "Follow", "Follow the file as it grows")
498                    .also(&["Pause", "Resume"])
499                        .more("Follow the file as it grows (CSV, TSV, PSV, NDJSON). Reads it again, so the query, filters and sort are cleared; while following, t pauses and resumes, and Esc stops"),
500                ],
501            },
502            Group {
503                name: "Go",
504                keys: &[
505                    k("q", "Back", "Home when opened from there, else quit")
506                        .more("Back to the home screen when the dataset was opened from it; otherwise quit"),
507                    k("Q", "Quit", "Quit"),
508                    k("Esc", "Back", "Leave a drill-down; stop a find, sample, follow")
509                    .also(&["Stop"])
510                        .more("Leave a drill-down; stop a find, a sample being drawn (its rows so far stay) or a follow"),
511                ],
512            },
513            Group {
514                name: "Mouse",
515                keys: &[
516                    k("Click", "Point", "The cursor to the cell; on a header, its column")
517                        .no_run(),
518                    k("Double-click", "Enter", "Enter on the row").no_run(),
519                    k("Double-click a header", "Sort", "Sort by it: up, down, off, as [ / ] do")
520                        .more("Double-click a column's header to sort by it, as [ and ] do: ascending, then descending, then back to no sort, replacing the sort in effect")
521                        .no_run(),
522                    k("Double-click a header's edge", "Fit", "Fit the column to the rows, as = does")
523                        .more("Double-click the gap right of a column's header to fit the column to the rows on screen, as = does; the column cursor moves to it, and nothing is sorted")
524                        .no_run(),
525                    k("Wheel", "Scroll", "↑ / ↓, three rows a notch")
526                        .more("↑ / ↓, three rows a notch; the same in help, the inspector and the sidebars")
527                        .no_run(),
528                    k("Shift+wheel", "Across", "← / →, the column cursor")
529                        .more("← / →, the column cursor (a sideways wheel too)")
530                        .no_run(),
531                    k("Click a key", "Press", "Press a key the footer shows")
532                        .more("Press a key the footer shows; a click on the filters and sort presses s, on query presses :")
533                        .no_run(),
534                    k("Drag a header", "Move column", "Move the column there, as H / L do")
535                        .more("Drag a column's header onto another column to move it there, as H / L do; a rule on the header marks where it lands")
536                        .no_run(),
537                    k("Drag a header's edge", "Width", "Set the column's width, as < / > do")
538                        .more("Drag the gap right of a column's header to set its width by hand, as < / > do, from 4 to 240 cells")
539                        .no_run(),
540                    k("Right-click", "Menu", "A menu of the keys that act on the cell")
541                        .more("Right-click a cell: the cursor goes there and a menu lists the keys that act on it (+, -, F, [, ], y, Space), each with its key. ↑ / ↓ and Enter, or a click, run a line as its key does; Esc or a click elsewhere closes it")
542                        .no_run(),
543                ],
544            },
545        ],
546    },
547    Screen {
548        context: Context::Home,
549        title: "Home screen",
550        reached: "`datui` with no path, or <kbd>Ctrl</kbd>+<kbd>O</kbd> from anywhere.",
551        groups: &[
552            Group {
553                name: "Explore",
554                keys: &[
555                    k("↑ / ↓", "Move", "Move the selection (Ctrl+P / Ctrl+N too)"),
556                    k("Ctrl+↑ / Ctrl+↓", "Section", "Previous or next section"),
557                    k("PgUp / PgDn", "Page", "A screenful, stopping at the first and last"),
558                    k("Home / End", "First, last", "The first or last row")
559                        .more("The first or last row. The filter has no cursor to move: it is edited at its end"),
560                    k("← / →", "Fold", "Fold or unfold; → goes inside or shows more")
561                        .more("Fold or unfold a section; → on a directory or a file of tables goes inside it, and on a file a format spec reads as record types lists them, one row each. On a directory cut to its first rows, or RECENT, → on its more row shows them all; ← on a row past the first ones cuts it back, and on any other row folds"),
562                    k("Space", "Fold", "Fold the section (types once filtering)")
563                        .more("While the filter is empty: fold or unfold the section header under the cursor. With a filter typed, it types"),
564                    k("Tab", "Sort", "Cycle the sort")
565                    .also(&["Complete"])
566                        .more("Cycle the sort; the footer names the order in effect when it has room"),
567                ],
568            },
569            Group {
570                name: "Go",
571                keys: &[
572                    k("Enter", "Open", "What the footer names: Open, Inside, Look")
573                    .also(&["Up", "Open all", "Inside", "Look", "Fold", "Show all", "Show", "Hex", "About"])
574                        .more("What the footer says on this row: \"Open all\" reads a whole directory as one table, \"Inside\" steps into it, \"Open\" loads a file, \"Look\" finds out first. A catalog bookmark, indented under its dataset, opens whole. On a section header, fold or unfold it; on a more row, show the rest; on `..`, go up a level; on the hidden-files row, show them"),
575                    k("Backspace", "Up", "Delete a filter character, or up a level")
576                        .more("Delete a filter character; on an empty filter, up a level (from a bucket, back to its cloud source; from the top of a catalog's remote dataset, back here)"),
577                    k("Esc", "Back", "Path prompt, filter, directory, then the table")
578                    .also(&["Cancel"])
579                        .more("Back out one layer: the path prompt, the filter (onto the first dataset), the directory (back to the row it was entered from), then to the open table"),
580                ],
581            },
582            Group {
583                name: "Find",
584                keys: &[
585                    k("(type)", "Filter", "Narrow by name or column, fuzzy")
586                        .more("Narrow by name or column; fuzzy, so \"sal\" finds \"sales\". What you open often ranks first. Typing also searches below the directory you are inside and the listed bucket names; matches appear under \"Found\"")
587                        .no_run(),
588                    k("~", "Path", "Type a path or URL (on an empty filter)")
589                        .more("While the filter is empty: type a path or URL by hand. The list shows the directory being typed, narrowed by the name after the last /. The prompt is a plain editor: characters, Backspace, Ctrl+U clears, The first name that matches is picked. Tab completes the one name left or what the names share, or a name picked further down; ↑ / ↓ pick a name, and ↑ from the first takes the path as typed; Enter opens the picked name or the typed path: a file opens, a directory is gone inside; Esc closes. s3://, gs:// and az:// complete from buckets and prefixes already known. With a filter typed, ~ types into it"),
590                    k("Ctrl+U", "Clear", "Clear the filter or path input"),
591                    k("Ctrl+R", "Refresh", "List again what is on screen"),
592                ],
593            },
594            Group {
595                name: "Manage",
596                keys: &[
597                    k("Ctrl+A", "All files", "Show or hide files datui cannot read")
598                        .more("Show or hide files datui cannot read; inside a SQLite database, its internal tables"),
599                    k("Ctrl+X", "Hex", "The file under the cursor as bytes")
600                        .more("Show the local file under the cursor as bytes, in the hex view, whatever datui would read it as"),
601                    k("Ctrl+D", "Catalog", "Add the row to catalog.toml; on its rows, forget it")
602                    .also(&["Add", "Forget"])
603                        .more("Add the dataset or directory under the cursor to catalog.toml, listed under My datasets; on a row from catalog.toml, forget it. A heading stands for the directory it lists. Only catalog.toml is written; another catalog is hidden with home.hide"),
604                    k("Ctrl+E", "Docs", "The row's documentation, full screen")
605                        .more("Open the Documentation view of a catalog row, of a place inside one, or of a file whose format spec documents it: description, publisher, license, links, record types, columns with units and value legends, bookmarks. A catalog's description, link and column notes stand over the spec's. Ctrl+E here is not readline's end of line: the filter is edited at its end"),
606                    k("Delete", "Forget", "Forget a recent, place or catalog.toml row; hide")
607                    .also(&["Hide"])
608                        .more("Forget the highlighted recent entry, or a whole place after confirming, or a row from catalog.toml, or hide a cloud source. On the Example datasets heading, hide them until datui cache clear, after confirming"),
609                    k("Shift+Delete", "Forget all", "Forget every recent entry, after confirming"),
610                ],
611            },
612            Group {
613                name: "Mouse",
614                keys: &[
615                    k("Click", "Select", "Select the row; double-click is Enter").no_run(),
616                    k("Wheel", "Scroll", "Move the selection three rows")
617                        .more("Move the selection three rows, stopping at the ends")
618                        .no_run(),
619                ],
620            },
621        ],
622    },
623    Screen {
624        context: Context::Documentation,
625        title: "Documentation",
626        reached: "<kbd>Ctrl</kbd>+<kbd>E</kbd> on the home screen, on a catalog row or a file a format spec documents.",
627        groups: &[Group {
628            name: "Read",
629            keys: &[
630                k("↑ / ↓ (j/k)", "Move", "Move the cursor a line"),
631                k("PgUp / PgDn", "Page", "A page"),
632                k("g / G", "Ends", "The first or last line (Home / End too)"),
633                k("Enter / Space / →", "Values", "Open or close the column's value legend")
634                    .more("Open or close the value legend of the column under the cursor: a catalog's values, or a spec's enum"),
635                k("o", "Open", "Open the line's link in the browser, after asking")
636                    .more("Open the link on the cursor's line in the system browser. Only http and https links open, and only after a question showing the whole URL (Enter opens, Esc does not). Off over SSH or without a display: y copies the link instead"),
637                k("y", "Copy", "Copy the line's link or value, whole")
638                    .more("Copy the link or value on the cursor's line, whole, however it is cut on screen"),
639                k("Esc / q / ←", "Back", "Back to the home screen"),
640            ],
641        }],
642    },
643    Screen {
644        context: Context::Query,
645        title: "Command line",
646        reached: "<kbd>:</kbd> at the table.",
647        groups: &[
648            Group {
649                name: "Run",
650                keys: &[
651                    k("(digits)", "Row", "Digits go to that row (row: shows it)")
652                        .more("Digits alone go to that row, and the prefix says row: (:0 Enter is the top)")
653                        .no_run(),
654                    k("Enter", "Run", "Go to the row, or run the query")
655                    .also(&["Go"])
656                        .more("Go to the row, or run the query as the prefix says, sql: or q:. Reopened with a query in effect, the line holds its text, selected: typing replaces it, arrows edit it"),
657                    k("Ctrl+J", "Run", "Run, the same as Enter"),
658                    k("Ctrl+T", "Language", "SQL or q; the line keeps its text")
659                        .more("Switch between SQL and q, keeping what is typed; the choice is remembered. [query] default_mode sets the first"),
660                    k("Esc", "Close", "Close"),
661                ],
662            },
663            Group {
664                name: "Edit",
665                keys: &[
666                    k("Tab", "Complete", "Complete a column name (SQL: or df)")
667                        .more("Complete a column name, or df in SQL; again for the next match. The line under the input lists the names that fit"),
668                    k("Alt+Enter", "New line", "SQL: start a new line"),
669                    k("↑ / ↓", "History", "Earlier and later queries (Ctrl+P / Ctrl+N)")
670                        .more("Earlier and later queries from the history (Ctrl+P / Ctrl+N too; SQL and q keep their own). In SQL over several lines, they move between lines first"),
671                    k("Ctrl+U / Ctrl+K", "Delete", "Delete to the start or end of the line"),
672                    k("Ctrl+Z / Ctrl+R", "Undo", "Undo, redo"),
673                ],
674            },
675        ],
676    },
677    Screen {
678        context: Context::Find,
679        title: "Find",
680        reached: "<kbd>/</kbd> (or <kbd>f</kbd>) at the table.",
681        groups: &[
682            Group {
683                name: "Find",
684                keys: &[
685                    k("(text)", "Pattern", "Text, a regex, or letters in order")
686                        .more("What to find: text (any case until a capital is typed), a regex with Ctrl+R, or letters in order with Ctrl+T. Matches in the rows on screen light up as you type, and the line says how many are on screen")
687                        .no_run(),
688                    k("Enter", "Next", "Go to the first match at or after the row")
689                        .more("Find: the cursor, column cursor and all, goes to the first match at or after its row, reading past the rows on hand when it must (the footer counts the rows read; Esc stops). On an empty field, clear the find"),
690                    k("Ctrl+G", "Keep matches", "Keep only the rows that match, as a filter")
691                        .more("Keep only the rows with a match, as a filter: the footer and the Sort & Filter sidebar show it, and removing it there (or R) brings the rows back"),
692                    k("Ctrl+R", "Regex", "Regex on or off"),
693                    k("Ctrl+T", "Letters in order", "Letters in order on or off: smth finds Smith"),
694                    k("Ctrl+L", "Column", "Only the cursor's column, or every column")
695                        .more("Only the column cursor's column, or every column shown"),
696                    k("↑ / ↓", "History", "Earlier patterns (Ctrl+P / Ctrl+N too)"),
697                    k("Esc", "Cancel", "Cancel"),
698                ],
699            },
700            Group {
701                // Keys of the table, not the prompt: Enter here would type them.
702                name: "At the table",
703                keys: &[
704                    k("n / N", "Next", "Next or previous match")
705                        .more("Next / previous match from the cursor's cell. Past the last match the find comes round to the first, and the footer says so. Each one typed while a find reads runs in turn; Esc stops them all").no_run(),
706                    k("/", "Find again", "Find again, the last pattern ready to edit").no_run(),
707                    k("Esc", "Clear", "Clear the find (or stop one still reading)").no_run(),
708                ],
709            },
710        ],
711    },
712    Screen {
713        context: Context::GoToColumn,
714        title: "Go to column",
715        reached: "<kbd>g</kbd> at the table.",
716        groups: &[Group {
717            name: "Go",
718            keys: &[
719                k("(type)", "Narrow", "Narrow to the names that contain it").no_run(),
720                k("↑ / ↓", "Move", "Move"),
721                k("Enter", "Go", "Move the column cursor to it")
722                    .more("Go. The column cursor moves to it. A column already whole on screen stays where it is; another becomes the first after the frozen ones, or lands on the last page when it is there"),
723                k("Backspace", "Delete", "Delete a character (Ctrl+W a word, Ctrl+U all)"),
724                k("Esc", "Cancel", "Close without moving"),
725            ],
726        }],
727    },
728    Screen {
729        context: Context::Inspector,
730        title: "Inspector",
731        reached: "<kbd>Space</kbd> at the table.",
732        groups: &[
733            Group {
734                name: "Fields",
735                keys: &[
736                    k("↑ / ↓ (j/k)", "Field", "Move between fields"),
737                    k("Home / End", "First, last", "First and last field"),
738                    k("PgUp / PgDn", "Page", "A page of fields"),
739                    k("← / → (h/l)", "Row", "Previous and next row")
740                        .more("Previous and next row; the table's cursor moves with it"),
741                    k("Tab / Shift+Tab", "Value", "Into the value, to scroll and find in it")
742                        .more("Into the value, to scroll and find in it. Nothing moves: the panes are split by what they hold, not by where the cursor is"),
743                    k("Enter", "Open", "Open a struct, list or JSON; read a field")
744                    .also(&["Rows", "Read", "Retry"])
745                        .more("On a group's row, its rows, as at the table. Else open a struct, a list, or text holding a JSON object or array; or read a field the table's rows do not hold (hidden and binary columns)"),
746                    k("r", "Read", "On a group's row, read a field the rows lack")
747                        .more("On a group's row, read a field the rows do not hold"),
748                    k("/", "Find", "Find a field by name, then by value")
749                        .more("Find a field by name, then by value: type to narrow, Enter or ↓ keeps the list narrowed, Esc clears it"),
750                    k("f", "Nulls", "Nulls shown or hidden (comparing: only diffs)")
751                    .also(&["Differ", "Nulls: hidden", "Nulls: shown"])
752                        .more("Nulls: shown or hidden (null and empty fields); comparing, only the fields that differ"),
753                    k("s", "Order", "Order: the table's, A-Z, or nulls last"),
754                    k("c", "Compare", "Compare with the next row, or the pinned one")
755                        .more("Compare: a column for the next row, or the pinned one"),
756                    k("m", "Pin", "Pin this row to compare others with; again to unpin"),
757                    k("Esc / Space", "Close", "Close; Esc clears a find, then Compare, first")
758                    .also(&["Clear", "No compare"])
759                        .more("Close. Esc backs out one level at a time: a find first, then Compare, then the inspector"),
760                ],
761            },
762            Group {
763                name: "Output",
764                keys: &[
765                    k("y", "Copy", "Copy the value as its view shows it")
766                    .also(&["Copy base64", "Copy JSON", "Copy text"]),
767                    k("Y", "Copy row", "Copy the whole row as one JSON object"),
768                    k("e", "View", "The value's next view, where it has more than one")
769                    .also(&["JSON", "Raw", "Escaped", "Hex", "Text"]),
770                    k("w", "Wrap", "Word wrap or hard wrap for long text")
771                    .also(&["Hard wrap", "Word wrap"]),
772                    k("o", "Open", "Open the value in another program"),
773                ],
774            },
775            Group {
776                name: "Value",
777                keys: &[
778                    k("↑ / ↓ (j/k)", "Scroll", "Scroll a line"),
779                    k("PgUp / PgDn", "Page", "Scroll a page"),
780                    k("Home / End", "Top/End", "Top and end, however long the value")
781                        .more("Top and end, at once however long the value"),
782                    k("/", "Find", "Find in the value; n and N go on")
783                        .more("Find in the value; n and N go to the next and last place"),
784                    k("n / N", "Next", "The next or last place found in the value"),
785                    k("e, w, y, o", "As fields", "As in the fields"),
786                    k("Esc / Tab", "Fields", "Back to the fields; Esc clears a find first")
787                        .more("Back to the fields (Shift+Tab too); Esc clears a find first"),
788                ],
789            },
790            Group {
791                name: "Find",
792                keys: &[
793                    k("(type)", "Find", "The name or value to find")
794                        .also(&["Text"])
795                        .no_run(),
796                    k("Enter", "Done", "Keep the list narrowed; in a value, find")
797                        .also(&["Find"]),
798                    k("Esc", "Clear", "Clear the find"),
799                ],
800            },
801            Group {
802                name: "Nested",
803                keys: &[
804                    k("Enter / → (l)", "Open", "Open the focused item"),
805                    k("↑ / ↓ (j/k)", "Field", "Move between fields, keys or items").also(&["Key", "Item"]),
806                    k("Tab / Shift+Tab", "Value", "Into the item's value; not in an empty level"),
807                    k("PgUp / PgDn", "Page", "A page of the level"),
808                    k("Esc / ← (h)", "Back", "Up a level; at the row, Esc closes"),
809                    k("y", "Copy", "Copy the item: text, or JSON indented")
810                        .more("Copy the focused item: text as itself, a JSON object or array indented"),
811                    k("e", "View", "The item's next view").also(&["JSON", "Raw", "Escaped", "Hex", "Text"]),
812                ],
813            },
814        ],
815    },
816    Screen {
817        context: Context::Info,
818        title: "Info panel",
819        reached: "<kbd>i</kbd> at the table.",
820        groups: &[Group {
821            name: "Panel",
822            keys: &[
823                k("← / → (h/l)", "Tabs", "Previous or next tab (Shift+Tab / Tab too)")
824                    .more("Previous or next tab, from anywhere in the panel; Shift+Tab and Tab do the same. The panel is a viewer, not a form: its body always has the keys"),
825                k("↑ / ↓ (j/k)", "Move", "Move the cursor, or scroll the list")
826                    .also(&["Scroll"])
827                    .more("Schema, Notes or Documentation tab: move the cursor. Model, Audio, MIDI, Metadata and format tabs: scroll the list"),
828                k("PgUp / PgDn", "Page", "Scroll the list a page")
829                    .more("Model, Audio, MIDI, Metadata and format tabs: scroll the list a page"),
830                k("Home / End", "Top, end", "The top or the end of the list")
831                    .more("Model, Audio, MIDI, Metadata and format tabs: the top or the end of the list"),
832                k("Enter", "Open", "Schema: the type; Notes: the offer; a table: open it")
833                    .also(&["Values"])
834                    .more("Schema tab: change the column's type, with the names and formats a format spec's type takes. Notes tab: take the offer on the note, where it has one. Documentation tab: open or close the value legend of the column under the cursor. Excel or SQLite tab: open the worksheet or table under the cursor in place of this one, as T does"),
835                k("o", "Open", "Documentation tab: open the line's link")
836                    .more("Documentation tab: open the link on the cursor's line in the system browser. Only http and https links open, and only after a question showing the whole URL. Off over SSH or without a display"),
837                k("y", "Copy", "Documentation tab: copy the line's link or value")
838                    .more("Documentation tab: copy the link or value on the cursor's line, whole, however it is cut on screen"),
839                k("H", "Header", "Schema tab, CSV: first row as data or names")
840                    .more("Schema tab, CSV, TSV, PSV: read the first row as data, under column_1, column_2, …; again to read it as column names. Reads the file again, so the query, filters and sort are cleared, and the panel closes"),
841                k("c", "Count", "Count every row, where the count is an estimate")
842                    .more("A dataset of more files than read.exact_count_files shows a row count estimated from a sample of its footers; c reads every footer for the exact count. The footer shows how far it has got, and Esc at the table stops it"),
843                k("x", "Hex", "Show the file's bytes in the hex view"),
844                k("Esc / i", "Close", "Close the panel"),
845            ],
846        }],
847    },
848    Screen {
849        context: Context::ValueCounts,
850        title: "Value counts",
851        reached: "<kbd>F</kbd> at the table.",
852        groups: &[
853            Group {
854                name: "Explore",
855                keys: &[
856                    k("↑ / ↓ (j/k)", "Move", "Move"),
857                    k("PgUp / PgDn", "Page", "A page"),
858                    k("Home / End", "First, last", "First and last row"),
859                    k("← / → (h/l)", "Column", "The previous or next column")
860                        .more("The previous or next column; the table's column cursor moves with it"),
861                    k("Enter", "Drill", "The rows holding the value")
862                    .also(&["Rows"])
863                        .more("The rows holding the value, as a drill-down; Esc there comes back here"),
864                    k("s", "Sort", "Sort by count or by value"),
865                    k("c", "Histogram", "A number's histogram, or its counts")
866                    .also(&["Counts"])
867                        .more("Between a number column's histogram, binned from the counts, and the listing of its values. A number opens as its histogram"),
868                    k("a", "All rows", "Count every row, when the counts are of a sample"),
869                    k("t", "New rows", "Count again with the rows that arrived")
870                    .also(&["Refresh"])
871                        .more("While following a file, count again with the rows that arrived since; the bar says how many"),
872                ],
873            },
874            Group {
875                name: "Output",
876                keys: &[
877                    k("y", "Copy", "Copy the counts as TSV")
878                        .more("Copy the counts as TSV: every value, its count, percent and cumulative percent"),
879                    k("e", "Export", "Export the counts to a file"),
880                    k("Esc", "Back", "Back to the table")
881                    .also(&["Stop"])
882                        .more("Back to the table; while every row is being counted, stop that and keep the sample"),
883                ],
884            },
885        ],
886    },
887    Screen {
888        context: Context::SortFilter,
889        title: "Sort and filter",
890        reached: "<kbd>s</kbd> at the table.",
891        groups: &[
892            Group {
893                name: "Sidebar",
894                keys: &[
895                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous field")
896                        .more("Next or previous field, wrapping; a field the form does not offer right now is skipped. The arrows move from the moment the dialog opens"),
897                    k("← / →", "Change", "Tabs on the tab bar; flip a sort; and/or")
898                    .also(&["Tabs", "And/Or"])
899                        .more("On the tab bar: switch Sort & Filter / Columns. On a sort: flip its direction. On a filter: and / or. On a column: step its sort (none, ascending, descending). h/l too"),
900                    k("Space", "Act", "Flip a sort, edit a filter, add one")
901                    .also(&["Flip", "Edit", "Add"])
902                        .more("On a sort: flip its direction. On a filter: edit it (column, operator, value). On \"add sort\": pick a column to sort by, last and ascending. On \"add filter\": a new filter, starting on the table's column cursor. On a column: step its sort"),
903                    k("Enter", "Apply", "Apply and close, from any row")
904                        .more("Apply everything staged and close, from any row (in the filter editor Enter takes the step; Ctrl+J applies)"),
905                    k("Ctrl+J", "Apply", "Apply from anywhere, mid-edit too")
906                        .more("Apply from anywhere, including mid-edit (the row in progress is saved). Ctrl+Enter does the same, on a terminal that tells it from Enter"),
907                    k("Esc", "Cancel", "Close a picker or editor, then the sidebar")
908                        .more("Close an open picker or filter editor; otherwise cancel and close, discarding what is staged. Reopening shows what is applied"),
909                ],
910            },
911            Group {
912                name: "In effect",
913                keys: &[
914                    k("[ / ]", "Move", "Move the sort or filter earlier or later")
915                        .more("Move the focused sort earlier or later in the sort order, or the focused filter in the list"),
916                    k("d / Del", "Remove", "Remove the sort or filter"),
917                    k("C", "Clear", "Remove every sort and filter"),
918                ],
919            },
920            Group {
921                name: "Columns",
922                keys: &[
923                    k("(type)", "Narrow", "Narrow the list, with the find field focused")
924                    .also(&["Find"])
925                        .more("Narrow the column list, when the find field is focused. ↓ from find goes to the list, on the table's column cursor")
926                        .no_run(),
927                    k("PgUp / PgDn, Home / End", "Page", "A page of columns; the first or last")
928                        .more("A page of columns, or the first or last; ↓ stops at the last column"),
929                    k("Space", "Sort", "Cycle the sort: none, ascending, descending")
930                        .more("Cycle the column's sort: none → ascending → descending (← steps back). Each column carries its own direction"),
931                    k("1-9", "Sort place", "Put the column at that place in the sort")
932                        .more("Put the column at that place in the sort order; 0 removes it (a digit past the end of the order says so)")
933                        .run("1"),
934                    k("Del", "Unsort", "Remove the column from the sort"),
935                    k("[ / ]", "Sort order", "Earlier or later in the sort order"),
936                    k("+ / - (= / _)", "Position", "Move the column's display position"),
937                    k("L", "Freeze", "Freeze columns up to this one at the left")
938                        .more("Freeze this column and every column up to it at the left edge; on a column already frozen, pull the boundary back"),
939                    k("v", "Hide", "Show or hide the column")
940                        .more("Show or hide the column (it keeps its place, dimmed)"),
941                    k("< / > (, / .)", "Width", "4 cells narrower or wider")
942                        .more("Make the column 4 cells narrower or wider. A number column is never narrower than its numbers"),
943                    k("f", "Fit", "Fit to the rows on screen")
944                        .more("Fit the column to the rows on screen, its name up to the automatic limit"),
945                    k("w", "Auto width", "Back to the automatic width"),
946                    k("C", "Clear", "Clear staged sort, order, locks, hidden, widths")
947                        .more("Clear the staged sort, order, locks, hidden columns and widths"),
948                ],
949            },
950            Group {
951                name: "Filter editor",
952                keys: &[
953                    k("(type)", "Narrow", "Narrow the column or operator list")
954                        .more("Narrow the column or operator list. The operators are those the column's type takes")
955                        .no_run(),
956                    k("Enter", "Next", "Choose the step; from the value, save the row")
957                    .also(&["Save", "Add"])
958                        .more("Pick the column (type to narrow, Enter chooses), the operator the same way, then type the value and Enter saves the row. Tab and → also choose at the column and operator steps, and so does Space until typing narrows the list (then it types a space); Shift+Tab steps back; ↑ / ↓ move in the lists"),
959                    k("Esc", "Back", "End the edit, and only the edit"),
960                ],
961            },
962        ],
963    },
964    Screen {
965        context: Context::PivotMelt,
966        title: "Pivot and melt",
967        reached: "<kbd>p</kbd> at the table: the form on the left, a live preview of the result on the right (above and below on a narrow terminal).",
968        groups: &[
969            Group {
970                name: "Form",
971                keys: &[
972                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous field")
973                        .more("Next or previous field, wrapping; a field the form does not offer right now is skipped. The arrows move from the moment the builder opens"),
974                    k("← / →", "Change", "Pivot / Melt on the first row; step a choice")
975                        .more("On the first row: switch Pivot and Melt. On the aggregation, strategy or type: the previous or next value. On a single column row: the previous or next column. In a text field: move the cursor. h/l too, outside text fields. The preview follows each change"),
976                    k("Space", "Open", "Open a column picker; next value of a choice")
977                        .more("On a column row: open its picker, scoped to that row; typing narrows it. On a choice: its next value, wrapping"),
978                    k("Enter", "Apply", "Apply the reshape the preview shows")
979                        .more("Apply the reshape the preview shows, to the whole view, from any field"),
980                    k("Esc", "Close", "Close without applying; stop a pivot")
981                        .more("Close without applying; while a pivot is computed, stop it and keep the builder"),
982                ],
983            },
984            Group {
985                name: "Picker",
986                keys: &[
987                    k("(type)", "Narrow", "Narrow the column list").no_run(),
988                    k("↑ / ↓", "Move", "Move; typing narrows"),
989                    k("Enter", "Choose", "Choose; on a several-choice row, done"),
990                    k("Space", "Toggle", "Choose; toggle a column on a several-choice row")
991                        .more("Choose, until typing narrows the list (then it types a space). On a several-choice row: toggle a column in or out"),
992                    k("Esc", "Back", "Back out of the picker, undoing its toggles")
993                        .more("Back out of the picker; the toggles made since it opened are undone (Enter keeps them)"),
994                ],
995            },
996        ],
997    },
998    Screen {
999        context: Context::Chart,
1000        title: "Chart",
1001        reached: "<kbd>c</kbd> at the table: a chart chosen from the cursor column's type.",
1002        groups: &[
1003            Group {
1004                name: "Shelves",
1005                keys: &[
1006                    k("1-7", "Type", "Chart type, in order: Line to Heatmap")
1007                        .more("Switch the chart type directly: Line, Scatter, Bar, Histogram, Box, KDE, Heatmap ([ / ] step). The shelves keep what the new type takes. On Rows, digits type a sample size instead")
1008                        .run("1"),
1009                    k("[ / ]", "Type", "Previous or next chart type"),
1010                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous row")
1011                        .more("Next or previous row of the panel, wrapping (j/k too). A shelf the type does not use is dimmed and skipped"),
1012                    k("Space / Enter", "Act", "Open a shelf's picker, toggle, or step the row")
1013                    .also(&["Pick", "Toggle", "Read"])
1014                        .more("On X, Y or Color: open its picker. On the line under Color: pick the values that get a series, by rows. On an option: toggle it or take its next value. The panel applies as it changes, so Enter acts as Space does, except on Rows: Space switches between Sample and Every row, and Enter reads what the row says"),
1015                    k("← / → (h/l)", "Change", "Step the type, bucket, aggregate or option")
1016                    .also(&["Type", "Bucket", "Aggregate", "Percentile", "Adjust", "Switch", "Order", "Range", "Cumulative"])
1017                        .more("Step the type, the time bucket (day, week, month, quarter, year), the aggregate (count, distinct, sum, mean, median, stdev, quantile, min, max, first, last) and a quantile's percentile, cumulative, bins, range or order; on Rows, switch between Sample and Every row (read on Enter); on a shelf that takes one column, the previous or next column; on the line under Color, turn Other (every value without a series) on or off; flip a toggle"),
1018                    k("+ / -", "Adjust", "Bins or bandwidth"),
1019                    k("0-9", "Size", "On Rows: type a sample size, like 50k or 2m")
1020                        .more("On Rows: type a sample size, like 50000, 50,000, 50k, 250k or 2m. Backspace edits, Enter reads it, Esc puts the row back as it was. A size of at least the table's rows is Every row. Nothing is read until Enter or focus leaves the row")
1021                        .no_run(),
1022                    k("g", "Grid", "Grid on or off")
1023                        .more("Grid on or off at the labeled ticks: Line, Scatter, Histogram, Box and KDE. [analysis] chart_grid sets where it starts"),
1024                    k("Esc", "Back", "Back to the table")
1025                    .also(&["Undo"])
1026                        .more("Back to the table; on Rows with a change waiting, put the row back first"),
1027                ],
1028            },
1029            Group {
1030                name: "Plot",
1031                keys: &[
1032                    k("x", "Crosshair", "Line, Scatter: a crosshair reads out the values")
1033                        .more("Line and Scatter: the plot takes the keys, and a crosshair reads out x and every series' value under the plot. ← / → (h/l) step to the next point or column, Home/End go to the ends; x, Tab or Esc hand the keys back to the panel. A click on the plot puts the crosshair there"),
1034                    k("e", "Export", "Export the chart to PNG, SVG or PDF")
1035                        .more("Export the chart to PNG, SVG or PDF, with a title, notes and source. Needs the chart's shelves filled first"),
1036                    k("t", "New rows", "Draw again with the rows that arrived")
1037                    .also(&["Refresh"])
1038                        .more("While following a file, draw again with the rows that arrived since; the bar says how many"),
1039                ],
1040            },
1041            Group {
1042                name: "Crosshair",
1043                keys: &[
1044                    k("← / →", "Cursor", "Move the crosshair along the plot"),
1045                    k("Tab", "Panel", "Back to the panel, the crosshair kept"),
1046                    k("Esc", "Back", "The crosshair off, back to the panel"),
1047                ],
1048            },
1049            Group {
1050                name: "Picker",
1051                keys: &[
1052                    k("↑ / ↓", "Move", "Move; typing narrows"),
1053                    k("Enter / Space", "Choose", "Choose (Y, Color values: Space toggles one)")
1054                    .also(&["Toggle", "Done"])
1055                        .more("Choose; on a line or scatter chart's Y and on the Color values, Space toggles one in or out (up to 10, fewer on a terminal of fewer colors). Elsewhere Space chooses until typing narrows the list, then types a space"),
1056                    k("Tab / Shift+Tab", "Next", "Choose and move to the next or previous row"),
1057                    k("Esc", "Back", "Back out of the picker alone"),
1058                ],
1059            },
1060            Group {
1061                name: "Export dialog",
1062                keys: &[
1063                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Path, format, style, size, legend, words")
1064                        .more("Next or previous field: Path, Format, Style, Size, Width, Height, Legend, the marks (Opacity and Point size for a scatter, Line width for a line, Y from zero for a line), Title, Description, Notes, Source, Byline, Recipe"),
1065                    k("← / →", "Change", "Step the format, style, size, legend or marks")
1066                        .more("Step the format (PNG, SVG, PDF), the style (Light, Dark, Transparent), the size (Slide 16:9, Document, Square, Single column, Double column, Custom), the legend (line ends, a corner, off), a scatter's point opacity (Auto, 100%, 50%, 20%) and size (Small, Medium, Large), a line's width (Thin, Normal, Bold), Y from zero, or the recipe (Include, Omit). Typing a width or height makes the size Custom"),
1067                    k("Ctrl+P / Ctrl+N", "History", "Earlier or later paths in the path field"),
1068                    k("Enter", "Export", "Export, from anywhere in the dialog")
1069                        .more("Export, from anywhere in the dialog. A path ending .png, .svg or .pdf takes that format; any other gets the format's extension after it. An existing file asks Overwrite / No, starting on No; ←/→ (h/l) or Tab pick, Enter confirms, and declining returns to the filled dialog"),
1070                    k("Esc", "Cancel", "Back to the chart"),
1071                ],
1072            },
1073        ],
1074    },
1075    Screen {
1076        context: Context::Describe,
1077        title: "Analysis: Describe",
1078        reached: "<kbd>a</kbd> at the table.",
1079        groups: &[
1080            Group {
1081                name: "Explore",
1082                keys: &[
1083                    k("Tab / Shift+Tab", "Focus", "Between the results and the tools")
1084                    .also(&["Tools", "Result"]),
1085                    k("↑ / ↓ (j/k)", "Move", "Rows, or the sidebar's tools")
1086                    .also(&["Tools", "Rows"]),
1087                    k("← / → (h/l)", "Scroll", "Scroll the statistics")
1088                    .also(&["Columns"])
1089                        .more("Scroll the statistics; the header counts those out of view"),
1090                    k("Home / End", "First, last", "First or last row"),
1091                    k("PgUp / PgDn", "Page", "A page"),
1092                    k("Enter", "Open", "Open the sidebar's tool")
1093                    .also(&["Detail"])
1094                        .more("Open the sidebar's tool and move into its pane. The first run on a dataset starts in the Sample form, where Enter runs it; later tools reuse that sample. Results last until the view changes: closing and reopening shows them again"),
1095                    k("Esc", "Back", "Cancel a run; the tools; then close")
1096                    .also(&["Cancel", "Tools", "Close"])
1097                        .more("Cancel a run in progress; otherwise from the results back to the tools, and from the tools close the analysis view"),
1098                ],
1099            },
1100            Group {
1101                name: "Sample",
1102                keys: SAMPLE_KEYS,
1103            },
1104        ],
1105    },
1106    Screen {
1107        context: Context::Distribution,
1108        title: "Analysis: Distribution",
1109        reached: "Distribution in the Analysis sidebar.",
1110        groups: &[
1111            Group {
1112                name: "Explore",
1113                keys: &[
1114                    k("↑ / ↓ (j/k)", "Move", "Rows, or the sidebar's tools")
1115                    .also(&["Tools", "Rows"]),
1116                    k("← / → (h/l)", "Scroll", "Scroll the statistics")
1117                    .also(&["Columns"])
1118                        .more("Scroll the statistics; the header counts those out of view"),
1119                    k("Home / End", "First, last", "First or last row"),
1120                    k("PgUp / PgDn", "Page", "A page"),
1121                    k("Tab / Shift+Tab", "Focus", "Between the results and the tools")
1122                    .also(&["Tools", "Result"]),
1123                    k("Enter", "Detail", "Q-Q plot and histogram for the column")
1124                    .also(&["Open"])
1125                        .more("Open detail view for selected column (shows Q-Q plot and histogram); with the sidebar focused, open a tool"),
1126                    k("Esc", "Back", "Cancel a run; the tools; then close")
1127                    .also(&["Cancel", "Tools", "Close"])
1128                        .more("Cancel a run in progress; otherwise from the results back to the tools, and from the tools close the analysis view"),
1129                ],
1130            },
1131            Group {
1132                name: "Sample",
1133                keys: SAMPLE_KEYS,
1134            },
1135        ],
1136    },
1137    Screen {
1138        context: Context::DistributionDetail,
1139        title: "Analysis: Distribution detail",
1140        reached: "<kbd>Enter</kbd> on a column in Distribution.",
1141        groups: &[Group {
1142            name: "Detail",
1143            keys: &[
1144                k("↑ / ↓ (j/k)", "Distribution", "Compare the values with another family"),
1145                k("Home / End", "First, last", "The first or last family"),
1146                k("s", "Scale", "Histogram scale: linear or log"),
1147                k("Esc", "Back", "Back to the distribution table"),
1148            ],
1149        }],
1150    },
1151    Screen {
1152        context: Context::Correlation,
1153        title: "Analysis: Correlation",
1154        reached: "Correlation Matrix in the Analysis sidebar.",
1155        groups: &[
1156            Group {
1157                name: "Explore",
1158                keys: &[
1159                    k("Tab / Shift+Tab", "Focus", "Between the matrix and the tools")
1160                    .also(&["Tools", "Result"]),
1161                    k("↑ / ↓ (j/k)", "Move", "Matrix rows, or the sidebar's tools")
1162                    .also(&["Tools", "Rows"]),
1163                    k("← / → (h/l)", "Column", "Matrix columns")
1164                    .also(&["Columns"]),
1165                    k("Home / End", "Ends", "The first or last pair")
1166                        .more("Jump to the first pair (the first row's second column) or the last (the last row's next-to-last column); the matrix opens on the first"),
1167                    k("PgUp / PgDn", "Page", "A page"),
1168                    k("Enter", "Detail", "The pair's detail (not on the diagonal)")
1169                    .also(&["Open"])
1170                        .more("Open pair detail view (on a cell) or open a tool (sidebar); does nothing on a diagonal cell"),
1171                    k("m", "Method", "Pearson or Spearman, named in the title")
1172                        .more("Method: Pearson r or Spearman ρ, named in the title (both come from the one run, so it reads nothing)"),
1173                    k("Esc", "Back", "Cancel a run; the tools; then close")
1174                    .also(&["Cancel", "Tools", "Close"])
1175                        .more("Cancel a run in progress; otherwise from the matrix back to the tools, and from the tools close the analysis view"),
1176                ],
1177            },
1178            Group {
1179                name: "Sample",
1180                keys: SAMPLE_KEYS,
1181            },
1182        ],
1183    },
1184    Screen {
1185        context: Context::CorrelationDetail,
1186        title: "Analysis: Correlation detail",
1187        reached: "<kbd>Enter</kbd> on a pair in the correlation matrix.",
1188        groups: &[Group {
1189            name: "Detail",
1190            keys: &[
1191                k("m", "Method", "Pearson or Spearman"),
1192                k("Esc", "Back", "Back to the correlation matrix")
1193                    .more("Return to the correlation matrix. Resampling (r) works from the matrix, not from inside this detail"),
1194            ],
1195        }],
1196    },
1197    Screen {
1198        context: Context::DataQuality,
1199        title: "Analysis: Data Quality",
1200        reached: "Data Quality in the Analysis sidebar.",
1201        groups: &[
1202            Group {
1203                name: "Setup",
1204                keys: &[
1205                    k("↑ / ↓, Tab", "Move", "Move between rows")
1206                    .also(&["Row"]),
1207                    k("← / →", "Choose", "Change a short list's choice")
1208                    .also(&["Change"]),
1209                    k("Space", "Open", "Open the row's form or list")
1210                    .also(&["Sample", "Choose", "Time roles", "Intervals", "Expected", "Intent"])
1211                        .more("Open the row: the Sample form, a list (type to narrow; Enter chooses, and Space until typing narrows it), Time roles, Intervals, Column intent or Expected"),
1212                    k("s", "Sample", "The Sample form")
1213                        .more("The Sample form; its Enter applies to Setup and returns there"),
1214                    k("p", "Access", "The access plan: what a run reads"),
1215                    k("d", "Release", "Release kept rows and the local copy")
1216                    .also(&["Release rows"])
1217                        .more("Release the rows runs kept and a full scan's local copy, named on the Read rule; the next run that would reuse them reads again"),
1218                    k("Enter", "Run", "Run, from any row")
1219                        .more("Run, from any row. A full read asks first; the report on screen or in the session cache is shown, not read again"),
1220                    k("Esc", "Discard", "Discard every staged edit")
1221                    .also(&["Back"]),
1222                ],
1223            },
1224            Group {
1225                name: "Setup lists",
1226                keys: &[
1227                    k("↑ / ↓", "Move", "Choose the role, pair, column or row")
1228                    .also(&["Role", "Field", "Column", "Pair"])
1229                        .more("Time roles: choose the role. Intervals: choose the pair. Column intent: choose the column. Expected: Windows, From, Before (Tab too)"),
1230                    k("← / →", "Choose", "Time roles: its column; Expected: windows")
1231                    .also(&["Column", "Windows"])
1232                        .more("Time roles: choose the role's column. Expected: choose the windows. Intervals: measure the pair or not"),
1233                    k("Space", "Toggle", "Intervals: measure or not; intent: its form")
1234                    .also(&["Declare"])
1235                        .more("Intervals: measure the pair or not. Column intent: declare the column's intent in a form"),
1236                    k("Enter", "Done", "Done"),
1237                    k("Esc", "Undo", "Put the list back as it was")
1238                    .also(&["Cancel"]),
1239                ],
1240            },
1241            Group {
1242                name: "Forms",
1243                keys: &[
1244                    k("Tab / Shift+Tab", "Next", "Next or previous field"),
1245                    k("← / →", "Change", "Change the field's choice")
1246                        .also(&["Format", "Reading"]),
1247                    k("Space", "Toggle", "Toggle a checkbox"),
1248                    k("Enter", "Apply", "Apply the form; export the report")
1249                        .also(&["Export"]),
1250                    k("Esc", "Cancel", "Close the form unchanged"),
1251                ],
1252            },
1253            Group {
1254                name: "Popups",
1255                keys: &[
1256                    k("↑ / ↓", "Scroll", "Scroll a popup, or move in its list")
1257                        .also(&["Move"]),
1258                    k("(type)", "Narrow", "Narrow a popup's list").no_run(),
1259                    k("Enter", "Close", "Close a popup, or act on its finding")
1260                        .also(&["Read", "Choose", "Fewer checks", "All checks", "Show rows", "Read rows"])
1261                        .more("Close a popup, or act on what it shows: a finding's rows (shown when the run kept them, else read), its checks all or fewer, a list's choice"),
1262                    k("Esc", "Back", "Close a popup or a list unchanged")
1263                        .also(&["Cancel", "Close"]),
1264                ],
1265            },
1266            Group {
1267                name: "Report",
1268                keys: &[
1269                    k("← / → (h/l)", "Page", "Previous or next page"),
1270                    k("1 - 5", "Page", "Overview, Columns, Segments, Trends, Intervals")
1271                        .run("1"),
1272                    k("↑ / ↓ (j/k)", "Move", "Move, or scroll a tall finding")
1273                    .also(&["Bar", "Tools"]),
1274                    k("PgUp / PgDn", "Page", "A page; Home / End the ends")
1275                        .more("Page; Home/End jump to either end"),
1276                    k("Enter", "Details", "Open a finding, then its rows")
1277                    .also(&["Open", "Inspect", "Columns", "Segments", "Trends", "Show rows", "Read rows", "Set grain", "Time roles", "Intervals"])
1278                        .more("Open a finding, then its rows. On an empty page, open the setting it needs"),
1279                    k("c / t", "Only", "Overview: one column's or type's findings")
1280                    .also(&["Column", "Type"])
1281                        .more("Overview: only one column's or one type's findings"),
1282                    k("o", "Order", "Overview: ranked, by rows, by rate")
1283                    .also(&["Ranked", "By rows", "By rate"]),
1284                    k("e", "Setup", "Setup"),
1285                    k("s", "Sample", "Setup, with the Sample form open"),
1286                    k("v", "Sample rows", "View the sample's rows; Esc returns"),
1287                    k("p", "Access", "The access plan: what a run reads"),
1288                    k("r", "Resample", "On a sample, run again with a new seed"),
1289                    k("x", "Export", "Export the report to JSON or Markdown")
1290                        .more("Export the report to JSON or Markdown; nothing is read"),
1291                    k("Tab / Shift+Tab", "Focus", "Between the result and the tools")
1292                    .also(&["Result"]),
1293                    k("Esc", "Back", "Back one level: all findings, the tools, close")
1294                    .also(&["Cancel", "All findings", "Tools", "Close"])
1295                        .more("Back one level: all findings again, then the tools, then close"),
1296                ],
1297            },
1298            Group {
1299                name: "Segments",
1300                keys: &[
1301                    k("Enter", "Details", "The segment's columns beside its comparison")
1302                        .more("A segment's columns beside the one it is compared with, largest change first"),
1303                    k("o", "Order", "Largest change first, or back in order")
1304                    .also(&["In order", "By change"]),
1305                    k("b", "Baseline", "Compare with the highlighted segment"),
1306                ],
1307            },
1308            Group {
1309                name: "Trends",
1310                keys: &[
1311                    k("Enter", "Details", "A line's bars, with rate and interval")
1312                    .also(&["Trends"])
1313                        .more("A line's bars: span, segments, rows sampled of counted, rate, 95% interval, and the bar before. ↑ / ↓ there: the next bar"),
1314                    k("m", "Measure", "Next measure"),
1315                    k("w", "Coarser", "Stage a coarser window in Setup")
1316                        .more("Stage a coarser window in Setup, for segments the sample reached thinly or not at all"),
1317                    k("g", "Gaps", "The expected windows with no rows")
1318                        .more("The expected windows with no rows: empty by exact count, not sampled, or out of scope"),
1319                    k("Esc", "Back", "Back to Trends"),
1320                ],
1321            },
1322            Group {
1323                name: "Intervals",
1324                keys: &[
1325                    k("Enter", "Details", "An interval's detail; again, its rows")
1326                    .also(&["Show rows", "Read rows"])
1327                        .more("An interval's detail: its ends, the rows with both, missing and unread ends, negative and zero durations, percentiles and breaches. Enter there shows the rows behind the count under the cursor: a sample's from the rows the run kept"),
1328                    k("Esc", "Back", "Back to the list"),
1329                ],
1330            },
1331        ],
1332    },
1333    Screen {
1334        context: Context::Export,
1335        title: "Export",
1336        reached: "<kbd>e</kbd> at the table.",
1337        groups: &[
1338            Group {
1339                name: "Form",
1340                keys: &[
1341                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous field")
1342                        .more("Next or previous field, wrapping; the fields follow the format. The dialog opens on Path, and the arrows move from there"),
1343                    k("← / →", "Change", "Step the format or compression; move the cursor")
1344                    .also(&["Format"])
1345                        .more("On Format or Compression: the previous or next value, along the Format row (h/l too). On Header or Source file: toggle. In Path and Delimiter: move the cursor"),
1346                    k("Space", "Act", "Toggle a checkbox; next format or compression")
1347                    .also(&["Toggle"])
1348                        .more("Toggle a checkbox (Header, Source file); on Format or Compression, the next value, wrapping"),
1349                    k("Ctrl+P / Ctrl+N", "History", "Earlier or later paths in the path field")
1350                        .more("In the path field: the paths exported to before, earlier or later (↑ and ↓ move between fields)"),
1351                    k("Enter", "Export", "Export, from anywhere in the form")
1352                        .more("Export, from anywhere in the form. On a blank path the form says \"Enter a file path.\" instead of exporting"),
1353                    k("Esc", "Cancel", "Close without exporting"),
1354                ],
1355            },
1356            Group {
1357                name: "File exists",
1358                keys: &[
1359                    k("← / → (h/l)", "Pick", "Pick Overwrite or No (Tab too)"),
1360                    k("Enter", "Confirm", "Confirm the one picked"),
1361                    k("Esc", "No", "Decline: back to the filled form"),
1362                ],
1363            },
1364        ],
1365    },
1366    Screen {
1367        context: Context::Copy,
1368        title: "Copy",
1369        reached: "<kbd>y</kbd> at the table.",
1370        groups: &[
1371            Group {
1372                name: "Form",
1373                keys: &[
1374                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous row"),
1375                    k("← / →", "Change", "Step the scope, column or format")
1376                        .more("The previous or next scope, column or format (h/l too); on Header: toggle"),
1377                    k("Space", "Act", "Next scope or format; pick a column; toggle")
1378                    .also(&["Toggle", "Pick"])
1379                        .more("On Scope or Format: the next value, wrapping. On Column: open its picker. On Header: toggle"),
1380                    k("Enter", "Copy", "Copy, from anywhere in the form")
1381                        .more("Copy, from anywhere in the form. On the Cell scope with no column picked, Enter re-accents the spec line instead of copying"),
1382                    k("Esc", "Cancel", "Close a picker, then the dialog")
1383                        .more("Close a picker, then the dialog, without copying"),
1384                ],
1385            },
1386            Group {
1387                name: "Picker",
1388                keys: &[
1389                    k("(type)", "Narrow", "Narrow the list").no_run(),
1390                    k("↑ / ↓", "Move", "Move the cursor (j/k narrow)")
1391                        .more("Move the cursor (j/k narrow the picker; only ↑/↓ move there)"),
1392                    k("Enter / Space", "Choose", "Choose")
1393                        .more("Choose. Space chooses until typing narrows the list, then types a space, so a name of several words narrows"),
1394                    k("Tab / Shift+Tab", "Next", "Choose and move on"),
1395                    k("Esc", "Back", "Back to the form, the choice unchanged"),
1396                ],
1397            },
1398        ],
1399    },
1400    Screen {
1401        context: Context::Views,
1402        title: "Views",
1403        reached: "<kbd>v</kbd> at the table.",
1404        groups: &[
1405            Group {
1406                name: "List",
1407                keys: &[
1408                    k("↑ / ↓ (j/k)", "Move", "Move in the list"),
1409                    k("Enter", "Apply", "Apply the selected view"),
1410                    k("s", "Save", "Save the current state as a view")
1411                        .more("Save the current state as a view (an untouched table has nothing to save, and s says so)"),
1412                    k("e", "Edit", "Edit the selected view"),
1413                    k("d", "Delete", "Delete the selected view, after confirming"),
1414                    k("i", "Score", "How the view's score was computed")
1415                        .more("Show how the selected view's score was computed (Esc closes the score view)"),
1416                    k("Esc", "Close", "Close"),
1417                ],
1418            },
1419            Group {
1420                name: "Save and edit",
1421                keys: &[
1422                    k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous row")
1423                        .more("Next or previous row. In the description ↑ / ↓ move between its lines, and leave it from the first or last"),
1424                    k("Enter", "Save", "Save (in the description, Enter types)")
1425                        .more("Save, from any row. In the description Enter types: Ctrl+J saves from there"),
1426                    k("Ctrl+J", "Save", "Save from anywhere, the description too")
1427                        .more("Save from anywhere, the description included; so does Ctrl+Enter, on a terminal that tells it from Enter"),
1428                    k("PgUp / PgDn", "Lines", "Five lines in the description"),
1429                    k("Space", "Toggle", "Expand Matching; toggle schema match")
1430                    .also(&["Collapse", "Expand"])
1431                        .more("Expand or collapse Matching; toggle schema match"),
1432                    k("Esc", "Cancel", "Back to the list, discarding edits"),
1433                ],
1434            },
1435            Group {
1436                name: "Delete",
1437                keys: &[
1438                    k("← / → (h/l)", "Pick", "Pick Delete or No (Tab too); it starts on No"),
1439                    k("Enter", "Confirm", "Confirm the one picked"),
1440                    k("Esc", "No", "Keep the view"),
1441                ],
1442            },
1443        ],
1444    },
1445    Screen {
1446        context: Context::FormatPicker,
1447        title: "Format picker",
1448        reached: "<kbd>b</kbd> at a table read through a format spec.",
1449        groups: &[Group {
1450            name: "Pick",
1451            keys: &[
1452                k("(type)", "Narrow", "Narrow to the names that contain it").no_run(),
1453                k("↑ / ↓", "Move", "Move"),
1454                k("Enter / Space", "Read", "Read the file again with the spec")
1455                    .more("Read the file again with the spec chosen. The query, filters and sort are cleared"),
1456                k("Backspace", "Delete", "Delete a character (Ctrl+W a word, Ctrl+U all)"),
1457                k("Esc", "Cancel", "Close and keep the format"),
1458            ],
1459        }],
1460    },
1461    Screen {
1462        context: Context::Retype,
1463        title: "Column type",
1464        reached: "<kbd>Enter</kbd> on the Info panel's Schema tab, or Change type in the cell menu.",
1465        groups: &[Group {
1466            name: "Pick",
1467            keys: &[
1468                k("(type)", "Narrow", "Narrow the list; a format typed is the format").no_run()
1469                    .more("Narrow the list to the names that contain it. In the format list, a strftime format typed that no line holds is the format"),
1470                k("↑ / ↓", "Move", "Move"),
1471                k("Enter", "Choose", "The type, or its format")
1472                    .more("The type: the column reads as it at once, a value that does not fit null. A date, time or datetime asks its format next, each line showing what it makes of the column's first value. as read takes the type away"),
1473                k("Backspace", "Delete", "Delete a character (Ctrl+W a word, Ctrl+U all)"),
1474                k("Esc", "Back", "Back to the types, or close")
1475                    .also(&["Cancel"]),
1476            ],
1477        }],
1478    },
1479    Screen {
1480        context: Context::Combine,
1481        title: "Combine into datetime",
1482        reached: "Combine into datetime in the cell menu, on a text, date or time column.",
1483        groups: &[
1484            Group {
1485            name: "Fields",
1486            keys: &[
1487                k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous field"),
1488                k("Space", "Pick", "Pick a column, or step the kind"),
1489                k("← / →", "Change", "Step the kind: datetime, date or time"),
1490                k("Enter", "Make", "Make the column")
1491                    .more("Make the column, before the first column it is made from, as a format spec's derived column is: a date and a time, and a UTC offset, make a datetime in UTC"),
1492                k("Esc", "Cancel", "Cancel"),
1493            ],
1494        },
1495        Group {
1496            name: "Picker",
1497            keys: &[
1498                k("(type)", "Narrow", "Narrow to the columns that contain it").no_run(),
1499                k("↑ / ↓", "Move", "Move"),
1500                k("Enter", "Choose", "Choose the column"),
1501                k("Esc", "Back", "Back to the fields, the choice unchanged"),
1502            ],
1503        }],
1504    },
1505    Screen {
1506        context: Context::TablePicker,
1507        title: "Table picker",
1508        reached: "<kbd>T</kbd> at a table of a file of several.",
1509        groups: &[Group {
1510            name: "Pick",
1511            keys: &[
1512                k("(type)", "Narrow", "Narrow to the names that contain it").no_run(),
1513                k("↑ / ↓", "Move", "Move"),
1514                k("Enter", "Open", "Open the table in place of this one")
1515                    .more("Open the table chosen in place of this one. The query, filters and sort are cleared"),
1516                k("Backspace", "Delete", "Delete a character (Ctrl+W a word, Ctrl+U all)"),
1517                k("Esc", "Cancel", "Close and keep the table"),
1518            ],
1519        }],
1520    },
1521    Screen {
1522        context: Context::Sample,
1523        title: "Sample",
1524        reached: "<kbd>S</kbd> at the table.",
1525        groups: &[Group {
1526            name: "Form",
1527            keys: &[
1528                k("Tab / Shift+Tab (↑ / ↓)", "Next", "Next or previous row")
1529                    .also(&["Row", "Tools", "Sample"]),
1530                k("← / →", "Change", "Step Rows from, Method, Per value of")
1531                    .more("Step Rows from, Method and Per value of; Method's No sample takes the view's sample away"),
1532                k("(type)", "Edit", "Type a size (50k, 2m), a seed, rows, values")
1533                    .more("Type into the focused row: the size (50000, 50k, 2m), the seed, a row range, partition values or file numbers")
1534                    .no_run(),
1535                    k("PgUp / PgDn", "Files", "Page through the files, where there are many"),
1536                k("Enter", "Draw", "Draw the sample; again past a memory warning")
1537                    .also(&["Clear", "Draw anyway", "Run", "Apply"])
1538                    .more("Draw the sample: the table shows its rows as they arrive, and the query, filters and sort run over them. When the estimate is more than the memory available now (or analysis.sample_memory_limit), the form says so; Enter again draws anyway"),
1539                k("Esc", "Cancel", "Close; the view's sample stays as it was")
1540                    .also(&["Back"]),
1541            ],
1542        }],
1543    },
1544    Screen {
1545        context: Context::Hex,
1546        title: "Hex view",
1547        reached: "`datui --hex FILE`, <kbd>Ctrl</kbd>+<kbd>X</kbd> on the home screen, or <kbd>x</kbd> in the Info panel.",
1548        groups: &[
1549            Group {
1550                name: "Explore",
1551                keys: &[
1552                    k("← / → (h/l)", "Byte", "A byte"),
1553                    k("↑ / ↓ (j/k)", "Row", "A row"),
1554                    k("w / b", "Group", "The next group of four, or back one"),
1555                    k("0 / $", "Row ends", "The start or end of the row"),
1556                    k("g / G", "File ends", "Start or end of the file (Home / End too)")
1557                        .more("The start or end of the file (Home and End too)"),
1558                    k("PgUp / PgDn", "Page", "A page (Ctrl+B / F; Ctrl+U / D half)")
1559                        .more("A page (Ctrl+B/F too; Ctrl+U/D half a page)"),
1560                    k(":", "Go to", "Go to an offset: 4096, 0x1000, +16, e-8")
1561                    .also(&["Offset"])
1562                        .more("Go to an offset: 4096 or 0x1000; +16 or -16 from the cursor; e-8 for the eighth byte from the end"),
1563                ],
1564            },
1565            Group {
1566                name: "Find",
1567                keys: &[
1568                    k("f", "Find", "Find text or bytes (de ad, 0x1acf, ?? any)")
1569                        .more("Find bytes. Text is found as its UTF-8 bytes (Ctrl+U in the prompt: as UTF-16 little-endian). 0x1acffc1d, or two or more hex pairs (de ad be ef), is a byte pattern, where ?? matches any byte. Text in double quotes is text, even when it looks like hex. A match may span rows"),
1570                    k("n / N", "Next, previous", "Next or previous match, round the end")
1571                    .also(&["Next", "Prev"])
1572                        .more("The next or previous match, round the end of the file"),
1573                    k("R", "Stride", "Bytes per row from the matches' spacing")
1574                    .also(&["Use stride"])
1575                        .more("When the matches after the one found are all the same distance apart, make that the bytes per row"),
1576                    k("Esc", "Stop", "Stop a find that is reading")
1577                    .also(&["Cancel"]),
1578                ],
1579            },
1580            Group {
1581                name: "Prompt",
1582                keys: &[
1583                    k("Enter", "Find", "Find, go to the offset or set the row size")
1584                        .also(&["Go", "Set"]),
1585                    k("Ctrl+U", "UTF-16", "Find the text as UTF-16 as well"),
1586                    k("Esc", "Cancel", "Close the prompt"),
1587                ],
1588            },
1589            Group {
1590                name: "Display",
1591                keys: &[
1592                    k("r", "Row size", "Bytes per row; empty: as many as fit")
1593                        .more("Bytes per row, so that records line up; empty goes back to as many as fit. --hex-width N sets it on the command line"),
1594                    k("#", "Offsets", "Offsets in decimal or hex")
1595                    .also(&["Hex", "Decimal"]),
1596                    k("i / Enter", "Inspector", "Show or hide the byte inspector")
1597                        .more("Show or hide the byte inspector. Beside the bytes when there is room for it and 16 bytes a row, over them when there is not"),
1598                    k("v", "Mark", "Mark a range from the cursor; again to unmark")
1599                    .also(&["Unmark"])
1600                        .more("Mark from the cursor; move to mark a range, and the status line counts it. v again, or Esc, unmarks"),
1601                ],
1602            },
1603            Group {
1604                name: "Go",
1605                keys: &[
1606                    k("B", "Format spec", "Read the file with a format spec instead")
1607                    .also(&["Format"])
1608                        .more("Read the file with a format spec instead: type to narrow the list of specs; Enter chooses, and Space until typing narrows it"),
1609                    k("Esc", "Back", "Back to the Info panel or home")
1610                        .more("Back to the table, when opened from the Info panel; back home, when opened from there"),
1611                    k("q", "Back", "Home, when opened from there; else quit")
1612                    .also(&["Home", "Quit"]),
1613                ],
1614            },
1615        ],
1616    },
1617];
1618
1619/// The screen for `context`.
1620pub fn screen(context: Context) -> &'static Screen {
1621    SCREENS
1622        .iter()
1623        .find(|s| s.context == context)
1624        .expect("every context has a screen")
1625}
1626
1627/// The entry for `keys` on `context`'s screen, or in `group` of it when named: what
1628/// the footer's hints read their labels from.
1629pub fn lookup(context: Context, group: Option<&str>, keys: &str) -> Option<&'static Key> {
1630    let groups: &'static [Group] = match context {
1631        Context::Global => std::slice::from_ref(&GLOBAL),
1632        Context::Help => std::slice::from_ref(&HELP),
1633        Context::Question => std::slice::from_ref(&QUESTION),
1634        _ => screen(context).groups,
1635    };
1636    let entries = || {
1637        groups
1638            .iter()
1639            .filter(move |g| group.is_none_or(|name| g.name == name))
1640            .flat_map(|g| g.keys.iter())
1641    };
1642    // As written, or the entry whose keys include every key named: a hint may offer
1643    // `d` of `d / Del`, or `↑ / ↓` of `↑ / ↓ (j/k)`.
1644    let wanted = chords(keys);
1645    entries().find(|k| k.keys == keys).or_else(|| {
1646        (!wanted.is_empty())
1647            .then(|| entries().find(|k| wanted.iter().all(|c| chords(k.keys).contains(c))))
1648            .flatten()
1649    })
1650}
1651
1652/// Every key entry with its screen and group, in reference order; [`GLOBAL`], [`HELP`]
1653/// and [`QUESTION`] first.
1654pub fn entries() -> impl Iterator<Item = (Option<&'static Screen>, &'static Group, &'static Key)> {
1655    [&GLOBAL, &HELP, &QUESTION]
1656        .into_iter()
1657        .flat_map(|group| group.keys.iter().map(move |key| (None, group, key)))
1658        .chain(SCREENS.iter().flat_map(|screen| {
1659            screen
1660                .groups
1661                .iter()
1662                .flat_map(move |group| group.keys.iter().map(move |key| (Some(screen), group, key)))
1663        }))
1664}
1665
1666/// Escape text for a markdown table cell.
1667fn cell(text: &str) -> String {
1668    text.replace('|', "\\|")
1669        .replace('<', "&lt;")
1670        .replace('>', "&gt;")
1671}
1672
1673/// A key label as markdown: code, so `[` and `*` read as themselves.
1674fn key_cell(label: &str) -> String {
1675    if label.contains('`') {
1676        format!("`` {} ``", label.replace('|', "\\|"))
1677    } else {
1678        format!("`{}`", label.replace('|', "\\|"))
1679    }
1680}
1681
1682fn markdown_table(out: &mut String, keys: &[Key]) {
1683    out.push_str("\n| Key | Action |\n|---|---|\n");
1684    for key in keys {
1685        out.push_str(&format!(
1686            "| {} | {} |\n",
1687            key_cell(key.keys),
1688            cell(key.long())
1689        ));
1690    }
1691}
1692
1693/// The keyboard reference: the keys every screen takes, then each screen's.
1694pub fn render_markdown() -> String {
1695    let mut out = String::new();
1696    out.push_str("\n## Every screen\n\nThese keys work on every screen.\n");
1697    markdown_table(&mut out, GLOBAL.keys);
1698    out.push_str("\n## Help\n\n<kbd>?</kbd> or <kbd>F1</kbd>.\n");
1699    markdown_table(&mut out, HELP.keys);
1700    out.push_str("\n## Question\n\nWhen datui asks before acting.\n");
1701    markdown_table(&mut out, QUESTION.keys);
1702    for screen in SCREENS {
1703        out.push_str(&format!("\n## {}\n\n{}\n", screen.title, screen.reached));
1704        for group in screen.groups {
1705            out.push_str(&format!("\n### {} · {}\n", screen.title, group.name));
1706            markdown_table(&mut out, group.keys);
1707        }
1708    }
1709    out
1710}
1711
1712#[cfg(test)]
1713mod tests {
1714    use super::*;
1715
1716    #[test]
1717    fn first_keys_are_read() {
1718        for (keys, first) in [
1719            ("↑ / ↓ (j/k)", "↑"),
1720            ("Ctrl+D / Ctrl+U", "Ctrl+D"),
1721            ("PgUp/PgDn", "PgUp"),
1722            ("/", "/"),
1723            ("+ / - (= / _)", "+"),
1724            ("e, w, y, o", "e"),
1725            ("Enter (d / D)", "Enter"),
1726            ("↑ / ↓, Tab", "↑"),
1727            ("Click a key", "Click"),
1728        ] {
1729            assert_eq!(first_key(keys), first, "{keys}");
1730        }
1731    }
1732
1733    #[test]
1734    fn chords_are_read() {
1735        let c = chord("Ctrl+O").unwrap();
1736        assert!(c.ctrl && !c.shift && c.code == Code::Char('o'));
1737        assert_eq!(chord("G").unwrap().code, Code::Char('G'));
1738        assert!(chord("G").unwrap().shift);
1739        assert_eq!(chord("Shift+Tab").unwrap().code, Code::BackTab);
1740        assert_eq!(chord("F1").unwrap().code, Code::F(1));
1741        assert_eq!(chord("↓").unwrap().code, Code::Down);
1742        assert_eq!(chord("Space").unwrap().code, Code::Char(' '));
1743        assert_eq!(chord("+").unwrap().code, Code::Char('+'));
1744        assert!(chord("Click").is_none());
1745        assert!(chord("(type)").is_none());
1746        assert!(chord("1-9").is_none());
1747        let codes: Vec<Code> = chords("↑ / ↓ (j/k)").iter().map(|c| c.code).collect();
1748        assert_eq!(
1749            codes,
1750            [Code::Up, Code::Down, Code::Char('j'), Code::Char('k')]
1751        );
1752        assert_eq!(chords("PgUp/PgDn").len(), 2);
1753        assert_eq!(chords("/")[0].code, Code::Char('/'));
1754        assert!(chords("(type)").is_empty());
1755    }
1756
1757    /// Every entry's Enter presses a key, unless it says it presses none; every line
1758    /// is one line, short enough for half the help; every label is three words at most.
1759    #[test]
1760    fn every_entry_is_whole() {
1761        let mut bad = Vec::new();
1762        for (screen, group, key) in entries() {
1763            let at = format!(
1764                "{} · {} · {}",
1765                screen.map_or("Global", |s| s.title),
1766                group.name,
1767                key.keys
1768            );
1769            if key.run != Run::Never && key.action().is_none() {
1770                bad.push(format!("{at}: Enter presses nothing; .run() or .no_run()"));
1771            }
1772            if key.line.contains('\n') || key.line.chars().count() > 52 {
1773                bad.push(format!("{at}: line longer than 52: {}", key.line));
1774            }
1775            for label in std::iter::once(&key.label).chain(key.also) {
1776                if label.is_empty() || label.split(' ').count() > 3 {
1777                    bad.push(format!("{at}: label {label:?}"));
1778                }
1779            }
1780            if key.line.ends_with('.') || key.more.is_some_and(|m| m.ends_with('.')) {
1781                bad.push(format!("{at}: ends with a period"));
1782            }
1783            if key.more == Some(key.line) {
1784                bad.push(format!("{at}: more repeats the line"));
1785            }
1786        }
1787        assert!(bad.is_empty(), "{}", bad.join("\n"));
1788    }
1789
1790    #[test]
1791    fn every_context_has_one_screen() {
1792        use std::collections::HashSet;
1793        let contexts: HashSet<_> = SCREENS.iter().map(|s| s.context).collect();
1794        assert_eq!(contexts.len(), SCREENS.len(), "a context is listed twice");
1795        for screen in SCREENS {
1796            assert!(!screen.groups.is_empty(), "{} has no keys", screen.title);
1797            let mut names = HashSet::new();
1798            for group in screen.groups {
1799                assert!(
1800                    names.insert(group.name),
1801                    "{}: {} twice",
1802                    screen.title,
1803                    group.name
1804                );
1805                assert!(!group.keys.is_empty());
1806            }
1807        }
1808    }
1809}