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
use std::cell::{OnceCell, RefCell};
use std::path::Path;
use std::rc::Rc;
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::style::Color;
use crate::diff::{self, Mark};
use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{self, Highlights, LineState};
use crate::history::{Change, History};
use crate::lsp::{Client, CompletionItem, Diagnostic, Encoding, Location, Reply, Severity};
use crate::screen::{cells, fit, overlay, widen, Decoration, Row, Span, Style, WIDE_PAD};
use crate::search;
use crate::snippets::Language;
mod editing;
mod prompts;
mod completion;
mod code;
mod draw;
#[cfg(test)]
mod tests;
/// Most suggestions shown at once, and the widest the list gets.
const MENU_ROWS: usize = 8;
const MENU_WIDTH: usize = 50;
/// A question asked in the status bar.
#[derive(Clone, Copy, Debug, PartialEq)]
enum PromptKind {
Find,
SaveAs,
/// The text to replace, which is searched for like `Find`.
Replace,
/// What to replace it with.
With,
/// The number of the line to go to.
GoTo,
}
struct Prompt {
kind: PromptKind,
/// What has been typed in answer so far.
text: String,
}
/// The list of suggestions from the language server, open under the cursor.
struct Completion {
items: Vec<CompletionItem>,
/// The items that match what has been typed, best first, as indexes
/// into `items`. Never empty while the list is open.
shown: Vec<usize>,
/// Which of `shown` is picked.
selected: usize,
/// True once the arrows have been used to pick one.
moved: bool,
/// Where the word being completed starts: column and line.
start: usize,
y: usize,
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// One open file: its text, cursor, view and everything known about it.
pub struct Editor {
pub document: Document,
/// The file's absolute path, which is how the language server and the
/// rest of the workspace refer to it. `None` for a file with no name yet.
pub abs_path: Option<String>,
/// Decides snippets, folding style and language server. `None` for
/// unknown file types.
pub language: Option<Language>,
folds: Folds,
/// Where foldable blocks are. Worked out on first use after each edit.
blocks: OnceCell<Blocks>,
/// Whether each line starts inside a comment or string left open by an
/// earlier line, for the built-in colouring. Empty for unknown file types.
line_states: Vec<LineState>,
/// The first and last line edited since `line_states` was brought up
/// to date.
stale: Option<(usize, usize)>,
cursor_x: usize,
cursor_y: usize,
row_offset: usize,
col_offset: usize,
/// Shown in the status bar until the next key press.
pub message: String,
/// Lines shown in a panel over the text until the next key press
/// (hover documentation).
info: Vec<String>,
/// Set for something to look at that is not a file (the changes since
/// the last commit): what it is called. It cannot be edited or saved.
pub view: Option<String>,
/// The git branch the project is on, for the status bar.
pub branch: Option<String>,
/// Set by a successful save, for the workspace to notice.
pub just_saved: bool,
/// Set when a file with no name was given one, for the workspace.
pub renamed: bool,
/// Rows of text on screen at the last draw: one page for PageUp/PageDown.
page_rows: usize,
history: History,
/// The question in the status bar, while one is being asked.
prompt: Option<Prompt>,
/// Where the cursor was when the search started.
find_from: (usize, usize),
/// The last thing searched for, for "find next".
last_query: String,
/// What "replace" is looking for, once that has been answered.
replace_what: String,
/// The other end of the selected text: it runs from here to the cursor.
anchor: Option<(usize, usize)>,
/// Set by a key that used the selection and wants it kept.
keep_selection: bool,
/// Text that was just copied or cut, for the workspace to put on the
/// clipboard.
pub copied: Option<String>,
completion: Option<Completion>,
/// The word (start column, line) suggestions were last asked for, so
/// each word is asked about once.
completion_word: Option<(usize, usize)>,
/// The number of the newest request for suggestions. Answers to older
/// ones are out of date.
completion_request: Option<u64>,
/// The file's lines in the last git commit, if it is in one.
git_base: Option<Vec<String>>,
/// How each line compares with `git_base`. Worked out on first use
/// after each edit.
marks: OnceCell<Vec<Mark>>,
/// The language server looking after this file. It is shared with the
/// other open files of the same project and language.
pub lsp: Option<Rc<RefCell<Client>>>,
/// Problems reported by the language server, sorted by line.
pub diagnostics: Vec<Diagnostic>,
/// Colours from the language server.
pub highlights: Highlights,
/// True while a language server is attached: adds a column for
/// error and warning markers.
pub show_diagnostics: bool,
}
impl Editor {
pub fn new(document: Document) -> Self {
let language = document.path.as_deref().and_then(Language::from_path);
let abs_path = document
.path
.as_deref()
.and_then(|path| std::path::absolute(path).ok())
.map(|path| path.to_string_lossy().into_owned());
Self {
language,
abs_path,
line_states: match language {
Some(language) => highlight::line_states(&document.lines, language),
None => Vec::new(),
},
stale: None,
document,
folds: Folds::default(),
blocks: OnceCell::new(),
cursor_x: 0,
cursor_y: 0,
row_offset: 0,
col_offset: 0,
message: String::new(),
info: Vec::new(),
view: None,
branch: None,
just_saved: false,
renamed: false,
page_rows: 0,
history: History::default(),
prompt: None,
find_from: (0, 0),
last_query: String::new(),
replace_what: String::new(),
anchor: None,
keep_selection: false,
copied: None,
completion: None,
completion_word: None,
completion_request: None,
git_base: None,
marks: OnceCell::new(),
lsp: None,
diagnostics: Vec::new(),
highlights: Highlights::default(),
show_diagnostics: false,
}
}
/// Puts a language server in charge of this file.
pub fn attach_lsp(&mut self, lsp: Rc<RefCell<Client>>) {
self.lsp = Some(lsp);
self.show_diagnostics = true;
}
/// Forgets the language server, and everything it said about the file.
pub fn detach_lsp(&mut self) {
self.lsp = None;
self.diagnostics.clear();
self.highlights = Highlights::default();
self.show_diagnostics = false;
self.completion = None;
self.completion_request = None;
}
/// Sets what the file looked like in the last git commit (`None` if it
/// is not in one), which the change markers compare against.
pub fn set_git_base(&mut self, base: Option<Vec<String>>) {
self.git_base = base;
self.marks = OnceCell::new();
}
/// The selected text, and the first and last line it touches
/// (counted from 0).
pub fn selected_text(&self) -> Option<(usize, usize, String)> {
let (start, end) = self.selection()?;
let (first, last) = self.selected_lines();
Some((first, last, self.text_between(start, end)))
}
/// The line the cursor is on, counted from 0.
pub fn cursor_line(&self) -> usize {
self.cursor_y
}
/// Something to look at that is not a file: `lines`, called `title`,
/// coloured as `language`.
pub fn view_of(title: &str, lines: Vec<String>, language: Language) -> Self {
let mut editor = Self::new(Document {
lines,
..Document::default()
});
editor.language = Some(language);
editor.line_states = highlight::line_states(&editor.document.lines, language);
editor.view = Some(title.to_string());
editor
}
/// In a view of changes: the file the cursor line belongs to, and the
/// line of that file it shows (counted from 0), if it is on a change.
pub fn change_at_cursor(&self) -> Option<(String, usize)> {
self.view.as_ref()?;
let lines = &self.document.lines[..=self.cursor_y.min(self.document.len().checked_sub(1)?)];
// The nearest `@@ -a,b +c,d @@` above says which line of the new
// file the lines under it start at; lines taken out do not count.
let header = lines.iter().rposition(|line| line.starts_with("@@"))?;
let start: usize = lines[header].split('+').nth(1)?.split([',', ' ']).next()?.parse().ok()?;
let below = lines[header + 1..].iter().filter(|line| !line.starts_with('-')).count();
let file = lines[..header].iter().rev().find_map(|line| line.strip_prefix("+++ b/"))?;
Some((file.to_string(), (start + below).saturating_sub(2).max(start.saturating_sub(1))))
}
/// The file's name without its folders, for tabs and the status bar.
pub fn name(&self) -> &str {
if let Some(title) = &self.view {
return title;
}
self.document
.path
.as_deref()
.and_then(|path| Path::new(path).file_name())
.and_then(|name| name.to_str())
.unwrap_or("[No Name]")
}
pub fn handle_key(&mut self, key: KeyEvent) {
// Windows reports both key press and key release; only act on press.
if key.kind == KeyEventKind::Release {
return;
}
// Messages and the hover panel only last until the next key.
self.message.clear();
self.info.clear();
if self.prompt.is_some() {
self.prompt_key(key);
self.recolour();
return;
}
// Everything one key changes is undone together, and a run of
// plain typing is too.
let command = KeyModifiers::CONTROL | KeyModifiers::ALT;
let typing = matches!(key.code, KeyCode::Char(c) if !key.modifiers.intersects(command) && c != ' ');
// Moving with Shift held selects, starting where the cursor is.
let moving = matches!(
key.code,
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right
| KeyCode::Home | KeyCode::End | KeyCode::PageUp | KeyCode::PageDown
);
let selecting = moving && key.modifiers.contains(KeyModifiers::SHIFT);
if selecting {
self.anchor.get_or_insert((self.cursor_x, self.cursor_y));
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let keeps_selection = selecting || matches!(key.code, KeyCode::Char('a' | 'c') if ctrl);
self.history.begin((self.cursor_x, self.cursor_y), typing);
self.edit_key(key);
// Any other key ends the selection (after using it, if it does).
let kept = std::mem::take(&mut self.keep_selection);
if !keeps_selection && !kept {
self.anchor = None;
}
self.clamp_cursor_x();
self.history.commit((self.cursor_x, self.cursor_y));
self.recolour();
}
fn edit_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let typed = matches!(key.code, KeyCode::Char(_) if !ctrl && !alt);
// While the list of suggestions is open it takes a few keys itself.
if let Some(completion) = &self.completion {
match key.code {
KeyCode::Up => return self.move_selection(-1),
KeyCode::Down => return self.move_selection(1),
KeyCode::Esc => return self.completion = None,
// Tab on a snippet trigger still expands the snippet,
// unless a suggestion was picked with the arrows.
KeyCode::Tab if completion.moved || self.snippet_at_cursor().is_none() => {
return self.accept_completion();
}
KeyCode::Backspace => {}
_ if typed => {}
_ => self.completion = None,
}
}
if !typed && key.code != KeyCode::Backspace {
self.completion_word = None;
}
match key.code {
KeyCode::Char('s') if ctrl => self.save_or_ask(),
KeyCode::Char('z') if ctrl => self.undo(),
KeyCode::Char('y') if ctrl => self.redo(),
// Each command has an Alt or function-key form as well, because
// some terminals (VS Code's, for one) keep Ctrl keys for themselves.
KeyCode::Char('a') if ctrl => self.select_all(),
KeyCode::Char('c') if ctrl => {
self.copy();
}
KeyCode::Char('x') if ctrl => self.cut(),
KeyCode::Char('f') if ctrl || alt => self.open_prompt(PromptKind::Find),
KeyCode::Char('r') if ctrl || alt => self.open_prompt(PromptKind::Replace),
KeyCode::Char('l') if ctrl || alt => self.open_prompt(PromptKind::GoTo),
// Ctrl+/ reaches a program in a terminal as Ctrl+7.
KeyCode::Char('7' | '/') if ctrl => self.toggle_comment(),
KeyCode::Char('c') if alt => self.toggle_comment(),
KeyCode::Char('d') if alt => self.duplicate_line(),
KeyCode::Up if alt => self.move_line(false),
KeyCode::Down if alt => self.move_line(true),
KeyCode::BackTab => self.shift_lines(false),
// Tab with several lines selected indents them all.
KeyCode::Tab if self.selection().is_some_and(|(start, end)| start.1 != end.1) => {
self.shift_lines(true);
}
KeyCode::Char('n') if alt => self.find_again(),
KeyCode::F(3) => self.find_again(),
KeyCode::Char(' ') if ctrl => self.ask_completion(true),
KeyCode::Char('/') if alt => self.ask_completion(true),
KeyCode::Char('k') if ctrl || alt => self.toggle_fold(),
KeyCode::Char('a') if alt => self.toggle_all_folds(),
KeyCode::Char('h') if alt => self.ask_lsp(Client::hover),
KeyCode::F(2) => self.ask_lsp(Client::hover),
KeyCode::Char('g') if alt => self.ask_lsp(Client::definition),
KeyCode::F(12) => self.ask_lsp(Client::definition),
// Typing over selected text replaces it.
KeyCode::Char(c) if !ctrl && !alt => {
self.delete_selection();
self.type_char(c);
self.after_typing(c);
}
KeyCode::Tab => {
self.delete_selection();
self.tab();
}
KeyCode::Enter => {
self.delete_selection();
let indent = self.indent_for_new_line();
self.insert_newline();
indent.chars().for_each(|c| self.insert_char(c));
}
KeyCode::Backspace => {
if !self.delete_selection() {
self.backspace();
}
// Deleting the whole word closes the list of suggestions.
if self.completion.as_ref().is_some_and(|completion| self.cursor_x <= completion.start) {
self.completion = None;
}
self.refilter();
}
KeyCode::Delete => {
if !self.delete_selection() {
self.delete();
}
}
KeyCode::Up => {
if let Some(y) = self.folds.prev_visible(self.cursor_y) {
self.cursor_y = y;
}
}
KeyCode::Down => {
if let Some(y) = self.folds.next_visible(self.cursor_y, self.document.len()) {
self.cursor_y = y;
}
}
KeyCode::PageUp => self.wheel(-(self.page_rows.max(1) as isize)),
KeyCode::PageDown => self.wheel(self.page_rows.max(1) as isize),
KeyCode::Left => {
if self.cursor_x > 0 {
self.cursor_x -= 1;
}
}
KeyCode::Right => {
if self.cursor_x < self.document.line_len(self.cursor_y) {
self.cursor_x += 1;
}
}
KeyCode::Home if ctrl => (self.cursor_x, self.cursor_y) = (0, 0),
KeyCode::End if ctrl => {
// The last line may be hidden inside a collapsed block.
self.cursor_y = self.folds.header_of(self.document.len().saturating_sub(1));
self.cursor_x = self.document.line_len(self.cursor_y);
}
KeyCode::Home => self.cursor_x = 0,
KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
_ => {}
}
}
/// Moving to a shorter line: don't leave the cursor past its end.
fn clamp_cursor_x(&mut self) {
let len = self.document.line_len(self.cursor_y);
if self.cursor_x > len {
self.cursor_x = len;
}
}
}
/// A piece of code as a span: plain when it has no colour or decoration.
fn code_span((decoration, text): (Decoration, String)) -> Span {
if decoration == Decoration::default() {
Span::new(Style::Plain, text)
} else {
Span::new(Style::Code(decoration), text)
}
}