A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(notes): undo a word at a time and add the usual editing keys
RoversXcafc9e81e129
diff --git a/wezterm-gui/src/markdown_editor/document.rs b/wezterm-gui/src/markdown_editor/document.rsindex 06c22c3a..c2aa7188 100644--- a/wezterm-gui/src/markdown_editor/document.rs+++ b/wezterm-gui/src/markdown_editor/document.rs@@ -2,7 +2,7 @@ use parking_lot::Mutex;use std::ops::Range;use std::path::PathBuf;use std::sync::Arc;-use std::time::SystemTime;+use std::time::{Duration, Instant, SystemTime};use unicode_segmentation::UnicodeSegmentation;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -108,8 +108,15 @@ struct EditRecord {inserted: String,before: SourceSelection,after: SourceSelection,+ /// Typing or deleting a character at a time, which the next such edit+ /// may join so that one undo takes back a word, not a letter.+ joinable: bool,+ at: Instant,}+/// A pause longer than this ends a run of typing as an undo step.+const UNDO_GROUP_PAUSE: Duration = Duration::from_secs(2);+#[derive(Debug, Clone)]struct DocumentEdit {replaced: Range<usize>,@@ -352,6 +359,21 @@ impl MarkdownDocumentSession {}pub(crate) fn insert_text(&mut self, view: &mut EditorViewState, text: &str) -> bool {+ self.insert_text_joining(view, text, false)+ }++ /// `insert_text` for what is typed: a run of it is undone a word at a+ /// time, where a paste is undone whole.+ pub(crate) fn type_text(&mut self, view: &mut EditorViewState, text: &str) -> bool {+ self.insert_text_joining(view, text, true)+ }++ fn insert_text_joining(+ &mut self,+ view: &mut EditorViewState,+ text: &str,+ joinable: bool,+ ) -> bool {if view.mode == EditorMode::ReadOnly {return false;}@@ -368,7 +390,7 @@ impl MarkdownDocumentSession {return false;}let range = self.clamped_selection_range(view);- self.replace_range(view, range, &filtered)+ self.replace_range_joining(view, range, &filtered, joinable)}pub(crate) fn delete_selection(&mut self, view: &mut EditorViewState) -> bool {@@ -379,6 +401,11 @@ impl MarkdownDocumentSession {self.replace_range(view, range, "")}+ /// What the platform's text input sends, against the text it was shown+ /// at `revision`. On macOS every typed key arrives this way while the+ /// editor has the keyboard: one character at the caret is typing, joined+ /// into the run before it like a typed key, where a word an input method+ /// commits is undone on its own.pub(crate) fn replace_range_at_revision(&mut self,view: &mut EditorViewState,@@ -389,7 +416,10 @@ impl MarkdownDocumentSession {if self.revision != revision || view.mode == EditorMode::ReadOnly {return false;}- self.replace_range(view, range, replacement)+ let mut chars = replacement.chars();+ let typed = range.is_empty()+ && matches!((chars.next(), chars.next()), (Some(ch), None) if ch != '\n');+ self.replace_range_joining(view, range, replacement, typed)}pub(crate) fn surround_selection(@@ -578,7 +608,7 @@ impl MarkdownDocumentSession {if previous == caret {return false;}- self.replace_range(view, previous..caret, "")+ self.replace_range_joining(view, previous..caret, "", true)}pub(crate) fn delete_forward(&mut self, view: &mut EditorViewState) -> bool {@@ -594,7 +624,7 @@ impl MarkdownDocumentSession {if next == caret {return false;}- self.replace_range(view, caret..next, "")+ self.replace_range_joining(view, caret..next, "", true)}pub(crate) fn move_left(&self, view: &mut EditorViewState, extend: bool) {@@ -638,6 +668,68 @@ impl MarkdownDocumentSession {self.replace_range(view, previous..caret, "")}+ pub(crate) fn delete_word_forward(&mut self, view: &mut EditorViewState) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let selection = self.clamped_selection_range(view);+ if selection.start != selection.end {+ return self.replace_range(view, selection, "");+ }+ let caret = clamp_char_boundary(&self.source, view.selection.focus.byte);+ let next = next_word_boundary(&self.source, caret);+ self.replace_range(view, caret..next, "")+ }++ /// Delete from `start`, where the caller's line begins, to the caret; at+ /// that start, the line break before it.+ pub(crate) fn delete_to(&mut self, view: &mut EditorViewState, start: usize) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let selection = self.clamped_selection_range(view);+ if selection.start != selection.end {+ return self.replace_range(view, selection, "");+ }+ let caret = clamp_char_boundary(&self.source, view.selection.focus.byte);+ let start = clamp_char_boundary(&self.source, start.min(caret));+ if start == caret {+ return self.backspace(view);+ }+ self.replace_range(view, start..caret, "")+ }++ /// Delete from the caret to `end`, where the caller's line ends; at that+ /// end, the line break after it.+ pub(crate) fn delete_until(&mut self, view: &mut EditorViewState, end: usize) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let selection = self.clamped_selection_range(view);+ if selection.start != selection.end {+ return self.replace_range(view, selection, "");+ }+ let caret = clamp_char_boundary(&self.source, view.selection.focus.byte);+ let end = clamp_char_boundary(&self.source, end.max(caret));+ if end == caret {+ return self.delete_forward(view);+ }+ self.replace_range(view, caret..end, "")+ }++ pub(crate) fn move_document_start(&self, view: &mut EditorViewState, extend: bool) {+ self.set_caret(view, 0, extend);+ }++ pub(crate) fn move_document_end(&self, view: &mut EditorViewState, extend: bool) {+ self.set_caret(view, self.source.len(), extend);+ }++ /// The source line holding `byte`, without its line break.+ pub(crate) fn source_line_bounds(&self, byte: usize) -> (usize, usize) {+ self.line_bounds(byte)+ }+pub(crate) fn move_line_start(&self, view: &mut EditorViewState, extend: bool) {let (start, _) = self.line_bounds(view.selection.focus.byte);self.set_caret(view, start, extend);@@ -660,6 +752,17 @@ impl MarkdownDocumentSession {line.saturating_add(delta as usize).min(self.line_starts.len().saturating_sub(1))};+ if target_line == line && delta != 0 {+ // Up on the first line goes to its start and down on the last to+ // its end, as Mac text views do.+ let edge = if delta.is_negative() {+ 0+ } else {+ self.source.len()+ };+ self.set_caret(view, edge, extend);+ return;+ }let start = self.line_starts[target_line];let end = self.line_end(target_line);let target = byte_for_grapheme_column(&self.source[start..end], desired) + start;@@ -685,6 +788,7 @@ impl MarkdownDocumentSession {return false;};self.undo_bytes = self.undo_bytes.saturating_sub(edit_record_bytes(&edit));+ self.break_undo_group();let end = edit.start + edit.inserted.len();self.source.replace_range(edit.start..end, &edit.deleted);view.selection = edit.before;@@ -711,6 +815,7 @@ impl MarkdownDocumentSession {view.preferred_column = None;let mutation = DocumentEdit::new(edit.start..end, edit.inserted.len());self.push_undo(edit);+ self.break_undo_group();self.note_mutation(mutation);stage.finish(true);true@@ -721,6 +826,16 @@ impl MarkdownDocumentSession {view: &mut EditorViewState,range: Range<usize>,inserted: &str,+ ) -> bool {+ self.replace_range_joining(view, range, inserted, false)+ }++ fn replace_range_joining(+ &mut self,+ view: &mut EditorViewState,+ range: Range<usize>,+ inserted: &str,+ joinable: bool,) -> bool {let stage = crate::input_diagnostics::StageTimer::begin("note_edit");let start = clamp_char_boundary(&self.source, range.start);@@ -736,19 +851,73 @@ impl MarkdownDocumentSession {let after = SourceSelection::caret(start + inserted.len());view.selection = after;view.preferred_column = None;- self.push_undo(EditRecord {+ let record = EditRecord {start,deleted,inserted: inserted.to_string(),before,after,- });+ joinable: joinable && before.is_caret(),+ at: Instant::now(),+ };+ if !self.join_undo(&record) {+ self.push_undo(record);+ }self.redo.clear();self.note_mutation(mutation);stage.finish(true);true}+ /// Fold `record` into the last undo step when it carries on the same run+ /// of typing or deleting: the caret has not moved in between, nor has+ /// the typist paused, and typing has not just begun a new word.+ fn join_undo(&mut self, record: &EditRecord) -> bool {+ if !record.joinable {+ return false;+ }+ let Some(last) = self.undo.last_mut() else {+ return false;+ };+ if !last.joinable+ || last.after != record.before+ || record.at.duration_since(last.at) > UNDO_GROUP_PAUSE+ {+ return false;+ }+ let typing = last.deleted.is_empty() && record.deleted.is_empty();+ let deleting = last.inserted.is_empty() && record.inserted.is_empty();+ if typing && record.start == last.start + last.inserted.len() {+ let new_word = last.inserted.ends_with(char::is_whitespace)+ && !record.inserted.starts_with(char::is_whitespace);+ if new_word {+ return false;+ }+ last.inserted.push_str(&record.inserted);+ } else if deleting && record.start + record.deleted.len() == last.start {+ // Backspace, walking back.+ last.deleted.insert_str(0, &record.deleted);+ last.start = record.start;+ } else if deleting && record.start == last.start {+ // Forward delete, the text closing in on the caret.+ last.deleted.push_str(&record.deleted);+ } else {+ return false;+ }+ last.after = record.after;+ last.at = record.at;+ self.undo_bytes = self+ .undo_bytes+ .saturating_add(record.deleted.len() + record.inserted.len());+ true+ }++ fn break_undo_group(&mut self) {+ if let Some(last) = self.undo.last_mut() {+ last.joinable = false;+ }+ }+fn push_undo(&mut self, record: EditRecord) {self.undo_bytes = self.undo_bytes.saturating_add(edit_record_bytes(&record));self.undo.push(record);@@ -1338,4 +1507,143 @@ mod tests {assert!(!session.can_undo());assert!(!session.can_redo());}++ fn type_each(session: &mut MarkdownDocumentSession, view: &mut EditorViewState, text: &str) {+ for ch in text.chars() {+ assert!(session.type_text(view, &ch.to_string()));+ }+ }++ #[test]+ fn typing_is_undone_a_word_at_a_time() {+ let (mut session, mut view) = session("");+ type_each(&mut session, &mut view, "hello world");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "hello ");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "");+ assert!(session.redo(&mut view));+ assert_eq!(session.source(), "hello ");+ }++ #[test]+ fn keys_from_native_text_input_are_undone_a_word_at_a_time() {+ let (mut session, mut view) = session("");+ for ch in "hello world".chars() {+ let at = view.selection.focus.byte;+ let revision = session.revision();+ assert!(session.replace_range_at_revision(+ &mut view,+ revision,+ at..at,+ &ch.to_string()+ ));+ }+ // A word committed whole by an input method is a step of its own.+ let at = view.selection.focus.byte;+ let revision = session.revision();+ assert!(session.replace_range_at_revision(&mut view, revision, at..at, "你好"));+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "hello world");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "hello ");+ }++ #[test]+ fn a_paste_or_a_moved_caret_starts_a_new_undo_step() {+ let (mut session, mut view) = session("");+ type_each(&mut session, &mut view, "ab");+ assert!(session.insert_text(&mut view, "PASTED"));+ type_each(&mut session, &mut view, "cd");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "abPASTED");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "ab");++ session.set_caret(&mut view, 0, false);+ type_each(&mut session, &mut view, "x");+ session.set_caret(&mut view, session.source().len(), false);+ type_each(&mut session, &mut view, "y");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "xab");+ }++ #[test]+ fn typing_after_undo_or_redo_starts_a_new_group() {+ let (mut session, mut view) = session("");+ type_each(&mut session, &mut view, "a");+ assert!(session.insert_text(&mut view, "PASTED"));+ assert!(session.undo(&mut view));+ type_each(&mut session, &mut view, "b");+ assert_eq!(session.source(), "ab");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "a");++ assert!(session.redo(&mut view));+ type_each(&mut session, &mut view, "c");+ assert_eq!(session.source(), "abc");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "ab");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "a");+ }++ #[test]+ fn deleting_after_undo_starts_a_new_group() {+ let (mut session, mut view) = session("abc");+ session.set_caret(&mut view, 3, false);+ assert!(session.backspace(&mut view));+ assert!(session.insert_text(&mut view, "PASTED"));+ assert!(session.undo(&mut view));+ assert!(session.backspace(&mut view));+ assert_eq!(session.source(), "a");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "ab");+ }++ #[test]+ fn backspacing_and_forward_deleting_are_undone_as_one_step() {+ let (mut session, mut view) = session("abcdef");+ session.set_caret(&mut view, 6, false);+ assert!(session.backspace(&mut view));+ assert!(session.backspace(&mut view));+ assert_eq!(session.source(), "abcd");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "abcdef");+ assert_eq!(view.selection.focus.byte, 6);++ session.set_caret(&mut view, 0, false);+ assert!(session.delete_forward(&mut view));+ assert!(session.delete_forward(&mut view));+ assert_eq!(session.source(), "cdef");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "abcdef");+ }++ #[test]+ fn line_and_word_deletes_and_document_edges() {+ let (mut session, mut view) = session("one two\nthree");+ session.set_caret(&mut view, 7, false);+ assert!(session.delete_to(&mut view, 0));+ assert_eq!(session.source(), "\nthree");+ // At the line's start it takes the line break before it.+ session.set_caret(&mut view, 1, false);+ assert!(session.delete_to(&mut view, 1));+ assert_eq!(session.source(), "three");++ session.set_caret(&mut view, 0, false);+ assert!(session.delete_word_forward(&mut view));+ assert_eq!(session.source(), "");++ let (mut lines, mut view) = self::session("ab\ncd");+ lines.set_caret(&mut view, 1, false);+ assert!(lines.delete_until(&mut view, 2));+ assert_eq!(lines.source(), "a\ncd");+ // Up on the first line goes to the start, down on the last to the end.+ lines.move_vertical(&mut view, -1, false);+ assert_eq!(view.selection.focus.byte, 0);+ lines.set_caret(&mut view, 3, false);+ lines.move_vertical(&mut view, 1, false);+ assert_eq!(view.selection.focus.byte, lines.source().len());+ }}diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rsindex 8ae16b08..de93e62f 100644--- a/wezterm-gui/src/markdown_editor/host.rs+++ b/wezterm-gui/src/markdown_editor/host.rs@@ -9,6 +9,7 @@ use std::ops::Range;use std::sync::Arc;use std::time::SystemTime;use std::time::{Duration, Instant};+use unicode_segmentation::UnicodeSegmentation;#[derive(Debug, Clone)]enum NoteDisplaySource {@@ -1034,9 +1035,8 @@ impl NoteHostState {}/// Move between painted visual rows (including soft wraps) while retaining- /// the preferred horizontal pixel. The controller falls back to physical- /// source-line navigation when the target row is outside the current- /// viewport and therefore intentionally has no shaped layout.+ /// the preferred horizontal pixel. A target row outside the viewport has+ /// no shaped layout and is stepped onto by `offscreen_vertical_target`.pub(crate) fn visual_vertical_target(&self, delta: isize) -> Option<(SourcePosition, usize)> {let caret = self.view.selection.focus.byte;let current = self.line_layouts.iter().position(|line| {@@ -1045,12 +1045,6 @@ impl NoteHostState {.any(|run| run.source.start <= caret && caret <= run.source.end)|| (line.runs.is_empty() && line.source.start == caret)})?;- let target = if delta.is_negative() {- current.checked_sub(delta.unsigned_abs())?- } else {- current.checked_add(delta as usize)?- };- let target_line = self.line_layouts.get(target)?;let current_line = &self.line_layouts[current];let current_x = current_line.runs@@ -1068,9 +1062,136 @@ impl NoteHostState {.view.preferred_column.unwrap_or(current_x.max(0.0) as usize);- let position = self- .source_position_for_point(preferred as f32, target_line.y + target_line.height / 2.0);- Some((position, preferred))+ // A short table cell answers for the rows below its text with its+ // last line, so a row can land where the caret already is: keep+ // going until one does not.+ let mut target = Some(current);+ loop {+ target = target.and_then(|target| target.checked_add_signed(delta));+ let Some(target_line) = target.and_then(|target| self.line_layouts.get(target)) else {+ return self+ .offscreen_vertical_target(delta)+ .map(|position| (position, preferred));+ };+ let position = self.source_position_for_point(+ preferred as f32,+ target_line.y + target_line.height / 2.0,+ );+ if position.byte != caret {+ return Some((position, preferred));+ }+ }+ }++ /// Up or Down onto a row with no shaped layout, off screen: as many+ /// characters into it as the caret is into its own row. Close enough+ /// until the row shows and is laid out, and never more than a row away.+ /// None past the first or last row.+ pub(crate) fn offscreen_vertical_target(&self, delta: isize) -> Option<SourcePosition> {+ let rows = &self.wrapped_visual.lines;+ let caret = self.view.selection.focus.byte;+ let holds = |line: &super::VisualLine| {+ line.runs+ .iter()+ .any(|run| run.source.start <= caret && caret <= run.source.end)+ || (line.runs.is_empty() && line.source.start == caret)+ };+ // At a wrap the byte ends one row and starts the next; the caret is+ // drawn on the next.+ let current = rows.iter().rposition(|line| holds(line))?;+ let target = current.checked_add_signed(delta)?;+ let row = rows.get(target)?;+ let text_start = |line: &super::VisualLine| {+ line.runs+ .iter()+ .find(|run| !run.atomic)+ .map(|run| run.source.start)+ };+ let session = self.session.as_ref()?.lock();+ let source = session.source();+ let column = text_start(&rows[current])+ .filter(|start| *start <= caret)+ .and_then(|start| source.get(start..caret))+ .map_or(0, |text| text.graphemes(true).count());+ let Some(start) = text_start(row) else {+ return Some(SourcePosition::new(row.source.start));+ };+ let end = row+ .runs+ .last()+ .map_or(start, |run| run.source.end)+ .max(start);+ let text = source.get(start..end)?;+ // A row the paragraph wraps on from ends before the space it wraps+ // at, so the caret stays on it.+ let wraps_on = rows+ .get(target + 1)+ .and_then(|next| next.runs.first())+ .is_some_and(|run| run.source.start == end);+ let text = if wraps_on { text.trim_end() } else { text };+ let offset = text+ .grapheme_indices(true)+ .nth(column)+ .map_or(text.len(), |(at, _)| at);+ Some(SourcePosition::new(start + offset))+ }++ /// The source the painted row holding `byte` shows, when that row is on+ /// screen: where ⌘← and ⌘→ go in a wrapped paragraph. A row starts after+ /// a list marker, and one the paragraph wraps on from ends before the+ /// space it wraps at, so the caret stays on the row.+ pub(crate) fn visual_line_bounds(&self, byte: usize) -> Option<(usize, usize)> {+ let contains = |line: &&NoteLineLayout| {+ line.runs+ .iter()+ .any(|run| run.source.start <= byte && byte <= run.source.end)+ };+ // At a wrap the byte ends one row and starts the next; the caret is+ // drawn on the next.+ let index = self.line_layouts.iter().rposition(|line| contains(&line))?;+ let line = &self.line_layouts[index];+ let start = line+ .runs+ .iter()+ .find(|run| !run.atomic || !self.is_list_marker_run(run))+ .or_else(|| line.runs.first())?+ .source+ .start;+ let mut end = line.runs.last()?.source.end;+ let wraps_on = self+ .line_layouts+ .get(index + 1)+ .and_then(|next| next.runs.first())+ .is_some_and(|run| run.source.start == end);+ if wraps_on {+ if let Some(session) = self.session.as_ref() {+ let session = session.lock();+ if let Some(row) = session.source().get(start..end) {+ end = start + row.trim_end().len();+ }+ }+ }+ Some((start, end.max(start)))+ }++ /// Whether `run` is a list item's marker or task box, which a row's+ /// start skips.+ fn is_list_marker_run(&self, run: &NoteRunLayout) -> bool {+ let Some(session) = self.session.as_ref() else {+ return false;+ };+ let session = session.lock();+ let Some(source) = session.source().get(run.source.clone()) else {+ return false;+ };+ let marker = source.trim();+ matches!(marker, "-" | "*" | "+" | "[ ]" | "[x]" | "[X]")+ || marker+ .strip_suffix('.')+ .or_else(|| marker.strip_suffix(')'))+ .is_some_and(|digits| {+ !digits.is_empty() && digits.chars().all(|ch| ch.is_ascii_digit())+ })}pub(crate) fn atomic_source_for_point(&self, x: f32, y: f32) -> Option<Range<usize>> {@@ -1218,6 +1339,37 @@ mod state_tests {host}+ #[test]+ fn up_and_down_step_one_row_onto_rows_with_no_layout() {+ // The document's one paragraph, wrapped over several rows, none of+ // them on screen.+ let mut host = host_with_source("aaaa bbb cccc ddd eeee fff gggg hhh");+ host.wrapped_visual = Arc::new(+ super::super::wrap_visual_document_by_width(&host.visual, 9.0, |_, _, text| {+ Ok::<f32, ()>(text.chars().count() as f32)+ })+ .unwrap(),+ );+ let rows: Vec<usize> = host+ .wrapped_visual+ .lines+ .iter()+ .map(|line| line.runs.first().unwrap().source.start)+ .collect();+ assert!(rows.len() >= 3);+ host.view.selection = SourceSelection::caret(rows[1] + 2);+ assert_eq!(host.visual_vertical_target(1), None);+ let target = |host: &NoteHostState, delta| {+ host.offscreen_vertical_target(delta)+ .map(|position| position.byte)+ };+ assert_eq!(target(&host, 1), Some(rows[2] + 2));+ assert_eq!(target(&host, -1), Some(rows[0] + 2));+ // None past the last row: the caret goes to the end from there.+ host.view.selection = SourceSelection::caret(rows[rows.len() - 1] + 1);+ assert_eq!(target(&host, 1), None);+ }+#[test]fn a_diagram_found_not_to_draw_is_laid_out_again_as_code() {// Parses, but relates to a requirement nobody defined.@@ -2092,6 +2244,36 @@ mod tests {assert_eq!(host.source_position_for_point(0.0, 65.0).byte, 2);}+ #[test]+ fn down_leaves_a_table_row_whose_short_cell_repeats_below() {+ // | a | bbbb/cccc wrapped | then a row below.+ let run = |source: std::ops::Range<usize>, x: f32| NoteRunLayout {+ boundaries: vec![(x, source.start), (x + 10.0, source.end)],+ source,+ x,+ width: 10.0,+ hit_x: x,+ hit_width: 50.0,+ atomic: false,+ };+ let line = |y: f32, runs: Vec<NoteRunLayout>| NoteLineLayout {+ source: 0..20,+ y,+ height: 20.0,+ runs,+ };+ let mut host = NoteHostState::default();+ host.line_layouts = vec![+ line(0.0, vec![run(0..1, 0.0), run(4..8, 50.0)]),+ // The short cell answers for the row's second line too.+ line(20.0, vec![run(0..1, 0.0), run(8..12, 50.0)]),+ line(40.0, vec![run(15..16, 0.0), run(17..18, 50.0)]),+ ];+ host.view.selection = SourceSelection::caret(1);+ let (position, _) = host.visual_vertical_target(1).unwrap();+ assert_eq!(position.byte, 16);+ }+#[test]fn external_link_hit_testing_uses_painted_run_bounds() {let source = "Read [docs](https://example.test/guide).";diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex 281b3167..e9d89892 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -5573,6 +5573,81 @@ impl crate::TermWindow {true}+ /// The painted row holding `byte`, or its whole line when that row is+ /// not on screen.+ fn right_sidebar_note_row_bounds(&self, byte: usize) -> (usize, usize) {+ self.right_sidebar_note+ .visual_line_bounds(byte)+ .or_else(|| {+ self.right_sidebar_note+ .session+ .as_ref()+ .map(|session| session.lock().source_line_bounds(byte))+ })+ .unwrap_or((byte, byte))+ }++ /// ⌘← and ⌘→: to the start or end of the row the caret is on.+ fn move_right_sidebar_note_to_row_edge(&mut self, end: bool, extend: bool) {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ let caret = self.right_sidebar_note.view.selection.focus.byte;+ let (row_start, row_end) = self.right_sidebar_note_row_bounds(caret);+ session.lock().set_caret(+ &mut self.right_sidebar_note.view,+ if end { row_end } else { row_start },+ extend,+ );+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ }++ /// Control-A, E, B, F, P, N, D, H and K, as in any Mac text field.+ fn handle_right_sidebar_note_control_key(&mut self, letter: char) -> bool {+ let key = match letter {+ 'a' | 'e' | 'k' => None,+ 'b' => Some(TermKeyCode::LeftArrow),+ 'f' => Some(TermKeyCode::RightArrow),+ 'p' => Some(TermKeyCode::UpArrow),+ 'n' => Some(TermKeyCode::DownArrow),+ 'd' => Some(TermKeyCode::Delete),+ 'h' => Some(TermKeyCode::Backspace),+ _ => return false,+ };+ if let Some(key) = key {+ return self.handle_right_sidebar_note_key(key, TermModifiers::NONE);+ }+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ self.right_sidebar_note.begin_live_editing();+ // By paragraph, as Cocoa's moveToBeginningOfParagraph: and+ // deleteToEndOfParagraph: do; ⌘← and ⌘→ go by row.+ let caret = self.right_sidebar_note.view.selection.focus.byte;+ let (start, end) = session.lock().source_line_bounds(caret);+ match letter {+ 'a' | 'e' => {+ session.lock().set_caret(+ &mut self.right_sidebar_note.view,+ if letter == 'a' { start } else { end },+ false,+ );+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ }+ _ => {+ if session+ .lock()+ .delete_until(&mut self.right_sidebar_note.view, end)+ {+ self.note_did_edit();+ }+ }+ }+ true+ }+fn handle_right_sidebar_note_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {// begin_live_editing() is deliberately deferred until a key is known// to be handled: an unrelated key must not flip the display source to@@ -5593,7 +5668,10 @@ impl crate::TermWindow {if word_modifier&& matches!(key,- TermKeyCode::LeftArrow | TermKeyCode::RightArrow | TermKeyCode::Backspace+ TermKeyCode::LeftArrow+ | TermKeyCode::RightArrow+ | TermKeyCode::Backspace+ | TermKeyCode::Delete){let Some(session) = self.right_sidebar_note.session.clone() else {@@ -5626,13 +5704,68 @@ impl crate::TermWindow {}return true;}+ TermKeyCode::Delete => {+ if session+ .lock()+ .delete_word_forward(&mut self.right_sidebar_note.view)+ {+ self.note_did_edit();+ }+ return true;+ }_ => {}}}+ // Off macOS, Control with Home or End goes to the document's ends,+ // and Control-Y redoes.+ if !cfg!(target_os = "macos") && ctrl && !alt && !super_ {+ match key {+ TermKeyCode::Home | TermKeyCode::End => {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ self.right_sidebar_note.begin_live_editing();+ let view = &mut self.right_sidebar_note.view;+ if key == TermKeyCode::Home {+ session.lock().move_document_start(view, shift);+ } else {+ session.lock().move_document_end(view, shift);+ }+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ return true;+ }+ TermKeyCode::Char('y') | TermKeyCode::Char('Y') => {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ self.right_sidebar_note.begin_live_editing();+ if session.lock().redo(&mut self.right_sidebar_note.view) {+ self.note_did_edit();+ }+ return true;+ }+ _ => {}+ }+ }++ // The Control keys every Mac text field answers to.+ if cfg!(target_os = "macos") && ctrl && !alt && !super_ && !shift {+ if let TermKeyCode::Char(letter) = key {+ if self.handle_right_sidebar_note_control_key(letter.to_ascii_lowercase()) {+ return true;+ }+ }+ }+if command && !alt {let command_handled = match key {- TermKeyCode::LeftArrow | TermKeyCode::RightArrow => super_,+ TermKeyCode::LeftArrow+ | TermKeyCode::RightArrow+ | TermKeyCode::UpArrow+ | TermKeyCode::DownArrow+ | TermKeyCode::Backspace => super_,TermKeyCode::Char('a' | 'A' | 'c' | 'C' | 'x' | 'X' | 'v' | 'V' | 'z' | 'Z' | 's' | 'S' | 'e'| 'E' | 'b' | 'B' | 'i' | 'I',@@ -5644,22 +5777,36 @@ impl crate::TermWindow {}match key {TermKeyCode::LeftArrow if super_ => {+ self.move_right_sidebar_note_to_row_edge(false, shift);+ return true;+ }+ TermKeyCode::RightArrow if super_ => {+ self.move_right_sidebar_note_to_row_edge(true, shift);+ return true;+ }+ TermKeyCode::UpArrow | TermKeyCode::DownArrow if super_ => {if let Some(session) = self.right_sidebar_note.session.clone() {- session- .lock()- .move_line_start(&mut self.right_sidebar_note.view, shift);+ let view = &mut self.right_sidebar_note.view;+ if key == TermKeyCode::UpArrow {+ session.lock().move_document_start(view, shift);+ } else {+ session.lock().move_document_end(view, shift);+ }self.right_sidebar_note.reveal_caret = true;self.right_sidebar_note.refresh_projection();}return true;}- TermKeyCode::RightArrow if super_ => {+ TermKeyCode::Backspace if super_ => {if let Some(session) = self.right_sidebar_note.session.clone() {- session+ let caret = self.right_sidebar_note.view.selection.focus.byte;+ let start = self.right_sidebar_note_row_bounds(caret).0;+ if session.lock()- .move_line_end(&mut self.right_sidebar_note.view, shift);- self.right_sidebar_note.reveal_caret = true;- self.right_sidebar_note.refresh_projection();+ .delete_to(&mut self.right_sidebar_note.view, start)+ {+ self.note_did_edit();+ }}return true;}@@ -5736,6 +5883,21 @@ impl crate::TermWindow {return false;}+ if matches!(key, TermKeyCode::PageUp | TermKeyCode::PageDown) {+ // A page at a time, the caret left where it is, as on a Mac.+ let padding = self.ui_f32(NOTE_BODY_PADDING as f32);+ let host = &mut self.right_sidebar_note;+ let page = (host.viewport_height - padding).max(1.0);+ host.reveal_caret = false;+ // As a wheel scroll is: the scrollbar shows it.+ host.scroll_by(if key == TermKeyCode::PageUp {+ -page+ } else {+ page+ });+ return true;+ }+let will_handle = matches!(key,TermKeyCode::Escape@@ -5786,6 +5948,14 @@ impl crate::TermWindow {SourceSelection::caret(position.byte);}self.right_sidebar_note.view.preferred_column = Some(preferred);+ } else if let Some(position) = self.right_sidebar_note.offscreen_vertical_target(-1)+ {+ if shift {+ self.right_sidebar_note.view.selection.focus = position;+ } else {+ self.right_sidebar_note.view.selection =+ SourceSelection::caret(position.byte);+ }} else {session.lock()@@ -5804,6 +5974,14 @@ impl crate::TermWindow {SourceSelection::caret(position.byte);}self.right_sidebar_note.view.preferred_column = Some(preferred);+ } else if let Some(position) = self.right_sidebar_note.offscreen_vertical_target(1)+ {+ if shift {+ self.right_sidebar_note.view.selection.focus = position;+ } else {+ self.right_sidebar_note.view.selection =+ SourceSelection::caret(position.byte);+ }} else {session.lock()@@ -5871,7 +6049,7 @@ impl crate::TermWindow {TermKeyCode::Char(ch) if !ch.is_control() => {changed = session.lock()- .insert_text(&mut self.right_sidebar_note.view, &ch.to_string());+ .type_text(&mut self.right_sidebar_note.view, &ch.to_string());true}_ => false,