jless 0.9.0

A command-line JSON viewer
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
use std::error::Error;
use std::io;
use std::io::Write;

use clipboard::{ClipboardContext, ClipboardProvider};
use rustyline::error::ReadlineError;
use rustyline::Editor;
use termion::event::Key;
use termion::event::MouseButton::{Left, WheelDown, WheelUp};
use termion::event::MouseEvent::Press;
use termion::raw::RawTerminal;
use termion::screen::{ToAlternateScreen, ToMainScreen};

use crate::flatjson;
use crate::input::TuiEvent;
use crate::input::TuiEvent::{KeyEvent, MouseEvent, WinChEvent};
use crate::jsonstringunescaper::unescape_json_string;
use crate::lineprinter::JS_IDENTIFIER;
use crate::options::{DataFormat, Opt};
use crate::screenwriter::{MessageSeverity, ScreenWriter};
use crate::search::{JumpDirection, SearchDirection, SearchState};
use crate::types::TTYDimensions;
use crate::viewer::{Action, JsonViewer, Mode};

pub struct App {
    viewer: JsonViewer,
    screen_writer: ScreenWriter,
    input_state: InputState,
    input_buffer: Vec<u8>,
    input_filename: String,
    search_state: SearchState,
    message: Option<(String, MessageSeverity)>,
    clipboard_context: Result<ClipboardContext, Box<dyn Error>>,
}

// State to determine how to process the next event input.
//
// The default state accepts most commands, and also buffers
// number inputs to provide a count for movement commands.
//
// Other commands require a combination of (non-numeric) key
// presses. When one of these commands is partially inputted,
// pressing a key not part of the combination will cancel
// the combination command, and no action will be performed.
#[derive(PartialEq)]
enum InputState {
    Default,
    PendingPCommand,
    PendingYCommand,
    PendingZCommand,
    WaitingForAnyKeyPress,
}

// Various things that can be copied/printed.
#[derive(Copy, Clone)]
enum ContentTarget {
    PrettyPrintedValue,
    OneLineValue,
    String,
    Key,
    DotPath,
    BracketPath,
    QueryPath,
}

enum Command {
    Quit,
    Help,
    SetShowLineNumber(Option<bool>),
    SetShowRelativeLineNumber(Option<bool>),
    Unknown,
}

// Help contents that we pipe to less.
const HELP: &str = std::include_str!("./jless.help");

pub const MAX_BUFFER_SIZE: usize = 9;
const BELL: &str = "\x07";

// https://docs.rs/termion/2.0.1/src/termion/input.rs.html#176-180
//
// The termion MouseTerminal sends the following escape codes:
//
// ESC [ ? 1000 h
// ESC [ ? 1002 h
// ESC [ ? 1015 h
// ESC [ ? 1006 h
//
// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
//
// 1000 enables better mouse support; 1002 enables button-event tracking,
// then 1015 and 1006 change the format that mouse events are sent in.
// (It seems like 1006 overrides 1015, but probably some legacy issue somewhere.)
//
// When we print stuff to the screen with 'p', we want to allow the user to
// highlight it with their mouse, so we disable the regular mouse button tracking.
const DISABLE_MOUSE_BUTTON_TRACKING: &str = "\x1b[?1002l";
const ENABLE_MOUSE_BUTTON_TRACKING: &str = "\x1b[?1002h";

impl App {
    pub fn new(
        opt: &Opt,
        data: String,
        data_format: DataFormat,
        input_filename: String,
        stdout: RawTerminal<Box<dyn Write>>,
    ) -> Result<App, String> {
        let flatjson = match Self::parse_input(data, data_format) {
            Ok(flatjson) => flatjson,
            Err(err) => return Err(format!("Unable to parse input: {err:?}")),
        };

        let mut viewer = JsonViewer::new(flatjson, opt.mode);
        viewer.scrolloff_setting = opt.scrolloff;

        let screen_writer =
            ScreenWriter::init(opt, stdout, Editor::<()>::new(), TTYDimensions::default());

        Ok(App {
            viewer,
            screen_writer,
            input_state: InputState::Default,
            input_buffer: vec![],
            input_filename,
            search_state: SearchState::empty(),
            message: None,
            clipboard_context: ClipboardProvider::new(),
        })
    }

    fn parse_input(data: String, data_format: DataFormat) -> Result<flatjson::FlatJson, String> {
        match data_format {
            DataFormat::Json => flatjson::parse_top_level_json(data),
            DataFormat::Yaml => flatjson::parse_top_level_yaml(data),
        }
    }

    pub fn run(&mut self, input: Box<dyn Iterator<Item = io::Result<TuiEvent>>>) {
        let dimensions = TTYDimensions::from_size(termion::terminal_size().unwrap());
        self.viewer.dimensions = dimensions.without_status_bar();
        self.screen_writer.dimensions = dimensions;
        self.draw_screen();

        for event in input {
            let event = match event {
                Ok(event) => event,
                Err(io_error) => {
                    self.set_error_message(format!("Error: {io_error}"));
                    self.draw_status_bar();
                    continue;
                }
            };

            // This state trumps everything else. We won't do anything until the user
            // hits a key, then we will redraw the screen and return to the default input
            // state. (We ignore the actual value of the key they press.)
            if self.input_state == InputState::WaitingForAnyKeyPress {
                if matches!(event, KeyEvent(_)) {
                    let _ = write!(self.screen_writer.stdout, "{ToAlternateScreen}");
                    let _ = write!(self.screen_writer.stdout, "{ENABLE_MOUSE_BUTTON_TRACKING}");
                    self.input_state = InputState::Default;
                    self.draw_screen();
                    self.message = None;
                }
                continue;
            }

            // When "actively" searching, we want to show highlighted search terms.
            // We consider someone "actively" searching immediately after the start
            // of a search, and while they navigate between matches using n/N.
            //
            // Once the user moves the focused row via another input, we will no longer
            // consider them actively searching. (So scrolling, as long as it doesn't
            // result in the cursor moving, does not stop the "active" search.)
            //
            // If a user expands a node that contained a search match, then we want
            // the next jump to go to that match inside the container. To handle this
            // we'll also stop considering the search active if the collapsed state
            // of the focused row changes.
            let mut jumped_to_search_match = false;
            let focused_row_before = self.viewer.focused_row;
            let previous_collapsed_state_of_focused_row =
                self.viewer.flatjson[focused_row_before].is_collapsed();

            let action = match event {
                // Put this first so the current input state doesn't get reset
                // when resizing the window.
                WinChEvent => {
                    let dimensions = TTYDimensions::from_size(termion::terminal_size().unwrap());
                    self.screen_writer.dimensions = dimensions;
                    Some(Action::ResizeViewerDimensions(
                        dimensions.without_status_bar(),
                    ))
                }
                // Handle special input states:
                // p commands:
                event if self.input_state == InputState::PendingPCommand => {
                    let content_target = match event {
                        KeyEvent(Key::Char('p')) => Some(ContentTarget::PrettyPrintedValue),
                        KeyEvent(Key::Char('v')) => Some(ContentTarget::OneLineValue),
                        KeyEvent(Key::Char('s')) => Some(ContentTarget::String),
                        KeyEvent(Key::Char('k')) => Some(ContentTarget::Key),
                        KeyEvent(Key::Char('P')) => Some(ContentTarget::DotPath),
                        KeyEvent(Key::Char('b')) => Some(ContentTarget::BracketPath),
                        KeyEvent(Key::Char('q')) => Some(ContentTarget::QueryPath),
                        _ => None,
                    };

                    self.input_buffer.clear();

                    if let Some(content_target) = content_target {
                        if self.print_content(content_target) {
                            self.input_state = InputState::WaitingForAnyKeyPress;
                            continue;
                        }
                    }

                    self.input_state = InputState::Default;

                    None
                }
                // y commands:
                event if self.input_state == InputState::PendingYCommand => {
                    let content_target = match event {
                        KeyEvent(Key::Char('y')) => Some(ContentTarget::PrettyPrintedValue),
                        KeyEvent(Key::Char('v')) => Some(ContentTarget::OneLineValue),
                        KeyEvent(Key::Char('s')) => Some(ContentTarget::String),
                        KeyEvent(Key::Char('k')) => Some(ContentTarget::Key),
                        KeyEvent(Key::Char('p')) => Some(ContentTarget::DotPath),
                        KeyEvent(Key::Char('b')) => Some(ContentTarget::BracketPath),
                        KeyEvent(Key::Char('q')) => Some(ContentTarget::QueryPath),
                        _ => None,
                    };

                    if let Some(content_target) = content_target {
                        self.copy_content(content_target);
                    }

                    self.input_state = InputState::Default;
                    self.input_buffer.clear();

                    None
                }
                // z commands:
                event if self.input_state == InputState::PendingZCommand => {
                    let z_action = match event {
                        KeyEvent(Key::Char('t')) => Some(Action::MoveFocusedLineToTop),
                        KeyEvent(Key::Char('z')) => Some(Action::MoveFocusedLineToCenter),
                        KeyEvent(Key::Char('b')) => Some(Action::MoveFocusedLineToBottom),
                        _ => None,
                    };

                    self.input_state = InputState::Default;
                    self.input_buffer.clear();

                    z_action
                }
                // These inputs quit.
                KeyEvent(Key::Ctrl('c') | Key::Char('q')) => break,
                // Show the help page
                KeyEvent(Key::F(1)) => {
                    self.show_help();
                    None
                }
                KeyEvent(Key::Esc) => {
                    self.input_buffer.clear();
                    self.search_state.set_no_longer_actively_searching();
                    None
                }
                // These inputs may be buffered.
                KeyEvent(Key::Char(ch @ '0'..='9')) => {
                    if ch == '0' && self.input_buffer.is_empty() {
                        Some(Action::FocusFirstSibling)
                    } else {
                        self.buffer_input(ch as u8);
                        None
                    }
                }
                KeyEvent(Key::Char('p')) => {
                    self.input_state = InputState::PendingPCommand;
                    self.input_buffer.clear();
                    self.buffer_input(b'p');
                    None
                }
                KeyEvent(Key::Char('y')) => {
                    match &self.clipboard_context {
                        Ok(_) => {
                            self.input_state = InputState::PendingYCommand;
                            self.input_buffer.clear();
                            self.buffer_input(b'y');
                        }
                        Err(err) => {
                            let msg = format!("Unable to access clipboard: {err}");
                            self.set_error_message(msg);
                        }
                    }

                    None
                }
                KeyEvent(Key::Char('z')) => {
                    self.input_state = InputState::PendingZCommand;
                    self.input_buffer.clear();
                    self.buffer_input(b'z');
                    None
                }
                // These inputs always clear the input_buffer (but may use its current contents).
                KeyEvent(key) => {
                    let action = match key {
                        // These interpret the input buffer as a number.
                        Key::Up | Key::Char('k') | Key::Ctrl('p') | Key::Backspace => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::MoveUp(lines))
                        }
                        Key::Down | Key::Char('j') | Key::Ctrl('n') | Key::Char('\n') => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::MoveDown(lines))
                        }
                        Key::Ctrl('e') => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::ScrollDown(lines))
                        }
                        Key::Ctrl('y') => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::ScrollUp(lines))
                        }
                        Key::Ctrl('d') => {
                            let maybe_distance = self.maybe_parse_input_buffer_as_number();
                            Some(Action::JumpDown(maybe_distance))
                        }
                        Key::Ctrl('u') => {
                            let maybe_distance = self.maybe_parse_input_buffer_as_number();
                            Some(Action::JumpUp(maybe_distance))
                        }
                        Key::Ctrl('b') | Key::PageUp => {
                            let count = self.parse_input_buffer_as_number();
                            Some(Action::PageUp(count))
                        }
                        Key::Ctrl('f') | Key::PageDown => {
                            let count = self.parse_input_buffer_as_number();
                            Some(Action::PageDown(count))
                        }
                        Key::Char('K') => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::FocusPrevSibling(lines))
                        }
                        Key::Char('J') => {
                            let lines = self.parse_input_buffer_as_number();
                            Some(Action::FocusNextSibling(lines))
                        }
                        Key::Char('n') => {
                            let count = self.parse_input_buffer_as_number();
                            jumped_to_search_match = true;
                            self.jump_to_search_match(JumpDirection::Next, count)
                        }
                        Key::Char('N') => {
                            let count = self.parse_input_buffer_as_number();
                            jumped_to_search_match = true;
                            self.jump_to_search_match(JumpDirection::Prev, count)
                        }
                        Key::Char('g') => match self.maybe_parse_input_buffer_as_number() {
                            None => Some(Action::FocusTop),
                            Some(n) => Some(Action::JumpTo {
                                line: n - 1,
                                make_visible: false,
                            }),
                        },
                        Key::Char('G') => match self.maybe_parse_input_buffer_as_number() {
                            None => Some(Action::FocusBottom),
                            Some(n) => Some(Action::JumpTo {
                                line: n - 1,
                                make_visible: true,
                            }),
                        },
                        Key::Char('.') => {
                            let count = self.parse_input_buffer_as_number();
                            self.screen_writer
                                .scroll_focused_line_right(&self.viewer, count);
                            None
                        }
                        Key::Char(',') => {
                            let count = self.parse_input_buffer_as_number();
                            self.screen_writer
                                .scroll_focused_line_left(&self.viewer, count);
                            None
                        }
                        Key::Char('/') => {
                            let count = self.parse_input_buffer_as_number();
                            let action = self
                                .get_search_input_and_start_search(SearchDirection::Forward, count);
                            jumped_to_search_match = action.is_some();
                            action
                        }
                        Key::Char('?') => {
                            let count = self.parse_input_buffer_as_number();
                            let action = self
                                .get_search_input_and_start_search(SearchDirection::Reverse, count);
                            jumped_to_search_match = action.is_some();
                            action
                        }
                        Key::Char('*') => {
                            let count = self.parse_input_buffer_as_number();
                            let action =
                                self.start_object_key_search(SearchDirection::Forward, count);
                            jumped_to_search_match = action.is_some();
                            action
                        }
                        Key::Char('#') => {
                            let count = self.parse_input_buffer_as_number();
                            let action =
                                self.start_object_key_search(SearchDirection::Reverse, count);
                            jumped_to_search_match = action.is_some();
                            action
                        }
                        // These ignore the input buffer
                        Key::Char('w') => Some(Action::MoveDownUntilDepthChange),
                        Key::Char('b') => Some(Action::MoveUpUntilDepthChange),
                        Key::Left | Key::Char('h') => Some(Action::MoveLeft),
                        Key::Right | Key::Char('l') => Some(Action::MoveRight),
                        Key::Char('H') => Some(Action::FocusParent),
                        Key::Char('c') => Some(Action::CollapseNodeAndSiblings),
                        Key::Char('C') => Some(Action::DeepCollapseNodeAndSiblings),
                        Key::Char('e') => Some(Action::ExpandNodeAndSiblings),
                        Key::Char('E') => Some(Action::DeepExpandNodeAndSiblings),
                        Key::Char(' ') => Some(Action::ToggleCollapsed),
                        Key::Char('^') => Some(Action::FocusFirstSibling),
                        Key::Char('$') => Some(Action::FocusLastSibling),
                        Key::Home => Some(Action::FocusTop),
                        Key::End => Some(Action::FocusBottom),
                        Key::Char('%') => Some(Action::FocusMatchingPair),
                        Key::Char('m') => Some(Action::ToggleMode),
                        Key::Char('<') => {
                            self.screen_writer
                                .decrease_indentation_level(self.viewer.flatjson.2 as u16);
                            None
                        }
                        Key::Char('>') => {
                            self.screen_writer.increase_indentation_level();
                            None
                        }
                        Key::Char(';') => {
                            self.screen_writer
                                .scroll_focused_line_to_an_end(&self.viewer);
                            None
                        }
                        Key::Char(':') => {
                            if let Some(command) = self.readline(":", "command") {
                                match Self::parse_command(&command) {
                                    Command::Quit => break,
                                    Command::Help => self.show_help(),
                                    Command::SetShowLineNumber(Some(new_val)) => {
                                        self.screen_writer.show_line_numbers = new_val
                                    }
                                    Command::SetShowLineNumber(None) => {
                                        self.screen_writer.show_line_numbers =
                                            !self.screen_writer.show_line_numbers
                                    }
                                    Command::SetShowRelativeLineNumber(Some(new_val)) => {
                                        self.screen_writer.show_relative_line_numbers = new_val
                                    }
                                    Command::SetShowRelativeLineNumber(None) => {
                                        self.screen_writer.show_relative_line_numbers =
                                            !self.screen_writer.show_relative_line_numbers
                                    }
                                    Command::Unknown => {
                                        self.set_warning_message(format!(
                                            "Unknown command: {command}"
                                        ));
                                    }
                                }
                            }

                            None
                        }
                        _ => {
                            eprint!("{BELL}\r");
                            None
                        }
                    };

                    self.input_buffer.clear();

                    action
                }
                MouseEvent(me) => {
                    self.input_buffer.clear();

                    match me {
                        Press(Left, _, h) => {
                            // Ignore clicks on status bar or below.
                            if h > self.screen_writer.dimensions.without_status_bar().height {
                                continue;
                            } else {
                                Some(Action::Click(h))
                            }
                        }
                        Press(WheelUp, _, _) => Some(Action::ScrollUp(3)),
                        Press(WheelDown, _, _) => Some(Action::ScrollDown(3)),
                        // Ignore all other mouse events and don't redraw the screen.
                        _ => {
                            continue;
                        }
                    }
                }
                TuiEvent::Unknown(bytes) => {
                    self.set_error_message(format!("Unknown byte sequence: {bytes:?}"));
                    None
                }
            };

            if let Some(action) = action {
                self.viewer.perform_action(action);
            }

            if jumped_to_search_match {
                self.screen_writer.scroll_line_to_search_match(
                    &self.viewer,
                    self.search_state.current_match_range(),
                );
            } else {
                // Check whether we're still actively searching. If the cursor moves,
                // we're no longer actively searching. If the focused row was expanded
                // or collapsed, we're still searching, but there's no longer a current
                // match.
                if focused_row_before != self.viewer.focused_row {
                    self.search_state.set_no_longer_actively_searching();
                } else if previous_collapsed_state_of_focused_row
                    != self.viewer.flatjson[focused_row_before].is_collapsed()
                {
                    self.search_state
                        .set_matches_visible_if_actively_searching();
                }
            }

            self.draw_screen();
            self.message = None;
        }
    }

    fn draw_screen(&mut self) {
        self.screen_writer.print(
            &self.viewer,
            &self.input_buffer,
            &self.input_filename,
            &self.search_state,
            &self.message,
        );
    }

    fn draw_status_bar(&mut self) {
        self.screen_writer.print_status_bar(
            &self.viewer,
            &self.input_buffer,
            &self.input_filename,
            &self.search_state,
            &self.message,
        );
    }

    fn set_info_message(&mut self, s: String) {
        self.message = Some((s, MessageSeverity::Info));
    }

    fn set_warning_message(&mut self, s: String) {
        self.message = Some((s, MessageSeverity::Warn));
    }

    fn set_error_message(&mut self, s: String) {
        self.message = Some((s, MessageSeverity::Error));
    }

    // Get user input via a readline prompt. May fail to return input if
    // the user deliberately cancels the prompt via Ctrl-C or Ctrl-D, or
    // if an actual error occurs, in which case an error message is set.
    fn readline(&mut self, prompt: &str, purpose: &str) -> Option<String> {
        match self.screen_writer.get_command(prompt) {
            Ok(s) => Some(s),
            // User hit Ctrl-C or Ctrl-D to cancel prompt
            Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => None,
            Err(err) => {
                self.set_error_message(format!("Error getting {purpose}: {err}"));
                None
            }
        }
    }

    fn buffer_input(&mut self, ch: u8) {
        // Don't buffer leading 0s.
        if self.input_buffer.is_empty() && ch == b'0' {
            return;
        }

        if self.input_buffer.len() >= MAX_BUFFER_SIZE {
            self.input_buffer.rotate_left(1);
            self.input_buffer.pop();
        }
        self.input_buffer.push(ch);
    }

    fn maybe_parse_input_buffer_as_number(&mut self) -> Option<usize> {
        let n = str::parse::<usize>(std::str::from_utf8(&self.input_buffer).unwrap());
        self.input_buffer.clear();
        n.ok()
    }

    fn parse_input_buffer_as_number(&mut self) -> usize {
        self.maybe_parse_input_buffer_as_number().unwrap_or(1)
    }

    fn get_search_input_and_start_search(
        &mut self,
        direction: SearchDirection,
        jumps: usize,
    ) -> Option<Action> {
        let prompt_str = match direction {
            SearchDirection::Forward => "/",
            SearchDirection::Reverse => "?",
        };

        let search_term = self.readline(prompt_str, "search input")?;

        // In vim, /<CR> or ?<CR> is a longcut for repeating the previous search.
        if search_term.is_empty() {
            // This will actually set the direction of a search going forward.
            self.search_state.direction = direction;
            self.jump_to_search_match(JumpDirection::Next, jumps)
        } else {
            if self.initialize_search(direction, search_term) {
                if !self.search_state.any_matches() {
                    self.set_warning_message(self.search_state.no_matches_message());
                    None
                } else {
                    self.jump_to_search_match(JumpDirection::Next, jumps)
                }
            } else {
                None
            }
        }
    }

    fn initialize_search(&mut self, direction: SearchDirection, search_term: String) -> bool {
        match SearchState::initialize_search(search_term, &self.viewer.flatjson.1, direction) {
            Ok(ss) => {
                self.search_state = ss;
                true
            }
            Err(err_message) => {
                self.set_error_message(err_message);
                false
            }
        }
    }

    fn start_object_key_search(
        &mut self,
        direction: SearchDirection,
        jumps: usize,
    ) -> Option<Action> {
        if self.initialize_object_key_search(direction) {
            self.jump_to_search_match(JumpDirection::Next, jumps)
        } else {
            let message = match direction {
                SearchDirection::Forward => "Must be focused on Object key to use '*'",
                SearchDirection::Reverse => "Must be focused on Object key to use '#'",
            };
            self.set_warning_message(message.to_string());
            None
        }
    }

    fn initialize_object_key_search(&mut self, direction: SearchDirection) -> bool {
        if let Some(key_range) = &self.viewer.flatjson[self.viewer.focused_row].key_range {
            // Note key_range already includes quotes around key.
            let object_key = format!("{}: ", &self.viewer.flatjson.1[key_range.clone()]);
            self.initialize_search(direction, object_key)
        } else {
            false
        }
    }

    fn jump_to_search_match(
        &mut self,
        jump_direction: JumpDirection,
        jumps: usize,
    ) -> Option<Action> {
        if !self.search_state.ever_searched {
            self.set_info_message("Type / to search".to_string());
            return None;
        } else if !self.search_state.any_matches() {
            self.set_warning_message(self.search_state.no_matches_message());
            return None;
        }

        let destination = self.search_state.jump_to_match(
            self.viewer.focused_row,
            &self.viewer.flatjson,
            jump_direction,
            jumps,
        );
        Some(Action::JumpTo {
            line: destination,
            make_visible: false,
        })
    }

    fn parse_command(command: &str) -> Command {
        match command {
            "h" | "he" | "hel" | "help" => Command::Help,
            "q" | "qu" | "qui" | "quit" | "quit()" | "exit" | "exit()" => Command::Quit,
            "set number" => Command::SetShowLineNumber(Some(true)),
            "set number!" => Command::SetShowLineNumber(None),
            "set nonumber" => Command::SetShowLineNumber(Some(false)),
            "set relativenumber" => Command::SetShowRelativeLineNumber(Some(true)),
            "set relativenumber!" => Command::SetShowRelativeLineNumber(None),
            "set norelativenumber" => Command::SetShowRelativeLineNumber(Some(false)),
            _ => Command::Unknown,
        }
    }

    fn show_help(&mut self) {
        let _ = write!(self.screen_writer.stdout, "{ToMainScreen}");
        let child = std::process::Command::new("less")
            .arg("-r")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::inherit())
            .spawn();

        match child {
            Ok(mut child) => {
                if let Some(ref mut stdin) = child.stdin {
                    let _ = stdin.write(HELP.as_bytes());
                    let _ = stdin.flush();
                }
                let _ = child.wait();
            }
            Err(err) => {
                self.set_error_message(format!("Error piping help documentation to less: {err}"));
            }
        }

        let _ = write!(self.screen_writer.stdout, "{ToAlternateScreen}");
    }

    fn get_content_target_data(&self, content_target: ContentTarget) -> Result<String, String> {
        let json = &self.viewer.flatjson.1;
        let focused_row_index = self.viewer.focused_row;
        let focused_row = &self.viewer.flatjson[focused_row_index];

        let data = match content_target {
            ContentTarget::PrettyPrintedValue if focused_row.is_container() => self
                .viewer
                .flatjson
                .pretty_printed_value(focused_row_index)
                .unwrap(),
            ContentTarget::PrettyPrintedValue | ContentTarget::OneLineValue => {
                let range = focused_row.range.clone();
                json[range].to_string()
            }
            ContentTarget::String => {
                if !focused_row.is_string() {
                    return Err("Current value is not a string".to_string());
                }

                let range = focused_row.range.clone();
                let quoteless_range = (range.start + 1)..(range.end - 1);
                let string_value = &json[quoteless_range];

                match unescape_json_string(string_value) {
                    Ok(unescaped) => unescaped,
                    Err(err) => {
                        return Err(format!("{err}"));
                    }
                }
            }
            ContentTarget::Key => {
                let Some(key_range) = &focused_row.key_range else {
                    return Err("No object key to copy".to_string());
                };

                let quoteless_range = (key_range.start + 1)..(key_range.end - 1);

                // Don't copy quotes in Data mode.
                if self.viewer.mode == Mode::Data
                    && JS_IDENTIFIER.is_match(&json[quoteless_range.clone()])
                {
                    json[quoteless_range].to_string()
                } else {
                    json[key_range.clone()].to_string()
                }
            }
            ct @ (ContentTarget::DotPath
            | ContentTarget::BracketPath
            | ContentTarget::QueryPath) => {
                let path_type = match ct {
                    ContentTarget::DotPath => flatjson::PathType::Dot,
                    ContentTarget::BracketPath => flatjson::PathType::Bracket,
                    ContentTarget::QueryPath => flatjson::PathType::Query,
                    _ => unreachable!(),
                };

                match self
                    .viewer
                    .flatjson
                    .build_path_to_node(path_type, focused_row_index)
                {
                    Ok(path) => path,
                    Err(err) => return Err(err),
                }
            }
        };

        Ok(data)
    }

    fn copy_content(&mut self, content_target: ContentTarget) {
        match self.get_content_target_data(content_target) {
            Ok(content) => {
                // Checked when the user first hits 'y'.
                let clipboard = self.clipboard_context.as_mut().unwrap();

                let focused_row = &self.viewer.flatjson[self.viewer.focused_row];

                let content_type = match content_target {
                    ContentTarget::PrettyPrintedValue if focused_row.is_container() => {
                        "pretty-printed value"
                    }
                    ContentTarget::PrettyPrintedValue | ContentTarget::OneLineValue => "value",
                    ContentTarget::String => "string contents",
                    ContentTarget::Key => "key",
                    ContentTarget::DotPath => "path",
                    ContentTarget::BracketPath => "bracketed path",
                    ContentTarget::QueryPath => "query path",
                };

                if let Err(err) = clipboard.set_contents(content) {
                    self.set_error_message(format!(
                        "Unable to copy {content_type} to clipboard: {err}"
                    ));
                } else {
                    self.set_info_message(format!("Copied {content_type} to clipboard"));
                }
            }
            Err(err) => self.set_warning_message(err),
        }
    }

    fn print_content(&mut self, content_target: ContentTarget) -> bool {
        match self.get_content_target_data(content_target) {
            Ok(content) => {
                // Exit raw mode so that the terminal interprets newlines as usual.
                let _ = self.screen_writer.stdout.suspend_raw_mode();
                // Go to the main screen so that the text will persist after exiting.
                let _ = write!(self.screen_writer.stdout, "{ToMainScreen}");
                // Disable mouse button tracking so that the user can use their mouse
                // to highlight the text.
                let _ = write!(self.screen_writer.stdout, "{DISABLE_MOUSE_BUTTON_TRACKING}");
                let _ = write!(
                    self.screen_writer.stdout,
                    "{}{}{}\n\nPress any key to continue.",
                    termion::clear::All,
                    termion::cursor::Goto(1, 1),
                    content
                );
                let _ = self.screen_writer.stdout.flush();
                // Go back to raw mode so we can immediately get key presses.
                let _ = self.screen_writer.stdout.activate_raw_mode();
                true
            }
            Err(err) => {
                self.set_warning_message(err);
                false
            }
        }
    }
}