summaryrefslogtreecommitdiffstats
path: root/src/line.rs
blob: 9877c484984d0d1f6444210d719b0e9bec4aa99b (plain) (blame)
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
use std::io::{self, IsTerminal, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;

use crossterm::cursor::{MoveToColumn, MoveUp};
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
use crossterm::terminal::{self, Clear, ClearType};
use crossterm::execute;

const HISTORY_LIMIT: usize = 200;

pub struct Editor {
    interactive: bool,
    history: Vec<String>,
    history_index: usize,
    draft: Vec<char>,
}

impl Editor {
    pub fn new() -> Self {
        Self {
            interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(),
            history: load_history(),
            history_index: 0,
            draft: Vec::new(),
        }
    }

    pub fn is_interactive(&self) -> bool {
        self.interactive
    }

    /// Reads one prompt. `None` means end of input (Ctrl-D or EOF).
    ///
    /// Raw mode is enabled only for the duration of this call, so Ctrl-C during
    /// a turn is still a signal handled by `signal`, not a keystroke.
    pub fn read(&mut self, prompt: &str) -> io::Result<Option<String>> {
        if !self.interactive {
            return read_plain();
        }

        let guard = RawGuard::enable()?;
        let mut buffer: Vec<char> = Vec::new();
        let mut cursor = 0usize;
        let mut state = DrawState::default();

        self.history_index = self.history.len();
        self.draft.clear();

        draw(prompt, &buffer, cursor, &mut state)?;

        loop {
            let event = event::read()?;
            match event {
                Event::Paste(text) => {
                    insert(&mut buffer, &mut cursor, &text);
                    draw(prompt, &buffer, cursor, &mut state)?;
                }
                Event::Resize(_, _) => {
                    // The terminal has already reflowed the block and moved the
                    // caret with it, so drawing again here would duplicate the
                    // prompt. Recompute only where the caret now sits relative
                    // to the block; the next redraw moves up from there.
                    let width = terminal_width();
                    let (cursor_row, _) = layout(prompt, &buffer, cursor, width);
                    state.cursor_row = cursor_row;
                }
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    match handle_key(key, &mut buffer, &mut cursor, self) {
                        Action::Continue => {}
                        Action::Submit => {
                            // Redraw with the caret at the end so the submitted
                            // line looks complete before we move on.
                            draw(prompt, &buffer, buffer.len(), &mut state)?;
                            drop(guard);
                            let line: String = buffer.iter().collect();
                            self.remember(&line);
                            println!();
                            return Ok(Some(line));
                        }
                        Action::Eof => {
                            drop(guard);
                            println!();
                            return Ok(None);
                        }
                        Action::Cancel => {
                            drop(guard);
                            println!("^C");
                            return Ok(Some(String::new()));
                        }
                    }
                    draw(prompt, &buffer, cursor, &mut state)?;
                }
                _ => {}
            }
        }
    }

    fn remember(&mut self, line: &str) {
        if line.trim().is_empty() {
            return;
        }
        // Prompt-mode commands are not worth recalling.
        if matches!(line.trim(), "/exit" | "/quit" | "/help" | "/paste") {
            return;
        }
        if self.history.last().map(|last| last.as_str()) == Some(line) {
            return;
        }
        self.history.push(line.to_string());
        if self.history.len() > HISTORY_LIMIT {
            self.history.remove(0);
        }
        append_history(line);
    }
}

/// Plain line reading for pipes, scripts and tests. Identical contract.
fn read_plain() -> io::Result<Option<String>> {
    let mut line = String::new();
    if io::stdin().read_line(&mut line)? == 0 {
        return Ok(None);
    }
    Ok(Some(line.trim_end_matches(['\n', '\r']).to_string()))
}

enum Action {
    Continue,
    Submit,
    Eof,
    Cancel,
}

fn handle_key(
    key: KeyEvent,
    buffer: &mut Vec<char>,
    cursor: &mut usize,
    editor: &mut Editor,
) -> Action {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

    match key.code {
        KeyCode::Enter => return Action::Submit,
        // Ctrl-J is what a pipe or a test harness sends for a newline; terminals
        // send CR for Enter, so both have to submit.
        KeyCode::Char('j') if ctrl => return Action::Submit,
        KeyCode::Char('d') if ctrl => {
            if buffer.is_empty() {
                return Action::Eof;
            }
            if *cursor < buffer.len() {
                buffer.remove(*cursor);
            }
        }
        KeyCode::Char('c') if ctrl => return Action::Cancel,
        KeyCode::Char('a') if ctrl => *cursor = 0,
        KeyCode::Char('e') if ctrl => *cursor = buffer.len(),
        KeyCode::Char('u') if ctrl => {
            buffer.clear();
            *cursor = 0;
        }
        KeyCode::Char('k') if ctrl => buffer.truncate(*cursor),
        KeyCode::Char('w') if ctrl => {
            let mut end = *cursor;
            while end > 0 && buffer[end - 1].is_whitespace() {
                end -= 1;
            }
            while end > 0 && !buffer[end - 1].is_whitespace() {
                end -= 1;
            }
            buffer.drain(end..*cursor);
            *cursor = end;
        }
        KeyCode::Char(ch) if !ctrl => {
            buffer.insert(*cursor, ch);
            *cursor += 1;
        }
        KeyCode::Tab => {
            for _ in 0..4 {
                buffer.insert(*cursor, ' ');
                *cursor += 1;
            }
        }
        KeyCode::Backspace => {
            if *cursor > 0 {
                buffer.remove(*cursor - 1);
                *cursor -= 1;
            }
        }
        KeyCode::Delete => {
            if *cursor < buffer.len() {
                buffer.remove(*cursor);
            }
        }
        KeyCode::Left => *cursor = cursor.saturating_sub(1),
        KeyCode::Right => *cursor = (*cursor + 1).min(buffer.len()),
        KeyCode::Home => *cursor = 0,
        KeyCode::End => *cursor = buffer.len(),
        KeyCode::Up => editor.history_up(buffer, cursor),
        KeyCode::Down => editor.history_down(buffer, cursor),
        _ => {}
    }
    Action::Continue
}

impl Editor {
    fn history_up(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
        if self.history.is_empty() || self.history_index == 0 {
            return;
        }
        if self.history_index == self.history.len() {
            self.draft = buffer.clone();
        }
        self.history_index -= 1;
        *buffer = self.history[self.history_index].chars().collect();
        *cursor = buffer.len();
    }

    fn history_down(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
        if self.history_index >= self.history.len() {
            return;
        }
        self.history_index += 1;
        if self.history_index == self.history.len() {
            *buffer = self.draft.clone();
        } else {
            *buffer = self.history[self.history_index].chars().collect();
        }
        *cursor = buffer.len();
    }
}

fn insert(buffer: &mut Vec<char>, cursor: &mut usize, text: &str) {
    let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
    for (offset, ch) in normalized.chars().enumerate() {
        buffer.insert(*cursor + offset, ch);
    }
    *cursor += normalized.chars().count();
}

fn terminal_width() -> usize {
    match terminal::size() {
        // A pty with no size reported reports 0 columns; treating that as 1
        // would make every character wrap onto its own line.
        Ok((cols, _)) if cols > 0 => cols as usize,
        _ => 80,
    }
}

/// Position of the cursor after consuming `prompt` plus `buffer[..upto]`.
///
/// Columns are 0-based, matching the cursor-move escape. Wrapping is modelled
/// the way terminals actually behave: filling the last column leaves the cursor
/// *in* that column, and only the next character wraps. Getting this wrong makes
/// the redraw move up one row too many and erase the line above the prompt.
fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) {
    let width = width.max(1);
    let mut row = 0usize;
    let mut col = 0usize;
    let mut pending_wrap = false;

    for ch in prompt
        .chars()
        .chain(buffer[..upto.min(buffer.len())].iter().copied())
    {
        if ch == '\n' {
            row += 1;
            col = 0;
            pending_wrap = false;
            continue;
        }
        let cells = cells(ch, col);
        if cells == 0 {
            // Combining marks draw on top of the previous cell and never wrap.
            continue;
        }
        if pending_wrap {
            row += 1;
            col = 0;
            pending_wrap = false;
        }
        if col + cells > width {
            row += 1;
            col = 0;
        }
        col += cells;
        if col >= width {
            col = width - 1;
            pending_wrap = true;
        }
    }

    (row, col)
}

/// Columns a character occupies at the given cursor position. Terminals expand
/// a tab to the next multiple of eight; wide characters occupy two cells.
fn cells(ch: char, col: usize) -> usize {
    if ch == '\t' {
        return 8 - (col % 8);
    }
    unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)
}

/// Where the caret physically is, relative to the first row of the input block.
/// The previous draw can leave the caret on any row, so a redraw must move up by
/// that row, not by the number of rows the block occupies.
#[derive(Default, Clone, Copy)]
struct DrawState {
    cursor_row: usize,
}

fn draw(
    prompt: &str,
    buffer: &[char],
    cursor: usize,
    state: &mut DrawState,
) -> io::Result<()> {
    let mut out = io::stdout();
    draw_to(&mut out, prompt, buffer, cursor, state)?;
    out.flush()
}

fn draw_to<W: Write>(
    out: &mut W,
    prompt: &str,
    buffer: &[char],
    cursor: usize,
    state: &mut DrawState,
) -> io::Result<()> {
    let width = terminal_width();

    let (end_row, _) = layout(prompt, buffer, buffer.len(), width);
    let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width);

    if state.cursor_row > 0 {
        execute!(out, MoveUp(clamp(state.cursor_row)))?;
    }
    execute!(out, MoveToColumn(0), Clear(ClearType::FromCursorDown))?;

    let mut text = String::with_capacity(prompt.len() + buffer.len());
    text.push_str(prompt);
    for ch in buffer {
        if *ch == '\n' {
            text.push_str("\r\n");
        } else {
            text.push(*ch);
        }
    }
    out.write_all(text.as_bytes())?;

    if end_row > cursor_row {
        execute!(out, MoveUp(clamp(end_row - cursor_row)))?;
    }
    execute!(out, MoveToColumn(clamp(cursor_col)))?;

    state.cursor_row = cursor_row;
    Ok(())
}

fn clamp(value: usize) -> u16 {
    value.min(u16::MAX as usize) as u16
}

struct RawGuard;

impl RawGuard {
    fn enable() -> io::Result<Self> {
        terminal::enable_raw_mode()?;
        execute!(io::stdout(), EnableBracketedPaste)?;
        Ok(RawGuard)
    }
}

impl Drop for RawGuard {
    fn drop(&mut self) {
        let _ = execute!(io::stdout(), DisableBracketedPaste);
        let _ = terminal::disable_raw_mode();
    }
}

fn history_path() -> PathBuf {
    crate::session::data_root().join("history")
}

fn load_history() -> Vec<String> {
    let path = history_path();
    let text = std::fs::read_to_string(&path).unwrap_or_default();
    let mut lines: Vec<String> = text
        .split('\n')
        .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}'))
        .map(|line| line.replace('\u{0}', "\n"))
        .collect();
    if lines.len() > HISTORY_LIMIT {
        lines.drain(..lines.len() - HISTORY_LIMIT);
        // Keep the file from growing without bound, not just the in-memory list.
        if lines.len() * 2 < text.lines().count() {
            let body: Vec<String> = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect();
            let _ = std::fs::write(&path, format!("{}\n", body.join("\n")));
        }
    }
    lines
}

fn append_history(line: &str) {
    let path = history_path();
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Some(parent) = path.parent() {
        let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
    }
    if let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)
    {
        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
        // One record per line, so newlines inside a prompt are escaped.
        let _ = writeln!(file, "{}", line.replace('\n', "\u{0}"));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn layout_accounts_for_newlines() {
        let buffer: Vec<char> = "ab\ncd".chars().collect();
        assert_eq!(layout("> ", &buffer, 0, 80), (0, 2));
        assert_eq!(layout("> ", &buffer, 2, 80), (0, 4));
        assert_eq!(layout("> ", &buffer, 3, 80), (1, 0));
        assert_eq!(layout("> ", &buffer, 5, 80), (1, 2));
    }

    #[test]
    fn layout_wraps_lazily_at_the_terminal_width() {
        let buffer: Vec<char> = "abcdef".chars().collect();
        // Prompt takes 2 columns, so six more fill the 8-column row exactly.
        // The cursor stays in the last column until another character arrives;
        // counting a new row here is what used to erase the line above.
        assert_eq!(layout("> ", &buffer, 6, 8), (0, 7));
        assert_eq!(layout("> ", &buffer, 3, 8), (0, 5));

        let mut longer = buffer.clone();
        longer.push('g');
        assert_eq!(layout("> ", &longer, 7, 8), (1, 1));
    }

    #[test]
    fn width_falls_back_when_the_terminal_reports_none() {
        // Cannot control the real terminal here, but the fallback path must not
        // produce a one-column layout.
        assert!(terminal_width() >= 1);
    }

    fn drawn(prompt: &str, buffer: &str, cursor: usize, state: &mut DrawState) -> String {
        let chars: Vec<char> = buffer.chars().collect();
        let mut out = Vec::new();
        draw_to(&mut out, prompt, &chars, cursor, state).unwrap();
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn redraw_moves_up_by_the_caret_row_not_the_block_height() {
        let mut state = DrawState::default();

        // First draw with the caret at the end of a two-line buffer.
        let first = drawn("> ", "one\ntwo", 7, &mut state);
        assert_eq!(state.cursor_row, 1, "caret ends on the second row");
        assert!(!first.contains("\u{1b}[1A"), "first draw must not move up");

        // Move the caret to the first row. The previous caret was on row 1, so
        // the redraw may move up exactly one row — not `rows - 1` from row 0,
        // which would land on the line above the prompt and erase it.
        let second = drawn("> ", "one\ntwo", 0, &mut state);
        assert!(
            second.starts_with("\u{1b}[1A"),
            "expected one MoveUp, got {:?}",
            second
        );
        assert_eq!(state.cursor_row, 0);

        // Drawing again with the caret already on row 0 must not move up
        // *before* clearing; the only MoveUp is the one after writing, which
        // puts the caret back on the first row.
        let third = drawn("> ", "one\ntwo", 0, &mut state);
        assert!(
            !third.starts_with("\u{1b}[1A"),
            "must not move up before clearing: {third:?}"
        );
        assert_eq!(
            third.matches("\u{1b}[1A").count(),
            1,
            "exactly one repositioning move after writing: {third:?}"
        );
    }

    #[test]
    fn a_combining_mark_at_the_wrap_boundary_does_not_wrap() {
        let text: Vec<char> = ['a', 'b', '\u{0301}'].to_vec();
        // width 2: 'b' fills the last column (pending wrap), the mark must not
        // consume that pending wrap and move to a new row.
        let (row, col) = layout("", &text, 3, 2);
        assert_eq!((row, col), (0, 1));
    }

    #[test]
    fn layout_counts_wide_and_combining_characters() {
        let wide: Vec<char> = "日本語".chars().collect();
        assert_eq!(layout("> ", &wide, 3, 20), (0, 8));

        let combining: Vec<char> = "e\u{0301}".chars().collect();
        assert_eq!(layout("", &combining, 2, 20), (0, 1));
    }

    #[test]
    fn layout_expands_tabs_to_the_next_stop() {
        let tab: Vec<char> = "\t".chars().collect();
        assert_eq!(layout("> ", &tab, 1, 80), (0, 8));
        assert_eq!(layout("", &tab, 1, 80), (0, 8));
    }

    #[test]
    fn insert_normalises_line_endings() {
        let mut buffer = vec!['a'];
        let mut cursor = 1;
        insert(&mut buffer, &mut cursor, "b\r\nc");
        assert_eq!(buffer, vec!['a', 'b', '\n', 'c']);
        assert_eq!(cursor, 4);
    }

    #[test]
    fn history_walks_both_ways() {
        let mut editor = Editor {
            interactive: false,
            history: vec!["one".into(), "two".into()],
            history_index: 0,
            draft: Vec::new(),
        };
        editor.history_index = editor.history.len();

        let mut buffer = vec!['x'];
        let mut cursor = 1;
        editor.history_up(&mut buffer, &mut cursor);
        assert_eq!(buffer.iter().collect::<String>(), "two");
        editor.history_up(&mut buffer, &mut cursor);
        assert_eq!(buffer.iter().collect::<String>(), "one");
        editor.history_up(&mut buffer, &mut cursor);
        assert_eq!(buffer.iter().collect::<String>(), "one");

        editor.history_down(&mut buffer, &mut cursor);
        assert_eq!(buffer.iter().collect::<String>(), "two");
        editor.history_down(&mut buffer, &mut cursor);
        assert_eq!(buffer.iter().collect::<String>(), "x");
    }
}