Something went wrong. Try again.
wip text editor
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463use std::{ iter, path::PathBuf,};
use crate::{ buffer::Buffer, command_list::CommandList, diagnostic_list::DiagnosticList, document::Document, file_picker::{ FileIndex, FilePicker, }, jujutsu::JJPoller, lsp::{ LspClient, LspEvent, LspTextEdit, }, ui::{ AppEvent, EditorDimensions, Layer, LayerKind, Position, },};
pub(crate) struct Editor { document: Document, layers: Vec<Box<dyn Layer>>, file_index: FileIndex, dimensions: EditorDimensions, jj_poller: JJPoller, lsp: Option<LspClient>,}
impl Editor { pub(crate) fn new( file_path: PathBuf, dimensions: EditorDimensions, lsp: Option<LspClient>, jj_poller: JJPoller, file_index: FileIndex, ) -> anyhow::Result<Self> { let document = Document::new(file_path, dimensions)?;
if let Some(ref client) = lsp { client.document_opened(document.lsp_snapshot()); }
Ok(Self { document, layers: vec![], file_index, dimensions, jj_poller, lsp, }) }
pub(crate) fn visual_cursor_position(&self) -> Position { self.layers() .rev() .find_map(Layer::visual_cursor_position) .expect( "at least one visual layer must have a cursor position (i.e. `Document` cursor \ position is always `Some`)", ) }
pub(crate) fn handle_event(&mut self, event: &AppEvent) -> EventOutcome { puffin::profile_function!();
match *event { AppEvent::Resize(dimensions) => { self.resize(dimensions); EventOutcome::Handled } AppEvent::Layer(ref layer_event) => { let mut event_context = EventContext::new();
let result = self .layers_mut() .rev() .find_map(|layer| { match layer.handle_event(layer_event, &mut event_context) { EventOutcome::Handled => Some(EventOutcome::Handled), EventOutcome::CloseApp => Some(EventOutcome::CloseApp), EventOutcome::Unhandled => None, } }) .unwrap_or(EventOutcome::Unhandled);
match result { EventOutcome::Handled => self.apply_actions(event_context.actions()), EventOutcome::Unhandled | EventOutcome::CloseApp => result, } } } }
pub(crate) fn render(&mut self, buffer: &mut Buffer) { puffin::profile_function!();
for layer in self.layers_mut() { layer.render(buffer); } }
pub(crate) fn handle_layer_events(&mut self) -> EventOutcome { let mut result = if let Some(status) = self.jj_poller.refresh() { self.document.set_jj_info(status); EventOutcome::Handled } else { EventOutcome::Unhandled };
if let Some(ref lsp) = self.lsp { for event in lsp.events() { match event { LspEvent::PublishDiagnostics { params, position_encoding, } => { // TODO: when we support multiple open documents, match // up `params.uri` with the // correct doc if self.document.url() == ¶ms.uri && params .version .is_none_or(|version| version == self.document.version().value()) { self.document.publish_diagnostics(params, position_encoding);
result = EventOutcome::Handled; } } } } }
for layer in self.layers_mut() { match layer.handle_internal_events() { EventOutcome::Handled => result = EventOutcome::Handled, EventOutcome::CloseApp => return EventOutcome::CloseApp, EventOutcome::Unhandled => {} } }
result }
fn layers(&self) -> impl DoubleEndedIterator<Item = &dyn Layer> { iter::once(&self.document as &dyn Layer).chain(self.layers.iter().map(AsRef::as_ref)) }
fn layers_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut (dyn Layer + '_)> { iter::once(&mut self.document as &mut dyn Layer) .chain(self.layers.iter_mut().map(|l| l.as_mut() as &mut dyn Layer)) }
fn apply_actions(&mut self, actions: Vec<EditorAction>) -> EventOutcome { for action in actions { match action { EditorAction::AddLayer(layer) => { match layer { LayerKind::CommandList => { self.layers .push(Box::new(CommandList::new(self.dimensions))); } LayerKind::FilePicker => { self.layers .push(Box::new(FilePicker::new(&self.file_index, self.dimensions))); } LayerKind::DiagnosticList => { let diagnostics = self.document.diagnostics_for_cursor_line();
if !diagnostics.is_empty() { self.layers.push(Box::new(DiagnosticList::new( &diagnostics, self.dimensions, ))); } } } } EditorAction::RemoveLayer(layer_kind) => { // TODO: will we ever have multiple layers of the same type? // if so, the layers will need ids so that we can ensure we // remove the correct one let remove_index = self .layers .iter() .position(|layer| layer.kind() == Some(layer_kind));
if let Some(idx) = remove_index { self.layers.remove(idx); } } EditorAction::Quit => return EventOutcome::CloseApp, EditorAction::Write => { match self.save_document() { Ok(()) => {} Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::WriteQuit => { match self.save_document() { Ok(()) => return EventOutcome::CloseApp, Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::OpenFile(path) => { match self.replace_document(path) { Ok(()) => {} Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::DocumentChanged(edit) => { if let Some(ref lsp) = self.lsp { lsp.document_changed(self.document.lsp_snapshot(), edit); } } } }
EventOutcome::Handled }
fn resize(&mut self, dimensions: EditorDimensions) { self.dimensions = dimensions;
for layer in self.layers_mut() { layer.resize(dimensions); } }
fn save_document(&self) -> anyhow::Result<()> { self.document.save()?; if let Some(ref lsp) = self.lsp { lsp.document_saved(self.document.lsp_snapshot()); }
Ok(()) }
fn replace_document(&mut self, path: PathBuf) -> anyhow::Result<()> { let new_doc = Document::new(path.clone(), self.dimensions)?;
if let Some(ref lsp) = self.lsp { let old_doc_id = self.document.lsp_id(); lsp.document_closed(old_doc_id.clone()); lsp.document_opened(new_doc.lsp_snapshot()); }
self.document = new_doc; self.jj_poller.update_path(path);
Ok(()) }
#[cfg(test)] pub(crate) const fn document(&self) -> &Document { &self.document }}
#[derive(Debug)]#[must_use]pub(crate) enum EventOutcome { Handled, Unhandled, CloseApp,}
pub(crate) struct EventContext { actions: Vec<EditorAction>,}
impl EventContext { pub(crate) const fn new() -> Self { Self { actions: Vec::new(), } }
/// Queue a new action to be applied to the /// [`Editor`](crate::editor::Editor). pub(crate) fn push_action(&mut self, action: EditorAction) { self.actions.push(action); }
pub(crate) fn actions(self) -> Vec<EditorAction> { self.actions }}
#[derive(Debug)]pub(crate) enum EditorAction { AddLayer(LayerKind), RemoveLayer(LayerKind), Quit, Write, WriteQuit, OpenFile(PathBuf), DocumentChanged(LspTextEdit),}
#[cfg(test)]mod tests {
use crossterm::event::KeyCode;
use crate::{ test_harness::TestHarness, ui::{ Columns, Dimensions, EditorDimensions, Rectangle, Rows, }, };
#[test] fn displays_basic_screen() { let harness = TestHarness::new( "hello\nthere\nworld", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), );
insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────▼──────────────────┐ ▶ 1 hello │ │ 1 there │ │ 2 world │ │ │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ " ); }
#[test] fn moves_cursor_and_inserts_text() { let mut harness = TestHarness::new( "hello\nthere\nworld", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), );
insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────▼──────────────────┐ ▶ 1 hello │ │ 1 there │ │ 2 world │ │ │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ " );
// navigate harness.send_key(KeyCode::Char('j')); harness.send_key(KeyCode::Char('l'));
// enter text harness.send_key(KeyCode::Char('i')); harness.send_key(KeyCode::Char('h')); harness.send_key(KeyCode::Char('e')); harness.send_key(KeyCode::Char('y'));
insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────────▼──────────────┐ │ 1 hello │ ▶ 2 theyhere │ │ 1 world │ │ │ │ INSERT test.txt text │ │ │ └────────────────────────┘ " ); }
#[test] #[expect( clippy::unicode_not_nfc, reason = "it's the point of the test that it displays correctly, so i want to see it" )] fn zero_width_graphemes_display_as_dotted_circle() { let mut harness = TestHarness::new( "\u{301}x\n\u{200B}\na\u{200B}\na\u{301}", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), );
harness.send_key(KeyCode::Char('w')); harness.send_key(KeyCode::Char('w'));
insta::assert_snapshot!(harness.screen().to_string(), @" ┌─────▼──────────────────┐ │ 1 ◌x │ ▶ 2 ◌ │ │ 1 a◌ │ │ 2 á │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ "); }
#[test] fn cursor_stays_on_screen_when_eof_wraps() { let mut harness = TestHarness::new("", EditorDimensions::MIN); let initial_screen = harness.screen(); let text_start = initial_screen.cursor(); let text_width = initial_screen.dimensions().width() - text_start.left();
assert!(text_width > Columns::new(0));
// insert text until cursor is one past the right edge. this should // cause it to wrap onto the next row harness.send_key(KeyCode::Char('i')); for _ in 0..text_width.value() { harness.send_key(KeyCode::Char('a')); }
let screen = harness.screen(); assert!(Rectangle::from_dimensions(screen.dimensions()).contains(&screen.cursor())); assert_eq!(screen.cursor(), text_start.row_offset(Rows::new(1))); }
#[test] fn cursor_stays_on_screen_for_lines_taller_than_screen() { let dimensions = EditorDimensions::MIN; let text_width = { let harness = TestHarness::new("", dimensions); let screen = harness.screen(); screen.dimensions().width() - screen.cursor().left() }; let height = dimensions.get().height();
// when wrapped, this single line is taller than the editor let contents = "a".repeat(text_width.value() * height.value() + 1); let mut harness = TestHarness::new(&contents, dimensions);
harness.send_key(KeyCode::Char('$'));
let screen = harness.screen(); let cursor = screen.cursor(); assert!(Rectangle::from_dimensions(screen.dimensions()).contains(&cursor)); }}