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
Add markdown editor to right sidebar with tree-sitter syntax highlighting
RoversX75e7cf6349f6
diff --git a/Cargo.lock b/Cargo.lockindex 81654ec9..05d8fd51 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -452,15 +452,6 @@ version = "0.4.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c335a9de639ba6a3e4107fe7763c9dcd4eb9422575f1191c2b8f2009f03fe4a"-[[package]]-name = "bincode"-version = "1.3.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"-dependencies = [- "serde",-]-[[package]]name = "bintree"version = "0.1.0"@@ -646,14 +637,14 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"[[package]]name = "cc"-version = "1.2.45"+version = "1.2.67"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "35900b6c8d709fb1d854671ae27aeaa9eec2f8b01b364e1619a40da3e6fe2afe"+checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"dependencies = ["find-msvc-tools","jobserver","libc",- "shlex",+ "shlex 2.0.1",][[package]]@@ -943,7 +934,7 @@ dependencies = ["promise","serde","serde_json",- "shlex",+ "shlex 1.3.0","smol","tempfile","termwiz",@@ -1746,9 +1737,9 @@ dependencies = [[[package]]name = "find-msvc-tools"-version = "0.1.4"+version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"[[package]]name = "finl_unicode"@@ -3947,28 +3938,6 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"-[[package]]-name = "onig"-version = "6.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"-dependencies = [- "bitflags 2.10.0",- "libc",- "once_cell",- "onig_sys",-]--[[package]]-name = "onig_sys"-version = "69.9.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"-dependencies = [- "cc",- "pkg-config",-]-[[package]]name = "oorandom"version = "11.1.5"@@ -4469,6 +4438,16 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"+[[package]]+name = "pretty_assertions"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"+dependencies = [+ "diff",+ "yansi",+]+[[package]]name = "proc-macro-crate"version = "3.4.0"@@ -4543,6 +4522,17 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "pulldown-cmark"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"+dependencies = [+ "bitflags 2.10.0",+ "memchr",+ "unicase",+]+[[package]]name = "pure-rust-locales"version = "0.8.2"@@ -5219,6 +5209,7 @@ version = "1.0.145"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"dependencies = [+ "indexmap 2.12.0","itoa","memchr","ryu",@@ -5366,6 +5357,12 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]name = "signal-hook"version = "0.3.18"@@ -5614,6 +5611,12 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"+[[package]]name = "strict-num"version = "0.1.1"@@ -5748,24 +5751,6 @@ dependencies = ["syn 2.0.110",]-[[package]]-name = "syntect"-version = "5.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"-dependencies = [- "bincode",- "flate2",- "fnv",- "once_cell",- "onig",- "regex-syntax",- "serde",- "serde_derive",- "thiserror 2.0.17",- "walkdir",-]-[[package]]name = "system-configuration"version = "0.6.1"@@ -5957,6 +5942,34 @@ dependencies = ["unicode-width",]+[[package]]+name = "thinkterm-syntax"+version = "0.1.0"+dependencies = [+ "anyhow",+ "pretty_assertions",+ "tree-sitter",+ "tree-sitter-bash",+ "tree-sitter-c",+ "tree-sitter-c-sharp",+ "tree-sitter-cpp",+ "tree-sitter-css",+ "tree-sitter-go",+ "tree-sitter-highlight",+ "tree-sitter-html",+ "tree-sitter-java",+ "tree-sitter-javascript",+ "tree-sitter-json",+ "tree-sitter-lua",+ "tree-sitter-md",+ "tree-sitter-python",+ "tree-sitter-rust",+ "tree-sitter-sequel",+ "tree-sitter-toml-ng",+ "tree-sitter-typescript",+ "tree-sitter-yaml",+]+[[package]]name = "thiserror"version = "1.0.69"@@ -6357,6 +6370,218 @@ dependencies = ["windows 0.56.0",]+[[package]]+name = "tree-sitter"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af1c71c1c4cc0920b20d6b0f6572e7682cd07a6a2faec71067a31fa394c586df"+dependencies = [+ "cc",+ "regex",+ "regex-syntax",+ "serde_json",+ "streaming-iterator",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-bash"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-c"+version = "0.24.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-c-sharp"+version = "0.23.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1aac67f1ad71de1d6d39708d34811081c26dfa495658de6c14c34200849357c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-cpp"+version = "0.23.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-css"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-go"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-highlight"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd7a0c48d503cf4e0a57a2453424eaef2fce4b4269f13e3579e52f0d0c9e5cc8"+dependencies = [+ "regex",+ "streaming-iterator",+ "thiserror 2.0.17",+ "tree-sitter",+]++[[package]]+name = "tree-sitter-html"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-java"+version = "0.23.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-javascript"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-json"+version = "0.24.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-language"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009994f150cc0cd50ff54917d5bc8bffe8cad10ca10d81c34da2ec421ae61782"++[[package]]+name = "tree-sitter-lua"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-md"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2efd398be546456c814598ee56c0f51769a77241511b4a58077815d120afa882"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-python"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-rust"+version = "0.24.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-sequel"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d198ad3c319c02e43c21efa1ec796b837afcb96ffaef1a40c1978fbdcec7d17"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-toml-ng"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-typescript"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-yaml"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97"+dependencies = [+ "cc",+ "tree-sitter-language",+]+[[package]]name = "try-lock"version = "0.2.5"@@ -7127,6 +7352,7 @@ dependencies = ["phf_codegen 0.10.0","portable-pty","promise",+ "pulldown-cmark","rangeset","ratelim","rayon",@@ -7135,23 +7361,25 @@ dependencies = ["serde","serde_json","shared_library",- "shlex",+ "shlex 1.3.0","smol",- "syntect","tabout","tempfile","terminfo","termwiz","termwiz-funcs","textwrap",+ "thinkterm-syntax","thiserror 1.0.69","tiny-skia","trash","umask","unicode-normalization","unicode-segmentation",+ "unicode-width","url","url-funcs",+ "uuid","walkdir","wezterm-bidi","wezterm-blob-leases",@@ -7627,7 +7855,7 @@ dependencies = ["resize","serde","shared_library",- "shlex",+ "shlex 1.3.0","smithay-client-toolkit","thiserror 1.0.69","tiny-skia",@@ -8350,6 +8578,12 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"+[[package]]+name = "yansi"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"+[[package]]name = "yasna"version = "0.5.2"diff --git a/Cargo.toml b/Cargo.tomlindex 44870cff..257d09dd 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,6 +4,7 @@ members = ["bidi/generate","strip-ansi-escapes","sync-color-schemes",+ "thinkterm-syntax","deps/cairo","wezterm","wezterm-blob-leases",@@ -171,6 +172,7 @@ pkg-config = "0.3"plist = "1.7"plugin = { path = "lua-api-crates/plugin" }portable-pty = { path = "pty" }+pulldown-cmark = { version = "0.13.4", default-features = false }predicates = "3.0"proc-macro2 = "1.0"procinfo = { path = "procinfo" }@@ -212,7 +214,6 @@ ssh2 = "0.9.3"starship-battery = "0.10"strsim = "0.11"syn = "1.0"-syntect = { version = "5.3", default-features = false, features = ["default-syntaxes", "default-themes", "regex-onig"] }tabout = { path = "tabout" }tar = "0.4"tempfile = "3.20"@@ -231,6 +232,7 @@ uds_windows = "1.1"umask = { path = "umask" }unicode-normalization = "0.1.24"unicode-segmentation = "1.12"+unicode-width = "0.2"url = "2"url-funcs = { path = "lua-api-crates/url-funcs" }utf8parse = "0.2"diff --git a/mux/src/ssh.rs b/mux/src/ssh.rsindex 3628919f..e3b6e3a1 100644--- a/mux/src/ssh.rs+++ b/mux/src/ssh.rs@@ -122,7 +122,9 @@ pub fn ssh_connect_with_ui_and_password(} else if password_answers_left > 0 {password_answers_left -= 1;ui.output_str(&format!("{editor_prompt} (using stored password)\n"));- Ok(password.clone().expect("password present when answers remain"))+ Ok(password+ .clone()+ .expect("password present when answers remain"))} else {ui.password(editor_prompt)};diff --git a/mux/src/tab.rs b/mux/src/tab.rsindex e1cc6100..54a61b19 100644--- a/mux/src/tab.rs+++ b/mux/src/tab.rs@@ -530,11 +530,7 @@ whereif panes.is_empty() {Tree::Empty} else {- Tree::Leaf(PaneStack::from_panes_with_id(- panes,- active_index,- stack_id,- ))+ Tree::Leaf(PaneStack::from_panes_with_id(panes, active_index, stack_id))}}}@@ -1149,15 +1145,15 @@ impl TabInner {log::debug!("sync_with_pane_tree with size {:?}", size);- let mut t = build_from_pane_tree(root.into_tree(), &mut active, &mut zoomed, &mut make_pane);+ let mut t =+ build_from_pane_tree(root.into_tree(), &mut active, &mut zoomed, &mut make_pane);// When the split topology is unchanged, keep the local cell// geometry (and self.size): the local window is the geometry// authority for client tabs, and the wire sizes are pane// dimensions that sit below the cells by the per-pane chrome.- let geometry_preserved = self- .pane- .as_ref()- .map_or(false, |old| copy_split_geometry_if_topology_matches(old, &mut t));+ let geometry_preserved = self.pane.as_ref().map_or(false, |old| {+ copy_split_geometry_if_topology_matches(old, &mut t)+ });log::debug!("sync_with_pane_tree tab {}: geometry_preserved={} old_size={:?}",self.id,@@ -1826,21 +1822,13 @@ impl TabInner {// collapse/expand can shrink a branch below its child's// remembered size, and an unclamped first here makes this// node wider than its parent (overlapping pane geometry).- node.first.cols = node- .first- .cols- .min(pane_size.cols.saturating_sub(2))- .max(1);+ node.first.cols = node.first.cols.min(pane_size.cols.saturating_sub(2)).max(1);node.second.cols = pane_size.cols.saturating_sub(1 + node.first.cols);} else {node.first.cols = pane_size.cols;node.second.cols = pane_size.cols;- node.first.rows = node- .first- .rows- .min(pane_size.rows.saturating_sub(2))- .max(1);+ node.first.rows = node.first.rows.min(pane_size.rows.saturating_sub(2)).max(1);node.second.rows = pane_size.rows.saturating_sub(1 + node.first.rows);}node.first.pixel_width = node.first.cols * cell_width;@@ -3787,11 +3775,13 @@ mod test {let size = test_size();let tab = Tab::new(&size);- let make_root = || PaneNode::Stack(PaneStackEntry {- active: 0,- panes: vec![pane_entry(200, size, true), pane_entry(201, size, false)],- pane_stack_id: Some(7),- });+ let make_root = || {+ PaneNode::Stack(PaneStackEntry {+ active: 0,+ panes: vec![pane_entry(200, size, true), pane_entry(201, size, false)],+ pane_stack_id: Some(7),+ })+ };tab.sync_with_pane_tree(size, make_root(), |entry| {FakePane::new(entry.pane_id, entry.size)diff --git a/thinkterm-syntax/Cargo.toml b/thinkterm-syntax/Cargo.tomlnew file mode 100644index 00000000..4abd4ce0--- /dev/null+++ b/thinkterm-syntax/Cargo.toml@@ -0,0 +1,31 @@+[package]+name = "thinkterm-syntax"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+anyhow.workspace = true+tree-sitter = "0.26.11"+tree-sitter-highlight = "0.26.11"+tree-sitter-bash = "0.25.1"+tree-sitter-c = "0.24.2"+tree-sitter-c-sharp = "0.23.5"+tree-sitter-cpp = "0.23.4"+tree-sitter-css = "0.25.0"+tree-sitter-go = "0.25.0"+tree-sitter-html = "0.23.2"+tree-sitter-java = "0.23.5"+tree-sitter-javascript = "0.25.0"+tree-sitter-json = "0.24.8"+tree-sitter-lua = "0.5.0"+tree-sitter-md = "0.5.3"+tree-sitter-python = "0.25.0"+tree-sitter-rust = "0.24.2"+tree-sitter-sequel = "0.3.11"+tree-sitter-toml-ng = "0.7.0"+tree-sitter-typescript = "0.23.2"+tree-sitter-yaml = "0.7.2"++[dev-dependencies]+pretty_assertions = "1"diff --git a/thinkterm-syntax/src/lib.rs b/thinkterm-syntax/src/lib.rsnew file mode 100644index 00000000..1bd458f9--- /dev/null+++ b/thinkterm-syntax/src/lib.rs@@ -0,0 +1,865 @@+//! Shared syntax detection, parsing, and highlighting for ThinkTerm.+//!+//! The GUI consumes semantic UTF-8 byte ranges from this crate and remains in+//! charge of mapping those semantic categories to theme colours. Keeping the+//! engine independent from window/rendering types lets the same registry back+//! file preview, Markdown code blocks, and a future code editor.++use anyhow::{anyhow, Context, Result};+use std::cell::RefCell;+use std::collections::HashMap;+use std::ops::Range;+use std::path::Path;+use std::sync::atomic::AtomicUsize;+use std::sync::OnceLock;+use tree_sitter::{InputEdit, Parser, Point, Tree};+use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter};++/// Maximum source size that GUI consumers should submit for highlighting.+///+/// The engine itself accepts larger inputs so future editors can choose their+/// own policy, but the current Preview and Note integrations use this bound.+pub const DEFAULT_HIGHLIGHT_BYTE_LIMIT: usize = 256 * 1024;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum LanguageId {+ Bash,+ C,+ Cpp,+ CSharp,+ Css,+ Go,+ Html,+ Java,+ JavaScript,+ Jsx,+ Json,+ Lua,+ Markdown,+ Python,+ Rust,+ Sql,+ Toml,+ Tsx,+ TypeScript,+ Yaml,+}++impl LanguageId {+ pub const ALL: [Self; 20] = [+ Self::Bash,+ Self::C,+ Self::Cpp,+ Self::CSharp,+ Self::Css,+ Self::Go,+ Self::Html,+ Self::Java,+ Self::JavaScript,+ Self::Jsx,+ Self::Json,+ Self::Lua,+ Self::Markdown,+ Self::Python,+ Self::Rust,+ Self::Sql,+ Self::Toml,+ Self::Tsx,+ Self::TypeScript,+ Self::Yaml,+ ];++ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Bash => "bash",+ Self::C => "c",+ Self::Cpp => "cpp",+ Self::CSharp => "c_sharp",+ Self::Css => "css",+ Self::Go => "go",+ Self::Html => "html",+ Self::Java => "java",+ Self::JavaScript => "javascript",+ Self::Jsx => "jsx",+ Self::Json => "json",+ Self::Lua => "lua",+ Self::Markdown => "markdown",+ Self::Python => "python",+ Self::Rust => "rust",+ Self::Sql => "sql",+ Self::Toml => "toml",+ Self::Tsx => "tsx",+ Self::TypeScript => "typescript",+ Self::Yaml => "yaml",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum HighlightKind {+ Attribute,+ Comment,+ Constant,+ Constructor,+ Embedded,+ Function,+ Keyword,+ Label,+ Module,+ Number,+ Operator,+ Property,+ Punctuation,+ String,+ Tag,+ Type,+ Variable,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct HighlightSpan {+ pub range: Range<usize>,+ pub kind: HighlightKind,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct HighlightResult {+ pub language: LanguageId,+ pub spans: Vec<HighlightSpan>,+}++const HIGHLIGHT_NAMES: [&str; 27] = [+ "attribute",+ "comment",+ "constant",+ "constant.builtin",+ "constructor",+ "embedded",+ "function",+ "function.builtin",+ "function.method",+ "function.method.builtin",+ "keyword",+ "label",+ "module",+ "number",+ "operator",+ "property",+ "punctuation",+ "punctuation.bracket",+ "punctuation.delimiter",+ "string",+ "string.documentation",+ "string.escape",+ "string.special",+ "tag",+ "type",+ "type.builtin",+ "variable",+];++const HIGHLIGHT_KINDS: [HighlightKind; HIGHLIGHT_NAMES.len()] = [+ HighlightKind::Attribute,+ HighlightKind::Comment,+ HighlightKind::Constant,+ HighlightKind::Constant,+ HighlightKind::Constructor,+ HighlightKind::Embedded,+ HighlightKind::Function,+ HighlightKind::Function,+ HighlightKind::Function,+ HighlightKind::Function,+ HighlightKind::Keyword,+ HighlightKind::Label,+ HighlightKind::Module,+ HighlightKind::Number,+ HighlightKind::Operator,+ HighlightKind::Property,+ HighlightKind::Punctuation,+ HighlightKind::Punctuation,+ HighlightKind::Punctuation,+ HighlightKind::String,+ HighlightKind::String,+ HighlightKind::String,+ HighlightKind::String,+ HighlightKind::Tag,+ HighlightKind::Type,+ HighlightKind::Type,+ HighlightKind::Variable,+];++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+enum ConfigId {+ Public(LanguageId),+ MarkdownInline,+}++struct Registry {+ configs: HashMap<ConfigId, HighlightConfiguration>,+ aliases: HashMap<&'static str, ConfigId>,+}++impl Registry {+ fn config(&self, id: LanguageId) -> Option<&HighlightConfiguration> {+ self.configs.get(&ConfigId::Public(id))+ }++ fn injection(&self, name: &str) -> Option<&HighlightConfiguration> {+ let normalized = normalize_token(name);+ self.aliases+ .get(normalized.as_str())+ .and_then(|id| self.configs.get(id))+ }+}++static REGISTRY: OnceLock<std::result::Result<Registry, String>> = OnceLock::new();++thread_local! {+ static HIGHLIGHTER: RefCell<Highlighter> = RefCell::new(Highlighter::new());+}++fn registry() -> Result<&'static Registry> {+ match REGISTRY.get_or_init(|| build_registry().map_err(|err| format!("{err:#}"))) {+ Ok(registry) => Ok(registry),+ Err(err) => Err(anyhow!(err.clone())),+ }+}++fn configured(+ language: tree_sitter::Language,+ name: &str,+ highlights: &str,+ injections: &str,+ locals: &str,+) -> Result<HighlightConfiguration> {+ let mut config = HighlightConfiguration::new(language, name, highlights, injections, locals)+ .with_context(|| format!("build Tree-sitter highlight query for {name}"))?;+ config.configure(&HIGHLIGHT_NAMES);+ Ok(config)+}++fn build_registry() -> Result<Registry> {+ let mut configs = HashMap::new();++ let javascript_highlights = format!(+ "{}\n{}",+ tree_sitter_javascript::HIGHLIGHT_QUERY,+ tree_sitter_javascript::JSX_HIGHLIGHT_QUERY+ );++ macro_rules! insert {+ ($id:expr, $language:expr, $name:expr, $highlights:expr) => {+ configs.insert(+ ConfigId::Public($id),+ configured(($language).into(), $name, $highlights, "", "")?,+ );+ };+ ($id:expr, $language:expr, $name:expr, $highlights:expr, $injections:expr, $locals:expr) => {+ configs.insert(+ ConfigId::Public($id),+ configured(($language).into(), $name, $highlights, $injections, $locals)?,+ );+ };+ }++ insert!(+ LanguageId::Bash,+ tree_sitter_bash::LANGUAGE,+ "bash",+ tree_sitter_bash::HIGHLIGHT_QUERY+ );+ insert!(+ LanguageId::C,+ tree_sitter_c::LANGUAGE,+ "c",+ tree_sitter_c::HIGHLIGHT_QUERY+ );+ insert!(+ LanguageId::Cpp,+ tree_sitter_cpp::LANGUAGE,+ "cpp",+ tree_sitter_cpp::HIGHLIGHT_QUERY+ );+ insert!(+ LanguageId::CSharp,+ tree_sitter_c_sharp::LANGUAGE,+ "c_sharp",+ tree_sitter_c_sharp::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Css,+ tree_sitter_css::LANGUAGE,+ "css",+ tree_sitter_css::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Go,+ tree_sitter_go::LANGUAGE,+ "go",+ tree_sitter_go::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Html,+ tree_sitter_html::LANGUAGE,+ "html",+ tree_sitter_html::HIGHLIGHTS_QUERY,+ tree_sitter_html::INJECTIONS_QUERY,+ ""+ );+ insert!(+ LanguageId::Java,+ tree_sitter_java::LANGUAGE,+ "java",+ tree_sitter_java::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::JavaScript,+ tree_sitter_javascript::LANGUAGE,+ "javascript",+ javascript_highlights.as_str(),+ tree_sitter_javascript::INJECTIONS_QUERY,+ tree_sitter_javascript::LOCALS_QUERY+ );+ insert!(+ LanguageId::Jsx,+ tree_sitter_javascript::LANGUAGE,+ "jsx",+ javascript_highlights.as_str(),+ tree_sitter_javascript::INJECTIONS_QUERY,+ tree_sitter_javascript::LOCALS_QUERY+ );+ insert!(+ LanguageId::Json,+ tree_sitter_json::LANGUAGE,+ "json",+ tree_sitter_json::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Lua,+ tree_sitter_lua::LANGUAGE,+ "lua",+ tree_sitter_lua::HIGHLIGHTS_QUERY,+ tree_sitter_lua::INJECTIONS_QUERY,+ tree_sitter_lua::LOCALS_QUERY+ );+ insert!(+ LanguageId::Markdown,+ tree_sitter_md::LANGUAGE,+ "markdown",+ tree_sitter_md::HIGHLIGHT_QUERY_BLOCK,+ tree_sitter_md::INJECTION_QUERY_BLOCK,+ ""+ );+ configs.insert(+ ConfigId::MarkdownInline,+ configured(+ tree_sitter_md::INLINE_LANGUAGE.into(),+ "markdown_inline",+ tree_sitter_md::HIGHLIGHT_QUERY_INLINE,+ tree_sitter_md::INJECTION_QUERY_INLINE,+ "",+ )?,+ );+ insert!(+ LanguageId::Python,+ tree_sitter_python::LANGUAGE,+ "python",+ tree_sitter_python::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Rust,+ tree_sitter_rust::LANGUAGE,+ "rust",+ tree_sitter_rust::HIGHLIGHTS_QUERY,+ tree_sitter_rust::INJECTIONS_QUERY,+ ""+ );+ insert!(+ LanguageId::Sql,+ tree_sitter_sequel::LANGUAGE,+ "sql",+ tree_sitter_sequel::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Toml,+ tree_sitter_toml_ng::LANGUAGE,+ "toml",+ tree_sitter_toml_ng::HIGHLIGHTS_QUERY+ );+ insert!(+ LanguageId::Tsx,+ tree_sitter_typescript::LANGUAGE_TSX,+ "tsx",+ tree_sitter_typescript::HIGHLIGHTS_QUERY,+ "",+ tree_sitter_typescript::LOCALS_QUERY+ );+ insert!(+ LanguageId::TypeScript,+ tree_sitter_typescript::LANGUAGE_TYPESCRIPT,+ "typescript",+ tree_sitter_typescript::HIGHLIGHTS_QUERY,+ "",+ tree_sitter_typescript::LOCALS_QUERY+ );+ insert!(+ LanguageId::Yaml,+ tree_sitter_yaml::LANGUAGE,+ "yaml",+ tree_sitter_yaml::HIGHLIGHTS_QUERY+ );++ let mut aliases = HashMap::new();+ let mut add_aliases = |id, values: &'static [&'static str]| {+ for value in values {+ aliases.insert(*value, id);+ }+ };+ add_aliases(+ ConfigId::Public(LanguageId::Bash),+ &["bash", "sh", "shell", "shellscript", "zsh"],+ );+ add_aliases(ConfigId::Public(LanguageId::C), &["c"]);+ add_aliases(ConfigId::Public(LanguageId::Cpp), &["cpp", "c++", "cxx"]);+ add_aliases(+ ConfigId::Public(LanguageId::CSharp),+ &["c_sharp", "csharp", "c#", "cs"],+ );+ add_aliases(ConfigId::Public(LanguageId::Css), &["css"]);+ add_aliases(ConfigId::Public(LanguageId::Go), &["go", "golang"]);+ add_aliases(ConfigId::Public(LanguageId::Html), &["html", "htm"]);+ add_aliases(ConfigId::Public(LanguageId::Java), &["java"]);+ add_aliases(+ ConfigId::Public(LanguageId::JavaScript),+ &["javascript", "js", "node"],+ );+ add_aliases(ConfigId::Public(LanguageId::Jsx), &["jsx"]);+ add_aliases(ConfigId::Public(LanguageId::Json), &["json", "jsonc"]);+ add_aliases(ConfigId::Public(LanguageId::Lua), &["lua"]);+ add_aliases(ConfigId::Public(LanguageId::Markdown), &["markdown", "md"]);+ add_aliases(ConfigId::MarkdownInline, &["markdown_inline"]);+ add_aliases(ConfigId::Public(LanguageId::Python), &["python", "py"]);+ add_aliases(ConfigId::Public(LanguageId::Rust), &["rust", "rs"]);+ add_aliases(ConfigId::Public(LanguageId::Sql), &["sql"]);+ add_aliases(ConfigId::Public(LanguageId::Toml), &["toml"]);+ add_aliases(ConfigId::Public(LanguageId::Tsx), &["tsx"]);+ add_aliases(+ ConfigId::Public(LanguageId::TypeScript),+ &["typescript", "ts"],+ );+ add_aliases(ConfigId::Public(LanguageId::Yaml), &["yaml", "yml"]);++ Ok(Registry { configs, aliases })+}++fn normalize_token(value: &str) -> String {+ value.trim().to_ascii_lowercase().replace('-', "_")+}++pub fn detect_fence(language: &str) -> Option<LanguageId> {+ let token = language+ .split_whitespace()+ .next()?+ .trim_matches(['{', '}'])+ .trim_start_matches('.');+ let token = normalize_token(token);+ let token = token.strip_prefix("language_").unwrap_or(&token);+ let registry = registry().ok()?;+ match registry.aliases.get(token)? {+ ConfigId::Public(id) => Some(*id),+ ConfigId::MarkdownInline => Some(LanguageId::Markdown),+ }+}++pub fn detect_path(path: &Path, source: &str) -> Option<LanguageId> {+ let file_name = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or_default();+ match file_name.to_ascii_lowercase().as_str() {+ ".bashrc" | ".bash_profile" | ".profile" => return Some(LanguageId::Bash),+ _ => {}+ }++ let extension = path+ .extension()+ .and_then(|extension| extension.to_str())+ .map(str::to_ascii_lowercase);+ if let Some(language) = extension.as_deref().and_then(detect_extension) {+ return Some(language);+ }++ detect_shebang(source.lines().next().unwrap_or_default())+}++fn detect_extension(extension: &str) -> Option<LanguageId> {+ Some(match extension {+ "sh" | "bash" => LanguageId::Bash,+ "c" => LanguageId::C,+ "h" | "cc" | "cp" | "cpp" | "cxx" | "h++" | "hh" | "hpp" | "hxx" => LanguageId::Cpp,+ "cs" => LanguageId::CSharp,+ "css" => LanguageId::Css,+ "go" => LanguageId::Go,+ "htm" | "html" => LanguageId::Html,+ "java" => LanguageId::Java,+ "cjs" | "js" | "mjs" => LanguageId::JavaScript,+ "jsx" => LanguageId::Jsx,+ "json" | "jsonc" => LanguageId::Json,+ "lua" => LanguageId::Lua,+ "markdown" | "md" | "mdown" | "mkd" => LanguageId::Markdown,+ "py" | "pyi" | "pyw" => LanguageId::Python,+ "rs" => LanguageId::Rust,+ "sql" => LanguageId::Sql,+ "toml" => LanguageId::Toml,+ "tsx" => LanguageId::Tsx,+ "cts" | "mts" | "ts" => LanguageId::TypeScript,+ "yaml" | "yml" => LanguageId::Yaml,+ _ => return None,+ })+}++fn detect_shebang(line: &str) -> Option<LanguageId> {+ if !line.starts_with("#!") {+ return None;+ }+ let lower = line.to_ascii_lowercase();+ if lower.contains("python") {+ Some(LanguageId::Python)+ } else if lower.contains("node") || lower.contains("deno") {+ Some(LanguageId::JavaScript)+ } else if lower.contains("bash") || lower.ends_with("/sh") || lower.contains(" sh ") {+ Some(LanguageId::Bash)+ } else if lower.contains("lua") {+ Some(LanguageId::Lua)+ } else {+ None+ }+}++pub fn highlight_path(+ path: &Path,+ source: &str,+ cancellation: Option<&AtomicUsize>,+) -> Result<Option<HighlightResult>> {+ let Some(language) = detect_path(path, source) else {+ return Ok(None);+ };+ highlight(language, source, cancellation).map(Some)+}++pub fn highlight(+ language: LanguageId,+ source: &str,+ cancellation: Option<&AtomicUsize>,+) -> Result<HighlightResult> {+ let registry = registry()?;+ let config = registry+ .config(language)+ .ok_or_else(|| anyhow!("missing Tree-sitter config for {}", language.as_str()))?;++ HIGHLIGHTER.with(|cell| {+ let mut highlighter = cell.borrow_mut();+ let events = highlighter+ .highlight(config, source.as_bytes(), cancellation, |name| {+ registry.injection(name)+ })+ .with_context(|| format!("highlight {} source", language.as_str()))?;++ let mut active = Vec::new();+ let mut spans: Vec<HighlightSpan> = Vec::new();+ for event in events {+ match event.with_context(|| format!("iterate {} highlights", language.as_str()))? {+ HighlightEvent::HighlightStart(highlight) => {+ active.push(HIGHLIGHT_KINDS[highlight.0]);+ }+ HighlightEvent::HighlightEnd => {+ active.pop();+ }+ HighlightEvent::Source { start, end } => {+ let Some(kind) = active.last().copied() else {+ continue;+ };+ if start >= end || end > source.len() {+ continue;+ }+ if let Some(previous) = spans.last_mut() {+ if previous.kind == kind && previous.range.end == start {+ previous.range.end = end;+ continue;+ }+ }+ spans.push(HighlightSpan {+ range: start..end,+ kind,+ });+ }+ }+ }+ Ok(HighlightResult { language, spans })+ })+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SyntaxPoint {+ pub row: usize,+ pub column: usize,+}++impl From<SyntaxPoint> for Point {+ fn from(value: SyntaxPoint) -> Self {+ Point::new(value.row, value.column)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SyntaxEdit {+ pub start_byte: usize,+ pub old_end_byte: usize,+ pub new_end_byte: usize,+ pub start_position: SyntaxPoint,+ pub old_end_position: SyntaxPoint,+ pub new_end_position: SyntaxPoint,+}++impl From<SyntaxEdit> for InputEdit {+ fn from(value: SyntaxEdit) -> Self {+ Self {+ start_byte: value.start_byte,+ old_end_byte: value.old_end_byte,+ new_end_byte: value.new_end_byte,+ start_position: value.start_position.into(),+ old_end_position: value.old_end_position.into(),+ new_end_position: value.new_end_position.into(),+ }+ }+}++pub struct SyntaxSession {+ language: LanguageId,+ parser: Parser,+ tree: Tree,+ revision: u64,+}++impl SyntaxSession {+ pub fn new(language: LanguageId, source: &str, revision: u64) -> Result<Self> {+ let registry = registry()?;+ let config = registry+ .config(language)+ .ok_or_else(|| anyhow!("missing Tree-sitter config for {}", language.as_str()))?;+ let mut parser = Parser::new();+ parser+ .set_language(&config.language)+ .with_context(|| format!("set {} parser language", language.as_str()))?;+ let tree = parser+ .parse(source, None)+ .ok_or_else(|| anyhow!("{} parse cancelled", language.as_str()))?;+ Ok(Self {+ language,+ parser,+ tree,+ revision,+ })+ }++ pub fn language(&self) -> LanguageId {+ self.language+ }++ pub fn revision(&self) -> u64 {+ self.revision+ }++ pub fn tree(&self) -> &Tree {+ &self.tree+ }++ pub fn apply_edit(+ &mut self,+ edit: SyntaxEdit,+ new_source: &str,+ revision: u64,+ ) -> Result<Vec<Range<usize>>> {+ self.tree.edit(&edit.into());+ let edited_old_tree = self.tree.clone();+ let new_tree = self+ .parser+ .parse(new_source, Some(&self.tree))+ .ok_or_else(|| anyhow!("{} incremental parse cancelled", self.language.as_str()))?;+ let changed = edited_old_tree+ .changed_ranges(&new_tree)+ .map(|range| range.start_byte..range.end_byte)+ .collect();+ self.tree = new_tree;+ self.revision = revision;+ Ok(changed)+ }++ /// Produce semantic spans for the session's current source.+ ///+ /// The syntax tree itself is updated incrementally. The official+ /// highlighter currently reparses for highlighting, but this API boundary+ /// allows a future editor to switch to changed-range queries without+ /// changing GUI consumers.+ pub fn highlight(+ &self,+ source: &str,+ cancellation: Option<&AtomicUsize>,+ ) -> Result<HighlightResult> {+ highlight(self.language, source, cancellation)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use pretty_assertions::assert_eq;++ #[test]+ fn detects_extensions_fences_and_shebangs() {+ assert_eq!(+ detect_path(Path::new("main.rs"), ""),+ Some(LanguageId::Rust)+ );+ assert_eq!(+ detect_path(Path::new("view.tsx"), ""),+ Some(LanguageId::Tsx)+ );+ assert_eq!(+ detect_path(Path::new("unknown"), "#!/usr/bin/env python3\n"),+ Some(LanguageId::Python)+ );+ assert_eq!(detect_fence("C++"), Some(LanguageId::Cpp));+ assert_eq!(detect_fence("typescript"), Some(LanguageId::TypeScript));+ assert_eq!(detect_fence("rust title=main.rs"), Some(LanguageId::Rust));+ assert_eq!(detect_fence("{.python}"), Some(LanguageId::Python));+ assert_eq!(detect_path(Path::new("unknown.xyz"), ""), None);+ }++ #[test]+ fn every_public_language_builds_and_highlights() {+ let fixtures = [+ (LanguageId::Bash, "if true; then echo hi; fi\n"),+ (LanguageId::C, "int main(void) { return 0; }\n"),+ (LanguageId::Cpp, "auto main() -> int { return 0; }\n"),+ (LanguageId::CSharp, "class C { string S = \"x\"; }\n"),+ (LanguageId::Css, "body { color: red; }\n"),+ (LanguageId::Go, "package main\nfunc main() {}\n"),+ (LanguageId::Html, "<script>const x = 1;</script>\n"),+ (LanguageId::Java, "class Main { int n = 1; }\n"),+ (LanguageId::JavaScript, "const x = () => 1;\n"),+ (LanguageId::Jsx, "const x = <div>ok</div>;\n"),+ (LanguageId::Json, "{\"ok\": true}\n"),+ (LanguageId::Lua, "local value = \"ok\"\n"),+ (+ LanguageId::Markdown,+ "# Hello\n\n```rust\nfn main() {}\n```\n",+ ),+ (LanguageId::Python, "def main():\n return 1\n"),+ (LanguageId::Rust, "fn main() { let x = 1; }\n"),+ (LanguageId::Sql, "select id from users;\n"),+ (LanguageId::Toml, "name = \"thinkterm\"\n"),+ (LanguageId::Tsx, "const x: JSX.Element = <div />;\n"),+ (LanguageId::TypeScript, "const x: number = 1;\n"),+ (LanguageId::Yaml, "name: thinkterm\n"),+ ];+ for (language, source) in fixtures {+ let result = highlight(language, source, None)+ .unwrap_or_else(|err| panic!("{} failed: {err:#}", language.as_str()));+ assert_eq!(result.language, language);+ assert!(+ !result.spans.is_empty(),+ "{} returned no spans",+ language.as_str()+ );+ }+ }++ #[test]+ fn highlight_ranges_are_valid_utf8_and_include_injections() {+ let source = "<script>const 你好 = \"ok\";</script>";+ let result = highlight(LanguageId::Html, source, None).unwrap();+ assert!(result+ .spans+ .iter()+ .any(|span| span.kind == HighlightKind::Keyword));+ assert!(result+ .spans+ .iter()+ .any(|span| span.kind == HighlightKind::String));+ for span in result.spans {+ assert!(source.is_char_boundary(span.range.start));+ assert!(source.is_char_boundary(span.range.end));+ assert!(span.range.end <= source.len());+ }+ }++ #[test]+ fn preserves_cross_line_state_and_nested_markdown_languages() {+ let javascript = "/* first line\nsecond line */\nconst value = 1;\n";+ let result = highlight(LanguageId::JavaScript, javascript, None).unwrap();+ assert!(result.spans.iter().any(|span| {+ span.kind == HighlightKind::Comment+ && javascript[span.range.clone()].contains("second line")+ }));++ let markdown = "```rust\nfn main() { let value = 1; }\n```\n";+ let result = highlight(LanguageId::Markdown, markdown, None).unwrap();+ assert!(result+ .spans+ .iter()+ .any(|span| span.kind == HighlightKind::Keyword));+ }++ #[test]+ fn highlighting_honors_cancellation() {+ let cancellation = AtomicUsize::new(1);+ let source = "let value = 1;\n".repeat(10_000);+ assert!(highlight(LanguageId::JavaScript, &source, Some(&cancellation)).is_err());+ }++ #[test]+ fn highlights_a_preview_sized_source() {+ let line = "const value = { nested: [1, 2, 3] };\n";+ let source = line.repeat(DEFAULT_HIGHLIGHT_BYTE_LIMIT / line.len());+ let result = highlight(LanguageId::JavaScript, &source, None).unwrap();+ assert!(!result.spans.is_empty());+ assert!(source.len() <= DEFAULT_HIGHLIGHT_BYTE_LIMIT);+ }++ #[test]+ fn incremental_session_matches_a_full_reparse() {+ let old = "fn main() { let value = 1; }\n";+ let inserted = "mut ";+ let start = old.find("value").unwrap();+ let mut new = old.to_string();+ new.insert_str(start, inserted);+ let point = SyntaxPoint {+ row: 0,+ column: start,+ };+ let edit = SyntaxEdit {+ start_byte: start,+ old_end_byte: start,+ new_end_byte: start + inserted.len(),+ start_position: point,+ old_end_position: point,+ new_end_position: SyntaxPoint {+ row: 0,+ column: start + inserted.len(),+ },+ };+ let mut session = SyntaxSession::new(LanguageId::Rust, old, 1).unwrap();+ let changed = session.apply_edit(edit, &new, 2).unwrap();+ assert!(!changed.is_empty());+ let full = SyntaxSession::new(LanguageId::Rust, &new, 2).unwrap();+ assert_eq!(+ session.tree().root_node().to_sexp(),+ full.tree().root_node().to_sexp()+ );+ assert_eq!(+ session.highlight(&new, None).unwrap(),+ highlight(LanguageId::Rust, &new, None).unwrap()+ );+ }+}diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 595cf2f8..7c60ce44 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -463,9 +463,7 @@ async fn client_thread_async(decoded.serial,decoded.pdu.pdu_name());- if pending_ping- .map_or(false, |(serial, _)| serial == decoded.serial)- {+ if pending_ping.map_or(false, |(serial, _)| serial == decoded.serial) {pending_ping = None;} else if decoded.serial == 0 {process_unilateral(local_domain_id, decoded)@@ -1245,12 +1243,9 @@ impl Client {.find(|window_id| {mux.get_window(*window_id).map_or(false, |w| {w.iter().any(|tab| {- tab.iter_panes_ignoring_zoom().iter().any(- |p| {- p.pane.domain_id()- == local_domain_id- },- )+ tab.iter_panes_ignoring_zoom().iter().any(|p| {+ p.pane.domain_id() == local_domain_id+ })})})});@@ -1271,9 +1266,7 @@ impl Client {// prompts can never be answered. Rebuild it// where the user is now.if let Some((ui, hosted_ws)) = &windowed_ui {- if !active_workspace.is_empty()- && hosted_ws != &active_workspace- {+ if !active_workspace.is_empty() && hosted_ws != &active_workspace {ui.close();windowed_ui = None;}diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex 372bc8a5..b299aeb6 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -55,7 +55,11 @@ pub(crate) struct StructureMutationGuard {impl Drop for StructureMutationGuard {fn drop(&mut self) {use std::sync::atomic::Ordering;- if self.inner.mutations_in_flight.fetch_sub(1, Ordering::SeqCst) == 1+ if self+ .inner+ .mutations_in_flight+ .fetch_sub(1, Ordering::SeqCst)+ == 1&& self.inner.resync_deferred.swap(false, Ordering::SeqCst){let domain_id = self.inner.local_domain_id;diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 3cf88934..007a72e9 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -175,8 +175,7 @@ impl ClientPane {// render surface (make_all_stale forces a refetch of every// visible line, which flashes the pane contents).if palette != *self.palette.lock() {- *self.application_palette.lock() =- palette != *self.configured_palette.lock();+ *self.application_palette.lock() = palette != *self.configured_palette.lock();*self.palette.lock() = palette;let mux = Mux::get();diff --git a/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rsindex 35bfdebf..476f92e6 100644--- a/wezterm-font/src/lib.rs+++ b/wezterm-font/src/lib.rs@@ -473,7 +473,7 @@ struct FontConfigInner {pane_select_font: RefCell<Option<Rc<LoadedFont>>>,char_select_font: RefCell<Option<Rc<LoadedFont>>>,command_palette_font: RefCell<Option<Rc<LoadedFont>>>,- entity_font_overrides: RefCell<HashMap<(Entity, u64, u16), Rc<LoadedFont>>>,+ entity_font_overrides: RefCell<HashMap<(Entity, u64, u16, bool), Rc<LoadedFont>>>,fallback_channel: RefCell<Option<Sender<FallbackResolveInfo>>>,}@@ -627,6 +627,7 @@ impl FontConfigInner {entity: Entity,override_font_size: Option<f64>,override_weight: Option<config::FontWeight>,+ override_italic: bool,) -> anyhow::Result<Rc<LoadedFont>> {let config = self.config.borrow();let make_bold = entity != Entity::CommandPalette;@@ -652,11 +653,16 @@ impl FontConfigInner {let text_style =text_style.unwrap_or(config.window_frame.font.as_ref().unwrap_or(&sys_font));let override_style;- let text_style = if let Some(weight) = override_weight {+ let text_style = if override_weight.is_some() || override_italic {override_style = {let mut style = text_style.clone();for attr in &mut style.font {- attr.weight = weight;+ if let Some(weight) = override_weight {+ attr.weight = weight;+ }+ if override_italic {+ attr.style = config::FontStyle::Italic;+ }}style};@@ -705,7 +711,7 @@ impl FontConfigInner {return Ok(Rc::clone(entry));}- let loaded = self.make_entity_font_impl(myself, Entity::Title, None, None)?;+ let loaded = self.make_entity_font_impl(myself, Entity::Title, None, None, false)?;title_font.replace(Rc::clone(&loaded));@@ -719,7 +725,8 @@ impl FontConfigInner {return Ok(Rc::clone(entry));}- let loaded = self.make_entity_font_impl(myself, Entity::CommandPalette, None, None)?;+ let loaded =+ self.make_entity_font_impl(myself, Entity::CommandPalette, None, None, false)?;command_palette_font.replace(Rc::clone(&loaded));@@ -733,7 +740,7 @@ impl FontConfigInner {return Ok(Rc::clone(entry));}- let loaded = self.make_entity_font_impl(myself, Entity::CharSelect, None, None)?;+ let loaded = self.make_entity_font_impl(myself, Entity::CharSelect, None, None, false)?;char_select_font.replace(Rc::clone(&loaded));@@ -747,7 +754,7 @@ impl FontConfigInner {return Ok(Rc::clone(entry));}- let loaded = self.make_entity_font_impl(myself, Entity::PaneSelect, None, None)?;+ let loaded = self.make_entity_font_impl(myself, Entity::PaneSelect, None, None, false)?;pane_select_font.replace(Rc::clone(&loaded));@@ -760,10 +767,11 @@ impl FontConfigInner {entity: Entity,font_size: f64,font_weight: Option<u16>,+ italic: bool,) -> anyhow::Result<Rc<LoadedFont>> {let font_size = font_size.clamp(6.0, 72.0);let font_weight = font_weight.unwrap_or(0);- let key = (entity, font_size.to_bits(), font_weight);+ let key = (entity, font_size.to_bits(), font_weight, italic);if let Some(entry) = self.entity_font_overrides.borrow().get(&key) {return Ok(Rc::clone(entry));}@@ -772,6 +780,7 @@ impl FontConfigInner {entity,Some(font_size),(font_weight > 0).then(|| config::FontWeight::from_opentype_weight(font_weight)),+ italic,)?;self.entity_font_overrides.borrow_mut()@@ -1152,7 +1161,7 @@ impl FontConfiguration {pub fn title_font_with_size(&self, font_size: f64) -> anyhow::Result<Rc<LoadedFont>> {self.inner- .entity_font_with_size(&self.inner, Entity::Title, font_size, None)+ .entity_font_with_size(&self.inner, Entity::Title, font_size, None, false)}pub fn title_font_with_size_and_weight(@@ -1160,8 +1169,27 @@ impl FontConfiguration {font_size: f64,font_weight: u16,) -> anyhow::Result<Rc<LoadedFont>> {- self.inner- .entity_font_with_size(&self.inner, Entity::Title, font_size, Some(font_weight))+ self.inner.entity_font_with_size(+ &self.inner,+ Entity::Title,+ font_size,+ Some(font_weight),+ false,+ )+ }++ pub fn title_font_with_size_weight_and_italic(+ &self,+ font_size: f64,+ font_weight: u16,+ ) -> anyhow::Result<Rc<LoadedFont>> {+ self.inner.entity_font_with_size(+ &self.inner,+ Entity::Title,+ font_size,+ Some(font_weight),+ true,+ )}pub fn command_palette_font(&self) -> anyhow::Result<Rc<LoadedFont>> {@@ -1169,8 +1197,13 @@ impl FontConfiguration {}pub fn command_palette_font_with_size(&self, font_size: f64) -> anyhow::Result<Rc<LoadedFont>> {- self.inner- .entity_font_with_size(&self.inner, Entity::CommandPalette, font_size, None)+ self.inner.entity_font_with_size(+ &self.inner,+ Entity::CommandPalette,+ font_size,+ None,+ false,+ )}pub fn command_palette_font_with_size_and_weight(@@ -1183,6 +1216,7 @@ impl FontConfiguration {Entity::CommandPalette,font_size,Some(font_weight),+ false,)}diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex f84fa36a..6a20ea9c 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -75,6 +75,7 @@ ordered-float.workspace = trueparking_lot.workspace = truephf.workspace = trueportable-pty = { workspace=true, features = ["serde_support"]}+pulldown-cmark.workspace = truepromise.workspace = truerangeset.workspace = trueratelim.workspace = true@@ -85,7 +86,6 @@ serde = {workspace=true, features = ["rc", "derive"]}serde_json.workspace = trueshlex.workspace = truesmol.workspace = true-syntect.workspace = truetabout.workspace = truetempfile.workspace = trueterminfo.workspace = true@@ -94,10 +94,13 @@ termwiz.workspace = truetextwrap.workspace = truethiserror.workspace = truetiny-skia.workspace = true+thinkterm-syntax = { path = "../thinkterm-syntax" }trash.workspace = trueumask.workspace = trueunicode-normalization.workspace = trueunicode-segmentation.workspace = true+unicode-width.workspace = true+uuid = { workspace = true, features = ["v4"] }url-funcs.workspace = trueurl.workspace = truewalkdir.workspace = truediff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex be6c9211..036e07d8 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -43,6 +43,7 @@ mod frontend;mod glyphcache;mod input_diagnostics;mod inputmap;+mod markdown_editor;mod native_paths;mod native_settings;mod overlay;@@ -497,9 +498,7 @@ pub(crate) async fn connect_domain_into_space(match attempt {Ok(()) => break,Err(err) => {- log::error!(- "attaching {domain_name} failed: {err:#}; retrying in {backoff:?}"- );+ log::error!("attaching {domain_name} failed: {err:#}; retrying in {backoff:?}");ui.output_str(&format!("Will retry in {backoff:?}...\n"));smol::Timer::after(backoff).await;backoff = (backoff * 2).min(MAX_BACKOFF);diff --git a/wezterm-gui/src/markdown_editor/document.rs b/wezterm-gui/src/markdown_editor/document.rsnew file mode 100644index 00000000..b33d5493--- /dev/null+++ b/wezterm-gui/src/markdown_editor/document.rs@@ -0,0 +1,738 @@+use parking_lot::Mutex;+use std::ops::Range;+use std::path::PathBuf;+use std::sync::Arc;+use unicode_segmentation::UnicodeSegmentation;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) enum Affinity {+ Before,+ After,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) struct SourcePosition {+ pub byte: usize,+ pub affinity: Affinity,+}++impl SourcePosition {+ pub(crate) fn new(byte: usize) -> Self {+ Self {+ byte,+ affinity: Affinity::After,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct SourceSelection {+ pub anchor: SourcePosition,+ pub focus: SourcePosition,+}++impl SourceSelection {+ pub(crate) fn caret(byte: usize) -> Self {+ let position = SourcePosition::new(byte);+ Self {+ anchor: position,+ focus: position,+ }+ }++ pub(crate) fn range(self) -> Range<usize> {+ self.anchor.byte.min(self.focus.byte)..self.anchor.byte.max(self.focus.byte)+ }++ pub(crate) fn is_caret(self) -> bool {+ self.anchor.byte == self.focus.byte+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum EditorMode {+ LivePreview,+ Source,+ ReadOnly,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum SaveState {+ Saved,+ Dirty,+ Saving(u64),+ Failed(String),+}++#[derive(Debug, Clone)]+pub(crate) struct EditorViewState {+ pub selection: SourceSelection,+ pub preferred_column: Option<usize>,+ pub scroll_offset: f32,+ pub mode: EditorMode,+ pub focused: bool,+ pub preedit: Option<String>,+}++impl Default for EditorViewState {+ fn default() -> Self {+ Self {+ selection: SourceSelection::caret(0),+ preferred_column: None,+ scroll_offset: 0.0,+ mode: EditorMode::LivePreview,+ focused: false,+ preedit: None,+ }+ }+}++#[derive(Debug, Clone)]+struct EditRecord {+ start: usize,+ deleted: String,+ inserted: String,+ before: SourceSelection,+ after: SourceSelection,+}++#[derive(Debug)]+pub(crate) struct MarkdownDocumentSession {+ #[allow(dead_code)]+ pub document_id: String,+ pub path: PathBuf,+ source: String,+ revision: u64,+ saved_revision: u64,+ save_state: SaveState,+ line_starts: Vec<usize>,+ undo: Vec<EditRecord>,+ redo: Vec<EditRecord>,+ save_lock: Arc<Mutex<()>>,+}++const MAX_UNDO_RECORDS: usize = 512;++impl MarkdownDocumentSession {+ pub(crate) fn new(document_id: String, path: PathBuf, source: String) -> Self {+ let line_starts = line_starts(&source);+ Self {+ document_id,+ path,+ source,+ revision: 0,+ saved_revision: 0,+ save_state: SaveState::Saved,+ line_starts,+ undo: vec![],+ redo: vec![],+ save_lock: Arc::new(Mutex::new(())),+ }+ }++ pub(crate) fn source(&self) -> &str {+ &self.source+ }++ pub(crate) fn revision(&self) -> u64 {+ self.revision+ }++ pub(crate) fn save_state(&self) -> &SaveState {+ &self.save_state+ }++ pub(crate) fn is_dirty(&self) -> bool {+ self.revision != self.saved_revision+ }++ pub(crate) fn snapshot_for_save(&mut self) -> (u64, PathBuf, String) {+ let revision = self.revision;+ self.save_state = SaveState::Saving(revision);+ (revision, self.path.clone(), self.source.clone())+ }++ pub(crate) fn save_lock(&self) -> Arc<Mutex<()>> {+ Arc::clone(&self.save_lock)+ }++ pub(crate) fn finish_save(&mut self, revision: u64, result: anyhow::Result<()>) {+ match result {+ Ok(()) => {+ self.saved_revision = self.saved_revision.max(revision);+ self.save_state = if self.saved_revision == self.revision {+ SaveState::Saved+ } else {+ SaveState::Dirty+ };+ }+ Err(err) => self.save_state = SaveState::Failed(format!("{err:#}")),+ }+ }++ pub(crate) fn selected_text(&self, view: &EditorViewState) -> Option<&str> {+ let range = self.clamped_selection_range(view);+ (range.start != range.end).then(|| &self.source[range])+ }++ pub(crate) fn set_caret(&self, view: &mut EditorViewState, byte: usize, extend: bool) {+ let byte = clamp_char_boundary(&self.source, byte);+ if extend {+ view.selection.focus = SourcePosition::new(byte);+ } else {+ view.selection = SourceSelection::caret(byte);+ }+ view.preferred_column = None;+ }++ pub(crate) fn select_all(&self, view: &mut EditorViewState) {+ view.selection = SourceSelection {+ anchor: SourcePosition::new(0),+ focus: SourcePosition::new(self.source.len()),+ };+ view.preferred_column = None;+ }++ pub(crate) fn clamp_view(&self, view: &mut EditorViewState) {+ view.selection.anchor.byte = clamp_char_boundary(&self.source, view.selection.anchor.byte);+ view.selection.focus.byte = clamp_char_boundary(&self.source, view.selection.focus.byte);+ }++ pub(crate) fn insert_text(&mut self, view: &mut EditorViewState, text: &str) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let filtered: String = text+ .chars()+ .filter_map(|ch| match ch {+ '\r' => None,+ '\n' | '\t' => Some(ch),+ _ if ch.is_control() => None,+ _ => Some(ch),+ })+ .collect();+ if filtered.is_empty() {+ return false;+ }+ let range = self.clamped_selection_range(view);+ self.replace_range(view, range, &filtered)+ }++ pub(crate) fn surround_selection(+ &mut self,+ view: &mut EditorViewState,+ prefix: &str,+ suffix: &str,+ ) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let range = self.clamped_selection_range(view);+ let selected_len = range.end.saturating_sub(range.start);+ let inserted = format!("{prefix}{}{suffix}", &self.source[range.clone()]);+ let start = range.start;+ if !self.replace_range(view, range, &inserted) {+ return false;+ }+ view.selection = if selected_len == 0 {+ SourceSelection::caret(start + prefix.len())+ } else {+ SourceSelection {+ anchor: SourcePosition::new(start + prefix.len()),+ focus: SourcePosition::new(start + prefix.len() + selected_len),+ }+ };+ 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;+ }+ if !view.selection.is_caret() {+ return self.insert_text(view, "\n");+ }+ let caret = clamp_char_boundary(&self.source, view.selection.focus.byte);+ let (line_start, line_end) = self.line_bounds(caret);+ let before = &self.source[line_start..caret];+ let indent_len = before+ .bytes()+ .take_while(|byte| matches!(byte, b' ' | b'\t'))+ .count();+ let indent = &before[..indent_len];+ let content = &before[indent_len..];+ let continuation = markdown_line_continuation(content);+ if continuation.is_some() && markdown_line_is_empty_marker(content) && caret == line_end {+ view.selection = SourceSelection {+ anchor: SourcePosition::new(line_start),+ focus: SourcePosition::new(caret),+ };+ return self.backspace(view);+ }+ let inserted = match continuation {+ Some(marker) => format!("\n{indent}{marker}"),+ None => format!("\n{indent}"),+ };+ self.insert_text(view, &inserted)+ }++ pub(crate) fn backspace(&mut self, view: &mut EditorViewState) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let selection = view.selection.range();+ if selection.start != selection.end {+ return self.replace_range(view, selection, "");+ }+ let caret = view.selection.focus.byte;+ let previous = previous_grapheme_boundary(&self.source, caret);+ if previous == caret {+ return false;+ }+ self.replace_range(view, previous..caret, "")+ }++ pub(crate) fn delete_forward(&mut self, view: &mut EditorViewState) -> bool {+ if view.mode == EditorMode::ReadOnly {+ return false;+ }+ let selection = view.selection.range();+ if selection.start != selection.end {+ return self.replace_range(view, selection, "");+ }+ let caret = view.selection.focus.byte;+ let next = next_grapheme_boundary(&self.source, caret);+ if next == caret {+ return false;+ }+ self.replace_range(view, caret..next, "")+ }++ pub(crate) fn move_left(&self, view: &mut EditorViewState, extend: bool) {+ if !extend && !view.selection.is_caret() {+ self.set_caret(view, view.selection.range().start, false);+ return;+ }+ let target = previous_grapheme_boundary(&self.source, view.selection.focus.byte);+ self.set_caret(view, target, extend);+ }++ pub(crate) fn move_right(&self, view: &mut EditorViewState, extend: bool) {+ if !extend && !view.selection.is_caret() {+ self.set_caret(view, view.selection.range().end, false);+ return;+ }+ let target = next_grapheme_boundary(&self.source, view.selection.focus.byte);+ self.set_caret(view, target, extend);+ }++ pub(crate) fn move_word_left(&self, view: &mut EditorViewState, extend: bool) {+ let target = previous_word_boundary(&self.source, view.selection.focus.byte);+ self.set_caret(view, target, extend);+ }++ pub(crate) fn move_word_right(&self, view: &mut EditorViewState, extend: bool) {+ let target = next_word_boundary(&self.source, view.selection.focus.byte);+ self.set_caret(view, target, extend);+ }++ pub(crate) fn delete_word_back(&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 previous = previous_word_boundary(&self.source, caret);+ self.replace_range(view, previous..caret, "")+ }++ 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);+ }++ pub(crate) fn move_line_end(&self, view: &mut EditorViewState, extend: bool) {+ let (_, end) = self.line_bounds(view.selection.focus.byte);+ self.set_caret(view, end, extend);+ }++ pub(crate) fn move_vertical(&self, view: &mut EditorViewState, delta: isize, extend: bool) {+ let caret = view.selection.focus.byte;+ let line = self.line_index(caret);+ let (line_start, _) = self.line_bounds(caret);+ let column = grapheme_column(&self.source[line_start..caret]);+ let desired = view.preferred_column.unwrap_or(column);+ let target_line = if delta.is_negative() {+ line.saturating_sub(delta.unsigned_abs())+ } else {+ line.saturating_add(delta as usize)+ .min(self.line_starts.len().saturating_sub(1))+ };+ 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;+ let anchor = if extend {+ Some(view.selection.anchor)+ } else {+ None+ };+ self.set_caret(view, target, extend);+ if let Some(anchor) = anchor {+ view.selection.anchor = anchor;+ }+ view.preferred_column = Some(desired);+ }++ pub(crate) fn undo(&mut self, view: &mut EditorViewState) -> bool {+ let Some(edit) = self.undo.pop() else {+ return false;+ };+ let end = edit.start + edit.inserted.len();+ self.source.replace_range(edit.start..end, &edit.deleted);+ view.selection = edit.before;+ self.redo.push(edit);+ self.note_mutation();+ true+ }++ pub(crate) fn redo(&mut self, view: &mut EditorViewState) -> bool {+ let Some(edit) = self.redo.pop() else {+ return false;+ };+ let end = edit.start + edit.deleted.len();+ self.source.replace_range(edit.start..end, &edit.inserted);+ view.selection = edit.after;+ self.undo.push(edit);+ self.note_mutation();+ true+ }++ fn replace_range(+ &mut self,+ view: &mut EditorViewState,+ range: Range<usize>,+ inserted: &str,+ ) -> bool {+ let start = clamp_char_boundary(&self.source, range.start);+ let end = clamp_char_boundary(&self.source, range.end).max(start);+ if start == end && inserted.is_empty() {+ return false;+ }+ let before = view.selection;+ let deleted = self.source[start..end].to_string();+ self.source.replace_range(start..end, inserted);+ let after = SourceSelection::caret(start + inserted.len());+ view.selection = after;+ view.preferred_column = None;+ self.undo.push(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();+ true+ }++ fn note_mutation(&mut self) {+ self.revision = self.revision.wrapping_add(1);+ self.save_state = SaveState::Dirty;+ self.line_starts = line_starts(&self.source);+ }++ fn clamped_selection_range(&self, view: &EditorViewState) -> Range<usize> {+ let range = view.selection.range();+ let start = clamp_char_boundary(&self.source, range.start);+ let end = clamp_char_boundary(&self.source, range.end).max(start);+ start..end+ }++ fn line_index(&self, byte: usize) -> usize {+ let byte = byte.min(self.source.len());+ self.line_starts+ .partition_point(|start| *start <= byte)+ .saturating_sub(1)+ }++ fn line_end(&self, line: usize) -> usize {+ self.line_starts+ .get(line + 1)+ .map(|next| next.saturating_sub(1))+ .unwrap_or(self.source.len())+ }++ fn line_bounds(&self, byte: usize) -> (usize, usize) {+ let line = self.line_index(byte);+ (self.line_starts[line], self.line_end(line))+ }+}++fn line_starts(source: &str) -> Vec<usize> {+ let mut starts = vec![0];+ starts.extend(+ source+ .match_indices('\n')+ .map(|(idx, _)| idx.saturating_add(1)),+ );+ starts+}++fn clamp_char_boundary(source: &str, mut byte: usize) -> usize {+ byte = byte.min(source.len());+ while byte > 0 && !source.is_char_boundary(byte) {+ byte -= 1;+ }+ byte+}++fn previous_grapheme_boundary(source: &str, byte: usize) -> usize {+ let byte = clamp_char_boundary(source, byte);+ source[..byte]+ .grapheme_indices(true)+ .next_back()+ .map(|(idx, _)| idx)+ .unwrap_or(0)+}++fn next_grapheme_boundary(source: &str, byte: usize) -> usize {+ let byte = clamp_char_boundary(source, byte);+ source[byte..]+ .grapheme_indices(true)+ .nth(1)+ .map(|(idx, _)| byte + idx)+ .unwrap_or(source.len())+}++fn previous_word_boundary(source: &str, byte: usize) -> usize {+ let mut cursor = clamp_char_boundary(source, byte);+ let mut class = None;+ while cursor > 0 {+ let previous = previous_grapheme_boundary(source, cursor);+ let grapheme = &source[previous..cursor];+ let next_class = word_class(grapheme);+ if class.is_none() && next_class == 0 {+ cursor = previous;+ continue;+ }+ if let Some(class) = class {+ if next_class != class {+ break;+ }+ } else {+ class = Some(next_class);+ }+ cursor = previous;+ }+ cursor+}++fn next_word_boundary(source: &str, byte: usize) -> usize {+ let mut cursor = clamp_char_boundary(source, byte);+ let mut class = None;+ while cursor < source.len() {+ let next = next_grapheme_boundary(source, cursor);+ let grapheme = &source[cursor..next];+ let next_class = word_class(grapheme);+ if class.is_none() && next_class == 0 {+ cursor = next;+ continue;+ }+ if let Some(class) = class {+ if next_class != class {+ break;+ }+ } else {+ class = Some(next_class);+ }+ cursor = next;+ }+ cursor+}++fn word_class(grapheme: &str) -> u8 {+ if grapheme.chars().all(char::is_whitespace) {+ 0+ } else if grapheme.chars().any(|ch| ch.is_alphanumeric() || ch == '_') {+ 1+ } else {+ 2+ }+}++fn grapheme_column(text: &str) -> usize {+ text.graphemes(true).count()+}++fn byte_for_grapheme_column(text: &str, column: usize) -> usize {+ text.grapheme_indices(true)+ .nth(column)+ .map(|(idx, _)| idx)+ .unwrap_or(text.len())+}++fn markdown_line_continuation(content: &str) -> Option<String> {+ for bullet in ["- ", "* ", "+ ", "> "] {+ if content.starts_with(bullet) {+ if content[bullet.len()..].starts_with("[ ] ")+ || content[bullet.len()..]+ .to_ascii_lowercase()+ .starts_with("[x] ")+ {+ return Some(format!("{bullet}[ ] "));+ }+ return Some(bullet.to_string());+ }+ }+ let digits = content.chars().take_while(|ch| ch.is_ascii_digit()).count();+ if digits == 0 {+ return None;+ }+ let suffix = content.as_bytes().get(digits..digits + 2)?;+ if suffix != b". " && suffix != b") " {+ return None;+ }+ let number = content[..digits].parse::<u64>().ok()?.saturating_add(1);+ Some(format!("{number}{}", &content[digits..digits + 2]))+}++fn markdown_line_is_empty_marker(content: &str) -> bool {+ let trimmed = content.trim_end();+ if matches!(trimmed, "-" | "*" | "+" | ">")+ || matches!(+ trimmed.to_ascii_lowercase().as_str(),+ "- [ ]" | "- [x]" | "* [ ]" | "* [x]" | "+ [ ]" | "+ [x]"+ )+ {+ return true;+ }+ let digits = trimmed.chars().take_while(|ch| ch.is_ascii_digit()).count();+ digits > 0+ && trimmed+ .as_bytes()+ .get(digits)+ .is_some_and(|suffix| matches!(*suffix, b'.' | b')'))+ && trimmed.len() == digits + 1+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session(text: &str) -> (MarkdownDocumentSession, EditorViewState) {+ (+ MarkdownDocumentSession::new("doc".into(), PathBuf::from("Inbox.md"), text.into()),+ EditorViewState::default(),+ )+ }++ #[test]+ fn grapheme_backspace_removes_one_visible_character() {+ let (mut session, mut view) = session("a👨👩👧👦你");+ session.set_caret(&mut view, session.source().len(), false);+ assert!(session.backspace(&mut view));+ assert_eq!(session.source(), "a👨👩👧👦");+ assert!(session.backspace(&mut view));+ assert_eq!(session.source(), "a");+ }++ #[test]+ fn undo_redo_restores_source_and_selection() {+ let (mut session, mut view) = session("hello");+ session.set_caret(&mut view, 5, false);+ session.insert_text(&mut view, " 世界");+ assert_eq!(session.source(), "hello 世界");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "hello");+ assert!(session.redo(&mut view));+ assert_eq!(session.source(), "hello 世界");+ }++ #[test]+ fn vertical_navigation_preserves_grapheme_column() {+ let (session, mut view) = session("abcd\n你😀\nabcdef");+ session.set_caret(&mut view, 3, false);+ session.move_vertical(&mut view, 1, false);+ assert_eq!(view.selection.focus.byte, "abcd\n你😀".len());+ session.move_vertical(&mut view, 1, false);+ assert_eq!(view.selection.focus.byte, "abcd\n你😀\nabc".len());+ }++ #[test]+ fn stale_save_completion_does_not_clear_newer_dirty_revision() {+ let (mut session, mut view) = session("a");+ session.set_caret(&mut view, 1, false);+ session.insert_text(&mut view, "b");+ let (revision, _, _) = session.snapshot_for_save();+ session.insert_text(&mut view, "c");+ session.finish_save(revision, Ok(()));+ assert!(session.is_dirty());+ assert_eq!(session.save_state(), &SaveState::Dirty);+ }++ #[test]+ fn formatting_surrounds_selection_and_read_only_blocks_edits() {+ let (mut session, mut view) = session("hello");+ view.selection = SourceSelection {+ anchor: SourcePosition::new(0),+ focus: SourcePosition::new(5),+ };+ assert!(session.surround_selection(&mut view, "**", "**"));+ assert_eq!(session.source(), "**hello**");+ assert_eq!(session.selected_text(&view), Some("hello"));+ view.mode = EditorMode::ReadOnly;+ assert!(!session.insert_text(&mut view, "x"));+ assert_eq!(session.source(), "**hello**");+ }++ #[test]+ fn stale_window_selection_is_clamped_after_shared_edits() {+ let (mut session, mut first_view) = session("shared");+ let mut stale_view = EditorViewState::default();+ session.set_caret(&mut stale_view, session.source().len(), false);+ session.select_all(&mut first_view);+ assert!(session.backspace(&mut first_view));+ assert_eq!(session.selected_text(&stale_view), None);+ assert!(session.insert_text(&mut stale_view, "safe"));+ assert_eq!(session.source(), "safe");+ }++ #[test]+ fn newline_continues_and_exits_markdown_lists() {+ let (mut task_session, mut view) = session("- [x] done");+ task_session.set_caret(&mut view, task_session.source().len(), false);+ assert!(task_session.insert_newline(&mut view));+ assert_eq!(task_session.source(), "- [x] done\n- [ ] ");++ let (mut ordered, mut ordered_view) = session("9. item");+ ordered.set_caret(&mut ordered_view, ordered.source().len(), false);+ assert!(ordered.insert_newline(&mut ordered_view));+ assert_eq!(ordered.source(), "9. item\n10. ");+ assert!(ordered.insert_newline(&mut ordered_view));+ assert_eq!(ordered.source(), "9. item\n");+ }++ #[test]+ fn word_navigation_and_delete_are_unicode_safe() {+ let (mut session, mut view) = session("hello 你好 👋 world");+ session.set_caret(&mut view, session.source().len(), false);+ session.move_word_left(&mut view, false);+ assert_eq!(&session.source()[view.selection.focus.byte..], "world");+ assert!(session.delete_word_back(&mut view));+ assert_eq!(session.source(), "hello 你好 world");+ session.move_word_left(&mut view, false);+ assert_eq!(&session.source()[view.selection.focus.byte..], "你好 world");+ session.move_word_right(&mut view, false);+ assert_eq!(&session.source()[view.selection.focus.byte..], " world");+ }+}diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rsnew file mode 100644index 00000000..bcaa3cf4--- /dev/null+++ b/wezterm-gui/src/markdown_editor/host.rs@@ -0,0 +1,420 @@+use super::{+ build_visual_document, default_document_session, EditorViewState, MarkdownDocumentSession,+ MarkdownProjection, ProjectedObject, SourcePosition, VisualDocument,+};+use parking_lot::Mutex;+use std::collections::{HashMap, HashSet};+use std::ops::Range;+use std::sync::Arc;++#[derive(Debug, Clone)]+pub(crate) struct NoteRunLayout {+ pub source: Range<usize>,+ pub x: f32,+ pub width: f32,+ pub hit_x: f32,+ pub hit_width: f32,+ /// Visual x offsets paired with the source byte position reached at that+ /// boundary. Contains both the leading and trailing edge.+ pub boundaries: Vec<(f32, usize)>,+ pub atomic: bool,+}++#[derive(Debug, Clone)]+pub(crate) struct NoteLineLayout {+ pub source: Range<usize>,+ pub y: f32,+ pub height: f32,+ pub runs: Vec<NoteRunLayout>,+}++#[derive(Debug, Clone)]+pub(crate) struct NoteCodeBlockLayout {+ pub source_start: usize,+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+ pub max_horizontal_scroll: f32,+}++pub(crate) struct NoteHostState {+ pub session: Option<Arc<Mutex<MarkdownDocumentSession>>>,+ pub view: EditorViewState,+ pub projection: MarkdownProjection,+ pub visual: VisualDocument,+ wrapped_visual: Arc<VisualDocument>,+ pub projection_revision: Option<u64>,+ pub visual_key: Option<(u64, super::EditorMode, usize)>,+ wrapped_key: Option<(u64, super::EditorMode, usize, usize)>,+ pub line_layouts: Vec<NoteLineLayout>,+ pub viewport_height: f32,+ pub content_height: f32,+ pub load_error: Option<String>,+ pub save_generation: u64,+ pub reveal_caret: bool,+ pub drag_selection_active: bool,+ pub drag_autoscroll_scheduled: bool,+ pub collapsed_code_blocks: HashSet<usize>,+ pub code_horizontal_offsets: HashMap<usize, f32>,+ pub code_block_layouts: Vec<NoteCodeBlockLayout>,+}++impl Default for NoteHostState {+ fn default() -> Self {+ Self {+ session: None,+ view: EditorViewState::default(),+ projection: MarkdownProjection::default(),+ visual: VisualDocument::default(),+ wrapped_visual: Arc::new(VisualDocument::default()),+ projection_revision: None,+ visual_key: None,+ wrapped_key: None,+ line_layouts: vec![],+ viewport_height: 0.0,+ content_height: 0.0,+ load_error: None,+ save_generation: 0,+ reveal_caret: true,+ drag_selection_active: false,+ drag_autoscroll_scheduled: false,+ collapsed_code_blocks: HashSet::new(),+ code_horizontal_offsets: HashMap::new(),+ code_block_layouts: vec![],+ }+ }+}++impl NoteHostState {+ pub(crate) fn ensure_loaded(&mut self) -> bool {+ if self.session.is_some() {+ return true;+ }+ match default_document_session() {+ Ok(session) => {+ self.view.selection = super::SourceSelection::caret(0);+ self.session = Some(session);+ self.load_error = None;+ self.refresh_projection();+ true+ }+ Err(err) => {+ self.load_error = Some(format!("{err:#}"));+ false+ }+ }+ }++ pub(crate) fn refresh_projection(&mut self) {+ let Some(session) = self.session.as_ref() else {+ return;+ };+ let session = session.lock();+ let revision = session.revision();+ let source = session.source();+ if self.projection_revision != Some(revision) {+ self.projection = MarkdownProjection::parse(source);+ let code_starts = self+ .projection+ .objects+ .iter()+ .filter_map(|object| match object {+ ProjectedObject::CodeBlock(code) => Some(code.source.start),+ _ => None,+ })+ .collect::<HashSet<_>>();+ self.collapsed_code_blocks+ .retain(|source_start| code_starts.contains(source_start));+ self.code_horizontal_offsets+ .retain(|source_start, _| code_starts.contains(source_start));+ self.projection_revision = Some(revision);+ self.visual_key = None;+ }+ let active_start = self+ .projection+ .active_syntax(self.view.selection.focus.byte)+ .map(|node| node.source.start)+ .unwrap_or(usize::MAX);+ let key = (revision, self.view.mode, active_start);+ if self.visual_key != Some(key) {+ self.visual = build_visual_document(+ source,+ &self.projection,+ self.view.mode,+ self.view.selection.focus.byte,+ );+ self.visual_key = Some(key);+ self.wrapped_key = None;+ }+ }++ pub(crate) fn cached_wrapped_visual(&self, wrap_key: usize) -> Option<Arc<VisualDocument>> {+ let Some((revision, mode, active_start)) = self.visual_key else {+ return None;+ };+ (self.wrapped_key == Some((revision, mode, active_start, wrap_key)))+ .then(|| Arc::clone(&self.wrapped_visual))+ }++ pub(crate) fn cache_wrapped_visual(+ &mut self,+ wrap_key: usize,+ visual: VisualDocument,+ ) -> Arc<VisualDocument> {+ self.wrapped_visual = Arc::new(visual);+ if let Some((revision, mode, active_start)) = self.visual_key {+ self.wrapped_key = Some((revision, mode, active_start, wrap_key));+ }+ Arc::clone(&self.wrapped_visual)+ }++ pub(crate) fn source_position_for_point(&self, x: f32, y: f32) -> SourcePosition {+ let Some(line) = self+ .line_layouts+ .iter()+ .min_by(|a, b| distance_to_line(a, y).total_cmp(&distance_to_line(b, y)))+ else {+ return SourcePosition::new(0);+ };+ if line.runs.is_empty() {+ return SourcePosition::new(line.source.start);+ }+ let run = line+ .runs+ .iter()+ .min_by(|a, b| distance_to_run(a, x).total_cmp(&distance_to_run(b, x)))+ .expect("non-empty runs");+ if run.atomic {+ let midpoint = run.x + run.width / 2.0;+ return SourcePosition {+ byte: if x < midpoint {+ run.source.start+ } else {+ run.source.end+ },+ affinity: if x < midpoint {+ super::Affinity::Before+ } else {+ super::Affinity::After+ },+ };+ }+ run.boundaries+ .iter()+ .min_by(|(ax, _), (bx, _)| (x - *ax).abs().total_cmp(&(x - *bx).abs()))+ .map(|(_, byte)| SourcePosition::new(*byte))+ .unwrap_or_else(|| SourcePosition::new(run.source.start))+ }++ /// 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.+ 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| {+ line.runs+ .iter()+ .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+ .iter()+ .find(|run| run.source.start <= caret && caret <= run.source.end)+ .and_then(|run| {+ run.boundaries+ .iter()+ .min_by_key(|(_, source)| source.abs_diff(caret))+ .map(|(x, _)| *x)+ })+ .or_else(|| current_line.runs.first().map(|run| run.x))+ .unwrap_or(0.0);+ let preferred = self+ .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))+ }++ pub(crate) fn atomic_source_for_point(&self, x: f32, y: f32) -> Option<Range<usize>> {+ self.line_layouts+ .iter()+ .find(|line| y >= line.y && y <= line.y + line.height)?+ .runs+ .iter()+ .find(|run| run.atomic && x >= run.x && x <= run.x + run.width)+ .map(|run| run.source.clone())+ }++ pub(crate) fn table_cell_target(&self, delta: isize) -> Option<usize> {+ let caret = self.view.selection.focus.byte;+ let cells: Vec<_> = self+ .projection+ .objects+ .iter()+ .filter_map(|object| match object {+ ProjectedObject::Table(table) => Some(table),+ _ => None,+ })+ .flat_map(|table| table.rows.iter().flat_map(|row| row.iter()))+ .collect();+ let current = cells+ .iter()+ .position(|cell| cell.source.start <= caret && caret <= cell.source.end)?;+ let target = if delta.is_negative() {+ current.checked_sub(delta.unsigned_abs())?+ } else {+ current.checked_add(delta as usize)?+ };+ cells.get(target).map(|cell| cell.source.start)+ }++ pub(crate) fn clamp_scroll(&mut self) {+ let max = (self.content_height - self.viewport_height).max(0.0);+ self.view.scroll_offset = self.view.scroll_offset.clamp(0.0, max);+ }++ pub(crate) fn scroll_by(&mut self, delta: f32) -> bool {+ let old = self.view.scroll_offset;+ self.view.scroll_offset += delta;+ self.clamp_scroll();+ (old - self.view.scroll_offset).abs() > f32::EPSILON+ }++ pub(crate) fn toggle_code_block(&mut self, source_start: usize) -> bool {+ if !self.collapsed_code_blocks.remove(&source_start) {+ self.collapsed_code_blocks.insert(source_start);+ true+ } else {+ false+ }+ }++ pub(crate) fn scroll_code_block_at(&mut self, x: f32, y: f32, delta: f32) -> bool {+ let Some(layout) = self.code_block_layouts.iter().find(|layout| {+ x >= layout.x+ && x <= layout.x + layout.width+ && y >= layout.y+ && y <= layout.y + layout.height+ && layout.max_horizontal_scroll > 0.0+ }) else {+ return false;+ };+ let offset = self+ .code_horizontal_offsets+ .entry(layout.source_start)+ .or_default();+ let old = *offset;+ *offset = (*offset + delta).clamp(0.0, layout.max_horizontal_scroll);+ (old - *offset).abs() > f32::EPSILON+ }+}++fn distance_to_line(line: &NoteLineLayout, y: f32) -> f32 {+ if y < line.y {+ line.y - y+ } else if y > line.y + line.height {+ y - (line.y + line.height)+ } else {+ 0.0+ }+}++fn distance_to_run(run: &NoteRunLayout, x: f32) -> f32 {+ if x < run.hit_x {+ run.hit_x - x+ } else if x > run.hit_x + run.hit_width {+ x - (run.hit_x + run.hit_width)+ } else {+ 0.0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn run(source: Range<usize>, glyph_x: f32, cell_x: f32) -> NoteRunLayout {+ NoteRunLayout {+ boundaries: vec![(glyph_x, source.start), (glyph_x + 10.0, source.end)],+ source,+ x: glyph_x,+ width: 10.0,+ hit_x: cell_x,+ hit_width: 100.0,+ atomic: false,+ }+ }++ #[test]+ fn table_cell_whitespace_hits_its_own_source_range() {+ let mut host = NoteHostState::default();+ host.line_layouts.push(NoteLineLayout {+ source: 0..20,+ y: 10.0,+ height: 30.0,+ runs: vec![run(1..2, 10.0, 0.0), run(11..12, 110.0, 100.0)],+ });++ assert_eq!(host.source_position_for_point(90.0, 20.0).byte, 2);+ assert_eq!(host.source_position_for_point(110.0, 20.0).byte, 11);+ assert_eq!(host.source_position_for_point(190.0, 20.0).byte, 12);+ }++ #[test]+ fn point_selection_chooses_the_nearest_visual_row() {+ let mut host = NoteHostState::default();+ host.line_layouts = vec![+ NoteLineLayout {+ source: 0..1,+ y: 10.0,+ height: 20.0,+ runs: vec![run(0..1, 0.0, 0.0)],+ },+ NoteLineLayout {+ source: 2..3,+ y: 40.0,+ height: 20.0,+ runs: vec![run(2..3, 0.0, 0.0)],+ },+ ];++ assert_eq!(host.source_position_for_point(0.0, 5.0).byte, 0);+ assert_eq!(host.source_position_for_point(0.0, 65.0).byte, 2);+ }++ #[test]+ fn code_block_view_state_is_per_block_and_bounded() {+ let mut host = NoteHostState::default();+ assert!(host.toggle_code_block(10));+ assert!(host.collapsed_code_blocks.contains(&10));+ assert!(!host.toggle_code_block(10));+ assert!(!host.collapsed_code_blocks.contains(&10));++ host.code_block_layouts.push(NoteCodeBlockLayout {+ source_start: 20,+ x: 100.0,+ y: 50.0,+ width: 300.0,+ height: 120.0,+ max_horizontal_scroll: 80.0,+ });+ assert!(!host.scroll_code_block_at(20.0, 60.0, 30.0));+ assert!(host.scroll_code_block_at(200.0, 80.0, 30.0));+ assert_eq!(host.code_horizontal_offsets.get(&20), Some(&30.0));+ assert!(host.scroll_code_block_at(200.0, 80.0, 100.0));+ assert_eq!(host.code_horizontal_offsets.get(&20), Some(&80.0));+ assert!(!host.scroll_code_block_at(200.0, 80.0, 100.0));+ }+}diff --git a/wezterm-gui/src/markdown_editor/mod.rs b/wezterm-gui/src/markdown_editor/mod.rsnew file mode 100644index 00000000..68349d4d--- /dev/null+++ b/wezterm-gui/src/markdown_editor/mod.rs@@ -0,0 +1,28 @@+//! Native, host-independent Markdown document/editor primitives.+//!+//! The right-sidebar Note is the first host, but this module deliberately has+//! no dependency on right-sidebar state so that a full content view and+//! read-only previews can share the same source/projection model.++mod document;+mod host;+mod projection;+mod store;+mod surface;++pub(crate) use document::{+ Affinity, EditorMode, EditorViewState, MarkdownDocumentSession, SaveState, SourcePosition,+ SourceSelection,+};+pub(crate) use host::{NoteCodeBlockLayout, NoteHostState, NoteLineLayout, NoteRunLayout};+pub(crate) use projection::{+ BlockKind, InlineStyle, MarkdownProjection, ProjectedCodeBlock, ProjectedObject, TableAlignment,+};+pub(crate) use store::{+ default_document_session, default_notebook, import_attachment, resolve_local_image,+ save_document_revision,+};+pub(crate) use surface::{+ build_visual_document, fit_table_columns, wrap_visual_document_by_width, VisualDocument,+ VisualLineKind,+};diff --git a/wezterm-gui/src/markdown_editor/projection.rs b/wezterm-gui/src/markdown_editor/projection.rsnew file mode 100644index 00000000..3634564e--- /dev/null+++ b/wezterm-gui/src/markdown_editor/projection.rs@@ -0,0 +1,758 @@+use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};+use std::ops::Range;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum BlockKind {+ Paragraph,+ Heading(u8),+ Quote,+ List,+ ListItem,+ CodeBlock,+ Table,+ Other,+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub(crate) struct InlineStyle {+ pub strong: bool,+ pub emphasis: bool,+ pub strikethrough: bool,+ pub code: bool,+ pub link: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum MarkdownSyntaxKind {+ Heading,+ Emphasis,+ Strong,+ Strikethrough,+ Link,+ Image,+ InlineCode,+ List,+ ListItem,+ Quote,+ CodeBlock,+ Table,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct MarkdownSyntaxNode {+ pub kind: MarkdownSyntaxKind,+ pub source: Range<usize>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectedText {+ pub source: Range<usize>,+ pub text: String,+ pub style: InlineStyle,+ pub block: BlockKind,+ pub link_target: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectedTableCell {+ pub source: Range<usize>,+ pub text: String,+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub(crate) enum TableAlignment {+ #[default]+ None,+ Left,+ Center,+ Right,+}++impl From<Alignment> for TableAlignment {+ fn from(value: Alignment) -> Self {+ match value {+ Alignment::None => Self::None,+ Alignment::Left => Self::Left,+ Alignment::Center => Self::Center,+ Alignment::Right => Self::Right,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectedTable {+ pub source: Range<usize>,+ pub rows: Vec<Vec<ProjectedTableCell>>,+ pub alignments: Vec<TableAlignment>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectedCodeBlock {+ /// Full Markdown range, including the opening/closing fences when fenced.+ pub source: Range<usize>,+ /// Exact editable code content, excluding fences and language metadata.+ pub content: Range<usize>,+ pub text: String,+ pub language: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum ProjectedObject {+ Rule {+ source: Range<usize>,+ },+ TaskCheckbox {+ source: Range<usize>,+ checked: bool,+ },+ ListMarker {+ source: Range<usize>,+ text: String,+ },+ Image {+ source: Range<usize>,+ target: String,+ title: String,+ alt: String,+ },+ CodeBlock(ProjectedCodeBlock),+ Table(ProjectedTable),+}++impl ProjectedObject {+ pub(crate) fn source(&self) -> Range<usize> {+ match self {+ Self::Rule { source }+ | Self::TaskCheckbox { source, .. }+ | Self::ListMarker { source, .. }+ | Self::Image { source, .. } => source.clone(),+ Self::CodeBlock(code) => code.source.clone(),+ Self::Table(table) => table.source.clone(),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectionBlock {+ pub kind: BlockKind,+ pub source: Range<usize>,+}++#[derive(Debug, Clone, Default)]+pub(crate) struct MarkdownProjection {+ pub text: Vec<ProjectedText>,+ pub objects: Vec<ProjectedObject>,+ pub blocks: Vec<ProjectionBlock>,+ pub syntax: Vec<MarkdownSyntaxNode>,+}++#[derive(Debug, Clone, Default)]+struct StyleState {+ strong: usize,+ emphasis: usize,+ strikethrough: usize,+ code: usize,+ links: Vec<String>,+}++impl StyleState {+ fn style(&self) -> InlineStyle {+ InlineStyle {+ strong: self.strong > 0,+ emphasis: self.emphasis > 0,+ strikethrough: self.strikethrough > 0,+ code: self.code > 0,+ link: !self.links.is_empty(),+ }+ }+}++#[derive(Debug)]+struct ImageBuilder {+ source: Range<usize>,+ target: String,+ title: String,+ alt: String,+}++#[derive(Debug)]+struct CodeBlockBuilder {+ source: Range<usize>,+ content: Option<Range<usize>>,+ text: String,+ language: Option<String>,+}++#[derive(Debug)]+struct TableBuilder {+ source: Range<usize>,+ rows: Vec<Vec<ProjectedTableCell>>,+ alignments: Vec<TableAlignment>,+ current_row: Vec<ProjectedTableCell>,+ current_cell_range: Option<Range<usize>>,+ current_cell_text: String,+}++impl MarkdownProjection {+ pub(crate) fn parse(source: &str) -> Self {+ let options =+ Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS;+ let mut projection = Self::default();+ let mut styles = StyleState::default();+ let mut block_stack = vec![BlockKind::Paragraph];+ let mut image: Option<ImageBuilder> = None;+ let mut code_block: Option<CodeBlockBuilder> = None;+ let mut table: Option<TableBuilder> = None;++ for (event, range) in Parser::new_ext(source, options).into_offset_iter() {+ match event {+ Event::Start(tag) => {+ if let Some(kind) = syntax_kind_for_tag(&tag) {+ projection.syntax.push(MarkdownSyntaxNode {+ kind,+ source: range.clone(),+ });+ }+ if let Some(kind) = block_kind_for_tag(&tag) {+ projection.blocks.push(ProjectionBlock {+ kind,+ source: range.clone(),+ });+ block_stack.push(kind);+ }+ match tag {+ Tag::Strong => styles.strong += 1,+ Tag::Emphasis => styles.emphasis += 1,+ Tag::Strikethrough => styles.strikethrough += 1,+ Tag::Link { dest_url, .. } => styles.links.push(dest_url.to_string()),+ Tag::Image {+ dest_url, title, ..+ } => {+ image = Some(ImageBuilder {+ source: range.clone(),+ target: dest_url.to_string(),+ title: title.to_string(),+ alt: String::new(),+ });+ }+ Tag::CodeBlock(kind) => {+ styles.code += 1;+ let language = match kind {+ CodeBlockKind::Fenced(info) => info+ .split_whitespace()+ .next()+ .filter(|language| !language.is_empty())+ .map(ToOwned::to_owned),+ CodeBlockKind::Indented => None,+ };+ code_block = Some(CodeBlockBuilder {+ source: range.clone(),+ content: None,+ text: String::new(),+ language,+ });+ }+ Tag::Table(alignments) => {+ table = Some(TableBuilder {+ source: range.clone(),+ rows: vec![],+ alignments: alignments+ .iter()+ .copied()+ .map(TableAlignment::from)+ .collect(),+ current_row: vec![],+ current_cell_range: None,+ current_cell_text: String::new(),+ });+ }+ Tag::TableRow => {+ if let Some(table) = table.as_mut() {+ table.current_row.clear();+ }+ }+ Tag::TableHead => {+ if let Some(table) = table.as_mut() {+ table.current_row.clear();+ }+ }+ Tag::TableCell => {+ if let Some(table) = table.as_mut() {+ table.current_cell_range = Some(range.clone());+ table.current_cell_text.clear();+ }+ }+ _ => {}+ }+ }+ Event::End(tag) => {+ match tag {+ TagEnd::Strong => styles.strong = styles.strong.saturating_sub(1),+ TagEnd::Emphasis => styles.emphasis = styles.emphasis.saturating_sub(1),+ TagEnd::Strikethrough => {+ styles.strikethrough = styles.strikethrough.saturating_sub(1)+ }+ TagEnd::Link => {+ styles.links.pop();+ }+ TagEnd::Image => {+ if let Some(image) = image.take() {+ projection.objects.push(ProjectedObject::Image {+ source: image.source,+ target: image.target,+ title: image.title,+ alt: image.alt,+ });+ }+ }+ TagEnd::CodeBlock => {+ styles.code = styles.code.saturating_sub(1);+ if let Some(mut code) = code_block.take() {+ code.source = range.clone();+ let content = code.content.take().unwrap_or_else(|| {+ empty_code_block_content_range(source, &code.source)+ });+ projection.objects.push(ProjectedObject::CodeBlock(+ ProjectedCodeBlock {+ source: code.source,+ content,+ text: code.text,+ language: code.language,+ },+ ));+ }+ }+ TagEnd::TableCell => {+ if let Some(table) = table.as_mut() {+ let raw_source = table+ .current_cell_range+ .take()+ .unwrap_or_else(|| range.clone());+ let source = table_cell_content_range(+ source,+ raw_source,+ &table.current_cell_text,+ );+ table.current_row.push(ProjectedTableCell {+ source,+ text: std::mem::take(&mut table.current_cell_text),+ });+ }+ }+ TagEnd::TableRow => {+ if let Some(table) = table.as_mut() {+ if !table.current_row.is_empty() {+ table.rows.push(std::mem::take(&mut table.current_row));+ }+ }+ }+ TagEnd::TableHead => {+ if let Some(table) = table.as_mut() {+ if !table.current_row.is_empty() {+ table.rows.push(std::mem::take(&mut table.current_row));+ }+ }+ }+ TagEnd::Table => {+ if let Some(mut table) = table.take() {+ table.source = range.clone();+ projection+ .objects+ .push(ProjectedObject::Table(ProjectedTable {+ source: table.source,+ rows: table.rows,+ alignments: table.alignments,+ }));+ }+ }+ _ => {}+ }+ if block_kind_for_end(tag).is_some() && block_stack.len() > 1 {+ block_stack.pop();+ }+ }+ Event::Text(text) => {+ if let Some(image) = image.as_mut() {+ image.alt.push_str(&text);+ continue;+ }+ if let Some(table) = table.as_mut() {+ if table.current_cell_range.is_some() {+ table.current_cell_text.push_str(&text);+ }+ }+ let source_range = content_range(source, range, &text);+ if let Some(code) = code_block.as_mut() {+ code.text.push_str(&text);+ code.content = Some(match code.content.take() {+ Some(content) => content.start..source_range.end.max(content.end),+ None => source_range.clone(),+ });+ }+ projection.text.push(ProjectedText {+ source: source_range,+ text: text.to_string(),+ style: styles.style(),+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: styles.links.last().cloned(),+ });+ }+ Event::Code(text) => {+ projection.syntax.push(MarkdownSyntaxNode {+ kind: MarkdownSyntaxKind::InlineCode,+ source: range.clone(),+ });+ let mut style = styles.style();+ style.code = true;+ let source_range = content_range(source, range, &text);+ projection.text.push(ProjectedText {+ source: source_range,+ text: text.to_string(),+ style,+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: styles.links.last().cloned(),+ });+ }+ Event::Html(text) | Event::InlineHtml(text) => {+ projection.text.push(ProjectedText {+ source: range,+ text: text.to_string(),+ style: styles.style(),+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: None,+ });+ }+ Event::SoftBreak | Event::HardBreak => {+ projection.text.push(ProjectedText {+ source: range,+ text: "\n".to_string(),+ style: styles.style(),+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: None,+ });+ }+ Event::Rule => projection+ .objects+ .push(ProjectedObject::Rule { source: range }),+ Event::TaskListMarker(checked) => {+ projection.objects.push(ProjectedObject::TaskCheckbox {+ source: range,+ checked,+ });+ }+ Event::InlineMath(text) | Event::DisplayMath(text) => {+ projection.text.push(ProjectedText {+ source: range,+ text: text.to_string(),+ style: styles.style(),+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: None,+ });+ }+ Event::FootnoteReference(text) => {+ projection.text.push(ProjectedText {+ source: range,+ text: text.to_string(),+ style: styles.style(),+ block: *block_stack.last().unwrap_or(&BlockKind::Other),+ link_target: None,+ });+ }+ }+ }+ projection+ .blocks+ .sort_by_key(|block| (block.source.start, block.source.end));+ projection+ .text+ .sort_by_key(|span| (span.source.start, span.source.end));+ projection.objects.extend(+ projection+ .blocks+ .iter()+ .filter(|block| block.kind == BlockKind::ListItem)+ .filter_map(|block| list_marker(source, &block.source)),+ );+ projection+ }++ pub(crate) fn active_syntax(&self, byte: usize) -> Option<&MarkdownSyntaxNode> {+ self.syntax+ .iter()+ .filter(|node| node.source.start <= byte && byte <= node.source.end)+ .min_by_key(|node| node.source.end.saturating_sub(node.source.start))+ }++ pub(crate) fn visible_source_ranges(+ &self,+ source: &str,+ caret: usize,+ source_mode: bool,+ ) -> Vec<Range<usize>> {+ if source_mode {+ return vec![0..source.len()];+ }+ let mut ranges: Vec<Range<usize>> =+ self.text.iter().map(|span| span.source.clone()).collect();+ ranges.extend(self.objects.iter().map(ProjectedObject::source));+ if let Some(active) = self.active_syntax(caret) {+ ranges.push(active.source.clone());+ }+ for (idx, ch) in source.char_indices() {+ if ch == '\n' {+ ranges.push(idx..idx + 1);+ }+ }+ merge_ranges(ranges, source.len())+ }+}++fn list_marker(source: &str, item: &Range<usize>) -> Option<ProjectedObject> {+ let start = item.start.min(source.len());+ let end = item.end.min(source.len()).max(start);+ let line_end = source[start..end]+ .find('\n')+ .map(|offset| start + offset)+ .unwrap_or(end);+ let line = &source[start..line_end];+ let indent = line.len().saturating_sub(line.trim_start().len());+ let marker_start = start + indent;+ let rest = &line[indent..];+ if rest.starts_with("- [") || rest.starts_with("* [") || rest.starts_with("+ [") {+ return None;+ }+ if rest.starts_with("- ") || rest.starts_with("* ") || rest.starts_with("+ ") {+ return Some(ProjectedObject::ListMarker {+ source: marker_start..marker_start + 2,+ text: "• ".to_string(),+ });+ }+ let digits = rest.chars().take_while(|ch| ch.is_ascii_digit()).count();+ if digits > 0 {+ let suffix = rest.as_bytes().get(digits..digits + 2)?;+ if suffix == b". " || suffix == b") " {+ return Some(ProjectedObject::ListMarker {+ source: marker_start..marker_start + digits + 2,+ text: rest[..digits + 2].to_string(),+ });+ }+ }+ None+}++fn content_range(source: &str, range: Range<usize>, rendered: &str) -> Range<usize> {+ let start = range.start.min(source.len());+ let end = range.end.min(source.len()).max(start);+ let slice = &source[start..end];+ if rendered.is_empty() {+ return start..start;+ }+ if let Some(relative) = slice.find(rendered) {+ return start + relative..start + relative + rendered.len();+ }+ // Escapes and normalized parser text may not be a literal source slice.+ // Keeping the whole event range visible is lossless and safer than hiding+ // characters that the user then cannot reach.+ start..end+}++fn table_cell_content_range(source: &str, range: Range<usize>, rendered: &str) -> Range<usize> {+ if !rendered.is_empty() {+ return content_range(source, range, rendered);+ }+ let start = range.start.min(source.len());+ let end = range.end.min(source.len()).max(start);+ let insertion = source[start..end]+ .char_indices()+ .find(|(_, ch)| !ch.is_whitespace())+ .map(|(relative, _)| start + relative)+ .unwrap_or(end);+ insertion..insertion+}++fn empty_code_block_content_range(source: &str, range: &Range<usize>) -> Range<usize> {+ let start = range.start.min(source.len());+ let end = range.end.min(source.len()).max(start);+ let slice = &source[start..end];+ let content_start = slice+ .find('\n')+ .map(|relative| start + relative + 1)+ .unwrap_or(start);+ content_start..content_start+}++fn merge_ranges(mut ranges: Vec<Range<usize>>, source_len: usize) -> Vec<Range<usize>> {+ ranges.retain(|range| range.start < range.end && range.start < source_len);+ for range in &mut ranges {+ range.end = range.end.min(source_len);+ }+ ranges.sort_by_key(|range| (range.start, range.end));+ let mut merged: Vec<Range<usize>> = vec![];+ for range in ranges {+ if let Some(last) = merged.last_mut() {+ if range.start <= last.end {+ last.end = last.end.max(range.end);+ continue;+ }+ }+ merged.push(range);+ }+ merged+}++fn syntax_kind_for_tag(tag: &Tag<'_>) -> Option<MarkdownSyntaxKind> {+ Some(match tag {+ Tag::Heading { .. } => MarkdownSyntaxKind::Heading,+ Tag::Emphasis => MarkdownSyntaxKind::Emphasis,+ Tag::Strong => MarkdownSyntaxKind::Strong,+ Tag::Strikethrough => MarkdownSyntaxKind::Strikethrough,+ Tag::Link { .. } => MarkdownSyntaxKind::Link,+ Tag::Image { .. } => MarkdownSyntaxKind::Image,+ Tag::List(_) => MarkdownSyntaxKind::List,+ Tag::Item => MarkdownSyntaxKind::ListItem,+ Tag::BlockQuote(_) => MarkdownSyntaxKind::Quote,+ Tag::CodeBlock(_) => MarkdownSyntaxKind::CodeBlock,+ Tag::Table(_) => MarkdownSyntaxKind::Table,+ _ => return None,+ })+}++fn block_kind_for_tag(tag: &Tag<'_>) -> Option<BlockKind> {+ Some(match tag {+ Tag::Paragraph => BlockKind::Paragraph,+ Tag::Heading { level, .. } => BlockKind::Heading(*level as u8),+ Tag::BlockQuote(_) => BlockKind::Quote,+ Tag::List(_) => BlockKind::List,+ Tag::Item => BlockKind::ListItem,+ Tag::CodeBlock(_) => BlockKind::CodeBlock,+ Tag::Table(_) => BlockKind::Table,+ _ => return None,+ })+}++fn block_kind_for_end(tag: TagEnd) -> Option<BlockKind> {+ Some(match tag {+ TagEnd::Paragraph => BlockKind::Paragraph,+ TagEnd::Heading(level) => BlockKind::Heading(level as u8),+ TagEnd::BlockQuote(_) => BlockKind::Quote,+ TagEnd::List(_) => BlockKind::List,+ TagEnd::Item => BlockKind::ListItem,+ TagEnd::CodeBlock => BlockKind::CodeBlock,+ TagEnd::Table => BlockKind::Table,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn captures_core_gfm_structures_and_source_ranges() {+ let source = "# Title\n\nA **bold** [link](https://example.com).\n\n- [x] done\n";+ let projection = MarkdownProjection::parse(source);+ assert!(projection+ .blocks+ .iter()+ .any(|block| block.kind == BlockKind::Heading(1)));+ assert!(projection+ .text+ .iter()+ .any(|span| span.text == "bold" && span.style.strong));+ assert!(projection+ .text+ .iter()+ .any(|span| span.text == "link" && span.style.link));+ assert!(projection+ .objects+ .iter()+ .any(|object| matches!(object, ProjectedObject::TaskCheckbox { checked: true, .. })));+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::TaskCheckbox { source: marker, .. }+ if &source[marker.clone()] == "[x]"+ )));+ assert!(!projection+ .objects+ .iter()+ .any(|object| matches!(object, ProjectedObject::ListMarker { .. })));+ for span in &projection.text {+ assert!(span.source.end <= source.len());+ assert!(source.is_char_boundary(span.source.start));+ assert!(source.is_char_boundary(span.source.end));+ }+ }++ #[test]+ fn projects_unordered_and_ordered_list_markers() {+ let source = "- one\n2. two\n";+ let projection = MarkdownProjection::parse(source);+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::ListMarker { text, .. } if text == "• "+ )));+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::ListMarker { text, .. } if text == "2. "+ )));+ }++ #[test]+ fn captures_table_cells_and_image() {+ let source =+ "| A | B | C |\n| :-- | :-: | --: |\n| 1 | 2 | 3 |\n\n\n";+ let projection = MarkdownProjection::parse(source);+ let table = projection.objects.iter().find_map(|object| match object {+ ProjectedObject::Table(table) => Some(table),+ _ => None,+ });+ let table = table.expect("table projection");+ assert_eq!(table.rows.len(), 2);+ assert_eq!(table.rows[0][0].text, "A");+ assert_eq!(&source[table.rows[0][0].source.clone()], "A");+ assert_eq!(&source[table.rows[1][2].source.clone()], "3");+ assert_eq!(+ table.alignments,+ vec![+ TableAlignment::Left,+ TableAlignment::Center,+ TableAlignment::Right+ ]+ );+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::Image { target, alt, .. }+ if target == "attachments/a.png" && alt == "Alt"+ )));+ }++ #[test]+ fn captures_fenced_code_language_and_exact_content() {+ let source =+ "before\n\n```python linenos\ndef greet(name):\n return name\n```\n\nafter\n";+ let projection = MarkdownProjection::parse(source);+ let code = projection.objects.iter().find_map(|object| match object {+ ProjectedObject::CodeBlock(code) => Some(code),+ _ => None,+ });+ let code = code.expect("fenced code projection");+ assert_eq!(code.language.as_deref(), Some("python"));+ assert_eq!(code.text, "def greet(name):\n return name\n");+ assert_eq!(&source[code.content.clone()], code.text);+ assert!(source[code.source.clone()].starts_with("```python"));+ assert!(source[code.source.clone()].trim_end().ends_with("```"));+ }++ #[test]+ fn live_preview_reveals_smallest_active_syntax() {+ let source = "A **bold** word";+ let projection = MarkdownProjection::parse(source);+ let caret = source.find("bold").unwrap();+ let active = projection.active_syntax(caret).unwrap();+ assert_eq!(active.kind, MarkdownSyntaxKind::Strong);+ let visible = projection.visible_source_ranges(source, caret, false);+ assert!(visible+ .iter()+ .any(|range| range.start <= source.find("**").unwrap() && range.end >= caret));+ }+}diff --git a/wezterm-gui/src/markdown_editor/store.rs b/wezterm-gui/src/markdown_editor/store.rsnew file mode 100644index 00000000..e12241ce--- /dev/null+++ b/wezterm-gui/src/markdown_editor/store.rs@@ -0,0 +1,447 @@+use super::MarkdownDocumentSession;+use anyhow::{bail, Context, Result};+use parking_lot::Mutex;+use serde::{Deserialize, Serialize};+use std::fs;+use std::io::{Read, Write};+use std::path::{Component, Path, PathBuf};+use std::sync::Arc;+use tempfile::NamedTempFile;+use uuid::Uuid;++pub(crate) type NotebookId = String;+pub(crate) type DocumentId = String;++const STORE_VERSION: u32 = 1;+const MAX_IMPORTED_IMAGE_BYTES: u64 = 25 * 1024 * 1024;+const SUPPORTED_IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];++#[derive(Debug, Clone, Serialize, Deserialize)]+struct Registry {+ version: u32,+ default_notebook_id: NotebookId,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+struct DocumentRecord {+ id: DocumentId,+ path: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+struct NotebookMetadata {+ version: u32,+ id: NotebookId,+ name: String,+ active_document_id: DocumentId,+ documents: Vec<DocumentRecord>,+}++#[derive(Clone)]+#[allow(dead_code)]+pub(crate) struct DefaultNotebook {+ pub notebook_id: NotebookId,+ pub document_id: DocumentId,+ pub root: PathBuf,+ pub content_root: PathBuf,+ pub document_path: PathBuf,+ pub session: Arc<Mutex<MarkdownDocumentSession>>,+}++lazy_static::lazy_static! {+ static ref DEFAULT_NOTEBOOK: Mutex<Option<DefaultNotebook>> = Mutex::new(None);+ static ref ATTACHMENT_IMPORT_LOCK: Mutex<()> = Mutex::new(());+}++pub(crate) fn default_notebook() -> Result<DefaultNotebook> {+ let mut slot = DEFAULT_NOTEBOOK.lock();+ if let Some(notebook) = slot.as_ref() {+ return Ok(notebook.clone());+ }+ let notebook = ensure_default_notebook_at(&crate::native_paths::data_dir().join("notes/v1"))?;+ *slot = Some(notebook.clone());+ Ok(notebook)+}++pub(crate) fn default_document_session() -> Result<Arc<Mutex<MarkdownDocumentSession>>> {+ Ok(default_notebook()?.session)+}++fn ensure_default_notebook_at(base: &Path) -> Result<DefaultNotebook> {+ fs::create_dir_all(base).with_context(|| format!("create {}", base.display()))?;+ let registry_path = base.join("registry.json");+ let registry = if registry_path.exists() {+ read_json::<Registry>(®istry_path)?+ } else {+ let registry = Registry {+ version: STORE_VERSION,+ default_notebook_id: new_id(),+ };+ write_json_atomic(®istry_path, ®istry)?;+ registry+ };++ if registry.version != STORE_VERSION {+ bail!("unsupported Note registry version {}", registry.version);+ }++ let root = base.join("notebooks").join(®istry.default_notebook_id);+ let content_root = root.join("content");+ let attachments = content_root.join("attachments");+ fs::create_dir_all(&attachments)+ .with_context(|| format!("create {}", attachments.display()))?;+ ensure_canonical_descendant(&content_root, &attachments)?;++ let metadata_path = root.join("notebook.json");+ let metadata = if metadata_path.exists() {+ read_json::<NotebookMetadata>(&metadata_path)?+ } else {+ let document_id = new_id();+ let metadata = NotebookMetadata {+ version: STORE_VERSION,+ id: registry.default_notebook_id.clone(),+ name: "Notes".to_string(),+ active_document_id: document_id.clone(),+ documents: vec![DocumentRecord {+ id: document_id,+ path: "Inbox.md".to_string(),+ }],+ };+ write_json_atomic(&metadata_path, &metadata)?;+ metadata+ };++ if metadata.version != STORE_VERSION || metadata.id != registry.default_notebook_id {+ bail!("invalid default Notebook metadata");+ }+ let document = metadata+ .documents+ .iter()+ .find(|document| document.id == metadata.active_document_id)+ .or_else(|| metadata.documents.first())+ .context("default Notebook has no document")?;+ let document_path = safe_content_path(&content_root, Path::new(&document.path))?;+ if !document_path.exists() {+ write_bytes_atomic(&document_path, b"")?;+ }+ let source = fs::read_to_string(&document_path)+ .with_context(|| format!("read {}", document_path.display()))?;+ let session = Arc::new(Mutex::new(MarkdownDocumentSession::new(+ document.id.clone(),+ document_path.clone(),+ source,+ )));+ Ok(DefaultNotebook {+ notebook_id: registry.default_notebook_id,+ document_id: document.id.clone(),+ root,+ content_root,+ document_path,+ session,+ })+}++pub(crate) fn save_document_revision(session: &Arc<Mutex<MarkdownDocumentSession>>) -> Result<u64> {+ let save_lock = session.lock().save_lock();+ let _save_guard = save_lock.lock();+ let (revision, path, source) = session.lock().snapshot_for_save();+ let result = write_bytes_atomic(&path, source.as_bytes());+ let finish_result = result+ .as_ref()+ .map(|_| ())+ .map_err(|err| anyhow::anyhow!("{err:#}"));+ session.lock().finish_save(revision, finish_result);+ result.map(|_| revision)+}++pub(crate) fn import_attachment(notebook: &DefaultNotebook, source: &Path) -> Result<String> {+ let _operation_guard = ATTACHMENT_IMPORT_LOCK.lock();+ let metadata = fs::metadata(source).with_context(|| format!("stat {}", source.display()))?;+ if !metadata.is_file() {+ bail!("{} is not a file", source.display());+ }+ if metadata.len() > MAX_IMPORTED_IMAGE_BYTES {+ bail!("image exceeds the 25 MiB attachment limit");+ }+ let extension = source+ .extension()+ .and_then(|value| value.to_str())+ .map(str::to_ascii_lowercase)+ .context("image has no extension")?;+ if !SUPPORTED_IMAGE_EXTENSIONS.contains(&extension.as_str()) {+ bail!("unsupported image type: {extension}");+ }++ let stem = source+ .file_stem()+ .and_then(|value| value.to_str())+ .map(sanitize_file_stem)+ .filter(|value| !value.is_empty())+ .unwrap_or_else(|| "image".to_string());+ let attachment_dir = notebook.content_root.join("attachments");+ fs::create_dir_all(&attachment_dir)+ .with_context(|| format!("create {}", attachment_dir.display()))?;+ ensure_canonical_descendant(¬ebook.content_root, &attachment_dir)?;+ let mut sequence = 1usize;+ let destination = loop {+ let name = if sequence == 1 {+ format!("{stem}.{extension}")+ } else {+ format!("{stem}-{sequence}.{extension}")+ };+ let candidate = attachment_dir.join(name);+ if !candidate.exists() {+ break candidate;+ }+ sequence += 1;+ };++ let mut input = fs::File::open(source).with_context(|| format!("open {}", source.display()))?;+ let mut temporary = NamedTempFile::new_in(&attachment_dir).with_context(|| {+ format!(+ "create temporary attachment in {}",+ attachment_dir.display()+ )+ })?;+ std::io::copy(&mut input, &mut temporary)+ .with_context(|| format!("copy {}", source.display()))?;+ temporary.flush().context("flush attachment")?;+ temporary.as_file().sync_all().context("sync attachment")?;+ temporary+ .persist(&destination)+ .with_context(|| format!("persist {}", destination.display()))?;+ set_private_permissions(&destination);++ let relative = destination+ .strip_prefix(¬ebook.content_root)+ .context("attachment escaped Notebook content")?;+ Ok(relative.to_string_lossy().replace('\\', "/"))+}++pub(crate) fn resolve_local_image(+ content_root: &Path,+ document_path: &Path,+ target: &str,+) -> Result<PathBuf> {+ if target.starts_with("http://") || target.starts_with("https://") {+ bail!("network images are not loaded");+ }+ let target = target.split(['?', '#']).next().unwrap_or(target);+ let relative = Path::new(target);+ if relative.is_absolute() {+ bail!("absolute image paths are not allowed");+ }+ let parent = document_path.parent().context("document has no parent")?;+ let candidate = parent.join(relative);+ let canonical_root = content_root+ .canonicalize()+ .with_context(|| format!("resolve {}", content_root.display()))?;+ let canonical = candidate+ .canonicalize()+ .with_context(|| format!("resolve {}", candidate.display()))?;+ if !canonical.starts_with(&canonical_root) {+ bail!("image path escapes Notebook content");+ }+ Ok(canonical)+}++fn safe_content_path(root: &Path, relative: &Path) -> Result<PathBuf> {+ if relative.is_absolute()+ || relative.components().any(|component| {+ matches!(+ component,+ Component::ParentDir | Component::RootDir | Component::Prefix(_)+ )+ })+ {+ bail!("invalid Notebook document path {}", relative.display());+ }+ let candidate = root.join(relative);+ let canonical_root = root+ .canonicalize()+ .with_context(|| format!("resolve {}", root.display()))?;+ let mut existing = candidate.as_path();+ while !existing.exists() {+ existing = existing+ .parent()+ .context("Notebook document path has no existing parent")?;+ }+ let canonical_existing = existing+ .canonicalize()+ .with_context(|| format!("resolve {}", existing.display()))?;+ if !canonical_existing.starts_with(&canonical_root) {+ bail!("Notebook document path escapes content root");+ }+ Ok(candidate)+}++fn ensure_canonical_descendant(root: &Path, path: &Path) -> Result<()> {+ let canonical_root = root+ .canonicalize()+ .with_context(|| format!("resolve {}", root.display()))?;+ let canonical_path = path+ .canonicalize()+ .with_context(|| format!("resolve {}", path.display()))?;+ if !canonical_path.starts_with(canonical_root) {+ bail!("{} escapes Notebook content root", path.display());+ }+ Ok(())+}++fn new_id() -> String {+ Uuid::new_v4().simple().to_string()+}++fn sanitize_file_stem(stem: &str) -> String {+ let mut result = String::new();+ let mut previous_dash = false;+ for ch in stem.chars() {+ if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {+ result.push(ch.to_ascii_lowercase());+ previous_dash = false;+ } else if !previous_dash {+ result.push('-');+ previous_dash = true;+ }+ }+ result.trim_matches('-').chars().take(80).collect()+}++fn read_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {+ let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;+ let mut bytes = Vec::new();+ file.read_to_end(&mut bytes)+ .with_context(|| format!("read {}", path.display()))?;+ serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))+}++fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> {+ let bytes = serde_json::to_vec_pretty(value).context("serialize Note metadata")?;+ write_bytes_atomic(path, &bytes)+}++fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> Result<()> {+ let parent = path.parent().context("Note path has no parent")?;+ fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;+ let mut temporary = NamedTempFile::new_in(parent)+ .with_context(|| format!("create temporary file in {}", parent.display()))?;+ temporary+ .write_all(bytes)+ .with_context(|| format!("write {}", path.display()))?;+ temporary+ .flush()+ .with_context(|| format!("flush {}", path.display()))?;+ temporary+ .as_file()+ .sync_all()+ .with_context(|| format!("sync {}", path.display()))?;+ temporary+ .persist(path)+ .with_context(|| format!("replace {}", path.display()))?;+ set_private_permissions(path);+ Ok(())+}++#[cfg(unix)]+fn set_private_permissions(path: &Path) {+ use std::os::unix::fs::PermissionsExt;+ if let Err(err) = fs::set_permissions(path, fs::Permissions::from_mode(0o600)) {+ log::warn!(+ "failed to set private Note permissions on {}: {err:#}",+ path.display()+ );+ }+}++#[cfg(not(unix))]+fn set_private_permissions(_path: &Path) {}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn creates_and_reopens_stable_default_notebook() {+ let temp = tempfile::tempdir().unwrap();+ let first = ensure_default_notebook_at(temp.path()).unwrap();+ first.session.lock().source();+ let second = ensure_default_notebook_at(temp.path()).unwrap();+ assert_eq!(first.notebook_id, second.notebook_id);+ assert_eq!(first.document_id, second.document_id);+ assert!(second.document_path.ends_with("Inbox.md"));+ }++ #[test]+ fn imports_supported_image_with_collision_safe_name() {+ let temp = tempfile::tempdir().unwrap();+ let source = temp.path().join("My image.PNG");+ fs::write(&source, b"not decoded by the store").unwrap();+ let store_root = temp.path().join("store");+ let notebook = ensure_default_notebook_at(&store_root).unwrap();+ assert_eq!(+ import_attachment(¬ebook, &source).unwrap(),+ "attachments/my-image.png"+ );+ assert_eq!(+ import_attachment(¬ebook, &source).unwrap(),+ "attachments/my-image-2.png"+ );+ }++ #[test]+ fn local_image_resolution_rejects_escape() {+ let temp = tempfile::tempdir().unwrap();+ let store_root = temp.path().join("store");+ let notebook = ensure_default_notebook_at(&store_root).unwrap();+ let outside = temp.path().join("outside.png");+ fs::write(&outside, b"x").unwrap();+ assert!(resolve_local_image(+ ¬ebook.content_root,+ ¬ebook.document_path,+ "../../../outside.png"+ )+ .is_err());+ }++ #[cfg(unix)]+ #[test]+ fn notebook_document_path_rejects_symlink_escape() {+ use std::os::unix::fs::symlink;++ let temp = tempfile::tempdir().unwrap();+ let content = temp.path().join("content");+ let outside = temp.path().join("outside");+ fs::create_dir_all(&content).unwrap();+ fs::create_dir_all(&outside).unwrap();+ symlink(&outside, content.join("linked")).unwrap();+ assert!(safe_content_path(&content, Path::new("linked/Note.md")).is_err());+ }++ #[test]+ fn serialized_saves_write_the_latest_shared_revision() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("Inbox.md");+ let session = Arc::new(Mutex::new(MarkdownDocumentSession::new(+ "doc".into(),+ path.clone(),+ "a".into(),+ )));+ let mut first_view = super::super::EditorViewState::default();+ session.lock().set_caret(&mut first_view, 1, false);+ session.lock().insert_text(&mut first_view, "b");++ let save_lock = session.lock().save_lock();+ let guard = save_lock.lock();+ let first_session = Arc::clone(&session);+ let first = std::thread::spawn(move || save_document_revision(&first_session));+ session.lock().insert_text(&mut first_view, "c");+ let second_session = Arc::clone(&session);+ let second = std::thread::spawn(move || save_document_revision(&second_session));+ drop(guard);++ first.join().unwrap().unwrap();+ second.join().unwrap().unwrap();+ assert_eq!(fs::read_to_string(path).unwrap(), "abc");+ assert!(!session.lock().is_dirty());+ }+}diff --git a/wezterm-gui/src/markdown_editor/surface.rs b/wezterm-gui/src/markdown_editor/surface.rsnew file mode 100644index 00000000..7454c3ed--- /dev/null+++ b/wezterm-gui/src/markdown_editor/surface.rs@@ -0,0 +1,684 @@+use super::projection::ProjectedText;+use super::{BlockKind, EditorMode, InlineStyle, MarkdownProjection, ProjectedObject};+use std::ops::Range;+use unicode_segmentation::UnicodeSegmentation;+#[cfg(test)]+use unicode_width::UnicodeWidthStr;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum VisualLineKind {+ Text,+ Rule,+ Image,+ TableHeader,+ TableRow,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct VisualRun {+ pub source: Range<usize>,+ pub text: String,+ pub style: InlineStyle,+ pub atomic: bool,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct VisualLine {+ pub source: Range<usize>,+ pub block: BlockKind,+ pub kind: VisualLineKind,+ pub runs: Vec<VisualRun>,+}++impl VisualLine {+ #[cfg(test)]+ pub(crate) fn text(&self) -> String {+ self.runs.iter().map(|run| run.text.as_str()).collect()+ }+}++/// Soft-wrap a projected document without changing the underlying source.+/// Hosts choose `max_columns` from their current viewport; every resulting run+/// retains byte ranges into the original Markdown for hit testing and edits.+#[cfg(test)]+pub(crate) fn wrap_visual_document(+ document: &VisualDocument,+ max_columns: usize,+) -> VisualDocument {+ let max_columns = max_columns.max(1);+ let mut lines = Vec::with_capacity(document.lines.len());+ for line in &document.lines {+ if line.runs.is_empty()+ || matches!(line.block, BlockKind::CodeBlock | BlockKind::Table)+ || matches!(line.kind, VisualLineKind::Rule | VisualLineKind::Image)+ {+ lines.push(line.clone());+ continue;+ }++ let mut current = empty_visual_line(line, line.source.start);+ let mut columns = 0usize;+ for run in &line.runs {+ let source_matches_text =+ !run.atomic && run.source.end.saturating_sub(run.source.start) == run.text.len();+ if !source_matches_text {+ let width = UnicodeWidthStr::width(run.text.as_str()).max(1);+ if columns > 0 && columns.saturating_add(width) > max_columns {+ lines.push(current);+ current = empty_visual_line(line, run.source.start);+ columns = 0;+ }+ append_run(&mut current, run.clone());+ columns = columns.saturating_add(width);+ continue;+ }++ for (relative, grapheme) in run.text.grapheme_indices(true) {+ let width = UnicodeWidthStr::width(grapheme).max(1);+ if columns > 0 && columns.saturating_add(width) > max_columns {+ lines.push(current);+ current = empty_visual_line(line, run.source.start + relative);+ columns = 0;+ }+ append_run(+ &mut current,+ VisualRun {+ source: run.source.start + relative+ ..run.source.start + relative + grapheme.len(),+ text: grapheme.to_string(),+ style: run.style,+ atomic: false,+ },+ );+ columns = columns.saturating_add(width);+ }+ }+ current.source.end = current.source.end.max(line.source.end);+ lines.push(current);+ }+ VisualDocument { lines }+}++/// Soft-wrap using the actual rendered width supplied by the host. Keeping+/// measurement outside this module lets each host use its own font stack while+/// every resulting run retains exact Markdown source byte ranges.+pub(crate) fn wrap_visual_document_by_width<E, F>(+ document: &VisualDocument,+ max_width: f32,+ mut measure: F,+) -> Result<VisualDocument, E>+where+ F: FnMut(BlockKind, &VisualRun) -> Result<f32, E>,+{+ let max_width = max_width.max(1.0);+ let mut lines = Vec::with_capacity(document.lines.len());+ for line in &document.lines {+ if line.runs.is_empty()+ || matches!(line.block, BlockKind::CodeBlock | BlockKind::Table)+ || matches!(line.kind, VisualLineKind::Rule | VisualLineKind::Image)+ {+ lines.push(line.clone());+ continue;+ }++ let mut current = empty_visual_line(line, line.source.start);+ let mut width = 0.0f32;+ for run in &line.runs {+ let source_matches_text =+ !run.atomic && run.source.end.saturating_sub(run.source.start) == run.text.len();+ let pieces = if source_matches_text {+ run.text+ .split_word_bound_indices()+ .map(|(relative, text)| VisualRun {+ source: run.source.start + relative+ ..run.source.start + relative + text.len(),+ text: text.to_string(),+ style: run.style,+ atomic: false,+ })+ .collect::<Vec<_>>()+ } else {+ vec![run.clone()]+ };++ for piece in pieces {+ let piece_width = measure(line.block, &piece)?.max(0.0);+ let whitespace = piece.text.chars().all(char::is_whitespace);+ if !piece.atomic && !whitespace && piece_width > max_width {+ for (relative, grapheme) in piece.text.grapheme_indices(true) {+ let grapheme_run = VisualRun {+ source: piece.source.start + relative+ ..piece.source.start + relative + grapheme.len(),+ text: grapheme.to_string(),+ style: piece.style,+ atomic: false,+ };+ let grapheme_width = measure(line.block, &grapheme_run)?.max(0.0);+ if visual_line_has_non_whitespace(¤t)+ && width + grapheme_width > max_width+ {+ lines.push(current);+ current = empty_visual_line(line, grapheme_run.source.start);+ width = 0.0;+ }+ append_run(&mut current, grapheme_run);+ width += grapheme_width;+ }+ continue;+ }++ if !whitespace+ && visual_line_has_non_whitespace(¤t)+ && width + piece_width > max_width+ {+ lines.push(current);+ current = empty_visual_line(line, piece.source.start);+ width = 0.0;+ }+ append_run(&mut current, piece);+ width += piece_width;+ }+ }+ current.source.end = current.source.end.max(line.source.end);+ lines.push(current);+ }+ Ok(VisualDocument { lines })+}++fn visual_line_has_non_whitespace(line: &VisualLine) -> bool {+ line.runs+ .iter()+ .any(|run| run.text.chars().any(|ch| !ch.is_whitespace()))+}++/// Fit measured table columns into the viewport. Wide tables shrink columns+/// toward a shared floor; very narrow hosts fall back to equal-width cells so+/// the grid remains bounded and individual cell painters can clip their text.+pub(crate) fn fit_table_columns(+ desired: &[f32],+ available_width: f32,+ minimum_width: f32,+) -> Vec<f32> {+ if desired.is_empty() {+ return vec![];+ }+ let available_width = available_width.max(1.0);+ let equal_width = available_width / desired.len() as f32;+ let floor = minimum_width.max(1.0).min(equal_width);+ let mut widths = desired+ .iter()+ .map(|width| width.max(floor))+ .collect::<Vec<_>>();+ let total = widths.iter().sum::<f32>();+ if total < available_width {+ let extra = (available_width - total) / widths.len() as f32;+ for width in &mut widths {+ *width += extra;+ }+ } else if total > available_width {+ let flexible = widths.iter().map(|width| width - floor).sum::<f32>();+ if flexible <= f32::EPSILON {+ widths.fill(equal_width);+ } else {+ let overflow = total - available_width;+ for width in &mut widths {+ let share = (*width - floor) / flexible;+ *width = (*width - overflow * share).max(floor);+ }+ }+ }+ let correction = available_width - widths.iter().sum::<f32>();+ if let Some(last) = widths.last_mut() {+ *last = (*last + correction).max(1.0);+ }+ widths+}++fn empty_visual_line(template: &VisualLine, source_start: usize) -> VisualLine {+ VisualLine {+ source: source_start..source_start,+ block: template.block,+ kind: template.kind,+ runs: vec![],+ }+}++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct VisualDocument {+ pub lines: Vec<VisualLine>,+}++pub(crate) fn build_visual_document(+ source: &str,+ projection: &MarkdownProjection,+ mode: EditorMode,+ caret: usize,+) -> VisualDocument {+ if mode == EditorMode::Source {+ return source_document(source);+ }++ let visible = projection.visible_source_ranges(source, caret, false);+ let mut objects: Vec<&ProjectedObject> = projection.objects.iter().collect();+ objects.sort_by_key(|object| {+ let range = object.source();+ (range.start, range.end)+ });+ let mut object_index = 0usize;+ let mut lines = vec![];+ let mut line = VisualLine {+ source: 0..0,+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Text,+ runs: vec![],+ };+ let mut idx = 0usize;++ while idx < source.len() {+ while object_index < objects.len() && objects[object_index].source().end <= idx {+ object_index += 1;+ }+ if let Some(object) = objects.get(object_index) {+ let range = object.source();+ if range.start == idx && range.end > range.start {+ match object {+ ProjectedObject::TaskCheckbox {+ source: object_source,+ checked,+ } => {+ append_run(+ &mut line,+ VisualRun {+ source: object_source.clone(),+ text: if *checked { "☑ " } else { "☐ " }.to_string(),+ style: InlineStyle::default(),+ atomic: true,+ },+ );+ }+ ProjectedObject::ListMarker {+ source: object_source,+ text,+ } => {+ append_run(+ &mut line,+ VisualRun {+ source: object_source.clone(),+ text: text.clone(),+ style: InlineStyle::default(),+ atomic: true,+ },+ );+ }+ ProjectedObject::Rule {+ source: object_source,+ } => {+ flush_line(&mut lines, &mut line, idx);+ lines.push(VisualLine {+ source: object_source.clone(),+ block: BlockKind::Other,+ kind: VisualLineKind::Rule,+ runs: vec![],+ });+ }+ ProjectedObject::Image {+ source: object_source,+ alt,+ target,+ ..+ } => {+ flush_line(&mut lines, &mut line, idx);+ let label = if alt.is_empty() { target } else { alt };+ lines.push(VisualLine {+ source: object_source.clone(),+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Image,+ runs: vec![VisualRun {+ source: object_source.clone(),+ text: format!("▧ {label}"),+ style: InlineStyle::default(),+ atomic: true,+ }],+ });+ }+ ProjectedObject::CodeBlock(code) => {+ flush_line_if_content(&mut lines, &mut line, idx);+ let mut content_start = code.content.start;+ let chunks = if code.text.is_empty() {+ vec![""]+ } else {+ code.text.split_inclusive('\n').collect::<Vec<_>>()+ };+ for chunk in chunks {+ let text = chunk.strip_suffix('\n').unwrap_or(chunk);+ let text_end = content_start + text.len();+ lines.push(VisualLine {+ source: content_start..text_end,+ block: BlockKind::CodeBlock,+ kind: VisualLineKind::Text,+ runs: if text.is_empty() {+ vec![]+ } else {+ vec![VisualRun {+ source: content_start..text_end,+ text: text.to_string(),+ style: InlineStyle {+ code: true,+ ..InlineStyle::default()+ },+ atomic: false,+ }]+ },+ });+ content_start += chunk.len();+ }+ }+ ProjectedObject::Table(table) => {+ flush_line(&mut lines, &mut line, idx);+ for (row_index, row) in table.rows.iter().enumerate() {+ let mut runs = vec![];+ for cell in row {+ runs.push(VisualRun {+ source: cell.source.clone(),+ text: cell.text.clone(),+ style: InlineStyle {+ strong: row_index == 0,+ ..InlineStyle::default()+ },+ atomic: false,+ });+ }+ lines.push(VisualLine {+ source: row+ .first()+ .map(|cell| cell.source.start)+ .unwrap_or(table.source.start)+ ..row+ .last()+ .map(|cell| cell.source.end)+ .unwrap_or(table.source.end),+ block: BlockKind::Table,+ kind: if row_index == 0 {+ VisualLineKind::TableHeader+ } else {+ VisualLineKind::TableRow+ },+ runs,+ });+ }+ }+ }+ idx = range.end.min(source.len());+ if matches!(object, ProjectedObject::CodeBlock(_))+ && source[idx..].starts_with('\n')+ {+ idx += 1;+ }+ object_index += 1;+ continue;+ }+ }++ let ch = source[idx..].chars().next().expect("valid source char");+ let next = idx + ch.len_utf8();+ if ch == '\n' {+ flush_line(&mut lines, &mut line, next);+ idx = next;+ continue;+ }+ if range_contains(&visible, idx) {+ let projected = projected_text_at(projection, idx);+ let style = projected.map(|span| span.style).unwrap_or_default();+ line.block = projected.map(|span| span.block).unwrap_or(line.block);+ append_run(+ &mut line,+ VisualRun {+ source: idx..next,+ text: ch.to_string(),+ style,+ atomic: false,+ },+ );+ }+ idx = next;+ }+ flush_line(&mut lines, &mut line, source.len());+ if lines.is_empty() {+ lines.push(VisualLine {+ source: 0..0,+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Text,+ runs: vec![],+ });+ }+ VisualDocument { lines }+}++fn projected_text_at(projection: &MarkdownProjection, byte: usize) -> Option<&ProjectedText> {+ let index = projection+ .text+ .partition_point(|span| span.source.end <= byte);+ projection+ .text+ .get(index)+ .filter(|span| span.source.start <= byte && byte < span.source.end)+}++fn source_document(source: &str) -> VisualDocument {+ let mut lines = vec![];+ let mut start = 0usize;+ for chunk in source.split_inclusive('\n') {+ let text = chunk.strip_suffix('\n').unwrap_or(chunk);+ let end = start + text.len();+ lines.push(VisualLine {+ source: start..end,+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Text,+ runs: if text.is_empty() {+ vec![]+ } else {+ vec![VisualRun {+ source: start..end,+ text: text.to_string(),+ style: InlineStyle::default(),+ atomic: false,+ }]+ },+ });+ start += chunk.len();+ }+ if source.is_empty() || source.ends_with('\n') {+ lines.push(VisualLine {+ source: source.len()..source.len(),+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Text,+ runs: vec![],+ });+ }+ VisualDocument { lines }+}++fn append_run(line: &mut VisualLine, run: VisualRun) {+ if let Some(last) = line.runs.last_mut() {+ if !last.atomic+ && !run.atomic+ && last.style == run.style+ && last.source.end == run.source.start+ {+ last.source.end = run.source.end;+ last.text.push_str(&run.text);+ line.source.end = line.source.end.max(run.source.end);+ return;+ }+ }+ if line.runs.is_empty() {+ line.source.start = run.source.start;+ }+ line.source.end = line.source.end.max(run.source.end);+ line.runs.push(run);+}++fn flush_line(lines: &mut Vec<VisualLine>, line: &mut VisualLine, source_end: usize) {+ if line.runs.is_empty() && line.source.start == line.source.end {+ line.source = source_end..source_end;+ } else {+ line.source.end = line.source.end.max(source_end);+ }+ lines.push(line.clone());+ *line = VisualLine {+ source: source_end..source_end,+ block: BlockKind::Paragraph,+ kind: VisualLineKind::Text,+ runs: vec![],+ };+}++fn flush_line_if_content(lines: &mut Vec<VisualLine>, line: &mut VisualLine, source_end: usize) {+ if line.runs.is_empty() && line.source.start == line.source.end {+ line.source = source_end..source_end;+ } else {+ flush_line(lines, line, source_end);+ }+}++fn range_contains(ranges: &[Range<usize>], byte: usize) -> bool {+ ranges+ .binary_search_by(|range| {+ if byte < range.start {+ std::cmp::Ordering::Greater+ } else if byte >= range.end {+ std::cmp::Ordering::Less+ } else {+ std::cmp::Ordering::Equal+ }+ })+ .is_ok()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn source_mode_is_lossless_by_lines() {+ let source = "# 你\n\n**bold**\n";+ let doc = build_visual_document(+ source,+ &MarkdownProjection::parse(source),+ EditorMode::Source,+ 0,+ );+ assert_eq!(doc.lines[0].text(), "# 你");+ assert_eq!(doc.lines[1].text(), "");+ assert_eq!(doc.lines[2].text(), "**bold**");+ }++ #[test]+ fn live_preview_hides_inactive_emphasis_markers() {+ let source = "**bold** plain";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, source.len());+ assert_eq!(doc.lines[0].text(), "bold plain");+ let active = build_visual_document(source, &projection, EditorMode::LivePreview, 3);+ assert_eq!(active.lines[0].text(), "**bold** plain");+ }++ #[test]+ fn live_preview_projects_table_and_task_object() {+ let source = "- [x] done\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, source.len());+ assert!(doc.lines.iter().any(|line| line.text().contains("☑")));+ assert!(doc+ .lines+ .iter()+ .any(|line| line.kind == VisualLineKind::TableHeader));+ let row = doc+ .lines+ .iter()+ .find(|line| line.kind == VisualLineKind::TableRow)+ .expect("table body row");+ assert_eq!(row.runs.len(), 2);+ assert_eq!(row.runs[0].text, "1");+ assert_eq!(row.runs[1].text, "2");+ }++ #[test]+ fn live_preview_keeps_fenced_code_component_stable_while_editing() {+ let source = "```rust\nfn main() {}\n```\n";+ let projection = MarkdownProjection::parse(source);+ let caret = source.find("main").unwrap();+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, caret);+ let code_lines = doc+ .lines+ .iter()+ .filter(|line| line.block == BlockKind::CodeBlock)+ .collect::<Vec<_>>();+ assert_eq!(code_lines.len(), 1);+ assert_eq!(code_lines[0].text(), "fn main() {}");+ assert!(!code_lines[0].text().contains("```"));++ let source_mode = build_visual_document(source, &projection, EditorMode::Source, caret);+ assert_eq!(source_mode.lines[0].text(), "```rust");+ assert_eq!(source_mode.lines[2].text(), "```");+ }++ #[test]+ fn soft_wrap_preserves_unicode_source_ranges() {+ let source = "ab你好cd";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, 0);+ let wrapped = wrap_visual_document(&doc, 4);+ assert_eq!(wrapped.lines.len(), 2);+ assert_eq!(wrapped.lines[0].text(), "ab你");+ assert_eq!(wrapped.lines[1].text(), "好cd");+ assert_eq!(wrapped.lines.last().unwrap().source.end, source.len());+ }++ #[test]+ fn pixel_wrap_uses_measured_word_widths_and_preserves_ranges() {+ let source = "wide words fit";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, 0);+ let wrapped = wrap_visual_document_by_width(&doc, 8.0, |_, run| {+ Ok::<_, ()>(+ run.text+ .chars()+ .map(|ch| if ch == 'w' { 4.0 } else { 1.0 })+ .sum(),+ )+ })+ .unwrap();+ assert_eq!(wrapped.lines.len(), 3);+ assert_eq!(wrapped.lines[0].text(), "wide ");+ assert_eq!(wrapped.lines[1].text(), "words ");+ assert_eq!(wrapped.lines[2].text(), "fit");+ assert_eq!(wrapped.lines.last().unwrap().source.end, source.len());+ }++ #[test]+ fn table_column_fitting_fills_and_bounds_the_grid() {+ assert_eq!(fit_table_columns(&[], 100.0, 20.0), Vec::<f32>::new());+ let roomy = fit_table_columns(&[30.0, 50.0], 100.0, 20.0);+ assert!((roomy.iter().sum::<f32>() - 100.0).abs() < 0.01);+ assert!(roomy[1] > roomy[0]);++ let narrow = fit_table_columns(&[200.0, 100.0, 50.0], 90.0, 48.0);+ assert!((narrow.iter().sum::<f32>() - 90.0).abs() < 0.01);+ assert!(narrow.iter().all(|width| *width >= 1.0));+ }++ #[test]+ fn read_only_projection_reuses_live_preview_and_large_documents_wrap() {+ let source = (0..2_000)+ .map(|index| format!("## Row {index} with **bold** and 你好\n"))+ .collect::<String>();+ let projection = MarkdownProjection::parse(&source);+ let live = build_visual_document(&source, &projection, EditorMode::LivePreview, 0);+ let read_only = build_visual_document(&source, &projection, EditorMode::ReadOnly, 0);+ assert_eq!(live, read_only);+ let narrow = wrap_visual_document(&read_only, 12);+ assert!(narrow.lines.len() > read_only.lines.len());+ assert_eq!(narrow.lines.last().unwrap().source.end, source.len());+ }+}diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 1d794da8..1b064718 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -492,9 +492,7 @@ pub(crate) fn right_sidebar_custom_open_with_apps() -> Vec<NativeOpenWithApp> {const MAX_CUSTOM_OPEN_WITH_APPS: usize = 20;-pub(crate) fn add_right_sidebar_custom_open_with_app(- app: NativeOpenWithApp,-) -> anyhow::Result<()> {+pub(crate) fn add_right_sidebar_custom_open_with_app(app: NativeOpenWithApp) -> anyhow::Result<()> {let mut settings = load();let apps = &mut settings.chrome.right_sidebar_custom_open_with_apps;apps.retain(|existing| existing.id != app.id);diff --git a/wezterm-gui/src/overlay/prompt.rs b/wezterm-gui/src/overlay/prompt.rsindex e4b3490f..2075b222 100644--- a/wezterm-gui/src/overlay/prompt.rs+++ b/wezterm-gui/src/overlay/prompt.rs@@ -169,9 +169,7 @@ pub fn pick_path_prompt_overlay(y: Position::Absolute(0),},Change::Text(format!("{}\r\n", description.replace('\n', "\r\n"))),- Change::Attribute(AttributeChange::Intensity(- termwiz::cell::Intensity::Half,- )),+ Change::Attribute(AttributeChange::Intensity(termwiz::cell::Intensity::Half)),Change::Text(format!("{hint}\r\n")),Change::AllAttributes(CellAttributes::default()),Change::Text(format!("{prompt}{input}\r\n")),@@ -193,7 +191,9 @@ pub fn pick_path_prompt_overlay(}}changes.push(Change::CursorPosition {- x: Position::Absolute(unicode_column_width(prompt, None) + unicode_column_width(&input, None)),+ x: Position::Absolute(+ unicode_column_width(prompt, None) + unicode_column_width(&input, None),+ ),y: Position::Absolute(description_rows + 1),});term.render(&changes)?;@@ -204,8 +204,9 @@ pub fn pick_path_prompt_overlay(match event {InputEvent::Key(KeyEvent { key, modifiers }) => match (key, modifiers) {(KeyCode::Escape, _) => return Ok(None),- (KeyCode::Char('c'), Modifiers::CTRL)- | (KeyCode::Char('g'), Modifiers::CTRL) => return Ok(None),+ (KeyCode::Char('c'), Modifiers::CTRL) | (KeyCode::Char('g'), Modifiers::CTRL) => {+ return Ok(None)+ }(KeyCode::UpArrow, _) | (KeyCode::Char('p'), Modifiers::CTRL) => {active = active.saturating_sub(1);}@@ -235,9 +236,7 @@ pub fn pick_path_prompt_overlay(top_row = 0;}(KeyCode::Char(c), mods)- if !mods.intersects(- Modifiers::CTRL | Modifiers::ALT | Modifiers::SUPER,- ) =>+ if !mods.intersects(Modifiers::CTRL | Modifiers::ALT | Modifiers::SUPER) =>{input.push(c);active = 0;@@ -245,9 +244,9 @@ pub fn pick_path_prompt_overlay(}_ => {}},- InputEvent::Mouse(MouseEvent {- mouse_buttons, ..- }) if mouse_buttons.contains(MouseButtons::VERT_WHEEL) => {+ InputEvent::Mouse(MouseEvent { mouse_buttons, .. })+ if mouse_buttons.contains(MouseButtons::VERT_WHEEL) =>+ {if mouse_buttons.contains(MouseButtons::WHEEL_POSITIVE) {top_row = top_row.saturating_sub(1);} else {diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex d3ef6a37..301ae559 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -562,6 +562,15 @@ impl super::TermWindow {}}+ // A focused sidebar editor owns keyboard input. Give application-level+ // key bindings above a chance to run, but never let an unhandled press or+ // release fall through to the terminal pane. In particular, enhanced+ // keyboard protocols can report key releases, which made the terminal+ // appear to retain focus while typing in Notes.+ if only_key_bindings == OnlyKeyBindings::No && self.right_sidebar_has_text_focus() {+ return true;+ }+// While the leader modifier is active, only registered// keybindings are recognized.let only_key_bindings = match (only_key_bindings, leader_active) {diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 35702ed7..af58ec27 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -53,7 +53,6 @@ use mux::tab::{};use mux::window::WindowId as MuxWindowId;use mux::{Mux, MuxNotification};-use wezterm_client::domain::ClientDomain;use mux_lua::MuxPane;use smol::channel::Sender;use smol::Timer;@@ -62,12 +61,13 @@ use std::collections::{HashMap, HashSet, LinkedList, VecDeque};use std::ops::Add;use std::path::{Path, PathBuf};use std::rc::Rc;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use termwiz::hyperlink::Hyperlink;use termwiz::image::ImageData;use termwiz::surface::SequenceNo;+use wezterm_client::domain::ClientDomain;use wezterm_dynamic::Value;use wezterm_font::FontConfiguration;use wezterm_term::color::{ColorAttribute, ColorPalette};@@ -295,6 +295,11 @@ pub enum UIItemType {RightSidebarSnippetDelete(String),RightSidebarSnippetScrollTrack,RightSidebarSnippetScrollThumb,+ RightSidebarNoteModeToggle,+ RightSidebarNoteSave,+ RightSidebarNoteCodeToggle(usize),+ RightSidebarNoteCodeCopy(usize),+ RightSidebarNoteBody,RightSidebarFilePreviewScrollTrack,RightSidebarFilePreviewScrollThumb,RightSidebarFilePreviewHorizontalScrollTrack,@@ -1007,6 +1012,16 @@ pub struct TermWindow {right_sidebar_snippet_body: TextInputState,right_sidebar_snippet_scroll_offset: f32,right_sidebar_snippet_scrollbar_visible_until: Option<Instant>,+ right_sidebar_note: crate::markdown_editor::NoteHostState,+ right_sidebar_note_images: HashMap<PathBuf, RightSidebarFilePreviewImage>,+ right_sidebar_note_images_loading: HashSet<PathBuf>,+ right_sidebar_note_image_order: VecDeque<PathBuf>,+ right_sidebar_note_code_highlights:+ HashMap<(u64, usize, bool), Arc<Vec<Vec<::window::color::LinearRgba>>>>,+ right_sidebar_note_code_highlight_order: VecDeque<(u64, usize, bool)>,+ right_sidebar_note_code_highlights_pending: HashSet<(u64, usize)>,+ right_sidebar_note_code_highlight_revision: u64,+ right_sidebar_note_code_highlight_cancel: Arc<AtomicUsize>,right_sidebar_file_view: RightSidebarFileView,right_sidebar_file_focus: Option<RightSidebarFileField>,right_sidebar_file_filter: TextInputState,@@ -1035,6 +1050,7 @@ pub struct TermWindow {right_sidebar_file_tree_width: usize,right_sidebar_file_preview_width: usize,right_sidebar_file_preview_generation: u64,+ right_sidebar_file_preview_highlight_cancel: Arc<AtomicUsize>,right_sidebar_file_preview_lines: Vec<RightSidebarFilePreviewLine>,right_sidebar_file_preview_max_columns: usize,right_sidebar_file_preview_image: Option<RightSidebarFilePreviewImage>,@@ -1061,8 +1077,7 @@ pub struct TermWindow {// Per-(root, project) remembered Files-panel view state (expanded folders,// selected/preview, scroll, filter) so switching workspaces / idle-release /// re-scan don't lose where you were. Only a few KB of paths each; LRU-bounded.- right_sidebar_file_view_state_by_root:- HashMap<(PathBuf, String), RightSidebarFileViewState>,+ right_sidebar_file_view_state_by_root: HashMap<(PathBuf, String), RightSidebarFileViewState>,right_sidebar_file_view_state_order: VecDeque<(PathBuf, String)>,// Bumped to invalidate a pending periodic-rescan timer tick.right_sidebar_file_rescan_token: u64,@@ -1185,6 +1200,7 @@ impl TermWindow {}fn close_requested(&mut self, window: &Window) {+ self.flush_right_sidebar_note_blocking();self.persist_workspace_layout_after_mutation("window close requested");let mux = Mux::get();@@ -1253,6 +1269,7 @@ impl TermWindow {}if self.focused.is_none() {+ self.save_right_sidebar_note_now();self.last_mouse_click = None;self.current_mouse_buttons.clear();self.current_mouse_capture = None;@@ -1366,10 +1383,7 @@ impl TermWindow {// initial size instead.log::debug!("new_window has no tabs... yet?");let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi());- config.initial_size(- dpi as u32,- crate::cell_pixel_dims(&config, dpi as f64).ok(),- )+ config.initial_size(dpi as u32, crate::cell_pixel_dims(&config, dpi as f64).ok())}};let physical_rows = size.rows as usize;@@ -1418,7 +1432,8 @@ impl TermWindow {pixel_cell: render_metrics.cell_size.width as f32,};let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize;- let workspace_sidebar_width = ui::workspace_sidebar_width_for_metrics(&render_metrics, dpi as usize);+ let workspace_sidebar_width =+ ui::workspace_sidebar_width_for_metrics(&render_metrics, dpi as usize);let padding_right = resize::effective_right_padding(&config, h_context) as usize;let v_context = DimensionContext {dpi: dpi as f32,@@ -1622,6 +1637,15 @@ impl TermWindow {right_sidebar_snippet_body: TextInputState::new(),right_sidebar_snippet_scroll_offset: 0.0,right_sidebar_snippet_scrollbar_visible_until: None,+ right_sidebar_note: crate::markdown_editor::NoteHostState::default(),+ right_sidebar_note_images: HashMap::new(),+ right_sidebar_note_images_loading: HashSet::new(),+ right_sidebar_note_image_order: VecDeque::new(),+ right_sidebar_note_code_highlights: HashMap::new(),+ right_sidebar_note_code_highlight_order: VecDeque::new(),+ right_sidebar_note_code_highlights_pending: HashSet::new(),+ right_sidebar_note_code_highlight_revision: 0,+ right_sidebar_note_code_highlight_cancel: Arc::new(AtomicUsize::new(0)),right_sidebar_file_view: RightSidebarFileView::Tree,right_sidebar_file_focus: None,right_sidebar_file_filter: TextInputState::new(),@@ -1644,9 +1668,13 @@ impl TermWindow {right_sidebar_file_browse_rows: Vec::new(),right_sidebar_file_browse_cache_key: None,right_sidebar_file_selected: None,- right_sidebar_file_tree_width: ui::right_sidebar_width_for_metrics(&render_metrics, dpi as usize),+ right_sidebar_file_tree_width: ui::right_sidebar_width_for_metrics(+ &render_metrics,+ dpi as usize,+ ),right_sidebar_file_preview_width: ui::right_sidebar_file_preview_width(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(),right_sidebar_file_preview_max_columns: 0,right_sidebar_file_preview_image: None,@@ -1834,6 +1862,7 @@ impl TermWindow {log::debug!("{event:?}");match event {WindowEvent::Destroyed => {+ self.flush_right_sidebar_note_blocking();// Ensure that we cancel any overlays we had running, so// that the mux can empty out, otherwise the mux keeps// the TermWindow alive via the frontend even though@@ -1977,6 +2006,61 @@ impl TermWindow {Ok(true)}WindowEvent::DroppedFile(paths) => {+ if self.right_sidebar_mode == RightSidebarMode::Tasks+ && self.right_sidebar_note.view.focused+ {+ let notebook = match crate::markdown_editor::default_notebook() {+ Ok(notebook) => notebook,+ Err(err) => {+ log::error!("failed to open Note attachment store: {err:#}");+ return Ok(true);+ }+ };+ let paths = paths.clone();+ let notify_window = window.clone();+ promise::spawn::spawn(async move {+ let markdown = promise::spawn::spawn_into_new_thread(move || {+ let mut inserted = Vec::new();+ for path in paths {+ match crate::markdown_editor::import_attachment(¬ebook, &path) {+ Ok(relative) => {+ let alt = path+ .file_stem()+ .and_then(|name| name.to_str())+ .unwrap_or("image")+ .replace('\\', "\\\\")+ .replace('[', "\\[")+ .replace(']', "\\]")+ .replace(['\r', '\n'], " ");+ inserted.push(format!(""));+ }+ Err(err) => {+ log::warn!(+ "unable to import Note attachment {}: {err:#}",+ path.display()+ );+ }+ }+ }+ anyhow::Ok(inserted.join("\n"))+ })+ .await;+ if let Ok(markdown) = markdown {+ if markdown.is_empty() {+ return;+ }+ notify_window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| {+ if term_window.push_right_sidebar_text(&markdown) {+ term_window.invalidate_window();+ }+ },+ )));+ }+ })+ .detach();+ return Ok(true);+ }let pane = match self.get_active_pane_or_overlay() {Some(pane) => pane,None => return Ok(true),@@ -2304,21 +2388,20 @@ impl TermWindow {let path = path.to_string_lossy();// In a mux-domain Space the path names a directory on the// remote server and must not be resolved locally.- let result = if crate::workspace_threads::client_domain_for_space(- &self.active_space_id,- )- .is_some()- {- crate::workspace_threads::create_remote_project_from_path(- &self.active_space_id,- path.as_ref(),- )- } else {- crate::workspace_threads::create_project_from_path(- &self.active_space_id,- path.as_ref(),- )- };+ let result =+ if crate::workspace_threads::client_domain_for_space(&self.active_space_id)+ .is_some()+ {+ crate::workspace_threads::create_remote_project_from_path(+ &self.active_space_id,+ path.as_ref(),+ )+ } else {+ crate::workspace_threads::create_project_from_path(+ &self.active_space_id,+ path.as_ref(),+ )+ };match result {Ok(thread_id) => self.activate_workspace_thread(thread_id, window),Err(err) => log::error!("failed to create ThinkTerm project: {err:#}"),@@ -4168,8 +4251,8 @@ impl TermWindow {if pane.domain_id() != domain_id {continue;}- if let Some(url) = pane- .get_current_working_dir(mux::pane::CachePolicy::AllowStale)+ if let Some(url) =+ pane.get_current_working_dir(mux::pane::CachePolicy::AllowStale){let path = url.path().to_string();if !path.is_empty() && !candidates.contains(&path) {@@ -4178,8 +4261,7 @@ impl TermWindow {}}}- for path in crate::workspace_threads::project_paths_for_space(&self.active_space_id)- {+ for path in crate::workspace_threads::project_paths_for_space(&self.active_space_id) {if !candidates.contains(&path) {candidates.push(path);}@@ -4251,10 +4333,9 @@ impl TermWindow {(InlineTabRenameTarget::WorkspaceThread(id), UIItemType::WorkspaceThread(other)) => {id == other}- (- InlineTabRenameTarget::File(path),- UIItemType::RightSidebarFileRow(other),- ) => path == other,+ (InlineTabRenameTarget::File(path), UIItemType::RightSidebarFileRow(other)) => {+ path == other+ }_ => false,}}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex d13b80dd..0d71137a 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -41,6 +41,25 @@ use wezterm_term::{ClickPosition, LastMouseClick, StableRowIndex};const TAB_WHEEL_SURFACE_LOCK_MS: u64 = 700;const TAB_WHEEL_DIRECTION_LOCK_MS: u64 = 140;+fn note_drag_scroll_delta(+ pointer_y: f32,+ top: f32,+ bottom: f32,+ edge: f32,+ max_step: f32,+) -> Option<f32> {+ let edge = edge.min((bottom - top).max(0.0) / 3.0).max(1.0);+ if pointer_y < top + edge {+ let intensity = ((top + edge - pointer_y) / edge).clamp(0.2, 1.0);+ Some(-max_step * intensity)+ } else if pointer_y > bottom - edge {+ let intensity = ((pointer_y - (bottom - edge)) / edge).clamp(0.2, 1.0);+ Some(max_step * intensity)+ } else {+ None+ }+}+fn trailing_action_reserved_width(fixed_clearance: usize,action_button_count: usize,@@ -66,7 +85,7 @@ fn trailing_action_reserved_width(#[cfg(test)]mod window_tab_layout_tests {- use super::trailing_action_reserved_width;+ use super::{note_drag_scroll_delta, trailing_action_reserved_width};#[test]fn trailing_actions_keep_tabs_before_the_new_tab_button() {@@ -78,6 +97,22 @@ mod window_tab_layout_tests {fn trailing_actions_include_integrated_window_buttons() {assert_eq!(trailing_action_reserved_width(26, 2, 34, 8, 3), 224);}++ #[test]+ fn note_drag_edge_scroll_has_direction_and_safe_zone() {+ assert_eq!(note_drag_scroll_delta(50.0, 0.0, 200.0, 40.0, 28.0), None);+ assert_eq!(+ note_drag_scroll_delta(0.0, 0.0, 200.0, 40.0, 28.0),+ Some(-28.0)+ );+ assert_eq!(+ note_drag_scroll_delta(200.0, 0.0, 200.0, 40.0, 28.0),+ Some(28.0)+ );+ assert!(+ note_drag_scroll_delta(30.0, 0.0, 200.0, 40.0, 28.0).expect("top edge delta") < 0.0+ );+ }}/// Overall ceiling on the "Connecting…" phase, as a backstop for the case where@@ -656,6 +691,21 @@ impl super::TermWindow {return false;}+ if self.right_sidebar_mode == super::RightSidebarMode::Tasks {+ if let WMEK::HorzWheel(amount) = event.kind {+ if amount != 0+ && self.right_sidebar_note.scroll_code_block_at(+ event.coords.x as f32,+ event.coords.y as f32,+ Self::sidebar_scroll_pixels(amount) * 2.0,+ )+ {+ context.invalidate();+ }+ return true;+ }+ }+let amount = match event.kind {WMEK::VertWheel(amount) => amount,WMEK::HorzWheel(_) => return true,@@ -665,17 +715,29 @@ impl super::TermWindow {return true;}- if self.right_sidebar_mode == super::RightSidebarMode::Chat {- if self.scroll_right_sidebar_files(amount) {- context.invalidate();+ match self.right_sidebar_mode {+ super::RightSidebarMode::Chat => {+ if self.scroll_right_sidebar_files(amount) {+ context.invalidate();+ }}- } else {- let was_visible = self.right_sidebar_snippet_scrollbar_visible_until;- self.show_right_sidebar_snippet_scrollbar();- if self.scroll_right_sidebar_snippets(amount)- || was_visible != self.right_sidebar_snippet_scrollbar_visible_until- {- context.invalidate();+ super::RightSidebarMode::Tasks => {+ self.right_sidebar_note.reveal_caret = false;+ if self+ .right_sidebar_note+ .scroll_by(Self::sidebar_scroll_pixels(amount))+ {+ context.invalidate();+ }+ }+ super::RightSidebarMode::Snippets => {+ let was_visible = self.right_sidebar_snippet_scrollbar_visible_until;+ self.show_right_sidebar_snippet_scrollbar();+ if self.scroll_right_sidebar_snippets(amount)+ || was_visible != self.right_sidebar_snippet_scrollbar_visible_until+ {+ context.invalidate();+ }}}true@@ -734,6 +796,11 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_)| UIItemType::RightSidebarSnippetScrollTrack| UIItemType::RightSidebarSnippetScrollThumb+ | UIItemType::RightSidebarNoteModeToggle+ | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteCodeToggle(_)+ | UIItemType::RightSidebarNoteCodeCopy(_)+ | UIItemType::RightSidebarNoteBody| UIItemType::RightSidebarFilePreviewScrollTrack| UIItemType::RightSidebarFilePreviewScrollThumb| UIItemType::RightSidebarFilePreviewHorizontalScrollTrack@@ -798,6 +865,11 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_)| UIItemType::RightSidebarSnippetScrollTrack| UIItemType::RightSidebarSnippetScrollThumb+ | UIItemType::RightSidebarNoteModeToggle+ | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteCodeToggle(_)+ | UIItemType::RightSidebarNoteCodeCopy(_)+ | UIItemType::RightSidebarNoteBody| UIItemType::RightSidebarFilePreviewScrollTrack| UIItemType::RightSidebarFilePreviewScrollThumb| UIItemType::RightSidebarFilePreviewHorizontalScrollTrack@@ -1028,6 +1100,19 @@ impl super::TermWindow {);context.invalidate();}+ if completed_drag+ .as_ref()+ .is_some_and(|(item, _)| item.item_type == UIItemType::RightSidebarNoteBody)+ {+ if self.right_sidebar_note.drag_selection_active {+ self.update_right_sidebar_note_drag_selection(+ event.coords.x,+ event.coords.y,+ );+ }+ self.right_sidebar_note.drag_selection_active = false;+ context.invalidate();+ }if completed_drag.as_ref().is_some_and(|(item, _)| {matches!(item.item_type, UIItemType::RightSidebarFileRow(_))}) {@@ -1460,6 +1545,96 @@ impl super::TermWindow {self.dragging.replace((item, start_event));}+ fn drag_right_sidebar_note_selection(+ &mut self,+ item: UIItem,+ start_event: MouseEvent,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ self.right_sidebar_note.drag_selection_active = true;+ self.update_right_sidebar_note_drag_selection(event.coords.x, event.coords.y);+ if self+ .right_sidebar_note_drag_scroll_delta(&item, &event)+ .is_some()+ {+ self.schedule_right_sidebar_note_drag_autoscroll();+ }+ context.set_cursor(Some(MouseCursor::Text));+ context.invalidate();+ self.dragging.replace((item, start_event));+ }++ fn update_right_sidebar_note_drag_selection(&mut self, x: isize, y: isize) {+ let position = self+ .right_sidebar_note+ .source_position_for_point(x as f32, y as f32);+ self.right_sidebar_note.view.selection.focus = position;+ self.right_sidebar_note.view.preferred_column = None;+ self.right_sidebar_note.reveal_caret = false;+ self.right_sidebar_note.refresh_projection();+ }++ fn right_sidebar_note_drag_scroll_delta(+ &self,+ item: &UIItem,+ event: &MouseEvent,+ ) -> Option<f32> {+ let top = item.y as f32;+ let bottom = item.y.saturating_add(item.height) as f32;+ note_drag_scroll_delta(+ event.coords.y as f32,+ top,+ bottom,+ self.ui_f32(40.0),+ self.ui_f32(28.0),+ )+ }++ fn schedule_right_sidebar_note_drag_autoscroll(&mut self) {+ if self.right_sidebar_note.drag_autoscroll_scheduled {+ return;+ }+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ self.right_sidebar_note.drag_autoscroll_scheduled = true;+ promise::spawn::spawn(async move {+ smol::Timer::after(Duration::from_millis(32)).await;+ window.notify(TermWindowNotif::Apply(Box::new(|term_window| {+ term_window.right_sidebar_note.drag_autoscroll_scheduled = false;+ if term_window.step_right_sidebar_note_drag_autoscroll() {+ term_window.invalidate_window();+ term_window.schedule_right_sidebar_note_drag_autoscroll();+ }+ })));+ })+ .detach();+ }++ fn step_right_sidebar_note_drag_autoscroll(&mut self) -> bool {+ if !self.right_sidebar_note.drag_selection_active {+ return false;+ }+ let Some((item, _)) = self.dragging.as_ref() else {+ return false;+ };+ if item.item_type != UIItemType::RightSidebarNoteBody {+ return false;+ }+ let Some(event) = self.current_mouse_event.clone() else {+ return false;+ };+ let Some(delta) = self.right_sidebar_note_drag_scroll_delta(item, &event) else {+ return false;+ };+ let changed = self.right_sidebar_note.scroll_by(delta);+ if changed {+ self.update_right_sidebar_note_drag_selection(event.coords.x, event.coords.y);+ }+ changed+ }+fn drag_ui_item(&mut self,item: UIItem,@@ -1512,6 +1687,9 @@ impl super::TermWindow {context,);}+ UIItemType::RightSidebarNoteBody => {+ self.drag_right_sidebar_note_selection(item, start_event, event, context);+ }UIItemType::RightSidebarFileFilter| UIItemType::RightSidebarSnippetSearch| UIItemType::RightSidebarSnippetTitle => {@@ -1806,6 +1984,13 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}+ UIItemType::RightSidebarNoteModeToggle+ | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteCodeToggle(_)+ | UIItemType::RightSidebarNoteCodeCopy(_)+ | UIItemType::RightSidebarNoteBody => {+ self.mouse_event_right_sidebar_note(item.clone(), event, context);+ }UIItemType::RightSidebarFileFilter| UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)@@ -1846,6 +2031,151 @@ impl super::TermWindow {}}+ fn mouse_event_right_sidebar_note(+ &mut self,+ item: UIItem,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ match item.item_type.clone() {+ UIItemType::RightSidebarNoteModeToggle => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.toggle_right_sidebar_note_mode();+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteSave => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.save_right_sidebar_note_now();+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteCodeToggle(source_start) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ let code =+ self.right_sidebar_note+ .projection+ .objects+ .iter()+ .find_map(|object| match object {+ crate::markdown_editor::ProjectedObject::CodeBlock(code)+ if code.source.start == source_start =>+ {+ Some(code.clone())+ }+ _ => None,+ });+ let collapsed = self.right_sidebar_note.toggle_code_block(source_start);+ if collapsed {+ if let Some(code) = code {+ let caret = self.right_sidebar_note.view.selection.focus.byte;+ if code.content.start <= caret && caret <= code.content.end {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ let target = {+ let session = session.lock();+ let source = session.source();+ let end = code.source.end.min(source.len());+ if source[end..].starts_with('\n') {+ (end + 1).min(source.len())+ } else {+ end+ }+ };+ session.lock().set_caret(+ &mut self.right_sidebar_note.view,+ target,+ false,+ );+ }+ }+ }+ }+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteCodeCopy(source_start) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ if let Some(text) =+ self.right_sidebar_note+ .projection+ .objects+ .iter()+ .find_map(|object| match object {+ crate::markdown_editor::ProjectedObject::CodeBlock(code)+ if code.source.start == source_start =>+ {+ Some(code.text.clone())+ }+ _ => None,+ })+ {+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);+ }+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteBody => {+ context.set_cursor(Some(MouseCursor::Text));+ if event.kind == WMEK::Press(MousePress::Left) {+ if let Some(range) = self+ .right_sidebar_note+ .atomic_source_for_point(event.coords.x as f32, event.coords.y as f32)+ {+ let replacement =+ self.right_sidebar_note+ .session+ .as_ref()+ .and_then(|session| {+ let session = session.lock();+ session.source().get(range.clone()).and_then(|source| {+ let trimmed = source.trim();+ if trimmed.eq_ignore_ascii_case("[x]") {+ Some("[ ]")+ } else if trimmed == "[ ]" {+ Some("[x]")+ } else {+ None+ }+ })+ });+ if let Some(replacement) = replacement {+ self.right_sidebar_note.view.focused = true;+ self.right_sidebar_note.view.selection =+ crate::markdown_editor::SourceSelection {+ anchor: crate::markdown_editor::SourcePosition::new(+ range.start,+ ),+ focus: crate::markdown_editor::SourcePosition::new(range.end),+ };+ self.push_right_sidebar_text(replacement);+ context.invalidate();+ return;+ }+ }+ let position = self+ .right_sidebar_note+ .source_position_for_point(event.coords.x as f32, event.coords.y as f32);+ self.right_sidebar_note.view.focused = true;+ self.right_sidebar_note.view.selection =+ crate::markdown_editor::SourceSelection::caret(position.byte);+ self.right_sidebar_note.view.preferred_column = None;+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.drag_selection_active = false;+ self.right_sidebar_note.refresh_projection();+ self.dragging.replace((item, event));+ context.invalidate();+ }+ }+ _ => {}+ }+ }+fn mouse_event_ui_item_without_pane(&mut self,item: UIItem,@@ -1987,6 +2317,13 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}+ UIItemType::RightSidebarNoteModeToggle+ | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteCodeToggle(_)+ | UIItemType::RightSidebarNoteCodeCopy(_)+ | UIItemType::RightSidebarNoteBody => {+ self.mouse_event_right_sidebar_note(item.clone(), event, context);+ }UIItemType::RightSidebarFileFilter| UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)@@ -2268,6 +2605,12 @@ impl super::TermWindow {context.set_cursor(Some(MouseCursor::Hand));if event.kind == WMEK::Press(MousePress::Left) {let previous_width = self.right_sidebar_width();+ let previous_mode = self.right_sidebar_mode;+ if previous_mode == super::RightSidebarMode::Tasks+ && mode != super::RightSidebarMode::Tasks+ {+ self.clear_right_sidebar_text_focus();+ }self.right_sidebar_mode = mode;// Leaving the file view (e.g. switching to Snippets/Tasks) makes the// file index idle; schedule it for release. Entering it refreshes +diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rsindex 63c8b0e0..d6244408 100644--- a/wezterm-gui/src/termwindow/render/mod.rs+++ b/wezterm-gui/src/termwindow/render/mod.rs@@ -587,6 +587,9 @@ impl crate::TermWindow {}pub fn compute_cell_fg_bg(&self, params: ComputeCellFgBgParams) -> ComputeCellFgBgResult {+ let focused_and_active =+ self.focused.is_some() && params.is_active_pane && !self.right_sidebar_has_text_focus();+if params.cursor.is_some() {if let Some(bg_color_mix) = self.get_intensity_if_bell_target_ringing(params.pane.expect("cursor only set if pane present"),@@ -627,7 +630,7 @@ impl crate::TermWindow {let dead_key_or_leader =self.dead_key_status != DeadKeyStatus::None || self.leader_is_active();- if dead_key_or_leader && params.is_active_pane {+ if dead_key_or_leader && focused_and_active {let (fg_color, bg_color) = if self.use_reverse_video_cursor(¶ms) {(params.bg_color, params.fg_color)} else {@@ -669,8 +672,6 @@ impl crate::TermWindow {_ => (CursorShape::default(), CursorVisibility::Hidden),};- let focused_and_active = self.focused.is_some() && params.is_active_pane;-let (fg_color, bg_color, cursor_bg) = match (params.selected,focused_and_active,@@ -722,10 +723,9 @@ impl crate::TermWindow {let fg_color = self.ensure_min_contrast(fg_color, bg_color);let blinking = params.cursor.is_some()- && params.is_active_pane+ && focused_and_active&& cursor_shape.is_blinking()- && params.config.cursor_blink_rate != 0- && self.focused.is_some();+ && params.config.cursor_blink_rate != 0;let mut fg_color_alt = fg_color;let bg_color_alt = bg_color;diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 0c65e2fd..65782db4 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -426,13 +426,8 @@ impl crate::TermWindow {.min(self.dimensions.pixel_height as f32 - pill_h).max(0.0);- self.filled_rectangle(- &mut layers,- 0,- euclid::rect(x, y, pill_w, pill_h),- bg,- )- .context("file drag ghost background")?;+ self.filled_rectangle(&mut layers, 0, euclid::rect(x, y, pill_w, pill_h), bg)+ .context("file drag ghost background")?;ctx.draw_text_on_layer(&mut layers,2,diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex 9c32f324..a3f0840f 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -1,3 +1,9 @@+use crate::markdown_editor::{+ default_notebook, fit_table_columns, resolve_local_image, save_document_revision,+ wrap_visual_document_by_width, BlockKind, EditorMode, NoteCodeBlockLayout, NoteLineLayout,+ NoteRunLayout, ProjectedCodeBlock, ProjectedObject, SaveState, SourceSelection, TableAlignment,+ VisualLineKind,+};use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};use crate::termwindow::ui::icons::{material_file_icon_for_name, material_folder_icon_for_name, MaterialIcon, SvgIcon,@@ -27,22 +33,22 @@ use std::borrow::Cow;use std::cmp::Ordering;use std::collections::{HashMap, HashSet};use std::fs;+use std::hash::{DefaultHasher, Hash, Hasher};use std::io::Read;use std::path::{Path, PathBuf};use std::rc::Rc;-use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};use std::sync::{Arc, Mutex, OnceLock, Weak};use std::time::{Duration, Instant};-use syntect::easy::HighlightLines;-use syntect::highlighting::{Color as SyntectColor, Style as SyntectStyle, Theme, ThemeSet};-use syntect::parsing::SyntaxSet;use termwiz::image::{ImageData, ImageDataType};use termwiz::input::{KeyCode as TermKeyCode, Modifiers as TermModifiers};+use thinkterm_syntax::{HighlightKind, HighlightResult, HighlightSpan};use walkdir::{DirEntry as WalkDirEntry, WalkDir};use wezterm_font::LoadedFont;use window::color::LinearRgba;use window::{- Clipboard, ContextMenuItem, IntegratedTitleButtonStyle, WindowDecorations, WindowOps,+ Clipboard, ContextMenuItem, DeadKeyStatus, IntegratedTitleButtonStyle, Point, Rect,+ WindowDecorations, WindowOps,};const RIGHT_SIDEBAR_SECTION_GAP: usize = 12;@@ -70,6 +76,22 @@ const SNIPPET_LIST_TOP_GAP: usize = 18;const SNIPPET_LIST_BOTTOM_PADDING: usize = 40;const RIGHT_SIDEBAR_SCROLLBAR_VISIBLE_MS: u64 = 900;const SNIPPET_CARET_WIDTH: f32 = 3.0;+const NOTE_TOOLBAR_HEIGHT: usize = 54;+const NOTE_BODY_TOP_GAP: usize = 12;+const NOTE_BODY_PADDING: usize = 16;+const NOTE_LINE_GAP: usize = 5;+const NOTE_CARET_WIDTH: f32 = 2.0;+const NOTE_TABLE_CELL_HORIZONTAL_PADDING: usize = 10;+const NOTE_TABLE_CELL_VERTICAL_PADDING: usize = 7;+const NOTE_TABLE_MIN_COLUMN_WIDTH: usize = 64;+const NOTE_CODE_HEADER_HEIGHT: usize = 38;+const NOTE_CODE_HORIZONTAL_PADDING: usize = 12;+const NOTE_CODE_VERTICAL_PADDING: usize = 9;+const NOTE_CODE_CONTROL_SIZE: usize = 28;+const NOTE_CODE_BLOCK_RADIUS: f32 = SIDEBAR_ROW_RADIUS;+const NOTE_CODE_HIGHLIGHT_CACHE_CAPACITY: usize = 64;+const NOTE_AUTOSAVE_MS: u64 = 300;+const NOTE_IMAGE_CACHE_CAPACITY: usize = 32;const FILE_FONT_MIN_SIZE: f64 = 14.0;const FILE_FILTER_HEIGHT: usize = 66;const FILE_TREE_TOP_GAP: usize = 14;@@ -86,12 +108,6 @@ 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;-// Per-line we keep the *full* content (bounded only by FILE_PREVIEW_MAX_BYTES-// for the whole file) so minified CSS/JS, lockfiles and JSON aren't truncated.-// We only bound the *syntax-highlighting* work per line: characters past this-// point are rendered in the default colour instead of being dropped. This keeps-// syntect cost bounded on pathological single-line files without losing data.-const FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT: usize = 8192;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@@ -111,6 +127,61 @@ const FILE_INDEX_RESCAN_SECS: u64 = 90;const FILE_VIEW_STATE_CACHE_CAP: usize = 32;const FILE_FILTER_DEBOUNCE_MS: u64 = 350;+fn note_boundary_x(boundaries: &[(f32, usize)], byte: usize) -> f32 {+ boundaries+ .iter()+ .filter(|(_, source)| *source <= byte)+ .next_back()+ .or_else(|| boundaries.first())+ .map(|(x, _)| *x)+ .unwrap_or(0.0)+}++fn note_code_row_height(+ row_index: usize,+ row_count: usize,+ collapsed: bool,+ line_height: f32,+ header_height: f32,+ vertical_padding: f32,+) -> f32 {+ if collapsed {+ return if row_index == 0 { header_height } else { 0.0 };+ }+ line_height+ + if row_index == 0 {+ header_height + vertical_padding+ } else {+ 0.0+ }+ + if row_index + 1 == row_count {+ vertical_padding+ } else {+ 0.0+ }+}++#[derive(Debug, Clone)]+struct NoteTableRowPaintLayout {+ column_widths: Rc<Vec<f32>>,+ alignments: Rc<Vec<TableAlignment>>,+ row_index: usize,+ row_count: usize,+}++#[derive(Debug, Clone)]+struct NoteCodeRowPaintLayout {+ block_start: usize,+ language: String,+ row_index: usize,+ row_count: usize,+ collapsed: bool,+ colors: Arc<Vec<Vec<LinearRgba>>>,+ horizontal_offset: f32,+ block_height: f32,+ max_horizontal_scroll: f32,+}+#[derive(Debug, Clone, Copy)]pub struct RightSidebarRect {pub x: usize,@@ -273,14 +344,6 @@ impl RightSidebarMode {Self::Snippets => "Snippets",}}-- fn empty_label(self) -> &'static str {- match self {- Self::Chat => "Coming soon",- Self::Tasks => "Coming soon",- Self::Snippets => "No snippets",- }- }}pub fn right_sidebar_width_for_metrics(render_metrics: &RenderMetrics, dpi: usize) -> usize {@@ -473,6 +536,9 @@ impl crate::TermWindow {pub fn toggle_right_sidebar(&mut self) {self.right_sidebar_collapsed = !self.right_sidebar_collapsed;if self.right_sidebar_collapsed {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.clear_right_sidebar_text_focus();+ }self.schedule_right_sidebar_file_memory_release();} else {self.kick_right_sidebar_file_rescan_cycle();@@ -636,13 +702,18 @@ impl crate::TermWindow {match self.right_sidebar_mode {RightSidebarMode::Chat => self.right_sidebar_file_focus.is_some(),RightSidebarMode::Snippets => self.right_sidebar_snippet_focus.is_some(),- RightSidebarMode::Tasks => false,+ RightSidebarMode::Tasks => self.right_sidebar_note.view.focused,}}pub(crate) fn clear_right_sidebar_text_focus(&mut self) {+ let note_was_focused = self.right_sidebar_note.view.focused;self.right_sidebar_snippet_focus = None;self.right_sidebar_file_focus = None;+ self.right_sidebar_note.view.focused = false;+ if note_was_focused {+ self.save_right_sidebar_note_now();+ }}pub(crate) fn open_new_snippet_editor(&mut self) {@@ -848,6 +919,10 @@ impl crate::TermWindow {self.right_sidebar_file_preview_generation =self.right_sidebar_file_preview_generation.wrapping_add(1);let generation = self.right_sidebar_file_preview_generation;+ self.right_sidebar_file_preview_highlight_cancel+ .store(1, AtomicOrdering::Relaxed);+ self.right_sidebar_file_preview_highlight_cancel = Arc::new(AtomicUsize::new(0));+ let highlight_cancel = Arc::clone(&self.right_sidebar_file_preview_highlight_cancel);self.right_sidebar_file_preview_lines.clear();self.right_sidebar_file_preview_max_columns = 0;self.clear_right_sidebar_file_preview_slice_cache();@@ -871,9 +946,10 @@ impl crate::TermWindow {let load_path = path.clone();promise::spawn::spawn(async move {let result = promise::spawn::spawn_into_new_thread(move || {- Ok(load_right_sidebar_file_preview(+ Ok(load_right_sidebar_file_preview_with_cancellation(&load_path,use_dark_syntax_theme,+ Some(highlight_cancel.as_ref()),))}).await@@ -916,6 +992,9 @@ impl crate::TermWindow {self.right_sidebar_file_selected = None;self.right_sidebar_file_preview_generation =self.right_sidebar_file_preview_generation.wrapping_add(1);+ self.right_sidebar_file_preview_highlight_cancel+ .store(1, AtomicOrdering::Relaxed);+ self.right_sidebar_file_preview_highlight_cancel = Arc::new(AtomicUsize::new(0));self.right_sidebar_file_preview_lines.clear();self.right_sidebar_file_preview_max_columns = 0;self.clear_right_sidebar_file_preview_slice_cache();@@ -942,6 +1021,97 @@ impl crate::TermWindow {.clear();}+ fn cached_note_code_highlights(+ &mut self,+ code: &ProjectedCodeBlock,+ use_dark_theme: bool,+ ) -> Arc<Vec<Vec<LinearRgba>>> {+ let revision = self.right_sidebar_note.projection_revision.unwrap_or(0);+ if self.right_sidebar_note_code_highlight_revision != revision {+ self.right_sidebar_note_code_highlight_cancel+ .store(1, AtomicOrdering::Relaxed);+ self.right_sidebar_note_code_highlight_cancel = Arc::new(AtomicUsize::new(0));+ self.right_sidebar_note_code_highlight_revision = revision;+ self.right_sidebar_note_code_highlights_pending.clear();+ }++ let key = (revision, code.source.start, use_dark_theme);+ if let Some(lines) = self.right_sidebar_note_code_highlights.get(&key).cloned() {+ return lines;+ }++ let lines = Arc::new(vec![vec![]; note_code_line_count(&code.text)]);+ self.insert_note_code_highlight_cache(key, Arc::clone(&lines));++ let supported = code.text.len() <= thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT+ && code+ .language+ .as_deref()+ .and_then(thinkterm_syntax::detect_fence)+ .is_some();+ let pending_key = (revision, code.source.start);+ if supported+ && self+ .right_sidebar_note_code_highlights_pending+ .insert(pending_key)+ {+ if let Some(window) = self.window.as_ref().cloned() {+ let code = code.clone();+ let cancellation = Arc::clone(&self.right_sidebar_note_code_highlight_cancel);+ syntax_highlight_pool().spawn(move || {+ let result = note_code_highlight_pair(&code, Some(cancellation.as_ref()));+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.apply_note_code_highlight_result(pending_key, result);+ })));+ });+ } else {+ self.right_sidebar_note_code_highlights_pending+ .remove(&pending_key);+ }+ }++ lines+ }++ fn insert_note_code_highlight_cache(+ &mut self,+ key: (u64, usize, bool),+ lines: Arc<Vec<Vec<LinearRgba>>>,+ ) {+ if !self.right_sidebar_note_code_highlights.contains_key(&key) {+ self.right_sidebar_note_code_highlight_order.push_back(key);+ }+ self.right_sidebar_note_code_highlights.insert(key, lines);+ while self.right_sidebar_note_code_highlight_order.len()+ > NOTE_CODE_HIGHLIGHT_CACHE_CAPACITY+ {+ if let Some(expired) = self.right_sidebar_note_code_highlight_order.pop_front() {+ self.right_sidebar_note_code_highlights.remove(&expired);+ }+ }+ }++ fn apply_note_code_highlight_result(+ &mut self,+ pending_key: (u64, usize),+ result: Option<(Vec<Vec<LinearRgba>>, Vec<Vec<LinearRgba>>)>,+ ) {+ self.right_sidebar_note_code_highlights_pending+ .remove(&pending_key);+ if self.right_sidebar_note.projection_revision.unwrap_or(0) != pending_key.0 {+ return;+ }+ let Some((light, dark)) = result else {+ return;+ };+ self.insert_note_code_highlight_cache(+ (pending_key.0, pending_key.1, false),+ Arc::new(light),+ );+ self.insert_note_code_highlight_cache((pending_key.0, pending_key.1, true), Arc::new(dark));+ self.invalidate_window();+ }+/// Per-byte colours for a whole preview line, keyed by (generation, line/// index) so horizontal scrolling reuses the same colour list. Indexed by/// byte offset into `line.plain` so a glyph's `cluster` maps straight to its@@ -1934,6 +2104,18 @@ impl crate::TermWindow {}pub(crate) fn copy_right_sidebar_focused_input(&self, destination: ClipboardCopyDestination) {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ let Some(session) = self.right_sidebar_note.session.as_ref() else {+ return;+ };+ let session = session.lock();+ if let Some(text) = session.selected_text(&self.right_sidebar_note.view) {+ if !text.is_empty() {+ self.copy_to_clipboard(destination, text.to_string());+ }+ }+ return;+ }let Some(input) = self.right_sidebar_focused_input() else {return;};@@ -1946,6 +2128,22 @@ impl crate::TermWindow {}pub(crate) fn cut_right_sidebar_focused_input(&mut self) {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ let selected = session+ .lock()+ .selected_text(&self.right_sidebar_note.view)+ .map(str::to_string);+ if let Some(text) = selected {+ if session.lock().backspace(&mut self.right_sidebar_note.view) {+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);+ self.note_did_edit();+ }+ }+ return;+ }let Some(input) = self.right_sidebar_focused_input_mut() else {return;};@@ -1984,6 +2182,15 @@ impl crate::TermWindow {}pub(crate) fn clear_right_sidebar_focused_input_selection(&mut self) {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ let focus = self.right_sidebar_note.view.selection.focus;+ self.right_sidebar_note.view.selection = SourceSelection {+ anchor: focus,+ focus,+ };+ self.right_sidebar_note.refresh_projection();+ return;+ }if let Some(input) = self.right_sidebar_focused_input_mut() {input.clear_selection();}@@ -2004,6 +2211,10 @@ impl crate::TermWindow {let ctrl = mods.contains(TermModifiers::CTRL);let multiline = self.right_sidebar_focused_is_multiline();+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ return self.handle_right_sidebar_note_key(key, mods);+ }+// Cmd shortcuts (macOS): clipboard, select-all, jump to line start/end.if super_ && !alt && !ctrl {return match key {@@ -2209,6 +2420,18 @@ impl crate::TermWindow {}pub(crate) fn push_right_sidebar_text(&mut self, text: &str) -> bool {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ let changed = session+ .lock()+ .insert_text(&mut self.right_sidebar_note.view, text);+ if changed {+ self.note_did_edit();+ }+ return changed;+ }let multiline = self.right_sidebar_focused_is_multiline();let Some(input) = self.right_sidebar_focused_input_mut() else {return false;@@ -2218,6 +2441,353 @@ impl crate::TermWindow {true}+ fn handle_right_sidebar_note_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {+ let shift = mods.contains(TermModifiers::SHIFT);+ let super_ = mods.contains(TermModifiers::SUPER);+ let ctrl = mods.contains(TermModifiers::CTRL);+ let alt = mods.contains(TermModifiers::ALT);+ let command = super_ || (ctrl && !cfg!(target_os = "macos"));+ let word_modifier = if cfg!(target_os = "macos") {+ alt && !super_ && !ctrl+ } else {+ ctrl && !super_ && !alt+ };++ if word_modifier {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ match key {+ TermKeyCode::LeftArrow => {+ session+ .lock()+ .move_word_left(&mut self.right_sidebar_note.view, shift);+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ return true;+ }+ TermKeyCode::RightArrow => {+ session+ .lock()+ .move_word_right(&mut self.right_sidebar_note.view, shift);+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ return true;+ }+ TermKeyCode::Backspace => {+ if session+ .lock()+ .delete_word_back(&mut self.right_sidebar_note.view)+ {+ self.note_did_edit();+ }+ return true;+ }+ _ => {}+ }+ }++ if command && !alt {+ match key {+ TermKeyCode::LeftArrow if super_ => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ session+ .lock()+ .move_line_start(&mut self.right_sidebar_note.view, shift);+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ }+ return true;+ }+ TermKeyCode::RightArrow if super_ => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ 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();+ }+ return true;+ }+ TermKeyCode::Char('a') | TermKeyCode::Char('A') => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ session.lock().select_all(&mut self.right_sidebar_note.view);+ self.right_sidebar_note.refresh_projection();+ }+ return true;+ }+ TermKeyCode::Char('c') | TermKeyCode::Char('C') => {+ self.copy_right_sidebar_focused_input(ClipboardCopyDestination::Clipboard);+ return true;+ }+ TermKeyCode::Char('x') | TermKeyCode::Char('X') => {+ self.cut_right_sidebar_focused_input();+ return true;+ }+ TermKeyCode::Char('v') | TermKeyCode::Char('V') => {+ self.paste_into_right_sidebar_from_clipboard(ClipboardPasteSource::Clipboard);+ return true;+ }+ TermKeyCode::Char('z') | TermKeyCode::Char('Z') => {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return true;+ };+ let changed = if shift {+ session.lock().redo(&mut self.right_sidebar_note.view)+ } else {+ session.lock().undo(&mut self.right_sidebar_note.view)+ };+ if changed {+ self.note_did_edit();+ }+ return true;+ }+ TermKeyCode::Char('s') | TermKeyCode::Char('S') => {+ self.save_right_sidebar_note_now();+ return true;+ }+ TermKeyCode::Char('e') | TermKeyCode::Char('E') => {+ self.toggle_right_sidebar_note_mode();+ return true;+ }+ TermKeyCode::Char('b') | TermKeyCode::Char('B') => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().surround_selection(+ &mut self.right_sidebar_note.view,+ "**",+ "**",+ ) {+ self.note_did_edit();+ }+ }+ return true;+ }+ TermKeyCode::Char('i') | TermKeyCode::Char('I') => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().surround_selection(+ &mut self.right_sidebar_note.view,+ "*",+ "*",+ ) {+ self.note_did_edit();+ }+ }+ return true;+ }+ _ => {}+ }+ }++ if command || ctrl || alt {+ return false;+ }++ let Some(session) = self.right_sidebar_note.session.clone() else {+ return false;+ };+ let mut changed = false;+ let handled = match key {+ TermKeyCode::Escape => {+ self.right_sidebar_note.view.focused = false;+ true+ }+ TermKeyCode::LeftArrow => {+ session+ .lock()+ .move_left(&mut self.right_sidebar_note.view, shift);+ true+ }+ TermKeyCode::RightArrow => {+ session+ .lock()+ .move_right(&mut self.right_sidebar_note.view, shift);+ true+ }+ TermKeyCode::UpArrow => {+ if let Some((position, preferred)) =+ self.right_sidebar_note.visual_vertical_target(-1)+ {+ if shift {+ self.right_sidebar_note.view.selection.focus = position;+ } else {+ self.right_sidebar_note.view.selection =+ SourceSelection::caret(position.byte);+ }+ self.right_sidebar_note.view.preferred_column = Some(preferred);+ } else {+ session+ .lock()+ .move_vertical(&mut self.right_sidebar_note.view, -1, shift);+ }+ true+ }+ TermKeyCode::DownArrow => {+ if let Some((position, preferred)) =+ self.right_sidebar_note.visual_vertical_target(1)+ {+ if shift {+ self.right_sidebar_note.view.selection.focus = position;+ } else {+ self.right_sidebar_note.view.selection =+ SourceSelection::caret(position.byte);+ }+ self.right_sidebar_note.view.preferred_column = Some(preferred);+ } else {+ session+ .lock()+ .move_vertical(&mut self.right_sidebar_note.view, 1, shift);+ }+ true+ }+ TermKeyCode::Home => {+ session+ .lock()+ .move_line_start(&mut self.right_sidebar_note.view, shift);+ true+ }+ TermKeyCode::End => {+ session+ .lock()+ .move_line_end(&mut self.right_sidebar_note.view, shift);+ true+ }+ TermKeyCode::Backspace => {+ changed = session.lock().backspace(&mut self.right_sidebar_note.view);+ true+ }+ TermKeyCode::Delete => {+ changed = session+ .lock()+ .delete_forward(&mut self.right_sidebar_note.view);+ true+ }+ TermKeyCode::Enter => {+ changed = session+ .lock()+ .insert_newline(&mut self.right_sidebar_note.view);+ true+ }+ TermKeyCode::Tab => {+ if let Some(target) =+ self.right_sidebar_note+ .table_cell_target(if shift { -1 } else { 1 })+ {+ session+ .lock()+ .set_caret(&mut self.right_sidebar_note.view, target, false);+ self.right_sidebar_note.reveal_caret = true;+ } else {+ changed = session+ .lock()+ .insert_text(&mut self.right_sidebar_note.view, " ");+ }+ true+ }+ TermKeyCode::Char(ch) if !ch.is_control() => {+ changed = session+ .lock()+ .insert_text(&mut self.right_sidebar_note.view, &ch.to_string());+ true+ }+ _ => false,+ };+ if changed {+ self.note_did_edit();+ } else if handled {+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ }+ handled+ }++ pub(crate) fn toggle_right_sidebar_note_mode(&mut self) {+ self.right_sidebar_note.view.mode = match self.right_sidebar_note.view.mode {+ EditorMode::LivePreview => EditorMode::Source,+ EditorMode::Source | EditorMode::ReadOnly => EditorMode::LivePreview,+ };+ self.right_sidebar_note.refresh_projection();+ self.invalidate_window();+ }++ pub(crate) fn save_right_sidebar_note_now(&mut self) {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ if !session.lock().is_dirty() {+ return;+ }+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ promise::spawn::spawn(async move {+ let result =+ promise::spawn::spawn_into_new_thread(move || save_document_revision(&session))+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if let Err(err) = result {+ log::error!("failed to save Note: {err:#}");+ }+ if let Some(front_end) = crate::frontend::try_front_end() {+ for gui_window in front_end.gui_windows() {+ gui_window.window.invalidate();+ }+ } else {+ term_window.invalidate_window();+ }+ })));+ })+ .detach();+ }++ pub(crate) fn flush_right_sidebar_note_blocking(&mut self) {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ if session.lock().is_dirty() {+ if let Err(err) = save_document_revision(&session) {+ log::error!("failed to flush Note before window lifecycle change: {err:#}");+ }+ }+ }++ fn note_did_edit(&mut self) {+ self.right_sidebar_note.refresh_projection();+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.save_generation =+ self.right_sidebar_note.save_generation.wrapping_add(1);+ let generation = self.right_sidebar_note.save_generation;+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ promise::spawn::spawn(async move {+ smol::Timer::after(Duration::from_millis(NOTE_AUTOSAVE_MS)).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if term_window.right_sidebar_note.save_generation != generation {+ return;+ }+ term_window.save_right_sidebar_note_now();+ })));+ })+ .detach();+ if let Some(front_end) = crate::frontend::try_front_end() {+ for gui_window in front_end.gui_windows() {+ gui_window+ .window+ .notify(TermWindowNotif::Apply(Box::new(|term_window| {+ if let Some(session) = term_window.right_sidebar_note.session.clone() {+ session+ .lock()+ .clamp_view(&mut term_window.right_sidebar_note.view);+ term_window.right_sidebar_note.refresh_projection();+ term_window.invalidate_window();+ }+ })));+ }+ } else {+ self.invalidate_window();+ }+ }+/// Map a sidebar text-input `UIItemType` to its `TextInputState`.fn right_sidebar_input_for_item(&self, item_type: &UIItemType) -> Option<&TextInputState> {match item_type {@@ -3204,105 +3774,1224 @@ impl crate::TermWindow {foreground,)?;}- segment_x = segment_right;+ segment_x = segment_right;+ }++ let content_top = mode_y + mode_height + self.ui_px(RIGHT_SIDEBAR_SECTION_GAP);+ match self.right_sidebar_mode {+ RightSidebarMode::Chat => {+ let file_font_size = self.right_sidebar_file_preview_font_size();+ let file_font = self+ .fonts+ .title_font_with_size(file_font_size)+ .context("right sidebar file font")?;+ let file_metrics = RenderMetrics::with_font_metrics(&file_font.metrics());+ let file_icon_size = (file_metrics.cell_size.height as usize + self.ui_px(6))+ .clamp(self.ui_px(22), self.ui_px(28));+ self.paint_files_sidebar(+ layers,+ &file_font,+ file_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ rect.y.saturating_add(rect.height),+ file_icon_size,+ )?;+ return Ok(());+ }+ RightSidebarMode::Snippets => {+ self.paint_snippets_sidebar(+ layers,+ &ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ rect.y.saturating_add(rect.height),+ icon_size,+ )?;+ return Ok(());+ }+ RightSidebarMode::Tasks => {+ self.paint_note_sidebar(+ layers,+ &ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ rect.y.saturating_add(rect.height),+ base_font_size,+ )?;+ return Ok(());+ }+ }+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_note_sidebar(+ &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,+ ) -> anyhow::Result<()> {+ if !self.right_sidebar_note.ensure_loaded() {+ let message = self+ .right_sidebar_note+ .load_error+ .clone()+ .unwrap_or_else(|| "Unable to open Notes".to_string());+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &message,+ content_x,+ content_top,+ content_width,+ muted_fg,+ )?;+ return Ok(());+ }+ self.right_sidebar_note.refresh_projection();++ let toolbar_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);+ let button_gap = self.ui_px(8);+ let mode_label = match self.right_sidebar_note.view.mode {+ EditorMode::LivePreview => "Preview",+ EditorMode::Source => "Source",+ EditorMode::ReadOnly => "Read only",+ };+ let save_state = self+ .right_sidebar_note+ .session+ .as_ref()+ .map(|session| session.lock().save_state().clone())+ .unwrap_or(SaveState::Saved);+ let save_label = match &save_state {+ SaveState::Saved => "Saved",+ SaveState::Dirty => "Save",+ SaveState::Saving(_) => "Saving…",+ SaveState::Failed(_) => "Retry",+ };+ let compact_button_padding = self.ui_px(SIDEBAR_INSET) * 2;+ let desired_mode_width = (self.sidebar_text_width(ui_font, mode_label)?.ceil() as usize+ + compact_button_padding)+ .max(self.ui_px(64));+ let desired_save_width = (self.sidebar_text_width(ui_font, save_label)?.ceil() as usize+ + compact_button_padding)+ .max(self.ui_px(64));+ let desired_actions_width = desired_mode_width + button_gap + desired_save_width;+ let title_label = "Inbox.md";+ let title_label_width = self.sidebar_text_width(ui_font, title_label)?.ceil() as usize;+ let show_title = content_width >= title_label_width + button_gap + desired_actions_width;+ let (title_width, mode_x, mode_width, save_width) = if show_title {+ let title_width = content_width.saturating_sub(desired_actions_width + button_gap);+ (+ title_width,+ content_x + title_width + button_gap,+ desired_mode_width,+ desired_save_width,+ )+ } else {+ let action_width = content_width.saturating_sub(button_gap);+ let mode_width = action_width / 2;+ (+ 0,+ content_x,+ mode_width,+ action_width.saturating_sub(mode_width),+ )+ };+ if show_title {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ title_label,+ content_x,+ content_top+ + (toolbar_height.saturating_sub(ui_metrics.cell_size.height as usize)) / 2,+ title_width,+ foreground,+ )?;+ }+ self.paint_snippet_button(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ mode_x,+ content_top,+ mode_width,+ toolbar_height,+ None,+ mode_label,+ UIItemType::RightSidebarNoteModeToggle,+ true,+ )?;+ let save_x = mode_x + mode_width + button_gap;+ self.paint_snippet_button(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ save_x,+ content_top,+ save_width,+ toolbar_height,+ None,+ save_label,+ UIItemType::RightSidebarNoteSave,+ !matches!(save_state, SaveState::Saving(_)),+ )?;++ 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));+ let body_height = body_bottom.saturating_sub(body_y);+ if body_height == 0 || content_width == 0 {+ return Ok(());+ }+ self.ui_items.push(UIItem {+ x: content_x,+ y: body_y,+ width: content_width,+ height: body_height,+ item_type: UIItemType::RightSidebarNoteBody,+ });++ let settings = crate::native_settings::load();+ let normal_weight = crate::native_settings::settings_font_weight(&settings);+ let bold_font = self+ .fonts+ .title_font_with_size_and_weight(base_font_size, normal_weight.max(700))?;+ let italic_font = self+ .fonts+ .title_font_with_size_weight_and_italic(base_font_size, normal_weight)?;+ let bold_italic_font = self+ .fonts+ .title_font_with_size_weight_and_italic(base_font_size, normal_weight.max(700))?;+ let h1_font = self+ .fonts+ .title_font_with_size_and_weight(base_font_size + 7.0, normal_weight.max(760))?;+ let h2_font = self+ .fonts+ .title_font_with_size_and_weight(base_font_size + 4.0, normal_weight.max(730))?;+ let h3_font = self+ .fonts+ .title_font_with_size_and_weight(base_font_size + 2.0, normal_weight.max(700))?;+ let h1_italic_font = self+ .fonts+ .title_font_with_size_weight_and_italic(base_font_size + 7.0, normal_weight.max(760))?;+ let h2_italic_font = self+ .fonts+ .title_font_with_size_weight_and_italic(base_font_size + 4.0, normal_weight.max(730))?;+ let h3_italic_font = self+ .fonts+ .title_font_with_size_weight_and_italic(base_font_size + 2.0, normal_weight.max(700))?;+ let code_font = self+ .fonts+ .resolve_font(&self.config.font)+ .context("Note code font")?;+ let h1_metrics = RenderMetrics::with_font_metrics(&h1_font.metrics());+ let h2_metrics = RenderMetrics::with_font_metrics(&h2_font.metrics());+ let h3_metrics = RenderMetrics::with_font_metrics(&h3_font.metrics());+ let bold_metrics = RenderMetrics::with_font_metrics(&bold_font.metrics());+ let italic_metrics = RenderMetrics::with_font_metrics(&italic_font.metrics());+ let bold_italic_metrics = RenderMetrics::with_font_metrics(&bold_italic_font.metrics());+ let h1_italic_metrics = RenderMetrics::with_font_metrics(&h1_italic_font.metrics());+ let h2_italic_metrics = RenderMetrics::with_font_metrics(&h2_italic_font.metrics());+ let h3_italic_metrics = RenderMetrics::with_font_metrics(&h3_italic_font.metrics());+ let code_metrics = RenderMetrics::with_font_metrics(&code_font.metrics());+ let selection = self.right_sidebar_note.view.selection;+ let focused = self.right_sidebar_note.view.focused;+ self.right_sidebar_note.view.preedit = if focused {+ match &self.dead_key_status {+ DeadKeyStatus::Composing(text) => Some(text.clone()),+ DeadKeyStatus::None => None,+ }+ } else {+ None+ };+ let preedit = self.right_sidebar_note.view.preedit.clone();+ let padding = self.ui_px(NOTE_BODY_PADDING) as f32;+ let text_left = content_x as f32 + padding;+ let clip_left = text_left;+ let clip_right = (content_x + content_width) as f32 - padding;+ let wrap_width = (clip_right - clip_left).max(1.0);+ let mut wrap_hasher = DefaultHasher::new();+ (wrap_width.floor() as usize).hash(&mut wrap_hasher);+ self.dimensions.dpi.hash(&mut wrap_hasher);+ for font_id in [+ ui_font.id(),+ bold_font.id(),+ italic_font.id(),+ bold_italic_font.id(),+ h1_font.id(),+ h2_font.id(),+ h3_font.id(),+ h1_italic_font.id(),+ h2_italic_font.id(),+ h3_italic_font.id(),+ code_font.id(),+ ] {+ font_id.hash(&mut wrap_hasher);+ }+ let wrap_key = wrap_hasher.finish() as usize;+ let visual = if let Some(visual) = self.right_sidebar_note.cached_wrapped_visual(wrap_key) {+ visual+ } else {+ let wrapped = wrap_visual_document_by_width(+ &self.right_sidebar_note.visual,+ wrap_width,+ |block, run| {+ let (font, metrics) = match block {+ BlockKind::Heading(1) if run.style.emphasis => {+ (&h1_italic_font, h1_italic_metrics)+ }+ BlockKind::Heading(2) if run.style.emphasis => {+ (&h2_italic_font, h2_italic_metrics)+ }+ BlockKind::Heading(_) if run.style.emphasis => {+ (&h3_italic_font, h3_italic_metrics)+ }+ BlockKind::Heading(1) => (&h1_font, h1_metrics),+ BlockKind::Heading(2) => (&h2_font, h2_metrics),+ BlockKind::Heading(_) => (&h3_font, h3_metrics),+ BlockKind::CodeBlock => (&code_font, code_metrics),+ _ if run.style.strong && run.style.emphasis => {+ (&bold_italic_font, bold_italic_metrics)+ }+ _ if run.style.strong => (&bold_font, bold_metrics),+ _ if run.style.emphasis => (&italic_font, italic_metrics),+ _ => (ui_font, ui_metrics),+ };+ self.cached_ui_text_advance(font, &metrics, &run.text)+ },+ )?;+ self.right_sidebar_note+ .cache_wrapped_visual(wrap_key, wrapped)+ };+ let projected_objects = self.right_sidebar_note.projection.objects.clone();+ let table_horizontal_padding = self.ui_f32(NOTE_TABLE_CELL_HORIZONTAL_PADDING as f32);+ let table_vertical_padding = self.ui_f32(NOTE_TABLE_CELL_VERTICAL_PADDING as f32);+ let table_row_height = ui_metrics.cell_size.height as f32 + table_vertical_padding * 2.0;+ let mut table_rows = vec![None; visual.lines.len()];+ for object in &projected_objects {+ let ProjectedObject::Table(table) = object else {+ continue;+ };+ let row_indices = visual+ .lines+ .iter()+ .enumerate()+ .filter_map(|(index, line)| {+ (line.block == BlockKind::Table+ && line.runs.iter().any(|run| {+ table.source.start <= run.source.start+ && run.source.end <= table.source.end+ }))+ .then_some(index)+ })+ .collect::<Vec<_>>();+ let column_count = table.rows.iter().map(Vec::len).max().unwrap_or(0);+ if row_indices.is_empty() || column_count == 0 {+ continue;+ }+ let mut desired_widths = vec![0.0f32; column_count];+ for (row_index, row) in table.rows.iter().enumerate() {+ let (font, metrics) = if row_index == 0 {+ (&bold_font, bold_metrics)+ } else {+ (ui_font, ui_metrics)+ };+ for (column_index, cell) in row.iter().enumerate() {+ let width = self.cached_ui_text_advance(font, &metrics, &cell.text)?+ + table_horizontal_padding * 2.0;+ desired_widths[column_index] = desired_widths[column_index].max(width);+ }+ }+ let column_widths = Rc::new(fit_table_columns(+ &desired_widths,+ wrap_width,+ self.ui_f32(NOTE_TABLE_MIN_COLUMN_WIDTH as f32),+ ));+ let mut alignments = table.alignments.clone();+ alignments.resize(column_count, TableAlignment::None);+ let alignments = Rc::new(alignments);+ let row_count = row_indices.len();+ for (row_index, visual_index) in row_indices.into_iter().enumerate() {+ table_rows[visual_index] = Some(NoteTableRowPaintLayout {+ column_widths: Rc::clone(&column_widths),+ alignments: Rc::clone(&alignments),+ row_index,+ row_count,+ });+ }+ }+ let use_dark_syntax_theme = matches!(+ crate::native_settings::effective_appearance(),+ window::Appearance::Dark | window::Appearance::DarkHighContrast+ );+ let code_horizontal_padding = self.ui_f32(NOTE_CODE_HORIZONTAL_PADDING as f32);+ let code_vertical_padding = self.ui_f32(NOTE_CODE_VERTICAL_PADDING as f32);+ let code_header_height = self.ui_f32(NOTE_CODE_HEADER_HEIGHT as f32);+ let code_line_height = code_metrics.cell_size.height as f32;+ let code_inner_width = (wrap_width - code_horizontal_padding * 2.0).max(1.0);+ let mut code_rows = vec![None; visual.lines.len()];+ for object in &projected_objects {+ let ProjectedObject::CodeBlock(code) = object else {+ continue;+ };+ let row_indices = visual+ .lines+ .iter()+ .enumerate()+ .filter_map(|(index, line)| {+ (line.block == BlockKind::CodeBlock+ && code.content.start <= line.source.start+ && line.source.end <= code.content.end)+ .then_some(index)+ })+ .collect::<Vec<_>>();+ if row_indices.is_empty() {+ continue;+ }+ let highlights = self.cached_note_code_highlights(code, use_dark_syntax_theme);+ let collapsed = self+ .right_sidebar_note+ .collapsed_code_blocks+ .contains(&code.source.start);+ let max_content_width = code+ .text+ .split_inclusive('\n')+ .map(|raw_line| raw_line.strip_suffix('\n').unwrap_or(raw_line))+ .map(|line| self.cached_ui_text_advance(&code_font, &code_metrics, line))+ .collect::<anyhow::Result<Vec<_>>>()?+ .into_iter()+ .fold(0.0f32, f32::max);+ let max_horizontal_scroll = (max_content_width - code_inner_width).max(0.0);+ let horizontal_offset = self+ .right_sidebar_note+ .code_horizontal_offsets+ .entry(code.source.start)+ .or_default();+ *horizontal_offset = horizontal_offset.clamp(0.0, max_horizontal_scroll);+ let horizontal_offset = *horizontal_offset;+ let row_count = row_indices.len();+ let block_height = code_header_height+ + if collapsed {+ 0.0+ } else {+ code_vertical_padding * 2.0 + code_line_height * row_count as f32+ };+ let language = code+ .language+ .as_deref()+ .unwrap_or("code")+ .to_ascii_uppercase();+ for (row_index, visual_index) in row_indices.into_iter().enumerate() {+ code_rows[visual_index] = Some(NoteCodeRowPaintLayout {+ block_start: code.source.start,+ language: language.clone(),+ row_index,+ row_count,+ collapsed,+ colors: Arc::clone(&highlights),+ horizontal_offset,+ block_height,+ max_horizontal_scroll,+ });+ }+ }+ let notebook = default_notebook().ok();+ let viewport_top = body_y as f32;+ let viewport_bottom = body_bottom as f32;+ let image_line_height = self.ui_f32(180.0);+ let line_gap = self.ui_px(NOTE_LINE_GAP) as f32;+ let mut measured_y = padding;+ let mut caret_row = None;+ for (line_index, line) in visual.lines.iter().enumerate() {+ let metrics = match line.block {+ BlockKind::Heading(1) => h1_metrics,+ BlockKind::Heading(2) => h2_metrics,+ BlockKind::Heading(_) => h3_metrics,+ BlockKind::CodeBlock => code_metrics,+ _ => ui_metrics,+ };+ let mut height = metrics.cell_size.height as f32;+ if line.kind == VisualLineKind::Image {+ height = height.max(image_line_height);+ }+ if table_rows[line_index].is_some() {+ height = table_row_height;+ }+ if let Some(code_row) = code_rows[line_index].as_ref() {+ height = note_code_row_height(+ code_row.row_index,+ code_row.row_count,+ code_row.collapsed,+ code_line_height,+ code_header_height,+ code_vertical_padding,+ );+ }+ if selection.is_caret()+ && (line.runs.iter().any(|run| {+ run.source.start <= selection.focus.byte+ && selection.focus.byte <= run.source.end+ }) || (line.runs.is_empty() && line.source.start == selection.focus.byte)+ || selection.focus.byte == line.source.end)+ {+ caret_row = Some((measured_y, height));+ }+ let row_gap = if let Some(code_row) = code_rows[line_index].as_ref() {+ if code_row.row_index + 1 < code_row.row_count {+ 0.0+ } else {+ line_gap+ }+ } else {+ table_rows[line_index]+ .as_ref()+ .filter(|row| row.row_index + 1 < row.row_count)+ .map(|_| 0.0)+ .unwrap_or(line_gap)+ };+ measured_y += height + row_gap;+ }+ let measured_content_height = measured_y + padding;+ let max_scroll = (measured_content_height - body_height as f32).max(0.0);+ let mut scroll = self+ .right_sidebar_note+ .view+ .scroll_offset+ .clamp(0.0, max_scroll);+ if focused && self.right_sidebar_note.reveal_caret {+ if let Some((caret_top, caret_height)) = caret_row {+ let safe_top = scroll + padding;+ let safe_bottom = scroll + body_height as f32 - padding;+ if caret_top < safe_top {+ scroll = (caret_top - padding).max(0.0);+ } else if caret_top + caret_height > safe_bottom {+ scroll =+ (caret_top + caret_height + padding - body_height as f32).min(max_scroll);+ }+ }+ self.right_sidebar_note.reveal_caret = false;+ }+ self.right_sidebar_note.view.scroll_offset = scroll;+ let mut logical_y = padding;+ let mut layouts = Vec::new();+ let mut code_block_layouts = Vec::new();+ let mut caret_rect: Option<(f32, f32, f32)> = None;+ let selected = selection.range();++ for (line_index, line) in visual.lines.iter().enumerate() {+ let table_row = table_rows[line_index].as_ref();+ let code_row = code_rows[line_index].as_ref();+ let (line_font, line_metrics) = match line.block {+ BlockKind::Heading(1) => (&h1_font, h1_metrics),+ BlockKind::Heading(2) => (&h2_font, h2_metrics),+ BlockKind::Heading(_) => (&h3_font, h3_metrics),+ BlockKind::CodeBlock => (&code_font, code_metrics),+ _ => (ui_font, ui_metrics),+ };+ let mut line_height = line_metrics.cell_size.height as f32;+ if line.kind == VisualLineKind::Image {+ line_height = line_height.max(image_line_height);+ }+ if table_row.is_some() {+ line_height = table_row_height;+ }+ if let Some(code_row) = code_row {+ line_height = note_code_row_height(+ code_row.row_index,+ code_row.row_count,+ code_row.collapsed,+ code_line_height,+ code_header_height,+ code_vertical_padding,+ );+ }+ let line_y = body_y as f32 + logical_y - scroll;+ let line_bottom = line_y + line_height;+ let visible = line_bottom >= viewport_top && line_y <= viewport_bottom;+ let row_gap = if let Some(code_row) = code_row {+ if code_row.row_index + 1 < code_row.row_count {+ 0.0+ } else {+ line_gap+ }+ } else {+ table_row+ .filter(|row| row.row_index + 1 < row.row_count)+ .map(|_| 0.0)+ .unwrap_or(line_gap)+ };+ let code_text_y = code_row.map(|row| {+ if row.row_index == 0 {+ line_y + code_header_height + code_vertical_padding+ } else {+ line_y+ }+ });+ let mut x = if let Some(code_row) = code_row {+ text_left + code_horizontal_padding - code_row.horizontal_offset+ } else {+ text_left+ };+ let mut run_layouts = Vec::new();++ if let Some(code_row) = code_row.filter(|row| row.row_index == 0) {+ let block_bottom = line_y + code_row.block_height;+ let draw_top = line_y.max(viewport_top);+ let draw_bottom = block_bottom.min(viewport_bottom);+ if draw_bottom > draw_top {+ let block_rect =+ euclid::rect(text_left, draw_top, wrap_width, draw_bottom - draw_top);+ if line_y >= viewport_top && block_bottom <= viewport_bottom {+ self.fill_rounded_rectangle(+ layers,+ 1,+ block_rect,+ chrome.sidebar_button_bg,+ self.ui_f32(NOTE_CODE_BLOCK_RADIUS),+ )?;+ } else {+ self.filled_rectangle(layers, 1, block_rect, chrome.sidebar_button_bg)?;+ }+ }+ let content_y = line_y + code_header_height;+ let content_height = (code_row.block_height - code_header_height).max(0.0);+ code_block_layouts.push(NoteCodeBlockLayout {+ source_start: code_row.block_start,+ x: text_left,+ y: content_y,+ width: wrap_width,+ height: content_height,+ max_horizontal_scroll: code_row.max_horizontal_scroll,+ });+ if line_y >= viewport_top+ && line_y + code_header_height <= viewport_bottom+ && code_header_height >= 1.0+ {+ let header_y = line_y.max(0.0) as usize;+ let header_height = code_header_height as usize;+ self.ui_items.push(UIItem {+ x: text_left as usize,+ y: header_y,+ width: wrap_width as usize,+ height: header_height,+ item_type: UIItemType::RightSidebarNoteCodeToggle(code_row.block_start),+ });+ let control_size = self.ui_px(NOTE_CODE_CONTROL_SIZE);+ let control_y = header_y + header_height.saturating_sub(control_size) / 2;+ let leading_x = text_left as usize + self.ui_px(4);+ self.paint_snippet_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ leading_x,+ control_y,+ control_size,+ if code_row.collapsed {+ SvgIcon::ChevronRight+ } else {+ SvgIcon::ChevronDown+ },+ UIItemType::RightSidebarNoteCodeToggle(code_row.block_start),+ )?;+ let copy_x = clip_right.max(text_left) as usize - control_size - self.ui_px(4);+ self.paint_snippet_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ copy_x,+ control_y,+ control_size,+ SvgIcon::Copy,+ UIItemType::RightSidebarNoteCodeCopy(code_row.block_start),+ )?;+ let language_x = leading_x + control_size + self.ui_px(4);+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &code_row.language,+ language_x,+ header_y+ + header_height.saturating_sub(ui_metrics.cell_size.height as usize)+ / 2,+ copy_x.saturating_sub(language_x + self.ui_px(4)),+ muted_fg,+ )?;+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ text_left,+ line_y + code_header_height - 1.0,+ wrap_width,+ 1.0,+ ),+ chrome.separator.mul_alpha(0.72),+ )?;+ }+ }++ if line_height <= 0.0 {+ logical_y += row_gap;+ continue;+ }++ let note_image_path = if visible && line.kind == VisualLineKind::Image {+ projected_objects.iter().find_map(|object| match object {+ ProjectedObject::Image { source, target, .. } if *source == line.source => {+ notebook.as_ref().and_then(|notebook| {+ resolve_local_image(+ ¬ebook.content_root,+ ¬ebook.document_path,+ target,+ )+ .ok()+ })+ }+ _ => None,+ })+ } else {+ None+ };+ let note_image = note_image_path+ .as_ref()+ .and_then(|path| self.right_sidebar_note_images.get(path))+ .cloned();+ if note_image.is_none() {+ if let Some(path) = note_image_path.clone() {+ self.schedule_right_sidebar_note_image(path);+ }+ }++ if visible {+ if let Some(table_row) = table_row {+ if table_row.row_index == 0 {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(text_left, line_y, wrap_width, line_height),+ chrome.sidebar_row_active_bg,+ )?;+ }+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(text_left, line_y, wrap_width, 1.0),+ chrome.separator,+ )?;+ if table_row.row_index + 1 == table_row.row_count {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(text_left, line_y + line_height - 1.0, wrap_width, 1.0),+ chrome.separator,+ )?;+ }+ let mut boundary_x = text_left;+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(boundary_x, line_y, 1.0, line_height),+ chrome.separator,+ )?;+ for column_width in table_row.column_widths.iter() {+ boundary_x += *column_width;+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(boundary_x - 1.0, line_y, 1.0, line_height),+ chrome.separator,+ )?;+ }+ }+ match line.kind {+ VisualLineKind::Rule => {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ text_left,+ line_y + line_height / 2.0,+ (clip_right - text_left).max(0.0),+ 1.0,+ ),+ chrome.separator,+ )?;+ }+ VisualLineKind::TableHeader => {}+ VisualLineKind::Image => {+ if let Some(image) = note_image.as_ref() {+ self.paint_right_sidebar_note_image(+ layers,+ image,+ text_left,+ line_y,+ (clip_right - text_left).max(0.0),+ line_height,+ )?;+ }+ }+ _ => {}+ }+ if line.block == BlockKind::Quote {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ text_left - self.ui_f32(8.0),+ line_y,+ self.ui_f32(3.0),+ line_height,+ ),+ muted_fg,+ )?;+ }+ }++ if !visible {+ logical_y += line_height + row_gap;+ continue;+ }++ for (run_index, run) in line.runs.iter().enumerate() {+ let (font, metrics) = match line.block {+ BlockKind::Heading(1) if run.style.emphasis => {+ (&h1_italic_font, h1_italic_metrics)+ }+ BlockKind::Heading(2) if run.style.emphasis => {+ (&h2_italic_font, h2_italic_metrics)+ }+ BlockKind::Heading(_) if run.style.emphasis => {+ (&h3_italic_font, h3_italic_metrics)+ }+ BlockKind::Heading(_) => (line_font, line_metrics),+ _ if run.style.strong && run.style.emphasis => {+ (&bold_italic_font, bold_italic_metrics)+ }+ _ if run.style.strong => (&bold_font, bold_metrics),+ _ if run.style.emphasis => (&italic_font, italic_metrics),+ _ => (line_font, line_metrics),+ };+ let (shaped, _) = self.cached_ui_shape(font, &metrics, &run.text)?;+ let advance = shaped+ .iter()+ .map(|info| info.glyph.x_advance.get() as f32)+ .sum::<f32>();+ let (run_x, run_y, run_clip_left, run_clip_right, hit_x, hit_width) =+ if let Some(table_row) = table_row {+ let cell_width = table_row+ .column_widths+ .get(run_index)+ .copied()+ .unwrap_or(0.0);+ let cell_left = x;+ let cell_right = (cell_left + cell_width).min(clip_right);+ let cell_clip_left = (cell_left + table_horizontal_padding).min(cell_right);+ let cell_clip_right = (cell_right - table_horizontal_padding)+ .max(cell_clip_left)+ .min(clip_right);+ let available = (cell_clip_right - cell_clip_left).max(0.0);+ let alignment = table_row+ .alignments+ .get(run_index)+ .copied()+ .unwrap_or(TableAlignment::None);+ let aligned_x = match alignment {+ TableAlignment::Center if advance < available => {+ cell_clip_left + (available - advance) / 2.0+ }+ TableAlignment::Right if advance < available => {+ cell_clip_right - advance+ }+ TableAlignment::None+ | TableAlignment::Left+ | TableAlignment::Center+ | TableAlignment::Right => cell_clip_left,+ };+ (+ aligned_x,+ line_y + table_vertical_padding,+ cell_clip_left,+ cell_clip_right,+ cell_left,+ cell_width,+ )+ } else if code_row.is_some() {+ let content_left = text_left + code_horizontal_padding;+ let content_right =+ (clip_right - code_horizontal_padding).max(content_left);+ (+ x,+ code_text_y.unwrap_or(line_y),+ content_left,+ content_right,+ content_left,+ (content_right - content_left).max(0.0),+ )+ } else {+ (x, line_y, clip_left, clip_right, x, advance)+ };+ let run_height = metrics.cell_size.height as f32;+ let mut boundaries = Vec::with_capacity(shaped.len() + 2);+ if run.atomic {+ boundaries.push((run_x, run.source.start));+ } else {+ let mut boundary_advance = 0.0f32;+ for info in shaped.iter() {+ boundaries.push((+ run_x + boundary_advance,+ (run.source.start + info.cluster).min(run.source.end),+ ));+ boundary_advance += info.glyph.x_advance.get() as f32;+ }+ }+ boundaries.push((run_x + advance, run.source.end));++ if selected.start < selected.end {+ let start = selected.start.max(run.source.start);+ let end = selected.end.min(run.source.end);+ if start < end+ || (run.atomic+ && selected.start <= run.source.start+ && selected.end >= run.source.end)+ {+ let left = note_boundary_x(&boundaries, start).max(run_clip_left);+ let right = note_boundary_x(&boundaries, end).min(run_clip_right);+ if right > left {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(left, run_y, right - left, run_height),+ chrome.selected_bg.mul_alpha(0.72),+ )?;+ }+ }+ }+ if run.style.code && line.block != BlockKind::CodeBlock && advance > 0.0 {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ run_x,+ run_y,+ advance.min((run_clip_right - run_x).max(0.0)),+ run_height,+ ),+ chrome.sidebar_button_bg,+ )?;+ }+ if !(line.kind == VisualLineKind::Image && note_image.is_some()) {+ let color = if run.style.link {+ chrome.secondary_text+ } else {+ foreground+ };+ let code_colors = code_row.and_then(|row| row.colors.get(row.row_index));+ self.paint_cached_ui_shape_clipped(+ layers,+ &metrics,+ &shaped,+ run_x,+ run_y,+ run_clip_left,+ run_clip_right,+ |info| {+ code_colors+ .and_then(|colors| colors.get(info.cluster))+ .copied()+ .unwrap_or(color)+ },+ )?;+ if run.style.strikethrough && advance > 0.0 {+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ run_x.max(run_clip_left),+ run_y + run_height * 0.52,+ advance.min((run_clip_right - run_x).max(0.0)),+ 1.0,+ ),+ color,+ )?;+ }+ }+ if focused+ && selection.is_caret()+ && selection.focus.byte >= run.source.start+ && selection.focus.byte <= run.source.end+ {+ caret_rect = Some((+ note_boundary_x(&boundaries, selection.focus.byte),+ run_y,+ run_height,+ ));+ }+ run_layouts.push(NoteRunLayout {+ source: run.source.clone(),+ x: run_x,+ width: advance,+ hit_x,+ hit_width,+ boundaries,+ atomic: run.atomic,+ });+ x = if let Some(table_row) = table_row {+ x + table_row+ .column_widths+ .get(run_index)+ .copied()+ .unwrap_or(0.0)+ } else {+ run_x + advance+ };+ if table_row.is_none() && x >= clip_right {+ break;+ }+ }+ if focused+ && selection.is_caret()+ && line.runs.is_empty()+ && line.source.start == selection.focus.byte+ {+ caret_rect = Some((+ if code_row.is_some() {+ text_left + code_horizontal_padding+ } else {+ text_left+ },+ code_text_y.unwrap_or(line_y),+ if code_row.is_some() {+ code_line_height+ } else {+ line_height+ },+ ));+ } else if focused+ && selection.is_caret()+ && selection.focus.byte == line.source.end+ && caret_rect.is_none()+ {+ caret_rect = Some((x, line_y, line_height));+ }+ layouts.push(NoteLineLayout {+ source: line.source.clone(),+ y: code_text_y.unwrap_or(line_y),+ height: if code_row.is_some() {+ code_line_height+ } else {+ line_height+ },+ runs: run_layouts,+ });+ logical_y += line_height + row_gap;+ }++ self.right_sidebar_note.line_layouts = layouts;+ self.right_sidebar_note.code_block_layouts = code_block_layouts;+ self.right_sidebar_note.viewport_height = body_height as f32;+ self.right_sidebar_note.content_height = measured_content_height;+ self.right_sidebar_note.clamp_scroll();++ if let Some((caret_x, caret_y, caret_height)) = caret_rect {+ if caret_y + caret_height >= viewport_top && caret_y <= viewport_bottom {+ if self.right_sidebar_snippet_cursor_on() {+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ caret_x.clamp(clip_left, clip_right),+ caret_y,+ NOTE_CARET_WIDTH.max(1.0),+ caret_height,+ ),+ foreground,+ )?;+ }+ if let Some(composing) = preedit.as_ref() {+ self.paint_ui_title_text_cached(+ layers,+ ui_font,+ &ui_metrics,+ composing,+ caret_x.max(clip_left) as usize,+ caret_y.max(viewport_top) as usize,+ (clip_right - caret_x).max(0.0) as usize,+ foreground,+ )?;+ let preedit_width = self+ .cached_ui_text_advance(ui_font, &ui_metrics, composing)?+ .min((clip_right - caret_x).max(0.0));+ if preedit_width > 0.0 {+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ caret_x.max(clip_left),+ caret_y + caret_height - 1.0,+ preedit_width,+ 1.0,+ ),+ foreground,+ )?;+ }+ }+ if let Some(window) = self.window.as_ref() {+ window.set_text_cursor_position(Rect::new(+ Point::new(caret_x as isize, caret_y as isize),+ ui_metrics.cell_size,+ ));+ }+ }}- let content_top = mode_y + mode_height + self.ui_px(RIGHT_SIDEBAR_SECTION_GAP);- match self.right_sidebar_mode {- RightSidebarMode::Chat => {- let file_font_size = self.right_sidebar_file_preview_font_size();- let file_font = self- .fonts- .title_font_with_size(file_font_size)- .context("right sidebar file font")?;- let file_metrics = RenderMetrics::with_font_metrics(&file_font.metrics());- let file_icon_size = (file_metrics.cell_size.height as usize + self.ui_px(6))- .clamp(self.ui_px(22), self.ui_px(28));- self.paint_files_sidebar(- layers,- &file_font,- file_metrics,- chrome,- foreground,- muted_fg,- content_x,- content_top,- content_width,- rect.y.saturating_add(rect.height),- file_icon_size,- )?;- return Ok(());- }- RightSidebarMode::Snippets => {- self.paint_snippets_sidebar(- layers,- &ui_font,- ui_metrics,- chrome,- foreground,- muted_fg,- content_x,- content_top,- content_width,- rect.y.saturating_add(rect.height),- icon_size,- )?;- return Ok(());- }- RightSidebarMode::Tasks => {}+ if self.right_sidebar_note.content_height > self.right_sidebar_note.viewport_height {+ let track_height = body_height as f32;+ let thumb_height = (track_height * self.right_sidebar_note.viewport_height+ / self.right_sidebar_note.content_height)+ .max(self.ui_f32(24.0));+ let max_scroll = (self.right_sidebar_note.content_height+ - self.right_sidebar_note.viewport_height)+ .max(1.0);+ let thumb_y = body_y as f32+ + (track_height - thumb_height)+ * (self.right_sidebar_note.view.scroll_offset / max_scroll);+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ (content_x + content_width).saturating_sub(self.ui_px(4)) as f32,+ thumb_y,+ self.ui_f32(3.0),+ thumb_height,+ ),+ chrome.scrollbar_thumb,+ )?;+ }+ Ok(())+ }++ fn schedule_right_sidebar_note_image(&mut self, path: PathBuf) {+ if self.right_sidebar_note_images.contains_key(&path)+ || !self.right_sidebar_note_images_loading.insert(path.clone())+ {+ return;}+ let Some(window) = self.window.as_ref().cloned() else {+ self.right_sidebar_note_images_loading.remove(&path);+ return;+ };+ promise::spawn::spawn(async move {+ let load_path = path.clone();+ let result =+ promise::spawn::spawn_into_new_thread(move || load_file_preview_image(&load_path))+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.right_sidebar_note_images_loading.remove(&path);+ match result {+ Ok(image) => {+ term_window+ .right_sidebar_note_image_order+ .retain(|cached| cached != &path);+ term_window+ .right_sidebar_note_image_order+ .push_back(path.clone());+ term_window.right_sidebar_note_images.insert(path, image);+ while term_window.right_sidebar_note_image_order.len()+ > NOTE_IMAGE_CACHE_CAPACITY+ {+ if let Some(expired) =+ term_window.right_sidebar_note_image_order.pop_front()+ {+ term_window.right_sidebar_note_images.remove(&expired);+ }+ }+ }+ Err(err) => {+ log::warn!("unable to render Note image {}: {err:#}", path.display());+ }+ }+ term_window.invalidate_window();+ })));+ })+ .detach();+ }- let empty_top = content_top;- let empty_height = self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT).min(- rect.y- .saturating_add(rect.height)- .saturating_sub(empty_top + self.ui_px(SIDEBAR_INSET)),- );- if empty_height == 0 {+ #[allow(clippy::too_many_arguments)]+ fn paint_right_sidebar_note_image(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ image: &RightSidebarFilePreviewImage,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ ) -> anyhow::Result<()> {+ if image.width == 0 || image.height == 0 || width <= 0.0 || height <= 0.0 {return Ok(());}- self.fill_rounded_rectangle_with_border(- layers,- 1,- euclid::rect(- content_x as f32,- empty_top as f32,- content_width as f32,- empty_height as f32,- ),- chrome.sidebar_button_bg,- chrome.control_border,- self.ui_f32(SIDEBAR_ROW_RADIUS) + 6.0,- CAPSULE_BORDER_WIDTH,- )- .context("right sidebar empty state")?;- let empty_icon_size = icon_size- .min(self.ui_px(22))- .min(empty_height.saturating_sub(20))- .max(1);- let empty_icon_x = content_x + self.ui_px(SIDEBAR_INSET) + 2;- let empty_icon_y = empty_top + (empty_height.saturating_sub(empty_icon_size)) / 2;- self.paint_sidebar_icon(- layers,- self.right_sidebar_mode.icon(),- empty_icon_x,- empty_icon_y,- empty_icon_size,- muted_fg,- )?;- self.paint_sidebar_text(- layers,- &ui_font,- ui_metrics,- self.right_sidebar_mode.empty_label(),- empty_icon_x + empty_icon_size + self.ui_px(SIDEBAR_ICON_GAP) + 2,- empty_top + (empty_height.saturating_sub(ui_cell_height)) / 2,- content_width.saturating_sub(- empty_icon_size + self.ui_px(SIDEBAR_ICON_GAP) + self.ui_px(SIDEBAR_INSET) * 3,- ),- muted_fg,- )?;-+ let scale = (width / image.width as f32)+ .min(height / image.height as f32)+ .min(1.0);+ let draw_width = (image.width as f32 * scale).max(1.0);+ let draw_height = (image.height as f32 * scale).max(1.0);+ let draw_x = x + (width - draw_width) / 2.0;+ let draw_y = y + (height - draw_height) / 2.0;+ let Some(gl_state) = self.render_state.as_ref() else {+ return Ok(());+ };+ let (sprite, next_due, _load_state) = gl_state+ .glyph_cache+ .borrow_mut()+ .cached_image(&image.data, None, self.allow_images)+ .context("right sidebar Note image")?;+ self.update_next_frame_time(next_due);+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;+ let mut quad = layers.allocate(2)?;+ quad.set_position(+ draw_x - left_offset,+ draw_y - top_offset,+ draw_x + draw_width - left_offset,+ draw_y + draw_height - top_offset,+ );+ quad.set_texture(sprite.texture_coords());+ quad.set_hsv(None);+ quad.set_has_color(true);+ quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));Ok(())}@@ -5852,18 +7541,20 @@ impl crate::TermWindow {.clamp(self.ui_px(18), self.ui_px(22))}).unwrap_or(0);- let horizontal_pad = self.ui_px(SIDEBAR_INSET) * 2;- let available_label_width = width.saturating_sub(horizontal_pad * 2 + icon_size);- let text_width =- (self.sidebar_text_width(ui_font, label)?.ceil() as usize).min(available_label_width);- let icon_label_gap = if icon.is_some() && text_width > 0 {+ let measured_text_width = self.sidebar_text_width(ui_font, label)?.ceil() as usize;+ let icon_label_gap = if icon.is_some() && measured_text_width > 0 {self.ui_px(SIDEBAR_ICON_GAP)} else {0};+ let intrinsic_width = icon_size + icon_label_gap + measured_text_width;+ let horizontal_pad =+ (self.ui_px(SIDEBAR_INSET) * 2).min(width.saturating_sub(intrinsic_width) / 2);+ let available_label_width =+ width.saturating_sub(horizontal_pad * 2 + icon_size + icon_label_gap);+ let text_width = measured_text_width.min(available_label_width);let total_width = icon_size + icon_label_gap + text_width;- let start_x =- x + horizontal_pad + width.saturating_sub(horizontal_pad * 2 + total_width) / 2;+ let start_x = x + width.saturating_sub(total_width) / 2;let color = if enabled { foreground } else { muted_fg };let mut text_x = start_x;if let Some(icon) = icon {@@ -5884,7 +7575,7 @@ impl crate::TermWindow {label,text_x,y + (height.saturating_sub(ui_metrics.cell_size.height as usize)) / 2,- width.saturating_sub(text_x.saturating_sub(x) + self.ui_px(SIDEBAR_INSET)),+ text_width,color,)}@@ -5943,86 +7634,177 @@ fn file_name_for_path(path: &Path) -> String {.unwrap_or_else(|| path.to_string_lossy().to_string())}-lazy_static::lazy_static! {- static ref FILE_PREVIEW_SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_newlines();- static ref FILE_PREVIEW_THEME_SET: ThemeSet = ThemeSet::load_defaults();+#[cfg(test)]+fn preview_lines_from_text(+ path: &Path,+ text: &str,+ use_dark_theme: bool,+) -> Vec<RightSidebarFilePreviewLine> {+ preview_lines_from_text_with_cancellation(path, text, use_dark_theme, None)}-fn preview_lines_from_text(+fn preview_lines_from_text_with_cancellation(path: &Path,text: &str,use_dark_theme: bool,+ cancellation: Option<&std::sync::atomic::AtomicUsize>,) -> Vec<RightSidebarFilePreviewLine> {- let Some(syntax) = FILE_PREVIEW_SYNTAX_SET- .find_syntax_for_file(path)- .ok()- .flatten()- else {- return preview_plain_lines_from_text(text);+ if cancellation+ .map(|token| token.load(AtomicOrdering::Relaxed) != 0)+ .unwrap_or(false)+ {+ return Vec::new();+ }+ let mut highlight_end = text+ .len()+ .min(thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT);+ while !text.is_char_boundary(highlight_end) {+ highlight_end = highlight_end.saturating_sub(1);+ }+ let highlight_source = &text[..highlight_end];+ let highlighted = match syntax_highlight_pool()+ .install(|| thinkterm_syntax::highlight_path(path, highlight_source, cancellation))+ {+ Ok(Some(result)) => result,+ Ok(None) => {+ if cancellation+ .map(|token| token.load(AtomicOrdering::Relaxed) != 0)+ .unwrap_or(false)+ {+ return Vec::new();+ }+ return preview_plain_lines_from_text(text);+ }+ Err(err) => {+ let was_cancelled = cancellation+ .map(|token| token.load(AtomicOrdering::Relaxed) != 0)+ .unwrap_or(false);+ if !was_cancelled {+ log::warn!("failed to highlight file preview: {err:#}");+ } else {+ return Vec::new();+ }+ return preview_plain_lines_from_text(text);+ }+ };++ highlighted_preview_lines(text, &highlighted.spans, use_dark_theme)+}++fn syntax_highlight_pool() -> &'static rayon::ThreadPool {+ static POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();+ POOL.get_or_init(|| {+ rayon::ThreadPoolBuilder::new()+ .num_threads(2)+ .thread_name(|index| format!("thinkterm-syntax-{index}"))+ .build()+ .expect("build ThinkTerm syntax highlighting pool")+ })+}++fn note_code_line_count(text: &str) -> usize {+ if text.is_empty() {+ 1+ } else {+ text.split_inclusive('\n').count()+ }+}++fn note_code_syntax_result(+ code: &ProjectedCodeBlock,+ cancellation: Option<&AtomicUsize>,+) -> Option<HighlightResult> {+ let Some(language) = code.language.as_deref() else {+ return None;+ };+ let Some(language) = thinkterm_syntax::detect_fence(language) else {+ return None;};- let Some(theme) = preview_syntax_theme(use_dark_theme) else {- return preview_plain_lines_from_text(text);+ if code.text.len() > thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT {+ return None;+ }+ match thinkterm_syntax::highlight(language, &code.text, cancellation) {+ Ok(result) => Some(result),+ Err(err) => {+ let was_cancelled = cancellation+ .map(|token| token.load(AtomicOrdering::Relaxed) != 0)+ .unwrap_or(false);+ if !was_cancelled {+ log::warn!("failed to highlight Note code block: {err:#}");+ }+ None+ }+ }+}++#[cfg(test)]+fn note_code_highlight_lines(+ code: &ProjectedCodeBlock,+ use_dark_theme: bool,+) -> Vec<Vec<LinearRgba>> {+ let Some(syntax_result) = note_code_syntax_result(code, None) else {+ return vec![vec![]; note_code_line_count(&code.text)];};+ note_code_colors(code, &syntax_result, use_dark_theme)+}- let default_color = theme- .settings- .foreground- .map(syntect_color_to_linear)- .unwrap_or_else(|| LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));+fn note_code_highlight_pair(+ code: &ProjectedCodeBlock,+ cancellation: Option<&AtomicUsize>,+) -> Option<(Vec<Vec<LinearRgba>>, Vec<Vec<LinearRgba>>)> {+ let syntax_result = note_code_syntax_result(code, cancellation)?;+ Some((+ note_code_colors(code, &syntax_result, false),+ note_code_colors(code, &syntax_result, true),+ ))+}- let mut highlighter = HighlightLines::new(syntax, theme);- let raw_lines: Vec<&str> = if text.is_empty() {+fn note_code_colors(+ code: &ProjectedCodeBlock,+ syntax_result: &HighlightResult,+ use_dark_theme: bool,+) -> Vec<Vec<LinearRgba>> {+ let raw_lines = if code.text.is_empty() {vec![""]} else {- text.lines().collect()+ code.text.split_inclusive('\n').collect::<Vec<_>>()};++ let default_color = syntax_default_color(use_dark_theme);let mut lines = Vec::with_capacity(raw_lines.len());- for line in raw_lines {- // Highlight only the head of very long lines to bound syntect cost, but- // keep the tail verbatim (rendered in the default colour) so no content- // is lost.- let (head, tail) = match line- .char_indices()- .nth(FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT)- .map(|(idx, _)| idx)+ let mut source_offset = 0usize;+ let mut span_index = 0usize;+ for raw_line in raw_lines {+ let line = raw_line.strip_suffix('\n').unwrap_or(raw_line);+ let line_end = source_offset.saturating_add(line.len());+ let mut colors = vec![default_color; line.len()];+ while span_index < syntax_result.spans.len()+ && syntax_result.spans[span_index].range.end <= source_offset{- Some(split) => (&line[..split], &line[split..]),- None => (line, ""),- };- let ranges = match highlighter.highlight_line(head, &FILE_PREVIEW_SYNTAX_SET) {- Ok(ranges) => ranges,- Err(err) => {- log::warn!("failed to highlight file preview line: {err:#}");- return preview_plain_lines_from_text(text);+ span_index += 1;+ }+ let mut index = span_index;+ while let Some(span) = syntax_result.spans.get(index) {+ if span.range.start >= line_end {+ break;}- };- lines.push(preview_line_from_highlighted_ranges(- ranges,- tail,- default_color,- ));+ let start = span+ .range+ .start+ .max(source_offset)+ .saturating_sub(source_offset);+ let end = span.range.end.min(line_end).saturating_sub(source_offset);+ if start < end && end <= colors.len() {+ colors[start..end].fill(syntax_color(span.kind, use_dark_theme));+ }+ index += 1;+ }+ lines.push(colors);+ source_offset = source_offset.saturating_add(raw_line.len());}lines}-fn preview_syntax_theme(use_dark_theme: bool) -> Option<&'static Theme> {- let dark_theme_names = [- "base16-eighties.dark",- "Solarized (dark)",- "base16-ocean.dark",- ];- let light_theme_names = ["base16-ocean.light", "Solarized (light)", "InspiredGitHub"];- let names = if use_dark_theme {- &dark_theme_names[..]- } else {- &light_theme_names[..]- };- names- .iter()- .find_map(|name| FILE_PREVIEW_THEME_SET.themes.get(*name))- .or_else(|| FILE_PREVIEW_THEME_SET.themes.values().next())-}-fn preview_plain_lines_from_text(text: &str) -> Vec<RightSidebarFilePreviewLine> {if text.is_empty() {vec![preview_line_from_plain("")]@@ -6039,52 +7821,132 @@ fn preview_line_from_plain(line: &str) -> RightSidebarFilePreviewLine {}}-fn preview_line_from_highlighted_ranges(- ranges: Vec<(SyntectStyle, &str)>,- tail: &str,- default_color: LinearRgba,-) -> RightSidebarFilePreviewLine {- let mut plain = String::new();- let mut char_count = 0usize;- let mut spans = Vec::new();-- for (style, text) in ranges {- if text.is_empty() {- continue;+fn highlighted_preview_lines(+ text: &str,+ highlights: &[HighlightSpan],+ use_dark_theme: bool,+) -> Vec<RightSidebarFilePreviewLine> {+ if text.is_empty() {+ return vec![preview_line_from_plain("")];+ }++ let default_color = syntax_default_color(use_dark_theme);+ let mut lines = Vec::new();+ let mut source_offset = 0usize;+ let mut span_index = 0usize;+ for raw_line in text.split_inclusive('\n') {+ let without_newline = raw_line.strip_suffix('\n').unwrap_or(raw_line);+ let line = without_newline+ .strip_suffix('\r')+ .unwrap_or(without_newline);+ let line_end = source_offset.saturating_add(line.len());+ while span_index < highlights.len() && highlights[span_index].range.end <= source_offset {+ span_index += 1;+ }++ let mut cursor = source_offset;+ let mut spans = Vec::new();+ let mut index = span_index;+ while let Some(span) = highlights.get(index) {+ if span.range.start >= line_end {+ break;+ }+ let start = span+ .range+ .start+ .max(cursor)+ .max(source_offset)+ .min(line_end);+ let end = span.range.end.min(line_end);+ if cursor < start {+ push_preview_span(&mut spans, &text[cursor..start], default_color);+ }+ if start < end {+ push_preview_span(+ &mut spans,+ &text[start..end],+ syntax_color(span.kind, use_dark_theme),+ );+ cursor = end;+ }+ index += 1;+ }+ if cursor < line_end {+ push_preview_span(&mut spans, &text[cursor..line_end], default_color);}- let color = syntect_color_to_linear(style.foreground);- let span_char_count = text.chars().count();- plain.push_str(text);- char_count = char_count.saturating_add(span_char_count);- spans.push(RightSidebarFilePreviewSpan {- text: text.to_string(),- char_count: span_char_count,- color,- });- }- // The un-highlighted remainder of a very long line is kept verbatim so no- // content is dropped; it just renders in the editor's default colour.- if !tail.is_empty() {- let span_char_count = tail.chars().count();- plain.push_str(tail);- char_count = char_count.saturating_add(span_char_count);- spans.push(RightSidebarFilePreviewSpan {- text: tail.to_string(),- char_count: span_char_count,- color: default_color,+ lines.push(RightSidebarFilePreviewLine {+ plain: line.to_string(),+ char_count: line.chars().count(),+ spans,});+ source_offset = source_offset.saturating_add(raw_line.len());}+ lines+}- RightSidebarFilePreviewLine {- plain,+fn push_preview_span(spans: &mut Vec<RightSidebarFilePreviewSpan>, text: &str, color: LinearRgba) {+ if text.is_empty() {+ return;+ }+ let char_count = text.chars().count();+ if let Some(previous) = spans.last_mut() {+ if previous.color == color {+ previous.text.push_str(text);+ previous.char_count = previous.char_count.saturating_add(char_count);+ return;+ }+ }+ spans.push(RightSidebarFilePreviewSpan {+ text: text.to_string(),char_count,- spans,+ color,+ });+}++fn syntax_default_color(use_dark_theme: bool) -> LinearRgba {+ if use_dark_theme {+ LinearRgba::with_srgba(0xab, 0xb2, 0xbf, 0xff)+ } else {+ LinearRgba::with_srgba(0x38, 0x3a, 0x42, 0xff)}}-fn syntect_color_to_linear(color: SyntectColor) -> LinearRgba {- LinearRgba::with_srgba(color.r, color.g, color.b, color.a)+fn syntax_color(kind: HighlightKind, use_dark_theme: bool) -> LinearRgba {+ let (red, green, blue) = if use_dark_theme {+ match kind {+ HighlightKind::Comment => (0x7f, 0x84, 0x8e),+ HighlightKind::Keyword | HighlightKind::Label => (0xc6, 0x78, 0xdd),+ HighlightKind::String => (0x98, 0xc3, 0x79),+ HighlightKind::Number | HighlightKind::Constant => (0xd1, 0x9a, 0x66),+ HighlightKind::Type | HighlightKind::Module => (0xe5, 0xc0, 0x7b),+ HighlightKind::Function | HighlightKind::Constructor => (0x61, 0xaf, 0xef),+ HighlightKind::Property | HighlightKind::Attribute | HighlightKind::Tag => {+ (0xe0, 0x6c, 0x75)+ }+ HighlightKind::Variable+ | HighlightKind::Embedded+ | HighlightKind::Operator+ | HighlightKind::Punctuation => (0xab, 0xb2, 0xbf),+ }+ } else {+ match kind {+ HighlightKind::Comment => (0x6a, 0x73, 0x7d),+ HighlightKind::Keyword | HighlightKind::Label => (0xa6, 0x26, 0xa4),+ HighlightKind::String => (0x50, 0xa1, 0x4f),+ HighlightKind::Number | HighlightKind::Constant => (0x98, 0x68, 0x01),+ HighlightKind::Type | HighlightKind::Module => (0xc1, 0x84, 0x01),+ HighlightKind::Function | HighlightKind::Constructor => (0x40, 0x78, 0xf2),+ HighlightKind::Property | HighlightKind::Attribute | HighlightKind::Tag => {+ (0xe4, 0x56, 0x49)+ }+ HighlightKind::Variable+ | HighlightKind::Embedded+ | HighlightKind::Operator+ | HighlightKind::Punctuation => (0x38, 0x3a, 0x42),+ }+ };+ LinearRgba::with_srgba(red, green, blue, 0xff)}fn preview_line_count(lines: &[RightSidebarFilePreviewLine]) -> usize {@@ -6381,9 +8243,10 @@ fn visible_file_row_range(start.min(row_count)..end.min(row_count)}-fn load_right_sidebar_file_preview(+fn load_right_sidebar_file_preview_with_cancellation(path: &Path,use_dark_syntax_theme: bool,+ cancellation: Option<&AtomicUsize>,) -> RightSidebarLoadedFilePreview {if is_preview_image_path(path) {return match load_file_preview_image(path) {@@ -6404,7 +8267,7 @@ fn load_right_sidebar_file_preview(let (text, message, truncated) = load_file_preview(path);let lines = if message.is_none() {- preview_lines_from_text(path, &text, use_dark_syntax_theme)+ preview_lines_from_text_with_cancellation(path, &text, use_dark_syntax_theme, cancellation)} else {Vec::new()};@@ -6468,7 +8331,7 @@ fn load_file_preview(path: &Path) -> (String, Option<String>, bool) {String::new(),Some(format!("Unable to open file: {err}")),false,- )+ );}};let mut bytes = Vec::with_capacity(FILE_PREVIEW_MAX_BYTES + 1);@@ -7156,14 +9019,16 @@ mod tests {use super::{build_right_sidebar_file_index, full_line_colors_by_byte,image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,- naturalish_cmp, open_with_candidate_allowed, path_key, preview_line_count,- preview_lines_from_text, preview_plain_lines_from_text, preview_text_range,- preview_visible_colored, preview_visible_line_range,- right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,- right_sidebar_open_with_cache_key, search_right_sidebar_file_index, snippet_cursor_visible,- snippet_run_buffer, sorted_open_with_candidates, visible_file_row_range,- wrap_snippet_text_for_width, FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, FILE_PREVIEW_MAX_BYTES,+ naturalish_cmp, note_code_highlight_lines, note_code_row_height,+ open_with_candidate_allowed, path_key, preview_line_count, preview_lines_from_text,+ preview_plain_lines_from_text, preview_text_range, preview_visible_colored,+ preview_visible_line_range, right_sidebar_file_browse_rows_from_index,+ right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key,+ search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,+ sorted_open_with_candidates, visible_file_row_range, wrap_snippet_text_for_width,+ FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,};+ use crate::markdown_editor::ProjectedCodeBlock;use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan};use crate::utilsprites::RenderMetrics;use std::collections::HashSet;@@ -7185,6 +9050,44 @@ mod tests {}}+ #[test]+ fn note_code_highlighting_resolves_aliases_and_utf8_byte_colors() {+ assert!(thinkterm_syntax::detect_fence("python").is_some());+ assert!(thinkterm_syntax::detect_fence("rust").is_some());+ assert!(thinkterm_syntax::detect_fence("definitely-not-a-language").is_none());++ let text = "def 你好(name):\n return name\n";+ let code = ProjectedCodeBlock {+ source: 0..text.len() + 12,+ content: 6..6 + text.len(),+ text: text.to_string(),+ language: Some("python".to_string()),+ };+ let colors = note_code_highlight_lines(&code, true);+ assert_eq!(colors.len(), 2);+ assert_eq!(colors[0].len(), "def 你好(name):".len());+ assert_eq!(colors[1].len(), " return name".len());+ let first = colors.iter().flatten().next().copied().unwrap();+ assert!(+ colors.iter().flatten().any(|color| *color != first),+ "Python should produce multiple token colors"+ );+ }++ #[test]+ fn note_code_row_heights_form_one_continuous_block() {+ assert_eq!(note_code_row_height(0, 3, false, 20.0, 38.0, 9.0), 67.0);+ assert_eq!(note_code_row_height(1, 3, false, 20.0, 38.0, 9.0), 20.0);+ assert_eq!(note_code_row_height(2, 3, false, 20.0, 38.0, 9.0), 29.0);+ assert_eq!(note_code_row_height(0, 3, true, 20.0, 38.0, 9.0), 38.0);+ assert_eq!(note_code_row_height(1, 3, true, 20.0, 38.0, 9.0), 0.0);+ }++ #[test]+ fn note_code_block_uses_panel_radius_not_capsule_radius() {+ assert!(NOTE_CODE_BLOCK_RADIUS < NOTE_CODE_HEADER_HEIGHT as f32 / 2.0);+ }+#[test]fn file_index_sorts_dirs_first_and_natural() {let dir = tempfile::tempdir().unwrap();@@ -7681,7 +9584,7 @@ mod tests {// A line far longer than the highlight cap must be preserved verbatim// (no 640-char truncation, no "...") on both the plain and highlighted// paths.- let line = "a".repeat(FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT * 2);+ let line = "a".repeat(16_384);let plain = preview_plain_lines_from_text(&line);assert_eq!(plain.len(), 1);@@ -7694,6 +9597,18 @@ mod tests {assert!(!highlighted[0].plain.contains("..."));}+ #[test]+ fn preview_highlight_limit_never_splits_utf8_or_truncates_text() {+ let mut text = "a".repeat(thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT - 1);+ text.push('你');+ text.push_str("tail");++ let lines = preview_lines_from_text(std::path::Path::new("large.py"), &text, true);+ assert_eq!(lines.len(), 1);+ assert_eq!(lines[0].plain, text);+ assert_eq!(lines[0].char_count, text.chars().count());+ }+#[test]fn preview_text_range_slices_by_character_columns() {assert_eq!(preview_text_range("ab你好cd", 2, 4), "你好");diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 29e9bb69..184b0f8d 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -1311,9 +1311,7 @@ pub fn workspace_pane_font_scales(let mut scales: HashMap<PaneId, Option<f64>> = HashMap::new();for tab in window.iter() {for pos in tab.iter_panes_ignoring_zoom() {- if let Some(client_pane) =- pos.pane.downcast_ref::<wezterm_client::pane::ClientPane>()- {+ if let Some(client_pane) = pos.pane.downcast_ref::<wezterm_client::pane::ClientPane>() {scales.insert(pos.pane.pane_id(),remote.get(&client_pane.remote_pane_id).copied(),@@ -3677,7 +3675,11 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {.projects.iter().any(|project| project.threads.iter().any(|thread| thread.id == thread_id));- if !store.projects.iter().any(|project| project.id == mux_project_id) {+ if !store+ .projects+ .iter()+ .any(|project| project.id == mux_project_id)+ {store.projects.push(Project {id: mux_project_id.clone(),space_id: space_id.to_string(),@@ -3705,7 +3707,9 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {changed = true;}None => {- let path = cwd.filter(|p| !p.is_empty()).unwrap_or_else(|| "~".to_string());+ let path = cwd+ .filter(|p| !p.is_empty())+ .unwrap_or_else(|| "~".to_string());let name = Path::new(&path).file_name().and_then(|n| n.to_str())@@ -3798,9 +3802,11 @@ pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {.find(|p| p.id == project_id).expect("mux domain project was just ensured");if project.threads.is_empty() {- project- .threads- .push(WorkspaceThread::new(project_id.clone(), "main".to_string(), None));+ project.threads.push(WorkspaceThread::new(+ project_id.clone(),+ "main".to_string(),+ None,+ ));}let thread_id = project.active_thread_iddiff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex fe204b5f..b9c7a06b 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -1103,9 +1103,9 @@ fn schedule_spawn_pane_in_stack<SND>() whereSND: Fn(anyhow::Result<Pdu>) + 'static,{- promise::spawn::spawn(async move {- send_response(spawn_pane_in_stack(request, client_id).await)- })+ promise::spawn::spawn(+ async move { send_response(spawn_pane_in_stack(request, client_id).await) },+ ).detach();}diff --git a/wezterm-open-url/src/lib.rs b/wezterm-open-url/src/lib.rsindex 97cd16a5..35bd3026 100644--- a/wezterm-open-url/src/lib.rs+++ b/wezterm-open-url/src/lib.rs@@ -102,9 +102,7 @@ fn windows_open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {let hkcu = RegKey::predef(HKEY_CURRENT_USER);let hkcr = RegKey::predef(HKEY_CLASSES_ROOT);- let file_exts = format!(- r"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}"- );+ let file_exts = format!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}");if let Some(exe) = windows_default_executable(&hkcu, &hkcr, &file_exts, &ext) {push_candidate(&mut out, &mut seen, exe, true);