#[cfg(test)] mod proptests; use std::{ cmp::{ self, Reverse, }, fmt, fs::File, io::{ BufReader, BufWriter, }, iter, num::{ NonZero, NonZeroUsize, }, ops::{ ControlFlow, Range, }, path::PathBuf, sync::{ self, mpsc::{ Receiver, Sender, }, }, thread, }; use anyhow::Context as _; use crossterm::event::{ KeyCode, KeyEvent, KeyModifiers, }; use gen_lsp_types::{ DiagnosticSeverity, Message, PublishDiagnosticsParams, }; use itertools::Itertools as _; use ropey::{ Rope, RopeSlice, }; use unicode_segmentation::UnicodeSegmentation as _; use url::Url; use crate::{ buffer::Buffer, cursor::{ CursorState, MovementAction, Selection, apply_movement, move_cursor_right, }, editor::{ EditorAction, EventContext, EventOutcome, }, grapheme_layout::{ GraphemeLayoutIterator, WrapBehavior, }, highlight::{ Checkpoint, Highlighter, Token, }, jujutsu::JJInfo, keymap::{ BehaviorAction, DocumentAction, EditAction, KeyBinding, KeyMap, KeySequence, }, language::Language, lsp::{ DocumentLspId, DocumentSnapshot, DocumentVersion, LspTextEdit, PositionEncoding, }, style::Style, text::{ ByteIndex, Grapheme, LeftChar, LineIndex, RightChar, RopeSliceExt as _, number_width, text_width, }, ui::{ Alignment, Columns, Dimensions, EditorDimensions, Layer, LayerEvent, LayerKind, NonZeroColumns, Position, Rectangle, Rows, Span, WrapOutcome, spans_width, text_area::TextArea, }, }; #[derive(Debug)] pub(crate) struct Document { text: Rope, cursor_state: CursorState, /// The keys that have been pressed which may add up to a registered /// keybinding. Used in the `KeyMap` lookups. key_sequence: KeySequence, file_path: PathBuf, lsp_id: DocumentLspId, layout: Layout, /// The detected language of the document - this is based on the extension /// rather than the contents of the file. language: Language, jj_info: JJInfo, error: Option, highlights: HighlightCache, highlight_request_tx: Sender, highlight_response_rx: Receiver, version: DocumentVersion, diagnostics: Diagnostics, } impl Document { pub(crate) fn new( file_path: PathBuf, editor_dimensions: EditorDimensions, ) -> anyhow::Result { let text = Rope::from_reader(BufReader::new(File::open(&file_path)?))?; let line_count = text.slice(..).line_count(); let language = Language::new(&file_path); let lsp_id = DocumentLspId::new(&file_path, language)?; let (highlight_request_tx, highlight_response_rx) = spawn_highlights_thread(); let this = Self { text, cursor_state: CursorState::default(), key_sequence: KeySequence::new(Mode::Normal), language, file_path, lsp_id, layout: Layout::new(line_count, editor_dimensions), jj_info: JJInfo::default(), error: None, highlights: HighlightCache::new(), highlight_request_tx, highlight_response_rx, version: DocumentVersion::default(), diagnostics: Diagnostics::new(), }; this.request_highlight_refresh(); Ok(this) } pub(crate) fn handle_key_event( &mut self, key_event: KeyEvent, context: &mut EventContext, ) -> EventOutcome { let keymap = KeyMap::for_mode(self.mode()); self.key_sequence.push(KeyBinding::from(key_event)); let (keys, count) = self.key_sequence.parse(); let maybe_action = match keymap.get(&keys) { Some(&KeyMap::BindingPart { map: _ }) => { // the key sequence could form a binding with subsequent key // events. since we'd already pushed the latest // event to the sequence store, we are done None } Some(&KeyMap::Action(action)) => Some(action), None => { // the current key sequence does not form a binding for any of // the registered commands. therefore, we clear // the sequence self.key_sequence.clear(); // look for any fallback events that aren't registered in the // map self.event_fallback(key_event) } }; if let Some(action) = maybe_action { self.apply_action(action, count, context); self.key_sequence.clear(); self.clamp_cursor(); self.recalculate_scroll(); } EventOutcome::Handled } /// Displays the keybindings (if any) that are currently possible for the /// user to invoke, based on the current sequence of key events. fn render_key_hint(&self, buffer: &mut Buffer) { // TODO: would be nice to display the count in the labels where it's // relevant let (keys, _count) = self.key_sequence.parse(); if keys.is_empty() { return; } let keymap = KeyMap::for_mode(self.mode()); let Some(&KeyMap::BindingPart { map }) = keymap.get(&keys) else { return; }; let (hints, max_width, max_height) = map.iter().fold( (String::new(), Columns::new(0), Rows::new(0)), |(hints, max_width, max_height), &(ref event, ref map_node)| { let key = event.to_string(); let label = match *map_node { KeyMap::BindingPart { map: _ } => "...", KeyMap::Action(action) => action.label(), }; let hint = format!("{key}: {label}\n"); ( hints + &hint, cmp::max(max_width, text_width(&hint)), // we will disable wrapping so we can simply increment the // count max_height + Rows::new(1), ) }, ); let container = self.layout.text.area(); let hints_rectangle = container.at_bottom_right(Dimensions::new( cmp::min(container.width(), max_width), cmp::min(container.height(), max_height), )); buffer.clear_and_style_rectangle(&hints_rectangle, Style::HINTS); for visual_grapheme in GraphemeLayoutIterator::new(hints.graphemes(true), WrapBehavior::NoWrap) { if visual_grapheme.position().top() >= hints_rectangle.height() { break; } // wrapping has been turned off, and therefore we ignore all // graphemes that would overflow if visual_grapheme.position().left() >= hints_rectangle.width() { continue; } buffer[visual_grapheme.position().offset(hints_rectangle.offset())] .set_content(visual_grapheme.grapheme().display()); } } fn render_status_line(&self, buffer: &mut Buffer) { buffer.clear_and_style_rectangle(&self.layout.status_line, Style::STATUS_LINE); buffer.clear_and_style_rectangle(&self.layout.messages, Style::STATUS_LINE_MESSAGES); let mode_span = Span::new(format!(" {} ", self.mode())).with_style(Style::STATUS_LINE_MODE); let file_name_span = self .file_path .file_name() .and_then(|name| name.to_str()) .map(|name| Span::new(format!(" {name} ")).with_style(Style::STATUS_LINE_TEXT)); let jj_desc_span = self .jj_info .description() .map(|desc| Span::new(format!(r#" "{desc}" "#)).with_style(Style::STATUS_LINE_TEXT)); let (jj_diff_added_span, jj_diff_removed_span) = self .jj_info .diff() .map(|diff| { ( Span::new(format!(" +{}", diff.added())).with_style(Style::DIFF_ADDED), Span::new(format!(" -{} ", diff.removed())).with_style(Style::DIFF_REMOVED), ) }) .unzip(); let left_spans: Vec = iter::once(Some(mode_span)) .chain([ file_name_span, jj_diff_added_span, jj_diff_removed_span, jj_desc_span, ]) .flatten() .collect(); let language_span = Span::new(format!(" {} ", self.language)).with_style(Style::STATUS_LINE_TEXT); let right_spans = match self.key_sequence.to_string().as_str() { "" => vec![language_span], keys => { vec![ Span::new(format!(" {keys} ")).with_style(Style::STATUS_LINE_TEXT), language_span, ] } }; let (left_rect, right_rect) = self .layout .status_line .split_at_column(spans_width(&left_spans)); buffer.render_spans(&left_spans, &left_rect, Alignment::Left); buffer.render_spans(&right_spans, &right_rect, Alignment::Right); if let Some(ref error) = self.error { buffer.render_span( &Span::new(error).with_style(Style::STATUS_LINE_ERROR), &self.layout.messages.offset(), &self.layout.messages, ); } } const fn cursor(&self) -> ByteIndex { self.cursor_state.cursor() } const fn selection(&self) -> Selection { self.cursor_state.selection() } const fn set_cursor(&mut self, index: ByteIndex) { self.cursor_state.set_cursor(index); } const fn set_anchor(&mut self, index: ByteIndex) { self.cursor_state.set_anchor(index); } fn apply_action( &mut self, action: DocumentAction, count: Option, event_context: &mut EventContext, ) { puffin::profile_function!(); let action_count = count.map_or(1, NonZero::get); match action { DocumentAction::Movement(movement_action) => { self.handle_movement_action(movement_action, count); } DocumentAction::Edit(edit_action) => { self.handle_edit_action(edit_action, action_count, event_context); } DocumentAction::Behavior(BehaviorAction::SwitchToInsertMode) => self.insert_mode(), DocumentAction::Behavior(BehaviorAction::SwitchToNormalMode) => self.normal_mode(), DocumentAction::Behavior(BehaviorAction::SwitchToVisualMode) => self.visual_mode(), DocumentAction::Behavior(BehaviorAction::OpenCommandList) => { Self::open_command_list(event_context); } DocumentAction::Behavior(BehaviorAction::ClearInput) => self.clear_input(), DocumentAction::Behavior(BehaviorAction::OpenFilePicker) => { Self::open_file_picker(event_context); } DocumentAction::Behavior(BehaviorAction::AppendText) => self.append_text(), DocumentAction::Behavior(BehaviorAction::OpenDiagnosticList) => { Self::open_diagnostic_list(event_context); } DocumentAction::Behavior(BehaviorAction::VerticallyCenter) => { self.center_cursor_vertically(); } } if action.should_reset_desired_column() { self.cursor_state.clear_desired_column(); } } fn handle_edit_action(&mut self, action: EditAction, count: usize, context: &mut EventContext) { let (transaction, mode) = match action { EditAction::InsertChar(ch) => (self.insert_char(ch), None), EditAction::DeleteGrapheme => (self.delete_grapheme(), None), EditAction::InsertNewline => (self.insert_newline(), None), EditAction::DeleteWord => (self.delete_word(count), None), EditAction::ChangeWord => (self.delete_word(count), Some(Mode::Insert)), EditAction::DeleteToLineEnd => (self.delete_to_line_end(), None), EditAction::ChangeToLineEnd => (self.delete_to_line_end(), Some(Mode::Insert)), EditAction::DeleteToLineStart => (self.delete_to_line_start(), None), EditAction::DeleteToLineFirstNonBlank => (self.delete_to_first_non_blank(), None), EditAction::DeleteLine => (self.delete_line(count), None), EditAction::DeleteWholeWord => (self.delete_whole_word(), None), EditAction::DeleteToPrevWordStart => (self.delete_to_prev_word_start(count), None), EditAction::AppendTextLineEnd => (self.append_text_line_end(), Some(Mode::Insert)), EditAction::DeleteToWordEnd => (self.delete_to_word_end(count), None), EditAction::ChangeToLineStart => (self.delete_to_line_start(), Some(Mode::Insert)), EditAction::ChangeToLineFirstNonBlank => { (self.delete_to_first_non_blank(), Some(Mode::Insert)) } EditAction::ChangeLine => (self.change_line(count), Some(Mode::Insert)), EditAction::ChangeWholeWord => (self.delete_whole_word(), Some(Mode::Insert)), EditAction::ChangeToPrevWordStart => { (self.delete_to_prev_word_start(count), Some(Mode::Insert)) } EditAction::ChangeToWordEnd => (self.delete_to_word_end(count), Some(Mode::Insert)), EditAction::DeleteSelection => (self.delete_selection(), Some(Mode::Normal)), EditAction::ChangeSelection => (self.delete_selection(), Some(Mode::Insert)), EditAction::OpenLineBelow => (self.open_new_line_below(), Some(Mode::Insert)), EditAction::OpenLineAbove => (self.open_new_line_above(), Some(Mode::Insert)), EditAction::DeleteDown => (self.delete_down(count), None), EditAction::DeleteUp => (self.delete_up(count), None), EditAction::InsertTab => (self.insert_tab(), None), }; self.apply_transaction(transaction, context); match mode { Some(Mode::Normal) => self.normal_mode(), Some(Mode::Insert) => self.insert_mode(), Some(Mode::Visual) => self.visual_mode(), None => {} } } fn handle_movement_action(&mut self, action: MovementAction, count: Option) { let text_width = self.layout.max_text_width(); apply_movement( self.text.slice(..), &mut self.cursor_state, action, count, text_width, ); } fn apply_transaction(&mut self, transaction: Transaction, context: &mut EventContext) { if let Some(edit) = transaction.edit && !edit.is_noop() { let initial_text = self.text.clone(); self.apply_edit(&edit); self.on_edit(edit, initial_text, context); } self.cursor_state.set_selection(transaction.selection); } #[expect( clippy::disallowed_methods, reason = "this is the only place we can use the rope-mutating methods" )] fn apply_edit(&mut self, edit: &TextEdit) { self.text .remove(edit.range.start.value()..edit.range.end.value()); self.text .insert(edit.range.start.value(), &edit.replacement); } fn on_edit(&mut self, edit: TextEdit, initial_text: Rope, context: &mut EventContext) { self.diagnostics.clear(); self.version = self.version.next(); self.request_highlight_refresh(); self.layout.resize( self.text.slice(..).line_count(), self.layout.editor_dimensions, ); context.push_action(EditorAction::DocumentChanged(LspTextEdit::new( initial_text, edit, ))); } /// Ensures that the cursor does not go past the end of the file. fn clamp_cursor(&mut self) { let end = ByteIndex::new(self.text.len()); let max_cursor = match self.mode() { Mode::Normal | Mode::Visual => self.text.slice(..).previous_grapheme_position(end), Mode::Insert => end, }; self.set_cursor(cmp::min(self.cursor(), max_cursor)); } fn recalculate_scroll(&mut self) { self.layout .text .recalculate_scroll(self.text.slice(..), self.cursor()); } fn center_cursor_vertically(&mut self) { let text = self.text.slice(..); let cursor_line = text.line_idx_containing_byte(self.cursor()); let middle = self.layout.text.area().height() / 2; self.layout .text .scroll_to_line(text, cursor_line.saturating_sub(middle)); } const fn event_fallback(&self, key_event: KeyEvent) -> Option { match self.mode() { Mode::Normal | Mode::Visual => None, Mode::Insert => { if let KeyCode::Char(ch) = key_event.code && !key_event.modifiers.contains(KeyModifiers::CONTROL) && !key_event.modifiers.contains(KeyModifiers::ALT) { Some(DocumentAction::Edit(EditAction::InsertChar(ch))) } else { None } } } } const fn insert_mode(&mut self) { self.key_sequence.set_mode(Mode::Insert); } const fn normal_mode(&mut self) { self.key_sequence.set_mode(Mode::Normal); } const fn visual_mode(&mut self) { self.set_anchor(self.cursor()); self.key_sequence.set_mode(Mode::Visual); } fn insert_char(&self, ch: char) -> Transaction { Transaction::new( Some(TextEdit::insert(self.cursor(), ch)), self.selection().with_cursor(self.cursor() + ch.len_utf8()), ) } fn delete_grapheme(&self) -> Transaction { let start = self .text .slice(..) .previous_grapheme_position(self.cursor()); Transaction::new( Some(TextEdit::delete(start..self.cursor())), self.selection().with_cursor(start), ) } fn insert_newline(&self) -> Transaction { self.insert_char('\n') } /// Deletes from the current cursor position up to (but not including) the /// start of the next word. fn delete_word(&self, count: usize) -> Transaction { let cursor = self.cursor(); let end = (0..count).fold(cursor, |start, _| { match self .text .slice(start.value()..) .chars() .tuple_windows() .map(|(left, right)| (LeftChar::new(left), RightChar::new(right))) .try_fold(start, |index, (left, right)| { let next_index = index + left.ch().len_utf8(); if right.is_word_start(left) { ControlFlow::Break(next_index) } else { ControlFlow::Continue(next_index) } }) { ControlFlow::Break(index) => index, ControlFlow::Continue(_) => ByteIndex::new(self.text.len()), } }); Transaction::new(Some(TextEdit::delete(cursor..end)), self.selection()) } fn delete_to_line_end(&self) -> Transaction { let text = self.text.slice(..); let end = text .line_break(text.line_idx_containing_byte(self.cursor())) .position; Transaction::new(Some(TextEdit::delete(self.cursor()..end)), self.selection()) } fn delete_to_line_start(&self) -> Transaction { let text = self.text.slice(..); let line_start = text.line_start_byte(text.line_idx_containing_byte(self.cursor())); Transaction::new( Some(TextEdit::delete( text.inclusive_to_exclusive_range(line_start..=self.cursor()), )), self.selection().with_cursor(line_start), ) } fn delete_to_first_non_blank(&self) -> Transaction { let text = self.text.slice(..); let line_index = text.line_idx_containing_byte(self.cursor()); let line = text.line_at(line_index); let cursor = self.cursor(); let start = text.line_start_byte(line_index) + line.first_non_blank_offset(); let delete_range = match cursor.cmp(&start) { cmp::Ordering::Less => cursor..start, cmp::Ordering::Equal => return Transaction::new(None, self.selection()), cmp::Ordering::Greater => { let range = text.inclusive_to_exclusive_range(start..=cursor); // this is to prevent deleting a line break range.start..cmp::min(range.end, text.line_break(line_index).position) } }; let new_cursor = delete_range.start; Transaction::new( Some(TextEdit::delete(delete_range)), self.selection().with_cursor(new_cursor), ) } fn delete_line(&self, count: usize) -> Transaction { let range = self.line_range(count); let cursor = range.start; Transaction::new( Some(TextEdit::delete(range)), self.selection().with_cursor(cursor), ) } fn delete_whole_word(&self) -> Transaction { let cursor = self.cursor(); let Ok(current_ch) = self.text.get_char(cursor.value()) else { return Transaction::new(None, self.selection()); }; let reversed_chars = self .text .slice(..cursor.value()) .chars_at(cursor.value()) .reversed(); let start = iter::once(current_ch) .chain(reversed_chars) .tuple_windows() .map(|(right, left)| (LeftChar::new(left), RightChar::new(right))) .try_fold(cursor, |index, (left, right)| { if right.is_word_start(left) { ControlFlow::Break(index) } else { ControlFlow::Continue(index.saturating_sub(left.ch().len_utf8())) } }) .break_value() .unwrap_or(ByteIndex::new(0)); let end = match self .text .slice(cursor.value()..) .chars() .tuple_windows() .map(|(left, right)| (LeftChar::new(left), RightChar::new(right))) .try_fold(self.cursor(), |index, (left, right)| { let next_index = index + left.ch().len_utf8(); if left.is_word_end(right) { // we started at the leftmost byte of the `left` char, and // we want to delete it, and so the byte // index we provide is the start of the next // char, allowing us to use an exclusive range in the // `remove` call below ControlFlow::Break(next_index) } else { ControlFlow::Continue(next_index) } }) { ControlFlow::Continue(index) | ControlFlow::Break(index) => index, }; Transaction::new( Some(TextEdit::delete(start..end)), self.selection().with_cursor(start), ) } fn delete_to_prev_word_start(&self, count: usize) -> Transaction { let cursor = self.cursor(); let text = self.text.slice(..cursor.value()); let start = match count { 0 => cursor, _ => { text.chars_at(cursor.value()) .reversed() .tuple_windows() .map(|(right, left)| (LeftChar::new(left), RightChar::new(right))) .scan(cursor, |index, (left, right)| { *index = index.saturating_sub(right.ch().len_utf8()); Some(right.is_word_start(left).then_some(*index)) }) .flatten() .nth(count - 1) .unwrap_or(ByteIndex::new(0)) } }; Transaction::new( Some(TextEdit::delete(start..cursor)), self.selection().with_cursor(start), ) } fn append_text(&mut self) { self.cursor_state.set_selection(move_cursor_right( self.text.slice(..), self.selection(), 1, )); self.insert_mode(); } fn append_text_line_end(&self) -> Transaction { let text = self.text.slice(..); let line_break = text.line_break(text.line_idx_containing_byte(self.cursor())); let edit = if line_break.has_linebreak { None } else { // there is no linebreak, and so we need to make room to append text // by adding one. we will not shift the cursor, so the // user will overwrite the empty space when they enter // text TODO: use the same linebreak style that the rest // of the document uses, if applicable Some(TextEdit::insert(line_break.position, '\n')) }; Transaction::new(edit, self.selection().with_cursor(line_break.position)) } fn delete_to_word_end(&self, count: usize) -> Transaction { let cursor = self.cursor(); let end = (0..count).fold(cursor, |start, _| { // we start searching at the next grapheme so that the cursor // doesn't stay where it is if it's already at the end // of a word (in that case, we want to go to the end of // the **next** word) let search_start = self.text.slice(..).next_grapheme_position(start); match self .text .slice(search_start.value()..) .chars() .tuple_windows() .map(|(left, right)| (LeftChar::new(left), RightChar::new(right))) .try_fold(search_start, |index, (left, right)| { let next_index = index + left.ch().len_utf8(); if left.is_word_end(right) { // we want to delete the whole character, which may be // multiple bytes, // and so we delete up to (but not including) the next // character index ControlFlow::Break(next_index) } else { ControlFlow::Continue(next_index) } }) { ControlFlow::Continue(index) | ControlFlow::Break(index) => index, } }); Transaction::new(Some(TextEdit::delete(cursor..end)), self.selection()) } fn change_line(&self, count: usize) -> Transaction { let range = self.line_range(count); let cursor = range.start; Transaction::new( // we removed the linebreak (if there was one), and so we need to // make room to append text by adding one. we will not shift the // cursor, so the user will overwrite the empty space when they // enter text TODO: use the same linebreak style that the rest of // the document uses, if applicable Some(TextEdit::replace(range, "\n")), self.selection().with_cursor(cursor), ) } fn delete_selection(&self) -> Transaction { let range = self.selection().range(self.text.slice(..)); let cursor = range.start; Transaction::new( Some(TextEdit::delete(range)), self.selection().with_cursor(cursor), ) } fn open_new_line_below(&self) -> Transaction { let text = self.text.slice(..); let line_index = text.line_idx_containing_byte(self.cursor()); let line_break = text.line_break(line_index); let to_insert = if line_break.has_linebreak { "\n" } else { "\n\n" }; Transaction::new( Some(TextEdit::insert(line_break.position, to_insert)), self.selection() .with_cursor(line_break.position + '\n'.len_utf8()), ) } fn open_new_line_above(&self) -> Transaction { let text = self.text.slice(..); let line_start = text.line_start_byte(text.line_idx_containing_byte(self.cursor())); Transaction::new( Some(TextEdit::insert(line_start, '\n')), self.selection().with_cursor(line_start), ) } /// Deletes the current plus the `count` succeeding lines. fn delete_down(&self, count: usize) -> Transaction { let text = self.text.slice(..); let range = self.line_range(count + 1); let next_line = text.slice(range.end.value()..).line_at(LineIndex::new(0)); let cursor = range.start + next_line.first_non_blank_offset(); Transaction::new( Some(TextEdit::delete(range)), self.selection().with_cursor(cursor), ) } /// Deletes the current plus the `count` preceding lines. fn delete_up(&self, count: usize) -> Transaction { let text = self.text.slice(..); let current_line = text.line_idx_containing_byte(self.cursor()); if current_line == LineIndex::new(0) { return Transaction::new(None, self.selection()); } let range = self.backwards_line_range(count + 1); let cursor = text .line_idx_containing_byte(range.start) .checked_sub(1) .map_or(range.start, |line| { text.line_start_byte(line) + text.line_at(line).first_non_blank_offset() }); Transaction::new( Some(TextEdit::delete(range)), self.selection().with_cursor(cursor), ) } fn open_command_list(event_context: &mut EventContext) { event_context.push_action(EditorAction::AddLayer(LayerKind::CommandList)); } fn open_file_picker(event_context: &mut EventContext) { event_context.push_action(EditorAction::AddLayer(LayerKind::FilePicker)); } fn open_diagnostic_list(event_context: &mut EventContext) { event_context.push_action(EditorAction::AddLayer(LayerKind::DiagnosticList)); } pub(crate) fn save(&self) -> anyhow::Result<()> { // TODO: atomic saves // TODO: async saves self.text .write_to(BufWriter::new( File::create(&self.file_path).context("File cannot be written to")?, )) .context("Failed to save")?; Ok(()) } pub(crate) fn set_error(&mut self, error_message: String) { self.error = Some(error_message); } fn clear_input(&mut self) { self.key_sequence.clear(); } pub(crate) const fn mode(&self) -> Mode { self.key_sequence.mode() } fn insert_tab(&self) -> Transaction { // TODO: if the file treats tabs as spaces, then we should insert spaces // here instead. self.insert_char('\t') } /// Gets the range of bytes for `count` lines, starting with the current /// line. fn line_range(&self, count: usize) -> Range { let text = self.text.slice(..); let index = text.line_idx_containing_byte(self.cursor()); let start = text.line_start_byte(index); let end = text .get_line_start_byte(index + count) .unwrap_or_else(|| ByteIndex::new(text.len())); start..end } /// Gets the range of bytes for `count` lines, going backwards from the /// current line. fn backwards_line_range(&self, count: usize) -> Range { let text = self.text.slice(..); let index_after_current = text.line_idx_containing_byte(self.cursor()) + 1; let start = text.line_start_byte(index_after_current.saturating_sub(count)); let end = text .get_line_start_byte(index_after_current) .unwrap_or_else(|| ByteIndex::new(text.len())); start..end } fn request_highlight_refresh(&self) { let _ = self.highlight_request_tx.send(HighlightRequest { text: self.text.clone(), language: self.language, }); } pub(crate) fn set_jj_info(&mut self, info: JJInfo) { self.jj_info = info; } /// Creates a snapshot of relevant data from the document to be used in /// requests made to language server(s). pub(crate) fn lsp_snapshot(&self) -> DocumentSnapshot { DocumentSnapshot::new(self.lsp_id.clone(), self.text.clone(), self.version) } pub(crate) const fn url(&self) -> &Url { self.lsp_id.url() } pub(crate) fn publish_diagnostics( &mut self, params: PublishDiagnosticsParams, position_encoding: PositionEncoding, ) { self.diagnostics .publish_new(params.diagnostics, self.text.slice(..), position_encoding); } pub(crate) const fn version(&self) -> DocumentVersion { self.version } pub(crate) const fn lsp_id(&self) -> &DocumentLspId { &self.lsp_id } /// A list of diagnostics that are part of the current cursor line. /// Sorted by severity first and then position. pub(crate) fn diagnostics_for_cursor_line(&self) -> Vec<&Diagnostic> { self.diagnostics .on_line(self.text.slice(..).line_idx_containing_byte(self.cursor())) .sorted_by_key(|diagnostic| { ( Reverse(diagnostic.severity_priority()), diagnostic.byte_range.start, ) }) .collect() } } fn spawn_highlights_thread() -> (Sender, Receiver) { let (highlight_request_tx, highlight_request_rx) = sync::mpsc::channel::(); let (highlight_response_tx, highlight_response_rx) = sync::mpsc::channel::(); thread::spawn(move || { while let Ok(request) = highlight_request_rx.recv() { let request = highlight_request_rx.try_iter().last().unwrap_or(request); let _ = highlight_response_tx.send(HighlightCache { tokens: Highlighter::new(request.text, ByteIndex::new(0), request.language) .filter_map(|(token, checkpoint)| { match checkpoint { Checkpoint::Yes => Some(token), Checkpoint::No => None, } }) .collect(), }); } }); (highlight_request_tx, highlight_response_rx) } impl Layer for Document { fn render(&mut self, buffer: &mut Buffer) { let text = self.text.slice(..); let scroll_offset = self.layout.text.scroll_offset(); let start_byte = scroll_offset.byte_index(); buffer.clear_and_style_rectangle(&self.layout.gutter.area, Style::BACKGROUND); buffer.clear_and_style_rectangle(self.layout.text.area(), Style::BACKGROUND); let Some(text_width) = self.layout.max_text_width() else { // if there's no room for text, there's no point rendering anything. return; }; let cursor_line = text.line_idx_containing_byte(self.cursor()); let mut line_index = text.line_idx_containing_byte(start_byte); let mut highlighter = Highlighter::new( self.text.clone(), self.highlights.checkpoint_before(start_byte), self.language, ); let mut current_highlight = highlighter.next(); let mut diagnostics = self.diagnostics.spans_from(start_byte); let mut current_diagnostic = diagnostics.next(); let gutter_renderer = GutterRenderer { gutter: &self.layout.gutter, cursor_line, }; for visual_grapheme in GraphemeLayoutIterator::new( self.text.slice(start_byte.value()..).graphemes(), WrapBehavior::Wrap { max_width: text_width, }, ) .starting_at(scroll_offset) { if visual_grapheme.position().top() >= self.layout.text.area().height() { break; } if visual_grapheme.position().left() == Columns::new(0) { gutter_renderer.render( visual_grapheme.position().top(), visual_grapheme.wrap_status(), line_index, self.diagnostics.line_severity(line_index), buffer, ); } let translated_position = visual_grapheme .position() .offset(self.layout.text.area().offset()); debug_assert!( self.layout.text.area().contains(&translated_position), "graphemes must be rendered inside the text area" ); let grapheme = visual_grapheme.grapheme(); let grapheme_index = visual_grapheme.byte_index(); while current_highlight .as_ref() .is_some_and(|&(ref highlight, _checkpoint)| !highlight.contains(grapheme_index)) { current_highlight = highlighter.next(); } while current_diagnostic .is_some_and(|diagnostic| diagnostic.range.end <= grapheme_index) { current_diagnostic = diagnostics.next(); } let style = current_highlight .as_ref() .map(|&(ref token, _checkpoint)| token.kind()) .map_or(Style::TEXT, Style::from) .merge( current_diagnostic .filter(|diagnostic| diagnostic.range.contains(&grapheme_index)) .map(|diagnostic| diagnostic.severity) .map_or_else(Style::new, Style::diagnostic), ); buffer[translated_position] .set_content(grapheme.display()) .set_style(style); if matches!(self.mode(), Mode::Visual) && self.selection().range(text).contains(&grapheme_index) { buffer[translated_position].set_style(style.merge(Style::TEXT_SELECTED)); } if matches!(grapheme, Grapheme::LineBreak) { line_index += LineIndex::new(1); } } self.render_status_line(buffer); self.render_key_hint(buffer); } fn handle_event( &mut self, event: &LayerEvent, event_context: &mut EventContext, ) -> EventOutcome { match *event { LayerEvent::Key(key_event) => self.handle_key_event(key_event, event_context), LayerEvent::Mouse(_mouse_event) => todo!(), LayerEvent::FocusGained | LayerEvent::FocusLost | LayerEvent::Paste => todo!(), } } fn visual_cursor_position(&self) -> Option { Some( self.layout .text .visual_cursor_position(self.text.slice(..), self.cursor()), ) } fn handle_internal_events(&mut self) -> EventOutcome { match self.highlight_response_rx.try_iter().last() { Some(highlights) => { self.highlights = highlights; EventOutcome::Handled } None => EventOutcome::Unhandled, } } fn kind(&self) -> Option { None } fn resize(&mut self, editor_dimensions: EditorDimensions) { self.layout .resize(self.text.slice(..).line_count(), editor_dimensions); self.recalculate_scroll(); } } #[derive(Debug, PartialEq, Eq)] struct Layout { editor_dimensions: EditorDimensions, gutter: Gutter, text: TextArea, status_line: Rectangle, messages: Rectangle, } impl Layout { fn new(line_count: usize, editor_dimensions: EditorDimensions) -> Self { let dimensions = editor_dimensions.get(); let (content, status_line) = Rectangle::from_dimensions(dimensions) .split_at_row(dimensions.height().saturating_sub(Rows::new(2))); let (status_line, messages) = status_line.split_at_row(Rows::new(1)); let line_number_width = Gutter::line_number_width(line_count); let (gutter_area, text) = content.split_at_column(Gutter::width(line_number_width)); Self { editor_dimensions, gutter: Gutter { area: gutter_area, line_number_width, }, text: TextArea::new(text), status_line, messages, } } fn resize(&mut self, line_count: usize, editor_dimensions: EditorDimensions) { let layout = Self::new(line_count, editor_dimensions); *self = Self { text: self.text.with_area(layout.text.into_area()), ..layout }; } fn max_text_width(&self) -> Option { NonZeroColumns::new(self.text.area().width()) } } #[derive(Debug, PartialEq, Eq)] struct Gutter { area: Rectangle, line_number_width: Columns, } impl Gutter { const DIAGNOSTIC_ICON: &str = "โ— "; const LINE_NUMBER_RIGHT_PADDING: Columns = Columns::new(1); fn line_number_width(line_count: usize) -> Columns { cmp::max(Columns::new(2), number_width(line_count)) } fn width(line_number_width: Columns) -> Columns { text_width(Self::DIAGNOSTIC_ICON) + line_number_width + Self::LINE_NUMBER_RIGHT_PADDING } } #[derive(Debug)] struct GutterRenderer<'gutter> { gutter: &'gutter Gutter, cursor_line: LineIndex, } impl GutterRenderer<'_> { /// Renders the gutter for the current visual line (derived from line index /// and wrap status) at the given `row`, relative to the top of the gutter. fn render( &self, row: Rows, wrapped: WrapOutcome, current_line: LineIndex, severity: Option, buffer: &mut Buffer, ) { let diagnostic_contents = match (wrapped, severity) { // we only display gutter contents on the first visual row of a // wrapped line (WrapOutcome::Wrapped, _) | (_, None) => { " ".repeat(text_width(Gutter::DIAGNOSTIC_ICON).value()) } (WrapOutcome::NotWrapped, Some(_)) => Gutter::DIAGNOSTIC_ICON.to_owned(), }; let line_number_contents = match wrapped { // we only display gutter contents on the first visual row of a // wrapped line WrapOutcome::Wrapped => { " ".repeat( self.gutter.line_number_width.value() + Gutter::LINE_NUMBER_RIGHT_PADDING.value(), ) } WrapOutcome::NotWrapped => { let line_number = if self.cursor_line == current_line { current_line + 1 } else { current_line.abs_diff(self.cursor_line) }; format!( "{line_number:>width$}{}", " ".repeat(Gutter::LINE_NUMBER_RIGHT_PADDING.value()), width = self.gutter.line_number_width.value(), ) } }; let gutter_style = if self.cursor_line == current_line { Style::GUTTER_SELECTED } else { Style::GUTTER }; let diagnostic_style = severity.map_or(gutter_style, |severity| { gutter_style.merge(Style::diagnostic_icon(severity)) }); let diagnostic_position = self.gutter.area.offset().row_offset(row); let line_number_position = diagnostic_position.col_offset(text_width(&diagnostic_contents)); buffer[diagnostic_position] .set_content(&diagnostic_contents) .set_style(diagnostic_style); buffer[line_number_position] .set_content(&line_number_contents) .set_style(gutter_style); } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Mode { Normal, Insert, Visual, } impl fmt::Display for Mode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", match *self { Self::Normal => "NORMAL", Self::Insert => "INSERT", Self::Visual => "VISUAL", }) } } #[derive(Debug)] struct HighlightCache { tokens: Vec, } impl HighlightCache { const fn new() -> Self { Self { tokens: Vec::new() } } /// Gets the start byte of the closest token that occurs before the given /// [`ByteIndex`]. This can be used as a start point to re-calculate the /// highlights for a section of the text. fn checkpoint_before(&self, index: ByteIndex) -> ByteIndex { // if the token cache isn't yet populated, we don't want to highlight // the whole text as this could be slow for extremely large // files and this method blocks the renderer. instead, we'll // just act as if `index` is a checkpoint and allow the // highlights to potentially be slightly off until the // token cache populates (shouldn't actually be noticeable to the user) if self.tokens.is_empty() { return index; } self.tokens .get( self.tokens .partition_point(|token| token.end() < index) .saturating_sub(1), ) .map_or(ByteIndex::new(0), Token::start) } } #[derive(Debug)] struct HighlightRequest { text: Rope, language: Language, } #[derive(Debug)] #[must_use] struct Transaction { edit: Option, selection: Selection, } impl Transaction { const fn new(edit: Option, selection: Selection) -> Self { Self { edit, selection } } } #[derive(Debug)] pub(crate) struct TextEdit { range: Range, replacement: String, } impl TextEdit { fn insert(at: ByteIndex, text: impl Into) -> Self { Self::replace(at..at, text) } fn delete(range: Range) -> Self { Self::replace(range, "") } fn replace(range: Range, text: impl Into) -> Self { assert!(range.start <= range.end, "range must be valid"); Self { range, replacement: text.into(), } } pub(crate) fn into_parts(self) -> (Range, String) { (self.range, self.replacement) } fn is_noop(&self) -> bool { self.range.is_empty() && self.replacement.is_empty() } } #[derive(Debug)] struct Diagnostics { /// Diagnostics with translated byte/line ranges. Sorted by start line /// index. entries: Vec, underlines: Vec, } impl Diagnostics { const fn new() -> Self { Self { entries: Vec::new(), underlines: Vec::new(), } } fn clear(&mut self) { self.entries.clear(); self.underlines.clear(); } fn publish_new( &mut self, diagnostics: Vec, text: RopeSlice<'_>, position_encoding: PositionEncoding, ) { let mut entries: Vec = diagnostics .into_iter() .filter_map(|diagnostic| { Diagnostic::new(diagnostic, position_encoding, text) .inspect_err(|err| log::warn!("invalid diagnostic: {err}")) .ok() }) .collect(); entries.sort_unstable_by_key(|diagnostic| diagnostic.line_range.start); self.entries = entries; self.underlines = Self::derive_underlines(&self.entries); } fn spans_from(&self, index: ByteIndex) -> impl Iterator { self.underlines[self .underlines .partition_point(|span| span.range.end <= index)..] .iter() } fn on_line(&self, line_index: LineIndex) -> impl Iterator { let partition = self .entries .partition_point(|diagnostic| diagnostic.line_range.start <= line_index); self.entries[..partition] .iter() .filter(move |diagnostic| diagnostic.line_range.contains(&line_index)) } fn line_severity(&self, line: LineIndex) -> Option { self.on_line(line) .max_by_key(|diagnostic| diagnostic.severity_priority()) .map(|diagnostic| diagnostic.severity) } fn derive_underlines(diagnostics: &[Diagnostic]) -> Vec { #[derive(Debug)] struct DiagnosticEvent { at: ByteIndex, kind: DiagnosticEventKind, severity: DiagnosticSeverity, } #[derive(Debug)] enum DiagnosticEventKind { Start, End, } #[derive(Debug)] struct SeverityCounts { error: usize, warning: usize, info: usize, hint: usize, } impl SeverityCounts { const fn increment(&mut self, severity: DiagnosticSeverity) { match severity { DiagnosticSeverity::Error => self.error += 1, DiagnosticSeverity::Warning => self.warning += 1, DiagnosticSeverity::Information => self.info += 1, DiagnosticSeverity::Hint => self.hint += 1, } } const fn decrement(&mut self, severity: DiagnosticSeverity) { match severity { DiagnosticSeverity::Error => self.error -= 1, DiagnosticSeverity::Warning => self.warning -= 1, DiagnosticSeverity::Information => self.info -= 1, DiagnosticSeverity::Hint => self.hint -= 1, } } const fn highest_severity(&self) -> Option { match (self.error, self.warning, self.info, self.hint) { (x, ..) if x > 0 => Some(DiagnosticSeverity::Error), (_, x, ..) if x > 0 => Some(DiagnosticSeverity::Warning), (_, _, x, ..) if x > 0 => Some(DiagnosticSeverity::Information), (_, _, _, x) if x > 0 => Some(DiagnosticSeverity::Hint), _ => None, } } } let mut events: Vec = diagnostics .iter() .flat_map(|diagnostic| { let start = diagnostic.byte_range.start; let end = diagnostic.byte_range.end; [ DiagnosticEvent { at: start, kind: DiagnosticEventKind::Start, severity: diagnostic.severity, }, DiagnosticEvent { // some diagnostics come back as an empty range, but we // still want to display an underline, and so we extend // it at: if start == end { start + 1 } else { end }, kind: DiagnosticEventKind::End, severity: diagnostic.severity, }, ] }) .collect(); let mut result: Vec = vec![]; let mut counts = SeverityCounts { error: 0, warning: 0, info: 0, hint: 0, }; events.sort_by_key(|event| event.at); let mut previous_at = None; let mut i = 0_usize; while i < events.len() { let event = &events[i]; if let Some(previous) = previous_at && let Some(severity) = counts.highest_severity() { if let Some(last) = result.last_mut() && severity == last.severity && last.range.end == previous { // we can extend the last range instead of pushing a new // span because it's the same severity // and there's no gap last.range.end = event.at; } else { result.push(DiagnosticSpan { range: previous..event.at, severity, }); } } while i < events.len() && events[i].at == event.at { match events[i].kind { DiagnosticEventKind::Start => { counts.increment(events[i].severity); } DiagnosticEventKind::End => { counts.decrement(events[i].severity); } } i += 1; } previous_at = Some(event.at); } debug_assert!( result.is_sorted_by_key(|span| span.range.end), "spans must be sorted" ); debug_assert!( result.windows(2).all( #[expect( clippy::missing_asserts_for_indexing, reason = "don't care about this in a debug assert" )] |pair| pair[0].range.end <= pair[1].range.start ), "diagnostic spans must not overlap" ); result } } #[derive(Debug)] pub(crate) struct Diagnostic { message: String, severity: DiagnosticSeverity, byte_range: Range, line_range: Range, } impl Diagnostic { fn new( diagnostic: gen_lsp_types::Diagnostic, position_encoding: PositionEncoding, text: RopeSlice<'_>, ) -> anyhow::Result { let byte_range = lsp_to_byte_range(diagnostic.range, position_encoding, text)?; let start_line = text.line_idx_containing_byte(byte_range.start); let end_line = if byte_range.is_empty() { start_line } else { text.line_idx_containing_byte(byte_range.end.saturating_sub(1)) }; Ok(Self { message: match diagnostic.message { Message::String(value) => value, // TODO: render markdown Message::MarkupContent(content) => content.value, }, severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::Error), byte_range, line_range: start_line..(end_line + 1), }) } pub(crate) fn message(&self) -> &str { &self.message } pub(crate) const fn severity(&self) -> DiagnosticSeverity { self.severity } const fn severity_priority(&self) -> u8 { match self.severity { DiagnosticSeverity::Hint => 0, DiagnosticSeverity::Information => 1, DiagnosticSeverity::Warning => 2, DiagnosticSeverity::Error => 3, } } } /// A diagnostic that will be displayed in the document (if it's part of the /// current viewport). Prioritises overlapping diagnostics by their severity. #[derive(Debug, Clone, PartialEq, Eq)] struct DiagnosticSpan { range: Range, severity: DiagnosticSeverity, } fn lsp_to_byte_range( range: gen_lsp_types::Range, position_encoding: PositionEncoding, text: RopeSlice<'_>, ) -> anyhow::Result> { let translate_position = |position: gen_lsp_types::Position| -> anyhow::Result { let line_index = LineIndex::try_from(position.line).context("line index is too large")?; let line = text .get_line_at(line_index) .context("invalid line index for this document")?; let character = usize::try_from(position.character).context("character offset is too large")?; let byte_offset = match position_encoding { PositionEncoding::UTF8 => character, // TODO: use non-panicking versions when is // done. PositionEncoding::UTF16 => line.utf16_to_byte_idx(character), PositionEncoding::UTF32 => line.char_to_byte_idx(character), }; Ok(text.line_start_byte(line_index) + byte_offset) }; let start = translate_position(range.start)?; let end = translate_position(range.end)?; anyhow::ensure!(start <= end, "diagnostic range is invalid: start > end"); anyhow::ensure!( end <= ByteIndex::new(text.len()), "diagnostic range is invalid: end > text.len()" ); Ok(start..end) } #[cfg(test)] mod tests { use std::io::Write as _; use crossterm::event::{ KeyCode, KeyEvent, }; use super::*; macro_rules! key_event { ($key:literal) => { KeyEvent::from(KeyCode::Char($key)) }; ($key:ident) => { KeyEvent::from(KeyCode::$key) }; } const TEST_DIMENSIONS: EditorDimensions = EditorDimensions::new(Dimensions::new(Columns::new(80), Rows::new(24))).unwrap(); struct TestCase<'text> { initial_text: &'text str, initial_cursor: usize, expected_initial_text_position: (usize, usize), keys: Vec, expected_text: &'text str, expected_cursor: usize, expected_text_position: (usize, usize), } impl TestCase<'_> { fn run(self) { let _ = color_eyre::install(); let mut document = doc(self.initial_text); document.set_cursor(self.initial_cursor.into()); assert_text_position( self.expected_initial_text_position, "initial position", &document, ); assert_char_boundary(&document); for event in self.keys { let _ = document.handle_key_event(event, &mut EventContext::new()); assert_char_boundary(&document); } assert_eq!( document.text.to_string(), self.expected_text, "text is incorrect" ); assert_eq!( document.cursor(), self.expected_cursor.into(), "cursor byte index is incorrect" ); assert_text_position(self.expected_text_position, "final position", &document); assert_char_boundary(&document); } } #[track_caller] fn assert_text_position(expected: (usize, usize), label: &str, document: &Document) { let actual = document.visual_cursor_position().unwrap(); let expected = Position::new(Columns::new(expected.0), Rows::new(expected.1)) .offset(document.layout.text.area().offset()); assert_eq!(actual, expected, "{label} did not match"); } #[track_caller] fn assert_char_boundary(doc: &Document) { assert!( doc.text.is_char_boundary(doc.cursor().value()), "cursor isn't a char boundary" ); } fn doc(contents: &str) -> Document { let mut temp_file = tempfile::NamedTempFile::new().unwrap(); write!(temp_file, "{contents}").unwrap(); Document::new(temp_file.path().to_path_buf(), TEST_DIMENSIONS).unwrap() } #[test] fn move_cursor_right() { TestCase { initial_text: "Test โš’๏ธ ๐Ÿ˜€ ", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('l'); 8], expected_text: "Test โš’๏ธ ๐Ÿ˜€ ", expected_cursor: 16, expected_text_position: (10, 0), } .run(); } #[test] fn move_cursor_right_from_end() { TestCase { initial_text: "Test", initial_cursor: 3, expected_initial_text_position: (3, 0), keys: vec![key_event!('l'); 1], expected_text: "Test", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn move_cursor_right_n() { TestCase { initial_text: "Test โš’๏ธ ๐Ÿ˜€ ", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('8'), key_event!('l')], expected_text: "Test โš’๏ธ ๐Ÿ˜€ ", expected_cursor: 16, expected_text_position: (10, 0), } .run(); } #[test] fn move_cursor_left() { TestCase { initial_text: "Test โš’๏ธ ๐Ÿ˜€ ", initial_cursor: 16, expected_initial_text_position: (10, 0), keys: vec![key_event!('h'); 1], expected_text: "Test โš’๏ธ ๐Ÿ˜€ ", expected_cursor: 12, expected_text_position: (8, 0), } .run(); } #[test] fn move_cursor_left_from_start() { TestCase { initial_text: "Test", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('h'); 1], expected_text: "Test", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_left_n() { TestCase { initial_text: "Test โš’๏ธ ๐Ÿ˜€ ", initial_cursor: 16, expected_initial_text_position: (10, 0), keys: vec![key_event!('4'), key_event!('h')], expected_text: "Test โš’๏ธ ๐Ÿ˜€ ", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn move_cursor_down() { TestCase { initial_text: "Test\nTest", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('j'); 1], expected_text: "Test\nTest", expected_cursor: 5, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_down_from_bottom() { TestCase { initial_text: "Test\nTest", initial_cursor: 5, expected_initial_text_position: (0, 1), keys: vec![key_event!('j'); 1], expected_text: "Test\nTest", expected_cursor: 5, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_down_from_bottom_trailing_newline() { TestCase { initial_text: "Test\nTest\n", initial_cursor: 5, expected_initial_text_position: (0, 1), keys: vec![key_event!('j'); 1], expected_text: "Test\nTest\n", expected_cursor: 5, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_down_wrapped() { TestCase { initial_text: &"a".repeat(200), initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('j')], expected_text: &"a".repeat(200), expected_cursor: 75, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_down_n() { TestCase { initial_text: "Test\nTest\nTest", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('2'), key_event!('j')], expected_text: "Test\nTest\nTest", expected_cursor: 12, expected_text_position: (2, 2), } .run(); } #[test] fn move_cursor_down_n_multiple_digits() { TestCase { initial_text: &"Test\n".repeat(15), initial_cursor: 3, expected_initial_text_position: (3, 0), keys: vec![key_event!('1'), key_event!('2'), key_event!('j')], expected_text: &"Test\n".repeat(15), expected_cursor: 63, expected_text_position: (3, 12), } .run(); } #[test] fn move_cursor_up() { TestCase { initial_text: "Test\nTest", initial_cursor: 5, expected_initial_text_position: (0, 1), keys: vec![key_event!('k'); 1], expected_text: "Test\nTest", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_up_from_top() { TestCase { initial_text: "Test\nTest", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('k'); 1], expected_text: "Test\nTest", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn move_cursor_up_wrapped() { TestCase { initial_text: &"a".repeat(200), initial_cursor: 75, expected_initial_text_position: (0, 1), keys: vec![key_event!('k')], expected_text: &"a".repeat(200), expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_up_n() { TestCase { initial_text: "Test\nTest\nTest", initial_cursor: 11, expected_initial_text_position: (1, 2), keys: vec![key_event!('2'), key_event!('k')], expected_text: "Test\nTest\nTest", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn maintain_column_up_multiple_lines() { TestCase { initial_text: "Long line\nShort\nLong line", initial_cursor: 24, expected_initial_text_position: (8, 2), keys: vec![key_event!('k'); 1], expected_text: "Long line\nShort\nLong line", expected_cursor: 15, expected_text_position: (5, 1), } .run(); } #[test] fn scroll_down() { let text = "Test\n".repeat(30); TestCase { initial_text: &text, initial_cursor: 21 * 5, expected_initial_text_position: (0, 21), keys: vec![key_event!('j'); 1], expected_text: &text, expected_cursor: 22 * 5, // visual position stays the same because we scrolled down, keeping // the cursor on the final line expected_text_position: (0, 21), } .run(); } #[test] fn scroll_down_wrapped() { let line = "a".repeat(200); let text = format!("{line}\n").repeat(100); TestCase { initial_text: &text, initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('G'); 1], expected_text: &text, expected_cursor: (200 * 99) + 99, expected_text_position: (0, 21), } .run(); } #[test] fn scroll_up() { let text = "Test\n".repeat(30); TestCase { initial_text: &text, initial_cursor: 1, expected_initial_text_position: (1, 0), keys: [vec![key_event!('j'); 26], vec![key_event!('k'); 25]].concat(), expected_text: &text, expected_cursor: 6, // visual position stays the same because we scrolled up, keeping // the cursor on the first line expected_text_position: (1, 0), } .run(); } #[test] fn center_cursor_vertically_normal_mode() { let text = "Test\n".repeat(40); TestCase { initial_text: &text, initial_cursor: 20 * 5, expected_initial_text_position: (0, 20), keys: vec![key_event!('z'), key_event!('z')], expected_text: &text, expected_cursor: 20 * 5, expected_text_position: (0, 11), } .run(); } #[test] fn center_cursor_vertically_visual_mode() { let text = "Test\n".repeat(40); TestCase { initial_text: &text, initial_cursor: 20 * 5, expected_initial_text_position: (0, 20), keys: vec![key_event!('v'), key_event!('z'), key_event!('z')], expected_text: &text, expected_cursor: 20 * 5, expected_text_position: (0, 11), } .run(); } #[test] fn maintain_column_down() { TestCase { initial_text: "Long line\nShort\nLong line", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![key_event!('j'); 2], expected_text: "Long line\nShort\nLong line", expected_cursor: 24, expected_text_position: (8, 2), } .run(); } #[test] fn maintain_column_up() { TestCase { initial_text: "Long line\nShort\nLong line", initial_cursor: 24, expected_initial_text_position: (8, 2), keys: vec![key_event!('k'); 2], expected_text: "Long line\nShort\nLong line", expected_cursor: 8, expected_text_position: (8, 0), } .run(); } #[test] fn move_cursor_next_word_start() { TestCase { initial_text: "Test text", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "Test text", expected_cursor: 5, expected_text_position: (5, 0), } .run(); } #[test] fn move_cursor_next_word_start_emoji() { TestCase { initial_text: "๐Ÿ˜€ hello", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "๐Ÿ˜€ hello", expected_cursor: 5, expected_text_position: (3, 0), } .run(); } #[test] fn move_cursor_next_word_start_multiple() { TestCase { initial_text: "hello world test", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w'); 3], expected_text: "hello world test", expected_cursor: 15, expected_text_position: (15, 0), } .run(); } #[test] fn move_cursor_next_word_start_mid_word() { TestCase { initial_text: "hello world", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('w')], expected_text: "hello world", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_next_word_start_at_space() { TestCase { initial_text: "hello world", initial_cursor: 5, expected_initial_text_position: (5, 0), keys: vec![key_event!('w')], expected_text: "hello world", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_next_word_start_end_of_file() { TestCase { initial_text: "hello world", initial_cursor: 6, expected_initial_text_position: (6, 0), keys: vec![key_event!('w')], expected_text: "hello world", expected_cursor: 10, expected_text_position: (10, 0), } .run(); } #[test] fn move_cursor_next_word_start_punctuation_to_word() { TestCase { initial_text: "hello, world", initial_cursor: 5, expected_initial_text_position: (5, 0), keys: vec![key_event!('w')], expected_text: "hello, world", expected_cursor: 7, expected_text_position: (7, 0), } .run(); } #[test] fn move_cursor_next_word_start_multiple_spaces() { TestCase { initial_text: "hello world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "hello world", expected_cursor: 9, expected_text_position: (9, 0), } .run(); } #[test] fn move_cursor_next_word_start_with_numbers() { TestCase { initial_text: "test123 abc456", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "test123 abc456", expected_cursor: 8, expected_text_position: (8, 0), } .run(); } #[test] fn move_cursor_next_word_start_ignore_underscore() { TestCase { initial_text: "hello_world test", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "hello_world test", expected_cursor: 12, expected_text_position: (12, 0), } .run(); } #[test] fn move_cursor_next_word_start_across_lines() { TestCase { initial_text: "hello\nworld", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "hello\nworld", expected_cursor: 6, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_next_word_start_empty_file() { TestCase { initial_text: "", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('w')], expected_text: "", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_next_word_start_n() { TestCase { initial_text: "hello world test", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('3'), key_event!('w')], expected_text: "hello world test", expected_cursor: 15, expected_text_position: (15, 0), } .run(); } #[test] fn move_cursor_prev_word_start() { TestCase { initial_text: "Test text", initial_cursor: 5, expected_initial_text_position: (5, 0), keys: vec![key_event!('b')], expected_text: "Test text", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_emoji() { TestCase { initial_text: "๐Ÿ˜€ hello", initial_cursor: 5, expected_initial_text_position: (3, 0), keys: vec![key_event!('b')], expected_text: "๐Ÿ˜€ hello", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_multiple() { TestCase { initial_text: "hello world test", initial_cursor: 15, expected_initial_text_position: (15, 0), keys: vec![key_event!('b'); 2], expected_text: "hello world test", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_prev_word_start_mid_word() { TestCase { initial_text: "hello world", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![key_event!('b')], expected_text: "hello world", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_prev_word_start_at_space() { TestCase { initial_text: "hello world ", initial_cursor: 11, expected_initial_text_position: (11, 0), keys: vec![key_event!('b')], expected_text: "hello world ", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_prev_word_start_start_of_file() { TestCase { initial_text: "hello world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('b')], expected_text: "hello world", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_punctuation_to_word() { TestCase { initial_text: "hello world ,", initial_cursor: 13, expected_initial_text_position: (13, 0), keys: vec![key_event!('b')], expected_text: "hello world ,", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_prev_word_start_with_numbers() { TestCase { initial_text: "test123 abc456", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![key_event!('b')], expected_text: "test123 abc456", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_ignore_underscore() { TestCase { initial_text: "hello_world test", initial_cursor: 12, expected_initial_text_position: (12, 0), keys: vec![key_event!('b')], expected_text: "hello_world test", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_across_lines() { TestCase { initial_text: "hello\nworld", initial_cursor: 6, expected_initial_text_position: (0, 1), keys: vec![key_event!('b')], expected_text: "hello\nworld", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_empty_file() { TestCase { initial_text: "", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('b')], expected_text: "", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_word_start_n() { TestCase { initial_text: "hello world test", initial_cursor: 15, expected_initial_text_position: (15, 0), keys: vec![key_event!('2'), key_event!('b')], expected_text: "hello world test", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_prev_word_start_varying_char_lengths() { TestCase { initial_text: "-ใ“ใ‚“ใซใกใฏ", initial_cursor: 13, expected_initial_text_position: (9, 0), keys: vec![key_event!('b')], expected_text: "-ใ“ใ‚“ใซใกใฏ", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn insert() { TestCase { initial_text: "lo", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('i'), key_event!('H'), key_event!('e'), key_event!('l'), ], expected_text: "Hello", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn delete_simple() { TestCase { initial_text: "Hello!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('i'), key_event!(Backspace)], expected_text: "Hllo!", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn delete_emoji() { TestCase { initial_text: "Hello โš’๏ธ !!", initial_cursor: 12, expected_initial_text_position: (8, 0), keys: vec![key_event!('i'), key_event!(Backspace)], expected_text: "Hello !!", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn delete_and_insert() { TestCase { initial_text: "Hello!!", initial_cursor: 6, expected_initial_text_position: (6, 0), keys: vec![ key_event!('i'), key_event!(Backspace), key_event!(Backspace), key_event!(Backspace), key_event!(Backspace), key_event!('y'), ], expected_text: "Hey!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn normal_mode() { TestCase { initial_text: "Hello!", initial_cursor: 5, expected_initial_text_position: (5, 0), keys: vec![ key_event!('i'), key_event!('!'), key_event!(Esc), key_event!('h'), key_event!('h'), ], expected_text: "Hello!!", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn insert_newline() { TestCase { initial_text: "Hello!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('i'), key_event!(Enter)], expected_text: "He\nllo!", expected_cursor: 3, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_line_end() { TestCase { initial_text: "Hello!!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('$')], expected_text: "Hello!!", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_line_end_with_lf() { TestCase { initial_text: "Hello!!\nNext line", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('$')], expected_text: "Hello!!\nNext line", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_line_end_with_crlf() { TestCase { initial_text: "Hello!!\r\nNext line", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('$')], expected_text: "Hello!!\r\nNext line", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn move_cursor_line_start() { TestCase { initial_text: "Hello!!", initial_cursor: 3, expected_initial_text_position: (3, 0), keys: vec![key_event!('0')], expected_text: "Hello!!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_first_non_blank() { TestCase { initial_text: " Hello!!", initial_cursor: 7, expected_initial_text_position: (7, 0), keys: vec![key_event!('^')], expected_text: " Hello!!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn move_cursor_first_non_blank_empty() { TestCase { initial_text: "\nHello", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('^')], expected_text: "\nHello", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_first_non_blank_grapheme_with_whitespace() { TestCase { // `" \u{1F3FB}"` is a single grapheme. the whitespace is part of it initial_text: " \u{1F3FB}", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('^')], expected_text: " \u{1F3FB}", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_next_paragraph() { TestCase { initial_text: "hello\nworld\n\nparagraph", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('}')], expected_text: "hello\nworld\n\nparagraph", expected_cursor: 12, expected_text_position: (0, 2), } .run(); } #[test] fn move_cursor_next_paragraph_consecutive_empty_lines() { TestCase { initial_text: "hello\nworld\n\n\n\n\nparagraph\n\n", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('}'); 2], expected_text: "hello\nworld\n\n\n\n\nparagraph\n\n", expected_cursor: 26, expected_text_position: (0, 7), } .run(); } #[test] fn move_cursor_next_paragraph_n() { TestCase { initial_text: "hello\nworld\n\n\n\n\nparagraph\n\n", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('2'), key_event!('}')], expected_text: "hello\nworld\n\n\n\n\nparagraph\n\n", expected_cursor: 26, expected_text_position: (0, 7), } .run(); } #[test] fn move_cursor_prev_paragraph() { TestCase { initial_text: "hello\n\nworld\n\n", initial_cursor: 13, expected_initial_text_position: (0, 3), keys: vec![key_event!('{')], expected_text: "hello\n\nworld\n\n", expected_cursor: 6, expected_text_position: (0, 1), } .run(); } #[test] fn move_cursor_prev_paragraph_consecutive_empty_lines() { TestCase { initial_text: "hello\nworld\n\n\n\n\nparagraph\n\n", initial_cursor: 26, expected_initial_text_position: (0, 7), keys: vec![key_event!('{'); 2], expected_text: "hello\nworld\n\n\n\n\nparagraph\n\n", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn move_cursor_prev_paragraph_n() { TestCase { initial_text: "hello\nworld\n\n\n\n\nparagraph\n\n", initial_cursor: 26, expected_initial_text_position: (0, 7), keys: vec![key_event!('2'), key_event!('{')], expected_text: "hello\nworld\n\n\n\n\nparagraph\n\n", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn go_to_nth_or_last_line_no_n() { TestCase { initial_text: "hello\nworld\n", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('G')], expected_text: "hello\nworld\n", expected_cursor: 6, expected_text_position: (0, 1), } .run(); } #[test] fn go_to_nth_or_last_line_with_n() { TestCase { initial_text: "hello\nworld\nyo\n", initial_cursor: 6, expected_initial_text_position: (0, 1), keys: vec![key_event!('1'), key_event!('G')], expected_text: "hello\nworld\nyo\n", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn go_to_last_line() { TestCase { initial_text: "hello\nworld\n", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('g'), key_event!('e')], expected_text: "hello\nworld\n", expected_cursor: 6, expected_text_position: (0, 1), } .run(); } #[test] fn go_to_nth_or_first_line_no_n() { TestCase { initial_text: "hello\nworld\n", initial_cursor: 6, expected_initial_text_position: (0, 1), keys: vec![key_event!('g'), key_event!('g')], expected_text: "hello\nworld\n", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn go_to_nth_or_first_line_with_n() { TestCase { initial_text: "hello\nworld\nyo\n", initial_cursor: 6, expected_initial_text_position: (0, 1), keys: vec![key_event!('3'), key_event!('g'), key_event!('g')], expected_text: "hello\nworld\nyo\n", expected_cursor: 12, expected_text_position: (0, 2), } .run(); } #[test] fn go_to_nth_or_first_line_with_middle_n() { TestCase { initial_text: "one\ntwo\nthree\nfour", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('2'), key_event!('g'), key_event!('g')], expected_text: "one\ntwo\nthree\nfour", expected_cursor: 4, expected_text_position: (0, 1), } .run(); } #[test] fn delete_word_from_start() { TestCase { initial_text: "Hello world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "world", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_from_middle() { TestCase { initial_text: "Hello world", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "Heworld", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn delete_word_stop_at_hyphen() { TestCase { initial_text: "Hello-world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "-world", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_leading_whitespace() { TestCase { initial_text: " Hello-world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "Hello-world", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_n() { TestCase { initial_text: "Hello world several words", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('2'), key_event!('d'), key_event!('w')], expected_text: "several words", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_eof() { TestCase { initial_text: "0", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_eof_long() { TestCase { initial_text: "Hello", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_word_eof_clamp() { TestCase { initial_text: "รฉ0", initial_cursor: 2, expected_initial_text_position: (1, 0), keys: vec![key_event!('d'), key_event!('w')], expected_text: "รฉ", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn change_word_from_start() { TestCase { initial_text: "Hello world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('w'), key_event!('h'), key_event!('i'), ], expected_text: "hiworld", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_word_from_middle() { TestCase { initial_text: "Hello world", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('c'), key_event!('w'), key_event!('h'), key_event!('i'), ], expected_text: "Hehiworld", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn change_word_stop_at_hyphen() { TestCase { initial_text: "Hello-world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('w'), key_event!('h'), key_event!('i'), ], expected_text: "hi-world", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_word_leading_whitespace() { TestCase { initial_text: " Hello-world", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('w'), key_event!('h'), key_event!('i'), ], expected_text: "hiHello-world", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_word_n() { TestCase { initial_text: "Hello world several words", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('2'), key_event!('c'), key_event!('w'), key_event!('H'), key_event!('i'), key_event!(' '), ], expected_text: "Hi several words", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn delete_to_line_end() { TestCase { initial_text: "Hello there!\nNext line", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('d'), key_event!('$')], expected_text: "He\nNext line", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_to_line_end() { TestCase { initial_text: "Hello there!\nNext line", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('c'), key_event!('$'), key_event!('y'), key_event!('!'), ], expected_text: "Hey!\nNext line", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn delete_to_line_start() { TestCase { initial_text: "Hello there!\n Next line!", initial_cursor: 26, expected_initial_text_position: (13, 1), keys: vec![key_event!('d'), key_event!('0')], expected_text: "Hello there!\n!", expected_cursor: 13, expected_text_position: (0, 1), } .run(); } #[test] fn delete_to_line_first_non_blank() { TestCase { initial_text: "Hello there!\n Next line!", initial_cursor: 26, expected_initial_text_position: (13, 1), keys: vec![key_event!('d'), key_event!('^')], expected_text: "Hello there!\n !", expected_cursor: 18, expected_text_position: (5, 1), } .run(); } #[test] fn delete_to_line_first_non_blank_forwards() { TestCase { initial_text: " Hello!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('^')], expected_text: "Hello!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_to_line_first_non_blank_empty_line() { TestCase { initial_text: "\nHello!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('^')], expected_text: "\nHello!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_line() { TestCase { initial_text: "Hello there!\nNext line!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![key_event!('d'), key_event!('d')], expected_text: "Next line!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_line_n() { TestCase { initial_text: "Hello there!\nNext line!\nAnd another line!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![key_event!('2'), key_event!('d'), key_event!('d')], expected_text: "And another line!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_whole_word() { TestCase { initial_text: "Hello there!!!", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![key_event!('d'), key_event!('i'), key_event!('w')], expected_text: "Hello !!!", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn delete_whole_word_from_start() { TestCase { initial_text: "Hello there!!!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('i'), key_event!('w')], expected_text: " there!!!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_whole_word_from_end() { TestCase { initial_text: "Hello there!!!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![key_event!('d'), key_event!('i'), key_event!('w')], expected_text: " there!!!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_whole_word_empty() { TestCase { initial_text: "", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('d'), key_event!('i'), key_event!('w')], expected_text: "", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_to_prev_word_start() { TestCase { initial_text: "Hello there!!!", initial_cursor: 6, expected_initial_text_position: (6, 0), keys: vec![key_event!('d'), key_event!('b')], expected_text: "there!!!", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_to_prev_word_start_n() { TestCase { initial_text: "Hello there words words words!!!", initial_cursor: 26, expected_initial_text_position: (26, 0), keys: vec![key_event!('4'), key_event!('d'), key_event!('b')], expected_text: "Hello rds!!!", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn delete_to_prev_word_start_varying_char_lengths() { TestCase { initial_text: "-ใ“ใ‚“ใซใกใฏ", initial_cursor: 13, expected_initial_text_position: (9, 0), keys: vec![key_event!('d'), key_event!('b')], expected_text: "-ใฏ", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn append_text() { TestCase { initial_text: "Hello", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('a'), key_event!('y'), key_event!('y')], expected_text: "Heyyllo", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn append_text_eof_no_newline() { TestCase { initial_text: "abc", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('a'), key_event!('X'), key_event!('Y')], expected_text: "abcXY", expected_cursor: 5, expected_text_position: (5, 0), } .run(); } #[test] fn append_text_end_of_line_no_newline() { TestCase { initial_text: "Hello", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('A'), key_event!('!'), key_event!('!')], expected_text: "Hello!!\n", expected_cursor: 7, expected_text_position: (7, 0), } .run(); } #[test] fn append_text_end_of_line_with_newline() { TestCase { initial_text: "Hello\n", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('A'), key_event!('!'), key_event!('!')], expected_text: "Hello!!\n", expected_cursor: 7, expected_text_position: (7, 0), } .run(); } #[test] fn move_cursor_word_end() { TestCase { initial_text: "Hello__123: there", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('e')], expected_text: "Hello__123: there", expected_cursor: 9, expected_text_position: (9, 0), } .run(); } #[test] fn move_cursor_word_end_n() { TestCase { initial_text: "Hello__123: there words words words", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('4'), key_event!('e')], expected_text: "Hello__123: there words words words", expected_cursor: 22, expected_text_position: (22, 0), } .run(); } #[test] fn delete_to_word_end() { TestCase { initial_text: "Hello there", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('d'), key_event!('e')], expected_text: "He there", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn delete_to_word_end_n() { TestCase { initial_text: "Hello there there there there there", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('4'), key_event!('d'), key_event!('e')], expected_text: "He there there", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_to_line_start() { TestCase { initial_text: "Hello there!\n Next line!", initial_cursor: 26, expected_initial_text_position: (13, 1), keys: vec![ key_event!('c'), key_event!('0'), key_event!('y'), key_event!('o'), key_event!('!'), ], expected_text: "Hello there!\nyo!!", expected_cursor: 16, expected_text_position: (3, 1), } .run(); } #[test] fn change_to_line_first_non_blank() { TestCase { initial_text: "Hello there!\n Next line!", initial_cursor: 26, expected_initial_text_position: (13, 1), keys: vec![ key_event!('c'), key_event!('^'), key_event!('y'), key_event!('o'), key_event!('!'), ], expected_text: "Hello there!\n yo!!", expected_cursor: 21, expected_text_position: (8, 1), } .run(); } #[test] fn change_to_line_first_non_blank_forwards() { TestCase { initial_text: " Hello!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('^'), key_event!('h'), key_event!('i'), ], expected_text: "hiHello!", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_to_line_first_non_blank_empty_line() { TestCase { initial_text: "\nHello!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('^'), key_event!('h'), key_event!('i'), ], expected_text: "hi\nHello!", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn change_line() { TestCase { initial_text: "Hello there!\nNext line!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![ key_event!('c'), key_event!('c'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey\nNext line!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_line_no_newline() { TestCase { initial_text: "Hello there!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![ key_event!('c'), key_event!('c'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey\n", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_line_n() { TestCase { initial_text: "Hello there!\nNext line!\nAnother line!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![ key_event!('2'), key_event!('c'), key_event!('c'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey\nAnother line!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_whole_word() { TestCase { initial_text: "Hello there!!!", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![ key_event!('c'), key_event!('i'), key_event!('w'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hello Hey!!!", expected_cursor: 9, expected_text_position: (9, 0), } .run(); } #[test] fn change_whole_word_from_start() { TestCase { initial_text: "Hello there!!!", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![ key_event!('c'), key_event!('i'), key_event!('w'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey there!!!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_whole_word_from_end() { TestCase { initial_text: "Hello there!!!", initial_cursor: 4, expected_initial_text_position: (4, 0), keys: vec![ key_event!('c'), key_event!('i'), key_event!('w'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey there!!!", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_to_prev_word_start() { TestCase { initial_text: "Hello there!!!", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![key_event!('c'), key_event!('b'), key_event!('H')], expected_text: "Hello Here!!!", expected_cursor: 7, expected_text_position: (7, 0), } .run(); } #[test] fn change_to_prev_word_start_from_word_start() { TestCase { initial_text: "Hello there!!!", initial_cursor: 6, expected_initial_text_position: (6, 0), keys: vec![ key_event!('c'), key_event!('b'), key_event!('H'), key_event!('e'), key_event!('y'), key_event!(' '), ], expected_text: "Hey there!!!", expected_cursor: 4, expected_text_position: (4, 0), } .run(); } #[test] fn change_to_prev_word_start_n() { TestCase { initial_text: "Hello there!!!", initial_cursor: 8, expected_initial_text_position: (8, 0), keys: vec![ key_event!('2'), key_event!('c'), key_event!('b'), key_event!('H'), ], expected_text: "Here!!!", expected_cursor: 1, expected_text_position: (1, 0), } .run(); } #[test] fn change_to_prev_word_start_varying_char_lengths() { TestCase { initial_text: "-ใ“ใ‚“ใซใกใฏ", initial_cursor: 13, expected_initial_text_position: (9, 0), keys: vec![ key_event!('c'), key_event!('b'), key_event!('h'), key_event!('i'), ], expected_text: "-hiใฏ", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_to_word_end() { TestCase { initial_text: "Hello there", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('c'), key_event!('e'), key_event!('y')], expected_text: "Hey there", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn change_to_word_end_n() { TestCase { initial_text: "Hello there words words", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('3'), key_event!('c'), key_event!('e'), key_event!('y'), ], expected_text: "Hey words", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn visual_mode_delete() { TestCase { initial_text: "Hello there\nAnother line!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('v'), key_event!('j'), key_event!('l'), key_event!('d'), ], expected_text: "Heher line!", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn visual_mode_change() { TestCase { initial_text: "Hello there\nAnother line!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('v'), key_event!('j'), key_event!('l'), key_event!('c'), key_event!('y'), key_event!(Enter), key_event!('a'), key_event!('n'), key_event!('o'), key_event!('t'), ], expected_text: "Hey\nanother line!", expected_cursor: 8, expected_text_position: (4, 1), } .run(); } #[test] fn reverse_selection() { TestCase { initial_text: "Hello there\nAnother line!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('v'), key_event!('j'), key_event!('l'), key_event!('o'), ], expected_text: "Hello there\nAnother line!", expected_cursor: 2, expected_text_position: (2, 0), } .run(); } #[test] fn reverse_selection_twice() { TestCase { initial_text: "Hello there\nAnother line!", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('v'), key_event!('j'), key_event!('l'), key_event!('o'), key_event!('o'), ], expected_text: "Hello there\nAnother line!", expected_cursor: 15, expected_text_position: (3, 1), } .run(); } #[test] fn open_new_line() { TestCase { initial_text: "Hello there\nAnother line!", initial_cursor: 15, expected_initial_text_position: (3, 1), keys: vec![ key_event!('o'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hello there\nAnother line!\nHey\n", expected_cursor: 29, expected_text_position: (3, 2), } .run(); } #[test] fn open_new_line_middle() { TestCase { initial_text: "Hello there\nAnother line!\nAgain a line :)", initial_cursor: 15, expected_initial_text_position: (3, 1), keys: vec![ key_event!('o'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hello there\nAnother line!\nHey\nAgain a line :)", expected_cursor: 29, expected_text_position: (3, 2), } .run(); } #[test] fn open_new_line_above() { TestCase { initial_text: "Hello there\nAnother line!\nAgain a line :)", initial_cursor: 15, expected_initial_text_position: (3, 1), keys: vec![ key_event!('O'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hello there\nHey\nAnother line!\nAgain a line :)", expected_cursor: 15, expected_text_position: (3, 1), } .run(); } #[test] fn open_new_line_above_top() { TestCase { initial_text: "Hello there\nAnother line!\nAgain a line :)", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('O'), key_event!('H'), key_event!('e'), key_event!('y'), ], expected_text: "Hey\nHello there\nAnother line!\nAgain a line :)", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn select_current_word() { TestCase { initial_text: "Hello there", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![ key_event!('v'), key_event!('i'), key_event!('w'), key_event!('d'), ], expected_text: " there", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_down() { TestCase { initial_text: "Hello there\nAnother line\n And another", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('d'), key_event!('j')], expected_text: " And another", expected_cursor: 5, expected_text_position: (5, 0), } .run(); } #[test] fn delete_down_n() { TestCase { initial_text: "Hello there\nAnother line\n And another\nAnd one more", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('2'), key_event!('d'), key_event!('j')], expected_text: "And one more", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_up() { TestCase { initial_text: "Hello there\nAnother line\nAnd another", initial_cursor: 27, expected_initial_text_position: (2, 2), keys: vec![key_event!('d'), key_event!('k')], expected_text: "Hello there\n", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn delete_up_n() { TestCase { initial_text: "Hello there\nAnother line\nAnd another\nAnd one more", initial_cursor: 27, expected_initial_text_position: (2, 2), keys: vec![key_event!('2'), key_event!('d'), key_event!('k')], expected_text: "And one more", expected_cursor: 0, expected_text_position: (0, 0), } .run(); } #[test] fn clear_key_sequence_with_esc() { TestCase { initial_text: "Hello there\nAnother line\nAnd another\nAnd one more", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('2'), key_event!(Esc), key_event!('j')], expected_text: "Hello there\nAnother line\nAnd another\nAnd one more", expected_cursor: 12, expected_text_position: (0, 1), } .run(); } #[test] fn match_pairs_braces() { TestCase { initial_text: "{Hello }", initial_cursor: 0, expected_initial_text_position: (0, 0), keys: vec![key_event!('%')], expected_text: "{Hello }", expected_cursor: 7, expected_text_position: (7, 0), } .run(); } #[test] fn match_pairs_brackets() { TestCase { initial_text: "H[ello]", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('%')], expected_text: "H[ello]", expected_cursor: 6, expected_text_position: (6, 0), } .run(); } #[test] fn match_pairs_parens() { TestCase { initial_text: "He()llo", initial_cursor: 2, expected_initial_text_position: (2, 0), keys: vec![key_event!('%')], expected_text: "He()llo", expected_cursor: 3, expected_text_position: (3, 0), } .run(); } #[test] fn match_pairs_after_line_end() { TestCase { initial_text: "hello {\nworld } test", initial_cursor: 1, expected_initial_text_position: (1, 0), keys: vec![key_event!('$'), key_event!('%')], expected_text: "hello {\nworld } test", expected_cursor: 14, expected_text_position: (6, 1), } .run(); } } #[cfg(test)] mod diagnostics_tests { use std::io::Write as _; use super::*; use crate::{ buffer::Cell, style::StyleAttributes, }; const TEST_DIMENSIONS: EditorDimensions = EditorDimensions::new(Dimensions::new(Columns::new(80), Rows::new(24))).unwrap(); fn doc(contents: &str) -> Document { let mut temp_file = tempfile::NamedTempFile::new().unwrap(); write!(temp_file, "{contents}").unwrap(); Document::new(temp_file.path().to_path_buf(), TEST_DIMENSIONS).unwrap() } #[derive(Debug, Clone)] struct TestDiagnostic { start: (u32, u32), end: (u32, u32), severity: DiagnosticSeverity, } fn doc_with_diagnostics(contents: &str, diagnostics: &[TestDiagnostic]) -> Document { let mut document = doc(contents); document.publish_diagnostics( PublishDiagnosticsParams { uri: document.lsp_id().url().clone(), version: None, diagnostics: diagnostics .iter() .map(|diagnostic| { gen_lsp_types::Diagnostic { range: gen_lsp_types::Range { start: gen_lsp_types::Position { line: diagnostic.start.0, character: diagnostic.start.1, }, end: gen_lsp_types::Position { line: diagnostic.end.0, character: diagnostic.end.1, }, }, severity: Some(diagnostic.severity), ..Default::default() } }) .collect(), }, PositionEncoding::UTF8, ); document } #[test] fn underline_rendering() { let diagnostics = vec![ TestDiagnostic { start: (0, 1), end: (0, 5), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (0, 2), end: (0, 4), severity: DiagnosticSeverity::Error, }, ]; let mut reversed_diagnostics = diagnostics.clone(); reversed_diagnostics.reverse(); for input in [diagnostics, reversed_diagnostics] { let doc_text = "hello, world!"; let mut document = doc_with_diagnostics(doc_text, &input); let mut buffer = Buffer::new(TEST_DIMENSIONS.get()); document.render(&mut buffer); let cell_at_column = |column: usize| -> &Cell { &buffer[Position::new(Columns::new(column), Rows::new(0)) .offset(document.layout.text.area().offset())] }; let assert_severity = |column: usize, severity: DiagnosticSeverity| { assert!( cell_at_column(column) .attributes() .contains(StyleAttributes::Undercurled) ); assert_eq!( cell_at_column(column).underline_color(), Style::diagnostic(severity).underline_color().unwrap() ); }; let assert_no_severity = |column: usize| { assert!( !cell_at_column(column) .attributes() .contains(StyleAttributes::Undercurled) ); }; assert_no_severity(0); assert_severity(1, DiagnosticSeverity::Warning); assert_severity(2, DiagnosticSeverity::Error); assert_severity(3, DiagnosticSeverity::Error); assert_severity(4, DiagnosticSeverity::Warning); for col in 5..doc_text.len() { assert_no_severity(col); } } } #[test] fn underline_severity_priority() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 1), end: (0, 10), severity: DiagnosticSeverity::Hint, }, TestDiagnostic { start: (0, 3), end: (0, 5), severity: DiagnosticSeverity::Error, }, ]); assert_eq!(document.diagnostics.underlines, vec![ DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(3), severity: DiagnosticSeverity::Hint, }, DiagnosticSpan { range: ByteIndex::new(3)..ByteIndex::new(5), severity: DiagnosticSeverity::Error, }, DiagnosticSpan { range: ByteIndex::new(5)..ByteIndex::new(10), severity: DiagnosticSeverity::Hint, }, ]); } #[test] fn underline_severity_priority_input_order_does_not_matter() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 3), end: (0, 5), severity: DiagnosticSeverity::Error, }, TestDiagnostic { start: (0, 1), end: (0, 10), severity: DiagnosticSeverity::Hint, }, ]); assert_eq!(document.diagnostics.underlines, vec![ DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(3), severity: DiagnosticSeverity::Hint, }, DiagnosticSpan { range: ByteIndex::new(3)..ByteIndex::new(5), severity: DiagnosticSeverity::Error, }, DiagnosticSpan { range: ByteIndex::new(5)..ByteIndex::new(10), severity: DiagnosticSeverity::Hint, }, ]); } #[test] fn underline_coalesce() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 1), end: (0, 6), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (0, 3), end: (0, 5), severity: DiagnosticSeverity::Warning, }, ]); assert_eq!(document.diagnostics.underlines, vec![DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(6), severity: DiagnosticSeverity::Warning, },]); } #[test] fn underline_coalesce_adjacent_start_and_end() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 1), end: (0, 3), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (0, 3), end: (0, 5), severity: DiagnosticSeverity::Warning, }, ]); assert_eq!(document.diagnostics.underlines, vec![DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(5), severity: DiagnosticSeverity::Warning, }]); } #[test] fn underline_no_coalesce_if_gap() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 1), end: (0, 3), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (0, 4), end: (0, 5), severity: DiagnosticSeverity::Warning, }, ]); assert_eq!(document.diagnostics.underlines, vec![ DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(3), severity: DiagnosticSeverity::Warning, }, DiagnosticSpan { range: ByteIndex::new(4)..ByteIndex::new(5), severity: DiagnosticSeverity::Warning, }, ]); } #[test] fn underline_empty_range() { let document = doc_with_diagnostics("hello, world!", &[TestDiagnostic { start: (0, 1), end: (0, 1), severity: DiagnosticSeverity::Warning, }]); assert_eq!(document.diagnostics.underlines, vec![DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(2), severity: DiagnosticSeverity::Warning, },]); } #[test] fn underline_high_priority_empty_range() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 0), end: (0, 4), severity: DiagnosticSeverity::Hint, }, TestDiagnostic { start: (0, 1), end: (0, 1), severity: DiagnosticSeverity::Error, }, ]); assert_eq!(document.diagnostics.underlines, vec![ DiagnosticSpan { range: ByteIndex::new(0)..ByteIndex::new(1), severity: DiagnosticSeverity::Hint, }, DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(2), severity: DiagnosticSeverity::Error, }, DiagnosticSpan { range: ByteIndex::new(2)..ByteIndex::new(4), severity: DiagnosticSeverity::Hint, }, ]); } #[test] fn underline_low_priority_empty_range() { let document = doc_with_diagnostics("hello, world!", &[ TestDiagnostic { start: (0, 0), end: (0, 4), severity: DiagnosticSeverity::Error, }, TestDiagnostic { start: (0, 1), end: (0, 1), severity: DiagnosticSeverity::Hint, }, ]); assert_eq!(document.diagnostics.underlines, vec![DiagnosticSpan { range: ByteIndex::new(0)..ByteIndex::new(4), severity: DiagnosticSeverity::Error, },]); } #[test] fn diagnostic_spans_from_byte_index() { let doc_text = "hello, world!"; let document = doc_with_diagnostics(doc_text, &[ TestDiagnostic { start: (0, 1), end: (0, 3), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (0, 5), end: (0, 7), severity: DiagnosticSeverity::Error, }, TestDiagnostic { start: (0, 9), end: (0, 10), severity: DiagnosticSeverity::Error, }, ]); for i in 0..3 { assert_eq!( document .diagnostics .spans_from(ByteIndex::new(i)) .cloned() .collect::>(), vec![ DiagnosticSpan { range: ByteIndex::new(1)..ByteIndex::new(3), severity: DiagnosticSeverity::Warning }, DiagnosticSpan { range: ByteIndex::new(5)..ByteIndex::new(7), severity: DiagnosticSeverity::Error }, DiagnosticSpan { range: ByteIndex::new(9)..ByteIndex::new(10), severity: DiagnosticSeverity::Error } ] ); } for i in 3..7 { assert_eq!( document .diagnostics .spans_from(ByteIndex::new(i)) .cloned() .collect::>(), vec![ DiagnosticSpan { range: ByteIndex::new(5)..ByteIndex::new(7), severity: DiagnosticSeverity::Error }, DiagnosticSpan { range: ByteIndex::new(9)..ByteIndex::new(10), severity: DiagnosticSeverity::Error } ] ); } for i in 7..10 { assert_eq!( document .diagnostics .spans_from(ByteIndex::new(i)) .cloned() .collect::>(), vec![DiagnosticSpan { range: ByteIndex::new(9)..ByteIndex::new(10), severity: DiagnosticSeverity::Error }] ); } for i in 10..doc_text.len() { assert_eq!( document .diagnostics .spans_from(ByteIndex::new(i)) .cloned() .collect::>(), vec![] ); } } #[test] fn line_severity() { let mut document = doc_with_diagnostics("hello, world!\nhow are you?\nare you okay?\n", &[ TestDiagnostic { start: (0, 3), end: (0, 5), severity: DiagnosticSeverity::Hint, }, TestDiagnostic { start: (0, 6), end: (0, 7), severity: DiagnosticSeverity::Warning, }, TestDiagnostic { start: (1, 2), end: (1, 2), severity: DiagnosticSeverity::Error, }, TestDiagnostic { start: (1, 3), end: (1, 8), severity: DiagnosticSeverity::Information, }, TestDiagnostic { start: (1, 9), end: (1, 9), severity: DiagnosticSeverity::Warning, }, ]); let mut buffer = Buffer::new(TEST_DIMENSIONS.get()); document.render(&mut buffer); let gutter_0 = &buffer[Position::new(0_usize.into(), 0_usize.into())]; assert_eq!( document.diagnostics.line_severity(0.into()), Some(DiagnosticSeverity::Warning) ); assert_eq!(gutter_0.content(), "โ— "); assert_eq!( gutter_0.foreground(), Style::diagnostic_icon(DiagnosticSeverity::Warning) .foreground() .unwrap() ); let gutter_1 = &buffer[Position::new(0_usize.into(), 1_usize.into())]; assert_eq!( document.diagnostics.line_severity(1.into()), Some(DiagnosticSeverity::Error) ); assert_eq!(gutter_1.content(), "โ— "); assert_eq!( gutter_1.foreground(), Style::diagnostic_icon(DiagnosticSeverity::Error) .foreground() .unwrap() ); let gutter_2 = &buffer[Position::new(0_usize.into(), 2_usize.into())]; assert_eq!(gutter_2.content(), " "); assert_eq!(document.diagnostics.line_severity(2.into()), None); } }