Completion while typing, and end-to-end tests with real tools
Adds tests/features.rs: live clangd, a shell, curses and nano, a real git repository, crash recovery, random edits and a 200k-line file. Fixes from those runs: completions appear while typing and use the server's ranking and filter text; a language server that dies is reported and word completion takes over; system fonts draw characters the code font lacks; block comments wrap the line and add spaces. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
1c1dab0a5d
commit
8c5b7ffc78
10 changed files with 837 additions and 23 deletions
93
Cargo.lock
generated
93
Cargo.lock
generated
|
|
@ -901,6 +901,7 @@ dependencies = [
|
|||
"egui-wgpu",
|
||||
"egui-winit",
|
||||
"egui_glow",
|
||||
"egui_system_font_provider",
|
||||
"glow",
|
||||
"glutin",
|
||||
"glutin-winit",
|
||||
|
|
@ -1021,6 +1022,21 @@ dependencies = [
|
|||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f2a2fdfe3c05dd9f691d2b1388b2312d6dce1af502f217c22136d22d9bd76f6"
|
||||
dependencies = [
|
||||
"epaint",
|
||||
"fontique",
|
||||
"log",
|
||||
"poll-promise",
|
||||
"skrifa",
|
||||
"sys-locale",
|
||||
"unicode-script",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
|
|
@ -1258,6 +1274,28 @@ dependencies = [
|
|||
"ttf-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontique"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"objc2-foundation 0.3.2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"roxmltree 0.21.2",
|
||||
"smallvec",
|
||||
"windows",
|
||||
"windows-core",
|
||||
"yeslogic-fontconfig-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.5.0"
|
||||
|
|
@ -1395,6 +1433,7 @@ dependencies = [
|
|||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"png 0.18.1",
|
||||
"skrifa",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
|
|
@ -2147,6 +2186,16 @@ dependencies = [
|
|||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-text"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
|
|
@ -2408,6 +2457,12 @@ dependencies = [
|
|||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parlance"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e"
|
||||
|
||||
[[package]]
|
||||
name = "peniko"
|
||||
version = "0.6.1"
|
||||
|
|
@ -2562,6 +2617,16 @@ dependencies = [
|
|||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poll-promise"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f6a58fecbf9da8965bcdb20ce4fd29788d1acee68ddbb64f0ba1b81bccdb7df"
|
||||
dependencies = [
|
||||
"document-features",
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polling"
|
||||
version = "3.11.0"
|
||||
|
|
@ -3270,6 +3335,15 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-locale"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
|
|
@ -3514,6 +3588,12 @@ version = "0.1.5"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-script"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.3"
|
||||
|
|
@ -3570,6 +3650,7 @@ dependencies = [
|
|||
"guillotiere",
|
||||
"log",
|
||||
"peniko",
|
||||
"png 0.18.1",
|
||||
"smallvec",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
|
@ -3583,6 +3664,7 @@ dependencies = [
|
|||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"png 0.18.1",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
|
|
@ -4388,6 +4470,17 @@ version = "0.1.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "yeslogic-fontconfig-sys"
|
||||
version = "6.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76"
|
||||
dependencies = [
|
||||
"dlib",
|
||||
"once_cell",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus"
|
||||
version = "5.19.0"
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ name = "damson"
|
|||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "clipboard", "default_fonts"] }
|
||||
eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "clipboard", "default_fonts", "system_fonts"] }
|
||||
ropey = "1"
|
||||
fancy-regex = "0.20"
|
||||
regex = "1"
|
||||
|
|
|
|||
|
|
@ -48,6 +48,10 @@ hot exit (unsaved text survives a crash or quit), and language servers for compl
|
|||
definition and diagnostics when they're installed (`clangd`, `rust-analyzer`, `pylsp`, `gopls`,
|
||||
`typescript-language-server`, `bash-language-server`, `lua-language-server`).
|
||||
|
||||
Completions appear as you type and with `Ctrl+Space`. With no working language server they come from
|
||||
words in the file. `~/.cargo/bin/rust-analyzer` is only a rustup placeholder until you run
|
||||
`rustup component add rust-analyzer`.
|
||||
|
||||
Colours follow your desktop (Caelestia's scheme or the KDE accent), or a colour you pick, and change live.
|
||||
|
||||
## Discord
|
||||
|
|
@ -90,10 +94,11 @@ Needs Rust and the `syntax-highlighting` package. No other KDE parts are needed
|
|||
cargo test --lib
|
||||
cargo test --test syntax_all -- --nocapture
|
||||
DAMSON_SHOTS=/tmp/shots cargo test --test shots -- --test-threads=1
|
||||
cargo test --test features -- --test-threads=1 --nocapture
|
||||
```
|
||||
|
||||
The last one drives the real app with no window, using real input events, and saves a screenshot of each
|
||||
screen. `DAMSON_SMOKE=/some/dir damson` runs the real window for 120 frames, saves `window.png` and
|
||||
`shots` drives the real app with no window, using real input events, and saves a screenshot of each
|
||||
screen. `features` runs the features against real tools: `clangd`, a shell, `nano`, a git repository. `DAMSON_SMOKE=/some/dir damson` runs the real window for 120 frames, saves `window.png` and
|
||||
`status.txt`, then quits.
|
||||
|
||||
## Licence
|
||||
|
|
|
|||
BIN
assets/damson.png
Normal file
BIN
assets/damson.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
62
src/app.rs
62
src/app.rs
|
|
@ -136,6 +136,8 @@ pub struct App {
|
|||
lsp_tx: Sender<(String, serde_json::Value)>,
|
||||
lsp_rx: Receiver<(String, serde_json::Value)>,
|
||||
pub lsp: HashMap<String, Client>,
|
||||
lsp_dead: std::collections::HashSet<String>,
|
||||
complete_due: Option<Instant>,
|
||||
lsp_sent: HashMap<u64, u64>,
|
||||
pub complete: Option<Completion>,
|
||||
pub hover: Option<(String, Pos2, u64)>,
|
||||
|
|
@ -176,7 +178,7 @@ impl App {
|
|||
settings_open: false, settings_tab: 0, settings_scroll: [0.0; 6], settings_height: [0.0; 6], shell_open: false, shells: vec![], toolbar_filter: String::new(), logo_spin: 0.0, logo_clock: 0.0, theme_wave: None, git: GitState::default(), diags: HashMap::new(),
|
||||
terms: vec![], term_cur: 0, next_term: 0, term_open: false, term_busy: false, term_want_focus: false, term_target: Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 300.0)), term_height: 300.0, fab_rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(FAB_W, 44.0)),
|
||||
palette: Palette::default(), find: Find::default(), menu: None, menu_seq: 0, dialog: None, toasts: vec![], toast_seq: 0, closed: vec![],
|
||||
zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, side_window: false, startup: vec![], window_title: String::new(), presence: discord::spawn(), presence_sent: None,
|
||||
zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_dead: Default::default(), complete_due: None, lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, side_window: false, startup: vec![], window_title: String::new(), presence: discord::spawn(), presence_sent: None,
|
||||
last_time: None, last_poll: Instant::now(), last_guess: Instant::now(), last_session: Instant::now(), last_git: Instant::now() - Duration::from_secs(60),
|
||||
last_stamp: theme::source_stamp(), saved_settings: s.clone(), s, quit_now: false,
|
||||
};
|
||||
|
|
@ -572,6 +574,9 @@ impl App {
|
|||
let d = self.docs.get(&id)?;
|
||||
d.path.as_ref()?;
|
||||
let (bin, args, lang) = lsp::server_for(&d.language)?;
|
||||
if self.lsp_dead.contains(bin) {
|
||||
return None;
|
||||
}
|
||||
if !self.lsp.contains_key(bin) {
|
||||
let root = self.root.clone().or_else(|| d.path.as_ref()?.parent().map(PathBuf::from))?;
|
||||
let c = Client::start(bin, args, &root, bin.to_string(), self.lsp_tx.clone())?;
|
||||
|
|
@ -624,6 +629,12 @@ impl App {
|
|||
|
||||
fn pump_lsp(&mut self, ctx: &egui::Context) {
|
||||
while let Ok((key, v)) = self.lsp_rx.try_recv() {
|
||||
if v.get(lsp::SERVER_GONE).is_some() {
|
||||
self.lsp.remove(&key);
|
||||
self.lsp_dead.insert(key.clone());
|
||||
self.toast("warning", format!("{key} isn't working, so completion is using words from your files"));
|
||||
continue;
|
||||
}
|
||||
let Some(ev) = self.lsp.get_mut(&key).and_then(|c| c.handle(v)) else { continue };
|
||||
match ev {
|
||||
LspEvent::Diagnostics(p, d) => {
|
||||
|
|
@ -649,13 +660,47 @@ impl App {
|
|||
let Some(d) = self.cur_doc() else { return };
|
||||
let word = d.buf.word_at(d.buf.head());
|
||||
let prefix = d.buf.text(word.start..d.buf.head()).to_lowercase();
|
||||
items.retain(|i| i.label.to_lowercase().starts_with(&prefix));
|
||||
items.retain(|i| i.filter.to_lowercase().starts_with(&prefix));
|
||||
if items.is_empty() {
|
||||
self.complete = None;
|
||||
return;
|
||||
}
|
||||
self.complete_seq += 1;
|
||||
self.complete = Some(Completion { items, sel: 0, start: word.start, seq: self.complete_seq });
|
||||
// an open list keeps its place in the animation as it narrows
|
||||
let seq = match &self.complete {
|
||||
Some(c) => c.seq,
|
||||
None => { self.complete_seq += 1; self.complete_seq }
|
||||
};
|
||||
self.complete = Some(Completion { items, sel: 0, start: word.start, seq });
|
||||
}
|
||||
|
||||
/// Asks for completions a moment after typing, when what was typed calls for them.
|
||||
fn typing_completion(&mut self, ctx: &egui::Context) {
|
||||
let focused = ctx.memory(|m| m.focused()) == Some(self.pane_focus_id(self.focus_pane));
|
||||
let typed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)) || matches!(e, egui::Event::Key { key: Key::Backspace, pressed: true, .. })));
|
||||
if focused && typed {
|
||||
self.complete_due = Some(Instant::now());
|
||||
}
|
||||
if self.complete_due.is_some_and(|t| t.elapsed() > Duration::from_millis(70)) {
|
||||
self.complete_due = None;
|
||||
let wanted = self.cur_doc().is_some_and(|d| {
|
||||
let head = d.buf.head();
|
||||
let word = d.buf.word_at(head);
|
||||
let before = |n: usize| head.checked_sub(n).and_then(|i| d.buf.rope.get_char(i));
|
||||
let member = before(1) == Some('.') || (before(1) == Some(':') && before(2) == Some(':')) || (before(1) == Some('>') && before(2) == Some('-'));
|
||||
head - word.start >= 2 || member
|
||||
});
|
||||
if wanted && (self.s.auto_complete || self.complete.is_some()) {
|
||||
self.run(ctx, Cmd::Complete);
|
||||
} else {
|
||||
self.complete = None;
|
||||
}
|
||||
}
|
||||
// moving out of the word ends the list
|
||||
if let (Some(c), Some(d)) = (&self.complete, self.cur_doc()) {
|
||||
if d.buf.word_at(d.buf.head()).start != c.start {
|
||||
self.complete = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Words already in the file, for when no language server is running.
|
||||
|
|
@ -670,7 +715,7 @@ impl App {
|
|||
for m in re.find_iter(&text).take(200_000) {
|
||||
if m.as_str().starts_with(&prefix) && m.as_str() != prefix { seen.insert(m.as_str().to_string()); }
|
||||
}
|
||||
let items = seen.into_iter().take(40).map(|w| CompletionItem { label: w.clone(), insert: w, detail: String::new(), kind: 1 }).collect();
|
||||
let items = seen.into_iter().take(40).map(|w| CompletionItem { label: w.clone(), filter: w.clone(), insert: w, detail: String::new(), kind: 1 }).collect();
|
||||
self.show_completion(items);
|
||||
}
|
||||
|
||||
|
|
@ -1138,7 +1183,7 @@ impl App {
|
|||
let ids: Vec<u64> = self.docs.keys().copied().collect();
|
||||
for id in ids {
|
||||
let d = self.docs.get_mut(&id).unwrap();
|
||||
while d.highlight_pending() && start.elapsed() < Duration::from_millis(5) {
|
||||
while d.highlight_pending() && start.elapsed() < Duration::from_millis(8) {
|
||||
d.highlight(&self.reg, 0, 96);
|
||||
}
|
||||
if d.highlight_pending() { motion::keep_alive() }
|
||||
|
|
@ -1309,11 +1354,8 @@ impl App {
|
|||
self.dialog = Some(Dialog::ConfirmQuit);
|
||||
}
|
||||
}
|
||||
// typing refreshes an open completion list
|
||||
if self.complete.is_some() && ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)) || matches!(e, egui::Event::Key { key: Key::Backspace, pressed: true, .. }))) {
|
||||
self.run(&ctx, Cmd::Complete);
|
||||
}
|
||||
self.layout(ui);
|
||||
self.typing_completion(&ctx);
|
||||
self.palette_ui(&ctx);
|
||||
self.menu_ui(&ctx);
|
||||
self.dialog_ui(&ctx);
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ pub struct Settings {
|
|||
pub shell: String,
|
||||
pub terminal_font: f32,
|
||||
pub lsp: bool,
|
||||
pub auto_complete: bool,
|
||||
pub toolbar: Vec<String>,
|
||||
pub discord: bool,
|
||||
pub discord_id: String,
|
||||
|
|
@ -47,7 +48,7 @@ impl Default for Settings {
|
|||
motion: 2, font_size: 14.0, mono_font: String::new(), tab_width: 4, spaces: true, auto_close: true,
|
||||
word_wrap: false, line_numbers: true, show_whitespace: false, indent_guides: true, preview: true,
|
||||
lens: true, trim_on_save: false, restore_session: true, shell: String::new(), terminal_font: 13.0,
|
||||
lsp: true, toolbar: vec!["Save".into(), "Find".into(), "Command palette".into()],
|
||||
lsp: true, auto_complete: true, toolbar: vec!["Save".into(), "Find".into(), "Command palette".into()],
|
||||
discord: true, discord_id: String::new(), discord_file: true, discord_project: true, recent: vec![], win: [1400.0, 900.0],
|
||||
}
|
||||
}
|
||||
|
|
|
|||
22
src/lsp.rs
22
src/lsp.rs
|
|
@ -22,6 +22,8 @@ pub struct CompletionItem {
|
|||
pub label: String,
|
||||
pub insert: String,
|
||||
pub detail: String,
|
||||
/// What typed text is matched against.
|
||||
pub filter: String,
|
||||
pub kind: u8,
|
||||
}
|
||||
|
||||
|
|
@ -78,6 +80,9 @@ pub fn path_of(uri: &str) -> Option<PathBuf> {
|
|||
Some(PathBuf::from(String::from_utf8_lossy(&out).into_owned()))
|
||||
}
|
||||
|
||||
/// Marks the message sent when a server's output ends, meaning it has stopped.
|
||||
pub const SERVER_GONE: &str = "damson-server-gone";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Pending { Init, Completion, Hover, Definition }
|
||||
|
||||
|
|
@ -102,21 +107,22 @@ impl Client {
|
|||
let stdout = child.stdout.take()?;
|
||||
std::thread::spawn(move || {
|
||||
let mut r = BufReader::new(stdout);
|
||||
loop {
|
||||
'read: loop {
|
||||
let mut len = 0usize;
|
||||
loop {
|
||||
let mut l = String::new();
|
||||
if r.read_line(&mut l).ok().filter(|n| *n > 0).is_none() { return }
|
||||
if r.read_line(&mut l).ok().filter(|n| *n > 0).is_none() { break 'read }
|
||||
let l = l.trim();
|
||||
if l.is_empty() { break }
|
||||
if let Some(v) = l.strip_prefix("Content-Length:") { len = v.trim().parse().unwrap_or(0) }
|
||||
}
|
||||
let mut buf = vec![0; len];
|
||||
if r.read_exact(&mut buf).is_err() { return }
|
||||
if r.read_exact(&mut buf).is_err() { break }
|
||||
if let Ok(v) = serde_json::from_slice::<Value>(&buf) {
|
||||
if tx.send((key.clone(), v)).is_err() { return }
|
||||
}
|
||||
}
|
||||
let _ = tx.send((key, json!({ SERVER_GONE: true })));
|
||||
});
|
||||
let mut c = Client { bin: bin.to_string(), stdin, child, next: 1, pending: HashMap::new(), ready: false, queue: vec![] };
|
||||
c.pending.insert(0, Pending::Init);
|
||||
|
|
@ -238,12 +244,16 @@ pub fn parse_diags(p: &Value) -> Vec<Diag> {
|
|||
|
||||
pub fn parse_completion(res: &Value) -> Vec<CompletionItem> {
|
||||
let items = res.get("items").or(Some(res)).and_then(Value::as_array);
|
||||
items.map(|v| v.iter().take(200).filter_map(|i| {
|
||||
let label = i.get("label")?.as_str()?.trim().to_string();
|
||||
let mut ranked: Vec<&Value> = items.map(|v| v.iter().collect()).unwrap_or_default();
|
||||
ranked.sort_by_key(|i| i.get("sortText").or(i.get("label")).and_then(Value::as_str).unwrap_or(""));
|
||||
Some(ranked).map(|v| v.into_iter().take(200).filter_map(|i| {
|
||||
// clangd marks entries that would add an #include with a bullet
|
||||
let label = i.get("label")?.as_str()?.trim_start_matches(['•', ' ']).trim().to_string();
|
||||
let edit = i.get("textEdit").and_then(|t| t.get("newText")).and_then(Value::as_str);
|
||||
let insert = edit.or(i.get("insertText").and_then(Value::as_str)).unwrap_or(&label).to_string();
|
||||
let detail = i.get("detail").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
Some(CompletionItem { label, insert, detail, kind: i.get("kind").and_then(Value::as_u64).unwrap_or(1) as u8 })
|
||||
let filter = i.get("filterText").and_then(Value::as_str).unwrap_or(&label).trim().to_string();
|
||||
Some(CompletionItem { label, insert, detail, filter, kind: i.get("kind").and_then(Value::as_u64).unwrap_or(1) as u8 })
|
||||
}).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -277,10 +277,17 @@ impl Buffer {
|
|||
pub fn toggle_comment(&mut self, line: Option<&str>, block: Option<(&str, &str)>) {
|
||||
let Some(tok) = line else {
|
||||
let Some((a, b)) = block else { return };
|
||||
// with nothing selected, the line's text is what gets wrapped
|
||||
let changes = self.sels.iter().map(|s| {
|
||||
let t = self.text(s.range());
|
||||
let inner = t.strip_prefix(a).and_then(|x| x.strip_suffix(b));
|
||||
(s.range(), inner.map(str::to_string).unwrap_or_else(|| format!("{a}{t}{b}")))
|
||||
let r = if s.is_empty() {
|
||||
let l = self.pos(s.head).0;
|
||||
let t = self.line_text(l);
|
||||
let start = self.line_start(l) + self.first_text_col(l);
|
||||
start..start + t.trim().chars().count()
|
||||
} else { s.range() };
|
||||
let t = self.text(r.clone());
|
||||
let inner = t.strip_prefix(a).and_then(|x| x.strip_suffix(b)).map(|x| x.strip_prefix(' ').unwrap_or(x)).map(|x| x.strip_suffix(' ').unwrap_or(x));
|
||||
(r, inner.map(str::to_string).unwrap_or_else(|| format!("{a} {t} {b}")))
|
||||
}).collect();
|
||||
return self.apply(changes, EditKind::Other, |_, st, n| Sel { anchor: st, head: st + n, want_col: None });
|
||||
};
|
||||
|
|
@ -567,6 +574,16 @@ mod tests {
|
|||
assert_eq!(text(&x), " a\n b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_comment_wraps_a_line_and_undoes_itself() {
|
||||
let mut x = b(" <p>hi</p>\nnext");
|
||||
x.set_cursor(4);
|
||||
x.toggle_comment(None, Some(("<!--", "-->")));
|
||||
assert_eq!(text(&x), " <!-- <p>hi</p> -->\nnext");
|
||||
x.toggle_comment(None, Some(("<!--", "-->")));
|
||||
assert_eq!(text(&x), " <p>hi</p>\nnext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_duplicate_lines() {
|
||||
let mut x = b("one\ntwo\nthree");
|
||||
|
|
|
|||
|
|
@ -175,6 +175,7 @@ impl App {
|
|||
self.toggle(ui, list, y, "set/nums", "Line numbers", "", |s| &mut s.line_numbers);
|
||||
self.toggle(ui, list, y, "set/guides", "Indent guides", "", |s| &mut s.indent_guides);
|
||||
self.toggle(ui, list, y, "set/trim", "Trim trailing spaces on save", "", |s| &mut s.trim_on_save);
|
||||
self.toggle(ui, list, y, "set/auto", "Show completions while typing", "Ctrl+Space always shows them", |s| &mut s.auto_complete);
|
||||
self.toggle(ui, list, y, "set/lsp", "Language servers", "clangd, rust-analyzer and others, when installed", |s| &mut s.lsp);
|
||||
}
|
||||
|
||||
|
|
|
|||
645
tests/features.rs
Normal file
645
tests/features.rs
Normal file
|
|
@ -0,0 +1,645 @@
|
|||
//! End-to-end checks of the features, using the real tools where they matter: live language
|
||||
//! servers, a real shell, a real git repository.
|
||||
//! `cargo test --test features -- --test-threads=1 --nocapture`
|
||||
|
||||
use damson::app::App;
|
||||
use damson::ui::commands::Cmd;
|
||||
use eframe::egui::{self, vec2, Event, Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type H<'a> = Harness<'a, App>;
|
||||
|
||||
const CTRL: Modifiers = Modifiers::COMMAND;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("damson-f-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::env::set_var("XDG_CONFIG_HOME", d.join(".config"));
|
||||
d
|
||||
}
|
||||
|
||||
fn app<'a>(files: Vec<String>) -> H<'a> {
|
||||
// the real app gets system fonts and draws a box for the rest; by default the harness panics
|
||||
let mut h: H = Harness::builder().with_size(vec2(1300.0, 850.0)).allow_missing_glyphs().wgpu().build_eframe(move |cc| App::new(cc, files.clone()));
|
||||
settle(&mut h, 6);
|
||||
h
|
||||
}
|
||||
|
||||
fn settle(h: &mut H, n: usize) {
|
||||
for _ in 0..n {
|
||||
h.step();
|
||||
std::thread::sleep(Duration::from_millis(16));
|
||||
}
|
||||
}
|
||||
|
||||
fn wait(h: &mut H, secs: u64, what: &str, mut ok: impl FnMut(&mut H) -> bool) {
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < Duration::from_secs(secs) {
|
||||
if ok(h) {
|
||||
println!(" {what}: {:.1}s", t.elapsed().as_secs_f32());
|
||||
return;
|
||||
}
|
||||
settle(h, 3);
|
||||
}
|
||||
panic!("timed out waiting for: {what}");
|
||||
}
|
||||
|
||||
fn key(h: &mut H, k: Key, m: Modifiers) {
|
||||
h.input_mut().events.push(Event::Key { key: k, physical_key: Some(k), pressed: true, repeat: false, modifiers: m });
|
||||
h.step();
|
||||
h.input_mut().events.push(Event::Key { key: k, physical_key: Some(k), pressed: false, repeat: false, modifiers: m });
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// Types like a person, one character per frame.
|
||||
fn typed(h: &mut H, s: &str) {
|
||||
for c in s.chars() {
|
||||
if c == '\n' {
|
||||
key(h, Key::Enter, Modifiers::NONE);
|
||||
} else {
|
||||
h.input_mut().events.push(Event::Text(c.to_string()));
|
||||
settle(h, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd(h: &mut H, c: Cmd) {
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().run(&ctx, c);
|
||||
settle(h, 3);
|
||||
}
|
||||
|
||||
fn text(h: &H) -> String {
|
||||
h.state().cur_doc().unwrap().buf.rope.to_string()
|
||||
}
|
||||
|
||||
fn caret(h: &mut H, line: usize, col: usize) {
|
||||
let d = h.state_mut().cur_doc_mut().unwrap();
|
||||
let at = d.buf.at(line, col);
|
||||
d.buf.set_cursor(at);
|
||||
settle(h, 2);
|
||||
}
|
||||
|
||||
fn pos(h: &H) -> (usize, usize) {
|
||||
let b = &h.state().cur_doc().unwrap().buf;
|
||||
b.pos(b.head())
|
||||
}
|
||||
|
||||
fn labels(h: &H) -> Vec<String> {
|
||||
h.state().complete.as_ref().map_or(vec![], |c| c.items.iter().map(|i| i.label.clone()).collect())
|
||||
}
|
||||
|
||||
fn write(p: &Path, s: &str) -> String {
|
||||
if let Some(d) = p.parent() { std::fs::create_dir_all(d).unwrap() }
|
||||
std::fs::write(p, s).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clangd_live() {
|
||||
let dir = tmp("clangd");
|
||||
let f = write(&dir.join("main.c"), "#include <stdio.h>\nstruct point { int x; int y; };\nint add(int a, int b) { return a + b; }\nint main(void) {\n struct point p;\n p.\n return add(1, 2) + missing;\n}\n");
|
||||
let mut h = app(vec![f]);
|
||||
h.state_mut().set_root(dir.clone());
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(h.state().cur_doc().unwrap().language, "C");
|
||||
wait(&mut h, 30, "diagnostics arrive", |h| h.state().problem_count() > 0);
|
||||
let (e, _) = h.state().problem_totals();
|
||||
assert!(e >= 1, "undeclared name is an error");
|
||||
|
||||
caret(&mut h, 5, 6);
|
||||
wait(&mut h, 20, "member completion", |h| { if h.state().complete.is_none() { key(h, Key::Space, CTRL); settle(h, 6) } !labels(h).is_empty() });
|
||||
println!(" got: {:?}", labels(&h));
|
||||
assert!(labels(&h).iter().any(|l| l == "x"), "{:?}", labels(&h));
|
||||
assert!(labels(&h).iter().any(|l| l == "y"));
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
assert!(text(&h).contains(" p.y\n"), "accepting inserts it: {}", text(&h));
|
||||
|
||||
caret(&mut h, 6, 13);
|
||||
key(&mut h, Key::F12, Modifiers::NONE);
|
||||
wait(&mut h, 15, "go to definition", |h| pos(h).0 == 2);
|
||||
|
||||
caret(&mut h, 6, 13);
|
||||
key(&mut h, Key::I, CTRL);
|
||||
wait(&mut h, 15, "hover", |h| h.state().hover.is_some());
|
||||
let t = h.state().hover.as_ref().unwrap().0.clone();
|
||||
println!(" hover: {:?}", t.lines().next());
|
||||
assert!(t.contains("add"), "{t}");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
|
||||
// diagnostics follow edits without saving: fix both problems on those two lines
|
||||
caret(&mut h, 5, 7);
|
||||
typed(&mut h, ";");
|
||||
caret(&mut h, 6, 0);
|
||||
key(&mut h, Key::K, CTRL);
|
||||
wait(&mut h, 20, "problem clears after the edit", |h| h.state().problem_totals().0 == 0);
|
||||
|
||||
// typing a name brings completion up by itself
|
||||
caret(&mut h, 4, 0);
|
||||
key(&mut h, Key::End, Modifiers::NONE);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
typed(&mut h, "ad");
|
||||
wait(&mut h, 10, "completion while typing", |h| !labels(h).is_empty());
|
||||
assert!(labels(&h).iter().any(|l| l.starts_with("add")), "{:?}", labels(&h));
|
||||
// and it narrows, then goes away on a non-word key
|
||||
typed(&mut h, "d");
|
||||
wait(&mut h, 5, "narrowed", |h| labels(h).iter().all(|l| l.to_lowercase().starts_with("add")));
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
settle(&mut h, 2);
|
||||
assert!(h.state().complete.is_none());
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_analyzer_live() {
|
||||
let dir = tmp("ra");
|
||||
write(&dir.join("Cargo.toml"), "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
|
||||
let f = write(&dir.join("src/main.rs"), "fn helper(n: u32) -> u32 {\n n + 1\n}\n\nfn main() {\n let v: Vec<u32> = Vec::new();\n v.\n let s = helper(1);\n let bad: u32 = \"text\";\n}\n");
|
||||
let mut h = app(vec![]);
|
||||
h.state_mut().set_root(dir.clone());
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().open_path(&ctx, f.into(), None);
|
||||
settle(&mut h, 5);
|
||||
assert_eq!(h.state().cur_doc().unwrap().language, "Rust");
|
||||
let works = std::process::Command::new("rust-analyzer").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !works {
|
||||
// a rustup placeholder starts and dies at once: say so and carry on with word completion
|
||||
println!(" rust-analyzer not really installed: checking the fallback");
|
||||
wait(&mut h, 10, "the failure is reported", |h| h.state().toasts.iter().any(|t| t.text.contains("isn't working")));
|
||||
caret(&mut h, 6, 4);
|
||||
typed(&mut h, "hel");
|
||||
wait(&mut h, 5, "word completion takes over", |h| labels(h).iter().any(|l| l == "helper"));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
return;
|
||||
}
|
||||
caret(&mut h, 6, 6);
|
||||
wait(&mut h, 90, "rust-analyzer completion", |h| {
|
||||
if h.state().complete.is_none() { key(h, Key::Space, CTRL); settle(h, 20) }
|
||||
!labels(h).is_empty()
|
||||
});
|
||||
assert!(labels(&h).iter().any(|l| l.starts_with("push")), "{:?}", labels(&h));
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
caret(&mut h, 7, 13);
|
||||
key(&mut h, Key::F12, Modifiers::NONE);
|
||||
wait(&mut h, 30, "go to definition", |h| pos(h).0 == 0);
|
||||
wait(&mut h, 60, "type error shows", |h| h.state().problem_totals().0 > 0);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_completion_without_a_server() {
|
||||
let dir = tmp("words");
|
||||
let f = write(&dir.join("notes.txt"), "alphabet alpine alpha beta\n");
|
||||
let mut h = app(vec![f]);
|
||||
caret(&mut h, 1, 0);
|
||||
typed(&mut h, "alp");
|
||||
key(&mut h, Key::Space, CTRL);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(labels(&h), ["alpha", "alphabet", "alpine"]);
|
||||
key(&mut h, Key::Tab, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
assert!(text(&h).ends_with("alpha"), "{}", text(&h));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_shortcuts() {
|
||||
let dir = tmp("edit");
|
||||
let f = write(&dir.join("a.rs"), "one\ntwo\nthree\nfour\n");
|
||||
let mut h = app(vec![f]);
|
||||
// Ctrl+K deletes the line
|
||||
caret(&mut h, 1, 0);
|
||||
key(&mut h, Key::K, CTRL);
|
||||
settle(&mut h, 2);
|
||||
assert_eq!(text(&h), "one\nthree\nfour\n");
|
||||
key(&mut h, Key::Z, CTRL);
|
||||
settle(&mut h, 2);
|
||||
// move and duplicate
|
||||
caret(&mut h, 1, 1);
|
||||
key(&mut h, Key::ArrowDown, Modifiers { shift: true, ..CTRL });
|
||||
settle(&mut h, 2);
|
||||
assert_eq!(text(&h), "one\nthree\ntwo\nfour\n");
|
||||
key(&mut h, Key::ArrowDown, Modifiers { alt: true, shift: true, ..CTRL });
|
||||
settle(&mut h, 2);
|
||||
assert_eq!(text(&h), "one\nthree\ntwo\ntwo\nfour\n");
|
||||
// Alt+J: select word, then next match
|
||||
caret(&mut h, 2, 1);
|
||||
key(&mut h, Key::J, Modifiers::ALT);
|
||||
key(&mut h, Key::J, Modifiers::ALT);
|
||||
settle(&mut h, 2);
|
||||
assert_eq!(h.state().cur_doc().unwrap().buf.sels.len(), 2);
|
||||
typed(&mut h, "2");
|
||||
assert_eq!(text(&h), "one\nthree\n2\n2\nfour\n", "typing replaces every selection");
|
||||
// upper case, join
|
||||
caret(&mut h, 0, 0);
|
||||
key(&mut h, Key::U, CTRL);
|
||||
settle(&mut h, 2);
|
||||
assert!(text(&h).starts_with("ONE\n"));
|
||||
caret(&mut h, 0, 0);
|
||||
key(&mut h, Key::J, CTRL);
|
||||
settle(&mut h, 2);
|
||||
assert!(text(&h).starts_with("ONE three\n"), "{}", text(&h));
|
||||
// clipboard path through events
|
||||
caret(&mut h, 0, 0);
|
||||
h.input_mut().events.push(Event::Paste("a\nb\n".into()));
|
||||
settle(&mut h, 2);
|
||||
assert!(text(&h).starts_with("a\nb\nONE"), "{}", text(&h));
|
||||
// selection by keyboard, then cut
|
||||
caret(&mut h, 0, 0);
|
||||
key(&mut h, Key::ArrowRight, Modifiers::SHIFT);
|
||||
h.input_mut().events.push(Event::Cut);
|
||||
settle(&mut h, 2);
|
||||
assert!(text(&h).starts_with("\nb\nONE"), "{}", text(&h));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folds_bookmarks_find_replace() {
|
||||
let dir = tmp("fold");
|
||||
let f = write(&dir.join("a.rs"), "fn a() {\n one();\n two();\n}\nfn b() {\n one();\n}\n");
|
||||
let mut h = app(vec![f]);
|
||||
settle(&mut h, 6);
|
||||
caret(&mut h, 1, 0);
|
||||
cmd(&mut h, Cmd::FoldHere);
|
||||
settle(&mut h, 3);
|
||||
{
|
||||
let tb = &h.state().panes[0].tabs[0];
|
||||
let d = h.state().cur_doc().unwrap();
|
||||
assert_eq!(tb.rows.count(d), 5, "lines 2-4 hidden");
|
||||
}
|
||||
cmd(&mut h, Cmd::UnfoldAll);
|
||||
settle(&mut h, 3);
|
||||
cmd(&mut h, Cmd::FoldAll);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(h.state().cur_doc().unwrap().folded.len(), 2);
|
||||
cmd(&mut h, Cmd::UnfoldAll);
|
||||
settle(&mut h, 3);
|
||||
|
||||
// bookmarks survive lines being added above them
|
||||
caret(&mut h, 5, 0);
|
||||
key(&mut h, Key::B, Modifiers { shift: true, ..CTRL });
|
||||
settle(&mut h, 2);
|
||||
caret(&mut h, 0, 0);
|
||||
h.input_mut().events.push(Event::Paste("// top\n".into()));
|
||||
settle(&mut h, 3);
|
||||
assert!(h.state().cur_doc().unwrap().bookmarks.contains(&6));
|
||||
key(&mut h, Key::PageDown, Modifiers::ALT);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(pos(&h).0, 6, "next bookmark");
|
||||
|
||||
cmd(&mut h, Cmd::Find);
|
||||
h.state_mut().find.query = "one".into();
|
||||
settle(&mut h, 6);
|
||||
assert_eq!(h.state().find.hits.len(), 2);
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().find_step(&ctx, false);
|
||||
settle(&mut h, 3);
|
||||
h.state_mut().find.regex = true;
|
||||
h.state_mut().find.query = r"\b(one|two)\(\)".into();
|
||||
settle(&mut h, 6);
|
||||
assert_eq!(h.state().find.hits.len(), 3, "regex");
|
||||
h.state_mut().find.query = "(".into();
|
||||
settle(&mut h, 4);
|
||||
assert!(h.state().find.error, "a broken regex shows as an error, not a crash");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_uses_each_languages_syntax() {
|
||||
let dir = tmp("comment");
|
||||
for (name, want) in [("a.rs", "// x"), ("a.py", "# x"), ("a.lua", "-- x"), ("a.sh", "# x"), ("a.sql", "-- x"), ("a.c", "// x"), ("a.html", "<!-- x -->")] {
|
||||
let f = write(&dir.join(name), "x");
|
||||
let mut h = app(vec![f]);
|
||||
key(&mut h, Key::Slash, CTRL);
|
||||
settle(&mut h, 2);
|
||||
assert_eq!(text(&h), want, "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
/// Odd text, including zero-width joiners and combining marks, gets through every surface.
|
||||
#[test]
|
||||
fn any_characters_can_be_shown() {
|
||||
let dir = tmp("glyphs");
|
||||
let f = write(&dir.join("a.txt"), "日本語のテキスト 한국어 العربية 🦀🚀 \u{1F9D1}\u{200D}\u{1F4BB} e\u{301} \u{FFFF}\n");
|
||||
let mut h = app(vec![f]);
|
||||
settle(&mut h, 20);
|
||||
typed(&mut h, "漢字");
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().run(&ctx, Cmd::ToggleTerminal);
|
||||
settle(&mut h, 30);
|
||||
h.state().terms[0].write("printf '日本語 🦀\\n'\r");
|
||||
settle(&mut h, 30);
|
||||
cmd(&mut h, Cmd::Palette);
|
||||
h.state_mut().palette.query = "日本".into();
|
||||
settle(&mut h, 10);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_views_share_a_document() {
|
||||
let dir = tmp("split");
|
||||
let f = write(&dir.join("a.txt"), "hello\n");
|
||||
let mut h = app(vec![f]);
|
||||
cmd(&mut h, Cmd::SplitRight);
|
||||
settle(&mut h, 8);
|
||||
assert_eq!(h.state().panes.len(), 2);
|
||||
assert_eq!(h.state().docs.len(), 1);
|
||||
typed(&mut h, "x");
|
||||
assert!(text(&h).contains('x'));
|
||||
cmd(&mut h, Cmd::New);
|
||||
assert_eq!(h.state().panes[1].tabs.len(), 2);
|
||||
cmd(&mut h, Cmd::CloseSplit);
|
||||
settle(&mut h, 6);
|
||||
assert_eq!(h.state().panes.len(), 1);
|
||||
assert_eq!(h.state().docs.len(), 1, "the shared file lives on in the other split");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_runs_real_programs() {
|
||||
let dir = tmp("term");
|
||||
let script = write(&dir.join("hi.py"), "print('from python', 6*7)\n");
|
||||
let mut h = app(vec![script]);
|
||||
let screen = |h: &H| h.state().terms[h.state().term_cur].screen_text().join("\n");
|
||||
|
||||
// the Run button, on a saved file
|
||||
cmd(&mut h, Cmd::RunFile);
|
||||
wait(&mut h, 15, "script output", |h| screen(h).contains("from python 42"));
|
||||
wait(&mut h, 5, "run finishes", |h| !h.state().terms[0].running);
|
||||
|
||||
// Ctrl+C reaches the program and gives the shell back
|
||||
h.state().terms[0].write("sleep 60\r");
|
||||
settle(&mut h, 30);
|
||||
h.input_mut().events.push(Event::Copy);
|
||||
settle(&mut h, 30);
|
||||
h.state().terms[0].write("echo back-at-prompt\r");
|
||||
wait(&mut h, 5, "Ctrl+C stopped it", |h| screen(h).lines().any(|l| l.trim() == "back-at-prompt"));
|
||||
|
||||
// a full-screen program: arrows, colours, and leaving the screen as it was
|
||||
let app = write(&dir.join("keys.py"), "import curses\ndef main(s):\n curses.start_color()\n s.addstr(0, 0, 'curses ready')\n s.refresh()\n s.keypad(True)\n got = []\n for _ in range(3):\n got.append(s.getch())\n open('KEYS', 'w').write(' '.join(map(str, got)))\ncurses.wrapper(main)\n");
|
||||
h.state().terms[0].write(format!("cd '{}'; python3 '{app}'\r", dir.display()));
|
||||
wait(&mut h, 8, "curses starts", |h| screen(h).contains("curses ready"));
|
||||
key(&mut h, Key::ArrowUp, Modifiers::NONE);
|
||||
key(&mut h, Key::PageDown, Modifiers::NONE);
|
||||
key(&mut h, Key::F2, Modifiers::NONE);
|
||||
wait(&mut h, 5, "keys arrive", |_| dir.join("KEYS").exists());
|
||||
settle(&mut h, 20);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("KEYS")).unwrap(), "259 338 266", "up, page down, F2");
|
||||
assert!(!screen(&h).contains("curses ready"), "left the alternate screen");
|
||||
|
||||
// nano: a real editor, saved with its own keys
|
||||
if which("nano") {
|
||||
let out = dir.join("from-nano.txt");
|
||||
h.state().terms[0].write(format!("nano '{}'\r", out.display()));
|
||||
wait(&mut h, 8, "nano opens", |h| screen(h).contains("GNU nano") || screen(h).contains("from-nano"));
|
||||
h.input_mut().events.push(Event::Text("hello from nano".into()));
|
||||
settle(&mut h, 8);
|
||||
key(&mut h, Key::O, Modifiers::CTRL);
|
||||
settle(&mut h, 8);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
wait(&mut h, 6, "nano saved", |_| out.exists());
|
||||
h.input_mut().events.push(Event::Cut);
|
||||
settle(&mut h, 20);
|
||||
assert_eq!(std::fs::read_to_string(&out).unwrap().trim(), "hello from nano");
|
||||
}
|
||||
|
||||
// colours and unicode survive
|
||||
h.state().terms[0].write("clear; printf '\\033[31mred\\033[0m café 日本\\n'\r");
|
||||
wait(&mut h, 5, "unicode text", |h| screen(h).contains("café"));
|
||||
settle(&mut h, 10);
|
||||
|
||||
// the run button turns into stop, and stop works
|
||||
let slow = write(&dir.join("slow.py"), "import time\ntime.sleep(60)\n");
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().open_path(&ctx, slow.into(), None);
|
||||
cmd(&mut h, Cmd::RunFile);
|
||||
settle(&mut h, 20);
|
||||
assert!(h.state().terms[0].running, "shows as running");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
fn which(bin: &str) -> bool {
|
||||
std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_panel_on_a_real_repository() {
|
||||
let dir = tmp("git");
|
||||
let run = |args: &[&str]| assert!(std::process::Command::new("git").arg("-C").arg(&dir).args(args).output().unwrap().status.success(), "{args:?}");
|
||||
run(&["init", "-q", "-b", "main"]);
|
||||
run(&["config", "user.name", "t"]);
|
||||
run(&["config", "user.email", "[email protected]"]);
|
||||
let f = write(&dir.join("a.txt"), "one\ntwo\nthree\n");
|
||||
write(&dir.join("new.txt"), "x\n");
|
||||
run(&["add", "a.txt"]);
|
||||
run(&["commit", "-qm", "first"]);
|
||||
write(&dir.join("a.txt"), "one\nTWO\nthree\nfour\n");
|
||||
let mut h = app(vec![f.clone()]);
|
||||
h.state_mut().set_root(dir.clone());
|
||||
wait(&mut h, 10, "status reads", |h| h.state().git.files.len() == 2);
|
||||
assert_eq!(h.state().git.branch, "main");
|
||||
let marks = h.state().git.marks.get(&std::fs::canonicalize(&f).unwrap()).cloned().unwrap_or_default();
|
||||
assert_eq!(marks, vec![(1, 1, 1), (3, 1, 0)], "changed line 2, added line 4");
|
||||
h.state_mut().git_stage("new.txt", false);
|
||||
wait(&mut h, 10, "staged", |h| h.state().git.files.iter().any(|x| x.0 == 'A'));
|
||||
h.state_mut().git_stage("new.txt", true);
|
||||
wait(&mut h, 10, "unstaged", |h| h.state().git.files.iter().all(|x| x.0 != 'A'));
|
||||
h.state_mut().git_stage("a.txt", false);
|
||||
settle(&mut h, 20);
|
||||
h.state_mut().side_state.commit = "second".into();
|
||||
h.state_mut().git_commit();
|
||||
wait(&mut h, 10, "committed", |h| h.state().git.files.len() == 1);
|
||||
let log = String::from_utf8(std::process::Command::new("git").arg("-C").arg(&dir).args(["log", "--oneline"]).output().unwrap().stdout).unwrap();
|
||||
assert_eq!(log.lines().count(), 2);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_outline_and_palette() {
|
||||
let dir = tmp("search");
|
||||
let f = write(&dir.join("src/a.rs"), "struct Thing;\nfn alpha() {}\nfn needle_here() {}\n");
|
||||
write(&dir.join("src/b.py"), "def needle_too():\n pass\n");
|
||||
write(&dir.join("target/skip.rs"), "needle in build output\n");
|
||||
let mut h = app(vec![f]);
|
||||
h.state_mut().set_root(dir.clone());
|
||||
h.state_mut().side_state.search = "needle".into();
|
||||
h.state_mut().start_search();
|
||||
wait(&mut h, 10, "search results", |h| !h.state().side_state.searching);
|
||||
assert_eq!(h.state().side_state.results.len(), 2, "build output skipped");
|
||||
|
||||
let names: Vec<String> = h.state_mut().outline().into_iter().map(|o| o.1).collect();
|
||||
assert_eq!(names, ["struct Thing", "alpha", "needle_here"]);
|
||||
settle(&mut h, 2);
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().open_palette(&ctx, ":3", false);
|
||||
settle(&mut h, 3);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(pos(&h).0, 2, ":3 goes to line 3");
|
||||
|
||||
h.state_mut().open_palette(&ctx, "@alph", false);
|
||||
settle(&mut h, 3);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(pos(&h).0, 1, "@ finds the symbol");
|
||||
|
||||
h.state_mut().open_palette(&ctx, ">zen", false);
|
||||
settle(&mut h, 3);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
|
||||
h.state_mut().open_palette(&ctx, "bpy", false);
|
||||
settle(&mut h, 3);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
settle(&mut h, 3);
|
||||
assert_eq!(h.state().cur_doc().unwrap().title(), "b.py", "fuzzy file open");
|
||||
assert_eq!(h.state().cur_doc().unwrap().language, "Python");
|
||||
|
||||
cmd(&mut h, Cmd::ReopenClosed);
|
||||
let tabs = h.state().panes[0].tabs.len();
|
||||
cmd(&mut h, Cmd::CloseTab);
|
||||
assert_eq!(h.state().panes[0].tabs.len(), tabs - 1);
|
||||
cmd(&mut h, Cmd::ReopenClosed);
|
||||
assert_eq!(h.state().panes[0].tabs.len(), tabs, "reopen closed tab");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crash_recovery_brings_unsaved_work_back() {
|
||||
let dir = tmp("recover");
|
||||
let f = write(&dir.join("a.txt"), "saved\n");
|
||||
{
|
||||
let mut h = app(vec![f.clone()]);
|
||||
caret(&mut h, 0, 0);
|
||||
typed(&mut h, "unsaved ");
|
||||
cmd(&mut h, Cmd::New);
|
||||
h.input_mut().events.push(Event::Paste("def scratch():\n pass\n".into()));
|
||||
settle(&mut h, 25);
|
||||
h.state().save_session();
|
||||
// dropped with no save or quit, as a crash would leave it
|
||||
}
|
||||
let mut h = app(vec![]);
|
||||
settle(&mut h, 20);
|
||||
assert_eq!(h.state().docs.len(), 2);
|
||||
let texts: Vec<String> = h.state().docs.values().map(|d| d.buf.rope.to_string()).collect();
|
||||
assert!(texts.iter().any(|t| t.starts_with("unsaved saved")), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t.starts_with("def scratch")), "{texts:?}");
|
||||
assert!(h.state().docs.values().all(|d| d.buf.is_modified()), "recovered text still counts as unsaved");
|
||||
assert_eq!(std::fs::read_to_string(&f).unwrap(), "saved\n", "the file itself is untouched");
|
||||
let py = h.state().docs.values().find(|d| d.path.is_none()).unwrap();
|
||||
assert_eq!(py.language, "Python", "recovered untitled file colours itself");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_changes_to_a_file() {
|
||||
let dir = tmp("outside");
|
||||
let f = write(&dir.join("a.txt"), "first\n");
|
||||
let mut h = app(vec![f.clone()]);
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
write(Path::new(&f), "changed outside\n");
|
||||
wait(&mut h, 6, "clean file follows the disk", |h| text(h) == "changed outside\n");
|
||||
assert!(!h.state().cur_doc().unwrap().buf.is_modified());
|
||||
typed(&mut h, "mine ");
|
||||
write(Path::new(&f), "changed again\n");
|
||||
settle(&mut h, 130);
|
||||
assert!(text(&h).contains("mine"), "unsaved work is not overwritten");
|
||||
assert!(h.state().toasts.iter().any(|t| t.text.contains("changed on disk")) || text(&h).contains("mine"));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
/// A little xorshift, so a failure can be replayed from its seed.
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self, n: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % n.max(1) as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// Random edits on real highlighted code. Nothing may panic, and undo must restore the text exactly.
|
||||
#[test]
|
||||
fn random_edits_hold_together() {
|
||||
use damson::syntax::Registry;
|
||||
use damson::text::commands::{Move, Prefs};
|
||||
use damson::text::{Doc, EditKind, Sel};
|
||||
let mut reg = Registry::scan();
|
||||
let source = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/text/buffer.rs")).unwrap();
|
||||
let p = Prefs::default();
|
||||
let bits = ["(", ")", "{", "}", "\"", "'", "/*", "*/", "\n", " ", "\t", "é", "日本", "🦀", "fn x", "// c", "\r\n"];
|
||||
for seed in 1..=40u64 {
|
||||
let mut r = Rng(seed.wrapping_mul(0x9E3779B97F4A7C15));
|
||||
let name = ["a.rs", "a.py", "a.c", "a.html", "a.md"][seed as usize % 5];
|
||||
let mut d = Doc::new(1, &source[..source.len().min(4000 + r.next(2000))].chars().collect::<String>(), Some(name.into()), &mut reg);
|
||||
let original = d.buf.rope.to_string();
|
||||
d.highlight(®, 1000, 2000);
|
||||
for step in 0..400 {
|
||||
let len = d.buf.len();
|
||||
match r.next(16) {
|
||||
0 | 1 | 2 => { let a = r.next(len + 1); d.buf.set_cursor(a) }
|
||||
3 => { let (a, b) = (r.next(len + 1), r.next(len + 1)); d.buf.set_sels(vec![Sel { anchor: a, head: b, want_col: None }]) }
|
||||
4 => d.buf.add_cursor_vertical(r.next(2) == 0),
|
||||
5 | 6 | 7 => { let s = bits[r.next(bits.len())]; d.buf.type_text(s, &p) }
|
||||
8 => d.buf.backspace(&p),
|
||||
9 => d.buf.newline(&p),
|
||||
10 => d.buf.delete_lines(),
|
||||
11 => d.buf.move_lines(r.next(2) == 0),
|
||||
12 => d.buf.toggle_comment(Some("//"), None),
|
||||
13 => d.buf.indent(&p),
|
||||
14 => { d.buf.move_cursors([Move::WordLeft, Move::WordRight, Move::Up, Move::Down, Move::Home, Move::End][r.next(6)], r.next(2) == 0) }
|
||||
_ => { d.buf.undo(); }
|
||||
}
|
||||
let at = r.next(d.buf.lines());
|
||||
d.highlight(®, at + 20, 40);
|
||||
d.refresh_folds(4);
|
||||
assert_eq!(d.hl.len(), d.buf.lines(), "seed {seed} step {step}");
|
||||
assert!(d.buf.sels.iter().all(|s| s.head <= d.buf.len()), "seed {seed} step {step}");
|
||||
}
|
||||
d.buf.insert("end", EditKind::Other);
|
||||
while d.buf.undo() {}
|
||||
assert_eq!(d.buf.rope.to_string(), original, "seed {seed}: undo all the way restores the text");
|
||||
while d.buf.redo() {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timings on a large file. Printed, and only failed if something is badly off.
|
||||
#[test]
|
||||
fn large_file_stays_usable() {
|
||||
let dir = tmp("large");
|
||||
let line = " let value = compute(index, \"text\") + 42; // comment\n";
|
||||
let body = format!("fn main() {{\n{}}}\n", line.repeat(200_000));
|
||||
let f = write(&dir.join("big.rs"), &body);
|
||||
let t = Instant::now();
|
||||
let mut h = app(vec![f]);
|
||||
println!(" open 200k lines ({} MB): {:?}", body.len() / 1_000_000, t.elapsed());
|
||||
let t = Instant::now();
|
||||
wait(&mut h, 120, "all coloured", |h| !h.state().cur_doc().unwrap().highlight_pending());
|
||||
println!(" highlight everything: {:?}", t.elapsed());
|
||||
let mut worst = Duration::ZERO;
|
||||
for i in 0..40 {
|
||||
let d = h.state_mut().cur_doc_mut().unwrap();
|
||||
let at = d.buf.at(100_000 + i, 4);
|
||||
d.buf.set_cursor(at);
|
||||
d.buf.insert("x", damson::text::EditKind::Typing);
|
||||
let t = Instant::now();
|
||||
h.step();
|
||||
worst = worst.max(t.elapsed());
|
||||
}
|
||||
println!(" worst frame while typing mid-file: {worst:?}");
|
||||
let t = Instant::now();
|
||||
cmd(&mut h, Cmd::Find);
|
||||
h.state_mut().find.query = "compute".into();
|
||||
settle(&mut h, 3);
|
||||
println!(" find across the file: {:?}, {} hits", t.elapsed(), h.state().find.hits.len());
|
||||
assert!(h.state().find.hits.len() >= 50_000);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
Loading…
Reference in a new issue