playr 0.4.0

A minimal TUI music player that plays local files and contacts nothing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! `:` commands: parsing a command line into an [`Action`], and the prompt
//! that edits one, with Tab completion and a history recalled by the arrows.

use std::time::Duration;

use super::action::{Action, Key};
use super::View;
use crate::audio::Mode;

/// A `:` command: its name, what may follow it, what it does, and the one
/// view it works in, if it is not every view.
pub struct Command {
    pub name: &'static str,
    pub args: &'static str,
    pub help: &'static str,
    pub view: Option<View>,
}

const fn any(name: &'static str, args: &'static str, help: &'static str) -> Command {
    Command {
        name,
        args,
        help,
        view: None,
    }
}

const fn only(view: View, name: &'static str, args: &'static str, help: &'static str) -> Command {
    Command {
        name,
        args,
        help,
        view: Some(view),
    }
}

use View::{Library, Playlists, Selection};

/// Every `:` command, grouped by view. A command may be typed as any prefix
/// that names only it among those that work in the current view.
pub const COMMANDS: &[Command] = &[
    any("help", "", "list these commands"),
    any("keys", "", "list the keys"),
    any("quit", "", "quit"),
    any("view", "VIEW", "library, selection or playlists"),
    any("next-view", "", "switch to the next view"),
    any("down", "[N]", "move the cursor down N rows, default 1"),
    any("up", "[N]", "move the cursor up N rows, default 1"),
    any("first", "", "move the cursor to the first row"),
    any("last", "", "move the cursor to the last row"),
    any("play", "", "play the list in view from the cursor"),
    any("search", "[QUERY]", "search the library; no query opens /"),
    any("playlist", "NAME", "play a saved playlist"),
    any("save", "[NAME]", "save the selection as a playlist"),
    any("pause", "", "play or pause"),
    any("next", "", "next track"),
    any("prev", "", "previous track"),
    any("stop", "", "stop"),
    any(
        "seek",
        "TIME | +TIME | -TIME",
        "seek to a time, or by one: 1:23, +10",
    ),
    any(
        "volume",
        "PERCENT | +N | -N",
        "set the volume, or change it: 60, +10",
    ),
    any(
        "speed",
        "N | +N | -N",
        "set varispeed in semitones, or change it",
    ),
    any(
        "mode",
        "MODE | + | -",
        "normal, shuffle, repeat, repeat-one; or cycle",
    ),
    any("mark", "[TIME]", "mark the playing position, or a time"),
    any("unmark", "", "undo the last mark"),
    any("delmarks", "", "clear all marks in this track; asks y/n"),
    any("next-mark", "", "seek to the next mark"),
    any("prev-mark", "", "seek to the previous mark"),
    any(
        "map",
        "[VIEW] KEY COMMAND",
        "bind a key, in one view or in all",
    ),
    any("unmap", "[VIEW] KEY", "remove a key binding"),
    only(Library, "toggle", "", "select or unselect the track"),
    only(Library, "clear-search", "", "show the whole library again"),
    only(
        Selection,
        "remove",
        "",
        "remove the track from the selection",
    ),
    only(Selection, "move", "+N | -N", "move the track N places"),
    only(Selection, "clear", "", "empty the selection; asks y/n"),
    only(
        Playlists,
        "add",
        "",
        "add the playlist's tracks to the selection",
    ),
    only(Playlists, "delete", "", "delete the playlist; asks y/n"),
    only(Playlists, "rename", "[NAME]", "rename the playlist"),
];

const MODES: &[(&str, Mode)] = &[
    ("normal", Mode::Normal),
    ("shuffle", Mode::Shuffle),
    ("repeat", Mode::Repeat),
    ("repeat-one", Mode::RepeatOne),
];

const VIEWS: &[(&str, View)] = &[
    ("library", Library),
    ("selection", Selection),
    ("playlists", Playlists),
];

/// The name of `view` as commands spell it.
pub fn view_name(view: View) -> &'static str {
    VIEWS.iter().find(|v| v.1 == view).expect("every view").0
}

/// The one name among `names` that is `word` or starts with it.
///
/// An exact match wins over longer names it prefixes, so `repeat` is not
/// ambiguous with `repeat-one`.
fn resolve<'a>(
    word: &str,
    names: impl Iterator<Item = &'a str> + Clone,
    what: &str,
) -> Result<&'a str, String> {
    if let Some(exact) = names.clone().find(|n| *n == word) {
        return Ok(exact);
    }
    let matches: Vec<&str> = names.filter(|n| n.starts_with(word)).collect();
    match matches.as_slice() {
        [one] => Ok(one),
        [] => Err(format!("unknown {what}: {word}")),
        many => Err(format!("ambiguous {what} {word}: {}", many.join(", "))),
    }
}

/// The commands that work in `view`, or in every view when `view` is `None`.
fn usable(view: Option<View>) -> impl Iterator<Item = &'static Command> + Clone {
    COMMANDS
        .iter()
        .filter(move |c| c.view.is_none_or(|v| Some(v) == view))
}

/// The command `word` names in `view`.
///
/// A command from another view is an error naming that view, whether typed in
/// full or as a prefix that matches nothing here.
fn resolve_command(word: &str, view: Option<View>) -> Result<&'static Command, String> {
    let elsewhere = |c: &Command| {
        let there = c.view.expect("usable in every view");
        format!(":{} works in the {} view", c.name, view_name(there))
    };
    if let Some(c) = COMMANDS.iter().find(|c| c.name == word) {
        return if usable(view).any(|u| u.name == c.name) {
            Ok(c)
        } else {
            Err(elsewhere(c))
        };
    }
    let find = |name: &str| COMMANDS.iter().find(|c| c.name == name).expect("resolved");
    match resolve(word, usable(view).map(|c| c.name), "command") {
        Ok(name) => Ok(find(name)),
        Err(e) if e.starts_with("unknown") => {
            match resolve(word, COMMANDS.iter().map(|c| c.name), "command") {
                Ok(name) => Err(elsewhere(find(name))),
                Err(_) => Err(e),
            }
        }
        Err(e) => Err(e),
    }
}

/// A number without a fractional part when it has none: `5`, `2.5`.
fn number(n: f64) -> String {
    let rounded = (n * 1000.0).round() / 1000.0;
    format!("{rounded}")
}

/// The command line that performs `action` in `view`: the inverse of [`parse`].
pub fn line(action: &Action, view: Option<View>) -> String {
    use Action::*;
    let time = |d: &Duration| number(d.as_secs_f64());
    match action {
        Quit => "quit".into(),
        Help => "keys".into(),
        CommandHelp => "help".into(),
        ShowView(v) => format!("view {}", view_name(*v)),
        NextView => "next-view".into(),
        Cursor(1) => "down".into(),
        Cursor(-1) => "up".into(),
        Cursor(n) if *n > 0 => format!("down {n}"),
        Cursor(n) => format!("up {}", -n),
        CursorFirst => "first".into(),
        CursorLast => "last".into(),
        StartSearch => "search".into(),
        Search(q) => format!("search {q}"),
        ClearSearch => "clear-search".into(),
        StartCommand => "command".into(),
        Activate => "play".into(),
        Add if view == Some(Library) => "toggle".into(),
        Add => "add".into(),
        Remove => "remove".into(),
        MoveTrack(n) => format!("move {n:+}"),
        ClearSelection => "clear".into(),
        StartSave => "save".into(),
        SaveAs(name) => format!("save {name}"),
        DeletePlaylist => "delete".into(),
        StartRename => "rename".into(),
        RenameTo(name) => format!("rename {name}"),
        PlayPlaylist(name) => format!("playlist {name}"),
        TogglePause => "pause".into(),
        Next => "next".into(),
        Prev => "prev".into(),
        Stop => "stop".into(),
        SeekBy(n) => format!("seek {n:+}"),
        SeekTo(d) => format!("seek {}", time(d)),
        VolumeBy(v) => format!(
            "volume {}{}",
            if *v < 0.0 { "-" } else { "+" },
            number(f64::from(v.abs()) * 100.0)
        ),
        SetVolume(v) => format!("volume {}", number(f64::from(*v) * 100.0)),
        SpeedBy(n) => format!("speed {n:+}"),
        SetSpeed(n) => format!("speed {n}"),
        CycleMode(true) => "mode +".into(),
        CycleMode(false) => "mode -".into(),
        SetMode(m) => format!(
            "mode {}",
            MODES.iter().find(|x| x.1 == *m).expect("every mode").0
        ),
        Mark => "mark".into(),
        MarkAt(d) => format!("mark {}", time(d)),
        UndoMark => "unmark".into(),
        ClearMarks => "delmarks".into(),
        NextMark => "next-mark".into(),
        PrevMark => "prev-mark".into(),
        Map { view, key, action } => {
            let target = match action {
                Some(a) => line(a, *view),
                None => "nop".into(),
            };
            match view {
                Some(v) => format!("map {} {key} {target}", view_name(*v)),
                None => format!("map {key} {target}"),
            }
        }
        Unmap { view: Some(v), key } => format!("unmap {} {key}", view_name(*v)),
        Unmap { view: None, key } => format!("unmap {key}"),
    }
}

/// The value named by `word`, or its prefix, in `table`, ignoring case. An
/// empty or unknown word is an error listing the choices.
fn choose<T: Copy>(word: &str, table: &[(&str, T)], what: &str) -> Result<T, String> {
    let names = || table.iter().map(|t| t.0);
    // Short enough to fit beside the indicators on an 80-column bottom line.
    let listed = || format!("{what}s: {}", names().collect::<Vec<_>>().join(", "));
    if word.is_empty() {
        return Err(listed());
    }
    match resolve(&word.to_ascii_lowercase(), names(), what) {
        Ok(name) => Ok(table.iter().find(|t| t.0 == name).expect("resolved").1),
        Err(e) if e.starts_with("unknown") => Err(listed()),
        Err(e) => Err(e),
    }
}

/// Parses `90`, `1:23`, `1:02:03` or `83.5` as a time into a track.
fn parse_time(text: &str) -> Result<Duration, String> {
    let bad = || format!("not a time: {text} (try 1:23 or 90)");
    let parts: Vec<&str> = text.split(':').collect();
    if parts.len() > 3 || parts.iter().any(|p| p.is_empty()) {
        return Err(bad());
    }
    let (whole, last) = parts.split_at(parts.len() - 1);
    let mut seconds: f64 = last[0].parse().map_err(|_| bad())?;
    for (i, part) in whole.iter().rev().enumerate() {
        let n: u64 = part.parse().map_err(|_| bad())?;
        seconds += n as f64 * 60f64.powi(i as i32 + 1);
    }
    if !seconds.is_finite() || seconds < 0.0 {
        return Err(bad());
    }
    Ok(Duration::from_secs_f64(seconds))
}

/// `+rest` or `-rest` as a sign and the rest, or `None` for an unsigned value.
fn signed(text: &str) -> Option<(f64, &str)> {
    match text.as_bytes().first() {
        Some(b'+') => Some((1.0, &text[1..])),
        Some(b'-') => Some((-1.0, &text[1..])),
        _ => None,
    }
}

/// `text` without one pair of surrounding double quotes.
fn unquote(text: &str) -> &str {
    text.strip_prefix('"')
        .and_then(|t| t.strip_suffix('"'))
        .unwrap_or(text)
}

/// Parses a `:` command line, without the colon, typed in `view`.
///
/// A leading `+` or `-` makes a number relative, for every command that takes one.
pub fn parse(line: &str, view: View) -> Result<Action, String> {
    parse_in(line, Some(view))
}

/// What a key bound to `target` in `view` does: `nop` is nothing, `command`
/// opens the prompt, and anything else is a command usable there.
pub fn key_target(target: &str, view: Option<View>) -> Result<Option<Action>, String> {
    match target.trim() {
        "" => Err("no command".into()),
        "nop" => Ok(None),
        // Opening the prompt only makes sense as a key.
        "command" => Ok(Some(Action::StartCommand)),
        target => match parse_in(target, view)? {
            Action::Map { .. } | Action::Unmap { .. } => {
                Err("a key cannot run :map or :unmap".into())
            }
            action => Ok(Some(action)),
        },
    }
}

/// The one view `target` works in, when it does not work in every view.
pub fn only_view(target: &str) -> Option<View> {
    if parse_in(target, None).is_ok() {
        return None;
    }
    VIEWS
        .iter()
        .map(|v| v.1)
        .find(|v| parse_in(target, Some(*v)).is_ok())
}

/// The playback mode named by `name` or a unique prefix of it.
pub fn mode_named(name: &str) -> Result<Mode, String> {
    choose(name, MODES, "mode")
}

/// The view named by `name`, in full.
pub fn view_named(name: &str) -> Option<View> {
    VIEWS.iter().find(|v| v.0 == name).map(|v| v.1)
}

/// The first word of `text` and the rest, trimmed.
fn first_word(text: &str) -> (&str, &str) {
    match text.split_once(char::is_whitespace) {
        Some((word, rest)) => (word, rest.trim()),
        None => (text, ""),
    }
}

/// Parses `[VIEW] KEY [COMMAND]` after `map` or `unmap`.
fn binding(rest: &str) -> Result<(Option<View>, Key, &str), String> {
    let (first, after) = first_word(rest);
    let (view, key, after) = match VIEWS.iter().find(|v| v.0 == first) {
        Some(&(_, view)) if !after.is_empty() => {
            let (key, after) = first_word(after);
            (Some(view), key, after)
        }
        _ => (None, first, after),
    };
    Ok((view, Key::parse(key)?, after))
}

/// Where a binding applies, for messages: `in the library view` or `for all views`.
pub fn scope(view: Option<View>) -> String {
    match view {
        Some(v) => format!("in the {} view", view_name(v)),
        None => "for all views".into(),
    }
}

/// `line` parsed in `view`, or with only every-view commands when `None`.
fn parse_in(line: &str, view: Option<View>) -> Result<Action, String> {
    let line = line.trim();
    let (word, rest) = match line.split_once(char::is_whitespace) {
        Some((word, rest)) => (word, rest.trim()),
        None => (line, ""),
    };
    if line.is_empty() {
        return Err("no command".into());
    }
    let command = resolve_command(word, view)?;
    let name = command.name;
    let usage = || format!("usage: :{} {}", name, command.args);
    let nothing = |action: Action| {
        if rest.is_empty() {
            Ok(action)
        } else {
            Err(format!(":{name} takes no arguments"))
        }
    };
    let rows = |sign: i64| match rest {
        "" => Ok(Action::Cursor(sign)),
        n => match n.parse::<i64>() {
            Ok(n) if n > 0 => Ok(Action::Cursor(sign * n)),
            _ => Err(format!("not a number of rows: {n}")),
        },
    };

    match name {
        "help" => nothing(Action::CommandHelp),
        "keys" => nothing(Action::Help),
        "quit" => nothing(Action::Quit),
        "view" => choose(rest, VIEWS, "view").map(Action::ShowView),
        "next-view" => nothing(Action::NextView),
        "down" => rows(1),
        "up" => rows(-1),
        "first" => nothing(Action::CursorFirst),
        "last" => nothing(Action::CursorLast),
        "play" => nothing(Action::Activate),
        "search" if rest.is_empty() => Ok(Action::StartSearch),
        "search" => Ok(Action::Search(rest.to_string())),
        "playlist" if rest.is_empty() => Err(usage()),
        "playlist" => Ok(Action::PlayPlaylist(unquote(rest).to_string())),
        "save" if rest.is_empty() => Ok(Action::StartSave),
        "save" => Ok(Action::SaveAs(unquote(rest).to_string())),
        "pause" => nothing(Action::TogglePause),
        "next" => nothing(Action::Next),
        "prev" => nothing(Action::Prev),
        "stop" => nothing(Action::Stop),
        "seek" => match signed(rest) {
            _ if rest.is_empty() => Err(usage()),
            Some((sign, time)) => Ok(Action::SeekBy(
                (sign * parse_time(time)?.as_secs_f64()).round() as i64,
            )),
            None => Ok(Action::SeekTo(parse_time(rest)?)),
        },
        "volume" => {
            let number = |t: &str| {
                t.parse::<f32>()
                    .map_err(|_| format!("not a volume: {rest}"))
            };
            match signed(rest) {
                _ if rest.is_empty() => Err(usage()),
                Some((sign, n)) => Ok(Action::VolumeBy(sign as f32 * number(n)? / 100.0)),
                None => match number(rest)? {
                    v if (0.0..=100.0).contains(&v) => Ok(Action::SetVolume(v / 100.0)),
                    _ => Err("volume is 0 to 100".into()),
                },
            }
        }
        "speed" => {
            let semitones = |t: &str| {
                t.parse::<u32>()
                    .ok()
                    .filter(|n| *n <= 24)
                    .map(|n| n as i32)
                    .ok_or_else(|| format!("not a number of semitones: {rest}"))
            };
            match signed(rest) {
                _ if rest.is_empty() => Err(usage()),
                Some((sign, n)) => Ok(Action::SpeedBy(sign as i32 * semitones(n)?)),
                None => match semitones(rest)? {
                    n if n <= 12 => Ok(Action::SetSpeed(n)),
                    _ => Err("speed is -12 to 12 semitones".into()),
                },
            }
        }
        "mode" => match rest {
            "+" => Ok(Action::CycleMode(true)),
            "-" => Ok(Action::CycleMode(false)),
            _ => {
                let typed = rest.split_whitespace().collect::<Vec<_>>().join("-");
                choose(&typed, MODES, "mode").map(Action::SetMode)
            }
        },
        "mark" if rest.is_empty() => Ok(Action::Mark),
        "mark" => Ok(Action::MarkAt(parse_time(rest)?)),
        "unmark" => nothing(Action::UndoMark),
        "delmarks" => nothing(Action::ClearMarks),
        "next-mark" => nothing(Action::NextMark),
        "prev-mark" => nothing(Action::PrevMark),
        "map" => {
            let (view, key, target) = binding(rest)?;
            if target.is_empty() {
                return Err(usage());
            }
            let action = key_target(target, view).map_err(|e| {
                match only_view(target).filter(|v| view != Some(*v)) {
                    Some(v) => format!("{e}; use map {} {key} {target}", view_name(v)),
                    None => e,
                }
            })?;
            Ok(Action::Map {
                view,
                key,
                action: action.map(Box::new),
            })
        }
        "unmap" => match binding(rest)? {
            (view, key, "") => Ok(Action::Unmap { view, key }),
            _ => Err(usage()),
        },
        "toggle" | "add" => nothing(Action::Add),
        "clear-search" => nothing(Action::ClearSearch),
        "remove" => nothing(Action::Remove),
        "move" => match signed(rest).map(|(sign, n)| (sign as i64, n.parse::<i64>())) {
            Some((sign, Ok(n))) if n > 0 => Ok(Action::MoveTrack(sign * n)),
            _ => Err(usage()),
        },
        "clear" => nothing(Action::ClearSelection),
        "delete" => nothing(Action::DeletePlaylist),
        "rename" if rest.is_empty() => Ok(Action::StartRename),
        "rename" => Ok(Action::RenameTo(unquote(rest).to_string())),
        _ => unreachable!("command {name} has no parser"),
    }
}

/// What Tab can complete `text` to in `view`, as whole command lines.
///
/// The first word completes to the names of commands that work in `view`.
/// After `mode` or `view` the argument completes to its choices, and after
/// `playlist` or `rename` to the names in `playlists`.
pub fn completions(text: &str, view: View, playlists: &[String]) -> Vec<String> {
    let Some((word, rest)) = text.split_once(' ') else {
        return usable(Some(view))
            .filter(|c| c.name.starts_with(text))
            .map(|c| c.name.to_string())
            .collect();
    };
    let Ok(command) = resolve_command(word, Some(view)) else {
        return Vec::new();
    };
    let rest = rest.trim_start();
    let choices: Vec<String> = match command.name {
        "mode" => MODES.iter().map(|m| m.0.to_string()).collect(),
        "view" => VIEWS.iter().map(|v| v.0.to_string()).collect(),
        "playlist" | "rename" => playlists.to_vec(),
        _ => Vec::new(),
    };
    let lower = rest.to_lowercase();
    choices
        .into_iter()
        .filter(|c| c.to_lowercase().starts_with(&lower))
        .map(|c| format!("{} {c}", command.name))
        .collect()
}

/// Most command lines kept in the history.
pub const HISTORY_LEN: usize = 100;

/// Command lines entered this session, oldest first.
#[derive(Debug, Default)]
pub struct History {
    lines: Vec<String>,
}

impl History {
    /// Records `line`, unless it is blank or repeats the line before it.
    pub fn push(&mut self, line: &str) {
        let line = line.trim();
        if line.is_empty() || self.lines.last().is_some_and(|l| l == line) {
            return;
        }
        if self.lines.len() == HISTORY_LEN {
            self.lines.remove(0);
        }
        self.lines.push(line.to_string());
    }

    pub fn lines(&self) -> &[String] {
        &self.lines
    }
}

/// A command line being typed after `:`.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct CommandLine {
    pub text: String,
    /// The completions Tab is cycling through, and which one is shown.
    tab: Option<(Vec<String>, usize)>,
    /// While recalling history: the text typed before the first Up, which
    /// recalled lines must start with, and the history index shown.
    recall: Option<(String, usize)>,
}

impl CommandLine {
    pub fn push(&mut self, c: char) {
        self.text.push(c);
        self.settle();
    }

    /// Deletes the last character; false if there was none to delete.
    pub fn pop(&mut self) -> bool {
        self.settle();
        self.text.pop().is_some()
    }

    /// Ends Tab cycling and history recall, keeping the text shown.
    fn settle(&mut self) {
        self.tab = None;
        self.recall = None;
    }

    /// Shows the next completion, or the previous one when `forward` is false.
    pub fn complete(&mut self, forward: bool, view: View, playlists: &[String]) {
        self.recall = None;
        let (choices, at) = match self.tab.take() {
            Some((choices, at)) => {
                let n = choices.len();
                let at = if forward {
                    (at + 1) % n
                } else {
                    (at + n - 1) % n
                };
                (choices, at)
            }
            None => {
                let choices = completions(&self.text, view, playlists);
                if choices.is_empty() {
                    return;
                }
                let at = if forward { 0 } else { choices.len() - 1 };
                (choices, at)
            }
        };
        self.text = choices[at].clone();
        self.tab = Some((choices, at));
    }

    /// Shows an older history line starting with the typed text, or a newer
    /// one when `older` is false. Past the newest, the typed text returns.
    pub fn recall(&mut self, older: bool, history: &History) {
        self.tab = None;
        let lines = history.lines();
        let (draft, at) = self
            .recall
            .take()
            .unwrap_or_else(|| (self.text.clone(), lines.len()));
        let found = if older {
            lines[..at].iter().rposition(|l| l.starts_with(&draft))
        } else {
            lines
                .iter()
                .enumerate()
                .skip(at + 1)
                .find(|(_, l)| l.starts_with(&draft))
                .map(|(i, _)| i)
        };
        match found {
            Some(i) => {
                self.text = lines[i].clone();
                self.recall = Some((draft, i));
            }
            // Nothing older: stay on the oldest match shown.
            None if older => {
                if at < lines.len() {
                    self.recall = Some((draft, at));
                }
            }
            None => self.text = draft,
        }
    }
}