Skip to content

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.

Fix Note editor bugs, add expandable Note pane, optimize rendering, enable macOS dictation

RoversXc766886602c6
diff --git a/wezterm-gui/src/markdown_editor/document.rs b/wezterm-gui/src/markdown_editor/document.rs
index a33ec4ba..0db5dbb3 100644
--- a/wezterm-gui/src/markdown_editor/document.rs
+++ b/wezterm-gui/src/markdown_editor/document.rs
@@ -141,12 +141,20 @@ pub(crate) struct MarkdownDocumentSession {
save_state: SaveState,
line_starts: Vec<usize>,
undo: Vec<EditRecord>,
+ /// Total `deleted + inserted` bytes retained across `undo`, so one huge
+ /// delete or paste cannot pin megabytes per record up to the count cap.
+ undo_bytes: usize,
redo: Vec<EditRecord>,
save_lock: Arc<Mutex<()>>,
disk_stamp: Option<(SystemTime, u64)>,
}
const MAX_UNDO_RECORDS: usize = 512;
+const MAX_UNDO_BYTES: usize = 4 * 1024 * 1024;
+
+fn edit_record_bytes(record: &EditRecord) -> usize {
+ record.deleted.len() + record.inserted.len()
+}
impl MarkdownDocumentSession {
pub(crate) fn new(document_id: String, path: PathBuf, source: String) -> Self {
@@ -167,6 +175,7 @@ impl MarkdownDocumentSession {
save_state: SaveState::Saved,
line_starts,
undo: vec![],
+ undo_bytes: 0,
redo: vec![],
save_lock: Arc::new(Mutex::new(())),
disk_stamp,
@@ -298,6 +307,7 @@ impl MarkdownDocumentSession {
self.save_state = SaveState::Saved;
self.line_starts = line_starts(&self.source);
self.undo.clear();
+ self.undo_bytes = 0;
self.redo.clear();
self.clamp_view(view);
true
@@ -412,6 +422,115 @@ impl MarkdownDocumentSession {
true
}
+ /// Whether Tab should indent whole lines rather than insert spaces at the
+ /// caret: any multi-line selection, or a caret on a Markdown list/quote
+ /// line (including task lists and ordered lists).
+ pub(crate) fn tab_indents_lines(&self, view: &EditorViewState) -> bool {
+ let range = self.clamped_selection_range(view);
+ // Any selection containing a newline (including one that ends exactly
+ // at the next line's start, like "first\n") indents lines; falling
+ // through to insert_text would replace the selection and join lines.
+ if self.source[range.clone()].contains('\n') {
+ return true;
+ }
+ let (line_start, line_end) = self.line_bounds(range.start);
+ markdown_line_continuation(self.source[line_start..line_end].trim_start()).is_some()
+ }
+
+ pub(crate) fn indent_lines(&mut self, view: &mut EditorViewState) -> bool {
+ self.reindent_lines(view, true)
+ }
+
+ pub(crate) fn outdent_lines(&mut self, view: &mut EditorViewState) -> bool {
+ self.reindent_lines(view, false)
+ }
+
+ fn reindent_lines(&mut self, view: &mut EditorViewState, indent: bool) -> bool {
+ const LINE_INDENT: &str = " ";
+ if view.mode == EditorMode::ReadOnly {
+ return false;
+ }
+ let anchor = clamp_char_boundary(&self.source, view.selection.anchor.byte);
+ let focus = clamp_char_boundary(&self.source, view.selection.focus.byte);
+ let range = anchor.min(focus)..anchor.max(focus);
+ let first_line = self.line_index(range.start);
+ let last_pos = if range.end > range.start {
+ range.end - 1
+ } else {
+ range.end
+ };
+ let last_line = self.line_index(last_pos.max(range.start));
+ let span_start = self.line_starts[first_line];
+ let span_end = self.line_end(last_line);
+
+ let mut replacement = String::with_capacity(span_end - span_start + LINE_INDENT.len());
+ // (old line start, byte delta applied at that line's start)
+ let mut deltas: Vec<(usize, isize)> = Vec::with_capacity(last_line - first_line + 1);
+ for line in first_line..=last_line {
+ let start = self.line_starts[line];
+ let end = self.line_end(line);
+ let text = &self.source[start..end];
+ if line > first_line {
+ replacement.push('\n');
+ }
+ if indent {
+ replacement.push_str(LINE_INDENT);
+ replacement.push_str(text);
+ deltas.push((start, LINE_INDENT.len() as isize));
+ } else {
+ let removed = if text.starts_with('\t') {
+ 1
+ } else {
+ text.bytes()
+ .take(LINE_INDENT.len())
+ .take_while(|byte| *byte == b' ')
+ .count()
+ };
+ replacement.push_str(&text[removed..]);
+ deltas.push((start, -(removed as isize)));
+ }
+ }
+ if replacement == self.source[span_start..span_end] {
+ return false;
+ }
+
+ let total: isize = deltas.iter().map(|(_, delta)| *delta).sum();
+ let map = |position: usize| -> usize {
+ if position < span_start {
+ return position;
+ }
+ if position > span_end {
+ return (position as isize + total).max(span_start as isize) as usize;
+ }
+ let index = deltas
+ .partition_point(|(start, _)| *start <= position)
+ .saturating_sub(1);
+ let (line_start, delta) = deltas[index];
+ let shifted_start: isize = line_start as isize
+ + deltas[..index].iter().map(|(_, delta)| *delta).sum::<isize>();
+ let relative = position - line_start;
+ let relative = if delta >= 0 {
+ relative + delta as usize
+ } else {
+ relative.saturating_sub(delta.unsigned_abs())
+ };
+ shifted_start as usize + relative
+ };
+ let (new_anchor, new_focus) = (map(anchor), map(focus));
+ if !self.replace_range(view, span_start..span_end, &replacement) {
+ return false;
+ }
+ view.selection = SourceSelection {
+ anchor: SourcePosition::new(new_anchor),
+ focus: SourcePosition::new(new_focus),
+ };
+ view.preferred_column = None;
+ if let Some(edit) = self.undo.last_mut() {
+ edit.after = view.selection;
+ }
+ true
+ }
+
pub(crate) fn insert_newline(&mut self, view: &mut EditorViewState) -> bool {
if view.mode == EditorMode::ReadOnly {
return false;
@@ -554,14 +673,19 @@ impl MarkdownDocumentSession {
}
pub(crate) fn undo(&mut self, view: &mut EditorViewState) -> bool {
+ if view.mode == EditorMode::ReadOnly {
+ return false;
+ }
let stage = crate::input_diagnostics::StageTimer::begin("note_edit");
let Some(edit) = self.undo.pop() else {
stage.finish(false);
return false;
};
+ self.undo_bytes = self.undo_bytes.saturating_sub(edit_record_bytes(&edit));
let end = edit.start + edit.inserted.len();
self.source.replace_range(edit.start..end, &edit.deleted);
view.selection = edit.before;
+ view.preferred_column = None;
let mutation = DocumentEdit::new(edit.start..end, edit.deleted.len());
self.redo.push(edit);
self.note_mutation(mutation);
@@ -570,6 +694,9 @@ impl MarkdownDocumentSession {
}
pub(crate) fn redo(&mut self, view: &mut EditorViewState) -> bool {
+ if view.mode == EditorMode::ReadOnly {
+ return false;
+ }
let stage = crate::input_diagnostics::StageTimer::begin("note_edit");
let Some(edit) = self.redo.pop() else {
stage.finish(false);
@@ -578,8 +705,9 @@ impl MarkdownDocumentSession {
let end = edit.start + edit.deleted.len();
self.source.replace_range(edit.start..end, &edit.inserted);
view.selection = edit.after;
+ view.preferred_column = None;
let mutation = DocumentEdit::new(edit.start..end, edit.inserted.len());
- self.undo.push(edit);
+ self.push_undo(edit);
self.note_mutation(mutation);
stage.finish(true);
true
@@ -605,22 +733,32 @@ impl MarkdownDocumentSession {
let after = SourceSelection::caret(start + inserted.len());
view.selection = after;
view.preferred_column = None;
- self.undo.push(EditRecord {
+ self.push_undo(EditRecord {
start,
deleted,
inserted: inserted.to_string(),
before,
after,
});
- if self.undo.len() > MAX_UNDO_RECORDS {
- self.undo.remove(0);
- }
self.redo.clear();
self.note_mutation(mutation);
stage.finish(true);
true
}
+ fn push_undo(&mut self, record: EditRecord) {
+ self.undo_bytes = self.undo_bytes.saturating_add(edit_record_bytes(&record));
+ self.undo.push(record);
+ while self.undo.len() > 1
+ && (self.undo.len() > MAX_UNDO_RECORDS || self.undo_bytes > MAX_UNDO_BYTES)
+ {
+ let evicted = self.undo.remove(0);
+ self.undo_bytes = self
+ .undo_bytes
+ .saturating_sub(edit_record_bytes(&evicted));
+ }
+ }
+
fn note_mutation(&mut self, edit: DocumentEdit) {
self.revision = self.revision.wrapping_add(1);
self.snapshot_cache = None;
@@ -994,6 +1132,127 @@ mod tests {
assert_eq!(session.source(), "**hello**");
}
+ #[test]
+ fn undo_history_is_byte_bounded_but_keeps_the_newest_record() {
+ let big = "x".repeat(MAX_UNDO_BYTES / 2 + 1);
+ let (mut session, mut view) = session("");
+ session.insert_text(&mut view, "small edit");
+ for _ in 0..3 {
+ session.select_all(&mut view);
+ session.insert_text(&mut view, &big);
+ }
+ assert!(session.undo_bytes <= MAX_UNDO_BYTES.max(edit_record_bytes(
+ session.undo.last().expect("newest record retained")
+ )));
+ // Older records were evicted to honor the byte cap...
+ assert!(session.undo.len() < 4);
+ // ...but the newest edit is always undoable.
+ assert!(session.undo(&mut view));
+ assert!(session.redo(&mut view));
+ assert_eq!(session.source(), big);
+ }
+
+ #[test]
+ fn tab_indents_list_lines_and_multi_line_selections() {
+ let (session, mut view) = session("plain prose\n- item\n1. ordered\n> quote");
+ session.set_caret(&mut view, 2, false);
+ assert!(!session.tab_indents_lines(&view));
+ session.set_caret(&mut view, session.source().find("item").unwrap(), false);
+ assert!(session.tab_indents_lines(&view));
+ session.set_caret(&mut view, session.source().find("ordered").unwrap(), false);
+ assert!(session.tab_indents_lines(&view));
+ session.set_caret(&mut view, session.source().find("quote").unwrap(), false);
+ assert!(session.tab_indents_lines(&view));
+ view.selection = SourceSelection {
+ anchor: SourcePosition::new(2),
+ focus: SourcePosition::new(session.source().find("item").unwrap()),
+ };
+ assert!(session.tab_indents_lines(&view));
+ }
+
+ #[test]
+ fn newline_ending_selection_indents_its_line_instead_of_replacing_it() {
+ let (mut session, mut view) = session("first\nsecond");
+ // Select "first\n" — ends exactly at the start of the second line.
+ view.selection = SourceSelection {
+ anchor: SourcePosition::new(0),
+ focus: SourcePosition::new(6),
+ };
+ assert!(session.tab_indents_lines(&view));
+ assert!(session.indent_lines(&mut view));
+ assert_eq!(session.source(), " first\nsecond");
+ }
+
+ #[test]
+ fn indent_and_outdent_shift_selected_lines_and_are_undoable() {
+ let (mut session, mut view) = session("- one\n- two\n- three");
+ let anchor = session.source().find("one").unwrap();
+ let focus = session.source().find("two").unwrap();
+ view.selection = SourceSelection {
+ anchor: SourcePosition::new(anchor),
+ focus: SourcePosition::new(focus),
+ };
+ assert!(session.indent_lines(&mut view));
+ assert_eq!(session.source(), " - one\n - two\n- three");
+ assert_eq!(view.selection.anchor.byte, anchor + 4);
+ assert_eq!(view.selection.focus.byte, focus + 8);
+ // The original selection covered "one\n- "; the indented equivalent
+ // keeps both endpoints anchored to the same text.
+ assert_eq!(&session.source()[view.selection.range()], "one\n - ");
+
+ assert!(session.outdent_lines(&mut view));
+ assert_eq!(session.source(), "- one\n- two\n- three");
+ assert_eq!(view.selection.anchor.byte, anchor);
+ assert_eq!(view.selection.focus.byte, focus);
+
+ // Nothing left to strip: outdent is a no-op, not an edit.
+ assert!(!session.outdent_lines(&mut view));
+
+ assert!(session.undo(&mut view));
+ assert_eq!(session.source(), " - one\n - two\n- three");
+ assert!(session.undo(&mut view));
+ assert_eq!(session.source(), "- one\n- two\n- three");
+ }
+
+ #[test]
+ fn outdent_strips_a_tab_or_partial_indent_and_clamps_the_caret() {
+ let (mut tabbed, mut tabbed_view) = session("\t- tabbed\n - short");
+ tabbed.select_all(&mut tabbed_view);
+ assert!(tabbed.outdent_lines(&mut tabbed_view));
+ assert_eq!(tabbed.source(), "- tabbed\n- short");
+
+ let (mut indented, mut indented_view) = session(" - item");
+ indented.set_caret(&mut indented_view, 2, false);
+ assert!(indented.outdent_lines(&mut indented_view));
+ assert_eq!(indented.source(), "- item");
+ assert_eq!(indented_view.selection.focus.byte, 0);
+ }
+
+ #[test]
+ fn undo_redo_respect_read_only_and_reset_preferred_column() {
+ let (mut session, mut view) = session("line one\nline two");
+ session.set_caret(&mut view, session.source().len(), false);
+ session.insert_text(&mut view, "!");
+ session.move_vertical(&mut view, -1, false);
+ assert!(view.preferred_column.is_some());
+
+ view.mode = EditorMode::ReadOnly;
+ assert!(!session.undo(&mut view));
+ assert_eq!(session.source(), "line one\nline two!");
+ assert!(session.can_undo());
+
+ view.mode = EditorMode::LivePreview;
+ assert!(session.undo(&mut view));
+ assert_eq!(session.source(), "line one\nline two");
+ assert_eq!(view.preferred_column, None);
+
+ session.move_vertical(&mut view, -1, false);
+ assert!(view.preferred_column.is_some());
+ assert!(session.redo(&mut view));
+ assert_eq!(session.source(), "line one\nline two!");
+ assert_eq!(view.preferred_column, None);
+ }
+
#[test]
fn unicode_word_selection_respects_words_punctuation_and_emoji() {
let (session, _) = session("hello, 世界 😀 done");
diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rs
index a0e406dd..bd82882c 100644
--- a/wezterm-gui/src/markdown_editor/host.rs
+++ b/wezterm-gui/src/markdown_editor/host.rs
@@ -4,7 +4,7 @@ use super::{
SourcePosition, SourceSelection, VaultDocument, VisualDocument, VisualWrapCache,
};
use parking_lot::Mutex;
-use std::collections::{HashMap, HashSet};
+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use std::time::SystemTime;
@@ -101,8 +101,9 @@ pub(crate) struct NoteHostState {
pub selection_granularity: SelectionGranularity,
pub drag_selection_base: Option<Range<usize>>,
pub drag_autoscroll_scheduled: bool,
- pub collapsed_code_blocks: HashSet<usize>,
- pub code_horizontal_offsets: HashMap<usize, f32>,
+ /// Ordered so paint can hash them each frame without sorting a copy.
+ pub collapsed_code_blocks: BTreeSet<usize>,
+ pub code_horizontal_offsets: BTreeMap<usize, f32>,
pub code_block_layouts: Vec<NoteCodeBlockLayout>,
pub spelling_issues: Arc<Vec<NoteSpellingIssue>>,
pub spelling_revision: Option<u64>,
@@ -113,6 +114,10 @@ pub(crate) struct NoteHostState {
pub native_text_input_token: u64,
pub parse_requested_revision: Option<u64>,
pub parse_in_flight_revision: Option<u64>,
+ /// The current projection reused cached wiki-link data but at least one
+ /// link had no cached resolution; a background parse round trip owes us
+ /// the authoritative vault lookup.
+ links_resolution_pending: bool,
background_wrap_preferred: bool,
background_wrap_requested_key: Option<NoteBackgroundWrapKey>,
background_wrap_generation: u64,
@@ -157,8 +162,8 @@ impl Default for NoteHostState {
selection_granularity: SelectionGranularity::Character,
drag_selection_base: None,
drag_autoscroll_scheduled: false,
- collapsed_code_blocks: HashSet::new(),
- code_horizontal_offsets: HashMap::new(),
+ collapsed_code_blocks: BTreeSet::new(),
+ code_horizontal_offsets: BTreeMap::new(),
code_block_layouts: vec![],
spelling_issues: Arc::new(vec![]),
spelling_revision: None,
@@ -169,6 +174,7 @@ impl Default for NoteHostState {
native_text_input_token: 0,
parse_requested_revision: None,
parse_in_flight_revision: None,
+ links_resolution_pending: false,
background_wrap_preferred: false,
background_wrap_requested_key: None,
background_wrap_generation: 0,
@@ -220,6 +226,7 @@ impl NoteHostState {
self.native_text_input_snapshot_key = None;
self.parse_requested_revision = None;
self.parse_in_flight_revision = None;
+ self.links_resolution_pending = false;
self.background_wrap_preferred = false;
self.background_wrap_requested_key = None;
let snapshot = self
@@ -241,11 +248,7 @@ impl NoteHostState {
let end = progressive_preview_end(&snapshot.source, PROGRESSIVE_PREVIEW_BYTES);
let source = &snapshot.source[..end];
self.projection = MarkdownProjection::parse(source);
- let active_start = self
- .projection
- .active_syntax(0)
- .map(|node| node.source.start)
- .unwrap_or(usize::MAX);
+ let active_start = self.projection.caret_reveal_start(0);
self.visual = Arc::new(build_visual_document(
source,
&self.projection,
@@ -273,6 +276,7 @@ impl NoteHostState {
self.line_geometry = Arc::new(vec![]);
self.parse_requested_revision = None;
self.parse_in_flight_revision = None;
+ self.links_resolution_pending = false;
self.background_wrap_preferred = false;
self.background_wrap_requested_key = None;
}
@@ -308,6 +312,19 @@ impl NoteHostState {
true
}
+ /// The exact snapshot this host currently displays. Background work
+ /// (link resolution, large-note parsing) must operate on this snapshot —
+ /// not the live session — or a Published host sharing a dirty session
+ /// would parse text it is not showing.
+ fn display_snapshot(&self) -> Option<DocumentSnapshot> {
+ let session = self.session.as_ref()?;
+ Some(match &self.display_source {
+ NoteDisplaySource::Published => session.lock().published_snapshot(),
+ NoteDisplaySource::Live => session.lock().current_snapshot(),
+ NoteDisplaySource::Frozen(snapshot) => snapshot.clone(),
+ })
+ }
+
pub(crate) fn refresh_projection(&mut self) {
let Some(session) = self.session.as_ref().cloned() else {
return;
@@ -361,32 +378,41 @@ impl NoteHostState {
})
.collect::<HashMap<_, _>>();
let mut projection = MarkdownProjection::parse(source);
- if matches!(self.display_source, NoteDisplaySource::Published) {
- if let Some(document) = self.document.as_ref() {
- projection.resolve_vault_links(&document.vault_root, &document.relative_path);
- }
- } else {
- for object in &mut projection.objects {
- let ProjectedObject::WikiLink {
- target,
- embed,
- resolved_path,
- ambiguous_paths,
- rendered_lines,
- ..
- } = object
- else {
- continue;
- };
- if let Some((cached_path, cached_ambiguous_paths, cached_lines)) =
- cached_links.get(&(target.clone(), *embed))
- {
- *resolved_path = cached_path.clone();
- *ambiguous_paths = cached_ambiguous_paths.clone();
- *rendered_lines = cached_lines.clone();
- }
+ // Never walk the vault (or read embedded notes) on the UI thread:
+ // reuse the previous projection's resolutions for immediate paint
+ // and let the background parse worker do the authoritative lookup.
+ let mut links_missing_resolution = false;
+ let mut any_links = false;
+ for object in &mut projection.objects {
+ let ProjectedObject::WikiLink {
+ target,
+ embed,
+ resolved_path,
+ ambiguous_paths,
+ rendered_lines,
+ ..
+ } = object
+ else {
+ continue;
+ };
+ any_links = true;
+ if let Some((cached_path, cached_ambiguous_paths, cached_lines)) =
+ cached_links.get(&(target.clone(), *embed))
+ {
+ *resolved_path = cached_path.clone();
+ *ambiguous_paths = cached_ambiguous_paths.clone();
+ *rendered_lines = cached_lines.clone();
+ } else {
+ links_missing_resolution = true;
}
}
+ // Published projections used to re-resolve on every reparse, which
+ // is what picks up created/renamed targets and edited embeds; keep
+ // that freshness, just on the worker instead of the UI thread.
+ // Live/Frozen keep the old cache-authoritative behavior and only
+ // owe a round trip for links the cache has never seen.
+ self.links_resolution_pending = links_missing_resolution
+ || (any_links && matches!(self.display_source, NoteDisplaySource::Published));
self.projection = projection;
let code_starts = self
.projection
@@ -410,9 +436,7 @@ impl NoteHostState {
}
let active_start = self
.projection
- .active_syntax(self.view.selection.focus.byte)
- .map(|node| node.source.start)
- .unwrap_or(usize::MAX);
+ .caret_reveal_start(self.view.selection.focus.byte);
let key = (revision, self.view.mode, active_start);
if self.visual_key != Some(key) {
if projection_stage.is_none() {
@@ -445,11 +469,10 @@ impl NoteHostState {
usize,
Option<(std::path::PathBuf, String)>,
)> {
- let session = self.session.as_ref()?.clone();
- let snapshot = session.lock().current_snapshot();
- if snapshot.source.len() <= BACKGROUND_PARSE_THRESHOLD_BYTES
- || self.projection_revision == Some(snapshot.revision)
- {
+ let snapshot = self.display_snapshot()?;
+ let needs_full_parse = snapshot.source.len() > BACKGROUND_PARSE_THRESHOLD_BYTES
+ && self.projection_revision != Some(snapshot.revision);
+ if !needs_full_parse && !self.links_resolution_pending {
return None;
}
self.parse_requested_revision = Some(snapshot.revision);
@@ -482,21 +505,19 @@ impl NoteHostState {
return false;
}
self.parse_in_flight_revision = None;
- let current_revision = self
- .session
- .as_ref()
- .map(|session| session.lock().revision());
- if current_revision != Some(revision)
+ let display_revision = self
+ .display_snapshot()
+ .map(|snapshot| snapshot.revision);
+ if display_revision != Some(revision)
|| self.view.mode != mode
|| self.view.selection.focus.byte != caret
{
return false;
}
- let active_start = projection
- .active_syntax(caret)
- .map(|node| node.source.start)
- .unwrap_or(usize::MAX);
+ let active_start = projection.caret_reveal_start(caret);
self.projection = projection;
+ // The worker performed the authoritative vault-link resolution.
+ self.links_resolution_pending = false;
self.visual = Arc::new(visual);
self.background_wrap_preferred =
self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;
@@ -573,11 +594,11 @@ impl NoteHostState {
}
pub(crate) fn background_parse_pending(&self) -> bool {
- let current = self
- .session
- .as_ref()
- .map(|session| session.lock().revision());
- current.is_some_and(|revision| self.projection_revision != Some(revision))
+ if self.links_resolution_pending {
+ return self.session.is_some();
+ }
+ self.display_snapshot()
+ .is_some_and(|snapshot| self.projection_revision != Some(snapshot.revision))
}
pub(crate) fn begin_live_editing(&mut self) {
@@ -1051,6 +1072,72 @@ mod state_tests {
assert!(host.background_parse_request().is_some());
}
+ #[test]
+ fn small_note_wiki_links_resolve_via_background_parse_not_ui_thread() {
+ let source = "See [[Other Note]] for details.";
+ let mut host = host_with_source(source);
+ // The synchronous refresh reused (empty) cached link data, so it owes
+ // a background round trip for the authoritative vault lookup.
+ assert!(host.background_parse_pending());
+ let (revision, request_source, mode, caret, _) =
+ host.background_parse_request().expect("resolution request");
+ assert_eq!(request_source.as_ref(), source);
+
+ // Single flight while the worker runs.
+ assert!(host.background_parse_request().is_none());
+
+ let resolved = MarkdownProjection::parse(source);
+ let visual = build_visual_document(source, &resolved, mode, caret);
+ assert!(host.apply_background_parse(revision, mode, caret, resolved, visual));
+ assert!(!host.background_parse_pending());
+ assert!(host.background_parse_request().is_none());
+ }
+
+ #[test]
+ fn published_host_resolves_links_for_the_displayed_snapshot_not_the_live_one() {
+ let mut host = host_with_source("See [[Other]]");
+ let session = host.session.as_ref().unwrap().clone();
+ let mut other_view = EditorViewState::default();
+ let end = session.lock().source().len();
+ session.lock().set_caret(&mut other_view, end, false);
+ assert!(session.lock().insert_text(&mut other_view, " and [[Extra]]"));
+
+ // The Published host must request its displayed (published) snapshot,
+ // not the newer dirty session text.
+ let (revision, source, mode, caret, _) =
+ host.background_parse_request().expect("resolution request");
+ assert_eq!(source.as_ref(), "See [[Other]]");
+ assert_eq!(revision, 0);
+
+ let resolved = MarkdownProjection::parse(&source);
+ let visual = build_visual_document(&source, &resolved, mode, caret);
+ assert!(host.apply_background_parse(revision, mode, caret, resolved, visual));
+ // Settled: no repeated background parsing while the session stays
+ // dirty and the display stays Published.
+ assert!(!host.background_parse_pending());
+ assert!(host.background_parse_request().is_none());
+ }
+
+ #[test]
+ fn published_reparse_rechecks_vault_links_even_on_cache_hits() {
+ let mut host = host_with_source("See [[Other]]");
+ let (revision, source, mode, caret, _) =
+ host.background_parse_request().expect("initial resolution");
+ let resolved = MarkdownProjection::parse(&source);
+ let visual = build_visual_document(&source, &resolved, mode, caret);
+ assert!(host.apply_background_parse(revision, mode, caret, resolved, visual));
+ assert!(!host.background_parse_pending());
+
+ // An external writer changed the note; the link target may have
+ // changed on disk too, so a cache hit must not suppress the
+ // background re-resolution the old synchronous path performed.
+ let external = "Also see [[Other]].".to_string();
+ let len = external.len() as u64;
+ assert!(host.apply_external_snapshot(SystemTime::now(), len, external));
+ assert!(host.background_parse_pending());
+ assert!(host.background_parse_request().is_some());
+ }
+
#[test]
fn published_host_ignores_unsaved_shared_revision() {
let mut host = host_with_source("saved");
diff --git a/wezterm-gui/src/markdown_editor/mod.rs b/wezterm-gui/src/markdown_editor/mod.rs
index a40a861d..a3e62770 100644
--- a/wezterm-gui/src/markdown_editor/mod.rs
+++ b/wezterm-gui/src/markdown_editor/mod.rs
@@ -7,7 +7,6 @@
mod document;
mod host;
mod projection;
-#[allow(dead_code)] // Removed once the Note paint host starts scheduling loads.
mod remote_image;
mod spellcheck;
mod store;
@@ -24,8 +23,7 @@ pub(crate) use host::{
pub(crate) use projection::{
BlockKind, InlineStyle, MarkdownProjection, ProjectedCodeBlock, ProjectedObject, TableAlignment,
};
-#[allow(unused_imports)] // Standalone API for the pending Note host integration.
-pub(crate) use remote_image::{load_remote_image, RemoteImage};
+pub(crate) use remote_image::load_remote_image;
pub(crate) use spellcheck::{build_spell_check_chunks_in_range, NoteSpellingIssue};
pub(crate) use store::{
import_attachment, open_vault_document, resolve_local_image, save_document_revision,
diff --git a/wezterm-gui/src/markdown_editor/projection.rs b/wezterm-gui/src/markdown_editor/projection.rs
index 6c5f362d..1d84e483 100644
--- a/wezterm-gui/src/markdown_editor/projection.rs
+++ b/wezterm-gui/src/markdown_editor/projection.rs
@@ -634,6 +634,22 @@ impl MarkdownProjection {
.min_by_key(|node| node.source.end.saturating_sub(node.source.start))
}
+ /// Cache key for caret-dependent syntax reveal in Live Preview. Must agree
+ /// with `build_visual_document`: frontmatter reveals only for a strictly
+ /// interior caret, so its boundary positions map to "nothing revealed".
+ pub(crate) fn caret_reveal_start(&self, byte: usize) -> usize {
+ match self.active_syntax(byte) {
+ Some(node)
+ if node.kind == MarkdownSyntaxKind::Frontmatter
+ && !(node.source.start < byte && byte < node.source.end) =>
+ {
+ usize::MAX
+ }
+ Some(node) => node.source.start,
+ None => usize::MAX,
+ }
+ }
+
pub(crate) fn active_block_range(&self, byte: usize) -> Option<Range<usize>> {
let end = self
.blocks
@@ -689,6 +705,12 @@ fn range_is_literal_code_or_frontmatter(
})
}
+/// The source range of a leading YAML frontmatter block, if present. Shared
+/// with spellcheck so both agree on what counts as frontmatter.
+pub(crate) fn frontmatter_range(source: &str) -> Option<Range<usize>> {
+ parse_frontmatter(source).map(|(range, _)| range)
+}
+
fn parse_frontmatter(source: &str) -> Option<(Range<usize>, Vec<ProjectedProperty>)> {
let opening_end = source
.strip_prefix("---\n")
diff --git a/wezterm-gui/src/markdown_editor/spellcheck.rs b/wezterm-gui/src/markdown_editor/spellcheck.rs
index 81594dcc..1182669c 100644
--- a/wezterm-gui/src/markdown_editor/spellcheck.rs
+++ b/wezterm-gui/src/markdown_editor/spellcheck.rs
@@ -222,11 +222,7 @@ fn ranges_intersect(a: &Range<usize>, b: &Range<usize>) -> bool {
}
fn front_matter_range(source: &str) -> Option<Range<usize>> {
- if !source.starts_with("---\n") {
- return None;
- }
- let end = source[4..].find("\n---").map(|offset| 4 + offset + 4)?;
- Some(0..end.min(source.len()))
+ super::projection::frontmatter_range(source)
}
#[cfg(test)]
@@ -249,6 +245,34 @@ mod tests {
assert!(!text.contains("let mistke"));
}
+ #[test]
+ fn unclosed_frontmatter_does_not_swallow_prose_before_a_dash_line() {
+ // The opening `---` is never closed by an exact `---` line, so this is
+ // not frontmatter; every prose line must still be spellchecked.
+ let source = "---\ntitlee: draft\n--- not a closing fence\nProse eror here.\n";
+ let projection = MarkdownProjection::parse(source);
+ let text = build_spell_check_chunks(source, &projection)
+ .into_iter()
+ .map(|chunk| chunk.text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(text.contains("titlee"));
+ assert!(text.contains("Prose eror"));
+ }
+
+ #[test]
+ fn crlf_frontmatter_is_excluded_from_spellcheck() {
+ let source = "---\r\ntitle: Helo\r\n---\r\n\r\nProse mistke.\r\n";
+ let projection = MarkdownProjection::parse(source);
+ let text = build_spell_check_chunks(source, &projection)
+ .into_iter()
+ .map(|chunk| chunk.text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(!text.contains("Helo"));
+ assert!(text.contains("Prose mistke"));
+ }
+
#[test]
fn maps_check_ranges_back_to_markdown_source() {
let source = "A **mistke** here";
diff --git a/wezterm-gui/src/markdown_editor/surface.rs b/wezterm-gui/src/markdown_editor/surface.rs
index b1e99c0e..9aafaf26 100644
--- a/wezterm-gui/src/markdown_editor/surface.rs
+++ b/wezterm-gui/src/markdown_editor/surface.rs
@@ -609,15 +609,21 @@ pub(crate) fn build_visual_document(
if let Some(object) = objects.get(object_index) {
let range = object.source();
if range.start == idx && range.end > range.start {
- if range.start <= caret
+ let reveal = (range.start <= caret
&& caret <= range.end
&& matches!(
object,
ProjectedObject::WikiLink { .. }
| ProjectedObject::Callout { .. }
| ProjectedObject::BlockId { .. }
- )
- {
+ ))
+ // Frontmatter reveals only when the caret is strictly
+ // inside it, so a freshly opened document (caret at 0)
+ // keeps the projected Properties view.
+ || (range.start < caret
+ && caret < range.end
+ && matches!(object, ProjectedObject::Frontmatter { .. }));
+ if reveal {
append_revealed_source_range(
&mut lines,
&mut line,
@@ -1216,6 +1222,31 @@ mod tests {
assert!(text.contains("tags:"));
}
+ #[test]
+ fn live_preview_reveals_raw_frontmatter_when_caret_is_strictly_inside() {
+ let source = "---\ntitle: Example\ntags:\n - notes\n---\n\n# Body\n";
+ let projection = MarkdownProjection::parse(source);
+ let caret = source.find("Example").unwrap();
+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, caret);
+ let text = doc
+ .lines
+ .iter()
+ .map(VisualLine::text)
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(text.contains("---"));
+ assert!(text.contains("title: Example"));
+ assert!(text.contains(" - notes"));
+
+ // The reveal-vs-projected states must hash to different visual keys so
+ // the host rebuilds when the caret enters or leaves the frontmatter.
+ assert_ne!(
+ projection.caret_reveal_start(caret),
+ projection.caret_reveal_start(0)
+ );
+ }
+
#[test]
fn live_preview_projects_table_and_task_object() {
let source = "- [x] done\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 1b064718..c6314231 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -195,6 +195,8 @@ pub(crate) struct NativeChromeSettings {
pub(crate) workspace_sidebar_width: Option<usize>,
pub(crate) right_sidebar_width: Option<usize>,
pub(crate) right_sidebar_file_preview_width: Option<usize>,
+ pub(crate) right_sidebar_note_pane_width: Option<usize>,
+ pub(crate) right_sidebar_note_pane_expanded: Option<bool>,
pub(crate) right_sidebar_open_with_app: Option<NativeOpenWithApp>,
pub(crate) right_sidebar_custom_open_with_apps: Vec<NativeOpenWithApp>,
pub(crate) tab_font_size: Option<f64>,
@@ -459,6 +461,17 @@ pub(crate) fn right_sidebar_file_preview_width() -> Option<usize> {
load().chrome.right_sidebar_file_preview_width
}
+pub(crate) fn right_sidebar_note_pane_width() -> Option<usize> {
+ load().chrome.right_sidebar_note_pane_width
+}
+
+pub(crate) fn right_sidebar_note_pane_expanded() -> bool {
+ load()
+ .chrome
+ .right_sidebar_note_pane_expanded
+ .unwrap_or(false)
+}
+
pub(crate) fn right_sidebar_open_with_app() -> Option<NativeOpenWithApp> {
load().chrome.right_sidebar_open_with_app
}
@@ -480,6 +493,18 @@ pub(crate) fn save_right_sidebar_file_preview_width(width: usize) -> anyhow::Res
save(&settings)
}
+pub(crate) fn save_right_sidebar_note_pane_width(width: usize) -> anyhow::Result<()> {
+ let mut settings = load();
+ settings.chrome.right_sidebar_note_pane_width = Some(width);
+ save(&settings)
+}
+
+pub(crate) fn save_right_sidebar_note_pane_expanded(expanded: bool) -> anyhow::Result<()> {
+ let mut settings = load();
+ settings.chrome.right_sidebar_note_pane_expanded = Some(expanded);
+ save(&settings)
+}
+
pub(crate) fn save_right_sidebar_open_with_app(app: NativeOpenWithApp) -> anyhow::Result<()> {
let mut settings = load();
settings.chrome.right_sidebar_open_with_app = Some(app);
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index e1b7f621..6e5ba46e 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -346,6 +346,8 @@ pub enum UIItemType {
RightSidebarNoteCodeToggle(usize),
RightSidebarNoteCodeCopy(usize),
RightSidebarNoteBody,
+ RightSidebarNotePaneToggle,
+ RightSidebarNotePaneResize,
RightSidebarFilePreviewScrollTrack,
RightSidebarFilePreviewScrollThumb,
RightSidebarFilePreviewHorizontalScrollTrack,
@@ -1097,7 +1099,7 @@ pub struct TermWindow {
right_sidebar_note_tree_expanded: HashSet<String>,
right_sidebar_note_vault_tree_collapsed: bool,
right_sidebar_note_wide_layout: bool,
- right_sidebar_note_table_horizontal_offsets: HashMap<usize, f32>,
+ right_sidebar_note_table_horizontal_offsets: std::collections::BTreeMap<usize, f32>,
right_sidebar_note_table_layouts: Vec<RightSidebarNoteTableLayout>,
right_sidebar_note_images: HashMap<RightSidebarNoteImageSource, RightSidebarFilePreviewImage>,
right_sidebar_note_images_loading: HashSet<RightSidebarNoteImageSource>,
@@ -1133,6 +1135,8 @@ pub struct TermWindow {
right_sidebar_file_selected: Option<PathBuf>,
right_sidebar_file_tree_width: usize,
right_sidebar_file_preview_width: usize,
+ right_sidebar_note_pane_expanded: bool,
+ right_sidebar_note_pane_width: usize,
right_sidebar_file_preview_generation: u64,
right_sidebar_file_preview_highlight_cancel: Arc<AtomicUsize>,
right_sidebar_file_preview_lines: Vec<RightSidebarFilePreviewLine>,
@@ -1740,7 +1744,7 @@ impl TermWindow {
right_sidebar_note_tree_expanded: HashSet::new(),
right_sidebar_note_vault_tree_collapsed: false,
right_sidebar_note_wide_layout: false,
- right_sidebar_note_table_horizontal_offsets: HashMap::new(),
+ right_sidebar_note_table_horizontal_offsets: std::collections::BTreeMap::new(),
right_sidebar_note_table_layouts: Vec::new(),
right_sidebar_note_images: HashMap::new(),
right_sidebar_note_images_loading: HashSet::new(),
@@ -1776,6 +1780,9 @@ impl TermWindow {
dpi as usize,
),
right_sidebar_file_preview_width: ui::right_sidebar_file_preview_width(dpi as usize),
+ right_sidebar_note_pane_expanded:
+ crate::native_settings::right_sidebar_note_pane_expanded(),
+ right_sidebar_note_pane_width: ui::right_sidebar_note_pane_width_for_dpi(dpi as usize),
right_sidebar_file_preview_generation: 0,
right_sidebar_file_preview_highlight_cancel: Arc::new(AtomicUsize::new(0)),
right_sidebar_file_preview_lines: Vec::new(),
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 0112cc9c..95523835 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -887,6 +887,8 @@ impl super::TermWindow {
| UIItemType::RightSidebarBackground
| UIItemType::RightSidebarResize
| UIItemType::RightSidebarFilePreviewResize
+ | UIItemType::RightSidebarNotePaneResize
+ | UIItemType::RightSidebarNotePaneToggle
| UIItemType::RightSidebarSnippetNew
| UIItemType::RightSidebarSnippetBack
| UIItemType::RightSidebarSnippetSave
@@ -960,6 +962,8 @@ impl super::TermWindow {
| UIItemType::RightSidebarBackground
| UIItemType::RightSidebarResize
| UIItemType::RightSidebarFilePreviewResize
+ | UIItemType::RightSidebarNotePaneResize
+ | UIItemType::RightSidebarNotePaneToggle
| UIItemType::RightSidebarSnippetNew
| UIItemType::RightSidebarSnippetBack
| UIItemType::RightSidebarSnippetSave
@@ -1196,6 +1200,13 @@ impl super::TermWindow {
}) {
self.persist_right_sidebar_file_preview_width();
}
+ if completed_drag.as_ref().is_some_and(|(item, _)| {
+ item.item_type == UIItemType::RightSidebarNotePaneResize
+ || (item.item_type == UIItemType::RightSidebarResize
+ && self.right_sidebar_note_pane_rect().is_some())
+ }) {
+ self.persist_right_sidebar_note_pane_width();
+ }
if completed_drag
.as_ref()
.is_some_and(|(item, _)| matches!(item.item_type, UIItemType::Split(_)))
@@ -1771,6 +1782,9 @@ impl super::TermWindow {
UIItemType::RightSidebarFilePreviewResize => {
self.drag_right_sidebar_file_preview_resize(item, start_event, event, context);
}
+ UIItemType::RightSidebarNotePaneResize => {
+ self.drag_right_sidebar_note_pane_resize(item, start_event, event, context);
+ }
UIItemType::RightSidebarSnippetScrollThumb => {
self.drag_right_sidebar_snippet_scroll_thumb(item, start_event, event, context);
}
@@ -1924,6 +1938,8 @@ impl super::TermWindow {
self.expand_right_sidebar();
if self.right_sidebar_file_preview_rect().is_some() {
self.set_right_sidebar_file_preview_total_width(width);
+ } else if self.right_sidebar_note_pane_rect().is_some() {
+ self.set_right_sidebar_note_pane_total_width(width);
} else {
self.set_right_sidebar_width(width);
}
@@ -1946,6 +1962,20 @@ impl super::TermWindow {
self.dragging.replace((item, start_event));
}
+ fn drag_right_sidebar_note_pane_resize(
+ &mut self,
+ item: UIItem,
+ start_event: MouseEvent,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ if self.set_right_sidebar_note_pane_split_x(event.coords.x) {
+ context.invalidate();
+ }
+ context.set_cursor(Some(MouseCursor::SizeLeftRight));
+ self.dragging.replace((item, start_event));
+ }
+
fn mouse_event_ui_item(
&mut self,
item: UIItem,
@@ -2058,6 +2088,9 @@ impl super::TermWindow {
UIItemType::RightSidebarFilePreviewResize => {
self.mouse_event_right_sidebar_file_preview_resize(item, event, context);
}
+ UIItemType::RightSidebarNotePaneResize => {
+ self.mouse_event_right_sidebar_note_pane_resize(item, event, context);
+ }
UIItemType::RightSidebarSnippetScrollTrack => {
self.mouse_event_right_sidebar_snippet_scroll_track(item, event, context);
}
@@ -2103,7 +2136,8 @@ impl super::TermWindow {
| UIItemType::RightSidebarNoteTreeRow(_)
| UIItemType::RightSidebarNoteCodeToggle(_)
| UIItemType::RightSidebarNoteCodeCopy(_)
- | UIItemType::RightSidebarNoteBody => {
+ | UIItemType::RightSidebarNoteBody
+ | UIItemType::RightSidebarNotePaneToggle => {
self.mouse_event_right_sidebar_note(item.clone(), event, context);
}
UIItemType::RightSidebarFileFilter
@@ -2184,6 +2218,13 @@ impl super::TermWindow {
context.invalidate();
}
}
+ UIItemType::RightSidebarNotePaneToggle => {
+ context.set_cursor(Some(MouseCursor::Hand));
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.toggle_right_sidebar_note_pane();
+ context.invalidate();
+ }
+ }
UIItemType::RightSidebarNoteTreeBack => {
context.set_cursor(Some(MouseCursor::Hand));
if event.kind == WMEK::Press(MousePress::Left) {
@@ -2535,6 +2576,9 @@ impl super::TermWindow {
UIItemType::RightSidebarFilePreviewResize => {
self.mouse_event_right_sidebar_file_preview_resize(item, event, context);
}
+ UIItemType::RightSidebarNotePaneResize => {
+ self.mouse_event_right_sidebar_note_pane_resize(item, event, context);
+ }
UIItemType::RightSidebarSnippetScrollTrack => {
self.mouse_event_right_sidebar_snippet_scroll_track(item, event, context);
}
@@ -2580,7 +2624,8 @@ impl super::TermWindow {
| UIItemType::RightSidebarNoteTreeRow(_)
| UIItemType::RightSidebarNoteCodeToggle(_)
| UIItemType::RightSidebarNoteCodeCopy(_)
- | UIItemType::RightSidebarNoteBody => {
+ | UIItemType::RightSidebarNoteBody
+ | UIItemType::RightSidebarNotePaneToggle => {
self.mouse_event_right_sidebar_note(item.clone(), event, context);
}
UIItemType::RightSidebarFileFilter
@@ -2734,6 +2779,18 @@ impl super::TermWindow {
}
}
+ pub fn mouse_event_right_sidebar_note_pane_resize(
+ &mut self,
+ item: UIItem,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::SizeLeftRight));
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.dragging.replace((item, event));
+ }
+ }
+
pub fn mouse_event_right_sidebar_snippet_scroll_thumb(
&mut self,
item: UIItem,
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index f7938001..366d6a6a 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -656,6 +656,8 @@ impl super::TermWindow {
rescale_ui_usize(self.right_sidebar_file_tree_width, old_dpi, new_dpi);
self.right_sidebar_file_preview_width =
rescale_ui_usize(self.right_sidebar_file_preview_width, old_dpi, new_dpi);
+ self.right_sidebar_note_pane_width =
+ rescale_ui_usize(self.right_sidebar_note_pane_width, old_dpi, new_dpi);
}
if scale_changed {
diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rs
index 21f0d6b3..11d280b3 100644
--- a/wezterm-gui/src/termwindow/ui/mod.rs
+++ b/wezterm-gui/src/termwindow/ui/mod.rs
@@ -8,7 +8,10 @@ pub mod tokens;
use crate::utilsprites::RenderMetrics;
-pub use right_sidebar::{right_sidebar_file_preview_width, right_sidebar_width_for_metrics};
+pub use right_sidebar::{
+ right_sidebar_file_preview_width, right_sidebar_note_pane_width_for_dpi,
+ right_sidebar_width_for_metrics,
+};
pub use sidebar::workspace_sidebar_width_for_metrics;
pub fn pane_nav_bar_height_for_metrics(render_metrics: RenderMetrics) -> usize {
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 9d321add..a4ff1ac8 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -123,6 +123,8 @@ const FILE_PREVIEW_IMAGE_MAX_BYTES: usize = 16 * 1024 * 1024;
const FILE_PREVIEW_IMAGE_MAX_PIXELS: u64 = 16_000_000;
const FILE_PREVIEW_PANE_MIN_WIDTH: usize = 360;
const FILE_PREVIEW_PANE_DEFAULT_WIDTH: usize = 560;
+const NOTE_PANE_MIN_WIDTH: usize = FILE_PREVIEW_PANE_MIN_WIDTH;
+const NOTE_PANE_DEFAULT_WIDTH: usize = FILE_PREVIEW_PANE_DEFAULT_WIDTH;
const FILE_PREVIEW_SLICE_CACHE_CAPACITY: usize = 256;
// Lines up to this many columns are shaped whole (once, cached) so horizontal
// scrolling is pure translation of the cached glyph run instead of re-shaping a
@@ -250,6 +252,18 @@ fn visible_code_block_rounded_edges(
(block_top >= viewport_top, block_bottom <= viewport_bottom)
}
+/// Hash an already-ordered sequence with the same shape as `Vec::hash`
+/// (length prefix + elements) so adjacent collections cannot alias.
+fn hash_ordered_iter<H: std::hash::Hasher, T: Hash>(
+ hasher: &mut H,
+ iter: impl ExactSizeIterator<Item = T>,
+) {
+ iter.len().hash(hasher);
+ for item in iter {
+ item.hash(hasher);
+ }
+}
+
fn virtual_note_line_range(
geometry: &[NoteLineGeometry],
scroll: f32,
@@ -258,7 +272,9 @@ fn virtual_note_line_range(
if geometry.is_empty() || viewport_height <= 0.0 {
return 0..0;
}
- let overscan = viewport_height * 2.0;
+ // Enough off-screen rows for drag-selection and caret hit-testing near the
+ // edges without paying for multiple invisible viewports per frame.
+ let overscan = viewport_height * 0.75;
let paint_top = (scroll - overscan).max(0.0);
let paint_bottom = scroll + viewport_height + overscan;
let start = geometry.partition_point(|line| line.top + line.height + line.gap < paint_top);
@@ -782,6 +798,14 @@ pub fn right_sidebar_file_preview_width(dpi: usize) -> usize {
.max(min_width)
}
+pub fn right_sidebar_note_pane_width_for_dpi(dpi: usize) -> usize {
+ let min_width = scale_ui_usize(NOTE_PANE_MIN_WIDTH, dpi);
+ crate::native_settings::right_sidebar_note_pane_width()
+ .map(|width| scale_ui_usize(width, dpi))
+ .unwrap_or_else(|| scale_ui_usize(NOTE_PANE_DEFAULT_WIDTH, dpi))
+ .max(min_width)
+}
+
impl crate::TermWindow {
fn right_sidebar_file_preview_active(&self) -> bool {
!self.right_sidebar_collapsed
@@ -809,7 +833,9 @@ impl crate::TermWindow {
.saturating_sub((border.left + border.right).get() as usize)
}
- fn right_sidebar_file_preview_total_max_width(&self) -> usize {
+ /// Maximum sidebar-column + expanded-pane total width. Shared by the file
+ /// preview pane and the Note pane; both keep a terminal reserve.
+ fn right_sidebar_pane_total_max_width(&self) -> usize {
let available_width = self.right_sidebar_available_width();
let content_width = available_width.saturating_sub(self.workspace_sidebar_width());
let min_preview_total =
@@ -831,7 +857,7 @@ impl crate::TermWindow {
}
let max_preview_width = self
- .right_sidebar_file_preview_total_max_width()
+ .right_sidebar_pane_total_max_width()
.saturating_sub(self.right_sidebar_tree_width());
if max_preview_width < self.ui_px(FILE_PREVIEW_PANE_MIN_WIDTH) {
return None;
@@ -847,14 +873,47 @@ impl crate::TermWindow {
Some(width)
}
+ pub(crate) fn right_sidebar_note_pane_active(&self) -> bool {
+ !self.right_sidebar_collapsed
+ && self.right_sidebar_mode == RightSidebarMode::Tasks
+ && self.right_sidebar_note_pane_expanded
+ // Without a vault there is no editor to expand; the sidebar shows
+ // the choose/create-vault UI inline instead of a blank pane.
+ && workspace_threads::space_note_vault(&self.active_space_id).is_some()
+ }
+
+ pub(crate) fn right_sidebar_note_pane_width(&self) -> Option<usize> {
+ if !self.right_sidebar_note_pane_active() {
+ return None;
+ }
+ let max_pane_width = self
+ .right_sidebar_pane_total_max_width()
+ .saturating_sub(self.right_sidebar_tree_width());
+ if max_pane_width < self.ui_px(NOTE_PANE_MIN_WIDTH) {
+ return None;
+ }
+ let configured_width = if self.right_sidebar_note_pane_width == 0 {
+ self.ui_px(NOTE_PANE_DEFAULT_WIDTH)
+ } else {
+ self.right_sidebar_note_pane_width
+ };
+ Some(configured_width.clamp(self.ui_px(NOTE_PANE_MIN_WIDTH), max_pane_width))
+ }
+
pub fn right_sidebar_width(&self) -> usize {
if self.right_sidebar_collapsed {
0
} else {
+ // The file preview pane and the Note pane are mutually exclusive
+ // (different sidebar modes); at most one is non-zero.
+ let pane_width = self
+ .right_sidebar_file_preview_width()
+ .or_else(|| self.right_sidebar_note_pane_width())
+ .unwrap_or(0);
self.right_sidebar_tree_width()
- .saturating_add(self.right_sidebar_file_preview_width().unwrap_or(0))
- .min(if self.right_sidebar_file_preview_active() {
- self.right_sidebar_file_preview_total_max_width()
+ .saturating_add(pane_width)
+ .min(if pane_width > 0 {
+ self.right_sidebar_pane_total_max_width()
} else {
self.right_sidebar_available_width()
})
@@ -916,7 +975,7 @@ impl crate::TermWindow {
}
let max_preview_width = self
- .right_sidebar_file_preview_total_max_width()
+ .right_sidebar_pane_total_max_width()
.saturating_sub(self.right_sidebar_tree_width());
if max_preview_width < self.ui_px(FILE_PREVIEW_PANE_MIN_WIDTH) {
return false;
@@ -928,6 +987,26 @@ impl crate::TermWindow {
old_width != self.right_sidebar_file_preview_width
}
+ pub(crate) fn set_right_sidebar_note_pane_total_width(&mut self, width: usize) -> bool {
+ if !self.right_sidebar_note_pane_active() {
+ return false;
+ }
+
+ let tree_width = self.right_sidebar_tree_width();
+ let pane_width = width.saturating_sub(tree_width);
+ let max_pane_width = self
+ .right_sidebar_pane_total_max_width()
+ .saturating_sub(tree_width);
+ if max_pane_width < self.ui_px(NOTE_PANE_MIN_WIDTH) {
+ return false;
+ }
+
+ let old_width = self.right_sidebar_note_pane_width;
+ self.right_sidebar_note_pane_width =
+ pane_width.clamp(self.ui_px(NOTE_PANE_MIN_WIDTH), max_pane_width);
+ old_width != self.right_sidebar_note_pane_width
+ }
+
pub fn persist_right_sidebar_width(&self) {
let width = self.right_sidebar_width.clamp(
self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH),
@@ -1379,7 +1458,7 @@ impl crate::TermWindow {
if !self.right_sidebar_file_preview_active() {
let max_tree_for_preview = self
- .right_sidebar_file_preview_total_max_width()
+ .right_sidebar_pane_total_max_width()
.saturating_sub(self.ui_px(FILE_PREVIEW_PANE_MIN_WIDTH))
.max(self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH));
self.right_sidebar_file_tree_width = self
@@ -3403,7 +3482,9 @@ impl crate::TermWindow {
}
fn handle_right_sidebar_note_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {
- self.right_sidebar_note.begin_live_editing();
+ // begin_live_editing() is deliberately deferred until a key is known
+ // to be handled: an unrelated key must not flip the display source to
+ // Live and invalidate the projection caches.
let shift = mods.contains(TermModifiers::SHIFT);
let super_ = mods.contains(TermModifiers::SUPER);
let ctrl = mods.contains(TermModifiers::CTRL);
@@ -3415,10 +3496,16 @@ impl crate::TermWindow {
ctrl && !super_ && !alt
};
- if word_modifier {
+ if word_modifier
+ && matches!(
+ key,
+ TermKeyCode::LeftArrow | TermKeyCode::RightArrow | TermKeyCode::Backspace
+ )
+ {
let Some(session) = self.right_sidebar_note.session.clone() else {
return false;
};
+ self.right_sidebar_note.begin_live_editing();
match key {
TermKeyCode::LeftArrow => {
session
@@ -3450,6 +3537,17 @@ impl crate::TermWindow {
}
if command && !alt {
+ let command_handled = match key {
+ TermKeyCode::LeftArrow | TermKeyCode::RightArrow => super_,
+ TermKeyCode::Char(
+ 'a' | 'A' | 'c' | 'C' | 'x' | 'X' | 'v' | 'V' | 'z' | 'Z' | 's' | 'S' | 'e'
+ | 'E' | 'b' | 'B' | 'i' | 'I',
+ ) => true,
+ _ => false,
+ };
+ if command_handled {
+ self.right_sidebar_note.begin_live_editing();
+ }
match key {
TermKeyCode::LeftArrow if super_ => {
if let Some(session) = self.right_sidebar_note.session.clone() {
@@ -3544,9 +3642,27 @@ impl crate::TermWindow {
return false;
}
+ let will_handle = matches!(
+ key,
+ TermKeyCode::Escape
+ | TermKeyCode::LeftArrow
+ | TermKeyCode::RightArrow
+ | TermKeyCode::UpArrow
+ | TermKeyCode::DownArrow
+ | TermKeyCode::Home
+ | TermKeyCode::End
+ | TermKeyCode::Backspace
+ | TermKeyCode::Delete
+ | TermKeyCode::Enter
+ | TermKeyCode::Tab
+ ) || matches!(key, TermKeyCode::Char(ch) if !ch.is_control());
+ if !will_handle {
+ return false;
+ }
let Some(session) = self.right_sidebar_note.session.clone() else {
return false;
};
+ self.right_sidebar_note.begin_live_editing();
let mut changed = false;
let handled = match key {
TermKeyCode::Escape => {
@@ -3638,7 +3754,20 @@ impl crate::TermWindow {
.lock()
.set_caret(&mut self.right_sidebar_note.view, target, false);
self.right_sidebar_note.reveal_caret = true;
- } else {
+ } else if session
+ .lock()
+ .tab_indents_lines(&self.right_sidebar_note.view)
+ {
+ changed = if shift {
+ session
+ .lock()
+ .outdent_lines(&mut self.right_sidebar_note.view)
+ } else {
+ session
+ .lock()
+ .indent_lines(&mut self.right_sidebar_note.view)
+ };
+ } else if !shift {
changed = session
.lock()
.insert_text(&mut self.right_sidebar_note.view, " ");
@@ -4452,6 +4581,83 @@ impl crate::TermWindow {
old_preview != self.right_sidebar_file_preview_width || tree_changed
}
+ pub(crate) fn right_sidebar_note_pane_rect(&self) -> Option<RightSidebarRect> {
+ let sidebar = self.right_sidebar_rect()?;
+ let width = self.right_sidebar_note_pane_width()?;
+ if sidebar.width <= width {
+ return None;
+ }
+ Some(RightSidebarRect {
+ x: sidebar.x,
+ y: sidebar.y,
+ width,
+ height: sidebar.height,
+ })
+ }
+
+ pub(crate) fn set_right_sidebar_note_pane_split_x(&mut self, split_x: isize) -> bool {
+ let Some(total_rect) = self.right_sidebar_rect() else {
+ return false;
+ };
+ if self.right_sidebar_note_pane_rect().is_none() {
+ return false;
+ }
+
+ let total_left = total_rect.x;
+ let total_right = total_rect.x.saturating_add(total_rect.width);
+ let min_pane = self.ui_px(NOTE_PANE_MIN_WIDTH);
+ let max_pane = total_rect
+ .width
+ .saturating_sub(self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH));
+ let min_tree = self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH);
+ let max_tree = self.right_sidebar_max_width().min(total_rect.width);
+ let min_split = total_left
+ .saturating_add(min_pane)
+ .max(total_right.saturating_sub(max_tree));
+ let max_split = total_right
+ .saturating_sub(min_tree)
+ .min(total_left.saturating_add(max_pane));
+ if min_split > max_split {
+ return false;
+ }
+
+ let split_x = split_x.clamp(min_split as isize, max_split as isize) as usize;
+ let pane_width = split_x.saturating_sub(total_left);
+ let tree_width = total_right.saturating_sub(split_x);
+ let old_pane = self.right_sidebar_note_pane_width;
+ self.right_sidebar_note_pane_width = pane_width;
+ let old_tree = self.right_sidebar_width;
+ self.set_right_sidebar_width(tree_width);
+ old_pane != self.right_sidebar_note_pane_width || old_tree != self.right_sidebar_width
+ }
+
+ pub fn persist_right_sidebar_note_pane_width(&self) {
+ let width = self
+ .right_sidebar_note_pane_width()
+ .unwrap_or(self.right_sidebar_note_pane_width)
+ .max(self.ui_px(NOTE_PANE_MIN_WIDTH));
+ let width = unscale_ui_usize(width, self.dimensions.dpi);
+ if let Err(err) = crate::native_settings::save_right_sidebar_note_pane_width(width) {
+ log::warn!("failed to save right sidebar Note pane width: {err:#}");
+ }
+ }
+
+ pub(crate) fn toggle_right_sidebar_note_pane(&mut self) {
+ self.right_sidebar_note_pane_expanded = !self.right_sidebar_note_pane_expanded;
+ if let Err(err) = crate::native_settings::save_right_sidebar_note_pane_expanded(
+ self.right_sidebar_note_pane_expanded,
+ ) {
+ log::warn!("failed to save right sidebar Note pane mode: {err:#}");
+ }
+ // The sidebar total width changed; reflow the terminal like the file
+ // preview open/close paths do.
+ if let Some(window) = self.window.as_ref().cloned() {
+ let dimensions = self.dimensions;
+ self.apply_dimensions(&dimensions, None, &window);
+ window.invalidate();
+ }
+ }
+
fn right_sidebar_file_preview_font_size(&self) -> f64 {
let settings = crate::native_settings::load();
let base_font_size = crate::native_settings::home_font_size(&settings);
@@ -4893,6 +5099,56 @@ impl crate::TermWindow {
)?;
}
+ if let Some(pane_rect) = self.right_sidebar_note_pane_rect() {
+ // Chrome only; paint_note_sidebar paints the editor into this
+ // rect later in the frame.
+ if pane_rect.y > 0 {
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ pane_rect.x as f32,
+ 0.0,
+ pane_rect.width as f32,
+ pane_rect.y as f32,
+ ),
+ sidebar_bg,
+ )
+ .context("right sidebar note pane top background")?;
+ }
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ pane_rect.x as f32,
+ pane_rect.y as f32,
+ pane_rect.width as f32,
+ pane_rect.height as f32,
+ ),
+ sidebar_bg,
+ )
+ .context("right sidebar note pane background")?;
+ self.ui_items.push(UIItem {
+ x: pane_rect.x,
+ y: 0,
+ width: pane_rect.width,
+ height: pane_rect.y.saturating_add(pane_rect.height),
+ item_type: UIItemType::RightSidebarBackground,
+ });
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ pane_rect.x as f32,
+ pane_rect.y as f32,
+ 1.0,
+ pane_rect.height as f32,
+ ),
+ chrome.separator,
+ )
+ .context("right sidebar note pane left separator")?;
+ }
+
if rect.y > 0 {
self.filled_rectangle(
layers,
@@ -4948,6 +5204,17 @@ impl crate::TermWindow {
item_type: UIItemType::RightSidebarFilePreviewResize,
});
}
+ if self.right_sidebar_note_pane_rect().is_some() {
+ self.ui_items.push(UIItem {
+ x: rect
+ .x
+ .saturating_sub(self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH) / 2),
+ y: rect.y,
+ width: self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH),
+ height: rect.height,
+ item_type: UIItemType::RightSidebarNotePaneResize,
+ });
+ }
let content_x = rect.x + self.ui_px(SIDEBAR_INSET) * 2;
let content_width = rect.width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 4);
@@ -5411,6 +5678,7 @@ impl crate::TermWindow {
content_width: usize,
content_bottom: usize,
narrow: bool,
+ show_header_button: bool,
) -> anyhow::Result<()> {
let header_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);
let button_size = header_height;
@@ -5428,7 +5696,7 @@ impl crate::TermWindow {
UIItemType::RightSidebarNoteTreeBack,
)?;
title_x = content_x + button_size + self.ui_px(6);
- } else {
+ } else if show_header_button {
self.paint_snippet_icon_button(
layers,
chrome,
@@ -5671,8 +5939,74 @@ impl crate::TermWindow {
true,
)?;
}
+ // The expanded pane may be reserved while the note is still
+ // loading (or failed); keep the collapse toggle reachable so the
+ // pane is never blank and stuck.
+ if let Some(pane_rect) = self.right_sidebar_note_pane_rect() {
+ let inset = self.ui_px(SIDEBAR_INSET);
+ let button_size = self.ui_px(NOTE_TOOLBAR_HEIGHT);
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ &message,
+ pane_rect.x + inset * 2,
+ pane_rect.y + inset * 2 + button_size + self.ui_px(NOTE_BODY_TOP_GAP),
+ pane_rect.width.saturating_sub(inset * 4),
+ muted_fg,
+ )?;
+ self.paint_snippet_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ pane_rect
+ .x
+ .saturating_add(pane_rect.width)
+ .saturating_sub(inset * 2 + button_size),
+ pane_rect.y + inset * 2,
+ button_size,
+ SvgIcon::Shrink,
+ UIItemType::RightSidebarNotePaneToggle,
+ )?;
+ }
return Ok(());
}
+ if let Some(pane_rect) = self.right_sidebar_note_pane_rect() {
+ // Pane mode: the sidebar column holds the vault tree and the
+ // editor paints into the expanded pane on its left.
+ self.right_sidebar_note_wide_layout = true;
+ self.paint_note_vault_tree(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ content_bottom,
+ false,
+ false,
+ )?;
+ let inset = self.ui_px(SIDEBAR_INSET);
+ return self.paint_note_editor_area(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ pane_rect.x + inset * 2,
+ pane_rect.y + inset * 2,
+ pane_rect.width.saturating_sub(inset * 4),
+ pane_rect.y.saturating_add(pane_rect.height),
+ base_font_size,
+ false,
+ SvgIcon::FolderTree,
+ );
+ }
let wide_layout = content_width >= self.ui_px(NOTE_VAULT_SPLIT_MIN_WIDTH);
self.right_sidebar_note_wide_layout = wide_layout;
let split = wide_layout && !self.right_sidebar_note_vault_tree_collapsed;
@@ -5689,6 +6023,7 @@ impl crate::TermWindow {
content_width,
content_bottom,
true,
+ true,
)?;
return Ok(());
}
@@ -5708,6 +6043,7 @@ impl crate::TermWindow {
tree_width,
content_bottom,
false,
+ true,
)?;
(
content_x + tree_width + self.ui_px(SIDEBAR_INSET),
@@ -5716,18 +6052,54 @@ impl crate::TermWindow {
} else {
(content_x, content_width)
};
- self.right_sidebar_note.refresh_projection();
- self.schedule_right_sidebar_note_parse();
- self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));
-
- let toolbar_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);
- let menu_size = toolbar_height;
let show_tree_button = !split;
let tree_button_icon = if wide_layout {
SvgIcon::PanelLeftOpen
} else {
SvgIcon::FolderTree
};
+ self.paint_note_editor_area(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ content_bottom,
+ base_font_size,
+ show_tree_button,
+ tree_button_icon,
+ )
+ }
+
+ /// Paint the Note toolbar and editor body into an arbitrary content rect —
+ /// either inline in the sidebar column or in the expanded Note pane.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_note_editor_area(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ content_top: usize,
+ content_width: usize,
+ content_bottom: usize,
+ base_font_size: f64,
+ show_tree_button: bool,
+ tree_button_icon: SvgIcon,
+ ) -> anyhow::Result<()> {
+ self.right_sidebar_note.refresh_projection();
+ self.schedule_right_sidebar_note_parse();
+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));
+
+ let toolbar_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);
+ let menu_size = toolbar_height;
let body_y = content_top + toolbar_height + self.ui_px(NOTE_BODY_TOP_GAP);
let body_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET));
@@ -5958,29 +6330,25 @@ impl crate::TermWindow {
document.vault_root.hash(&mut component_hasher);
document.relative_path.hash(&mut component_hasher);
}
- let mut collapsed_blocks = self
- .right_sidebar_note
- .collapsed_code_blocks
- .iter()
- .copied()
- .collect::<Vec<_>>();
- collapsed_blocks.sort_unstable();
- collapsed_blocks.hash(&mut component_hasher);
- let mut code_offsets = self
- .right_sidebar_note
- .code_horizontal_offsets
- .iter()
- .map(|(source, offset)| (*source, offset.to_bits()))
- .collect::<Vec<_>>();
- code_offsets.sort_unstable_by_key(|(source, _)| *source);
- code_offsets.hash(&mut component_hasher);
- let mut table_offsets = self
- .right_sidebar_note_table_horizontal_offsets
- .iter()
- .map(|(source, offset)| (*source, offset.to_bits()))
- .collect::<Vec<_>>();
- table_offsets.sort_unstable_by_key(|(source, _)| *source);
- table_offsets.hash(&mut component_hasher);
+ // These are ordered maps/sets so each frame can hash them in place
+ // without sorting a temporary copy.
+ hash_ordered_iter(
+ &mut component_hasher,
+ self.right_sidebar_note.collapsed_code_blocks.iter(),
+ );
+ hash_ordered_iter(
+ &mut component_hasher,
+ self.right_sidebar_note
+ .code_horizontal_offsets
+ .iter()
+ .map(|(source, offset)| (*source, offset.to_bits())),
+ );
+ hash_ordered_iter(
+ &mut component_hasher,
+ self.right_sidebar_note_table_horizontal_offsets
+ .iter()
+ .map(|(source, offset)| (*source, offset.to_bits())),
+ );
let component_key = component_hasher.finish();
if self.right_sidebar_note_paint_cache.key != Some(component_key) {
@@ -6245,14 +6613,10 @@ impl crate::TermWindow {
loaded_image_metrics.sort_unstable();
loaded_image_metrics.hash(&mut geometry_hasher);
line_gap.to_bits().hash(&mut geometry_hasher);
- let mut collapsed = self
- .right_sidebar_note
- .collapsed_code_blocks
- .iter()
- .copied()
- .collect::<Vec<_>>();
- collapsed.sort_unstable();
- collapsed.hash(&mut geometry_hasher);
+ hash_ordered_iter(
+ &mut geometry_hasher,
+ self.right_sidebar_note.collapsed_code_blocks.iter(),
+ );
let geometry_key = geometry_hasher.finish();
if self.right_sidebar_note.line_geometry_key != Some(geometry_key)
|| self.right_sidebar_note.line_geometry.len() != visual.lines.len()
@@ -6369,9 +6733,14 @@ impl crate::TermWindow {
self.right_sidebar_note.reveal_caret = false;
}
self.right_sidebar_note.view.scroll_offset = scroll;
- let mut layouts = Vec::new();
- let mut code_block_layouts = Vec::new();
- let mut table_layouts = Vec::new();
+ // Reuse last frame's allocations; scroll repaints refill these every
+ // frame and the capacities are stable.
+ let mut layouts = std::mem::take(&mut self.right_sidebar_note.line_layouts);
+ layouts.clear();
+ let mut code_block_layouts = std::mem::take(&mut self.right_sidebar_note.code_block_layouts);
+ code_block_layouts.clear();
+ let mut table_layouts = std::mem::take(&mut self.right_sidebar_note_table_layouts);
+ table_layouts.clear();
let mut caret_rect: Option<(f32, f32, f32)> = None;
let selected = selection.range();
@@ -7222,7 +7591,42 @@ impl crate::TermWindow {
menu_size,
SvgIcon::Ellipsis,
UIItemType::RightSidebarNoteMenu,
- )
+ )?;
+
+ // Inline <-> expanded-pane switch, immediately left of the menu.
+ let pane_toggle_x = menu_x.saturating_sub(menu_size + self.ui_px(2));
+ if pane_toggle_x > content_x {
+ if self.is_pointer_over_ui_rect(pane_toggle_x, content_top, menu_size, menu_size) {
+ self.fill_rounded_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ pane_toggle_x as f32,
+ content_top as f32,
+ menu_size as f32,
+ menu_size as f32,
+ ),
+ chrome.control_hover_bg,
+ WINDOW_TAB_ADD_BUTTON_RADIUS,
+ )?;
+ }
+ self.paint_snippet_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ pane_toggle_x,
+ content_top,
+ menu_size,
+ if self.right_sidebar_note_pane_expanded {
+ SvgIcon::Shrink
+ } else {
+ SvgIcon::Expand
+ },
+ UIItemType::RightSidebarNotePaneToggle,
+ )?;
+ }
+ Ok(())
}
fn request_right_sidebar_note_open(
@@ -11609,7 +12013,7 @@ mod tests {
}
#[test]
- fn note_virtualization_keeps_two_viewports_of_overscan() {
+ fn note_virtualization_keeps_modest_overscan_around_the_viewport() {
let geometry = (0..1_000)
.map(|index| NoteLineGeometry {
top: index as f32 * 10.0,
@@ -11617,10 +12021,12 @@ mod tests {
gap: 0.0,
})
.collect::<Vec<_>>();
+ // Viewport covers rows 500..510; overscan must extend past both edges
+ // without painting multiple invisible viewports.
let range = virtual_note_line_range(&geometry, 5_000.0, 100.0);
- assert!(range.start <= 480);
- assert!(range.end >= 530);
- assert!(range.len() < 60, "virtual range was {} rows", range.len());
+ assert!(range.start <= 495);
+ assert!(range.end >= 515);
+ assert!(range.len() < 30, "virtual range was {} rows", range.len());
}
#[test]
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 2fe76ec2..cbf3d22d 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -2791,7 +2791,13 @@ impl WindowView {
};
let inner = myself.inner.borrow();
let Some(snapshot) = inner.native_text_input_snapshot.as_ref() else {
- return NSRange::new(NSNotFound as _, 0);
+ // The terminal has no reified text storage, but system text
+ // services still need a valid caret: macOS dictation queries
+ // selectedRange and treats NSNotFound as "no editable text",
+ // silently discarding the dictated words. Reporting an empty
+ // selection at 0 lets dictation deliver text through the normal
+ // insertText: path.
+ return NSRange::new(0, 0);
};
let start = utf16_offset_for_byte(&snapshot.text, snapshot.selection.start);
let end = utf16_offset_for_byte(&snapshot.text, snapshot.selection.end);