curd-editor 0.27.2

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
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
//! The editor's part of the screen: lines, colours, the status bar, the mouse.

use super::*;

impl Editor {
    // ---- Drawing -------------------------------------------------------

    /// Width of the column left of the text: an error/warning marker (only
    /// with a language server), the line number, a fold marker, and a
    /// change marker (only for files in git).
    /// An empty document shows the welcome screen with no gutter.
    pub fn gutter_width(&self) -> usize {
        if self.document.is_empty() {
            0
        } else {
            self.show_diagnostics as usize
                + self.document.len().to_string().len()
                + 1
                + self.git_base.is_some() as usize
        }
    }

    /// Moves the view so the cursor is inside a text area of `width` x `height`.
    pub fn scroll(&mut self, width: usize, height: usize) {
        self.page_rows = height;
        // The top line may have been hidden by a fold or removed by an edit.
        self.row_offset = self.folds.header_of(self.row_offset.min(self.cursor_y));
        if height > 0 && self.folds.rows_between(self.row_offset, self.cursor_y) >= height {
            // The cursor is below the view: put it on the last row, by
            // walking up from it.
            let mut top = self.cursor_y;
            for _ in 1..height {
                match self.folds.prev_visible(top) {
                    Some(above) => top = above,
                    None => break,
                }
            }
            self.row_offset = top;
        }
        let column = self.column_of(self.cursor_x, self.cursor_y);
        if column < self.col_offset {
            self.col_offset = column;
        }
        if width > 0 && column >= self.col_offset + width {
            self.col_offset = column - width + 1;
        }
    }

    /// The screen column, counted from the start of the line, where
    /// character `x` of line `y` is drawn. It is `x` itself unless there
    /// are tabs or wide characters before it.
    pub(super) fn column_of(&self, x: usize, y: usize) -> usize {
        let Some(line) = self.document.lines.get(y) else {
            return x;
        };
        if line.is_ascii() && !line.contains('\t') {
            return x;
        }
        let cells = cells(line);
        cells.iter().position(|(index, _)| *index >= x).unwrap_or(cells.len())
    }

    /// The character of line `y` drawn at screen column `column`, counted
    /// from the start of the line: the end of the line, if it is shorter.
    pub(super) fn char_at(&self, column: usize, y: usize) -> usize {
        let Some(line) = self.document.lines.get(y) else {
            return 0;
        };
        match cells(line).get(column) {
            Some((index, _)) => *index,
            None => line.chars().count(),
        }
    }

    /// The text shown for line `y`. A collapsed block shows its first line
    /// followed by `...` (and its closing line, for brace blocks), like
    /// `fn main() { ... }`.
    pub(super) fn display_line(&self, y: usize) -> String {
        let line = &self.document.lines[y];
        match self.folds.end_of(y) {
            Some(_) if self.language.is_some_and(Language::blocks_by_indent) => format!("{line} ..."),
            Some(end) => format!("{line} ... {}", self.document.lines[end].trim()),
            None => line.clone(),
        }
    }

    /// The status bar, exactly `width` cells wide, in parts that each
    /// have their place and their colour. On the left: a question being
    /// asked, a message, the problem on the cursor line, or else the file
    /// name with whether it has unsaved changes and how many problems.
    /// On the right: the git branch, the language and the cursor position;
    /// the first two give way when there is no room.
    pub(super) fn status_row(&self, width: usize) -> Row {
        let mut left: Vec<(Style, String)> = Vec::new();
        if let Some(prompt) = &self.prompt {
            let note = match self.message.as_str() {
                "" => String::new(),
                message => format!("   ({message})"),
            };
            left.push((Style::Bar, format!("{}{}{note}", self.prompt_label(prompt.kind), prompt.text)));
        } else if !self.message.is_empty() {
            left.push((Style::Bar, self.message.clone()));
        } else if let Some(diagnostic) = self.diagnostic_on(self.cursor_y) {
            let (style, kind) = match diagnostic.severity {
                Severity::Error => (Style::BarError, "error"),
                Severity::Warning => (Style::BarWarn, "warning"),
                Severity::Info => (Style::Bar, "info"),
            };
            left.push((style, format!("{kind}: {}", diagnostic.message)));
        } else {
            // Just the file name: a full path rarely fits.
            left.push((Style::BarBold, self.name().to_string()));
            if self.document.dirty {
                left.push((Style::BarWarn, " [modified]".into()));
            }
            let count = |severity| {
                self.diagnostics
                    .iter()
                    .filter(|diagnostic| diagnostic.severity == severity)
                    .count()
            };
            let (errors, warnings) = (count(Severity::Error), count(Severity::Warning));
            if errors + warnings > 0 {
                // Each count in its colour, when there is something to count.
                let style = |count, style| if count > 0 { style } else { Style::BarDim };
                left.push((style(errors, Style::BarError), format!("  E:{errors}")));
                left.push((style(warnings, Style::BarWarn), format!(" W:{warnings}")));
            }
        }
        let mut right: Vec<(Style, String)> = Vec::new();
        if let Some(branch) = &self.branch {
            right.push((Style::BarDim, format!("{branch}  ")));
        }
        if let Some(language) = self.language {
            right.push((Style::BarDim, format!("{}  ", language.name())));
        }
        right.push((Style::Bar, format!("Ln {}, Col {}", self.cursor_y + 1, self.cursor_x + 1)));

        let cells = |parts: &[(Style, String)]| -> usize {
            parts.iter().map(|(_, text)| widen(text).chars().count()).sum()
        };
        // What matters less on the right goes first when it is a squeeze;
        // if even the position does not fit, the left part has the bar.
        while right.len() > 1 && cells(&left) + 1 + cells(&right) > width {
            right.remove(0);
        }
        if cells(&left) + 1 + cells(&right) > width {
            right.clear();
        }
        let gap = width.saturating_sub(cells(&left) + cells(&right));
        left.push((Style::Bar, " ".repeat(gap)));
        left.extend(right);

        let mut row = Row::new();
        let mut room = width;
        for (style, text) in left {
            let text: String = widen(&text).chars().take(room).collect();
            room -= text.chars().count();
            if !text.is_empty() {
                row.push(Span::new(style, text));
            }
        }
        row
    }

    /// The columns of a status bar `width` wide that show the git branch:
    /// from, and up to. `None` if it is not shown.
    pub fn branch_columns(&self, width: usize) -> Option<(usize, usize)> {
        let name = format!("{}  ", self.branch.as_ref()?);
        let mut at = 0;
        for span in self.status_row(width) {
            let cells = span.text.chars().count();
            if span.style == Style::BarDim && span.text == widen(&name) {
                return Some((at, at + cells - 2));
            }
            at += cells;
        }
        None
    }

    /// The text of the status bar.
    #[cfg(test)]
    pub(super) fn status_line(&self, width: usize) -> String {
        self.status_row(width).iter().map(|span| span.text.as_str()).collect()
    }

    /// How line `y` compares with the last git commit.
    pub(super) fn mark_on(&self, y: usize) -> Mark {
        let Some(base) = &self.git_base else {
            return Mark::Same;
        };
        let marks = self
            .marks
            .get_or_init(|| diff::marks(base, &self.document.lines));
        marks.get(y).copied().unwrap_or_default()
    }

    /// One row of text: problem marker, line number, fold marker, change
    /// marker, text.
    pub(super) fn render_line(&self, y: usize, gutter: usize, text_width: usize) -> Row {
        let mut row = Row::new();
        let mut number_width = gutter - 1 - self.git_base.is_some() as usize;
        if self.show_diagnostics {
            number_width -= 1;
            row.push(match self.diagnostic_on(y).map(|d| d.severity) {
                Some(Severity::Error) => Span::new(Style::Error, "E"),
                Some(Severity::Warning) => Span::new(Style::Warning, "W"),
                Some(Severity::Info) => Span::new(Style::Dim, "i"),
                None => Span::new(Style::Plain, " "),
            });
        }
        // `+` marks a collapsed block, `-` a line that can be collapsed.
        let marker = if self.folds.end_of(y).is_some() {
            '+'
        } else if self.blocks().end(y).is_some() {
            '-'
        } else {
            ' '
        };
        // The line the cursor is on stands out: its number, and its text.
        let current = y == self.cursor_y;
        row.push(Span::new(
            Style::LineNumber(current),
            format!("{:>number_width$}{marker}", y + 1),
        ));
        if self.git_base.is_some() {
            // A bar beside lines that are new or changed since the last
            // commit, and a dash where lines were removed.
            row.push(match self.mark_on(y) {
                Mark::Added => Span::new(Style::Colored(Color::Green), "▎"),
                Mark::Modified => Span::new(Style::Colored(Color::Yellow), "▎"),
                Mark::RemovedBelow => Span::new(Style::Colored(Color::Red), "▁"),
                Mark::RemovedAbove => Span::new(Style::Colored(Color::Red), "▔"),
                // Nothing to mark: on the cursor line the highlight runs
                // through this column too.
                Mark::Same if y == self.cursor_y => {
                    let on_line = Decoration { current: true, ..Decoration::default() };
                    Span::new(Style::Code(on_line), " ")
                }
                Mark::Same => Span::new(Style::Plain, " "),
            });
        }
        // Cut the text into pieces that share one look.
        let decorations = self.decorations(y);
        // The line as cells of the screen (a tab is several, a wide
        // character two), of which the part in view is drawn.
        let line = cells(&self.display_line(y));
        let last = (self.col_offset + text_width).min(line.len());
        let mut visible: Vec<(usize, char)> = line.get(self.col_offset..last).unwrap_or_default().to_vec();
        // A wide character cut in two by an edge of the view cannot be
        // shown: a space stands in for the half that is in view.
        if let Some(first) = visible.first_mut().filter(|cell| cell.1 == WIDE_PAD) {
            first.1 = ' ';
        }
        if line.get(last).is_some_and(|cell| cell.1 == WIDE_PAD)
            && let Some(cut) = visible.last_mut()
        {
            cut.1 = ' ';
        }
        let mut piece: Option<(Decoration, String)> = None;
        for (x, c) in visible {
            let mut decoration = decorations.get(x).copied().unwrap_or_default();
            decoration.current = current;
            match &mut piece {
                Some((same, text)) if *same == decoration => text.push(c),
                _ => {
                    row.extend(piece.take().map(code_span));
                    piece = Some((decoration, c.to_string()));
                }
            }
        }
        row.extend(piece.map(code_span));
        if current {
            // An end to the row that carries the highlight on to the edge
            // of the window, also when the line is empty.
            let rest = Decoration { current: true, ..Decoration::default() };
            row.push(Span::new(Style::Code(rest), ""));
        }
        row
    }

    /// The colour and decoration of each character of line `y`: colours
    /// from the built-in scanner, then the server's more exact ones over
    /// them, then underlines, fading and strike-through from the problems
    /// that cover the line.
    pub(super) fn decorations(&self, y: usize) -> Vec<Decoration> {
        let line = &self.document.lines[y];
        let len = line.chars().count();
        let mut decorations = vec![Decoration::default(); len];
        let mut scanned = Vec::new();
        if let Some(language) = self.language {
            let state = self.line_states.get(y).copied().unwrap_or_default();
            highlight::lex_line(line, language, state, &mut scanned);
        }
        for token in scanned.iter().chain(self.highlights.on(y)) {
            for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
                decoration.kind = token.kind;
            }
        }
        // Selected text is shown in reverse.
        if let Some((start, end)) = self.selection()
            && (start.1..=end.1).contains(&y)
        {
            let from = if y == start.1 { start.0 } else { 0 };
            let to = if y == end.1 { end.0 } else { len };
            for decoration in &mut decorations[from.min(len)..to.min(len)] {
                decoration.marked = true;
            }
        }
        // While a search is open, every match is shown.
        if let Some(text) = self.shown_query() {
            let width = text.chars().count();
            for start in search::matches(line, text) {
                for decoration in &mut decorations[start..(start + width).min(len)] {
                    decoration.marked = true;
                }
            }
        }
        let encoding = self.encoding();
        for diagnostic in &self.diagnostics {
            if diagnostic.line > y {
                // They are sorted by line: none of the rest reach this one.
                break;
            }
            if diagnostic.end_line < y {
                continue;
            }
            // A problem spanning several lines covers the first from its
            // start column, the last up to its end column, and all between.
            let start = if diagnostic.line == y {
                encoding.to_chars(line, diagnostic.start)
            } else {
                0
            };
            let mut end = if diagnostic.end_line == y {
                encoding.to_chars(line, diagnostic.end)
            } else {
                len
            };
            if diagnostic.line == diagnostic.end_line {
                // Some problems point at a single spot: mark one character.
                end = end.max(start + 1).min(len);
            }
            let underlined = matches!(diagnostic.severity, Severity::Error | Severity::Warning);
            for decoration in decorations.iter_mut().take(end).skip(start) {
                decoration.underlined |= underlined;
                decoration.faded |= diagnostic.unnecessary;
                decoration.struck |= diagnostic.deprecated;
            }
        }
        decorations
    }

    /// Everything that should be on a `width` x `height` screen, row by row:
    /// the text, the hover panel if open, and the status bar on the last row.
    pub fn render(&self, width: usize, height: usize) -> Vec<Row> {
        let text_rows = height.saturating_sub(1);
        let gutter = self.gutter_width();
        let text_width = width.saturating_sub(gutter);
        let mut rows = Vec::with_capacity(height);

        // Collapsed lines are skipped, so walk the visible lines one by one.
        let mut next_line = Some(self.row_offset).filter(|y| *y < self.document.len());
        for row in 0..text_rows {
            if let Some(y) = next_line {
                rows.push(self.render_line(y, gutter, text_width));
                next_line = self.folds.next_visible(y, self.document.len());
            } else if self.document.is_empty() && row == text_rows / 3 {
                let msg = concat!("curd editor -- v", env!("CARGO_PKG_VERSION"));
                let padding = width.saturating_sub(msg.len()) / 2;
                let text = format!("~{}{}", " ".repeat(padding), msg);
                rows.push(vec![Span::new(Style::Plain, text)]);
            } else {
                rows.push(vec![Span::new(Style::Plain, "~")]);
            }
        }

        self.render_completion(&mut rows, width, text_rows);

        // The hover panel sits at the bottom, or at the top when it would
        // cover the cursor.
        let panel = self.info.len().min(text_rows / 2);
        if panel > 0 {
            let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
            let top = if cursor_row >= text_rows - panel { 0 } else { text_rows - panel };
            for (offset, line) in self.info.iter().take(panel).enumerate() {
                let text = fit(&format!(" {line}"), width);
                rows[top + offset] = vec![Span::new(Style::Menu, text)];
            }
        }

        if height > 0 {
            rows.push(self.status_row(width));
        }
        rows
    }

    /// Lays the list of suggestions over the text: under the cursor, or
    /// above it when there is more room there.
    pub(super) fn render_completion(&self, rows: &mut [Row], width: usize, text_rows: usize) {
        let Some(completion) = &self.completion else {
            return;
        };
        let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
        let below = text_rows.saturating_sub(cursor_row + 1);
        let wanted = completion.shown.len().min(MENU_ROWS);
        let (top, count) = if below >= wanted || below >= cursor_row {
            (cursor_row + 1, wanted.min(below))
        } else {
            let count = wanted.min(cursor_row);
            (cursor_row - count, count)
        };
        // Keep the picked one in view when the list is longer than fits.
        let first = (completion.selected + 1).saturating_sub(count);
        let lines: Vec<String> = completion.shown[first..first + count]
            .iter()
            .map(|index| {
                let item = &completion.items[*index];
                format!(" {}  {}", item.label, item.detail).trim_end().to_string() + " "
            })
            .collect();
        let widest = lines.iter().map(|line| line.chars().count()).max().unwrap_or(0);
        let menu_width = widest.min(MENU_WIDTH).min(width);
        // Line the labels up with the word being typed.
        let x = (self.gutter_width() + self.column_of(completion.start, completion.y))
            .saturating_sub(self.col_offset + 1)
            .min(width - menu_width);
        for (offset, line) in lines.iter().enumerate() {
            let style = if first + offset == completion.selected {
                Style::Selected
            } else {
                Style::Menu
            };
            overlay(&mut rows[top + offset], x, &Span::new(style, fit(line, menu_width)));
        }
    }

    /// Where the cursor is within the editor's part of the screen, as
    /// (column, row).
    pub fn cursor_on_screen(&self) -> (usize, usize) {
        if let Some(prompt) = &self.prompt {
            // In the status bar, after what has been typed.
            let typed = widen(&self.prompt_label(prompt.kind)).chars().count()
                + widen(&prompt.text).chars().count();
            return (typed, self.page_rows);
        }
        let column = self.column_of(self.cursor_x, self.cursor_y);
        (
            self.gutter_width() + column.saturating_sub(self.col_offset),
            self.folds.rows_between(self.row_offset, self.cursor_y),
        )
    }

    /// A mouse click at column `x`, row `y` of the editor's part of the
    /// screen: the cursor goes to the character under the pointer.
    pub fn click(&mut self, x: usize, y: usize) {
        self.anchor = None;
        let on_a_line = self.point_at(x, y);
        // A click beside a line that starts a block folds or unfolds it.
        let foldable = self.folds.end_of(self.cursor_y).is_some()
            || self.blocks().end(self.cursor_y).is_some();
        if on_a_line && x < self.gutter_width() && foldable {
            self.toggle_fold();
        }
    }

    /// The mouse moved to column `x`, row `y` with its button held: the
    /// text from where it was pressed to here is selected.
    pub fn drag(&mut self, x: usize, y: usize) {
        self.anchor.get_or_insert((self.cursor_x, self.cursor_y));
        self.point_at(x, y);
    }

    /// Puts the cursor under the pointer. Returns false if the pointer is
    /// below the last line (the cursor then goes to the last line).
    pub(super) fn point_at(&mut self, x: usize, y: usize) -> bool {
        self.message.clear();
        self.info.clear();
        self.completion = None;
        // Walk down the visible lines to the clicked row.
        let mut line = self.row_offset;
        let mut on_a_line = line < self.document.len();
        for _ in 0..y {
            match self.folds.next_visible(line, self.document.len()) {
                Some(next) => line = next,
                None => {
                    on_a_line = false;
                    break;
                }
            }
        }
        if line < self.document.len() {
            self.cursor_y = line;
            let column = x.saturating_sub(self.gutter_width()) + self.col_offset;
            self.cursor_x = self.char_at(column, line);
        }
        on_a_line
    }

    /// The mouse wheel: moves `lines` lines down (up, when negative).
    pub fn wheel(&mut self, lines: isize) {
        self.completion = None;
        for _ in 0..lines.unsigned_abs() {
            let next = if lines > 0 {
                self.folds.next_visible(self.cursor_y, self.document.len())
            } else {
                self.folds.prev_visible(self.cursor_y)
            };
            match next {
                Some(y) => self.cursor_y = y,
                None => break,
            }
        }
        self.clamp_cursor_x();
    }
}