Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat: Align interactions with IntelliJ IDEA (#22)

l0ng-ai81e0e8e2d074
diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs
index 43547f962..b6f879a4f 100644
--- a/crates/ide-core/src/editor_settings.rs
+++ b/crates/ide-core/src/editor_settings.rs
@@ -102,7 +102,7 @@ pub struct BreadcrumbsSettings {
impl Default for BreadcrumbsSettings {
fn default() -> Self {
- Self { show: false, placement: "bottom".into(), disabled_languages: Vec::new() }
+ Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
}
}
@@ -130,10 +130,10 @@ impl Default for CompletionSettings {
case_sensitivity: "first".into(),
auto_popup: true,
insert_on_special_keys: false,
- show_documentation: true,
+ show_documentation: false,
documentation_delay: 500,
parameter_info: true,
- parameter_info_delay: 300,
+ parameter_info_delay: 1000,
}
}
}
@@ -192,9 +192,9 @@ impl Default for EditorTabsSettings {
show_close_button: true,
preview_tab: true,
open_at_end: false,
- tab_limit: 10,
- closing_policy: "unchanged".into(),
- activate_on_close: "mru".into(),
+ tab_limit: 30,
+ closing_policy: "lru".into(),
+ activate_on_close: "left".into(),
}
}
}
@@ -214,7 +214,7 @@ pub struct SmartKeysSettings {
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
pub smart_indent: bool,
- /// Backspace › Unindent: `nearest` indent position | `none`.
+ /// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
}
@@ -226,10 +226,10 @@ impl Default for SmartKeysSettings {
pair_brackets: true,
pair_quotes: true,
surround_selection: true,
- tab_out_of_pair: false,
+ tab_out_of_pair: true,
reformat_on_paste: "indentBlock".into(),
smart_indent: true,
- backspace_unindent: "nearest".into(),
+ backspace_unindent: "autoindent".into(),
}
}
}
@@ -314,6 +314,12 @@ pub struct LanguageCodeStyle {
pub indent: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hard_wrap_at: Option<u32>,
+ /// Comment Code › Line comment at first column.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub line_comment_at_first_column: Option<bool>,
+ /// Comment Code › Add a space at line comment start.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub line_comment_add_space: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs
index 5ff6c797b..4d3ebcc6e 100644
--- a/crates/ide-coverage/src/plan.rs
+++ b/crates/ide-coverage/src/plan.rs
@@ -287,6 +287,7 @@ mod tests {
detected: true,
is_test: true,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs
index eef25d350..2d737f9ff 100644
--- a/crates/ide-index/src/lib.rs
+++ b/crates/ide-index/src/lib.rs
@@ -159,6 +159,26 @@ impl ProjectIndex {
self.shared.enqueue(Job::SaveRecent);
}
+ /// Drops a file from Recent Files (Delete in the ⌘E popup).
+ pub fn remove_recent(&self, path: &Path) {
+ let path = match path.to_str() {
+ Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
+ _ => match self.normalize(path) {
+ Some(p) => p,
+ None => return,
+ },
+ };
+ {
+ let mut r = self.shared.recent.lock();
+ let before = r.len();
+ r.retain(|p| p != &path);
+ if r.len() == before {
+ return;
+ }
+ }
+ self.shared.enqueue(Job::SaveRecent);
+ }
+
/// Recently opened files, most recent first.
pub fn recent_files(&self) -> Vec<PathBuf> {
self.shared.recent.lock().clone()
diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs
index 36468d7b6..1de6c22d4 100644
--- a/crates/ide-index/src/tests.rs
+++ b/crates/ide-index/src/tests.rs
@@ -192,7 +192,11 @@ fn persistence_skips_unchanged_files_on_reopen() {
assert_eq!(idx.status().files, 8);
assert_eq!(symbols(&idx, "OrderController", SymbolFilter::Types)[0], "OrderController");
assert_eq!(idx.recent_files(), vec![fx.root.join("web/app.py")]);
+ idx.remove_recent(&fx.root.join("web/app.py"));
+ assert!(idx.recent_files().is_empty());
+ assert!(idx.wait_idle(WAIT));
}
+ assert!(fx.open().recent_files().is_empty(), "removal is persisted");
std::thread::sleep(Duration::from_millis(20));
fx.write("src/main.rs", "fn main() {}\nfn renamed_fn() {}\n");
std::fs::remove_file(fx.root.join("docs/maintenance.md")).unwrap();
diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs
index 67388a227..1320e490c 100644
--- a/crates/ide-language/src/lib.rs
+++ b/crates/ide-language/src/lib.rs
@@ -13,7 +13,7 @@ mod registry;
mod syntax;
pub use registry::LanguageRegistry;
pub use syntax::{
- CSS_CLASS, CSS_ID, CSS_VARIABLE, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache,
+ CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache,
SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, WebReferenceKind,
};
diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs
index ac4cb7daf..bd24fc77e 100644
--- a/crates/ide-language/src/syntax/mod.rs
+++ b/crates/ide-language/src/syntax/mod.rs
@@ -18,7 +18,7 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
use tree_sitter::{Language, Parser, Tree};
-pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, WebReference, WebReferenceKind};
+pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind};
/// Texts larger than this are not parsed (minified bundles, generated dumps).
pub const MAX_PARSE_BYTES: usize = 16 * 1024 * 1024;
@@ -210,6 +210,11 @@ impl Syntax {
self.with_web_tree(lang, text, |g, css, tree| web::reference_at(g, css, tree, text, pos)).flatten()
}
+ /// File paths written in an HTML document or stylesheet (`href`, `src`, `srcset`, `url()`, `@import`).
+ pub fn web_file_references(&self, lang: &LanguageId, text: &str) -> Vec<FileReference> {
+ self.with_web_tree(lang, text, |g, css, tree| web::file_references(g, css, tree, text)).unwrap_or_default()
+ }
+
/// Value ranges of the `id="name"` / `name="name"` attributes in an HTML document.
pub fn web_anchors(&self, lang: &LanguageId, text: &str, name: &str) -> Vec<Range> {
self.with_web_tree(lang, text, |_, _, tree| web::anchors(tree, text, name)).unwrap_or_default()
diff --git a/crates/ide-language/src/syntax/tests.rs b/crates/ide-language/src/syntax/tests.rs
index 68691e5c5..f61c8590a 100644
--- a/crates/ide-language/src/syntax/tests.rs
+++ b/crates/ide-language/src/syntax/tests.rs
@@ -1154,3 +1154,19 @@ fn web_anchors_find_ids_and_names() {
syntax().web_anchors(&lang("html"), html, "top").into_iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(found, vec![(0, 8), (1, 9)]);
}
+
+#[test]
+fn web_file_references_in_attributes_and_stylesheets() {
+ let refs = |id: &str, src: &str| -> Vec<String> {
+ syntax().web_file_references(&lang(id), src).into_iter().map(|r| r.value).collect()
+ };
+ let html = concat!(
+ "<link href=\"css/a.css\"><img srcset=\"a.png 1x, b.png 2x\" src=img/c.png alt=\"x\">\n",
+ "<a href=\"#top\" class=\"k\">t</a><div style=\"background: url(d.svg)\"></div>\n",
+ "<style>@import \"e.css\"; .x { background: url('f.png') }</style>",
+ );
+ assert_eq!(refs("html", html), ["css/a.css", "a.png", "b.png", "img/c.png", "#top", "d.svg", "e.css", "f.png"]);
+ assert_eq!(refs("css", "@import url(g.css);\n.y { mask: url(\"h.svg#i\") }"), ["g.css", "h.svg#i"]);
+ let first = &syntax().web_file_references(&lang("html"), html)[0];
+ assert_eq!((first.range.start.col, first.range.end.col), (12, 21));
+}
diff --git a/crates/ide-language/src/syntax/web.rs b/crates/ide-language/src/syntax/web.rs
index b221ae721..73c9896d4 100644
--- a/crates/ide-language/src/syntax/web.rs
+++ b/crates/ide-language/src/syntax/web.rs
@@ -250,3 +250,125 @@ pub(crate) fn anchors(tree: &Tree, text: &str, name: &str) -> Vec<Range> {
});
out
}
+
+/// A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct FileReference {
+ pub range: Range,
+ pub value: String,
+}
+
+/// HTML attributes whose value is a URL.
+const URL_ATTRIBUTES: &[&str] = &[
+ "href",
+ "src",
+ "srcset",
+ "action",
+ "formaction",
+ "poster",
+ "data",
+ "cite",
+ "background",
+ "manifest",
+ "xlink:href",
+ "longdesc",
+ "icon",
+];
+
+/// `url(…)` arguments and `@import` targets of a stylesheet: `(start, end)` byte ranges.
+fn css_paths(tree: &Tree, css_text: &str, out: &mut Vec<(usize, usize)>) {
+ let target = |n: Node| -> Option<(usize, usize)> {
+ let n =
+ if n.kind() == "string_value" { n.named_child(0).filter(|c| c.kind() == "string_content")? } else { n };
+ matches!(n.kind(), "plain_value" | "string_content").then(|| (n.start_byte(), n.end_byte()))
+ };
+ walk(tree.root_node(), &mut |n| {
+ match n.kind() {
+ "import_statement" => {
+ if let Some(first) = n.named_child(0)
+ && first.kind() == "string_value"
+ {
+ out.extend(target(first));
+ }
+ }
+ "call_expression" => {
+ let is_url =
+ n.named_child(0).is_some_and(|f| f.kind() == "function_name" && text_of(f, css_text) == "url");
+ if is_url
+ && let Some(args) = n.child_by_field_name("arguments").or_else(|| n.named_child(1))
+ && let Some(arg) = args.named_child(0)
+ {
+ out.extend(target(arg));
+ }
+ }
+ _ => {}
+ }
+ true
+ });
+}
+
+/// File paths written in an HTML document or a stylesheet.
+pub(crate) fn file_references(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<FileReference> {
+ let idx = LineIndex::new(text);
+ let mut spans: Vec<(usize, usize)> = Vec::new();
+ for (base, css_text) in css_regions(g.spec.name, tree, text) {
+ let parsed;
+ let css_tree = if g.spec.name == "css" {
+ tree
+ } else {
+ let Some(t) = css.and_then(|c| parse(&c.language, css_text, None)) else { continue };
+ parsed = t;
+ &parsed
+ };
+ let mut found = Vec::new();
+ css_paths(css_tree, css_text, &mut found);
+ spans.extend(found.into_iter().map(|(s, e)| (base + s, base + e)));
+ }
+ if g.spec.name == "html" {
+ walk(tree.root_node(), &mut |n| {
+ if n.kind() != "attribute" {
+ return true;
+ }
+ let name = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase()).unwrap_or_default();
+ let mut value = None;
+ walk(n, &mut |v| {
+ if v.kind() == "attribute_value" {
+ value = Some(v);
+ }
+ value.is_none()
+ });
+ let Some(v) = value else { return false };
+ let (vs, vtext) = (v.start_byte(), text_of(v, text));
+ match name.as_str() {
+ "srcset" => {
+ // `a.png 1x, b.png 2x`: the URL of each candidate.
+ let mut at = 0;
+ for part in vtext.split(',') {
+ let lead = part.len() - part.trim_start().len();
+ let url = part.split_whitespace().next().unwrap_or_default();
+ if !url.is_empty() {
+ spans.push((vs + at + lead, vs + at + lead + url.len()));
+ }
+ at += part.len() + 1;
+ }
+ }
+ "style" => {
+ let wrapped = format!("x{{{vtext}}}");
+ if let Some(t) = css.and_then(|c| parse(&c.language, &wrapped, None)) {
+ let mut found = Vec::new();
+ css_paths(&t, &wrapped, &mut found);
+ spans.extend(found.into_iter().map(|(s, e)| (vs + s - 2, vs + e - 2)));
+ }
+ }
+ _ if URL_ATTRIBUTES.contains(&name.as_str()) && !vtext.trim().is_empty() => {
+ spans.push((vs, vs + vtext.len()));
+ }
+ _ => {}
+ }
+ false
+ });
+ }
+ spans.sort_unstable();
+ spans.into_iter().map(|(s, e)| FileReference { range: idx.range(s, e), value: text[s..e].to_owned() }).collect()
+}
diff --git a/crates/ide-profiler/src/plan.rs b/crates/ide-profiler/src/plan.rs
index 8dd749a37..9a679e02f 100644
--- a/crates/ide-profiler/src/plan.rs
+++ b/crates/ide-profiler/src/plan.rs
@@ -232,6 +232,7 @@ mod tests {
detected: true,
is_test: false,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs
index 72ed774f1..4fc44368b 100644
--- a/crates/ide-run/src/config.rs
+++ b/crates/ide-run/src/config.rs
@@ -11,6 +11,7 @@
//! env = { RUST_LOG = "debug" }
//! is-test = false
//! debug-adapter = "codelldb"
+//! allow-parallel = true
//! ```
use crate::RunConfig;
@@ -51,6 +52,8 @@ struct FileConfig {
is_test: bool,
#[serde(alias = "debugAdapter", alias = "debug_adapter")]
debug_adapter: Option<String>,
+ #[serde(default, alias = "allowParallel", alias = "allow_parallel")]
+ allow_parallel: bool,
}
fn slug(s: &str) -> String {
@@ -91,6 +94,7 @@ pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
detected: false,
is_test: c.is_test,
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
+ allow_parallel: c.allow_parallel,
});
}
Ok(out)
@@ -121,6 +125,9 @@ fn to_table(c: &RunConfig) -> Table {
if let Some(adapter) = &c.debug_adapter {
t.insert("debug-adapter", value(adapter));
}
+ if c.allow_parallel {
+ t.insert("allow-parallel", value(true));
+ }
t
}
diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs
index 27027ec58..cb4c2fe03 100644
--- a/crates/ide-run/src/detect.rs
+++ b/crates/ide-run/src/detect.rs
@@ -37,6 +37,7 @@ fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &
detected: true,
is_test: false,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs
index ca0d3d52e..55f950573 100644
--- a/crates/ide-run/src/lib.rs
+++ b/crates/ide-run/src/lib.rs
@@ -34,6 +34,10 @@ pub struct RunConfig {
pub is_test: bool,
/// DAP adapter that can debug this config, if any.
pub debug_adapter: Option<String>,
+ /// "Allow multiple instances": Run on a running config starts another one instead of restarting it.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ #[specta(optional)]
+ pub allow_parallel: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
diff --git a/crates/ide-run/src/wrap.rs b/crates/ide-run/src/wrap.rs
index d3fe25b9e..3c00c97bb 100644
--- a/crates/ide-run/src/wrap.rs
+++ b/crates/ide-run/src/wrap.rs
@@ -260,6 +260,7 @@ mod tests {
detected: false,
is_test: false,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-run/tests/config.rs b/crates/ide-run/tests/config.rs
index 7d364f1b2..74344b026 100644
--- a/crates/ide-run/tests/config.rs
+++ b/crates/ide-run/tests/config.rs
@@ -16,6 +16,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: false,
debug_adapter: Some("codelldb".into()),
+ allow_parallel: true,
},
RunConfig {
id: "user:tests".into(),
@@ -28,6 +29,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: true,
debug_adapter: None,
+ allow_parallel: false,
},
]
}
diff --git a/crates/ide-run/tests/process.rs b/crates/ide-run/tests/process.rs
index a87cd90a9..bd9d51c4a 100644
--- a/crates/ide-run/tests/process.rs
+++ b/crates/ide-run/tests/process.rs
@@ -42,6 +42,7 @@ fn cfg(id: &str, command: &str, args: &[&str]) -> RunConfig {
detected: false,
is_test: false,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs
index ae2dce420..0d74f038e 100644
--- a/crates/ide-sdk/src/tests.rs
+++ b/crates/ide-sdk/src/tests.rs
@@ -46,6 +46,7 @@ fn run(kind: &str, command: &str, args: &[&str]) -> RunConfig {
detected: true,
is_test: false,
debug_adapter: None,
+ allow_parallel: false,
}
}
diff --git a/crates/ide-terminal/src/lib.rs b/crates/ide-terminal/src/lib.rs
index 5592a2bc1..1ab4b72e9 100644
--- a/crates/ide-terminal/src/lib.rs
+++ b/crates/ide-terminal/src/lib.rs
@@ -160,6 +160,19 @@ impl TerminalManager {
Ok(())
}
+ /// Whether the shell is running a command, so closing its tab should ask first
+ /// (as IDEA does). On Unix: the PTY's foreground process
+ /// group isn't the shell's, i.e. a job is in the foreground (background helpers
+ /// such as prompt daemons don't count). On Windows: the shell has child processes.
+ pub fn is_busy(&self, id: TerminalId) -> IdeResult<bool> {
+ let session = self.session(id)?;
+ if session.exited.load(Ordering::Acquire) {
+ return Ok(false);
+ }
+ let Some(pid) = session.info.pid else { return Ok(false) };
+ Ok(foreground_busy(&session, pid))
+ }
+
pub fn list(&self) -> Vec<TerminalInfo> {
let mut out: Vec<TerminalInfo> = self.sessions.lock().values().map(|s| s.info.clone()).collect();
out.sort_by_key(|i| i.id);
@@ -191,6 +204,76 @@ fn not_found(id: TerminalId) -> IdeError {
IdeError::not_found(format!("no such terminal: {id}"))
}
+#[cfg(unix)]
+fn foreground_busy(session: &Session, pid: u32) -> bool {
+ let leader = session.master.lock().process_group_leader();
+ leader.is_some_and(|fg| u32::try_from(fg).ok() != Some(pid))
+}
+
+#[cfg(windows)]
+fn foreground_busy(_session: &Session, pid: u32) -> bool {
+ win::has_child_processes(pid)
+}
+
+#[cfg(not(any(unix, windows)))]
+fn foreground_busy(_session: &Session, _pid: u32) -> bool {
+ false
+}
+
+#[cfg(windows)]
+mod win {
+ use std::ffi::c_void;
+
+ const TH32CS_SNAPPROCESS: u32 = 0x2;
+ const INVALID_HANDLE_VALUE: isize = -1;
+
+ /// `PROCESSENTRY32W` from `<tlhelp32.h>`.
+ #[repr(C)]
+ struct ProcessEntry32W {
+ dw_size: u32,
+ cnt_usage: u32,
+ th32_process_id: u32,
+ th32_default_heap_id: usize,
+ th32_module_id: u32,
+ cnt_threads: u32,
+ th32_parent_process_id: u32,
+ pc_pri_class_base: i32,
+ dw_flags: u32,
+ sz_exe_file: [u16; 260],
+ }
+
+ #[link(name = "kernel32")]
+ unsafe extern "system" {
+ fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> *mut c_void;
+ fn Process32FirstW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
+ fn Process32NextW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
+ fn CloseHandle(handle: *mut c_void) -> i32;
+ }
+
+ pub fn has_child_processes(pid: u32) -> bool {
+ // SAFETY: plain Win32 calls on a locally owned snapshot handle and entry buffer.
+ unsafe {
+ let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ if snapshot.is_null() || snapshot as isize == INVALID_HANDLE_VALUE {
+ return false;
+ }
+ let mut entry: ProcessEntry32W = std::mem::zeroed();
+ entry.dw_size = std::mem::size_of::<ProcessEntry32W>() as u32;
+ let mut found = false;
+ let mut ok = Process32FirstW(snapshot, &mut entry);
+ while ok != 0 {
+ if entry.th32_parent_process_id == pid && entry.th32_process_id != pid {
+ found = true;
+ break;
+ }
+ ok = Process32NextW(snapshot, &mut entry);
+ }
+ CloseHandle(snapshot);
+ found
+ }
+ }
+}
+
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
if session.exited.load(Ordering::Acquire) {
@@ -650,6 +733,31 @@ mod tests {
assert!(h.manager.kill(info.id).is_err());
}
+ #[test]
+ fn busy_while_a_command_runs_in_the_foreground() {
+ let h = harness();
+ let mut opts = sh("");
+ opts.args = vec!["-i".into()];
+ opts.env.insert("PS1".into(), "$ ".into());
+ opts.env.insert("ENV".into(), "/dev/null".into());
+ let (info, _rx) = spawn_collect(&h, opts);
+ let wait_for = |want: bool| {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while h.manager.is_busy(info.id).unwrap() != want {
+ assert!(Instant::now() < deadline, "is_busy never became {want}");
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ };
+ wait_for(false);
+ h.manager.write(info.id, "sleep 30\n").unwrap();
+ wait_for(true);
+ h.manager.write(info.id, "\u{3}").unwrap();
+ wait_for(false);
+ h.manager.write(info.id, "exit\n").unwrap();
+ let _ = wait_exit(&h, info.id);
+ assert!(h.manager.is_busy(info.id).is_err());
+ }
+
#[test]
fn large_output_is_batched_and_complete() {
let h = harness();
diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs
index 4151a6c06..8cb4d85c8 100644
--- a/crates/ide-vcs/src/lib.rs
+++ b/crates/ide-vcs/src/lib.rs
@@ -136,6 +136,30 @@ pub struct CommitOptions {
pub author: Option<String>,
/// False skips the pre-commit and commit-msg hooks (`--no-verify`).
pub run_hooks: bool,
+ /// Files committed with only some of their changes (IDEA's partial commit). They are
+ /// committed through a temporary index, so neither the working tree nor the other
+ /// entries of the index change; afterwards their index entries match the new commit.
+ #[serde(default)]
+ pub partial: Vec<PartialCommitFile>,
+}
+
+/// A file of a partial commit: which of its changes against HEAD to commit.
+#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PartialCommitFile {
+ pub path: ide_core::IpcPath,
+ /// The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them.
+ pub hunks: Vec<HunkRange>,
+}
+
+/// A hunk identified by its line ranges (0-based), see [`LineHunk`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct HunkRange {
+ pub start: u32,
+ pub lines: u32,
+ pub old_start: u32,
+ pub old_lines: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -237,6 +261,106 @@ pub struct ApplyOutcome {
pub conflicts: Vec<String>,
}
+/// How Checkout treats local changes that the switch would overwrite (IDEA's Smart
+/// Checkout dialog).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum CheckoutMode {
+ /// Fail with [`CheckoutOutcome::LocalChanges`] and change nothing.
+ #[default]
+ Normal,
+ /// Stash local changes, switch, and restore them (conflicts are left to resolve).
+ Smart,
+ /// Discard the local changes in the way (`git switch --discard-changes`).
+ Force,
+}
+
+/// Checking out remote `origin/x` while local `x` has commits `origin/x` lacks.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum DivergedLocal {
+ /// Rebase local `x` onto `origin/x` (IDEA "Rebase onto Remote").
+ Rebase,
+ /// Reset local `x` to `origin/x` (IDEA "Drop Local Commits").
+ Reset,
+}
+
+#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct CheckoutOptions {
+ #[serde(default)]
+ pub mode: CheckoutMode,
+ /// Required when checking out a remote branch whose local namesake is ahead of it.
+ #[serde(default)]
+ pub diverged: Option<DivergedLocal>,
+}
+
+/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
+/// left the repository untouched.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum CheckoutOutcome {
+ Done,
+ /// These local changes (repository-relative paths) would be overwritten.
+ LocalChanges {
+ files: Vec<String>,
+ },
+ /// Local branch `local` has commits that remote branch `remote` does not.
+ LocalBranchAhead {
+ local: String,
+ remote: String,
+ },
+ /// Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
+ /// on conflicts in these files.
+ Conflicts {
+ files: Vec<String>,
+ },
+}
+
+/// A deleted local branch, enough to restore it (IDEA's "Restore" notification action).
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct DeletedBranch {
+ pub name: String,
+ /// The commit the branch pointed at.
+ pub tip: String,
+ /// Its upstream (`origin/x`), restored with it.
+ pub upstream: Option<String>,
+ /// It was not fully merged: its own commits are now unreachable from any branch.
+ pub unmerged: bool,
+}
+
+/// Who stands on each side of the conflicts of the operation in progress (merge editor
+/// titles, as IDEA labels them).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct MergeSides {
+ /// `merge`, `rebase`, `cherry-pick`, `revert`…; `None` outside an operation.
+ pub operation: Option<String>,
+ /// Git's "ours" is not the user's work: during a rebase stage 2 holds the commits
+ /// rebased onto and stage 3 the user's commit being replayed. [`MergeVersions`] is
+ /// already swapped; conflict markers in the file are not.
+ pub reversed: bool,
+ /// The current branch (for a rebase: the branch being rebased).
+ pub branch: Option<String>,
+ /// Short id of the commit being applied (REBASE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD)
+ /// or merged (MERGE_HEAD).
+ pub commit: Option<String>,
+ /// The other branch: the one being merged, or the one rebased onto.
+ pub other_branch: Option<String>,
+}
+
+/// The versions of a conflicted file as the merge editor shows them.
+#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct MergeVersions {
+ pub base: Option<String>,
+ /// The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`.
+ pub ours: Option<String>,
+ pub theirs: Option<String>,
+ pub sides: MergeSides,
+}
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Changelist {
@@ -416,7 +540,7 @@ impl Repo {
/// Commits the index; returns the new HEAD commit id. An empty message with
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
- let options = CommitOptions { amend, sign_off, author: None, run_hooks: true };
+ let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
write::commit(self, message, &options)
}
/// Commits with the Commit Options popup's choices.
@@ -429,6 +553,13 @@ impl Repo {
pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> {
write::checkout(self, branch, create)
}
+ /// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or
+ /// stashed / discarded per `options.mode`), and a remote branch whose local namesake
+ /// is behind fast-forwards that branch, while one that is ahead is reported (or
+ /// rebased / reset per `options.diverged`).
+ pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult<CheckoutOutcome> {
+ write::checkout_with(self, branch, create, options)
+ }
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
/// remote-tracking start point (`origin/x`) becomes the new branch's upstream.
pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
@@ -444,6 +575,16 @@ impl Repo {
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
write::delete_branch(self, branch, force)
}
+ /// Deletes a local branch as IDEA does: without asking, force-deleting one that is not
+ /// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`]
+ /// needs to undo it.
+ pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult<DeletedBranch> {
+ write::delete_branch_restorable(self, branch)
+ }
+ /// Recreates a deleted branch at its old tip, with its upstream.
+ pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> {
+ write::restore_branch(self, deleted)
+ }
/// Renames a local branch (`git branch -m`); its upstream configuration moves with it.
pub fn rename_branch(&self, from: &str, to: &str) -> IdeResult<()> {
write::rename_branch(self, from, to)
@@ -523,7 +664,20 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
- write::push_branch(self, branch, revision, force_with_lease, cancel, on_output)
+ write::push_branch(self, branch, revision, None, force_with_lease, cancel, on_output)
+ }
+ /// [`Repo::push_branch`] to remote branch `target` instead of the upstream's name (the
+ /// Push dialog's editable target).
+ pub fn push_branch_to(
+ &self,
+ branch: &str,
+ revision: Option<&str>,
+ target: &str,
+ force_with_lease: bool,
+ cancel: &CancellationToken,
+ on_output: &dyn Fn(String),
+ ) -> IdeResult<()> {
+ write::push_branch(self, branch, revision, Some(target), force_with_lease, cancel, on_output)
}
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
/// Update). Fails when the branch has diverged.
@@ -586,6 +740,10 @@ impl Repo {
pub fn tags(&self) -> IdeResult<Vec<String>> {
ops::tags(self)
}
+ /// Files that differ between revisions `from` and `to`.
+ pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
+ ops::diff_revisions(self, from, to)
+ }
/// Tracked files whose working-tree content differs from `rev`.
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_with_worktree(self, rev)
@@ -618,6 +776,18 @@ impl Repo {
shelf::unshelve(self, shelf_dir, id, remove)
}
+ /// Who is on each side of the conflicts of the operation in progress.
+ pub fn merge_sides(&self) -> IdeResult<MergeSides> {
+ ops::merge_sides(self)
+ }
+ /// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
+ /// dialog shows them (sides swapped during a rebase).
+ pub fn merge_versions(&self, path: &Path) -> IdeResult<MergeVersions> {
+ let (base, ours, theirs) = self.conflict_versions(path)?;
+ let sides = self.merge_sides()?;
+ let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
+ Ok(MergeVersions { base, ours, theirs, sides })
+ }
/// For conflict resolution: (base, ours, theirs) versions of a conflicted file.
pub fn conflict_versions(&self, path: &Path) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
let rel = self.rel_path(path)?;
diff --git a/crates/ide-vcs/src/ops.rs b/crates/ide-vcs/src/ops.rs
index dba15a2a6..892a2ef66 100644
--- a/crates/ide-vcs/src/ops.rs
+++ b/crates/ide-vcs/src/ops.rs
@@ -3,7 +3,7 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
-use crate::{ChangeKind, ChangedFile, RebaseAction, RebaseEntry, Repo, ResetMode};
+use crate::{ChangeKind, ChangedFile, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode};
use ide_core::{CancellationToken, IdeError, IdeResult};
/// The in-progress operation git can continue / abort / skip.
@@ -20,6 +20,64 @@ fn sequencer(r: &Repo) -> IdeResult<&'static str> {
use crate::write::unmerged_paths;
+/// The sides of the operation in progress, read from the files git keeps in `.git`.
+pub(crate) fn merge_sides(r: &Repo) -> IdeResult<MergeSides> {
+ let repo = r.gix()?;
+ let operation = crate::refs::operation(&repo);
+ let read = |name: &str| {
+ std::fs::read_to_string(r.git_dir.join(name))
+ .ok()
+ .and_then(|s| s.lines().next().map(|l| l.trim().to_string()))
+ .filter(|s| !s.is_empty())
+ };
+ let short = |id: String| id.chars().take(8).collect::<String>();
+ let head_branch = repo.head_name().map_err(gx)?.map(|n| crate::repo::to_string(n.as_ref().shorten()));
+ let mut sides = MergeSides { operation: operation.clone(), branch: head_branch, ..Default::default() };
+ match operation.as_deref() {
+ Some("rebase") => {
+ sides.reversed = true;
+ let dir = ["rebase-merge", "rebase-apply"].into_iter().find(|d| r.git_dir.join(d).is_dir());
+ if let Some(dir) = dir {
+ if let Some(head) = read(&format!("{dir}/head-name")) {
+ sides.branch = Some(head.strip_prefix("refs/heads/").unwrap_or(&head).to_string());
+ }
+ sides.other_branch = read(&format!("{dir}/onto")).and_then(|onto| branch_at(r, &onto));
+ }
+ sides.commit = read("REBASE_HEAD").map(short);
+ }
+ Some("merge") => {
+ let head = read("MERGE_HEAD");
+ // git quotes the merged ref on the first line: `Merge branch 'main' into feature`.
+ sides.other_branch = read("MERGE_MSG")
+ .and_then(|m| m.split('\'').nth(1).map(str::to_string))
+ .filter(|b| !b.is_empty())
+ .or_else(|| head.as_deref().and_then(|h| branch_at(r, h)));
+ sides.commit = head.map(short);
+ }
+ Some("cherry-pick") => sides.commit = read("CHERRY_PICK_HEAD").map(short),
+ Some("revert") => sides.commit = read("REVERT_HEAD").map(short),
+ _ => {}
+ }
+ Ok(sides)
+}
+
+/// The single branch (local first, then remote) pointing at `commit`.
+fn branch_at(r: &Repo, commit: &str) -> Option<String> {
+ if commit.starts_with('-') {
+ return None;
+ }
+ ["refs/heads", "refs/remotes"].into_iter().find_map(|refs| {
+ let out =
+ run(r.root(), &["for-each-ref", "--points-at", commit, "--format=%(refname:short)", refs], None).ok()?;
+ let names: Vec<String> =
+ out.stdout_str().lines().filter(|l| !l.is_empty() && !l.ends_with("/HEAD")).map(str::to_string).collect();
+ match names.as_slice() {
+ [one] => Some(one.clone()),
+ _ => None,
+ }
+ })
+}
+
fn check_commits(commits: &[String]) -> IdeResult<()> {
if commits.is_empty() {
return Err(IdeError::invalid("no commits selected"));
@@ -259,6 +317,13 @@ pub(crate) fn diff_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFi
Ok(parse_name_status(&out.stdout_str()))
}
+/// Files that differ between two revisions (Update Project's "N files updated").
+pub(crate) fn diff_revisions(r: &Repo, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
+ check_commits(&[from.to_string(), to.to_string()])?;
+ let out = run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", from, to, "--"], None)?;
+ Ok(parse_name_status(&out.stdout_str()))
+}
+
/// Parses `git diff --name-status -z` output.
pub(crate) fn parse_name_status(text: &str) -> Vec<ChangedFile> {
let mut parts = text.split('\0').filter(|s| !s.is_empty());
diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs
index e70c497f6..943808cbd 100644
--- a/crates/ide-vcs/src/write.rs
+++ b/crates/ide-vcs/src/write.rs
@@ -2,7 +2,9 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
-use crate::{BlameLine, CommitOptions, Repo};
+use crate::{
+ BlameLine, CheckoutMode, CheckoutOptions, CheckoutOutcome, CommitOptions, DeletedBranch, DivergedLocal, Repo,
+};
use gix::bstr::{BStr, ByteSlice};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -247,11 +249,85 @@ pub(crate) fn commit(r: &Repo, message: &str, options: &CommitOptions) -> IdeRes
args.extend(["-F", "-"]);
Some(message.as_bytes())
};
- run(r.root(), &args, stdin)?;
+ if options.partial.is_empty() {
+ run(r.root(), &args, stdin)?;
+ } else {
+ commit_partial(r, &args, stdin, &options.partial)?;
+ }
let repo = r.gix()?;
Ok(repo.head_id().map_err(gx)?.detach().to_string())
}
+/// Removes the temporary index however the partial commit ends.
+struct TempIndex(PathBuf);
+
+impl Drop for TempIndex {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ let _ = std::fs::remove_file(self.0.with_extension("lock"));
+ }
+}
+
+/// Commits the index with only the chosen hunks of `partial` files, through a copy of the
+/// index (`GIT_INDEX_FILE`), as IDEA's partial commit does: the working tree and the
+/// user's index are left alone except that the partial files' entries end up matching
+/// the new commit.
+fn commit_partial(
+ r: &Repo,
+ commit_args: &[&str],
+ stdin: Option<&[u8]>,
+ partial: &[crate::PartialCommitFile],
+) -> IdeResult<()> {
+ let tmp = TempIndex(r.git_dir.join("openidea-partial-index"));
+ let index = r.git_dir.join("index");
+ if index.exists() {
+ std::fs::copy(&index, &tmp.0)?;
+ }
+ let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
+ let mut rels = Vec::new();
+ for file in partial {
+ let rel = r.rel_path(&file.path.0)?;
+ let head = {
+ let repo = r.gix()?;
+ crate::repo::blob_at(&repo, &rel, "HEAD")?
+ }
+ .ok_or_else(|| {
+ IdeError::invalid(format!("{rel}: only changes of a file in HEAD can be committed partially"))
+ })?;
+ let disk = std::fs::read(r.abs_path(&rel))?;
+ if head.contains(&0) || disk.contains(&0) {
+ return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially")));
+ }
+ let (head, disk) = (String::from_utf8_lossy(&head), String::from_utf8_lossy(&disk));
+ let hunks = crate::diff::line_hunks(&head, &disk);
+ let mut selected = Vec::new();
+ for want in &file.hunks {
+ let found = hunks.iter().position(|h| {
+ (h.start, h.lines, h.old_start, h.old_lines) == (want.start, want.lines, want.old_start, want.old_lines)
+ });
+ match found {
+ Some(i) => selected.push(i),
+ None => return Err(IdeError::invalid(format!("{rel} changed on disk; review its changes again"))),
+ }
+ }
+ cli::run_env(r.root(), &["--literal-pathspecs", "reset", "-q", "HEAD", "--", &rel], None, &env)?;
+ let patch = crate::diff::build_partial_patch(&rel, &head, &disk, &selected);
+ if !patch.is_empty() {
+ cli::run_env(
+ r.root(),
+ &["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"],
+ Some(patch.as_bytes()),
+ &env,
+ )?;
+ }
+ rels.push(rel);
+ }
+ cli::run_env(r.root(), commit_args, stdin, &env)?;
+ // The user's index still holds the partial files' previous entries: align them with
+ // the commit so the remaining changes show as unstaged, nothing as staged.
+ run_paths(r, &["reset", "-q", "HEAD"], &rels)
+}
+
pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
let branch = branch.trim();
if branch.is_empty() {
@@ -280,6 +356,128 @@ pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
run(r.root(), &["switch", "--detach", branch], None).map(|_| ())
}
+/// What a checkout of `branch` runs.
+enum SwitchPlan {
+ Switch(Vec<String>),
+ /// `git rebase <remote> <local>`.
+ Rebase {
+ local: String,
+ remote: String,
+ },
+ Ahead {
+ local: String,
+ remote: String,
+ },
+}
+
+fn switch_plan(r: &Repo, branch: &str, create: bool, diverged: Option<DivergedLocal>) -> IdeResult<SwitchPlan> {
+ let args = |a: &[&str]| SwitchPlan::Switch(a.iter().map(|s| s.to_string()).collect());
+ if create {
+ return Ok(args(&["switch", "-c", branch]));
+ }
+ let repo = r.gix()?;
+ let exists = |name: &str| repo.try_find_reference(name).map_err(gx).map(|r| r.is_some());
+ if exists(&format!("refs/heads/{branch}"))? {
+ return Ok(args(&["switch", branch]));
+ }
+ if exists(&format!("refs/remotes/{branch}"))?
+ && let Some((_, name)) = branch.split_once('/')
+ {
+ if !exists(&format!("refs/heads/{name}"))? {
+ return Ok(args(&["switch", "-c", name, "--track", branch]));
+ }
+ // IDEA: a local namesake that is merely behind is fast-forwarded; one with commits
+ // of its own needs the user's choice.
+ let range = format!("{branch}..refs/heads/{name}");
+ let ahead = run(r.root(), &["rev-list", "--count", &range], None)?.stdout_str().trim() != "0";
+ return Ok(match (ahead, diverged) {
+ (true, None) => SwitchPlan::Ahead { local: name.to_string(), remote: branch.to_string() },
+ (true, Some(DivergedLocal::Rebase)) => {
+ SwitchPlan::Rebase { local: name.to_string(), remote: branch.to_string() }
+ }
+ _ => args(&["switch", "-C", name, "--track", branch]),
+ });
+ }
+ // A tag or commit: detached HEAD.
+ resolve(&repo, branch)?;
+ Ok(args(&["switch", "--detach", branch]))
+}
+
+/// Files git refuses to overwrite with local changes, from its error message.
+fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
+ let mut lines =
+ stderr.lines().skip_while(|l| !l.contains("local changes to the following files would be overwritten"));
+ lines.next()?;
+ Some(lines.take_while(|l| l.starts_with('\t')).map(|l| l.trim().to_string()).collect())
+}
+
+pub(crate) fn checkout_with(
+ r: &Repo,
+ branch: &str,
+ create: bool,
+ options: &CheckoutOptions,
+) -> IdeResult<CheckoutOutcome> {
+ let branch = branch.trim();
+ if branch.is_empty() {
+ return Err(IdeError::invalid("branch name is empty"));
+ }
+ if branch.starts_with('-') {
+ return Err(IdeError::invalid(format!("invalid revision '{branch}'")));
+ }
+ let mut args = match switch_plan(r, branch, create, options.diverged)? {
+ SwitchPlan::Ahead { local, remote } => return Ok(CheckoutOutcome::LocalBranchAhead { local, remote }),
+ SwitchPlan::Rebase { local, remote } => {
+ let out = cli::run_raw(r.root(), &["rebase", "--autostash", &remote, &local], None)?;
+ if out.code == Some(0) {
+ return Ok(CheckoutOutcome::Done);
+ }
+ let files = unmerged_paths(r)?;
+ if files.is_empty() {
+ return Err(cli::failure(&["rebase"], &out.stderr, &out.stdout, out.code));
+ }
+ return Ok(CheckoutOutcome::Conflicts { files });
+ }
+ SwitchPlan::Switch(args) => args,
+ };
+ if options.mode == CheckoutMode::Force {
+ args.push("--discard-changes".into());
+ }
+ let argv: Vec<&str> = args.iter().map(String::as_str).collect();
+ let out = cli::run_raw(r.root(), &argv, None)?;
+ if out.code == Some(0) {
+ return Ok(CheckoutOutcome::Done);
+ }
+ let Some(files) = overwritten_files(&String::from_utf8_lossy(&out.stderr)) else {
+ return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
+ };
+ if options.mode != CheckoutMode::Smart {
+ return Ok(CheckoutOutcome::LocalChanges { files });
+ }
+ // Smart Checkout: stash → switch → unstash, like IDEA.
+ let before = stash_count(r)?;
+ run(r.root(), &["stash", "push", "-q", "-m", &format!("Uncommitted changes before checkout of {branch}")], None)?;
+ if stash_count(r)? == before {
+ return Err(IdeError::invalid("could not save the local changes"));
+ }
+ if let Err(e) = run(r.root(), &argv, None) {
+ run(r.root(), &["stash", "pop", "-q", "--index"], None)?;
+ return Err(e);
+ }
+ let pop = cli::run_raw(r.root(), &["stash", "pop", "-q"], None)?;
+ if pop.code == Some(0) {
+ return Ok(CheckoutOutcome::Done);
+ }
+ let files = unmerged_paths(r)?;
+ if files.is_empty() {
+ return Err(cli::failure(&["stash", "pop"], &pop.stderr, &pop.stdout, pop.code));
+ }
+ Ok(CheckoutOutcome::Conflicts { files })
+}
+
+fn stash_count(r: &Repo) -> IdeResult<usize> {
+ Ok(run(r.root(), &["stash", "list"], None)?.stdout_str().lines().count())
+}
+
/// Creates `name` at `start` (default HEAD); a remote-tracking start point is tracked.
pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
let name = name.trim();
@@ -342,6 +540,39 @@ pub(crate) fn delete_branch(r: &Repo, branch: &str, force: bool) -> IdeResult<()
run(r.root(), &["branch", if force { "-D" } else { "-d" }, "--", branch], None).map(|_| ())
}
+pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult<DeletedBranch> {
+ check_local_branch(r, branch)?;
+ let tip = run(r.root(), &["rev-parse", "--verify", "-q", &format!("refs/heads/{branch}^{{commit}}")], None)?
+ .stdout_str()
+ .trim()
+ .to_string();
+ let upstream =
+ cli::run_raw(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?
+ .stdout_str()
+ .trim()
+ .to_string();
+ let out = cli::run_raw(r.root(), &["branch", "-d", "--", branch], None)?;
+ let unmerged = match out.code {
+ Some(0) => false,
+ _ if String::from_utf8_lossy(&out.stderr).contains("not fully merged") => {
+ run(r.root(), &["branch", "-D", "--", branch], None)?;
+ true
+ }
+ code => return Err(cli::failure(&["branch"], &out.stderr, &out.stdout, code)),
+ };
+ Ok(DeletedBranch { name: branch.to_string(), tip, upstream: (!upstream.is_empty()).then_some(upstream), unmerged })
+}
+
+pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()> {
+ let tip = check_rev(&deleted.tip)?;
+ run(r.root(), &["branch", "--", &deleted.name, tip], None)?;
+ if let Some(upstream) = &deleted.upstream {
+ let target = format!("--set-upstream-to={upstream}");
+ run(r.root(), &["branch", &target, "--", &deleted.name], None)?;
+ }
+ Ok(())
+}
+
pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str) -> IdeResult<()> {
let to = to.trim();
if to.is_empty() {
@@ -479,15 +710,25 @@ pub(crate) fn push_branch(
r: &Repo,
branch: &str,
revision: Option<&str>,
+ target: Option<&str>,
force_with_lease: bool,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
check_local_branch(r, branch)?;
- let (remote, target, set_upstream) = match branch_upstream(r, branch) {
+ let (remote, mut name, set_upstream) = match branch_upstream(r, branch) {
Some((remote, name)) => (remote, name, false),
None => (push_remote(r)?, branch.to_string(), revision.is_none()),
};
+ if let Some(t) = target.map(str::trim).filter(|t| !t.is_empty()) {
+ let valid =
+ !t.starts_with('-') && cli::run_raw(r.root(), &["check-ref-format", "--branch", t], None)?.code == Some(0);
+ if !valid {
+ return Err(IdeError::invalid(format!("'{t}' is not a valid branch name")));
+ }
+ name = t.to_string();
+ }
+ let target = name;
let source = match revision {
Some(rev) => check_rev(rev)?.to_string(),
None => format!("refs/heads/{branch}"),
diff --git a/crates/ide-vcs/tests/history_ops.rs b/crates/ide-vcs/tests/history_ops.rs
index f9ff882a9..f29c1d026 100644
--- a/crates/ide-vcs/tests/history_ops.rs
+++ b/crates/ide-vcs/tests/history_ops.rs
@@ -106,6 +106,47 @@ fn rebase_conflict_then_continue() {
assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), fx.git(&["rev-parse", "main"]));
}
+#[test]
+fn merge_versions_put_the_users_work_on_the_left() {
+ // Rebase: git's "ours" is main; the user's commit (topic) must be `ours` here.
+ let fx = diverged();
+ let repo = fx.repo();
+ let topic = fx.git(&["rev-parse", "topic"]);
+ assert!(repo.rebase("main").is_err());
+ let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
+ assert_eq!(v.ours.as_deref(), Some("topic\n"));
+ assert_eq!(v.theirs.as_deref(), Some("main\n"));
+ assert_eq!(v.base.as_deref(), Some("base\n"));
+ assert!(v.sides.reversed);
+ assert_eq!(v.sides.operation.as_deref(), Some("rebase"));
+ assert_eq!(v.sides.branch.as_deref(), Some("topic"));
+ assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
+ assert_eq!(v.sides.commit.as_deref(), Some(&topic[..8]));
+ let (cancel, out) = quiet();
+ repo.abort_operation(&cancel, &out).unwrap();
+
+ // Merge: not swapped; the merged branch is named.
+ assert!(repo.merge("main").is_err());
+ let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
+ assert_eq!(v.ours.as_deref(), Some("topic\n"));
+ assert_eq!(v.theirs.as_deref(), Some("main\n"));
+ assert!(!v.sides.reversed);
+ assert_eq!(v.sides.branch.as_deref(), Some("topic"));
+ assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
+ repo.abort_operation(&cancel, &out).unwrap();
+
+ // Cherry-pick: not swapped; the picked commit is named.
+ let main = fx.git(&["rev-parse", "main"]);
+ assert!(repo.cherry_pick(std::slice::from_ref(&main), &cancel, &out).is_err());
+ let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
+ assert_eq!(v.ours.as_deref(), Some("topic\n"));
+ assert!(!v.sides.reversed);
+ assert_eq!(v.sides.operation.as_deref(), Some("cherry-pick"));
+ assert_eq!(v.sides.commit.as_deref(), Some(&main[..8]));
+ repo.abort_operation(&cancel, &out).unwrap();
+ assert_eq!(repo.merge_sides().unwrap(), MergeSides { branch: Some("topic".into()), ..Default::default() });
+}
+
#[test]
fn rebase_conflict_then_abort_and_skip() {
let fx = diverged();
@@ -262,6 +303,11 @@ fn compare_with_local_lists_differences() {
got,
vec![("a.txt", ChangeKind::Modified), ("b.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]
);
+ // Between two revisions the working tree does not count.
+ let files = fx.repo().diff_revisions(&one, "HEAD").unwrap();
+ let got: Vec<(&str, ChangeKind)> = files.iter().map(|f| (f.path.as_str(), f.kind)).collect();
+ assert_eq!(got, vec![("a.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]);
+ assert!(fx.repo().diff_revisions("-x", "HEAD").is_err());
}
#[test]
@@ -448,6 +494,12 @@ fn push_branch_and_up_to_revision() {
assert_eq!(git_in(&bare, &["rev-parse", "side"]), c2);
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "side@{upstream}"]), "origin/side");
assert!(repo.push_branch("nope", None, false, &cancel, &out).is_err());
+
+ // An edited target: same remote, another branch name; the upstream stays as it was.
+ repo.push_branch_to("main", None, "review/main", false, &cancel, &out).unwrap();
+ assert_eq!(git_in(&bare, &["rev-parse", "review/main"]), c3);
+ assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "main@{upstream}"]), "origin/main");
+ assert!(repo.push_branch_to("main", None, "bad..name", false, &cancel, &out).is_err());
}
#[test]
diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs
index f785076b3..cc198bed4 100644
--- a/crates/ide-vcs/tests/repo.rs
+++ b/crates/ide-vcs/tests/repo.rs
@@ -770,6 +770,213 @@ fn checkout_create_detached_delete_rebase() {
assert!(repo.checkout("does-not-exist", false).is_err());
}
+#[test]
+fn smart_and_force_checkout_with_local_changes_in_the_way() {
+ let fx = Fixture::new();
+ fx.write("f.txt", "1\n2\n3\n4\n5\n");
+ fx.commit_all("base");
+ fx.git(&["checkout", "-q", "-b", "other"]);
+ fx.write("f.txt", "1\nother\n3\n4\n5\n");
+ fx.commit_all("other edit");
+ fx.git(&["checkout", "-q", "main"]);
+ let repo = fx.repo();
+ let opts = |mode| CheckoutOptions { mode, diverged: None };
+
+ // A non-conflicting local edit to a file the switch rewrites.
+ fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
+ let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Normal)).unwrap();
+ assert_eq!(outcome, CheckoutOutcome::LocalChanges { files: vec!["f.txt".into()] });
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
+ assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\nlocal\n");
+
+ let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
+ assert_eq!(outcome, CheckoutOutcome::Done);
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
+ assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n", "local change carried over");
+ assert!(repo.stashes().unwrap().is_empty(), "stash restored and dropped");
+
+ // A local edit that conflicts with the target: smart checkout leaves a conflict.
+ fx.git(&["checkout", "-q", "-f", "main"]);
+ fx.write("f.txt", "1\nmine\n3\n4\n5\n");
+ let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
+ assert_eq!(outcome, CheckoutOutcome::Conflicts { files: vec!["f.txt".into()] });
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
+ assert_eq!(repo.stashes().unwrap().len(), 1, "git keeps the stash after a conflicting pop");
+
+ // Force discards the change in the way.
+ fx.git(&["reset", "-q", "--hard"]);
+ fx.git(&["stash", "drop", "-q"]);
+ fx.write("f.txt", "1\nmine\n3\n4\n5\n");
+ fx.write("untouched.txt", "new\n");
+ let outcome = repo.checkout_with("main", false, &opts(CheckoutMode::Force)).unwrap();
+ assert_eq!(outcome, CheckoutOutcome::Done);
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
+ assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\n5\n");
+ assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
+}
+
+#[test]
+fn checkout_remote_branch_with_existing_local_namesake() {
+ let (fx, bare) = with_remote();
+ let repo = fx.repo();
+ // Another clone advances origin/main.
+ let other = fx._tmp.path().join("other");
+ git_in(fx._tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]);
+ configure(&other);
+ std::fs::write(other.join("b.txt"), "remote\n").unwrap();
+ git_in(&other, &["add", "-A"]);
+ git_in(&other, &["commit", "-q", "-m", "remote work"]);
+ git_in(&other, &["push", "-q", "origin", "main"]);
+ fx.git(&["fetch", "-q"]);
+ fx.git(&["checkout", "-q", "-b", "topic"]);
+ let none = CheckoutOptions::default();
+
+ // Local main is only behind: it is fast-forwarded and checked out.
+ assert_eq!(repo.checkout_with("origin/main", false, &none).unwrap(), CheckoutOutcome::Done);
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
+ assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
+
+ // Local main has its own commit: the user must choose; nothing changes meanwhile.
+ fx.write("c.txt", "local\n");
+ let local_tip = fx.commit_all("local work");
+ fx.git(&["checkout", "-q", "topic"]);
+ let outcome = repo.checkout_with("origin/main", false, &none).unwrap();
+ assert_eq!(outcome, CheckoutOutcome::LocalBranchAhead { local: "main".into(), remote: "origin/main".into() });
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
+
+ // Rebase onto Remote keeps the local commit on top of origin/main.
+ let rebase = CheckoutOptions { diverged: Some(DivergedLocal::Rebase), ..Default::default() };
+ assert_eq!(repo.checkout_with("origin/main", false, &rebase).unwrap(), CheckoutOutcome::Done);
+ assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
+ assert_eq!(fx.git(&["rev-parse", "main~1"]), fx.git(&["rev-parse", "origin/main"]));
+ assert_eq!(fx.git(&["log", "-1", "--format=%s"]), "local work");
+
+ // Drop Local Commits resets main to origin/main.
+ fx.git(&["checkout", "-q", "topic"]);
+ let reset = CheckoutOptions { diverged: Some(DivergedLocal::Reset), ..Default::default() };
+ assert_eq!(repo.checkout_with("origin/main", false, &reset).unwrap(), CheckoutOutcome::Done);
+ assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
+ assert_ne!(fx.git(&["rev-parse", "main"]), local_tip);
+ assert_eq!(repo.branch_info().unwrap().upstream.as_deref(), Some("origin/main"));
+}
+
+#[test]
+fn delete_branch_without_asking_and_restore_it() {
+ let (fx, _bare) = with_remote();
+ let repo = fx.repo();
+ fx.git(&["checkout", "-q", "-b", "merged", "--track", "origin/main"]);
+ fx.git(&["checkout", "-q", "-b", "work"]);
+ fx.write("w.txt", "work\n");
+ let work_tip = fx.commit_all("work");
+ fx.git(&["checkout", "-q", "main"]);
+
+ let merged = repo.delete_branch_restorable("merged").unwrap();
+ assert!(!merged.unmerged);
+ assert_eq!(merged.upstream.as_deref(), Some("origin/main"));
+
+ let work = repo.delete_branch_restorable("work").unwrap();
+ assert!(work.unmerged, "not fully merged branches are force-deleted and reported");
+ assert_eq!(work.tip, work_tip);
+ assert!(!repo.branches().unwrap().iter().any(|b| b.name == "work"));
+ assert!(repo.delete_branch_restorable("main").is_err(), "the current branch cannot be deleted");
+
+ repo.restore_branch(&work).unwrap();
+ repo.restore_branch(&merged).unwrap();
+ let branches = repo.branches().unwrap();
+ let find = |n: &str| branches.iter().find(|b| !b.remote && b.name == n).unwrap().clone();
+ assert_eq!(find("work").commit, work_tip);
+ assert_eq!(find("merged").upstream.as_deref(), Some("origin/main"));
+}
+
+fn range(h: &LineHunk) -> HunkRange {
+ HunkRange { start: h.start, lines: h.lines, old_start: h.old_start, old_lines: h.old_lines }
+}
+
+#[test]
+fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
+ let fx = Fixture::new();
+ let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
+ fx.write("f.txt", base);
+ fx.write("other.txt", "o\n");
+ fx.write("staged.txt", "s\n");
+ fx.commit_all("base");
+ let repo = fx.repo();
+
+ let edited = "A\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\n";
+ fx.write("f.txt", edited);
+ fx.write("other.txt", "o2\n");
+ fx.write("staged.txt", "s2\n");
+ repo.stage(&[fx.path("other.txt")]).unwrap();
+ let hunks = diff_hunks(base, edited);
+ assert_eq!(hunks.len(), 2);
+
+ // Commit the first hunk of f.txt plus the staged other.txt; staged.txt is not staged.
+ let options = CommitOptions {
+ partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
+ ..Default::default()
+ };
+ repo.commit_with("partial", &options).unwrap();
+
+ assert_eq!(fx.git(&["show", "HEAD:f.txt"]), "A\nb\nc\nd\ne\nf\ng\nh\ni\nj");
+ assert_eq!(fx.git(&["show", "HEAD:other.txt"]), "o2");
+ assert_eq!(fx.git(&["show", "HEAD:staged.txt"]), "s");
+ // The working tree is untouched.
+ assert_eq!(fx.read("f.txt"), edited);
+ assert_eq!(fx.read("staged.txt"), "s2\n");
+ // The index matches the commit; the rest of f.txt is an unstaged change.
+ assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
+ let st = repo.status().unwrap();
+ assert_eq!(status_of(&st, "f.txt").unstaged, Some(ChangeKind::Modified));
+ assert_eq!(status_of(&st, "f.txt").staged, None);
+ assert!(!fx.dir.join(".git/openidea-partial-index").exists());
+
+ // A stale hunk (the file changed since the UI computed it) refuses to commit anything.
+ let before = fx.git(&["rev-parse", "HEAD"]);
+ let stale = CommitOptions {
+ partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
+ ..Default::default()
+ };
+ let err = repo.commit_with("stale", &stale).unwrap_err();
+ assert!(err.message.contains("changed"), "{}", err.message);
+ assert_eq!(fx.git(&["rev-parse", "HEAD"]), before);
+ assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
+ assert!(!fx.dir.join(".git/openidea-partial-index").exists());
+
+ // The remaining hunk commits on its own; then nothing is left.
+ let rest = diff_hunks(&repo.file_at(&fx.path("f.txt"), None).unwrap().unwrap(), edited);
+ assert_eq!(rest.len(), 1);
+ let options = CommitOptions {
+ partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&rest[0])] }],
+ ..Default::default()
+ };
+ repo.commit_with("rest", &options).unwrap();
+ assert_eq!(repo.file_at(&fx.path("f.txt"), None).unwrap().as_deref(), Some(edited));
+ assert!(repo.status().unwrap().iter().all(|f| f.rel_path != "f.txt"));
+ assert_eq!(fx.read("staged.txt"), "s2\n");
+
+ // A failing pre-commit hook leaves everything as it was.
+ fx.write("f.txt", "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
+ let hook = fx.dir.join(".git/hooks/pre-commit");
+ std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
+ std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let head = fx.git(&["rev-parse", "HEAD"]);
+ let hunks = diff_hunks(edited, &fx.read("f.txt"));
+ let options = CommitOptions {
+ run_hooks: true,
+ partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
+ ..Default::default()
+ };
+ assert!(repo.commit_with("hooked", &options).is_err());
+ assert_eq!(fx.git(&["rev-parse", "HEAD"]), head);
+ assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
+ assert_eq!(fx.read("f.txt"), "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
+}
+
#[test]
fn partial_staging_with_built_patch() {
let fx = Fixture::new();
diff --git a/crates/ide-workspace/src/file_refs.rs b/crates/ide-workspace/src/file_refs.rs
new file mode 100644
index 000000000..d2484aa61
--- /dev/null
+++ b/crates/ide-workspace/src/file_refs.rs
@@ -0,0 +1,212 @@
+//! File references in text (`href="css/a.css"`, `url(../img/x.png)`,
+//! `open("data/x.csv")`), resolved like IDEA's file references: relative to the
+//! referencing file, `/`-rooted paths against the project root and its resource
+//! roots (`public/`, `src/main/resources`), which web servers serve at `/`.
+
+use std::path::{Component, Path, PathBuf};
+
+/// Whether `value` names a local file at all (not a URL, an anchor, a data URI
+/// or a template expression), so an unresolved one is worth reporting.
+pub fn is_file_reference(value: &str) -> bool {
+ let v = value.trim();
+ !(v.is_empty()
+ || v.starts_with('#')
+ || v.starts_with("//")
+ || v.starts_with('~')
+ || has_scheme(v)
+ || ["{{", "${", "<%", "{%", "<?", "@{"].iter().any(|t| v.contains(t)))
+}
+
+/// `http:`, `mailto:`, `data:`, `javascript:`… (a Windows drive `C:` is a path).
+fn has_scheme(v: &str) -> bool {
+ match v.find(':') {
+ Some(i) if i > 1 => v[..i].chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)),
+ _ => false,
+ }
+}
+
+/// The path part: no `?query` / `#fragment`, percent-decoded.
+pub fn path_part(value: &str) -> String {
+ let bare = value.trim().split(['?', '#']).next().unwrap_or_default();
+ percent_decode(bare)
+}
+
+fn percent_decode(s: &str) -> String {
+ let bytes = s.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%'
+ && let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
+ {
+ out.push(b);
+ i += 3;
+ continue;
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8(out).unwrap_or_else(|_| s.to_owned())
+}
+
+/// Removes `.` and resolves `..` lexically.
+fn normalize(path: &Path) -> PathBuf {
+ let mut out = PathBuf::new();
+ for c in path.components() {
+ match c {
+ Component::CurDir => {}
+ Component::ParentDir => {
+ if !out.pop() {
+ out.push("..");
+ }
+ }
+ other => out.push(other),
+ }
+ }
+ out
+}
+
+/// Directories a reference's path is looked up in, most likely first.
+pub fn base_dirs(path: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
+ // A file outside the project is not served from its roots.
+ let root = root.filter(|r| from.starts_with(r));
+ let mut dirs: Vec<PathBuf> = Vec::new();
+ if path.starts_with('/') {
+ dirs.extend(root.map(Path::to_path_buf));
+ if root.is_some() {
+ dirs.extend(resource_roots.iter().cloned());
+ }
+ dirs.push(PathBuf::from("/"));
+ } else {
+ dirs.extend(from.parent().map(Path::to_path_buf));
+ // `img/a.png` from a page served at the root; never for `./` or `../`.
+ if !path.starts_with('.') {
+ dirs.extend(root.map(Path::to_path_buf));
+ }
+ }
+ let mut seen = Vec::new();
+ dirs.retain(|d| {
+ let fresh = !seen.contains(d);
+ seen.push(d.clone());
+ fresh
+ });
+ dirs
+}
+
+/// Paths `value` may point at, most likely first.
+pub fn candidates(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
+ let path = path_part(value);
+ let rel = path.trim_start_matches('/');
+ base_dirs(&path, from, root, resource_roots).iter().map(|d| normalize(&d.join(rel))).collect()
+}
+
+/// The existing file or directory `value` names, if any.
+pub fn resolve(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Option<PathBuf> {
+ if !is_file_reference(value) || path_part(value).is_empty() {
+ return None;
+ }
+ candidates(value, from, root, resource_roots).into_iter().find(|p| p.exists())
+}
+
+/// An entry offered when completing a path.
+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PathCompletion {
+ pub name: String,
+ pub dir: bool,
+}
+
+/// Entries of the directories `prefix` (the path typed so far) continues in:
+/// the part before its last `/`, looked up like a reference. Dot files only
+/// when the last segment starts with `.`.
+pub fn complete(prefix: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathCompletion> {
+ let prefix = percent_decode(prefix);
+ let (dir_part, last) = prefix.rsplit_once('/').map_or(("", prefix.as_str()), |(d, l)| (d, l));
+ let dir_value =
+ if prefix.starts_with('/') { format!("/{}", dir_part.trim_start_matches('/')) } else { dir_part.to_owned() };
+ let show_hidden = last.starts_with('.');
+ let rel = dir_value.trim_start_matches('/');
+ let mut out: Vec<PathCompletion> = Vec::new();
+ for base in base_dirs(&dir_value, from, root, resource_roots) {
+ // The file system root only as a last resort for `/` paths.
+ if base == Path::new("/") && !out.is_empty() {
+ continue;
+ }
+ let Ok(entries) = std::fs::read_dir(normalize(&base.join(rel))) else { continue };
+ for e in entries.flatten() {
+ let name = e.file_name().to_string_lossy().into_owned();
+ if (name.starts_with('.') && !show_hidden) || out.iter().any(|c| c.name == name) {
+ continue;
+ }
+ let dir = e.file_type().is_ok_and(|t| t.is_dir()) || e.path().is_dir();
+ out.push(PathCompletion { name, dir });
+ }
+ }
+ out.sort_by(|a, b| b.dir.cmp(&a.dir).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn what_counts_as_a_file_reference() {
+ for v in ["a.css", "./a", "../img/x.png", "/splash.css", "a%20b.png?v=1#x", "C:/x"] {
+ assert!(is_file_reference(v), "{v}");
+ }
+ for v in [
+ "",
+ "#top",
+ "https://x.org",
+ "//cdn.x/a.js",
+ "mailto:a@b",
+ "data:image/png;base64,x",
+ "{{ url }}",
+ "${base}/a.js",
+ "~/x",
+ ] {
+ assert!(!is_file_reference(v), "{v}");
+ }
+ assert_eq!(path_part(" img/a%20b.png?v=2#i "), "img/a b.png");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn candidates_follow_ideas_rules() {
+ let from = Path::new("/p/web/pages/index.html");
+ let root = Some(Path::new("/p"));
+ let res = [PathBuf::from("/p/public")];
+ let s = |v| candidates(v, from, root, &res).into_iter().map(|p| p.display().to_string()).collect::<Vec<_>>();
+ assert_eq!(s("../img/a.png"), ["/p/web/img/a.png"]);
+ assert_eq!(s("img/a.png"), ["/p/web/pages/img/a.png", "/p/img/a.png"]);
+ assert_eq!(s("/splash.css"), ["/p/splash.css", "/p/public/splash.css", "/splash.css"]);
+ }
+
+ #[test]
+ fn resolves_and_completes_against_the_file_system() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ for f in ["web/index.html", "web/css/a.css", "web/css/.hidden", "public/splash.css", "public/img/logo.svg"] {
+ let p = root.join(f);
+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+ std::fs::write(p, "").unwrap();
+ }
+ let from = root.join("web/index.html");
+ let res = [root.join("public")];
+ let r = |v| resolve(v, &from, Some(root), &res);
+ assert_eq!(r("css/a.css?v=1"), Some(root.join("web/css/a.css")));
+ assert_eq!(r("/splash.css"), Some(root.join("public/splash.css")));
+ assert_eq!(r("css/missing.css"), None);
+ assert_eq!(r("https://x.org/a.css"), None);
+
+ let names = |p| complete(p, &from, Some(root), &res).into_iter().map(|c| (c.name, c.dir)).collect::<Vec<_>>();
+ assert_eq!(names("css/"), [("a.css".into(), false)]);
+ assert_eq!(names("css/."), [(".hidden".into(), false), ("a.css".into(), false)]);
+ assert_eq!(
+ names("/im"),
+ [("img".into(), true), ("public".into(), true), ("web".into(), true), ("splash.css".into(), false)]
+ );
+ assert_eq!(names("/img/"), [("logo.svg".into(), false)]);
+ }
+}
diff --git a/crates/ide-workspace/src/lib.rs b/crates/ide-workspace/src/lib.rs
index 5e9aca7b9..ab8ac7592 100644
--- a/crates/ide-workspace/src/lib.rs
+++ b/crates/ide-workspace/src/lib.rs
@@ -5,6 +5,7 @@ pub mod documents;
pub mod editorconfig;
pub mod file_defaults;
pub mod file_moves;
+pub mod file_refs;
pub mod history;
pub mod memory;
pub mod process;
diff --git a/crates/ide-workspace/src/roots/mod.rs b/crates/ide-workspace/src/roots/mod.rs
index ec15be05c..126c5a520 100644
--- a/crates/ide-workspace/src/roots/mod.rs
+++ b/crates/ide-workspace/src/roots/mod.rs
@@ -107,6 +107,11 @@ impl ProjectRoots {
}
}
+ /// Effective resource folders (project-relative): served at `/` for web file references.
+ pub fn resource_dirs(&self) -> Vec<&str> {
+ self.roots.iter().filter(|r| r.kind == RootKind::Resources).map(|r| r.path.as_str()).collect()
+ }
+
/// Effective excluded folders as anchored globs (`/target`), for the index, watcher and search.
pub fn excluded_globs(&self) -> Vec<String> {
self.roots
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index e3f462486..c3d025307 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -103,7 +103,11 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
nav::find_symbols,
nav::mark_recent,
nav::recent_files,
+ nav::remove_recent,
nav::web_goto,
+ nav::fs_resolve_reference,
+ nav::path_completions,
+ nav::web_unresolved_references,
search::search_start,
search::replace_in_files,
search::replace_preview,
@@ -150,6 +154,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_commit,
vcs::vcs_checkout,
vcs::vcs_delete_branch,
+ vcs::vcs_restore_branch,
vcs::vcs_create_branch,
vcs::vcs_undo_commit,
vcs::vcs_rename_branch,
@@ -171,6 +176,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_create_tag,
vcs::vcs_tags,
vcs::vcs_diff_with_worktree,
+ vcs::vcs_diff_revisions,
vcs::vcs_create_patch,
vcs::vcs_patch_preview,
vcs::vcs_apply_patch,
@@ -187,6 +193,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
term::term_write,
term::term_resize,
term::term_kill,
+ term::term_is_busy,
term::term_default_shell,
term::term_available_shells,
run::run_configs,
diff --git a/src-tauri/src/commands/nav.rs b/src-tauri/src/commands/nav.rs
index eb20d9e1a..252d0f656 100644
--- a/src-tauri/src/commands/nav.rs
+++ b/src-tauri/src/commands/nav.rs
@@ -1,8 +1,9 @@
use super::doc::blocking;
-use crate::state::AppState;
-use ide_core::{DocId, IdeResult, Location, Pos};
+use crate::state::{AppState, Project};
+use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
-use ide_language::WebReference;
+use ide_language::{FileReference, WebReference};
+use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
@@ -39,6 +40,13 @@ pub fn mark_recent(window: Window, state: State<'_, AppState>, path: PathBuf) ->
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+pub fn remove_recent(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
+ state.project(window.label())?.index.remove_recent(&path);
+ Ok(())
+}
+
/// Recently opened files, most recent first (⌘E).
#[tauri::command]
#[specta::specta]
@@ -96,3 +104,74 @@ pub async fn web_goto(window: Window, state: State<'_, AppState>, doc: DocId, po
})
.await
}
+
+/// The project root and its resource roots (served at `/`), for file references.
+fn reference_roots(project: &Project) -> (PathBuf, Vec<PathBuf>) {
+ let resources = project.roots().resource_dirs().iter().map(|d| project.root.join(d)).collect();
+ (project.root.clone(), resources)
+}
+
+/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
+#[tauri::command]
+#[specta::specta]
+pub async fn fs_resolve_reference(
+ window: Window,
+ state: State<'_, AppState>,
+ from: IpcPath,
+ value: String,
+) -> IdeResult<Option<IpcPath>> {
+ let project = state.project(window.label()).ok();
+ blocking(move || {
+ let (root, resources) = project.as_deref().map(reference_roots).unzip();
+ let resources = resources.unwrap_or_default();
+ Ok(file_refs::resolve(&value, &from, root.as_deref(), &resources).map(Into::into))
+ })
+ .await
+}
+
+/// Files and folders that continue `prefix`, a path being typed in `from`.
+#[tauri::command]
+#[specta::specta]
+pub async fn path_completions(
+ window: Window,
+ state: State<'_, AppState>,
+ from: IpcPath,
+ prefix: String,
+) -> IdeResult<Vec<PathCompletion>> {
+ let project = state.project(window.label()).ok();
+ blocking(move || {
+ let (root, resources) = project.as_deref().map(reference_roots).unzip();
+ let resources = resources.unwrap_or_default();
+ Ok(file_refs::complete(&prefix, &from, root.as_deref(), &resources))
+ })
+ .await
+}
+
+/// Paths in an HTML document or stylesheet that name no existing file.
+#[tauri::command]
+#[specta::specta]
+pub async fn web_unresolved_references(
+ window: Window,
+ state: State<'_, AppState>,
+ doc: DocId,
+) -> IdeResult<Vec<FileReference>> {
+ let project = state.project(window.label())?;
+ let syntax = state.syntax();
+ blocking(move || {
+ let snap = project.documents.snapshot(doc)?;
+ if snap.large {
+ return Ok(Vec::new());
+ }
+ let (root, resources) = reference_roots(&project);
+ Ok(syntax
+ .web_file_references(&snap.language, &snap.text)
+ .into_iter()
+ .filter(|r| {
+ file_refs::is_file_reference(&r.value)
+ && !file_refs::path_part(&r.value).is_empty()
+ && file_refs::resolve(&r.value, &snap.path, Some(&root), &resources).is_none()
+ })
+ .collect())
+ })
+ .await
+}
diff --git a/src-tauri/src/commands/term.rs b/src-tauri/src/commands/term.rs
index a510080df..07401d208 100644
--- a/src-tauri/src/commands/term.rs
+++ b/src-tauri/src/commands/term.rs
@@ -48,6 +48,14 @@ pub fn term_kill(state: State<'_, AppState>, id: TerminalId) -> IdeResult<()> {
state.terminals.kill(id)
}
+/// Whether the session is running a command (closing its tab asks first). A
+/// `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
+#[tauri::command]
+#[specta::specta]
+pub async fn term_is_busy(state: State<'_, AppState>, id: TerminalId) -> IdeResult<bool> {
+ state.terminals.is_busy(id)
+}
+
/// Shell used when Settings › Terminal › Shell path is empty.
#[tauri::command]
#[specta::specta]
diff --git a/src-tauri/src/commands/vcs.rs b/src-tauri/src/commands/vcs.rs
index 42ec9c4ee..1dbc9baf6 100644
--- a/src-tauri/src/commands/vcs.rs
+++ b/src-tauri/src/commands/vcs.rs
@@ -185,10 +185,15 @@ pub async fn vcs_checkout(
repo: Option<PathBuf>,
branch: String,
create: bool,
-) -> IdeResult<()> {
+ options: Option<ide_vcs::CheckoutOptions>,
+) -> IdeResult<ide_vcs::CheckoutOutcome> {
let project = state.project(window.label())?;
- blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout(&branch, create)))
- .await
+ let options = options.unwrap_or_default();
+ blocking(move || {
+ project
+ .with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout_with(&branch, create, &options))
+ })
+ .await
}
/// New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out.
@@ -231,10 +236,22 @@ pub async fn vcs_delete_branch(
state: State<'_, AppState>,
repo: Option<PathBuf>,
branch: String,
- force: bool,
+) -> IdeResult<ide_vcs::DeletedBranch> {
+ let project = state.project(window.label())?;
+ blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch_restorable(&branch))).await
+}
+
+/// "Restore" of the branch-deleted notification.
+#[tauri::command]
+#[specta::specta]
+pub async fn vcs_restore_branch(
+ window: Window,
+ state: State<'_, AppState>,
+ repo: Option<PathBuf>,
+ deleted: ide_vcs::DeletedBranch,
) -> IdeResult<()> {
let project = state.project(window.label())?;
- blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch(&branch, force))).await
+ blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_branch(&deleted))).await
}
#[tauri::command]
@@ -336,11 +353,14 @@ pub enum RemoteOp {
DeleteBranch {
branch: String,
},
- /// Pushes local `branch` (only up to `revision` when set) to its upstream.
+ /// Pushes local `branch` (only up to `revision` when set) to its upstream, or to
+ /// remote branch `target` of the same remote.
PushBranch {
branch: String,
revision: Option<String>,
force_with_lease: bool,
+ #[serde(default)]
+ target: Option<String>,
},
/// Fast-forwards local `branch` (not checked out) to its upstream.
UpdateBranch {
@@ -373,9 +393,12 @@ pub async fn vcs_remote(
r.push_with_tags(force_with_lease, set_upstream, tags, &cancel, &out)
}
RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out),
- RemoteOp::PushBranch { branch, revision, force_with_lease } => {
- r.push_branch(&branch, revision.as_deref(), force_with_lease, &cancel, &out)
- }
+ RemoteOp::PushBranch { branch, revision, force_with_lease, target } => match target {
+ Some(target) => {
+ r.push_branch_to(&branch, revision.as_deref(), &target, force_with_lease, &cancel, &out)
+ }
+ None => r.push_branch(&branch, revision.as_deref(), force_with_lease, &cancel, &out),
+ },
RemoteOp::UpdateBranch { branch } => r.update_branch(&branch, &cancel, &out),
})
})
@@ -385,27 +408,16 @@ pub async fn vcs_remote(
result
}
-#[derive(Serialize, Deserialize, Type)]
-pub struct ConflictVersions {
- pub base: Option<String>,
- pub ours: Option<String>,
- pub theirs: Option<String>,
-}
-
+/// The user's side is `ours` (sides swapped during a rebase, as in IDEA).
#[tauri::command]
#[specta::specta]
pub async fn vcs_conflict_versions(
window: Window,
state: State<'_, AppState>,
path: PathBuf,
-) -> IdeResult<ConflictVersions> {
+) -> IdeResult<ide_vcs::MergeVersions> {
let project = state.project(window.label())?;
- blocking(move || {
- project.with_repo_of(&path, |r| {
- r.conflict_versions(&path).map(|(base, ours, theirs)| ConflictVersions { base, ours, theirs })
- })
- })
- .await
+ blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path))).await
}
#[tauri::command]
@@ -622,6 +634,20 @@ pub async fn vcs_diff_with_worktree(
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
}
+/// Files that differ between two revisions (the "N files updated" of Update Project).
+#[tauri::command]
+#[specta::specta]
+pub async fn vcs_diff_revisions(
+ window: Window,
+ state: State<'_, AppState>,
+ repo: Option<PathBuf>,
+ from: String,
+ to: String,
+) -> IdeResult<Vec<ChangedFile>> {
+ let project = state.project(window.label())?;
+ blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
+}
+
/// Runs `f` once per repository with the `paths` that belong to it.
fn per_repo(
project: &Project,
diff --git a/src/bindings.ts b/src/bindings.ts
index 7ccc71a16..2d57f0ac8 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -186,11 +186,18 @@ export const commands = {
markRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("mark_recent", { path })),
/** Recently opened files, most recent first (⌘E). */
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
+ removeRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remove_recent", { path })),
/** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */
webGoto: (doc: DocId, pos: Pos) => typedError<{
reference: WebReference,
targets: Location[],
} | null, IdeError>(__TAURI_INVOKE("web_goto", { doc, pos })),
+ /** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
+ fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
+ /** Files and folders that continue `prefix`, a path being typed in `from`. */
+ pathCompletions: (from: IpcPath, prefix: string) => typedError<PathCompletion[], IdeError>(__TAURI_INVOKE("path_completions", { from, prefix })),
+ /** Paths in an HTML document or stylesheet that name no existing file. */
+ webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -284,8 +291,14 @@ export const commands = {
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
vcsCommit: (repo: string | null, message: string, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { repo, message, options })),
- vcsCheckout: (repo: string | null, branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create })),
- vcsDeleteBranch: (repo: string | null, branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch, force })),
+ vcsCheckout: (repo: string | null, branch: string, create: boolean, options: {
+ mode?: CheckoutMode,
+ /** Required when checking out a remote branch whose local namesake is ahead of it. */
+ diverged?: DivergedLocal | null,
+} | null) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })),
+ vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
+ /** "Restore" of the branch-deleted notification. */
+ vcsRestoreBranch: (repo: string | null, deleted: DeletedBranch) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_branch", { repo, deleted })),
/** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */
vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout })),
/**
@@ -301,7 +314,8 @@ export const commands = {
vcsStashDrop: (repo: string | null, index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { repo, index })),
/** Network operation; progress lines stream through `on_output`. Cancellable. */
vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput })),
- vcsConflictVersions: (path: string) => typedError<ConflictVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
+ /** The user's side is `ours` (sides swapped during a rebase, as in IDEA). */
+ vcsConflictVersions: (path: string) => typedError<MergeVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
@@ -330,6 +344,8 @@ export const commands = {
vcsTags: (repo: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags", { repo })),
/** Compare with Local: tracked files that differ between `rev` and the working tree. */
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
+ /** Files that differ between two revisions (the "N files updated" of Update Project). */
+ vcsDiffRevisions: (repo: string | null, from: string, to: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_revisions", { repo, from, to })),
vcsCreatePatch: (source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { source })),
vcsPatchPreview: (patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { patch })),
vcsApplyPatch: (patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { patch })),
@@ -352,14 +368,19 @@ export const commands = {
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
+ /**
+ * Whether the session is running a command (closing its tab asks first). A
+ * `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
+ */
+ termIsBusy: (id: TerminalId) => typedError<boolean, IdeError>(__TAURI_INVOKE("term_is_busy", { id })),
/** Shell used when Settings › Terminal › Shell path is empty. */
termDefaultShell: () => __TAURI_INVOKE<string>("term_default_shell"),
/** Installed shells for the Terminal's "New Predefined Session" menu. */
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
/** Detected configs followed by user-defined ones (user ids win on conflict). */
- runConfigs: () => typedError<RunConfig[], IdeError>(__TAURI_INVOKE("run_configs")),
- runSaveConfigs: (configs: RunConfig[]) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs })),
- runStart: (config: RunConfig, onOutput: Channel<OutputChunk>) => typedError<RunInfo, IdeError>(__TAURI_INVOKE("run_start", { config, onOutput })),
+ runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
+ runSaveConfigs: (configs: RunConfig_Deserialize[]) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs })),
+ runStart: (config: RunConfig_Deserialize, onOutput: Channel<OutputChunk>) => typedError<RunInfo, IdeError>(__TAURI_INVOKE("run_start", { config, onOutput })),
runStop: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_stop", { id })),
runStdin: (id: RunId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("run_stdin", { id, data })),
runList: () => __TAURI_INVOKE<RunInfo[]>("run_list"),
@@ -515,7 +536,7 @@ export const commands = {
* How to run `config` with coverage: the command to launch and where its report will be,
* or which tool is missing.
*/
- coveragePrepare: (config: RunConfig) => typedError<CoveragePrepared, IdeError>(__TAURI_INVOKE("coverage_prepare", { config })),
+ coveragePrepare: (config: RunConfig_Deserialize) => typedError<CoveragePrepared_Serialize, IdeError>(__TAURI_INVOKE("coverage_prepare", { config })),
/** Reads the report a coverage run left behind. */
coverageCollect: (report: CoverageReportSpec) => typedError<CoverageSuite, IdeError>(__TAURI_INVOKE("coverage_collect", { report })),
/** The browsers installed on this machine. */
@@ -525,7 +546,7 @@ export const commands = {
/** Opens `url` in `browser` (an id from `web_browsers`), or the default browser. */
webOpen: (url: string, browser: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("web_open", { url, browser })),
/** How to run `config` under a sampling profiler, or which profiler is missing. */
- profilerPrepare: (config: RunConfig) => typedError<ProfilePrepared, IdeError>(__TAURI_INVOKE("profiler_prepare", { config })),
+ profilerPrepare: (config: RunConfig_Deserialize) => typedError<ProfilePrepared_Serialize, IdeError>(__TAURI_INVOKE("profiler_prepare", { config })),
/** Reads the profile a profiled run left behind. */
profilerCollect: (spec: ProfileSpec) => typedError<Profile, IdeError>(__TAURI_INVOKE("profiler_collect", { spec })),
/** Routes this window's plugin events to `on_event` (replaces an earlier subscription). */
@@ -969,6 +990,39 @@ export type ChangelistState = {
export type CheckStatus = "pending" | "success" | "failure" | "cancelled" | "skipped" | "neutral";
+/**
+ * How Checkout treats local changes that the switch would overwrite (IDEA's Smart
+ * Checkout dialog).
+ */
+export type CheckoutMode =
+/** Fail with [`CheckoutOutcome::LocalChanges`] and change nothing. */
+"normal" |
+/** Stash local changes, switch, and restore them (conflicts are left to resolve). */
+"smart" |
+/** Discard the local changes in the way (`git switch --discard-changes`). */
+"force";
+
+export type CheckoutOptions = {
+ mode?: CheckoutMode,
+ /** Required when checking out a remote branch whose local namesake is ahead of it. */
+ diverged?: DivergedLocal | null,
+};
+
+/**
+ * Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
+ * left the repository untouched.
+ */
+export type CheckoutOutcome = { kind: "done" } |
+/** These local changes (repository-relative paths) would be overwritten. */
+{ kind: "localChanges"; files: string[] } |
+/** Local branch `local` has commits that remote branch `remote` does not. */
+{ kind: "localBranchAhead"; local: string; remote: string } |
+/**
+ * Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
+ * on conflicts in these files.
+ */
+{ kind: "conflicts"; files: string[] };
+
export type ClearCachesResult = {
/** Syntax trees dropped (they are rebuilt on demand). */
syntaxTrees: number,
@@ -1086,6 +1140,12 @@ export type CommitOptions = {
author: string | null,
/** False skips the pre-commit and commit-msg hooks (`--no-verify`). */
runHooks: boolean,
+ /**
+ * Files committed with only some of their changes (IDEA's partial commit). They are
+ * committed through a temporary index, so neither the working tree nor the other
+ * entries of the index change; afterwards their index entries match the new commit.
+ */
+ partial?: PartialCommitFile[],
};
/** Version Control › Commit: commit checks and commit-message inspections. */
@@ -1157,12 +1217,6 @@ export type ComposeOp = "start" | "stop" | "restart" |
/** Stops and removes the project's containers and networks. */
"down";
-export type ConflictVersions = {
- base: string | null,
- ours: string | null,
- theirs: string | null,
-};
-
/** Build, Execution, Deployment › Console. */
export type ConsoleSettings = {
softWrap?: boolean,
@@ -1176,9 +1230,15 @@ export type ConsoleSettings = {
export type ContainerOp = "start" | "stop" | "restart" | "pause" | "unpause" | "kill";
-export type CoveragePrepared = { status: "ready"; runner: string;
+export type CoveragePrepared = CoveragePrepared_Serialize | CoveragePrepared_Deserialize;
+
+export type CoveragePrepared_Deserialize = ({ status: "ready"; runner: string;
/** What to launch instead of the configuration. */
-launch: RunConfig; report: CoverageReportSpec } | { status: "missingTool"; tool: string; message: string; install: InstallCommand | null } | { status: "unsupported"; reason: string };
+launch: RunConfig_Deserialize; report: CoverageReportSpec }) & { install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: InstallCommand | null }) & { launch?: never; reason?: never; report?: never; runner?: never } | ({ status: "unsupported"; reason: string }) & { install?: never; launch?: never; message?: never; report?: never; runner?: never; tool?: never };
+
+export type CoveragePrepared_Serialize = ({ status: "ready"; runner: string;
+/** What to launch instead of the configuration. */
+launch: RunConfig_Serialize; report: CoverageReportSpec }) & { install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: InstallCommand | null }) & { launch?: never; reason?: never; report?: never; runner?: never } | ({ status: "unsupported"; reason: string }) & { install?: never; launch?: never; message?: never; report?: never; runner?: never; tool?: never };
/** Where the report of a prepared run will be, and how to read it. */
export type CoverageReportSpec =
@@ -1452,6 +1512,17 @@ export type DebuggerSettings = {
python?: PythonDebuggerSettings,
};
+/** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */
+export type DeletedBranch = {
+ name: string,
+ /** The commit the branch pointed at. */
+ tip: string,
+ /** Its upstream (`origin/x`), restored with it. */
+ upstream: string | null,
+ /** It was not fully merged: its own commits are now unreachable from any branch. */
+ unmerged: boolean,
+};
+
export type Diagnostic = {
range: Range,
severity: Severity,
@@ -1471,6 +1542,13 @@ export type DirectoryHistory = {
deleted: IpcPath[],
};
+/** Checking out remote `origin/x` while local `x` has commits `origin/x` lacks. */
+export type DivergedLocal =
+/** Rebase local `x` onto `origin/x` (IDEA "Rebase onto Remote"). */
+"rebase" |
+/** Reset local `x` to `origin/x` (IDEA "Drop Local Commits"). */
+"reset";
+
/** An open document buffer. */
export type DocId = number;
@@ -1918,6 +1996,12 @@ export type FileProbe = {
tooLarge: boolean,
};
+/** A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`. */
+export type FileReference = {
+ range: Range,
+ value: string,
+};
+
/** Reference updates for a file / folder move (`workspace/willRenameFiles`). */
export type FileRenameEdits = {
/** Edits of every server that took part, in terms of the paths before the move. */
@@ -2217,6 +2301,14 @@ export type HttpResponse = {
export type HunkKind = "added" | "modified" | "deleted";
+/** A hunk identified by its line ranges (0-based), see [`LineHunk`]. */
+export type HunkRange = {
+ start: number,
+ lines: number,
+ oldStart: number,
+ oldLines: number,
+};
+
/**
* The single error type that crosses the IPC boundary.
*
@@ -2436,6 +2528,10 @@ export type LanguageCodeStyle_Deserialize = {
tabSize?: number | null,
indent?: number | null,
hardWrapAt?: number | null,
+ /** Comment Code › Line comment at first column. */
+ lineCommentAtFirstColumn?: boolean | null,
+ /** Comment Code › Add a space at line comment start. */
+ lineCommentAddSpace?: boolean | null,
};
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
@@ -2444,6 +2540,10 @@ export type LanguageCodeStyle_Serialize = {
tabSize?: number | null,
indent?: number | null,
hardWrapAt?: number | null,
+ /** Comment Code › Line comment at first column. */
+ lineCommentAtFirstColumn?: boolean | null,
+ /** Comment Code › Add a space at line comment start. */
+ lineCommentAddSpace?: boolean | null,
};
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
@@ -2757,6 +2857,39 @@ export type MenuNode = { kind: "submenu"; id: string; label: string; children: M
/** A disabled placeholder such as "No Recent Projects". */
{ kind: "placeholder"; id: string; label: string } | { kind: "separator" };
+/**
+ * Who stands on each side of the conflicts of the operation in progress (merge editor
+ * titles, as IDEA labels them).
+ */
+export type MergeSides = {
+ /** `merge`, `rebase`, `cherry-pick`, `revert`…; `None` outside an operation. */
+ operation: string | null,
+ /**
+ * Git's "ours" is not the user's work: during a rebase stage 2 holds the commits
+ * rebased onto and stage 3 the user's commit being replayed. [`MergeVersions`] is
+ * already swapped; conflict markers in the file are not.
+ */
+ reversed: boolean,
+ /** The current branch (for a rebase: the branch being rebased). */
+ branch: string | null,
+ /**
+ * Short id of the commit being applied (REBASE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD)
+ * or merged (MERGE_HEAD).
+ */
+ commit: string | null,
+ /** The other branch: the one being merged, or the one rebased onto. */
+ otherBranch: string | null,
+};
+
+/** The versions of a conflicted file as the merge editor shows them. */
+export type MergeVersions = {
+ base: string | null,
+ /** The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`. */
+ ours: string | null,
+ theirs: string | null,
+ sides: MergeSides,
+};
+
/** Per-function totals (a recursive function's samples count once in `total`). */
export type MethodStat = {
frame: number,
@@ -2844,6 +2977,13 @@ export type OutputChunk = { kind: "stdout"; text: string } | { kind: "stderr"; t
/** System message from the IDE (command line echo, exit code). */
{ kind: "system"; text: string };
+/** A file of a partial commit: which of its changes against HEAD to commit. */
+export type PartialCommitFile = {
+ path: IpcPath,
+ /** The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them. */
+ hunks: HunkRange[],
+};
+
/** One file of a patch (Apply Patch preview). */
export type PatchFile = {
/** Path relative to the repository root (after the change). */
@@ -2863,6 +3003,12 @@ export type PatchSource =
/** Changes made by these commits (oldest first). */
{ from: "commits"; commits: string[]; reverse: boolean };
+/** An entry offered when completing a path. */
+export type PathCompletion = {
+ name: string,
+ dir: boolean,
+};
+
/** Capabilities a plugin must declare to use the gated host functions. */
export type Permission =
/** `workspace-root`, `read-file` (inside the project root only). */
@@ -3076,7 +3222,11 @@ export type ProfileNode = {
children: number[],
};
-export type ProfilePrepared = { status: "ready"; profiler: string; launch: RunConfig; spec: ProfileSpec } | { status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null } | { status: "unsupported"; reason: string };
+export type ProfilePrepared = ProfilePrepared_Serialize | ProfilePrepared_Deserialize;
+
+export type ProfilePrepared_Deserialize = ({ status: "ready"; profiler: string; launch: RunConfig_Deserialize; spec: ProfileSpec }) & { homepage?: never; install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null }) & { launch?: never; profiler?: never; reason?: never; spec?: never } | ({ status: "unsupported"; reason: string }) & { homepage?: never; install?: never; launch?: never; message?: never; profiler?: never; spec?: never; tool?: never };
+
+export type ProfilePrepared_Serialize = ({ status: "ready"; profiler: string; launch: RunConfig_Serialize; spec: ProfileSpec }) & { homepage?: never; install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null }) & { launch?: never; profiler?: never; reason?: never; spec?: never } | ({ status: "unsupported"; reason: string }) & { homepage?: never; install?: never; launch?: never; message?: never; profiler?: never; spec?: never; tool?: never };
/** Where a prepared run's profile will be, and how to read it. */
export type ProfileSpec =
@@ -3248,8 +3398,11 @@ export type RemoteOp = { op: "fetch" } | { op: "pull"; rebase: boolean } | { op:
tags?: PushTags | null } |
/** Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`). */
{ op: "deleteBranch"; branch: string } |
-/** Pushes local `branch` (only up to `revision` when set) to its upstream. */
-{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean } |
+/**
+ * Pushes local `branch` (only up to `revision` when set) to its upstream, or to
+ * remote branch `target` of the same remote.
+ */
+{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean; target?: string | null } |
/** Fast-forwards local `branch` (not checked out) to its upstream. */
{ op: "updateBranch"; branch: string };
@@ -3294,7 +3447,29 @@ export type ReviewEvent = "approve" | "requestChanges" | "comment";
export type RootKind = "source" | "test" | "resources" | "testResources" | "excluded";
-export type RunConfig = {
+export type RunConfig = RunConfig_Serialize | RunConfig_Deserialize;
+
+export type RunConfig_Deserialize = {
+ /** Stable id, e.g. `npm:dev`, `cargo:run:app`, or a uuid for user-defined. */
+ id: string,
+ name: string,
+ /** `npm` | `cargo` | `gradle` | `maven` | `go` | `python` | `pytest` | `make` | `shell` … */
+ kind: string,
+ command: string,
+ args: string[],
+ cwd: IpcPath | null,
+ env: { [key in string]: string },
+ /** Detected configs are regenerated; user configs persist in `.openidea/run.toml`. */
+ detected: boolean,
+ /** Test runner configs render results in the test tree. */
+ isTest: boolean,
+ /** DAP adapter that can debug this config, if any. */
+ debugAdapter: string | null,
+ /** "Allow multiple instances": Run on a running config starts another one instead of restarting it. */
+ allowParallel?: boolean,
+};
+
+export type RunConfig_Serialize = {
/** Stable id, e.g. `npm:dev`, `cargo:run:app`, or a uuid for user-defined. */
id: string,
name: string,
@@ -3310,6 +3485,8 @@ export type RunConfig = {
isTest: boolean,
/** DAP adapter that can debug this config, if any. */
debugAdapter: string | null,
+ /** "Allow multiple instances": Run on a running config starts another one instead of restarting it. */
+ allowParallel?: boolean,
};
/** A process started from a run configuration. */
@@ -3577,7 +3754,7 @@ export type SmartKeysSettings = {
/** Reformat on paste: `none` | `indentBlock` | `indentEachLine`. */
reformatOnPaste?: string,
smartIndent?: boolean,
- /** Backspace › Unindent: `nearest` indent position | `none`. */
+ /** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
backspaceUnindent?: string,
};
diff --git a/src/editor/core/actions.ts b/src/editor/core/actions.ts
index 77783de77..8371a8a2a 100644
--- a/src/editor/core/actions.ts
+++ b/src/editor/core/actions.ts
@@ -1,8 +1,9 @@
/** Editor actions (ids from keymaps/intellij-macos.ts). */
import { EditorSelection, type EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
-import { deleteLine, moveLineDown, moveLineUp, toggleBlockComment } from "@codemirror/commands";
+import { addCursorAbove, addCursorBelow, deleteLine, moveLineDown, moveLineUp, toggleBlockComment } from "@codemirror/commands";
import { foldAll, syntaxTree, toggleFold, unfoldAll } from "@codemirror/language";
+import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
import { executeAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { editorController, useGotoLine, useTabs } from "./controller";
@@ -26,6 +27,7 @@ import type { EditorSlot } from "./model/slot";
import { findAgain, openFindBar } from "./view/FindBar";
import { foldAtCaret, foldSelection, unfoldAtCaret } from "./cm/folding";
import { reverseLines, sortLines } from "./cm/lines";
+import { cursorCodeBlockEnd, cursorCodeBlockStart, scrollToCenter, splitLine } from "./cm/caretCommands";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
@@ -67,7 +69,8 @@ function withView(run: (view: EditorView, slot: EditorSlot) => unknown) {
// --- extend / shrink selection ---------------------------------------------------
-const stacks = new WeakMap<EditorSlot, SelectionStack>();
+/** One stack per selection range (by index): ⌥↑ / ⌥↓ work on every caret. */
+const stacks = new WeakMap<EditorSlot, SelectionStack[]>();
/** Syntax-tree candidates when the backend has nothing (or the language isn't parsed there). */
export function syntaxCandidates(state: EditorState, sel: SimpleRange): SimpleRange[] {
@@ -115,35 +118,40 @@ export function reusableChain(chain: BackendChain | undefined, counter: number,
const chains = new WeakMap<EditorSlot, BackendChain>();
+/** Backend candidates around `current` (the cached chain for repeated extends of one range). */
+async function backendCandidates(slot: EditorSlot, current: SimpleRange, cache: boolean): Promise<SimpleRange[]> {
+ const model = slot.model;
+ const cached = cache ? reusableChain(chains.get(slot), model.changeCounter, current) : null;
+ if (cached) return cached;
+ try {
+ await model.sync.whenIdle();
+ const counter = model.changeCounter;
+ const ranges = await model.manager.backend.selectionRanges(model.doc, current.from);
+ if (counter !== model.changeCounter || !slot.view) return [];
+ const candidates = rangesFromBackend(slot.view.state, ranges);
+ if (cache) chains.set(slot, { counter, pos: current.from, ranges: candidates });
+ return candidates;
+ } catch {
+ return []; // fall back to the syntax tree
+ }
+}
+
async function extend(slot: EditorSlot) {
const view = slot.view;
if (!view) return;
- const main = view.state.selection.main;
- const current = { from: main.from, to: main.to };
- let candidates: SimpleRange[] = [];
- const model = slot.model;
- const cached = reusableChain(chains.get(slot), model.changeCounter, current);
- if (cached) {
- candidates = cached;
- } else {
- try {
- await model.sync.whenIdle();
- const counter = model.changeCounter;
- const ranges = await model.manager.backend.selectionRanges(model.doc, current.from);
- if (counter === model.changeCounter && slot.view) {
- candidates = rangesFromBackend(slot.view.state, ranges);
- chains.set(slot, { counter, pos: current.from, ranges: candidates });
- }
- } catch {
- // fall back to the syntax tree
- }
- }
+ const before = view.state.selection;
+ const currents = before.ranges.map((r) => ({ from: r.from, to: r.to }));
+ const candidates = await Promise.all(currents.map((c, i) => backendCandidates(slot, c, i === before.mainIndex)));
const v = slot.view;
- if (!v || !v.state.selection.main.eq(main)) return;
- const all = [...candidates, ...syntaxCandidates(v.state, current)];
- const r = extendSelection(stacks.get(slot) ?? emptyStack(), current, all);
- stacks.set(slot, r.state);
- if (r.next) v.dispatch({ selection: EditorSelection.single(r.next.from, r.next.to), scrollIntoView: true, userEvent: "select.extend" });
+ if (!v || !v.state.selection.eq(before)) return;
+ const prev = stacks.get(slot) ?? [];
+ const results = currents.map((c, i) =>
+ extendSelection(prev[i] ?? emptyStack(), c, [...candidates[i]!, ...syntaxCandidates(v.state, c)]),
+ );
+ stacks.set(slot, results.map((r) => r.state));
+ if (!results.some((r) => r.next)) return;
+ const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : before.ranges[i]!));
+ v.dispatch({ selection: EditorSelection.create(ranges, before.mainIndex), scrollIntoView: true, userEvent: "select.extend" });
}
/** Extend / shrink run in order: a quick ⌥↑⌥↑ extends twice although extending waits for the backend. */
@@ -158,10 +166,13 @@ function queueSelection(slot: EditorSlot, step: (slot: EditorSlot) => void | Pro
function shrink(slot: EditorSlot) {
const view = slot.view;
if (!view) return;
- const main = view.state.selection.main;
- const r = shrinkSelection(stacks.get(slot) ?? emptyStack(), { from: main.from, to: main.to });
- stacks.set(slot, r.state);
- if (r.next) view.dispatch({ selection: EditorSelection.single(r.next.from, r.next.to), scrollIntoView: true, userEvent: "select.shrink" });
+ const sel = view.state.selection;
+ const prev = stacks.get(slot) ?? [];
+ const results = sel.ranges.map((r, i) => shrinkSelection(prev[i] ?? emptyStack(), { from: r.from, to: r.to }));
+ stacks.set(slot, results.map((r) => r.state));
+ if (!results.some((r) => r.next)) return;
+ const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : sel.ranges[i]!));
+ view.dispatch({ selection: EditorSelection.create(ranges, sel.mainIndex), scrollIntoView: true, userEvent: "select.shrink" });
}
// --- structural editing without a Lezer tree ------------------------------------------
@@ -221,8 +232,10 @@ function moveStatement(view: EditorView, slot: EditorSlot, up: boolean) {
* Complete Current Statement: tree-sitter knows what is missing where (and
* which multi-line statement the caret is in) for stream-mode languages, and
* places Java's `;` better than the line heuristics; the heuristics finish the line.
+ * With the completion lookup open, its selected item is inserted first (IDEA).
*/
function completeCurrentStatement(view: EditorView, slot: EditorSlot) {
+ if (completionStatus(view.state) === "active") acceptCompletion(view);
const language = slot.model.getMeta().language;
const sel = view.state.selection;
if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1) return completeStatement(language)(view);
@@ -335,6 +348,12 @@ export function registerEditorActions(): () => void {
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
text("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
text("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
+ text("code.splitLine", "Split Line", (v) => splitLine(v)),
+ text("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
+ text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), { category: "Editor Actions" }),
+ text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), { category: "Editor Actions" }),
+ text("editor.cloneCaretAbove", "Clone Caret Above", (v) => addCursorAbove(v), { category: "Editor Actions" }),
+ text("editor.cloneCaretBelow", "Clone Caret Below", (v) => addCursorBelow(v), { category: "Editor Actions" }),
text("code.joinLines", "Join Lines", (v) => joinLines(v)),
text("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), { category: "Edit" }),
@@ -543,6 +562,8 @@ export function registerEditorActions(): () => void {
category: "Edit",
icon: "copy",
when: "textEditorActive",
+ // ⇧⌘C / Ctrl+Shift+C stays with the terminal (copy) and other tool windows.
+ keyWhen: "editorFocus || !toolWindowFocus",
run: () => {
const p = ctrl.activePath();
if (p) void navigator.clipboard?.writeText(p);
diff --git a/src/editor/core/cm/baseKeymap.ts b/src/editor/core/cm/baseKeymap.ts
new file mode 100644
index 000000000..179eaaec6
--- /dev/null
+++ b/src/editor/core/cm/baseKeymap.ts
@@ -0,0 +1,36 @@
+/**
+ * CodeMirror's default keymap minus the bindings that clash with IntelliJ IDEA.
+ * Those keys belong to IDE actions instead (keymaps in `platform/keymaps/`):
+ * ⌘/Ctrl+Enter is Split Line, Ctrl+M / ⌃L Scroll to Center, Ctrl+[ / ] code
+ * block navigation, ⌥⌘↑↓ / Ctrl+Alt+↑↓ Previous / Next Occurrence.
+ */
+import type { KeyBinding } from "@codemirror/view";
+import {
+ addCursorAbove,
+ addCursorBelow,
+ defaultKeymap,
+ historyKeymap,
+ indentLess,
+ indentMore,
+ insertBlankLine,
+ redo,
+ selectLine,
+ toggleTabFocusMode,
+} from "@codemirror/commands";
+
+const DROPPED = new Set<unknown>([
+ insertBlankLine, // Mod-Enter
+ toggleTabFocusMode, // Ctrl-m / Shift-Alt-m
+ selectLine, // Alt-l / Ctrl-l
+ addCursorAbove, // Mod-Alt-ArrowUp
+ addCursorBelow, // Mod-Alt-ArrowDown
+ indentLess, // Mod-[
+ indentMore, // Mod-]
+]);
+
+export const editorBaseKeymap: readonly KeyBinding[] = [
+ ...defaultKeymap.filter((b) => !DROPPED.has(b.run)),
+ ...historyKeymap,
+ // IDEA's Windows Redo is Ctrl+Shift+Z (Ctrl+Y is Delete Line); CodeMirror only binds it on macOS and Linux.
+ { win: "Ctrl-Shift-z", run: redo, preventDefault: true },
+];
diff --git a/src/editor/core/cm/caretCommands.test.ts b/src/editor/core/cm/caretCommands.test.ts
new file mode 100644
index 000000000..fb2e2bf3b
--- /dev/null
+++ b/src/editor/core/cm/caretCommands.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+import { EditorSelection, EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { indentService, type LanguageSupport } from "@codemirror/language";
+import { languages } from "@codemirror/language-data";
+import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
+import { codeBlockEnd, codeBlockStart, splitLine } from "./caretCommands";
+import { editorBaseKeymap } from "./baseKeymap";
+
+const views: EditorView[] = [];
+afterEach(() => views.splice(0).forEach((v) => v.destroy()));
+
+/** One unit deeper after a line ending in `{`. */
+const braceIndent = indentService.of((cx, pos) => {
+ const line = cx.lineAt(pos, -1);
+ const base = /^ */.exec(line.text)![0].length;
+ return line.text.slice(0, pos - line.from).trimEnd().endsWith("{") ? base + 2 : base;
+});
+
+/** `|` marks carets. */
+function make(text: string) {
+ const carets: number[] = [];
+ let doc = "";
+ for (const ch of text) {
+ if (ch === "|") carets.push(doc.length);
+ else doc += ch;
+ }
+ const view = new EditorView({
+ state: EditorState.create({
+ doc,
+ selection: EditorSelection.create(carets.map((c) => EditorSelection.cursor(c))),
+ extensions: [EditorState.allowMultipleSelections.of(true), braceIndent],
+ }),
+ });
+ views.push(view);
+ return view;
+}
+
+function show(view: EditorView) {
+ const doc = view.state.doc.toString();
+ const heads = view.state.selection.ranges.map((r) => r.head).sort((a, b) => b - a);
+ return heads.reduce((s, h) => s.slice(0, h) + "|" + s.slice(h), doc);
+}
+
+describe("Split Line", () => {
+ it("breaks the line at each caret and leaves the caret before the break", () => {
+ const view = make("if (a) {|return 1; }");
+ splitLine(view);
+ expect(show(view)).toBe("if (a) {|\n return 1; }");
+ const multi = make("a|b\nc|d");
+ splitLine(multi);
+ expect(show(multi)).toBe("a|\nb\nc|\nd");
+ });
+});
+
+describe("code block navigation", () => {
+ let js: LanguageSupport;
+ beforeAll(async () => {
+ js = await languages.find((l) => l.name === "JavaScript")!.load();
+ });
+ const at = (text: string) => {
+ const pos = text.indexOf("|");
+ return { state: EditorState.create({ doc: text.replace("|", ""), extensions: js }), pos };
+ };
+
+ it("goes to just inside the enclosing braces", () => {
+ const { state, pos } = at("f() { if (x) { a|(); } b(); }");
+ expect(codeBlockStart(state, pos)).toBe("f() { if (x) {".length);
+ expect(codeBlockEnd(state, pos)).toBe("f() { if (x) { a(); ".length);
+ });
+
+ it("jumps across a brace at the caret to its match, and outward from inside one", () => {
+ const text = "f() { if (x) { a(); } b(); }";
+ const { state } = at(text);
+ const open = text.indexOf("{", 6);
+ const close = text.indexOf("}");
+ expect(codeBlockEnd(state, open)).toBe(close + 1); // |{ … } → { … }|
+ expect(codeBlockStart(state, close + 1)).toBe(open); // { … }| → |{ … }
+ expect(codeBlockStart(state, open + 1)).toBe(text.indexOf("{") + 1); // {| → outer block
+ expect(codeBlockEnd(state, close)).toBe(text.lastIndexOf("}")); // |} → outer block
+ });
+
+ it("skips braces in strings and comments", () => {
+ const { state, pos } = at('f() { const s = "{"; /* } */ a|(); }');
+ expect(codeBlockStart(state, pos)).toBe("f() {".length);
+ expect(codeBlockEnd(state, pos)).toBe('f() { const s = "{"; /* } */ a(); '.length);
+ });
+
+ it("has nowhere to go outside any block", () => {
+ const { state, pos } = at("a|();");
+ expect(codeBlockStart(state, pos)).toBeNull();
+ expect(codeBlockEnd(state, pos)).toBeNull();
+ });
+});
+
+describe("editor base keymap", () => {
+ it("drops CodeMirror defaults that IDEA uses for other actions", () => {
+ const runs = editorBaseKeymap.map((b) => b.run);
+ for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove]) expect(runs).not.toContain(cmd);
+ expect(editorBaseKeymap.some((b) => b.key === "Mod-Enter" || b.key === "Ctrl-m")).toBe(false);
+ expect(editorBaseKeymap.some((b) => b.win === "Ctrl-Shift-z")).toBe(true);
+ });
+});
diff --git a/src/editor/core/cm/caretCommands.ts b/src/editor/core/cm/caretCommands.ts
new file mode 100644
index 000000000..11dd8d38e
--- /dev/null
+++ b/src/editor/core/cm/caretCommands.ts
@@ -0,0 +1,92 @@
+/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center, code block navigation. */
+import { EditorSelection, type EditorState, type Transaction } from "@codemirror/state";
+import { EditorView, type Command } from "@codemirror/view";
+import { insertNewlineAndIndent } from "@codemirror/commands";
+import { syntaxTree } from "@codemirror/language";
+
+/** Split Line: break the line at each caret, indented, leaving the caret before the break. */
+export const splitLine: Command = (view) => {
+ if (view.state.readOnly) return false;
+ const before = view.state.selection;
+ let tr: Transaction | null = null;
+ insertNewlineAndIndent({ state: view.state, dispatch: (t) => (tr = t) });
+ if (!tr) return false;
+ const changes = (tr as Transaction).changes;
+ const selection = EditorSelection.create(
+ before.ranges.map((r) => EditorSelection.cursor(changes.mapPos(r.from, -1))),
+ before.mainIndex,
+ );
+ view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "input" });
+ return true;
+};
+
+/** Scroll to Center: put the caret line in the middle of the viewport. */
+export const scrollToCenter: Command = (view) => {
+ view.dispatch({ effects: EditorView.scrollIntoView(view.state.selection.main.head, { y: "center" }) });
+ return true;
+};
+
+const NOT_CODE = /String|Comment|Regexp|Char|Template/;
+
+/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
+function braceAt(state: EditorState, pos: number): "{" | "}" | null {
+ const ch = state.sliceDoc(pos, pos + 1);
+ if (ch !== "{" && ch !== "}") return null;
+ const tree = syntaxTree(state);
+ if (tree.length && NOT_CODE.test(tree.resolveInner(pos, 1).name)) return null;
+ return ch;
+}
+
+/**
+ * Where Move Caret to Code Block Start goes from `pos` (as IDEA):
+ * just after the enclosing `{`, or before the `{` matching a `}` the caret follows.
+ */
+export function codeBlockStart(state: EditorState, pos: number): number | null {
+ const from = pos - 1;
+ if (from < 0) return null;
+ const afterClose = braceAt(state, from) === "}";
+ let depth = afterClose ? -1 : 0;
+ for (let p = from; p >= 0; p--) {
+ const b = braceAt(state, p);
+ if (b === "{" && p !== from) {
+ if (depth === 0) return afterClose ? p : p + 1;
+ depth--;
+ } else if (b === "}") {
+ depth++;
+ }
+ }
+ return null;
+}
+
+/**
+ * Where Move Caret to Code Block End goes from `pos`: before the enclosing `}`,
+ * or after the `}` matching a `{` the caret precedes.
+ */
+export function codeBlockEnd(state: EditorState, pos: number): number | null {
+ const len = state.doc.length;
+ const beforeOpen = braceAt(state, pos) === "{";
+ let depth = beforeOpen ? -1 : 0;
+ for (let p = pos; p < len; p++) {
+ const b = braceAt(state, p);
+ if (b === "}" && p !== pos) {
+ if (depth === 0) return beforeOpen ? p + 1 : p;
+ depth--;
+ } else if (b === "{") {
+ depth++;
+ }
+ }
+ return null;
+}
+
+function moveToBlock(find: (state: EditorState, pos: number) => number | null): Command {
+ return (view) => {
+ const { state } = view;
+ const target = find(state, state.selection.main.head);
+ if (target == null) return false;
+ view.dispatch({ selection: EditorSelection.cursor(target), scrollIntoView: true, userEvent: "select.navigate" });
+ return true;
+ };
+}
+
+export const cursorCodeBlockStart = moveToBlock(codeBlockStart);
+export const cursorCodeBlockEnd = moveToBlock(codeBlockEnd);
diff --git a/src/editor/core/cm/comments.ts b/src/editor/core/cm/comments.ts
new file mode 100644
index 000000000..ecd86ddd9
--- /dev/null
+++ b/src/editor/core/cm/comments.ts
@@ -0,0 +1,263 @@
+/**
+ * Comment with Line Comment and Enter inside a line comment, as in IDEA.
+ */
+import { EditorSelection, Facet, countColumn, type ChangeSpec, type EditorState, type SelectionRange } from "@codemirror/state";
+import type { Command, EditorView } from "@codemirror/view";
+import { indentString, syntaxTree } from "@codemirror/language";
+import { toggleComment } from "@codemirror/commands";
+
+/** Code Style › <Language> › Code Generation › Comment Code. */
+export interface LineCommentStyle {
+ atFirstColumn: boolean;
+ addSpace: boolean;
+}
+
+export const lineCommentStyle = Facet.define<LineCommentStyle, LineCommentStyle>({
+ combine: (values) => values[0] ?? { atFirstColumn: true, addSpace: false },
+});
+
+function lineToken(state: EditorState, pos: number): string | undefined {
+ return state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
+}
+
+const leadingWs = (text: string) => /^[ \t]*/.exec(text)![0].length;
+
+interface Block {
+ startLine: number;
+ endLine: number;
+ ranges: number[];
+ caretUpdate: "commentStart" | "down" | "restoreSelection" | null;
+}
+
+/** The view state right after the last ⌘/, to tell a repeated ⌘/ (IDEA's previous performed action). */
+const afterComment = new WeakMap<EditorView, EditorState>();
+
+/**
+ * ⌘/: comments the caret / selected lines (or uncomments when every line is
+ * commented). Without a selection the caret moves down — on an empty line it
+ * stays after the inserted prefix; with whole lines selected the selection
+ * then starts at its first line's start.
+ */
+export const commentLine: Command = (view) => {
+ const { state } = view;
+ if (state.readOnly) return false;
+ const doc = state.doc;
+ const style = state.facet(lineCommentStyle);
+ const repeated = afterComment.get(view) === state;
+
+ const blocks: Block[] = [];
+ const order = state.selection.ranges.map((r, i) => ({ r, i })).sort((a, b) => a.r.from - b.r.from);
+ for (const { r, i } of order) {
+ const startLine = doc.lineAt(r.from).number;
+ let endLine = doc.lineAt(r.to).number;
+ if (!r.empty && endLine > startLine && doc.line(endLine).from === r.to) endLine--;
+ const last = blocks[blocks.length - 1];
+ const block = last && startLine <= last.endLine + 1 ? last : null;
+ const target = block ?? { startLine, endLine, ranges: [], caretUpdate: null };
+ if (!block) blocks.push(target);
+ target.ranges.push(i);
+ target.endLine = Math.max(target.endLine, endLine);
+ const wholeLines = r.empty || (r.from === doc.lineAt(r.from).from && r.to === doc.lineAt(r.to).from && r.to > r.from);
+ const emptyLine = !doc.lineAt(r.from).text.trim();
+ target.caretUpdate = r.empty && emptyLine && !repeated ? "commentStart" : r.empty ? "down" : wholeLines ? "restoreSelection" : null;
+ }
+
+ const tokens = blocks.map((b) => lineToken(state, doc.line(b.startLine).from + leadingWs(doc.line(b.startLine).text)));
+ // Languages without line comments (CSS, HTML…): block comments.
+ if (tokens.some((t) => !t)) return toggleComment(view);
+
+ let allCommented = true;
+ let commentedNonEmpty = false;
+ blocks.forEach((b, bi) => {
+ const token = tokens[bi]!;
+ const single = b.startLine === b.endLine;
+ for (let n = b.startLine; n <= b.endLine; n++) {
+ const text = doc.line(n).text;
+ const commented = text.slice(leadingWs(text)).startsWith(token);
+ const empty = !text.trim();
+ if (commented && !empty) commentedNonEmpty = true;
+ if (!commented && (single || !empty)) allCommented = false;
+ }
+ if (allCommented && !single && !commentedNonEmpty) allCommented = false;
+ });
+
+ const changes: ChangeSpec[] = [];
+ blocks.forEach((b, bi) => {
+ const token = tokens[bi]!;
+ if (allCommented) {
+ for (let n = b.startLine; n <= b.endLine; n++) {
+ const line = doc.line(n);
+ const start = line.from + leadingWs(line.text);
+ if (!doc.sliceString(start, line.to).startsWith(token) || !line.text.trim()) continue;
+ let end = start + token.length;
+ if (style.addSpace && doc.sliceString(end, end + 1) === " ") end++;
+ // Nothing but whitespace left: the line is emptied.
+ if (!doc.sliceString(end, line.to).trim()) changes.push({ from: line.from, to: line.to });
+ else changes.push({ from: start, to: end });
+ }
+ return;
+ }
+ const commentStart = b.caretUpdate === "commentStart";
+ const prefixFor = (shifted: number, line: { to: number }) =>
+ token + (style.addSpace && (shifted < line.to || (commentStart && shifted < doc.length)) ? " " : "");
+ if (style.atFirstColumn) {
+ for (let n = b.startLine; n <= b.endLine; n++) {
+ const line = doc.line(n);
+ changes.push({ from: line.from, insert: prefixFor(line.from + leadingWs(line.text), line) });
+ }
+ return;
+ }
+ const min = minIndent(state, b.startLine, b.endLine, token);
+ for (let n = b.startLine; n <= b.endLine; n++) {
+ const line = doc.line(n);
+ let cols = 0;
+ let i = 0;
+ for (; i < line.length && cols < min; i++) {
+ const ch = line.text[i];
+ if (ch === " ") cols++;
+ else if (ch === "\t") cols += state.tabSize - (cols % state.tabSize);
+ else break;
+ }
+ const prefix = prefixFor(line.from + leadingWs(line.text), line);
+ if (cols >= min) changes.push({ from: line.from + i, insert: prefix });
+ else changes.push({ from: line.from, to: line.from + i, insert: indentString(state, min) + prefix });
+ }
+ });
+
+ const set = state.changes(changes);
+ const next = set.apply(doc);
+ const moveCarets = !blocks.some((b) => b.ranges.length > 1 && b.startLine !== b.endLine);
+ const ranges: SelectionRange[] = state.selection.ranges.map((r) => r.map(set));
+ for (const [bi, b] of blocks.entries()) {
+ if (!moveCarets || !b.caretUpdate) continue;
+ for (const i of b.ranges) {
+ const r = ranges[i]!;
+ if (b.caretUpdate === "commentStart") {
+ const line = next.line(b.startLine);
+ let pos = line.from + leadingWs(line.text) + tokens[bi]!.length;
+ pos += leadingWs(next.sliceString(pos, line.to));
+ ranges[i] = EditorSelection.cursor(Math.min(pos, next.length));
+ } else if (b.caretUpdate === "down") {
+ const line = next.lineAt(r.head);
+ if (line.number >= next.lines) continue;
+ const col = countColumn(next.sliceString(line.from, r.head), state.tabSize);
+ const below = next.line(line.number + 1);
+ ranges[i] = EditorSelection.cursor(below.from + offsetAtColumn(below.text, col, state.tabSize));
+ } else {
+ const from = next.lineAt(r.from).from;
+ ranges[i] = r.head >= r.anchor ? EditorSelection.range(from, r.to) : EditorSelection.range(r.to, from);
+ }
+ }
+ }
+ view.dispatch({
+ changes: set,
+ selection: EditorSelection.create(ranges, state.selection.mainIndex),
+ scrollIntoView: true,
+ userEvent: allCommented ? "delete.uncomment" : "input.comment",
+ });
+ afterComment.set(view, view.state);
+ return true;
+};
+
+function offsetAtColumn(text: string, col: number, tabSize: number): number {
+ let cols = 0;
+ for (let i = 0; i < text.length; i++) {
+ if (cols >= col) return i;
+ cols += text[i] === "\t" ? tabSize - (cols % tabSize) : 1;
+ }
+ return text.length;
+}
+
+/** Smallest indent of the non-blank lines, also no deeper than a line comment right above. */
+function minIndent(state: EditorState, startLine: number, endLine: number, token: string): number {
+ const doc = state.doc;
+ const indentOf = (text: string) => countColumn(text.slice(0, leadingWs(text)), state.tabSize);
+ let min: number | null = null;
+ const scan = (from: number, to: number) => {
+ for (let n = from; n <= to; n++) {
+ const line = doc.line(n);
+ if (!line.text.trim() && n < doc.lines) continue;
+ const indent = indentOf(line.text);
+ min = min === null ? indent : Math.min(min, indent);
+ }
+ };
+ scan(startLine, endLine);
+ if (min === null && startLine === endLine && startLine < doc.lines) scan(startLine + 1, startLine + 1);
+ if (startLine > 1) {
+ const above = doc.line(startLine - 1).text;
+ if (above.slice(leadingWs(above)).startsWith(token)) min = Math.min(min ?? Infinity, indentOf(above));
+ }
+ return min ?? 0;
+}
+
+// --- Enter in a line comment ------------------------------------------------------
+
+/** The start of the line comment the caret is in (after its prefix), else -1. */
+function lineCommentStart(state: EditorState, pos: number, token: string): number {
+ if (pos < 1) return -1;
+ const tree = syntaxTree(state);
+ if (!tree.length) return -1;
+ const node = tree.resolveInner(pos, -1);
+ if (!/comment/i.test(node.type.name) || node.from >= pos) return -1;
+ const line = state.doc.lineAt(pos);
+ if (node.from < line.from || !state.sliceDoc(node.from, pos).startsWith(token)) return -1;
+ return node.from + token.length <= pos ? node.from : -1;
+}
+
+/**
+ * Enter inside a `//` comment with text after the caret: the rest moves to a
+ * new line that continues the comment (with the comment's own spacing).
+ */
+export const enterInLineComment: Command = (view) => {
+ const { state } = view;
+ if (state.readOnly || state.selection.ranges.some((r) => !r.empty)) return false;
+ const doc = state.doc;
+ const plans: Array<{ changes: ChangeSpec[]; caret: number }> = [];
+ for (const r of state.selection.ranges) {
+ const pos = r.head;
+ const token = lineToken(state, pos);
+ if (!token) return false;
+ const start = lineCommentStart(state, pos, token);
+ if (start < 0) return false;
+ const line = doc.lineAt(pos);
+ const offset = pos + leadingWs(doc.sliceString(pos, line.to));
+ if (offset >= line.to) return false;
+ const indent = line.text.slice(0, leadingWs(line.text));
+ const onlyComment = start === line.from + indent.length;
+ const br = state.lineBreak;
+ if (doc.sliceString(offset, offset + token.length) === token) {
+ // The rest is a comment already: break before it.
+ const after = offset + token.length;
+ const changes: ChangeSpec[] = [{ from: offset, insert: br + indent }];
+ if (after < line.to && doc.sliceString(after, after + 1) !== " ") changes.push({ from: after, insert: " " });
+ plans.push({ changes, caret: onlyComment ? token.length + 1 : 0 });
+ continue;
+ }
+ let spacing = " ";
+ let to = pos;
+ if (onlyComment) {
+ const own = /^[ \t]*/.exec(doc.sliceString(start + token.length, line.to))![0];
+ if (own) spacing = own;
+ to = offset;
+ } else if (doc.sliceString(pos, pos + 1) === " ") spacing = "";
+ plans.push({
+ changes: [{ from: pos, to, insert: br + indent + token + spacing }],
+ caret: onlyComment ? token.length + spacing.length : 0,
+ });
+ }
+ const tr = state.changeByRange((r) => {
+ const plan = plans[state.selection.ranges.indexOf(r)]!;
+ const set = state.changes(plan.changes);
+ // The caret lands on the new line, after its indent (and the prefix when the comment owns the line).
+ let lineStart = -1;
+ set.iterChanges((_fa, _ta, fromB, _tb, inserted) => {
+ const text = inserted.toString();
+ const at = text.indexOf(state.lineBreak);
+ if (lineStart < 0 && at >= 0) lineStart = fromB + at + state.lineBreak.length;
+ });
+ const indent = leadingWs(doc.lineAt(r.head).text);
+ return { changes: set, range: EditorSelection.cursor(lineStart + indent + plan.caret) };
+ });
+ view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input" }));
+ return true;
+};
diff --git a/src/editor/core/cm/editing.test.ts b/src/editor/core/cm/editing.test.ts
index 50106f3ec..0272acc58 100644
--- a/src/editor/core/cm/editing.test.ts
+++ b/src/editor/core/cm/editing.test.ts
@@ -12,6 +12,8 @@ import {
unselectOccurrence,
} from "./editing";
import { toggleCaret } from "./multiCaret";
+import { enterInLineComment, lineCommentStyle } from "./comments";
+import { languages } from "@codemirror/language-data";
/** Brace languages in miniature: one unit deeper after a line ending in `{`. */
const javascript = () =>
@@ -108,18 +110,24 @@ describe("join lines", () => {
});
describe("toggle case", () => {
- it("upper-cases mixed text and lower-cases upper-case text", () => {
+ it("lower-cases text with any upper-case letter, upper-cases the rest", () => {
const v = make("[fooBar]");
toggleCase(v);
- expect(v.state.doc.toString()).toBe("FOOBAR");
- toggleCase(v);
expect(v.state.doc.toString()).toBe("foobar");
+ toggleCase(v);
+ expect(v.state.doc.toString()).toBe("FOOBAR");
});
- it("uses the word at the caret without a selection", () => {
+ it("selects the word at the caret without a selection", () => {
const v = make("one tw|o three");
toggleCase(v);
- expect(show(v)).toBe("one TW|O three");
+ expect(show(v)).toBe("one [TWO] three");
+ });
+
+ it("decides once for all carets", () => {
+ const v = make("[abc] [Def]");
+ toggleCase(v);
+ expect(v.state.doc.toString()).toBe("abc def");
});
});
@@ -157,17 +165,68 @@ describe("multiple carets", () => {
describe("comment with line comment", () => {
const comments = EditorState.languageData.of(() => [{ commentTokens: { line: "//" } }]);
+ const indented = [comments, lineCommentStyle.of({ atFirstColumn: false, addSpace: true })];
- it("moves the caret to the next line without a selection", () => {
- const v = make("a|b\ncd\n", comments);
+ it("comments at the first column without a space and moves the caret down", () => {
+ const v = make(" a|b\n cd\n", comments);
commentLine(v);
- expect(show(v)).toBe("// ab\nc|d\n");
+ expect(show(v)).toBe("// ab\n cd|\n");
});
- it("keeps a selection where it is", () => {
- const v = make("[ab\ncd]\n", comments);
+ it("moves every caret down", () => {
+ const v = make("a|\nb\nc|\nd\n", comments);
commentLine(v);
- expect(v.state.doc.toString()).toBe("// ab\n// cd\n");
- expect(v.state.doc.lineAt(v.state.selection.main.head).number).toBe(2);
+ expect(show(v)).toBe("//a\nb|\n//c\nd|\n");
+ });
+
+ it("keeps the caret after the prefix on an empty line", () => {
+ const v = make("f {\n |\n b", indented);
+ commentLine(v);
+ expect(show(v)).toBe("f {\n // |\n b");
+ const w = make("a\n|\nb", comments);
+ commentLine(w);
+ expect(show(w)).toBe("a\n//|\nb");
+ });
+
+ it("uncomments with or without the space", () => {
+ const v = make("[//a\n // b\n]c", comments);
+ commentLine(v);
+ expect(v.state.doc.toString()).toBe("a\n b\nc");
+ const w = make("[//a\n // b\n]c", indented);
+ commentLine(w);
+ expect(w.state.doc.toString()).toBe("a\n b\nc");
+ });
+
+ it("comments at the smallest indent of the lines when not at the first column", () => {
+ const v = make("[ a\n b\n\n c]", indented);
+ commentLine(v);
+ expect(v.state.doc.toString()).toBe(" // a\n // b\n //\n // c");
+ });
+
+ it("restores a whole-line selection from its first line's start", () => {
+ const v = make("x\n[ab\ncd\n]", comments);
+ commentLine(v);
+ expect(show(v)).toBe("x\n[//ab\n//cd\n]");
+ });
+});
+
+describe("enter in a line comment", async () => {
+ const ext = await languages.find((l) => l.name === "JavaScript")!.load();
+
+ it("continues the comment with its own spacing", () => {
+ const v = make(" // one |two", ext);
+ expect(enterInLineComment(v)).toBe(true);
+ expect(show(v)).toBe(" // one \n // |two");
+ });
+
+ it("splits a trailing comment onto a commented line", () => {
+ const v = make("f(); // one |two", ext);
+ enterInLineComment(v);
+ expect(show(v)).toBe("f(); // one \n|// two");
+ });
+
+ it("does nothing at the end of the comment or outside one", () => {
+ expect(enterInLineComment(make("// one|", ext))).toBe(false);
+ expect(enterInLineComment(make("f(|x)", ext))).toBe(false);
});
});
diff --git a/src/editor/core/cm/editing.ts b/src/editor/core/cm/editing.ts
index 3a45f5e34..8d9a70df4 100644
--- a/src/editor/core/cm/editing.ts
+++ b/src/editor/core/cm/editing.ts
@@ -9,7 +9,6 @@ import {
insertNewlineAndIndent,
moveLineDown,
moveLineUp,
- toggleComment,
} from "@codemirror/commands";
import { selectNextOccurrence, selectSelectionMatches } from "@codemirror/search";
import { humpLeft, humpRight } from "../model/camelHumps";
@@ -286,22 +285,7 @@ export function selectRange(view: EditorView, range: SelectionRange | { from: nu
// --- comments ------------------------------------------------------------------------
-/** ⌘/: toggles line comments; without a selection the caret then moves to the next line, as in IDEA. */
-export const commentLine: Command = (view) => {
- const before = view.state.selection;
- const column = before.main.head - view.state.doc.lineAt(before.main.head).from;
- if (!toggleComment(view)) return false;
- const sel = view.state.selection;
- if (before.ranges.length === 1 && before.main.empty && sel.ranges.length === 1) {
- const line = view.state.doc.lineAt(sel.main.head);
- if (line.number < view.state.doc.lines) {
- const next = view.state.doc.line(line.number + 1);
- const col = Math.min(column, next.length);
- view.dispatch({ selection: EditorSelection.cursor(next.from + col), scrollIntoView: true, userEvent: "select" });
- }
- }
- return true;
-};
+export { commentLine } from "./comments";
// --- smart keys ------------------------------------------------------------------
@@ -381,17 +365,44 @@ export const joinLines: Command = (view) => {
return true;
};
-/** ⌘⇧U: Toggle Case of the selection (or the word at the caret). */
+/** Escape sequences keep their case: `\n` must not become `\N`. */
+function caseOf(state: EditorState, from: number, to: number, lower: boolean): string {
+ const text = state.sliceDoc(from, to);
+ const conv = (t: string) => (lower ? t.toLowerCase() : t.toUpperCase());
+ const keep: Array<[number, number]> = [];
+ syntaxTree(state).iterate({
+ from,
+ to,
+ enter: (n) => {
+ if (/Escape/.test(n.type.name)) keep.push([Math.max(n.from, from) - from, Math.min(n.to, to) - from]);
+ },
+ });
+ if (!keep.length) return conv(text);
+ let out = "";
+ let pos = 0;
+ for (const [a, b] of keep) {
+ if (a < pos) continue;
+ out += conv(text.slice(pos, a)) + text.slice(a, b);
+ pos = b;
+ }
+ return out + conv(text.slice(pos));
+}
+
+/**
+ * ⌘⇧U: Toggle Case of the selections (the word at a caret, which stays
+ * selected): lower case when any of them has an upper-case letter, else upper.
+ */
export const toggleCase: Command = (view) => {
const { state } = view;
if (state.readOnly) return false;
+ const targets = state.selection.ranges.map((r) => (r.empty ? state.wordAt(r.head) : r));
+ const lower = targets.some((t) => t && state.sliceDoc(t.from, t.to) !== state.sliceDoc(t.from, t.to).toLowerCase());
const tr = state.changeByRange((r) => {
- const range = r.empty ? state.wordAt(r.head) : r;
- if (!range) return { range: r };
- const text = state.sliceDoc(range.from, range.to);
- // Mixed or lower case → upper; all upper → lower (as IDEA).
- const insert = text === text.toUpperCase() ? text.toLowerCase() : text.toUpperCase();
- return { changes: { from: range.from, to: range.to, insert }, range: r.empty ? r : EditorSelection.range(r.anchor, r.head) };
+ const t = targets[state.selection.ranges.indexOf(r)];
+ if (!t) return { range: r };
+ const insert = caseOf(state, t.from, t.to, lower);
+ const range = r.empty ? EditorSelection.range(t.from, t.from + insert.length) : EditorSelection.range(r.anchor, r.head);
+ return { changes: { from: t.from, to: t.to, insert }, range };
});
view.dispatch(state.update(tr, { userEvent: "input.case" }));
return true;
diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.ts
index da0aef1d3..4da4372c2 100644
--- a/src/editor/core/cm/prefs.ts
+++ b/src/editor/core/cm/prefs.ts
@@ -26,6 +26,8 @@ import {
import type { EditorExtras } from "@/platform/editorSettings";
import { openideaHighlightStyle } from "./highlight";
import { cursorHumpLeft, cursorHumpRight, deleteHumpBackward, deleteHumpForward, selectHumpLeft, selectHumpRight } from "./editing";
+import { enterInLineComment, lineCommentStyle, type LineCommentStyle } from "./comments";
+import { smartBackspace, smartBackspaceApplies, tabOut } from "./smartKeys";
// --- soft wraps ---------------------------------------------------------------
@@ -335,23 +337,6 @@ const centerCaret = EditorState.transactionExtender.of((tr) => {
// --- smart keys ----------------------------------------------------------------
-const CLOSERS = new Set([")", "]", "}", '"', "'", "`"]);
-
-const tabOut = keymap.of([
- {
- key: "Tab",
- run: (view) => {
- const sel = view.state.selection;
- if (sel.ranges.some((r) => !r.empty)) return false;
- const next = (r: { head: number }) => view.state.sliceDoc(r.head, r.head + 1);
- if (!sel.ranges.every((r) => CLOSERS.has(next(r)) && !/^\s*$/.test(view.state.doc.lineAt(r.head).text.slice(0, r.head - view.state.doc.lineAt(r.head).from))))
- return false;
- view.dispatch({ selection: EditorSelection.create(sel.ranges.map((r) => EditorSelection.cursor(r.head + 1)), sel.mainIndex), userEvent: "select" });
- return true;
- },
- },
-]);
-
const OPENERS: Record<string, true> = { "(": true, "[": true, "{": true, '"': true, "'": true, "`": true };
/** Typing a bracket / quote over a selection replaces it instead of wrapping it. */
@@ -379,6 +364,10 @@ export interface PrefsOptions {
readOnly: boolean;
/** Distraction Free Mode: no right margin / visual guides beside the centred column. */
distractionFree?: boolean;
+ /** Language id of the document (per-language smart-key behaviour). */
+ language?: string;
+ /** Code Style › Comment Code of the document's language. */
+ commentStyle?: LineCommentStyle;
}
export function caretExtension(prefs: EditorExtras): Extension {
@@ -414,7 +403,8 @@ export function prefsExtension(o: PrefsOptions): Extension {
const brackets = [...(k.pairBrackets ? ["(", "[", "{"] : []), ...(k.pairQuotes ? ["'", '"'] : [])];
out.push(Prec.highest(EditorState.languageData.of(() => [{ closeBrackets: { brackets } }])));
if (!k.surroundSelection) out.push(Prec.highest(noSurround));
- if (k.tabOutOfPair) out.push(Prec.highest(tabOut));
+ if (k.tabOutOfPair) out.push(tabOut);
+ if (o.commentStyle) out.push(lineCommentStyle.of(o.commentStyle));
const keys = [];
if (k.camelHumps)
@@ -429,8 +419,10 @@ export function prefsExtension(o: PrefsOptions): Extension {
{ key: "Home", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
{ mac: "Mod-ArrowLeft", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
);
+ if (!o.readOnly) keys.push({ key: "Enter", run: enterInLineComment });
if (!k.smartIndent) keys.push({ key: "Enter", run: insertNewlineKeepIndent });
if (k.backspaceUnindent === "none") keys.push({ key: "Backspace", run: deleteCharBackwardStrict });
+ else if (smartBackspaceApplies(k.backspaceUnindent, o.language)) keys.push({ key: "Backspace", run: smartBackspace });
if (keys.length) out.push(Prec.high(keymap.of(keys)));
return out;
}
diff --git a/src/editor/core/cm/setup.ts b/src/editor/core/cm/setup.ts
index b1a6f2a90..3f60ebac2 100644
--- a/src/editor/core/cm/setup.ts
+++ b/src/editor/core/cm/setup.ts
@@ -20,12 +20,12 @@ import {
type LanguageSupport,
type MatchResult,
} from "@codemirror/language";
-import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands";
+import { history, indentWithTab } from "@codemirror/commands";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { highlightSelectionMatches } from "@codemirror/search";
import type { EditorConfigProps } from "@/bindings";
import type { EditorSettings } from "@/platform/ipc";
-import { editorPrefs, type EditorExtras } from "@/platform/editorSettings";
+import { editorPrefs, lineCommentStyleFor, type EditorExtras } from "@/platform/editorSettings";
import { editorContributions, type EditorDocContext } from "@/editor/api";
import { distractionFreeWidth, isDistractionFree } from "@/workbench/distractionFree";
import { openideaHighlightStyle } from "./highlight";
@@ -42,6 +42,8 @@ import { caretExtension, fontZoom, methodLinesField, prefsExtension, softWrapAct
import { commentTokens } from "./languages";
import { multiCaretMouse } from "./multiCaret";
import { columnModeExtension } from "./columnMode";
+import { tabKeymap } from "./smartKeys";
+import { editorBaseKeymap } from "./baseKeymap";
import { clipboardHistoryExtension } from "../clipboardHistory";
import type { LanguageInfo } from "../backend";
@@ -241,6 +243,8 @@ export function prefsFor(o: {
hardWrapAt: hardWrapAt(o.settings, o.info),
readOnly: o.readOnly,
distractionFree: isDistractionFree(),
+ language: o.info?.id,
+ commentStyle: lineCommentStyleFor(prefsOf(o.settings), o.info?.id),
});
}
@@ -298,7 +302,8 @@ export function baseExtensions(o: SetupOptions): Extension {
overviewLane,
codeLensExtension,
EditorView.contentAttributes.of({ spellcheck: "false", autocorrect: "off", autocapitalize: "off", "aria-label": `Editor for ${o.ctx.path}` }),
- keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, indentWithTab]),
+ tabKeymap,
+ keymap.of([...closeBracketsKeymap, ...editorBaseKeymap, indentWithTab]),
compartments.language.of(o.language ?? []),
compartments.comments.of(commentTokens(o.info)),
compartments.indent.of(indentExtension(o.indent ?? effectiveIndent(o.settings, o.info))),
diff --git a/src/editor/core/cm/smartKeys.test.ts b/src/editor/core/cm/smartKeys.test.ts
new file mode 100644
index 000000000..79ce8dd4d
--- /dev/null
+++ b/src/editor/core/cm/smartKeys.test.ts
@@ -0,0 +1,152 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { indentService, indentUnit } from "@codemirror/language";
+import { closeBrackets, insertBracket } from "@codemirror/autocomplete";
+import { autoIndentBackspace, insertTab, smartBackspace, smartBackspaceApplies, tabOutOfScope, tabOutScopes } from "./smartKeys";
+
+/** One unit (2) deeper after a (non-blank) line ending in `{`, one less on a line starting with `}`. */
+const braces = indentService.of((cx, pos) => {
+ let prev = cx.lineAt(pos, -1);
+ do {
+ if (prev.from === 0) return 0;
+ prev = cx.lineAt(prev.from - 1, -1);
+ } while (!prev.text.trim());
+ const base = /^ */.exec(prev.text)![0].length;
+ const own = cx.state.doc.lineAt(pos).text;
+ return Math.max(0, base + (prev.text.trimEnd().endsWith("{") ? 2 : 0) - (/^\s*}/.test(own) ? 2 : 0));
+});
+
+const views: EditorView[] = [];
+afterEach(() => views.splice(0).forEach((v) => v.destroy()));
+
+/** `|` marks carets, `[`/`]` a selection. */
+function make(text: string, extensions: Extension = [], unit = " ") {
+ const ranges: ReturnType<typeof EditorSelection.cursor>[] = [];
+ let doc = "";
+ let anchor = -1;
+ for (const ch of text) {
+ if (ch === "|") ranges.push(EditorSelection.cursor(doc.length));
+ else if (ch === "[") anchor = doc.length;
+ else if (ch === "]") ranges.push(EditorSelection.range(anchor, doc.length));
+ else doc += ch;
+ }
+ const view = new EditorView({
+ state: EditorState.create({
+ doc,
+ selection: EditorSelection.create(ranges.length ? ranges : [EditorSelection.cursor(0)]),
+ extensions: [EditorState.allowMultipleSelections.of(true), EditorState.tabSize.of(4), indentUnit.of(unit), extensions],
+ }),
+ parent: document.body,
+ });
+ views.push(view);
+ return view;
+}
+
+function show(view: EditorView): string {
+ const { doc, selection } = view.state;
+ let out = doc.toString();
+ for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
+ out = r.empty ? out.slice(0, r.head) + "|" + out.slice(r.head) : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
+ return out;
+}
+
+describe("tab", () => {
+ it("inserts whitespace up to the next indent stop at each caret", () => {
+ const v = make("ab|c\n|x");
+ insertTab(v);
+ expect(show(v)).toBe("ab |c\n |x");
+ });
+
+ it("inserts a tab character when the code style uses tabs", () => {
+ const v = make("a|b", [], "\t");
+ insertTab(v);
+ expect(show(v)).toBe("a\t|b");
+ });
+
+ it("indents the lines of a selection", () => {
+ const v = make("[a\nb]");
+ insertTab(v);
+ expect(v.state.doc.toString()).toBe(" a\n b");
+ });
+
+ it("replaces a whitespace-only selection like a caret", () => {
+ const v = make("a[ ]b");
+ insertTab(v);
+ expect(show(v)).toBe("a |b");
+ });
+});
+
+describe("smart backspace", () => {
+ it("applies in 'proper indent' mode except in indentation-based languages", () => {
+ expect(smartBackspaceApplies("autoindent", "java")).toBe(true);
+ expect(smartBackspaceApplies("autoindent", "python")).toBe(false);
+ expect(smartBackspaceApplies("nearest", "java")).toBe(false);
+ });
+
+ it("goes back to the proper indent from deeper whitespace", () => {
+ const v = make("f {\n |x\n}", braces);
+ smartBackspace(v);
+ expect(show(v)).toBe("f {\n |x\n}");
+ });
+
+ it("joins with the line above at the proper indent", () => {
+ const v = make("f {\n a\n |b\n}", braces);
+ smartBackspace(v);
+ expect(show(v)).toBe("f {\n a |b\n}");
+ });
+
+ it("moves text up over a blank line at its proper indent", () => {
+ const v = make("f {\n a\n\n |b\n}", braces);
+ smartBackspace(v);
+ expect(show(v)).toBe("f {\n a\n |b\n}");
+ });
+
+ it("joins an empty line without leaving a space", () => {
+ const v = make("f {\n a\n |\n}", braces);
+ smartBackspace(v);
+ expect(show(v)).toBe("f {\n a|\n}");
+ });
+
+ it("leaves Backspace after text to the default", () => {
+ const v = make("f {\n a|b\n}", braces);
+ expect(autoIndentBackspace(v.state, v.state.selection.main.head)).toBeNull();
+ expect(smartBackspace(v)).toBe(false);
+ });
+});
+
+describe("tab out of pairs", () => {
+ const ext = [closeBrackets(), tabOutScopes];
+ const type = (v: EditorView, ch: string) => {
+ const tr = insertBracket(v.state, ch);
+ if (tr) v.dispatch(tr);
+ else v.dispatch(v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" }));
+ };
+
+ it("steps over a closing bracket the editor inserted", () => {
+ const v = make("f|", ext);
+ type(v, "(");
+ type(v, "x");
+ expect(show(v)).toBe("f(x|)");
+ expect(insertTab(v)).toBe(true);
+ expect(show(v)).toBe("f(x)|");
+ // Once out, Tab inserts whitespace again.
+ insertTab(v);
+ expect(show(v)).toBe("f(x) |");
+ });
+
+ it("ignores closers the user typed", () => {
+ const v = make("f(x|)", ext);
+ expect(tabOutOfScope(v)).toBe(false);
+ });
+
+ it("keeps the pair through edits elsewhere while the caret is inside, else forgets it", () => {
+ const v = make("a f|", ext);
+ type(v, "(");
+ v.dispatch({ changes: { from: 0, to: 1, insert: "bb" } });
+ expect(show(v)).toBe("bb f(|)");
+ v.dispatch({ selection: { anchor: 0 } });
+ v.dispatch({ changes: { from: 0, insert: "c" }, selection: { anchor: 6 } });
+ expect(tabOutOfScope(v)).toBe(false);
+ });
+});
diff --git a/src/editor/core/cm/smartKeys.ts b/src/editor/core/cm/smartKeys.ts
new file mode 100644
index 000000000..870865c94
--- /dev/null
+++ b/src/editor/core/cm/smartKeys.ts
@@ -0,0 +1,144 @@
+/**
+ * IDEA-style Tab, smart Backspace and Tab out of auto-inserted brackets and
+ * quotes.
+ */
+import { EditorSelection, StateEffect, countColumn, StateField, type EditorState, type Extension, type Transaction } from "@codemirror/state";
+import { keymap, type Command } from "@codemirror/view";
+import { getIndentUnit, getIndentation, indentString, indentUnit } from "@codemirror/language";
+import { indentMore } from "@codemirror/commands";
+
+// --- Tab -------------------------------------------------------------------------------
+
+/**
+ * Tab: steps out of an auto-inserted pair (when enabled); with a selection
+ * holding more than whitespace, indents the selected lines; otherwise inserts
+ * whitespace at each caret up to the next indent stop (a tab character when
+ * the code style uses tabs). Live templates / Emmet get Tab first.
+ */
+export const insertTab: Command = (view) => {
+ const { state } = view;
+ if (state.readOnly) return false;
+ if (tabOutOfScope(view)) return true;
+ if (state.selection.ranges.some((r) => !r.empty && state.sliceDoc(r.from, r.to).trim())) return indentMore(view);
+ const useTab = state.facet(indentUnit) === "\t";
+ const size = Math.max(1, getIndentUnit(state));
+ const tr = state.changeByRange((r) => {
+ const line = state.doc.lineAt(r.from);
+ const col = countColumn(line.text.slice(0, r.from - line.from), state.tabSize);
+ const insert = useTab ? "\t" : " ".repeat(size - (col % size));
+ return { changes: { from: r.from, to: r.to, insert }, range: EditorSelection.cursor(r.from + insert.length) };
+ });
+ view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input" }));
+ return true;
+};
+
+/** Tab ahead of the default `indentWithTab` (⇧Tab stays Unindent). */
+export const tabKeymap: Extension = keymap.of([{ key: "Tab", run: insertTab }]);
+
+// --- Backspace -------------------------------------------------------------------------------
+
+/** Languages whose layout is indentation: IDEA keeps "to nearest indent position" there. */
+const NEAREST_INDENT_LANGS = new Set(["python", "yaml", "shellscript"]);
+
+export function smartBackspaceApplies(mode: string, language: string | undefined): boolean {
+ return mode === "autoindent" && !NEAREST_INDENT_LANGS.has(language ?? "");
+}
+
+/** The change one Backspace makes at `pos` in "To proper indent position" mode, or null to delete normally. */
+export function autoIndentBackspace(state: EditorState, pos: number): { from: number; to: number; insert: string } | null {
+ const doc = state.doc;
+ const line = doc.lineAt(pos);
+ if (/[^ \t]/.test(doc.sliceString(line.from, pos))) return null;
+ const target = getIndentation(state, line.from);
+ if (target === null) return null;
+ const end = pos + /^[ \t]*/.exec(doc.sliceString(pos, line.to))![0].length;
+ const current = countColumn(doc.sliceString(line.from, end), state.tabSize);
+ if (current > target) return { from: line.from, to: end, insert: indentString(state, target) };
+ if (line.number === 1) return end > 0 ? { from: 0, to: end, insert: "" } : null;
+ const prev = doc.line(line.number - 1);
+ const prevEnd = prev.from + prev.text.trimEnd().length;
+ if (prevEnd === prev.from && prevEnd !== 0) {
+ // A blank line above: the text moves up, at its proper indent.
+ return { from: prevEnd, to: end, insert: indentString(state, target) };
+ }
+ const before = doc.sliceString(prev.from, prevEnd);
+ const after = doc.sliceString(end, line.to);
+ const space = !after || !before || /[([{]$/.test(before) || /^[)\]}.,;]/.test(after) ? "" : " ";
+ return { from: prevEnd, to: end, insert: space };
+}
+
+/** Backspace in leading whitespace: to the proper indent, or joined with the line above when already there. */
+export const smartBackspace: Command = (view) => {
+ const { state } = view;
+ if (state.readOnly || state.selection.ranges.some((r) => !r.empty)) return false;
+ const plans = state.selection.ranges.map((r) => autoIndentBackspace(state, r.head));
+ if (plans.some((p) => !p)) return false;
+ const tr = state.changeByRange((r) => {
+ const p = plans[state.selection.ranges.indexOf(r)]!;
+ return { changes: p, range: EditorSelection.cursor(p.from + p.insert.length) };
+ });
+ view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "delete.backward" }));
+ return true;
+};
+
+// --- Tab out of brackets / quotes ------------------------------------------------------------
+
+const PAIRS: Record<string, string> = { "(": ")", "[": "]", "{": "}", '"': '"', "'": "'", "`": "`" };
+
+interface Scope {
+ from: number;
+ to: number;
+}
+
+const leaveScopes = StateEffect.define<readonly number[]>();
+
+/** Inside each pair the editor inserted itself; Tab at a scope's end steps over the closing character. */
+export const tabOutScopes = StateField.define<readonly Scope[]>({
+ create: () => [],
+ update(scopes, tr) {
+ for (const e of tr.effects) if (e.is(leaveScopes)) scopes = scopes.filter((s) => !e.value.includes(s.to));
+ if (!tr.docChanged) return scopes;
+ const caret = tr.startState.selection.main.head;
+ let next: Scope[] = scopes.filter((s) => {
+ let keep = true;
+ tr.changes.iterChangedRanges((fromA, toA) => {
+ const outside = fromA < s.from || toA > s.to;
+ if (outside && (caret < s.from || caret > s.to || (toA >= s.from && fromA <= s.to))) keep = false;
+ });
+ return keep;
+ });
+ next = next.map((s) => ({ from: tr.changes.mapPos(s.from, -1), to: tr.changes.mapPos(s.to, 1) }));
+ return [...next, ...insertedPairs(tr)];
+ },
+});
+
+/** Empty scopes between the bracket / quote pairs a typing transaction auto-inserted. */
+function insertedPairs(tr: Transaction): Scope[] {
+ if (!tr.isUserEvent("input.type")) return [];
+ const out: Scope[] = [];
+ tr.changes.iterChanges((_fa, _ta, fromB, toB, inserted) => {
+ const text = inserted.toString();
+ if (toB - fromB !== 2 || PAIRS[text[0]!] !== text[1]) return;
+ const inside = fromB + 1;
+ if (tr.newSelection.ranges.some((r) => r.empty && r.head === inside)) out.push({ from: inside, to: inside });
+ });
+ return out;
+}
+
+export const tabOutOfScope: Command = (view) => {
+ const { state } = view;
+ const scopes = state.field(tabOutScopes, false);
+ if (!scopes?.length || state.selection.ranges.some((r) => !r.empty || !scopes.some((s) => s.to === r.head))) return false;
+ view.dispatch({
+ selection: EditorSelection.create(
+ state.selection.ranges.map((r) => EditorSelection.cursor(Math.min(r.head + 1, state.doc.length))),
+ state.selection.mainIndex,
+ ),
+ effects: leaveScopes.of(state.selection.ranges.map((r) => r.head)),
+ userEvent: "select",
+ });
+ return true;
+};
+
+/** Settings › Smart Keys › "Jump outside closing bracket/quote with Tab" (Tab itself is `insertTab`). */
+export const tabOut: Extension = tabOutScopes;
diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts
index cfdfd936e..60b1a1f65 100644
--- a/src/editor/core/controller.ts
+++ b/src/editor/core/controller.ts
@@ -404,7 +404,7 @@ export class EditorController implements SlotHost {
path: slot?.model.path ?? nonTextTab?.input.path ?? null,
doc: slot?.model.doc ?? null,
});
- if (slot) this.recordNav(slot);
+ if (slot) this.recordNav(slot, true);
}
this.scheduleStatus();
}
@@ -431,8 +431,13 @@ export class EditorController implements SlotHost {
if (this.autoSave()) void slot.model.save("auto").catch(() => {});
}
- onSelection(slot: EditorSlot) {
+ onSelection(slot: EditorSlot, navigatedFrom?: { line: number; col: number }) {
if (slot !== this.activeSlot) return;
+ if (navigatedFrom && this.navSuppress === 0 && !slot.disposed) {
+ // The place left behind is where the caret was right before the navigation.
+ this.nav.update({ path: slot.model.path, ...navigatedFrom });
+ this.recordNav(slot, true);
+ }
// The status bar reflects the view state synchronously (programmatic and
// synthetic selection changes included); events / history are throttled.
this.publishStatus(slot);
@@ -661,10 +666,11 @@ export class EditorController implements SlotHost {
// --- navigation history --------------------------------------------------------------
- private recordNav(slot: EditorSlot) {
+ /** `navigation`: the caret got here by a navigation (see NavigationHistory.update). */
+ private recordNav(slot: EditorSlot, navigation = false) {
if (this.navSuppress > 0 || slot.disposed) return;
const c = slot.caret();
- this.nav.update({ path: slot.model.path, line: c.line, col: c.col });
+ this.nav.update({ path: slot.model.path, line: c.line, col: c.col }, navigation);
}
async navigateTo(loc: NavigationLocation | null) {
@@ -804,7 +810,7 @@ export class EditorController implements SlotHost {
}
} finally {
this.navSuppress--;
- if (this.navSuppress === 0 && this.activeSlot) this.recordNav(this.activeSlot);
+ if (this.navSuppress === 0 && this.activeSlot) this.recordNav(this.activeSlot, true);
}
}
@@ -872,6 +878,10 @@ export class EditorController implements SlotHost {
togglePin(paneId: string, tabId: string) {
this.apply((s) => togglePin(s, paneId, tabId));
}
+ /** Turns a preview tab into a regular one (double-click on the tab). */
+ keepTab(paneId: string, tabId: string) {
+ this.apply((s) => (s.panes[paneId] ? promoteTab(s, paneId, tabId) : s));
+ }
/** Drag & drop; the tab keeps its id (and slot) when moved within a pane. */
moveTab(fromPane: string, tabId: string, toPane: string, index: number) {
this.apply((s) => moveTab(s, fromPane, tabId, toPane, index));
@@ -976,6 +986,23 @@ export class EditorController implements SlotHost {
pane?.querySelector<HTMLElement>("[data-editor-focus], .cm-content")?.focus({ preventScroll: true });
}
+ openPaths(): string[] {
+ const s = useTabs.getState();
+ const out = new Set<string>();
+ for (const id of paneIds(s)) for (const t of s.panes[id]?.tabs ?? []) if (t.input.path) out.add(t.input.path);
+ return [...out];
+ }
+
+ closePath(path: string) {
+ this.apply((s) => {
+ const keys = new Set<string>();
+ for (const pane of Object.values(s.panes)) for (const t of pane.tabs) if (t.input.path === path) keys.add(t.input.key);
+ let next = s;
+ for (const key of keys) next = closeKey(next, key);
+ return next;
+ });
+ }
+
activePath(): string | null {
return this.activeSlot?.model.path ?? this.activeTabOf()?.input.path ?? null;
}
diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts
index b3d067d20..9796bcd69 100644
--- a/src/editor/core/index.ts
+++ b/src/editor/core/index.ts
@@ -37,6 +37,8 @@ export function activate(): void | (() => void) {
activeCursor: () => ctrl.activeCursor(),
saveAll: () => ctrl.saveAll(),
focus: () => ctrl.focus(),
+ openPaths: () => ctrl.openPaths(),
+ closePath: (path) => ctrl.closePath(path),
});
_provideDocumentAttacher((path) => attachDocument(ctrl.manager, path));
const disposers = [
diff --git a/src/editor/core/model/model.test.ts b/src/editor/core/model/model.test.ts
index 258bcc928..360d0dfea 100644
--- a/src/editor/core/model/model.test.ts
+++ b/src/editor/core/model/model.test.ts
@@ -16,6 +16,7 @@ import {
promoteTab,
reopenClosed,
splitPane,
+ tabOptions,
togglePin,
type TabsState,
} from "./tabs";
@@ -94,14 +95,46 @@ describe("tab model", () => {
expect(labels(s)).toEqual(["a^", "d"]);
});
- it("activates the most recently used tab when closing the active one", () => {
+ it("activates the left neighbour when closing the active tab (IDEA default)", () => {
let s = initialTabsState();
for (const p of ["a", "b", "c"]) s = open(s, p);
s = openTab(s, s.activePane, file("a")).state;
s = openTab(s, s.activePane, file("c")).state;
- const c = findTab(s, "file:c")!.tab;
- s = closeTab(s, s.activePane, c.id);
- expect(active(s)).toBe("a");
+ s = closeTab(s, s.activePane, findTab(s, "file:c")!.tab.id);
+ expect(active(s)).toBe("b");
+ // The first tab has no left neighbour: the right one.
+ s = openTab(s, s.activePane, file("a")).state;
+ s = closeTab(s, s.activePane, findTab(s, "file:a")!.tab.id);
+ expect(active(s)).toBe("b");
+ });
+
+ it("activates the most recently used tab when closing the active one if set", () => {
+ tabOptions.activateOnClose = "mru";
+ try {
+ let s = initialTabsState();
+ for (const p of ["a", "b", "c"]) s = open(s, p);
+ s = openTab(s, s.activePane, file("a")).state;
+ s = openTab(s, s.activePane, file("c")).state;
+ const c = findTab(s, "file:c")!.tab;
+ s = closeTab(s, s.activePane, c.id);
+ expect(active(s)).toBe("a");
+ } finally {
+ tabOptions.activateOnClose = "left";
+ }
+ });
+
+ it("closes the preview tab when a regular tab opens", () => {
+ let s = initialTabsState();
+ s = open(s, "a");
+ s = open(s, "p", { preview: true });
+ s = open(s, "b");
+ expect(labels(s)).toEqual(["a", "b"]);
+ expect(active(s)).toBe("b");
+ expect(s.panes[s.activePane]!.mru).toHaveLength(2);
+ // Reopening an existing regular tab keeps the preview.
+ s = open(s, "q", { preview: true });
+ s = open(s, "a");
+ expect(labels(s)).toEqual(["a", "b", "q*"]);
});
it("reopens closed tabs at their position, most recent first", () => {
@@ -151,17 +184,19 @@ describe("tab model", () => {
});
describe("navigation history", () => {
- it("records file switches and big jumps, merges small moves", () => {
+ it("records file switches and navigations, not plain caret moves", () => {
let t = 0;
const h = new NavigationHistory(() => ++t);
h.update({ path: "a", line: 1, col: 0 });
h.update({ path: "a", line: 5, col: 2 });
+ // Arrows / paging / typing move the current place, however far.
+ h.update({ path: "a", line: 300, col: 0 });
expect(h.entries).toHaveLength(1);
- h.update({ path: "a", line: 100, col: 0 });
+ h.update({ path: "a", line: 100, col: 0 }, true);
h.update({ path: "b", line: 0, col: 0 });
- expect(h.entries.map((e) => `${e.path}:${e.line}`)).toEqual(["a:5", "a:100", "b:0"]);
+ expect(h.entries.map((e) => `${e.path}:${e.line}`)).toEqual(["a:300", "a:100", "b:0"]);
expect(h.back()).toMatchObject({ path: "a", line: 100 });
- expect(h.back()).toMatchObject({ path: "a", line: 5 });
+ expect(h.back()).toMatchObject({ path: "a", line: 300 });
expect(h.back()).toBeNull();
expect(h.forward()).toMatchObject({ path: "a", line: 100 });
// Navigating somewhere new from the middle drops the forward stack.
@@ -172,6 +207,25 @@ describe("navigation history", () => {
expect(h.snapshot()).toMatchObject({ index: 0, entries: [{ path: "c" }] });
});
+ it("a navigation on the same line records nothing", () => {
+ const h = new NavigationHistory();
+ h.update({ path: "a", line: 7, col: 0 });
+ h.update({ path: "a", line: 7, col: 9 }, true);
+ expect(h.entries).toHaveLength(1);
+ });
+
+ it("merges back places less than four lines apart", () => {
+ const h = new NavigationHistory();
+ h.update({ path: "a", line: 10, col: 0 });
+ h.update({ path: "a", line: 50, col: 0 }, true);
+ h.update({ path: "a", line: 12, col: 0 });
+ h.update({ path: "a", line: 80, col: 0 }, true);
+ // a:10 and a:12 are one place: the newer one stays.
+ expect(h.entries.map((e) => e.line)).toEqual([12, 80]);
+ h.update({ path: "a", line: 20, col: 0 }, true);
+ expect(h.entries.map((e) => e.line)).toEqual([12, 80, 20]);
+ });
+
it("arriving at a back target updates it in place", () => {
const h = new NavigationHistory();
h.update({ path: "a", line: 0, col: 0 });
diff --git a/src/editor/core/model/navHistory.ts b/src/editor/core/model/navHistory.ts
index b843e8843..384612a3a 100644
--- a/src/editor/core/model/navHistory.ts
+++ b/src/editor/core/model/navHistory.ts
@@ -1,14 +1,31 @@
/**
- * Back / Forward navigation history (⌘[ / ⌘]), like IDEA's: the current
- * place is continuously updated while the caret moves locally; a file switch
- * or a jump of more than `JUMP_LINES` lines starts a new entry and drops the
- * forward stack.
+ * Back / Forward navigation history (⌘[ / ⌘]), like IDEA's:
+ * `entries[index]` is the current place, kept up to
+ * date while the caret moves. Only a navigation (a file switch, a mouse click,
+ * a jump to a declaration / usage / search result / line …) that changes the
+ * caret line leaves the previous place behind as a back entry and drops the
+ * forward stack; typing, arrows and paging don't. A back entry within
+ * `MERGE_LINES` of the one before it replaces it.
*/
+import type { Transaction } from "@codemirror/state";
import type { NavigationLocation } from "@/editor/api";
-export const JUMP_LINES = 10;
+export const MERGE_LINES = 4;
+
+/** userEvent of in-file navigation commands (method up / down, code block start / end…). */
+export const NAVIGATE_EVENT = "select.navigate";
+
+/** Caret moves that count as navigation: mouse clicks, find, reveals, stripe / sticky-line clicks, navigate commands. */
+export function isNavigation(tr: Transaction): boolean {
+ return ["select.pointer", "select.reveal", "select.search", "select.overview", "select.sticky", NAVIGATE_EVENT].some((e) =>
+ tr.isUserEvent(e),
+ );
+}
const MAX_ENTRIES = 100;
+const samePlace = (a: Omit<NavigationLocation, "time">, b: Omit<NavigationLocation, "time">) =>
+ a.path === b.path && Math.abs(a.line - b.line) < MERGE_LINES;
+
export class NavigationHistory {
entries: NavigationLocation[] = [];
index = -1;
@@ -28,18 +45,28 @@ export class NavigationHistory {
return this.index < this.entries.length - 1;
}
- /** Records the caret position after a selection change / tab switch. */
- update(loc: Omit<NavigationLocation, "time">) {
+ /**
+ * Records the caret position. `navigation`: the move came from a navigation
+ * command; a file switch always counts as one.
+ */
+ update(loc: Omit<NavigationLocation, "time">, navigation = false) {
const entry = { ...loc, time: this.now() };
const cur = this.current;
- if (cur && cur.path === loc.path && Math.abs(cur.line - loc.line) <= JUMP_LINES) {
+ if (!cur) {
+ this.entries = [entry];
+ this.index = 0;
+ this.emit();
+ return;
+ }
+ const switched = cur.path !== loc.path;
+ if (!switched && (!navigation || cur.line === loc.line)) {
this.entries[this.index] = entry;
return;
}
+ // The place we leave becomes a back entry, merged with a close one before it.
this.entries = this.entries.slice(0, this.index + 1);
- // Revisiting the place we came from shouldn't stutter the history.
- const prev = this.entries[this.entries.length - 1];
- if (prev && prev.path === loc.path && prev.line === loc.line) this.entries.pop();
+ const prev = this.entries[this.index - 1];
+ if (prev && samePlace(prev, cur)) this.entries.splice(this.index - 1, 1);
this.entries.push(entry);
if (this.entries.length > MAX_ENTRIES) this.entries.splice(0, this.entries.length - MAX_ENTRIES);
this.index = this.entries.length - 1;
diff --git a/src/editor/core/model/session.test.ts b/src/editor/core/model/session.test.ts
index eb45e258f..3cd45ef51 100644
--- a/src/editor/core/model/session.test.ts
+++ b/src/editor/core/model/session.test.ts
@@ -13,8 +13,9 @@ describe("editor session", () => {
s = open(s, "/p/a.ts");
s = open(s, "/p/b.ts");
s = togglePin(s, s.activePane, s.panes[s.activePane]!.tabs[1]!.id);
- s = open(s, "/p/c.ts", { preview: true });
s = openTab(s, s.activePane, { kind: "diff", key: "diff:x", data: { big: true } }).state;
+ // A regular tab opened later would close the preview: open it in the background last.
+ s = open(s, "/p/c.ts", { preview: true, activate: false });
const first = s.activePane;
s = splitPane(s, first, "column").state;
s = open(s, "/p/d.ts");
diff --git a/src/editor/core/model/slot.ts b/src/editor/core/model/slot.ts
index 03f8067b7..3352d91b5 100644
--- a/src/editor/core/model/slot.ts
+++ b/src/editor/core/model/slot.ts
@@ -23,11 +23,13 @@ import { showContextMenu } from "@/ui";
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
import type { DocModel } from "./document";
+import { isNavigation } from "./navHistory";
export interface SlotHost {
onFocus(slot: EditorSlot): void;
onBlur(slot: EditorSlot): void;
- onSelection(slot: EditorSlot): void;
+ /** `navigatedFrom`: the caret before a navigation transaction (mouse click, find, jump…). */
+ onSelection(slot: EditorSlot, navigatedFrom?: { line: number; col: number }): void;
onUserEdit(slot: EditorSlot, tr: Transaction): void;
onContextMenu(slot: EditorSlot, e: MouseEvent): void;
/** Escape in the editor (close the find bar…); return true when handled. */
@@ -175,7 +177,13 @@ export class EditorSlot {
private onTransactions(trs: readonly Transaction[], view: EditorView) {
view.update(trs);
let selection = false;
+ let navigatedFrom: { line: number; col: number } | undefined;
for (const tr of trs) {
+ if (!navigatedFrom && tr.selection && isNavigation(tr)) {
+ const head = tr.startState.selection.main.head;
+ const line = tr.startState.doc.lineAt(head);
+ navigatedFrom = { line: line.number - 1, col: head - line.from };
+ }
if (tr.docChanged && !isExternalChange(tr)) {
this.model.onLocal(tr.changes, this);
if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move") || tr.isUserEvent("undo") || tr.isUserEvent("redo"))
@@ -183,7 +191,7 @@ export class EditorSlot {
}
if (tr.selection || tr.docChanged) selection = true;
}
- if (selection) this.host.onSelection(this);
+ if (selection) this.host.onSelection(this, navigatedFrom);
}
/** Applies a transaction as if the user made it (synced, undoable). */
diff --git a/src/editor/core/model/tabs.ts b/src/editor/core/model/tabs.ts
index b88de1171..7a460c20b 100644
--- a/src/editor/core/model/tabs.ts
+++ b/src/editor/core/model/tabs.ts
@@ -1,11 +1,12 @@
/**
* Editor tabs and splits as pure state transitions (IDEA semantics):
* - one preview tab per pane (italic), replaced by the next preview, promoted
- * to a regular tab when edited or opened explicitly;
+ * to a regular tab when edited or opened explicitly, closed when another
+ * regular tab opens;
* - pinned tabs stay at the front and survive Close Others / Close Tabs to the
* Right / Close All but Pinned;
- * - new tabs open right of the active tab; closing activates the most
- * recently used tab of the pane;
+ * - new tabs open right of the active tab; closing activates the left
+ * neighbour (or the right one / the most recently used, per settings);
* - splits form a tree of rows / columns; an emptied pane collapses away
* unless it is the last one.
*/
@@ -48,7 +49,7 @@ export interface TabsState {
const MAX_CLOSED = 50;
/** Editor Tabs › "When the current tab is closed, activate": set from settings by the controller. */
-export const tabOptions: { activateOnClose: "mru" | "left" | "right" } = { activateOnClose: "mru" };
+export const tabOptions: { activateOnClose: "mru" | "left" | "right" } = { activateOnClose: "left" };
let seq = 0;
const nextId = (p: string) => `${p}${++seq}`;
@@ -150,7 +151,15 @@ export function openTab(
}
tabs.splice(index, 0, tab);
}
- pane = { ...pane, tabs, mru: activate ? mru : [...mru, tab.id] };
+ let active = pane.active;
+ if (!tab.preview && tabs.some((t) => t.preview)) {
+ // A new regular editor closes the preview tab (IDEA trims previews on every open).
+ const previews = new Set(tabs.filter((t) => t.preview).map((t) => t.id));
+ tabs.splice(0, tabs.length, ...tabs.filter((t) => !previews.has(t.id)));
+ mru = mru.filter((id) => !previews.has(id));
+ if (active && previews.has(active)) active = null;
+ }
+ pane = { ...pane, tabs, active, mru: activate ? mru : [...mru, tab.id] };
pane = activate ? touch(pane, tab.id) : { ...pane, active: pane.active ?? tab.id };
return { state: { ...withPane(s, pane), activePane: activate ? paneId : s.activePane }, tabId: tab.id };
}
diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx
index e14ac42b9..a87773e54 100644
--- a/src/editor/core/view/EditorArea.tsx
+++ b/src/editor/core/view/EditorArea.tsx
@@ -1,11 +1,13 @@
/**
* The editor area: split layout of panes, each with IDEA-style tabs (preview
* tab in italics, pinned tabs, modified dot, file icons coloured by file
- * decorations, middle-click close, context menu) and the active editor.
+ * decorations, middle-click close, Alt+click close others, double-click to
+ * keep a preview / maximize the editor, context menu) and the active editor.
*/
import { Fragment, useMemo, useRef, useState, type DragEvent, type FocusEvent, type ReactNode } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
+import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { useEditorPrefs } from "@/platform/editorSettings";
import { basename, dirname } from "@/platform/project";
@@ -252,6 +254,12 @@ function PaneView({ paneId }: { paneId: string }) {
dnd={dnd}
onSelect={(id) => ctrl.activate(paneId, id)}
onClose={(id) => ctrl.closeTab(paneId, id)}
+ onCloseOthers={(id) => ctrl.closeOthers(paneId, id)}
+ onDoubleClick={(id) => {
+ // IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
+ if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
+ else void executeAction("toolwindow.hideAll");
+ }}
onContextMenu={(id, e) => {
const tab = pane.tabs.find((t) => t.id === id);
if (!tab) return;
diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx
index 8ce10a071..be0e0fa45 100644
--- a/src/editor/core/view/FindBar.tsx
+++ b/src/editor/core/view/FindBar.tsx
@@ -1,7 +1,7 @@
/**
* IDEA-style Find / Replace bar at the top of the editor (⌘F / ⌘R): search
* field with Match Case / Words / Regex toggles (⌥C / ⌥W / ⌥X), In Selection
- * (on by default when opened over a multi-line selection), n/N counter,
+ * (on by default when Replace opens over a multi-line selection), n/N counter,
* ↑/↓ (⇧↵ / ↵), Replace / Replace All, Esc closes.
*/
import { useEffect, useLayoutEffect, useRef, type KeyboardEvent } from "react";
@@ -52,24 +52,41 @@ export function closeFindBar(paneId: string) {
useFindBars.setState({ [paneId]: undefined });
}
-/** Opens (or refocuses) the bar; a single-line selection becomes the query. */
+/** Longest selection that becomes the query. */
+const MAX_QUERY = 10_000;
+
+/**
+ * Opens (or refocuses) the bar, as in IDEA: the
+ * selection becomes the query — multi-line too — and the search covers the
+ * file, except that Replace over a multi-line selection searches in it. A
+ * multi-line query isn't kept for a later search without a selection.
+ */
export function openFindBar(paneId: string, replace: boolean) {
const view = activeView(paneId);
const sel = view?.state.selection.main;
if (view && sel && !sel.empty) {
- const text = view.state.sliceDoc(sel.from, Math.min(sel.to, sel.from + 500));
+ const text = view.state.sliceDoc(sel.from, sel.to);
+ const multiline = text.includes("\n");
openSelections.set(paneId, { from: sel.from, to: sel.to });
- if (text.includes("\n") || sel.to - sel.from >= 500) {
- // A multi-line selection becomes the search scope, like IDEA.
+ if (multiline && replace) {
view.dispatch({ effects: setFindScope.of({ from: sel.from, to: sel.to }) });
+ useFindOptions.setState({ search: "" });
} else {
view.dispatch({ effects: setFindScope.of(null) });
- useFindOptions.setState((o) => ({ search: o.regexp ? text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : text }));
+ if (text.length < MAX_QUERY)
+ useFindOptions.setState((o) => ({ search: o.regexp ? text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : text }));
}
+ } else if (useFindOptions.getState().search.includes("\n")) {
+ useFindOptions.setState({ search: "" });
}
useFindBars.setState((s) => ({ [paneId]: { replace, seq: (s[paneId]?.seq ?? 0) + 1 } }));
}
+/** Show / Hide Replace on the open bar, keeping its query and scope. */
+function setReplaceShown(paneId: string, replace: boolean) {
+ useFindBars.setState((s) => ({ [paneId]: { replace, seq: s[paneId]?.seq ?? 0 } }));
+}
+
/** ⌘G / ⇧⌘G: next / previous occurrence of the last search, with or without the bar. */
export function findAgain(paneId: string, forward: boolean) {
const view = activeView(paneId);
@@ -290,7 +307,7 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
title={replace ? "Hide Replace" : "Show Replace"}
size="small"
pressed={replace}
- onClick={() => openFindBar(paneId, !replace)}
+ onClick={() => setReplaceShown(paneId, !replace)}
/>
</div>
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
diff --git a/src/editor/core/view/NavBarPopup.module.css b/src/editor/core/view/NavBarPopup.module.css
index fff146b39..8c6eda656 100644
--- a/src/editor/core/view/NavBarPopup.module.css
+++ b/src/editor/core/view/NavBarPopup.module.css
@@ -77,3 +77,24 @@
padding: 4px 6px;
color: var(--fg-muted);
}
+.childList {
+ min-width: 200px;
+ max-height: 360px;
+ overflow-y: auto;
+ padding: 4px;
+ outline: none;
+}
+.childHeader {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: var(--h-list-row);
+ padding: 0 6px;
+ margin-bottom: 2px;
+ border-bottom: 1px solid var(--border-popup);
+ color: var(--fg-muted);
+}
+.rowChevron {
+ margin-left: auto;
+ color: var(--fg-faint);
+}
diff --git a/src/editor/core/view/NavBarPopup.tsx b/src/editor/core/view/NavBarPopup.tsx
index a196795a8..363ba62df 100644
--- a/src/editor/core/view/NavBarPopup.tsx
+++ b/src/editor/core/view/NavBarPopup.tsx
@@ -210,3 +210,111 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
</Popup>
);
}
+
+/**
+ * The status bar navigation bar's popup (as IDEA's navigation bar): clicking
+ * a segment lists its children; a folder lists its own (← goes back), a file
+ * or symbol opens.
+ */
+export function NavChildrenPopup({
+ segment,
+ anchor,
+ onClose,
+}: {
+ segment: NavSegment;
+ anchor: HTMLElement;
+ onClose: () => void;
+}) {
+ const [stack, setStack] = useState<NavSegment[]>([segment]);
+ const top = stack[stack.length - 1]!;
+ const outline = useOutline((s) => s[top.path]);
+ const [loaded, setLoaded] = useState<{ top: NavSegment; items: NavChild[] } | null>(null);
+ const [active, setActive] = useState(0);
+ const listRef = useRef<HTMLDivElement>(null);
+ const items = loaded?.top === top ? loaded.items : null;
+
+ useEffect(() => {
+ let alive = true;
+ void childrenOf(top, outline)
+ .catch((): NavChild[] => [])
+ .then((list) => {
+ if (!alive) return;
+ setLoaded({ top, items: list });
+ setActive(0);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [top, outline]);
+ useEffect(() => {
+ listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" });
+ }, [active, items]);
+
+ const choose = (child: NavChild) => {
+ if (child.kind === "dir") return setStack((s) => [...s, { kind: "dir", path: child.path, label: child.label }]);
+ onClose();
+ if (child.kind === "file") void editorController().openFile(child.path, { focus: true });
+ else {
+ const p = child.item.selection_range.start;
+ void editorController().openFile(child.path, { selection: { line: p.line, col: p.col }, focus: true });
+ }
+ };
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ const n = items?.length ?? 0;
+ let handled = true;
+ if (e.key === "ArrowDown" && n) setActive((a) => (a + 1) % n);
+ else if (e.key === "ArrowUp" && n) setActive((a) => (a - 1 + n) % n);
+ else if (e.key === "Enter" || (e.key === "ArrowRight" && items?.[active]?.kind === "dir")) {
+ const child = items?.[active];
+ if (child) choose(child);
+ } else if (e.key === "ArrowLeft" && stack.length > 1) setStack((s) => s.slice(0, -1));
+ else handled = false;
+ if (handled) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ };
+
+ return (
+ <Popup open anchor={anchor} placement="top-start" onClose={onClose} aria-label={top.label} className={styles.popup}>
+ <div
+ ref={listRef}
+ className={styles.childList}
+ role="listbox"
+ aria-label={top.label}
+ tabIndex={0}
+ data-autofocus
+ aria-activedescendant={items?.length ? `navbar-child-${active}` : undefined}
+ onKeyDown={onKeyDown}
+ >
+ {stack.length > 1 && (
+ <div className={styles.childHeader}>
+ <Icon name={iconOf(top)} size={14} />
+ <span className={styles.rowLabel}>{top.label}</span>
+ </div>
+ )}
+ {items?.length === 0 && (
+ <div className={styles.empty}>
+ <T>Nothing here</T>
+ </div>
+ )}
+ {items?.map((c, i) => (
+ <div
+ key={`${c.path}:${c.label}:${i}`}
+ id={`navbar-child-${i}`}
+ role="option"
+ aria-selected={i === active}
+ className={clsx(styles.row, i === active && styles.rowActive)}
+ onMouseEnter={() => setActive(i)}
+ onClick={() => choose(c)}
+ >
+ <Icon name={iconOf(c)} size={14} />
+ <span className={styles.rowLabel}>{c.label}</span>
+ {c.kind === "dir" && <Icon name="chevron-right" size={12} className={styles.rowChevron} />}
+ </div>
+ ))}
+ </div>
+ </Popup>
+ );
+}
diff --git a/src/editor/core/view/StatusItems.tsx b/src/editor/core/view/StatusItems.tsx
index ced7676d6..853829ba8 100644
--- a/src/editor/core/view/StatusItems.tsx
+++ b/src/editor/core/view/StatusItems.tsx
@@ -12,6 +12,8 @@ import { isVirtualUri } from "@/platform/virtualDocs";
import { editorController, useEditorStatus, useGotoLine } from "../controller";
import { useDocMeta, useOutline } from "../model/document";
import { symbolChain } from "./outline";
+import { NavChildrenPopup } from "./NavBarPopup";
+import type { NavSegment } from "./navBar";
import styles from "./EditorArea.module.css";
function useActiveMeta() {
@@ -24,10 +26,15 @@ interface Crumb {
label: string;
icon?: string;
title: string;
- run: () => void;
+ /** Clicking lists the segment's children (IDEA navigation bar). */
+ nav?: NavSegment;
+ run?: () => void;
}
-/** IDEA new UI navigation bar in the status bar: project › dirs › file › symbols, with icons. */
+/**
+ * IDEA new UI navigation bar in the status bar: project › dirs › file ›
+ * symbols, with icons; clicking a segment opens a popup of its children.
+ */
export function Breadcrumbs() {
const status = useEditorStatus((s) => s.status);
const project = useProject((s) => s.project);
@@ -35,6 +42,7 @@ export function Breadcrumbs() {
const line = status?.line ?? 0;
const col = status?.col ?? 0;
const chain = useMemo(() => (outline ? symbolChain(outline, line, col) : []), [outline, line, col]);
+ const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
if (!status) return null;
const path = status.path;
const parent = dirname(path);
@@ -44,7 +52,7 @@ export function Breadcrumbs() {
label: project.name,
icon: "module",
title: project.root,
- run: () => void executeAction("navigate.selectIn", { path: project.root }),
+ nav: { kind: "dir", path: project.root, label: project.name, root: true },
});
if (project && parent !== project.root && parent.startsWith(project.root + "/")) {
// Every directory from the root to the file, eliding the middle of deep paths.
@@ -67,7 +75,7 @@ export function Breadcrumbs() {
label,
icon: "folder",
title: relativePath(project.root, dir),
- run: () => void executeAction("navigate.selectIn", { path: dir }),
+ nav: { kind: "dir", path: dir, label },
});
}
}
@@ -77,29 +85,37 @@ export function Breadcrumbs() {
label: file,
icon: fileIconName(file),
title: project ? relativePath(project.root, path) : path,
- run: () => void executeAction("navigate.selectIn", { path }),
+ nav: { kind: "file", path, label: file },
});
for (const item of chain.filter((it, i) => i > 0 || it.name !== stem))
segments.push({
label: item.name,
icon: `symbol-${badgeKind(item.kind)}`,
title: item.detail ?? item.name,
- run: () =>
- void editorController().openFile(path, {
- selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
- }),
+ nav: { kind: "symbol", path, label: item.name, item },
});
return (
<nav className={styles.status} aria-label="Breadcrumbs">
{segments.map((s, i) => (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
- <BarButton className={styles.crumbButton} tooltip={s.title} onClick={s.run}>
+ <BarButton
+ className={styles.crumbButton}
+ tooltip={s.title}
+ aria-haspopup={s.nav ? "listbox" : undefined}
+ onClick={(e) => {
+ const nav = s.nav;
+ const anchor = e.currentTarget;
+ if (nav) setPopup((p) => (p?.anchor === anchor ? null : { nav, anchor }));
+ else s.run?.();
+ }}
+ >
{s.icon && <Icon name={s.icon} size={14} className={styles.crumbIcon} />}
<span className={styles.crumbLabel}>{s.label}</span>
</BarButton>
</Fragment>
))}
+ {popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
</nav>
);
}
diff --git a/src/editor/core/view/navChildren.test.tsx b/src/editor/core/view/navChildren.test.tsx
new file mode 100644
index 000000000..14ff595d4
--- /dev/null
+++ b/src/editor/core/view/navChildren.test.tsx
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import type { OutlineItem } from "@/platform/ipc";
+
+const openFile = vi.fn(async () => {});
+vi.mock("../controller", () => ({
+ editorController: () => ({ openFile }),
+ useEditorStatus: () => null,
+}));
+
+const { useOutline } = await import("../model/document");
+const { NavChildrenPopup } = await import("./NavBarPopup");
+
+const range = (line: number) => ({ start: { line, col: 2 }, end: { line, col: 5 } });
+const item = (name: string, line: number, children: OutlineItem[] = []): OutlineItem =>
+ ({ name, detail: null, kind: "function", range: range(line), selection_range: range(line), children }) as OutlineItem;
+
+describe("status bar navigation bar popup", () => {
+ it("lists a file's symbols and navigates to the chosen one", async () => {
+ useOutline.setState({ "/p/a.ts": [item("first", 1), item("second", 7)] });
+ const anchor = document.createElement("button");
+ document.body.appendChild(anchor);
+ const onClose = vi.fn();
+ render(<NavChildrenPopup segment={{ kind: "file", path: "/p/a.ts", label: "a.ts" }} anchor={anchor} onClose={onClose} />);
+ await act(async () => {});
+ const list = screen.getByRole("listbox", { name: "a.ts" });
+ expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["first", "second"]);
+ fireEvent.keyDown(list, { key: "ArrowDown" });
+ fireEvent.keyDown(list, { key: "Enter" });
+ expect(onClose).toHaveBeenCalled();
+ expect(openFile).toHaveBeenCalledWith("/p/a.ts", { selection: { line: 7, col: 2 }, focus: true });
+ });
+});
diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css
index 2d7184802..433e9b403 100644
--- a/src/editor/lsp/Popups.module.css
+++ b/src/editor/lsp/Popups.module.css
@@ -276,3 +276,10 @@
color: var(--fg-search-match, inherit);
border-radius: 2px;
}
+
+.statusMessage {
+ color: var(--fg-secondary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx
index a854bfecc..4381de674 100644
--- a/src/editor/lsp/Popups.tsx
+++ b/src/editor/lsp/Popups.tsx
@@ -19,6 +19,7 @@ import { editorService } from "@/workbench/contributions";
import { closePopup, useLspPopup, type ListPopupItem, type LspPopup } from "./popupStore";
import { renderCode, renderMarkup } from "./markdown";
import { describeSummary } from "./workspaceEdit";
+import { useUsagesStatus } from "./navigation";
import styles from "./Popups.module.css";
export function BulbIcon({ fix }: { fix?: boolean }) {
@@ -209,9 +210,15 @@ function DomContent({ build, className }: { build: () => HTMLElement; className?
}
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
+ const focusSeq = useLspPopup((s) => s.focusSeq);
+ const scope = useRef<HTMLDivElement>(null);
+ const opened = useRef(focusSeq);
+ useEffect(() => {
+ if (focusSeq !== opened.current) scope.current?.focus({ preventScroll: true });
+ }, [focusSeq]);
return (
<Popup open anchor={popup.anchor} onClose={closePopup} aria-label="Documentation" className={styles.docPopup}>
- <div className={clsx(popup.themeClasses, styles.docScope)}>
+ <div ref={scope} tabIndex={-1} className={clsx(popup.themeClasses, styles.docScope)}>
<DomContent className={styles.docBody} build={() => renderMarkup(popup.markup, popup.language)} />
</div>
</Popup>
@@ -319,6 +326,17 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
);
}
+/** Status bar text while ⌘⇧F7 usages are highlighted ("3 usages of 'x' found…"). */
+export function UsagesStatus() {
+ const text = useUsagesStatus((s) => s.text);
+ if (!text) return null;
+ return (
+ <span className={styles.statusMessage} role="status" title={text}>
+ {text}
+ </span>
+ );
+}
+
/** Overlay host: renders the current LSP popup, if any. */
export function LspPopups() {
const popup = useLspPopup((s) => s.popup);
diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts
index 9bc45fac2..dff9b73c2 100644
--- a/src/editor/lsp/actions.ts
+++ b/src/editor/lsp/actions.ts
@@ -4,7 +4,7 @@ import { registerActions, type Action } from "@/platform/actions";
import { activeEditor, editorsFor, registerSaveParticipant, type TextEditorHandle } from "@/editor/api";
import { maybeEditorService } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
-import { startCompletion } from "./completion";
+import { explicitCompletion } from "./completion";
import { triggerSignatureHelp } from "./signature";
import { quickDefinition, quickDocumentation } from "./hover";
import { expressionTypeInfo } from "./typeInfo";
@@ -99,7 +99,7 @@ export function registerActionsOnSave(): () => void {
export function registerLspActions(): () => void {
return registerActions([
- editorAction("code.completion", "Basic", "Code Completion", (v) => startCompletion(v), {
+ editorAction("code.completion", "Basic", "Code Completion", (v) => explicitCompletion(v), {
icon: "list",
keywords: ["code completion", "basic completion", "autocomplete"],
}),
diff --git a/src/editor/lsp/completion.test.ts b/src/editor/lsp/completion.test.ts
index f2bcddbbd..0a92203ea 100644
--- a/src/editor/lsp/completion.test.ts
+++ b/src/editor/lsp/completion.test.ts
@@ -1,9 +1,10 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { CompletionItem } from "@/bindings";
import { completionSymbolKind, identifierEnd, toCmCompletion, triggerCharacter } from "./completionItems";
-import { applyLspCompletion, makeCompletion } from "./completion";
+import { applyLspCompletion, commitsLookup, completionExtension, explicitCompletion, makeCompletion } from "./completion";
+import type { CompletionSource } from "@codemirror/autocomplete";
function item(over: Partial<CompletionItem> = {}): CompletionItem {
return {
@@ -161,3 +162,55 @@ describe("applying completions", () => {
expect(view.state.sliceDoc(sel.from, sel.to)).toBe("arg");
});
});
+
+describe("lookup commit characters", () => {
+ it("finishes only focused lookups unless the setting asks for it (IDEA)", () => {
+ expect(commitsLookup(".", true, false)).toBe(true);
+ expect(commitsLookup(".", false, false)).toBe(false);
+ expect(commitsLookup(".", false, true)).toBe(true);
+ expect(commitsLookup("-", true, false)).toBe(false);
+ expect(commitsLookup("[", true, false, ["["])).toBe(true);
+ });
+
+ it("leaves server commit characters to the lookup", () => {
+ const req = { doc: 1, path: "/a.ts", language: "typescript", pos: 0, text: EditorState.create().doc };
+ expect(makeCompletion(item({ commitCharacters: ["."] }), req).commitCharacters).toBeUndefined();
+ });
+});
+
+describe("explicit completion", () => {
+ // jsdom has no layout; CodeMirror measures text when the tooltip is positioned.
+ Range.prototype.getClientRects ??= () => [] as unknown as DOMRectList;
+ Range.prototype.getBoundingClientRect ??= () => new DOMRect();
+
+ function editor(labels: string[]) {
+ const source: CompletionSource = (ctx) => {
+ const word = ctx.matchBefore(/\w*/);
+ return { from: word?.from ?? ctx.pos, options: labels.map((label) => ({ label })) };
+ };
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: "pri",
+ selection: { anchor: 3 },
+ extensions: [completionExtension(), EditorState.languageData.of(() => [{ openideaCompletion: source }])],
+ }),
+ parent: document.body,
+ });
+ return view;
+ }
+
+ it("inserts a sole candidate right away (IDEA)", async () => {
+ const view = editor(["println"]);
+ explicitCompletion(view);
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("println"), { timeout: 2000 });
+ view.destroy();
+ });
+
+ it("shows the list when there are several candidates", async () => {
+ const view = editor(["println", "print"]);
+ explicitCompletion(view);
+ await new Promise((r) => setTimeout(r, 300));
+ expect(view.state.doc.toString()).toBe("pri");
+ view.destroy();
+ });
+});
diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts
index 201596233..964e4dcab 100644
--- a/src/editor/lsp/completion.ts
+++ b/src/editor/lsp/completion.ts
@@ -11,7 +11,9 @@ import {
autocompletion,
completeFromList,
completionStatus,
+ currentCompletions,
pickedCompletion,
+ selectedCompletion,
snippet,
startCompletion,
type Completion,
@@ -22,7 +24,7 @@ import {
} from "@codemirror/autocomplete";
import { EditorSelection, Prec, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
-import { commands, isTauri, nextRequestId, type CompletionItem, type RequestId } from "@/platform/ipc";
+import { commands, isTauri, nextRequestId, type CompletionItem, type Markup, type RequestId } from "@/platform/ipc";
import { completionSymbolKind, identifierEnd, toCmCompletion, triggerCharacter } from "./completionItems";
import { lspSnippetToCm, snippetVariables } from "./snippet";
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
@@ -31,7 +33,10 @@ import { isEmptyMarkup, renderCode, renderMarkup } from "./markdown";
import { iconNode } from "./iconMarkup";
import { triggerSignatureHelp } from "./signature";
import { serverBackoff } from "./availability";
+import { pathCompletionSource } from "./fileReferences";
import { editorPrefs } from "@/platform/editorSettings";
+import { showHint } from "./hint";
+import { inplaceRenameActive } from "./inplaceRename";
interface RequestContext {
doc: number;
@@ -65,10 +70,28 @@ function resolveItem(doc: number, item: CompletionItem): Promise<CompletionItem>
return p;
}
+/**
+ * F1 in the lookup (IDEA's documentation popup next to the lookup): docs then
+ * follow the selection until the lookup closes. Without the auto-popup setting
+ * the info panel waits for this.
+ */
+let docsRequested = false;
+const docWaiters = new Set<() => void>();
+
function renderInfo(c: LspCompletion): Promise<CompletionInfo> {
const prefs = editorPrefs().completion;
- if (!prefs.showDocumentation) return Promise.resolve(null);
- const delay = Math.max(0, prefs.documentationDelay);
+ if (!prefs.showDocumentation && !docsRequested)
+ return new Promise((resolve) => {
+ const show = () => {
+ docWaiters.delete(show);
+ resolve(buildInfo(c, 0));
+ };
+ docWaiters.add(show);
+ });
+ return buildInfo(c, docsRequested ? 0 : Math.max(0, prefs.documentationDelay));
+}
+
+function buildInfo(c: LspCompletion, delay: number): Promise<CompletionInfo> {
const wait = delay ? new Promise<void>((r) => setTimeout(r, delay)) : Promise.resolve();
return Promise.all([resolveItem(c.req.doc, c.lsp), wait]).then(([item]) => {
c.resolved = item;
@@ -82,6 +105,35 @@ function renderInfo(c: LspCompletion): Promise<CompletionInfo> {
});
}
+function resetLookupDocs() {
+ docsRequested = false;
+ docWaiters.clear();
+}
+
+/**
+ * F1 while the lookup is open: shows the selected item's docs beside it
+ * (`shown`), or reports that they are already showing (`showing`) so the
+ * caller can open them focused instead. `none` without an open lookup.
+ */
+export function showLookupDocs(view: EditorView): "shown" | "showing" | "none" {
+ if (completionStatus(view.state) !== "active" || !selectedCompletion(view.state)) return "none";
+ if (docsRequested || editorPrefs().completion.showDocumentation) return "showing";
+ docsRequested = true;
+ for (const show of [...docWaiters]) show();
+ return "shown";
+}
+
+/** Documentation of the selected lookup item as markup (detail as a code block), or null. */
+export async function selectedLookupDoc(view: EditorView): Promise<{ markup: Markup; language: string | null } | null> {
+ const c = selectedCompletion(view.state);
+ if (!c || !isLsp(c)) return null;
+ const item = await resolveItem(c.req.doc, c.lsp);
+ const parts: string[] = [];
+ if (item.detail) parts.push("```" + (c.req.language ?? "") + "\n" + item.detail + "\n```");
+ if (!isEmptyMarkup(item.documentation)) parts.push(item.documentation!.value);
+ return parts.length ? { markup: { kind: "markdown", value: parts.join("\n\n") }, language: c.req.language } : null;
+}
+
// ---------------------------------------------------------------------------
// Apply
@@ -204,7 +256,9 @@ async function fallback(ctx: CompletionContext): Promise<CompletionResult | null
}
export function makeCompletion(item: CompletionItem, req: RequestContext): LspCompletion {
- return Object.assign(toCmCompletion(item), {
+ // The lookup handles commit characters itself (focused lookups only, see `lookupKeys`).
+ const { commitCharacters: _server, ...cm } = toCmCompletion(item);
+ return Object.assign(cm, {
lsp: item,
req,
apply: applyLsp,
@@ -281,7 +335,6 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
// "All letters" must re-check case on every keystroke.
validFor: list.isIncomplete || (prefs.matchCase && prefs.caseSensitivity === "all") ? undefined : VALID_FOR,
filter: true,
- ...(prefs.insertOnSpecialKeys ? { commitCharacters: [" ", ".", "(", ",", ";"] } : {}),
};
}
@@ -300,7 +353,102 @@ export function matchesCase(label: string, typed: string, mode: string): boolean
/** Show suggestions as you type: sources only answer explicit requests when it is off. */
function gated(source: CompletionSource): CompletionSource {
- return (ctx) => (!ctx.explicit && !editorPrefs().completion.autoPopup ? null : source(ctx));
+ return (ctx) =>
+ !ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state)) ? null : source(ctx);
+}
+
+// ---------------------------------------------------------------------------
+// Lookup focus, commit characters, explicit invocation
+
+/**
+ * As in IDEA, these finish a *focused* lookup with the selected
+ * item before being typed; an unfocused auto-popup just
+ * closes on them unless Settings › Code Completion › "Insert selected
+ * suggestion by pressing space, dot…" is on.
+ */
+export const COMMIT_CHARS = [".", ",", ";", "=", " ", ":", "("];
+
+/** Lookups the user engaged with: opened explicitly (⌃Space) or navigated with ↑/↓. */
+const focusedLookups = new WeakSet<EditorView>();
+/** Explicit invocations waiting for their first result (single candidate → insert it). */
+const explicitPending = new WeakSet<EditorView>();
+
+const NAVIGATION_KEYS = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown"]);
+
+/** Whether typing `ch` finishes the open lookup with its selected item. */
+export function commitsLookup(ch: string, focused: boolean, insertOnSpecialKeys: boolean, itemChars: readonly string[] = []): boolean {
+ if (!focused && !insertOnSpecialKeys) return false;
+ return COMMIT_CHARS.includes(ch) || itemChars.includes(ch);
+}
+
+const lookupKeys = Prec.highest(
+ EditorView.domEventHandlers({
+ keydown(e, view) {
+ if (e.isComposing || completionStatus(view.state) !== "active") return false;
+ if (NAVIGATION_KEYS.has(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) {
+ focusedLookups.add(view);
+ return false;
+ }
+ if (e.key.length !== 1 || e.metaKey || e.ctrlKey || e.altKey) return false;
+ const selected = selectedCompletion(view.state);
+ if (!selected) return false;
+ const itemChars = isLsp(selected) ? selected.lsp.commitCharacters : (selected.commitCharacters ?? []);
+ if (!commitsLookup(e.key, focusedLookups.has(view), editorPrefs().completion.insertOnSpecialKeys, itemChars)) return false;
+ if (!acceptCompletion(view)) return false;
+ // A call snippet already opened the parenthesis: the typed one is consumed.
+ const head = view.state.selection.main.head;
+ if (e.key === "(" && view.state.sliceDoc(head - 1, head) === "(") {
+ e.preventDefault();
+ return true;
+ }
+ return false;
+ },
+ }),
+);
+
+/** IDEA inserts a sole candidate right away on explicit invocation. */
+const AUTO_INSERT_DELAY = 80; // past CodeMirror's interactionDelay
+
+const lookupTracker = ViewPlugin.fromClass(
+ class {
+ private prev: ReturnType<typeof completionStatus> = null;
+ constructor(private view: EditorView) {}
+ update(u: ViewUpdate) {
+ const status = completionStatus(u.state);
+ const prev = this.prev;
+ this.prev = status;
+ if (status === prev && status !== "active") return;
+ const view = this.view;
+ if (status === null) {
+ focusedLookups.delete(view);
+ resetLookupDocs();
+ if (explicitPending.has(view)) {
+ explicitPending.delete(view);
+ if (prev === "pending" && !u.docChanged) queueMicrotask(() => showHint(view, "No suggestions", { timeout: 2000 }));
+ }
+ } else if (status === "active" && explicitPending.has(view)) {
+ explicitPending.delete(view);
+ const options = currentCompletions(u.state);
+ if (options.length === 1) {
+ const doc = u.state.doc;
+ setTimeout(() => {
+ const now = currentCompletions(view.state);
+ if (view.state.doc === doc && completionStatus(view.state) === "active" && now.length === 1 && now[0] === options[0])
+ acceptCompletion(view);
+ }, AUTO_INSERT_DELAY);
+ }
+ }
+ }
+ },
+);
+
+/** ⌃Space: explicit completion (a focused lookup; a sole candidate is inserted at once). */
+export function explicitCompletion(view: EditorView): boolean {
+ explicitPending.add(view);
+ const started = startCompletion(view);
+ if (!started) explicitPending.delete(view);
+ else focusedLookups.add(view);
+ return started;
}
// ---------------------------------------------------------------------------
@@ -358,8 +506,9 @@ const completionFooter = ViewPlugin.fromClass(
export function completionExtension() {
return [
+ lookupKeys,
autocompletion({
- override: [gated(lspCompletionSource), gated(contributedSource)],
+ override: [gated(lspCompletionSource), gated(contributedSource), gated(pathCompletionSource)],
icons: false,
addToOptions: [
{ render: kindBadge, position: 20 },
@@ -373,6 +522,7 @@ export function completionExtension() {
tooltipClass: () => "cm-lsp-completion",
}),
completionFooter,
+ lookupTracker,
Prec.highest(
keymap.of([
{
diff --git a/src/editor/lsp/diagnostics.ts b/src/editor/lsp/diagnostics.ts
index 7d627b5d0..f6351baf1 100644
--- a/src/editor/lsp/diagnostics.ts
+++ b/src/editor/lsp/diagnostics.ts
@@ -214,7 +214,7 @@ export function gotoDiagnostic(view: EditorView, dir: 1 | -1): boolean {
dir === 1
? (list.find((p) => p.from > head) ?? list[0]!)
: ([...list].reverse().find((p) => p.from < head && !(p.from <= head && head <= p.to)) ?? list[list.length - 1]!);
- view.dispatch({ selection: EditorSelection.cursor(target.from), scrollIntoView: true, userEvent: "select" });
+ view.dispatch({ selection: EditorSelection.cursor(target.from), scrollIntoView: true, userEvent: "select.navigate" });
showHint(view, target.diagnostic.message, {
pos: target.from,
tone: target.diagnostic.severity === "error" ? "error" : target.diagnostic.severity === "warning" ? "warning" : "info",
diff --git a/src/editor/lsp/features.test.ts b/src/editor/lsp/features.test.ts
index f870d7f25..acd5c67a0 100644
--- a/src/editor/lsp/features.test.ts
+++ b/src/editor/lsp/features.test.ts
@@ -2,9 +2,11 @@ import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import type { CodeAction } from "@/bindings";
import { semanticRanges } from "./semantic";
-import { sortCodeActions } from "./intentions";
+import { lineErrorsAwayFromCaret, sortCodeActions } from "./intentions";
import { splitSignature } from "./signature";
-import { dedupeLocations } from "./navigation";
+import { dedupeLocations, usagesStatusText } from "./navigation";
+import { declarationSummary } from "./markdown";
+import { linkedSpans } from "./rename";
describe("semanticRanges", () => {
const doc = Text.of(["let mut count = Foo::new();", "const MAX: u32 = 1;"]);
@@ -67,3 +69,54 @@ describe("dedupeLocations", () => {
expect(dedupeLocations([loc("/a", 1), loc("/a", 1), loc("/b", 1)])).toHaveLength(2);
});
});
+
+describe("lineErrorsAwayFromCaret", () => {
+ const p = (from: number, to: number, severity = "error") => ({ from, to, severity });
+
+ it("offers errors elsewhere on the caret line when none is at the caret", () => {
+ expect(lineErrorsAwayFromCaret([p(30, 34), p(12, 15), p(50, 52), p(5, 6, "warning")], 0, 40, 2)).toEqual([p(12, 15), p(30, 34)]);
+ });
+
+ it("offers nothing extra when an error touches the caret", () => {
+ expect(lineErrorsAwayFromCaret([p(0, 3), p(12, 15)], 0, 40, 3)).toEqual([]);
+ });
+});
+
+describe("usagesStatusText", () => {
+ it("reads like IDEA's status bar message", () => {
+ expect(usagesStatusText(1, "'x'", "⇧⌘F7")).toBe(
+ "1 usage of 'x' found (press ⇧⌘F7 again to remove the highlighting, Escape to remove all highlighting)",
+ );
+ expect(usagesStatusText(3, "'x'", null)).toBe("3 usages of 'x' found (Escape to remove all highlighting)");
+ });
+});
+
+describe("declarationSummary", () => {
+ it("takes the first code block of hover markdown", () => {
+ expect(declarationSummary({ kind: "markdown", value: "```ts\nconst x: number\n```\n---\nDocs" })).toEqual({
+ code: "const x: number",
+ language: "ts",
+ });
+ });
+
+ it("falls back to the first paragraph", () => {
+ expect(declarationSummary({ kind: "plaintext", value: "fn main()\n\nmore" })).toEqual({ text: "fn main()" });
+ expect(declarationSummary({ kind: "markdown", value: " " })).toBeNull();
+ });
+});
+
+describe("linkedSpans", () => {
+ it("keeps other same-name occurrences, sorted and without the primary or overlaps", () => {
+ const spans = [
+ { from: 20, to: 23 },
+ { from: 4, to: 7 },
+ { from: 10, to: 13 },
+ { from: 11, to: 14 },
+ { from: 30, to: 35 },
+ ];
+ expect(linkedSpans(spans, { from: 4, to: 7 }, (s) => s.to - s.from === 3)).toEqual([
+ { from: 10, to: 13 },
+ { from: 20, to: 23 },
+ ]);
+ });
+});
diff --git a/src/editor/lsp/fileReferences.test.ts b/src/editor/lsp/fileReferences.test.ts
new file mode 100644
index 000000000..163a2ca3e
--- /dev/null
+++ b/src/editor/lsp/fileReferences.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { pathContext, pathLike } from "./fileReferences";
+
+describe("path completion context", () => {
+ it("completes URL attributes, url(), @import and Markdown links eagerly", () => {
+ expect(pathContext('<link rel="stylesheet" href="css/', "html")).toEqual({ prefix: "css/", eager: true });
+ expect(pathContext("<img src=", "html")).toEqual({ prefix: "", eager: true });
+ expect(pathContext(".a { background: url(../img/lo", "css")).toEqual({ prefix: "../img/lo", eager: true });
+ expect(pathContext('@import "the', "scss")).toEqual({ prefix: "the", eager: true });
+ expect(pathContext("See [docs](guide/", "markdown")).toEqual({ prefix: "guide/", eager: true });
+ });
+
+ it("completes string literals only once they look like paths", () => {
+ expect(pathContext('open("data/x', "python")).toEqual({ prefix: "data/x", eager: false });
+ expect(pathLike("data/x") && pathLike("./") && pathLike("../a")).toBe(true);
+ expect(pathLike("hello")).toBe(false);
+ // Closed strings and module specifiers (the language server's job) are left alone.
+ expect(pathContext('log("done") + x', "python")).toBeNull();
+ expect(pathContext('import { a } from "./ut', "typescript")).toBeNull();
+ expect(pathContext('const m = await import("./m', "javascript")).toBeNull();
+ expect(pathContext('fetch("./data/', "typescript")).toEqual({ prefix: "./data/", eager: false });
+ });
+});
diff --git a/src/editor/lsp/fileReferences.ts b/src/editor/lsp/fileReferences.ts
new file mode 100644
index 000000000..a93123526
--- /dev/null
+++ b/src/editor/lsp/fileReferences.ts
@@ -0,0 +1,150 @@
+/**
+ * File references while editing, in every language: path completion inside
+ * `href="…"`, `src="…"`, `url(…)`, `@import "…"`, Markdown links and path-like
+ * string literals (folders first; picking one continues into it), and the
+ * "Cannot resolve file" warning on HTML / CSS paths that name no file.
+ * Paths resolve in the backend like IDEA's file references: relative to the
+ * file, `/…` against the project root and its resource roots.
+ */
+import { startCompletion, type Completion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete";
+import type { Extension } from "@codemirror/state";
+import { EditorView, ViewPlugin } from "@codemirror/view";
+import { whenSynced } from "@/editor/api";
+import { call, commands, isTauri, onIdeEvent, type PathCompletion } from "@/platform/ipc";
+import { fileIconName, folderIconName } from "@/ui";
+import { setFileDiagnostics } from "./diagnostics";
+import { docOf, lspDoc } from "./lsp";
+
+// --- completion ---------------------------------------------------------------
+
+export interface PathContext {
+ /** The path typed so far. */
+ prefix: string;
+ /** Whether to complete without an explicit request even when `prefix` does not look like a path yet. */
+ eager: boolean;
+}
+
+const URL_ATTRIBUTE = /\b(?:href|src|srcset|action|formaction|poster|data|xlink:href)\s*=\s*["']?([^"'\s>]*)$/i;
+const CSS_URL = /\burl\(\s*["']?([^"')\s]*)$/;
+const CSS_IMPORT = /@(?:import|use|forward)\s+["']([^"']*)$/;
+const MARKDOWN_LINK = /\]\(([^)\s]*)$/;
+const STRING = /(["'`])([^"'`\\]*)$/;
+/** Module specifiers: the language server completes those. */
+const MODULE_SPECIFIER = /(?:\bimport\b|\bfrom\b|\brequire\s*\(|\bimport\s*\()\s*["'`][^"'`]*$/;
+const JS_LIKE = new Set(["javascript", "typescript", "javascriptreact", "typescriptreact", "vue", "svelte"]);
+
+/** Whether `prefix` already reads like a path (`./`, `../`, `a/b`). */
+export const pathLike = (prefix: string) => /^\.{1,2}\/|\//.test(prefix);
+
+/** The path being typed at the end of `before` (the line up to the caret), if any. */
+export function pathContext(before: string, language: string): PathContext | null {
+ for (const re of [URL_ATTRIBUTE, CSS_URL, CSS_IMPORT, MARKDOWN_LINK]) {
+ const m = re.exec(before);
+ if (m) return { prefix: m[1]!, eager: true };
+ }
+ const m = STRING.exec(before);
+ if (!m) return null;
+ // Inside a string only when the quote opens one (an odd count on the line).
+ if ((before.split(m[1]!).length - 1) % 2 === 0) return null;
+ if (JS_LIKE.has(language) && MODULE_SPECIFIER.test(before)) return null;
+ return { prefix: m[2]!, eager: false };
+}
+
+const listings = new Map<string, { at: number; items: Promise<PathCompletion[]> }>();
+const LISTING_TTL = 3000;
+
+function listing(from: string, dirPrefix: string): Promise<PathCompletion[]> {
+ const key = `${from}\n${dirPrefix}`;
+ const hit = listings.get(key);
+ if (hit && Date.now() - hit.at < LISTING_TTL) return hit.items;
+ const items = call(commands.pathCompletions(from, dirPrefix)).catch(() => []);
+ listings.set(key, { at: Date.now(), items });
+ if (listings.size > 32) listings.delete(listings.keys().next().value!);
+ return items;
+}
+
+function option(entry: PathCompletion): Completion & { icon: string } {
+ if (!entry.dir) return { label: entry.name, type: "file", icon: fileIconName(entry.name), boost: -1 };
+ return {
+ label: `${entry.name}/`,
+ type: "folder",
+ icon: folderIconName(),
+ apply: (view, _c, from, to) => {
+ view.dispatch({ changes: { from, to, insert: `${entry.name}/` }, selection: { anchor: from + entry.name.length + 1 } });
+ startCompletion(view);
+ },
+ };
+}
+
+export async function pathCompletionSource(ctx: CompletionContext): Promise<CompletionResult | null> {
+ const doc = ctx.state.facet(lspDoc);
+ if (!doc || doc.virtual || doc.readOnly || !isTauri()) return null;
+ const line = ctx.state.doc.lineAt(ctx.pos);
+ const found = pathContext(line.text.slice(0, ctx.pos - line.from), doc.language);
+ if (!found || /[?#]/.test(found.prefix)) return null;
+ if (!ctx.explicit && !found.eager && !pathLike(found.prefix)) return null;
+ const slash = found.prefix.lastIndexOf("/");
+ const entries = await listing(doc.path, found.prefix.slice(0, slash + 1));
+ if (ctx.aborted || !entries.length) return null;
+ return {
+ from: ctx.pos - (found.prefix.length - slash - 1),
+ options: entries.map(option),
+ validFor: /^[^/"'`)\s?#]*$/,
+ };
+}
+
+// --- unresolved references --------------------------------------------------
+
+const WEB_LANGUAGES = new Set(["html", "css", "scss", "less", "vue", "svelte"]);
+const SOURCE = "file-references";
+const INSPECT_DELAY = 600;
+
+/** Warns about HTML / CSS paths that name no file; re-checked on edits and file-system changes. */
+export function unresolvedReferences(): Extension {
+ return ViewPlugin.define((view: EditorView) => {
+ const doc = docOf(view);
+ if (!doc || doc.virtual || !WEB_LANGUAGES.has(doc.language) || !isTauri()) return {};
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let seq = 0;
+ const run = async () => {
+ const mine = ++seq;
+ try {
+ await whenSynced(view);
+ const refs = await call(commands.webUnresolvedReferences(doc.doc));
+ if (mine !== seq) return;
+ setFileDiagnostics(
+ doc.path,
+ SOURCE,
+ refs.map((r) => ({
+ range: r.range,
+ severity: "warning",
+ message: `Cannot resolve file '${r.value}'`,
+ source: doc.language === "html" || doc.language === "vue" || doc.language === "svelte" ? "HTML" : "CSS",
+ code: null,
+ })),
+ );
+ } catch (e) {
+ console.debug("[file references]", e);
+ }
+ };
+ const schedule = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => void run(), INSPECT_DELAY);
+ };
+ schedule();
+ const offFs = onIdeEvent("fsChanged", (e) => {
+ if (e.created.length || e.removed.length) schedule();
+ });
+ return {
+ update: (u) => {
+ if (u.docChanged) schedule();
+ },
+ destroy: () => {
+ clearTimeout(timer);
+ offFs();
+ seq++;
+ setFileDiagnostics(doc.path, SOURCE, []);
+ },
+ };
+ });
+}
diff --git a/src/editor/lsp/hover.ts b/src/editor/lsp/hover.ts
index 822651891..30f25db8f 100644
--- a/src/editor/lsp/hover.ts
+++ b/src/editor/lsp/hover.ts
@@ -13,7 +13,8 @@ import { isEmptyMarkup, languageForPath, renderMarkup } from "./markdown";
import { docOf, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, rangeToOffsets } from "./positions";
import { showHint } from "./hint";
-import { caretAnchor, openPopup } from "./popupStore";
+import { caretAnchor, focusPopup, openPopup, useLspPopup } from "./popupStore";
+import { selectedLookupDoc, showLookupDocs } from "./completion";
import { readFileLines } from "./files";
import { iconNode } from "./iconMarkup";
import { editorPrefs } from "@/platform/editorSettings";
@@ -117,9 +118,31 @@ export function hoverExtension() {
);
}
-/** F1: documentation for the symbol at the caret in a sticky popup. */
+/**
+ * F1: documentation for the symbol at the caret in a sticky popup; in an open
+ * lookup, for its selected item. Again on an open popup: focuses it.
+ */
export async function quickDocumentation(view: EditorView) {
+ if (useLspPopup.getState().popup?.kind === "doc") {
+ focusPopup();
+ return;
+ }
const pos = view.state.selection.main.head;
+ const lookup = showLookupDocs(view);
+ if (lookup === "shown") return;
+ if (lookup === "showing") {
+ const doc = await selectedLookupDoc(view).catch(() => null);
+ if (!doc) showHint(view, "No documentation found");
+ else
+ openPopup({
+ kind: "doc",
+ anchor: caretAnchor(view, pos),
+ markup: doc.markup,
+ language: doc.language,
+ themeClasses: view.themeClasses,
+ });
+ return;
+ }
try {
const hover = await requestHover(view, pos);
if (!hover) {
diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts
index 4f2760a2e..76b567ed1 100644
--- a/src/editor/lsp/index.ts
+++ b/src/editor/lsp/index.ts
@@ -7,10 +7,11 @@
*/
import type { Extension } from "@codemirror/state";
import { registerEditorContribution, type EditorDocContext } from "@/editor/api";
-import { registerOverlay } from "@/workbench/contributions";
+import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
import { lspDoc } from "./lsp";
import { hintExtension } from "./hint";
import { completionExtension } from "./completion";
+import { inplaceRenameExtension } from "./inplaceRename";
import { diagnosticsExtension, installDiagnosticsEvents } from "./diagnostics";
import { hoverExtension } from "./hover";
import { signatureExtension } from "./signature";
@@ -24,7 +25,8 @@ import { installAvailabilityEvents } from "./availability";
import { registerActionsOnSave, registerFormatOnSave, registerLspActions } from "./actions";
import { lspTheme } from "./theme";
import { inspectionWidgetExtension } from "./inspectionWidget";
-import { LspPopups } from "./Popups";
+import { unresolvedReferences } from "./fileReferences";
+import { LspPopups, UsagesStatus } from "./Popups";
import { prefetchMarkdown } from "./markdown";
import { registerNavigationActions } from "@/editor/navigation";
@@ -38,12 +40,14 @@ export function lspExtensions(ctx: EditorDocContext): Extension[] {
hoverExtension(),
signatureExtension(),
completionExtension(),
+ inplaceRenameExtension(),
navigationExtension(),
intentionsExtension(),
inlayExtension(),
semanticExtension(),
usagesLensExtension(),
autoImportExtension(),
+ unresolvedReferences(),
];
}
@@ -53,6 +57,7 @@ export function activate(): () => void {
installAvailabilityEvents(),
registerEditorContribution({ id: "lsp", order: 50, extensions: lspExtensions }),
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
+ registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
registerLspActions(),
registerNavigationActions(),
registerFormatOnSave(),
diff --git a/src/editor/lsp/inplaceRename.test.ts b/src/editor/lsp/inplaceRename.test.ts
new file mode 100644
index 000000000..338f41bd0
--- /dev/null
+++ b/src/editor/lsp/inplaceRename.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
+import { history, undoDepth } from "@codemirror/commands";
+import { EditorView } from "@codemirror/view";
+import { endInplaceRename, inplaceRenameActive, inplaceRenameExtension, startInplaceRename } from "./inplaceRename";
+
+const views: EditorView[] = [];
+afterEach(() => views.splice(0).forEach((v) => v.destroy()));
+
+// "let foo = 1; foo + foo;" — foo at 4, 13 and 19.
+function session(commit = vi.fn(), dialog = vi.fn(), extensions: Extension[] = []) {
+ const view = new EditorView({
+ state: EditorState.create({ doc: "let foo = 1; foo + foo;", extensions: [inplaceRenameExtension(), ...extensions] }),
+ });
+ views.push(view);
+ startInplaceRename(view, {
+ primary: { from: 4, to: 7 },
+ others: [
+ { from: 13, to: 16 },
+ { from: 19, to: 22 },
+ ],
+ hint: "Press ⇧F6 to show dialog with more options",
+ commit,
+ dialog,
+ });
+ return { view, commit, dialog };
+}
+
+const type = (view: EditorView, from: number, to: number, insert: string) =>
+ view.dispatch({ changes: { from, to, insert }, selection: EditorSelection.cursor(from + insert.length), userEvent: "input.type" });
+
+describe("in-place rename", () => {
+ it("preselects the name and mirrors edits to the other occurrences", () => {
+ const { view } = session();
+ expect(view.state.selection.main).toMatchObject({ from: 4, to: 7 });
+ type(view, 4, 7, "bar");
+ expect(view.state.doc.toString()).toBe("let bar = 1; bar + bar;");
+ type(view, 7, 7, "Baz");
+ expect(view.state.doc.toString()).toBe("let barBaz = 1; barBaz + barBaz;");
+ expect(inplaceRenameActive(view.state)).toBe(true);
+ });
+
+ it("restores the old name on cancel without committing", () => {
+ const { view, commit } = session();
+ type(view, 4, 7, "x");
+ expect(endInplaceRename(view, "cancel")).toBe("x");
+ expect(view.state.doc.toString()).toBe("let foo = 1; foo + foo;");
+ expect(inplaceRenameActive(view.state)).toBe(false);
+ expect(commit).not.toHaveBeenCalled();
+ });
+
+ it("puts the old text back before committing the typed name", () => {
+ const commit = vi.fn();
+ const { view } = session(commit);
+ type(view, 4, 7, "count");
+ commit.mockImplementation(() => expect(view.state.doc.toString()).toBe("let foo = 1; foo + foo;"));
+ endInplaceRename(view, "commit");
+ expect(commit).toHaveBeenCalledWith("count");
+ });
+
+ it("keeps the session's edits out of the undo history", () => {
+ const { view } = session(vi.fn(), vi.fn(), [history()]);
+ type(view, 4, 7, "bar");
+ expect(undoDepth(view.state)).toBe(0);
+ endInplaceRename(view, "cancel");
+ expect(undoDepth(view.state)).toBe(0);
+ });
+
+ it("commits when the caret leaves the name", async () => {
+ const { view, commit } = session();
+ type(view, 4, 7, "bar");
+ view.dispatch({ selection: EditorSelection.cursor(0) });
+ await Promise.resolve();
+ expect(commit).toHaveBeenCalledWith("bar");
+ expect(inplaceRenameActive(view.state)).toBe(false);
+ });
+});
+
+describe("in-place rename edits elsewhere", () => {
+ it("finishes the rename when text outside the name changes", async () => {
+ const { view, commit } = session();
+ type(view, 4, 7, "bar");
+ view.dispatch({ changes: { from: 0, to: 0, insert: "// x\n" }, userEvent: "input.type" });
+ await Promise.resolve();
+ expect(commit).toHaveBeenCalledWith("bar");
+ });
+});
diff --git a/src/editor/lsp/inplaceRename.ts b/src/editor/lsp/inplaceRename.ts
new file mode 100644
index 000000000..7c1fab393
--- /dev/null
+++ b/src/editor/lsp/inplaceRename.ts
@@ -0,0 +1,175 @@
+/**
+ * In-place rename, as in IDEA: the
+ * name is edited right in the editor and its occurrences in this file follow
+ * as you type. ↵ / ⇥ (or leaving the name) commits through the language
+ * server, Esc restores the old name; ⇧F6 again opens the rename dialog
+ * (handled by `rename.ts`).
+ *
+ * The live edits are kept out of the undo history and the old text is put
+ * back before the server renames, so the project-wide rename stays a single
+ * undoable edit computed against the original document.
+ */
+import { Annotation, EditorSelection, EditorState, Prec, StateEffect, StateField, Transaction, type ChangeSet, type Extension } from "@codemirror/state";
+import { Decoration, EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
+import { isExternalChange } from "@/editor/api";
+
+export interface Span {
+ from: number;
+ to: number;
+}
+
+export interface InplaceSession {
+ /** The name being edited. */
+ primary: Span;
+ /** Its other occurrences in this file, kept equal to `primary`. */
+ others: Span[];
+ oldName: string;
+ /** Advertisement under the name ("Press ⇧F6 to show dialog with more options"). */
+ hint: string;
+ /** Runs after the old text is back, with the typed name. */
+ commit: (newName: string) => void;
+ /** ⇧F6 again: the rename dialog, prefilled with the typed name. */
+ dialog: (typed: string) => void;
+}
+
+const startSession = StateEffect.define<InplaceSession>();
+const endSession = StateEffect.define<null>();
+/** Marks the session's own edits (mirroring, restoring). */
+const inplaceEdit = Annotation.define<boolean>();
+
+const mapSpan = (s: Span, changes: ChangeSet): Span => ({ from: changes.mapPos(s.from, -1), to: changes.mapPos(s.to, 1) });
+
+const sessionField = StateField.define<InplaceSession | null>({
+ create: () => null,
+ update(value, tr) {
+ for (const e of tr.effects) {
+ if (e.is(startSession)) return e.value;
+ if (e.is(endSession)) return null;
+ }
+ if (!value || !tr.docChanged) return value;
+ return { ...value, primary: mapSpan(value.primary, tr.changes), others: value.others.map((o) => mapSpan(o, tr.changes)) };
+ },
+ provide: (f) => [
+ EditorView.decorations.from(f, (s) => {
+ if (!s) return Decoration.none;
+ const ranges = [
+ ...s.others.filter((o) => o.from < o.to).map((o) => occurrenceMark.range(o.from, o.to)),
+ ...(s.primary.from < s.primary.to ? [primaryMark.range(s.primary.from, s.primary.to)] : []),
+ ];
+ return Decoration.set(ranges, true);
+ }),
+ showTooltip.from(f, (s): Tooltip | null =>
+ s
+ ? {
+ pos: s.primary.from,
+ above: false,
+ create: () => {
+ const dom = document.createElement("div");
+ dom.className = "cm-lsp-hint cm-lsp-inplace-hint";
+ dom.setAttribute("role", "status");
+ dom.textContent = s.hint;
+ return { dom };
+ },
+ }
+ : null,
+ ),
+ ],
+});
+
+const primaryMark = Decoration.mark({ class: "cm-lsp-inplace cm-lsp-inplace-primary" });
+const occurrenceMark = Decoration.mark({ class: "cm-lsp-inplace" });
+
+/** True when every change of `changes` lies within `span` (boundaries included). */
+export function changesWithin(changes: ChangeSet, span: Span): boolean {
+ let inside = true;
+ changes.iterChangedRanges((fromA, toA) => {
+ if (fromA < span.from || toA > span.to) inside = false;
+ });
+ return inside;
+}
+
+/** Linked editing: an edit inside the name is repeated on every other occurrence. */
+const mirror = EditorState.transactionFilter.of((tr) => {
+ const s = tr.startState.field(sessionField, false);
+ if (!s || !tr.docChanged || tr.annotation(inplaceEdit) || isExternalChange(tr)) return tr;
+ if (!changesWithin(tr.changes, s.primary)) return tr;
+ const primary = mapSpan(s.primary, tr.changes);
+ const name = tr.newDoc.sliceString(primary.from, primary.to);
+ const changes = s.others.map((o) => ({ ...mapSpan(o, tr.changes), insert: name }));
+ return [tr, { changes, sequential: true, annotations: [inplaceEdit.of(true), Transaction.addToHistory.of(false)] }];
+});
+
+export function inplaceSession(state: EditorState): InplaceSession | null {
+ return state.field(sessionField, false) ?? null;
+}
+
+export function inplaceRenameActive(state: EditorState): boolean {
+ return !!inplaceSession(state);
+}
+
+/** Starts editing `primary` in place, its `others` linked; the name is preselected (IDEA's "Preselect old name"). */
+export function startInplaceRename(view: EditorView, session: Omit<InplaceSession, "oldName">): void {
+ const oldName = view.state.sliceDoc(session.primary.from, session.primary.to);
+ view.dispatch({
+ effects: startSession.of({ ...session, oldName }),
+ selection: EditorSelection.range(session.primary.from, session.primary.to),
+ scrollIntoView: true,
+ });
+}
+
+/**
+ * Ends the session, putting the old name back everywhere. Returns the name
+ * that was typed (null without a session). `commit` then runs the rename.
+ */
+export function endInplaceRename(view: EditorView, how: "commit" | "cancel" | "restore"): string | null {
+ const s = inplaceSession(view.state);
+ if (!s) return null;
+ const typed = view.state.sliceDoc(s.primary.from, s.primary.to);
+ const spans = [s.primary, ...s.others].sort((a, b) => a.from - b.from);
+ const changes = view.state.changes(spans.map((o) => ({ ...o, insert: s.oldName })));
+ const head = view.state.selection.main.head;
+ const inName = Math.min(Math.max(0, head - s.primary.from), s.oldName.length);
+ const caret = changes.mapPos(s.primary.from, -1) + inName;
+ const insideName = head >= s.primary.from && head <= s.primary.to;
+ view.dispatch({
+ changes,
+ effects: endSession.of(null),
+ // Leaving the name keeps the caret where the user put it.
+ selection: insideName ? EditorSelection.cursor(caret) : undefined,
+ annotations: [inplaceEdit.of(true), Transaction.addToHistory.of(false)],
+ });
+ if (how === "commit") s.commit(typed);
+ return typed;
+}
+
+/** Leaving the name (caret or an edit elsewhere) finishes the rename, like IDEA's template. */
+const watcher = ViewPlugin.fromClass(
+ class {
+ constructor(private view: EditorView) {}
+ update(u: ViewUpdate) {
+ const s = inplaceSession(u.state);
+ if (!s || !inplaceSession(u.startState)) return;
+ const head = u.state.selection.main.head;
+ const outside = head < s.primary.from || head > s.primary.to || u.state.selection.ranges.length > 1;
+ const foreignEdit = u.transactions.some((tr) => {
+ const before = inplaceSession(tr.startState);
+ return !!before && tr.docChanged && !tr.annotation(inplaceEdit) && !isExternalChange(tr) && !changesWithin(tr.changes, before.primary);
+ });
+ if (outside || foreignEdit) queueMicrotask(() => endInplaceRename(this.view, "commit"));
+ }
+ },
+);
+
+const keys = Prec.highest(
+ keymap.of([
+ { key: "Enter", run: (v) => endInplaceRename(v, "commit") !== null },
+ { key: "Tab", run: (v) => endInplaceRename(v, "commit") !== null },
+ { key: "Escape", run: (v) => endInplaceRename(v, "cancel") !== null },
+ // Undo while renaming restores the old name instead of undoing earlier edits.
+ { key: "Mod-z", run: (v) => endInplaceRename(v, "cancel") !== null },
+ ]),
+);
+
+export function inplaceRenameExtension(): Extension {
+ return [sessionField, mirror, watcher, keys];
+}
diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts
index f6f9c1843..144513609 100644
--- a/src/editor/lsp/intentions.ts
+++ b/src/editor/lsp/intentions.ts
@@ -37,6 +37,51 @@ async function fetchActions(view: EditorView, only: string[], whole = false): Pr
return lspRequest(() => commands.lspCodeActions(doc.doc, range, only));
}
+interface PlacedProblem {
+ from: number;
+ to: number;
+ severity: string;
+}
+
+/**
+ * As in IDEA, when no error touches the caret, the fixes of an
+ * error elsewhere on the caret line are offered too. The errors to ask about,
+ * in line order; none when an error is at the caret.
+ */
+export function lineErrorsAwayFromCaret(problems: readonly PlacedProblem[], lineFrom: number, lineTo: number, caret: number): PlacedProblem[] {
+ const errors = problems.filter((p) => p.severity === "error");
+ if (errors.some((p) => p.from <= caret && caret <= p.to)) return [];
+ return errors.filter((p) => p.from >= lineFrom && p.from <= lineTo).sort((a, b) => a.from - b.from);
+}
+
+/** ⌥↵ / lightbulb actions: those at the caret plus, as in IDEA, quick fixes of another error on the line. */
+async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
+ const actions = (await fetchActions(view, [])).filter((a) => !a.disabledReason);
+ const doc = docOf(view);
+ const state = view.state;
+ const sel = state.selection.main;
+ if (!doc || !sel.empty) return actions;
+ const line = state.doc.lineAt(sel.head);
+ const problems: PlacedProblem[] = [];
+ forEachDiagnostic(state, (d, from, to) => problems.push({ from, to, severity: d.severity }));
+ const titles = new Set(actions.map((a) => a.title));
+ for (const p of lineErrorsAwayFromCaret(problems, line.from, line.to, sel.head)) {
+ let more: CodeAction[];
+ try {
+ more = await lspRequest(() => commands.lspCodeActions(doc.doc, offsetsToRange(state.doc, p.from, p.to), ["quickfix"]));
+ } catch {
+ break;
+ }
+ if (view.state.doc !== state.doc) break;
+ const fixes = more.filter((a) => isQuickFix(a) && !a.disabledReason && !titles.has(a.title));
+ if (fixes.length) {
+ actions.push(...fixes);
+ break;
+ }
+ }
+ return actions;
+}
+
export async function applyCodeAction(view: EditorView, action: CodeAction) {
const doc = docOf(view);
if (!doc) return;
@@ -91,7 +136,7 @@ function actionItems(view: EditorView, actions: CodeAction[]): ListPopupItem[] {
export async function showIntentions(view: EditorView) {
try {
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
- const actions = (await fetchActions(view, [])).filter((a) => !a.disabledReason);
+ const actions = await fetchIntentions(view);
if (!actions.length) {
showHint(view, "No intentions available");
return;
@@ -205,7 +250,7 @@ const bulbPlugin = ViewPlugin.fromClass(
if (!doc || doc.readOnly || serverBackoff.active(doc.doc) || !this.view.dom.isConnected) return;
const state = this.view.state;
try {
- const actions = (await fetchActions(this.view, [])).filter((a) => !a.disabledReason);
+ const actions = await fetchIntentions(this.view);
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection)) return;
const line = state.doc.lineAt(state.selection.main.head).number;
this.view.dispatch({
diff --git a/src/editor/lsp/links.test.ts b/src/editor/lsp/links.test.ts
index 7d402c358..f4c47d79b 100644
--- a/src/editor/lsp/links.test.ts
+++ b/src/editor/lsp/links.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
-import { fragmentOffset, linkReference, looksLikePath, normalizePath, pathCandidates, textReference } from "./links";
+import { fragmentOffset, linkReference, looksLikePath, textReference } from "./links";
const at = (src: string, marker = "|") => {
const offset = src.indexOf(marker);
@@ -40,19 +40,6 @@ describe("text references", () => {
});
});
-describe("path resolution", () => {
- it("resolves against the file's directory, then the project root", () => {
- expect(pathCandidates("../img/a%20b.png?v=2", "/p/web/x/index.html", "/p")).toEqual(["/p/web/img/a b.png"]);
- expect(pathCandidates("img/a.png", "/p/web/index.html", "/p")).toEqual(["/p/web/img/a.png", "/p/img/a.png"]);
- expect(pathCandidates("/splash.css", "/p/index.html", "/p", ["/p/public"])).toEqual([
- "/p/splash.css",
- "/p/public/splash.css",
- "/splash.css",
- ]);
- expect(normalizePath("/a/./b/../c")).toBe("/a/c");
- });
-});
-
describe("links and fragments", () => {
it("picks the server link around the offset", () => {
const text = Text.of(['<a href="b.html#top">']);
diff --git a/src/editor/lsp/links.ts b/src/editor/lsp/links.ts
index 8208435d3..675862c75 100644
--- a/src/editor/lsp/links.ts
+++ b/src/editor/lsp/links.ts
@@ -11,8 +11,7 @@ import type { EditorView } from "@codemirror/view";
import { whenSynced, type EditorDocContext } from "@/editor/api";
import { call, commands, isTauri, type DocumentLink } from "@/platform/ipc";
import { openExternalUrl } from "@/platform/openUrl";
-import { useProject } from "@/platform/project";
-import { currentRoots } from "@/platform/projectRoots";
+import { executeAction } from "@/platform/actions";
import { editorService } from "@/workbench/contributions";
import { lspRequest } from "./lsp";
import { rangeToOffsets } from "./positions";
@@ -22,6 +21,8 @@ export type Reference =
| { kind: "url"; from: number; to: number; url: string }
/** A quoted path that still has to be resolved against the file system. */
| { kind: "path"; from: number; to: number; value: string }
+ /** A folder: revealed in the project view. */
+ | { kind: "folder"; from: number; to: number; path: string }
/** A link whose file does not exist (reported, never opened). */
| { kind: "missing"; from: number; to: number; value: string };
@@ -99,48 +100,6 @@ export function textReference(text: Text, offset: number): Reference | null {
return null;
}
-function dirname(path: string): string {
- const i = path.lastIndexOf("/");
- return i > 0 ? path.slice(0, i) : "/";
-}
-
-/** `a/./b/../c` → `a/c`. */
-export function normalizePath(path: string): string {
- const out: string[] = [];
- for (const seg of path.split("/")) {
- if (seg === "." || (seg === "" && out.length)) continue;
- if (seg === ".." && out.length > 1) out.pop();
- else out.push(seg);
- }
- return out.join("/") || "/";
-}
-
-/**
- * Where a path-like string may point, most likely first. `/x` resolves against
- * the project root and its resource roots (`resourceRoots`, absolute), like IDEA.
- */
-export function pathCandidates(value: string, from: string, root: string | null, resourceRoots: readonly string[] = []): string[] {
- const bare = decodeURIComponentSafe(value.replace(/[?#].*$/, ""));
- const list: string[] = [];
- if (bare.startsWith("/")) {
- if (root) list.push(`${root}${bare}`);
- list.push(...resourceRoots.map((d) => `${d}${bare}`));
- list.push(bare);
- } else if (!bare.startsWith("~")) {
- list.push(`${dirname(from)}/${bare}`);
- if (root && !bare.startsWith("..")) list.push(`${root}/${bare}`);
- }
- return [...new Set(list.map(normalizePath))];
-}
-
-function decodeURIComponentSafe(s: string): string {
- try {
- return decodeURIComponent(s);
- } catch {
- return s;
- }
-}
-
async function isFile(path: string): Promise<boolean> {
if (!isTauri()) return false;
try {
@@ -151,18 +110,16 @@ async function isFile(path: string): Promise<boolean> {
}
}
-/** Resolves a `path` reference to an existing file; null when none exists. */
+/** Resolves a `path` reference (in the backend, like IDEA's file references); null when nothing exists there. */
export async function resolvePath(ref: Reference, from: string): Promise<Reference | null> {
if (ref.kind !== "path") return ref;
- const root = useProject.getState().project?.root ?? null;
- const resources = root
- ? currentRoots()
- .filter((r) => r.kind === "resources")
- .map((r) => (r.path ? `${root}/${r.path}` : root))
- : [];
- for (const path of pathCandidates(ref.value, from, root, resources))
- if (await isFile(path)) return { kind: "file", from: ref.from, to: ref.to, path, fragment: ref.value.split("#")[1] ?? null };
- return null;
+ if (!isTauri()) return null;
+ const path = await call(commands.fsResolveReference(from, ref.value)).catch(() => null);
+ if (!path) return null;
+ const fragment = ref.value.split("#")[1] ?? null;
+ return (await isFile(path))
+ ? { kind: "file", from: ref.from, to: ref.to, path, fragment }
+ : { kind: "folder", from: ref.from, to: ref.to, path };
}
// --- following ----------------------------------------------------------------
@@ -200,6 +157,10 @@ const slug = (s: string) =>
export async function followReference(ref: Reference): Promise<void> {
if (ref.kind === "missing") throw new Error(`Cannot find file '${ref.value}'`);
+ if (ref.kind === "folder") {
+ await executeAction("navigate.selectIn", { path: ref.path });
+ return;
+ }
if (ref.kind === "url") {
await openExternalUrl(ref.url);
return;
diff --git a/src/editor/lsp/markdown.ts b/src/editor/lsp/markdown.ts
index 5a245a5fb..b07cf978c 100644
--- a/src/editor/lsp/markdown.ts
+++ b/src/editor/lsp/markdown.ts
@@ -68,6 +68,23 @@ export function isEmptyMarkup(m: Markup | null | undefined): boolean {
return !m || !m.value.trim();
}
+/**
+ * The declaration line(s) of hover documentation, for the brief ⌘-hover info: the first fenced code block, else the first paragraph.
+ */
+export function declarationSummary(m: Markup, maxLines = 6): { code: string; language: string | null } | { text: string } | null {
+ if (m.kind === "markdown") {
+ const fence = /^\s*(```|~~~)[ \t]*([\w+#.-]*)[^\n]*\n([\s\S]*?)\n\s*\1/m.exec(m.value);
+ if (fence && fence[3]!.trim()) {
+ const lines = fence[3]!.replace(/\s+$/, "").split("\n");
+ const code = lines.slice(0, maxLines).join("\n") + (lines.length > maxLines ? "\n…" : "");
+ return { code, language: fence[2] || null };
+ }
+ }
+ const para = m.value.trim().split(/\n\s*\n/)[0]?.trim();
+ if (!para) return null;
+ return { text: para.length > 200 ? `${para.slice(0, 199)}…` : para };
+}
+
const langCache = new Map<string, LanguageDescription | null>();
function findLanguage(name: string): LanguageDescription | null {
diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts
index c5515a69c..4b648e228 100644
--- a/src/editor/lsp/navigation.ts
+++ b/src/editor/lsp/navigation.ts
@@ -4,8 +4,17 @@
* chooser, and document highlights (occurrences of the symbol at the caret,
* plus the sticky find.highlightUsages variant).
*/
-import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
-import { Decoration, EditorView, ViewPlugin, keymap, type DecorationSet, type ViewUpdate } from "@codemirror/view";
+import { EditorSelection, Prec, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
+import {
+ Decoration,
+ EditorView,
+ ViewPlugin,
+ keymap,
+ showTooltip,
+ type DecorationSet,
+ type Tooltip,
+ type ViewUpdate,
+} from "@codemirror/view";
import {
commands,
isCancelled,
@@ -36,9 +45,12 @@ import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { readManyFileLines } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
import { serverBackoff } from "./availability";
+import { requestHover } from "./hover";
+import { declarationSummary, renderCode } from "./markdown";
import { editorPrefs } from "@/platform/editorSettings";
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
-import { hasPrimaryModifier, isMacHost } from "@/platform/keymap";
+import { hasPrimaryModifier, isMacHost, shortcutLabel } from "@/platform/keymap";
+import { create } from "zustand";
export async function navigateTo(loc: Location) {
await editorService().openFile(loc.path, {
@@ -227,49 +239,134 @@ async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos):
// ---------------------------------------------------------------------------
// ⌘-hover link + ⌘-click
-const setLink = StateEffect.define<{ from: number; to: number } | null>();
+type NavInfo = NonNullable<ReturnType<typeof declarationSummary>>;
+
+interface LinkState {
+ from: number;
+ to: number;
+ /** Brief declaration info shown above the underlined element (IDEA's ⌘-hover tooltip). */
+ info: NavInfo | null;
+}
+
+const setLink = StateEffect.define<LinkState | null>();
const linkMark = Decoration.mark({ class: "cm-lsp-link" });
-const linkField = StateField.define<DecorationSet>({
- create: () => Decoration.none,
- update(deco, tr) {
- for (const e of tr.effects)
- if (e.is(setLink)) return e.value ? Decoration.set([linkMark.range(e.value.from, e.value.to)]) : Decoration.none;
- return tr.docChanged ? Decoration.none : deco;
+const linkField = StateField.define<LinkState | null>({
+ create: () => null,
+ update(value, tr) {
+ for (const e of tr.effects) if (e.is(setLink)) return e.value;
+ return tr.docChanged ? null : value;
},
- provide: (f) => EditorView.decorations.from(f),
+ provide: (f) => [
+ EditorView.decorations.from(f, (v) => (v ? Decoration.set([linkMark.range(v.from, v.to)]) : Decoration.none)),
+ showTooltip.from(f, (v): Tooltip | null => {
+ const info = v?.info;
+ if (!v || !info) return null;
+ return {
+ pos: v.from,
+ above: true,
+ create: (view) => {
+ const dom = document.createElement("div");
+ dom.className = "cm-lsp-hover cm-lsp-nav-info";
+ if ("code" in info) dom.appendChild(renderCode(info.code, info.language ?? docOf(view)?.uiMode ?? null, "cm-lsp-code"));
+ else dom.textContent = info.text;
+ return { dom };
+ },
+ };
+ }),
+ ],
});
-/** What ⌘-hover underlines: a whole link, URL or path, else the word. */
-function linkAt(view: EditorView, x: number, y: number) {
+/** What ⌘-hover underlines: a whole link, URL or path (always navigable), else the word. */
+function linkAt(view: EditorView, x: number, y: number): { from: number; to: number; link: boolean } | null {
const pos = view.posAtCoords({ x, y }, false);
if (pos == null) return null;
const links = knownLinks(view);
const ref = (links && linkReference(view.state.doc, links, pos)) ?? textReference(view.state.doc, pos);
- if (ref) return ref;
+ if (ref) return { from: ref.from, to: ref.to, link: true };
const word = view.state.wordAt(pos);
- return word && word.from < word.to ? word : null;
+ return word && word.from < word.to ? { from: word.from, to: word.to, link: false } : null;
+}
+
+/**
+ * Whether ⌘-click at `offset` would navigate somewhere, with the declaration
+ * info to show; null when there is no target (no underline then, as in IDEA).
+ */
+async function probeNavigation(view: EditorView, offset: number): Promise<{ info: NavInfo | null } | null> {
+ const doc = docOf(view);
+ let navigable = !!contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
+ if (!navigable && doc) {
+ const pos = offsetToPos(view.state.doc, offset);
+ try {
+ navigable = (await lspRequest(() => commands.lspGoto(doc.doc, pos, "definition"))).length > 0;
+ } catch (e) {
+ if (isCancelled(e)) return null;
+ if (isUnavailable(e)) navigable = !!(await gotoFallback(view, doc, pos))?.length;
+ }
+ if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual)
+ navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length;
+ }
+ if (!navigable) return null;
+ const hover = await requestHover(view, offset).catch(() => null);
+ return { info: hover ? declarationSummary(hover.contents) : null };
}
const linkPlugin = ViewPlugin.fromClass(
class {
last: { x: number; y: number } | null = null;
+ /** Probe results per word (`from:to`) for the current document. */
+ private probed = new Map<string, { info: NavInfo | null } | null>();
+ private probedDoc: Text | null = null;
+ private probing: string | null = null;
constructor(readonly view: EditorView) {}
+ private set(value: LinkState | null) {
+ const current = this.view.state.field(linkField);
+ if (current === value || (current && value && current.from === value.from && current.to === value.to && current.info === value.info))
+ return;
+ if (!current && !value) return;
+ this.view.dispatch({ effects: setLink.of(value) });
+ }
show(meta: boolean) {
- const doc = meta ? docOf(this.view) : null;
+ const view = this.view;
+ const doc = meta ? docOf(view) : null;
// Underline whole links once the server's links are in.
- if (doc && !doc.virtual && !knownLinks(this.view))
- void documentLinks(this.view, doc).then(() => {
- if (this.view.state.field(linkField).size) this.show(true);
+ if (doc && !doc.virtual && !knownLinks(view))
+ void documentLinks(view, doc).then(() => {
+ if (view.state.field(linkField)) this.show(true);
});
- const current = this.view.state.field(linkField);
- const target = meta && this.last ? linkAt(this.view, this.last.x, this.last.y) : null;
- let same = false;
- current.between(0, this.view.state.doc.length, (from, to) => {
- same = !!target && target.from === from && target.to === to;
+ const target = meta && this.last ? linkAt(view, this.last.x, this.last.y) : null;
+ if (!target) {
+ this.probing = null;
+ this.set(null);
+ return;
+ }
+ if (target.link) {
+ this.probing = null;
+ this.set({ from: target.from, to: target.to, info: null });
+ return;
+ }
+ if (this.probedDoc !== view.state.doc) {
+ this.probed.clear();
+ this.probedDoc = view.state.doc;
+ }
+ const key = `${target.from}:${target.to}`;
+ if (this.probed.has(key)) {
+ const hit = this.probed.get(key);
+ this.set(hit ? { from: target.from, to: target.to, info: hit.info } : null);
+ return;
+ }
+ const current = view.state.field(linkField);
+ if (current && (current.from !== target.from || current.to !== target.to)) this.set(null);
+ if (this.probing === key) return;
+ this.probing = key;
+ const docAt = view.state.doc;
+ void probeNavigation(view, target.from).then((result) => {
+ if (view.state.doc !== docAt) return;
+ this.probed.set(key, result);
+ if (this.probing !== key) return;
+ this.probing = null;
+ if (result) this.set({ from: target.from, to: target.to, info: result.info });
});
- if (same || (!target && current.size === 0)) return;
- this.view.dispatch({ effects: setLink.of(target) });
}
},
{
@@ -314,7 +411,9 @@ interface HighlightState {
sticky: boolean;
}
-const setHighlights = StateEffect.define<{ items: Array<{ from: number; to: number; kind: Highlight["kind"] }>; sticky: boolean }>();
+type HighlightItem = { from: number; to: number; kind: Highlight["kind"] };
+
+const setHighlights = StateEffect.define<{ items: HighlightItem[]; sticky: boolean }>();
const marks = {
text: Decoration.mark({ class: "cm-lsp-occurrence" }),
@@ -334,20 +433,48 @@ const highlightField = StateField.define<HighlightState>({
),
sticky: e.value.sticky,
};
- if (tr.docChanged) return { deco: Decoration.none, sticky: false };
+ // Kept (mapped) until recomputed; ⌘⇧F7 highlights survive edits until Escape.
+ if (tr.docChanged) return { deco: value.deco.map(tr.changes), sticky: value.sticky };
return value;
},
provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
});
+/** IDEA's status bar text while ⌘⇧F7 highlights are shown. */
+export const useUsagesStatus = create<{ text: string | null; owner: EditorView | null }>(() => ({ text: null, owner: null }));
+
+function setUsagesStatus(owner: EditorView | null, text: string | null) {
+ useUsagesStatus.setState({ owner, text });
+}
+
+export function usagesStatusText(count: number, name: string, toggleKeys: string | null): string {
+ const again = toggleKeys ? `press ${toggleKeys} again to remove the highlighting, ` : "";
+ return `${count} ${count === 1 ? "usage" : "usages"} of ${name} found (${again}Escape to remove all highlighting)`;
+}
+
+function clearHighlights(view: EditorView) {
+ view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) });
+ if (useUsagesStatus.getState().owner === view) setUsagesStatus(null, null);
+}
+
async function fetchHighlights(view: EditorView, sticky: boolean) {
const doc = docOf(view);
if (!doc) return;
+ await whenSynced(view);
const state = view.state;
const head = state.selection.main.head;
const stale = () => view.state.doc !== state.doc || view.state.selection.main.head !== head;
- const apply = (items: Array<{ from: number; to: number; kind: Highlight["kind"] }>) =>
- view.dispatch({ effects: setHighlights.of({ items, sticky }) });
+ const apply = (items: HighlightItem[]) => {
+ view.dispatch({ effects: setHighlights.of({ items, sticky: sticky && items.length > 0 }) });
+ if (!sticky) return;
+ if (!items.length) {
+ if (useUsagesStatus.getState().owner === view) setUsagesStatus(null, null);
+ return;
+ }
+ const at = items.find((i) => i.from <= head && head <= i.to) ?? state.wordAt(head);
+ const name = at ? state.sliceDoc(at.from, at.to) : "";
+ setUsagesStatus(view, usagesStatusText(items.length, name ? `'${name}'` : "the element", shortcutLabel("find.highlightUsages") ?? null));
+ };
let lspError: unknown = null;
if (!serverBackoff.active(doc.doc)) {
try {
@@ -388,8 +515,18 @@ async function syntaxHighlights(view: EditorView, doc: EditorDocContext, head: n
}
}
-/** ⌘⇧F7: highlight usages of the symbol at the caret until Escape. */
+/** ⌘⇧F7: highlight usages of the symbol at the caret until Escape; again on a highlighted usage removes them. */
export function highlightUsages(view: EditorView) {
+ const st = view.state.field(highlightField, false);
+ const head = view.state.selection.main.head;
+ let onUsage = false;
+ st?.deco.between(head, head, (from, to) => {
+ if (from <= head && head <= to) onUsage = true;
+ });
+ if (st?.sticky && onUsage) {
+ clearHighlights(view);
+ return;
+ }
void fetchHighlights(view, true);
}
@@ -398,25 +535,27 @@ const highlightPlugin = ViewPlugin.fromClass(
private request = debounce(() => void fetchHighlights(this.view, false), 300);
constructor(private view: EditorView) {}
update(u: ViewUpdate) {
- if (u.docChanged) this.request.cancel();
- if (!u.selectionSet || u.docChanged) return;
+ // Recomputed after caret moves and, like IDEA's daemon, after edits.
+ if (!u.selectionSet && !u.docChanged) return;
const st = u.state.field(highlightField);
- if (st.sticky) return;
- // Code Editing › "Usages of element at caret".
- if (!editorPrefs().codeEditing.highlightUsages) {
- if (st.deco.size) queueMicrotask(() => this.view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) }));
+ if (st.sticky) {
+ this.request.cancel();
return;
}
- const sel = u.state.selection.main;
- if (!sel.empty) {
+ const clear = () => {
this.request.cancel();
if (st.deco.size) queueMicrotask(() => this.view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) }));
+ };
+ // Code Editing › "Usages of element at caret".
+ if (!editorPrefs().codeEditing.highlightUsages || !u.state.selection.main.empty) {
+ clear();
return;
}
this.request();
}
destroy() {
this.request.cancel();
+ if (useUsagesStatus.getState().owner === this.view) setUsagesStatus(null, null);
}
},
);
@@ -434,7 +573,7 @@ export function navigationExtension(): Extension {
run: (view) => {
const st = view.state.field(highlightField, false);
if (!st?.sticky) return false;
- view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) });
+ clearHighlights(view);
return true;
},
},
diff --git a/src/editor/lsp/popupStore.ts b/src/editor/lsp/popupStore.ts
index 738a707a0..3f827a318 100644
--- a/src/editor/lsp/popupStore.ts
+++ b/src/editor/lsp/popupStore.ts
@@ -75,9 +75,15 @@ interface PopupState {
popup: LspPopup | null;
/** Bumped per open so React remounts a popup of the same kind. */
seq: number;
+ /** Bumped to move focus into the open popup (F1 on an open documentation popup). */
+ focusSeq: number;
}
-export const useLspPopup = create<PopupState>(() => ({ popup: null, seq: 0 }));
+export const useLspPopup = create<PopupState>(() => ({ popup: null, seq: 0, focusSeq: 0 }));
+
+export function focusPopup() {
+ useLspPopup.setState((s) => ({ focusSeq: s.focusSeq + 1 }));
+}
export function openPopup(popup: LspPopup) {
useLspPopup.setState((s) => ({ popup, seq: s.seq + 1 }));
diff --git a/src/editor/lsp/rename.ts b/src/editor/lsp/rename.ts
index 96645a920..680a20b30 100644
--- a/src/editor/lsp/rename.ts
+++ b/src/editor/lsp/rename.ts
@@ -1,7 +1,8 @@
/**
- * Rename (⇧F6): `lsp_prepare_rename` → inline name popup at the symbol →
- * `lsp_rename` → preview dialog when the edit spans several files (or moves
- * files), otherwise applied directly via `apply_workspace_edit`.
+ * Rename (⇧F6): `lsp_prepare_rename` → the name is edited in place with this
+ * file's occurrences linked (`inplaceRename.ts`; ⇧F6 again opens the name
+ * dialog) → `lsp_rename` → preview dialog when the edit spans several files
+ * (or moves files), otherwise applied directly via `apply_workspace_edit`.
*
* Dumb mode: when the server is not ready / failing, or answers nothing over
* code with syntax errors, a *local* variable is renamed in place from the
@@ -18,6 +19,8 @@ import { comparePos, offsetToPos, rangeToOffsets } from "./positions";
import { showHint } from "./hint";
import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore";
import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit";
+import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename";
+import { shortcutLabel } from "@/platform/keymap";
import {
SYNTAX_NOTE,
VALID_NAME,
@@ -46,6 +49,13 @@ async function hasSyntaxErrors(doc: number): Promise<boolean> {
export async function startRename(view: EditorView) {
const doc = docOf(view);
if (!doc) return;
+ // ⇧F6 while renaming in place: the dialog with more options, keeping what was typed.
+ const session = inplaceSession(view.state);
+ if (session) {
+ const typed = endInplaceRename(view, "restore");
+ if (typed !== null) session.dialog(typed);
+ return;
+ }
if (doc.readOnly) {
showHint(view, "The file is read-only");
return;
@@ -69,15 +79,68 @@ export async function startRename(view: EditorView) {
}
const { from, to } = rangeToOffsets(view.state.doc, range);
const oldName = view.state.sliceDoc(from, to);
- openPopup({
- kind: "rename",
- anchor: caretAnchor(view, from),
- title: `Rename '${oldName}'`,
- initial: oldName,
- onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
+ const dialog = (initial: string) =>
+ openPopup({
+ kind: "rename",
+ anchor: caretAnchor(view, from),
+ title: `Rename '${oldName}'`,
+ initial,
+ onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
+ });
+ if (from === to) {
+ dialog(oldName);
+ return;
+ }
+ // IDEA renames in place by default: occurrences in this file follow live.
+ const state = view.state;
+ const others = await linkedOccurrences(view, doc.doc, pos, { from, to }, oldName);
+ if (view.state.doc !== state.doc) return;
+ const keys = shortcutLabel("refactor.rename");
+ startInplaceRename(view, {
+ primary: { from, to },
+ others,
+ hint: keys ? `Press ${keys} to show dialog with more options` : "Rename in place: ↵ to finish, Esc to cancel",
+ commit: (newName) => void commitInplace(view, doc, pos, oldName, newName),
+ dialog,
});
}
+/** This file's other occurrences of the symbol (document highlights with the same text). */
+async function linkedOccurrences(view: EditorView, doc: number, pos: Pos, primary: Span, name: string): Promise<Span[]> {
+ let highlights;
+ try {
+ highlights = await lspRequest(() => commands.lspDocumentHighlights(doc, pos));
+ } catch {
+ return [];
+ }
+ const text = view.state.doc;
+ return linkedSpans(
+ highlights.map((h) => rangeToOffsets(text, h.range)),
+ primary,
+ (s) => text.sliceString(s.from, s.to) === name,
+ );
+}
+
+/** Occurrence spans other than `primary`, sorted, without overlaps, that `accept` keeps. */
+export function linkedSpans(spans: readonly Span[], primary: Span, accept: (s: Span) => boolean): Span[] {
+ const out: Span[] = [];
+ for (const s of [...spans].sort((a, b) => a.from - b.from)) {
+ if (s.to > primary.from && s.from < primary.to) continue;
+ if (s.from >= s.to || !accept(s)) continue;
+ const last = out[out.length - 1];
+ if (last && s.from < last.to) continue;
+ out.push(s);
+ }
+ return out;
+}
+
+async function commitInplace(view: EditorView, doc: EditorDocContext, pos: Pos, oldName: string, newName: string) {
+ if (!newName.trim() || newName === oldName) return;
+ // The server renames from the original text, which the session just restored.
+ await whenSynced(view);
+ await finishRename(view, doc, pos, oldName, newName);
+}
+
async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, oldName: string, newName: string) {
if (!newName || newName === oldName) return;
let edit: WorkspaceEdit;
diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts
index 95220c816..df8ba2b2c 100644
--- a/src/editor/lsp/theme.ts
+++ b/src/editor/lsp/theme.ts
@@ -255,6 +255,18 @@ export const lspTheme = EditorView.theme({
".cm-lsp-occurrence-write": {
backgroundColor: "var(--bg-identifier-under-caret-write, color-mix(in srgb, var(--danger) 12%, transparent))",
},
+ ".cm-lsp-nav-info": { padding: "4px 8px" },
+
+ // --- in-place rename (inplaceRename.ts) ------------------------------------
+ ".cm-lsp-inplace": {
+ backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
+ },
+ ".cm-lsp-inplace-primary": {
+ outline: "1px solid var(--focus-ring)",
+ outlineOffset: "-1px",
+ borderRadius: "2px",
+ },
+ ".cm-lsp-inplace-hint": { color: "var(--fg-secondary)", fontSize: "var(--fs-small)", padding: "3px 8px" },
// --- floating lightbulb (intentions.ts) -----------------------------------
".cm-lsp-bulb": {
diff --git a/src/editor/navigation/index.ts b/src/editor/navigation/index.ts
index 6cfb1e72f..c839f1ee5 100644
--- a/src/editor/navigation/index.ts
+++ b/src/editor/navigation/index.ts
@@ -56,7 +56,7 @@ async function gotoMethod(view: EditorView, dir: 1 | -1) {
const target = methodStop(at.outline, at.caret, dir);
if (!target) return;
const pos = posToOffset(view.state.doc, target);
- view.dispatch({ selection: EditorSelection.cursor(pos), scrollIntoView: true, userEvent: "select" });
+ view.dispatch({ selection: EditorSelection.cursor(pos), scrollIntoView: true, userEvent: "select.navigate" });
}
/** Without a type hierarchy: languages whose servers answer "super" through another request. */
diff --git a/src/features/build/Build.module.css b/src/features/build/Build.module.css
index 237e4ebe6..be0f0c465 100644
--- a/src/features/build/Build.module.css
+++ b/src/features/build/Build.module.css
@@ -79,7 +79,7 @@
color: var(--fg);
background: var(--bg-app);
-webkit-user-select: text;
-cursor: text;
+ cursor: text;
-webkit-user-select: text;
user-select: text;
outline: none;
@@ -115,3 +115,42 @@ cursor: text;
height: 30px;
border-radius: 6px;
}
+.treeHost {
+ display: flex;
+ flex-direction: column;
+}
+.treeHost > * {
+ flex: 1;
+ min-height: 0;
+}
+
+.detail {
+ overflow: auto;
+ padding: 4px 12px;
+ font-family: var(--font-mono);
+ font-size: var(--fs-code);
+ line-height: 20px;
+ color: var(--fg);
+ background: var(--bg-app);
+ -webkit-user-select: text;
+ user-select: text;
+ outline: none;
+}
+.detailLocation {
+ display: block;
+ padding: 0;
+ border: none;
+ background: none;
+ font: inherit;
+ color: var(--link);
+ cursor: pointer;
+ text-align: left;
+}
+.detailLocation:hover {
+ color: var(--link-hover);
+ text-decoration: underline;
+}
+.detailText {
+ white-space: pre-wrap;
+ tab-size: 4;
+}
diff --git a/src/features/build/BuildView.tsx b/src/features/build/BuildView.tsx
index 35b82e1bf..61f27239c 100644
--- a/src/features/build/BuildView.tsx
+++ b/src/features/build/BuildView.tsx
@@ -1,13 +1,13 @@
/**
* Build tool window (IDEA's Build view): the build → file → message tree on
* the left, the raw console of the build on the right. Selecting a message
- * shows its source; Enter / double-click moves focus there.
+ * shows its full text on the right instead; Enter / double-click / F4 opens
+ * its source (as IDEA: selection shows, navigation jumps).
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { useVirtualizer } from "@tanstack/react-virtual";
import { basename, relativeDir, useProject } from "@/platform/project";
-import { editorService } from "@/workbench/contributions";
import {
EmptyState,
Icon,
@@ -18,6 +18,7 @@ import {
Spinner,
Tree,
fileIconName,
+ type TreeHandle,
type TreeRowState,
T,
} from "@/ui";
@@ -25,6 +26,7 @@ import type { BuildMessage, Severity } from "@/platform/ipc";
import {
ROOT_KEY,
fileChildren,
+ findNode,
finishSummary,
formatDuration,
rootChildren,
@@ -32,21 +34,11 @@ import {
type BuildNode,
type BuildStatus,
} from "./model";
-import { rerunBuild, useBuildRun } from "./store";
+import { navigateToMessage, rerunBuild, selectBuildNode, useBuildRun } from "./store";
import styles from "./Build.module.css";
const SEVERITY_ICON: Record<Severity, string> = { error: "error", warning: "warning", info: "info", hint: "info" };
-function openMessage(m: BuildMessage, focus: boolean) {
- if (!m.path) return;
- const start = m.range?.start;
- void editorService().openFile(m.path, {
- selection: start ? { line: start.line, col: start.col } : undefined,
- focus,
- preview: !focus,
- });
-}
-
function firstLocated(n: BuildNode): BuildMessage | undefined {
if (n.kind === "message") return n.message;
if (n.kind === "file") return n.messages[0];
@@ -79,9 +71,11 @@ export function BuildHeaderActions() {
}
function BuildTree() {
- const { title, status, messages, durationMs } = useBuildRun();
+ const { title, status, messages, durationMs, selected } = useBuildRun();
const root = useProject((s) => s.project?.root ?? "");
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
+ const tree = useRef<TreeHandle>(null);
+ const selection = useMemo(() => new Set(selected ? [selected] : []), [selected]);
const roots = useMemo(() => (status ? [rootNode(title, status, messages)] : []), [title, status, messages]);
const children = useMemo(() => rootChildren(messages), [messages]);
const expanded = useMemo(() => {
@@ -91,6 +85,27 @@ function BuildTree() {
return keys;
}, [children, collapsed]);
+ // A selection made by the store (the first error of a failed build) expands
+ // its file, then is scrolled into view.
+ const [shown, setShown] = useState(selected);
+ if (shown !== selected) {
+ setShown(selected);
+ const file = selected?.split("\u0000")[0];
+ if (file && file !== selected && collapsed.has(file)) {
+ const next = new Set(collapsed);
+ next.delete(file);
+ setCollapsed(next);
+ }
+ }
+ useEffect(() => {
+ if (selected && tree.current?.leadKey() !== selected) tree.current?.reveal(selected);
+ }, [selected, expanded]);
+
+ const navigate = (n: BuildNode) => {
+ const m = firstLocated(n);
+ if (m) navigateToMessage(m, true);
+ };
+
const getChildren = useCallback(
(n: BuildNode): BuildNode[] | undefined =>
n.kind === "root" ? children : n.kind === "file" ? fileChildren(n) : undefined,
@@ -143,33 +158,42 @@ function BuildTree() {
};
return (
- <Tree<BuildNode>
- aria-label="Build"
- roots={roots}
- getKey={(n) => n.key}
- getLabel={(n) => (n.kind === "root" ? n.title : n.kind === "file" ? basename(n.path) : n.message.text)}
- getChildren={getChildren}
- isExpandable={(n) => n.kind !== "message"}
- expanded={expanded}
- onExpandedChange={(_next, node, isOpen) =>
- setCollapsed((prev) => {
- const s = new Set(prev);
- if (isOpen) s.delete(node.key);
- else s.add(node.key);
- return s;
- })
- }
- renderNode={renderNode}
- onActivate={(n) => {
- const m = firstLocated(n);
- if (m) openMessage(m, true);
- }}
- onSelectionChange={(_sel, lead) => {
- if (lead?.kind === "message") openMessage(lead.message, false);
+ <div
+ className={styles.treeHost}
+ onKeyDown={(e) => {
+ if (e.key !== "F4" || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey || !selected) return;
+ const n = findNode(messages, selected);
+ if (!n) return;
+ e.preventDefault();
+ e.stopPropagation();
+ navigate(n);
}}
- multiSelect={false}
- empty={<EmptyState title="No build output" />}
- />
+ >
+ <Tree<BuildNode>
+ handleRef={tree}
+ aria-label="Build"
+ roots={roots}
+ getKey={(n) => n.key}
+ getLabel={(n) => (n.kind === "root" ? n.title : n.kind === "file" ? basename(n.path) : n.message.text)}
+ getChildren={getChildren}
+ isExpandable={(n) => n.kind !== "message"}
+ expanded={expanded}
+ onExpandedChange={(_next, node, isOpen) =>
+ setCollapsed((prev) => {
+ const s = new Set(prev);
+ if (isOpen) s.delete(node.key);
+ else s.add(node.key);
+ return s;
+ })
+ }
+ renderNode={renderNode}
+ selected={selection}
+ onActivate={navigate}
+ onSelectionChange={(_sel, lead) => selectBuildNode(lead?.key ?? null)}
+ multiSelect={false}
+ empty={<EmptyState title="No build output" />}
+ />
+ </div>
);
}
@@ -218,6 +242,34 @@ function BuildConsole() {
);
}
+/** Full text and location of the selected message (IDEA shows the node's own console). */
+function MessageDetail({ message }: { message: BuildMessage }) {
+ const root = useProject((s) => s.project?.root ?? "");
+ const start = message.range?.start;
+ const location = message.path
+ ? `${relativeDir(root, message.path) ? `${relativeDir(root, message.path)}/` : ""}${basename(message.path)}${
+ start ? `:${start.line + 1}:${start.col + 1}` : ""
+ }`
+ : null;
+ return (
+ <div className={styles.detail} tabIndex={0} role="document" aria-label="Build message">
+ {location && (
+ <button type="button" className={styles.detailLocation} onClick={() => navigateToMessage(message, true)}>
+ {location}
+ </button>
+ )}
+ <div className={clsx(styles.detailText, message.severity === "error" && styles.err)}>{message.text}</div>
+ </div>
+ );
+}
+
+function BuildOutput() {
+ const selected = useBuildRun((s) => s.selected);
+ const messages = useBuildRun((s) => s.messages);
+ const node = useMemo(() => (selected ? findNode(messages, selected) : undefined), [selected, messages]);
+ return node?.kind === "message" ? <MessageDetail message={node.message} /> : <BuildConsole />;
+}
+
export function BuildView() {
const hasBuild = useBuildRun((s) => s.status !== null);
if (!hasBuild) {
@@ -237,7 +289,7 @@ export function BuildView() {
</SplitPanel>
<SplitHandle />
<SplitPanel id="build-console" minSize="120px" className={styles.pane}>
- <BuildConsole />
+ <BuildOutput />
</SplitPanel>
</SplitGroup>
</div>
diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx
index 74352ba51..ac96fa84b 100644
--- a/src/features/build/build.test.tsx
+++ b/src/features/build/build.test.tsx
@@ -1,15 +1,34 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import { getAction, isActionEnabled } from "@/platform/actions";
import { getContext, setContext } from "@/platform/context";
import { bindingsFor } from "@/platform/keymap";
import { IpcError, type BuildEvent, type BuildMessage, type BuildResult } from "@/platform/ipc";
import { useProject } from "@/platform/project";
-import { menuGroupItems, provideNotificationService, useContributions, type NotificationService } from "@/workbench/contributions";
+import {
+ menuGroupItems,
+ provideEditorService,
+ provideNotificationService,
+ provideToolWindowService,
+ useContributions,
+ type EditorService,
+ type NotificationService,
+ type ToolWindowService,
+} from "@/workbench/contributions";
import { useTasks } from "@/workbench/tasks";
import { BuildView } from "./BuildView";
import { activate } from "./index";
-import { appendOutput, finishSummary, formatDuration, messageFiles, rootChildren, rootNode, MAX_CONSOLE_LINES } from "./model";
+import {
+ appendOutput,
+ findNode,
+ finishSummary,
+ firstError,
+ formatDuration,
+ messageFiles,
+ rootChildren,
+ rootNode,
+ MAX_CONSOLE_LINES,
+} from "./model";
import { BUILD_TASK_ID, setBuildBackend, startBuild, stopBuild, useBuildRun, type BuildBackend } from "./store";
const err = (path: string | null, line: number, text = "cannot find symbol"): BuildMessage => ({
@@ -30,6 +49,10 @@ describe("build model", () => {
expect(a.kind === "file" && a.messages.map((m) => m.range?.start.line)).toEqual([2, 9]);
expect(rootNode("demo", "failed", messages)).toMatchObject({ errors: 2, warnings: 2 });
expect(messageFiles(messages)).toEqual(["/p/B.java", "/p/A.java"]);
+ const first = firstError(messages)!;
+ expect(first.message.range?.start.line).toBe(9);
+ expect(findNode(messages, first.key)).toEqual(first);
+ expect(firstError([warn("/p/B.java", 3)])).toBeUndefined();
});
it("formats IDEA's finish summaries", () => {
@@ -37,12 +60,16 @@ describe("build model", () => {
expect(formatDuration(3000)).toBe("3 s");
expect(formatDuration(3120)).toBe("3 s 120 ms");
expect(formatDuration(65_000)).toBe("1 m 5 s");
- expect(finishSummary({ success: true, errors: 0, warnings: 0, durationMs: 3000 })).toBe("Build completed successfully in 3 s");
+ expect(finishSummary({ success: true, errors: 0, warnings: 0, durationMs: 3000 })).toBe(
+ "Build completed successfully in 3 s",
+ );
expect(finishSummary({ success: true, errors: 0, warnings: 1, durationMs: 500 })).toBe(
"Build completed successfully with 1 warning in 500 ms",
);
expect(finishSummary({ success: false, errors: 2, warnings: 0, durationMs: 1 })).toBe("Build failed: 2 errors");
- expect(finishSummary({ success: false, errors: 1, warnings: 2, durationMs: 1 })).toBe("Build failed: 1 error, 2 warnings");
+ expect(finishSummary({ success: false, errors: 1, warnings: 2, durationMs: 1 })).toBe(
+ "Build failed: 1 error, 2 warnings",
+ );
expect(finishSummary({ success: false, errors: 0, warnings: 0, durationMs: 1 })).toBe("Build failed");
});
@@ -97,9 +124,19 @@ describe("build feature", () => {
let dispose: () => void;
let notes: Note[];
let fake: FakeBackend;
+ let openFile: ReturnType<typeof vi.fn>;
+ let show: ReturnType<typeof vi.fn>;
beforeEach(() => {
notes = [];
+ openFile = vi.fn(() => Promise.resolve());
+ show = vi.fn();
+ provideEditorService({
+ openFile,
+ saveAll: () => Promise.resolve(),
+ activePath: () => null,
+ } as unknown as EditorService);
+ provideToolWindowService({ show } as unknown as ToolWindowService);
provideNotificationService({ notify: (n) => void notes.push(n) });
fake = new FakeBackend();
setBuildBackend(fake);
@@ -136,6 +173,7 @@ describe("build feature", () => {
await act(async () => {});
expect(getContext()["build.running"]).toBe(true);
expect(isActionEnabled(getAction("build.buildProject")!)).toBe(false);
+ expect(show).not.toHaveBeenCalled();
expect(useTasks.getState().tasks.some((t) => t.id === BUILD_TASK_ID && !t.done)).toBe(true);
const messages = [err("/p/src/A.java", 11), warn("/p/src/B.java", 2)];
await act(async () => {
@@ -157,6 +195,14 @@ describe("build feature", () => {
expect(screen.getByText("deprecated")).toBeInTheDocument();
expect(screen.getByText(":12:5")).toBeInTheDocument();
expect(notes.at(-1)).toMatchObject({ level: "error", title: "Build failed: 1 error, 1 warning" });
+ // A failure shows the tool window (unfocused), selects the first error and opens it.
+ expect(show).toHaveBeenCalledWith("build", false);
+ expect(useBuildRun.getState().selected).toBe(firstError(messages)!.key);
+ expect(openFile).toHaveBeenCalledWith(
+ "/p/src/A.java",
+ expect.objectContaining({ focus: true, selection: { line: 11, col: 4 } }),
+ );
+ expect(screen.getByRole("document", { name: "Build message" })).toHaveTextContent("cannot find symbol");
expect(getContext()["build.running"]).toBe(false);
const second = startBuild("rebuild");
@@ -167,6 +213,24 @@ describe("build feature", () => {
await second;
});
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Build completed successfully in 3 s" });
+ expect(show).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows a message on single click and navigates on F4", async () => {
+ const messages = [err("/p/src/A.java", 11, "first problem"), warn("/p/src/B.java", 2)];
+ const run = startBuild("build");
+ await act(async () => {});
+ await act(async () => {
+ fake.resolve(result(messages, true));
+ await run;
+ });
+ render(<BuildView />);
+ expect(screen.getByRole("log", { name: "Build output" })).toBeInTheDocument();
+ fireEvent.mouseDown(screen.getByText("deprecated"));
+ expect(openFile).not.toHaveBeenCalled();
+ expect(screen.getByRole("document", { name: "Build message" })).toHaveTextContent("deprecated");
+ fireEvent.keyDown(screen.getByRole("tree"), { key: "F4" });
+ expect(openFile).toHaveBeenCalledWith("/p/src/B.java", expect.objectContaining({ focus: true }));
});
it("builds the module of the given file and can be stopped", async () => {
diff --git a/src/features/build/model.ts b/src/features/build/model.ts
index e12b616ac..79bb341d5 100644
--- a/src/features/build/model.ts
+++ b/src/features/build/model.ts
@@ -35,7 +35,14 @@ const count = (messages: readonly BuildMessage[], s: Severity) => messages.filte
/** Root node of the tree for the current build. */
export function rootNode(title: string, status: BuildStatus, messages: readonly BuildMessage[]): BuildNode {
- return { kind: "root", key: ROOT_KEY, title, status, errors: count(messages, "error"), warnings: count(messages, "warning") };
+ return {
+ kind: "root",
+ key: ROOT_KEY,
+ title,
+ status,
+ errors: count(messages, "error"),
+ warnings: count(messages, "warning"),
+ };
}
/** Children of the root: files with messages (errors first), then messages about the build itself. */
@@ -61,7 +68,9 @@ export function rootChildren(messages: readonly BuildMessage[]): BuildNode[] {
),
}));
const worst = (n: BuildNode) => (n.kind === "file" ? Math.min(...n.messages.map((m) => RANK[m.severity])) : 0);
- files.sort((a, b) => worst(a) - worst(b) || (a.kind === "file" && b.kind === "file" ? a.path.localeCompare(b.path) : 0));
+ files.sort(
+ (a, b) => worst(a) - worst(b) || (a.kind === "file" && b.kind === "file" ? a.path.localeCompare(b.path) : 0),
+ );
return [...files, ...general];
}
@@ -100,3 +109,24 @@ export function finishSummary(result: Pick<BuildResult, "success" | "errors" | "
export function messageFiles(messages: readonly BuildMessage[]): string[] {
return [...new Set(messages.filter((m) => m.path && m.range).map((m) => m.path!))];
}
+
+/** The node with `key` in the tree of `messages` (root excluded). */
+export function findNode(messages: readonly BuildMessage[], key: string): BuildNode | undefined {
+ for (const c of rootChildren(messages)) {
+ if (c.key === key) return c;
+ if (c.kind === "file") {
+ const hit = fileChildren(c).find((m) => m.key === key);
+ if (hit) return hit;
+ }
+ }
+ return undefined;
+}
+
+/** The first error in tree order, selected (and navigated to) when a build fails. */
+export function firstError(messages: readonly BuildMessage[]): Extract<BuildNode, { kind: "message" }> | undefined {
+ for (const c of rootChildren(messages)) {
+ const leaves = c.kind === "file" ? fileChildren(c) : [c];
+ for (const n of leaves) if (n.kind === "message" && n.message.severity === "error") return n;
+ }
+ return undefined;
+}
diff --git a/src/features/build/store.ts b/src/features/build/store.ts
index 1912ee489..f481cc451 100644
--- a/src/features/build/store.ts
+++ b/src/features/build/store.ts
@@ -4,6 +4,9 @@
* as a cancellable background task and a notification when it finishes.
* Compiler messages reach the Problems view and editors as `build`
* diagnostics, published (and cleared on the next build) by the backend.
+ *
+ * Like IDEA, the tool window is not shown when a build starts; a failed build
+ * shows it, selects the first error and opens its location in the editor.
*/
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
@@ -23,7 +26,7 @@ import {
import { useProject } from "@/platform/project";
import { maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
import { removeTask, upsertTask } from "@/workbench/tasks";
-import { appendOutput, finishSummary, messageFiles, type BuildStatus, type ConsoleLine } from "./model";
+import { appendOutput, finishSummary, firstError, messageFiles, type BuildStatus, type ConsoleLine } from "./model";
export const BUILD_TASK_ID = "build:compile";
export const BUILD_RUNNING = "build.running";
@@ -71,6 +74,8 @@ export interface BuildState {
lines: ConsoleLine[];
/** Files with diagnostics from the last build. */
files: string[];
+ /** Key of the selected tree node (a message node shows its detail beside the tree). */
+ selected: string | null;
}
const INITIAL: BuildState = {
@@ -85,6 +90,7 @@ const INITIAL: BuildState = {
messages: [],
lines: [],
files: [],
+ selected: null,
};
export const useBuildRun = create<BuildState>(() => INITIAL);
@@ -124,11 +130,6 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
useBuildRun.setState({ ...INITIAL, request, kind, file, title: taskTitle, status: "running", files: previous });
setContext(BUILD_RUNNING, true);
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: null, done: false, cancel });
- try {
- toolWindowService().show("build", false);
- } catch {
- // No workbench (tests / settings window).
- }
await maybeEditorService()
?.saveAll()
.catch(() => undefined);
@@ -173,8 +174,12 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
title: summary,
key: "build-finished",
sticky: false,
- actions: result.success && !result.warnings ? undefined : [{ label: "Show Build", run: () => toolWindowService().show("build", true) }],
+ actions:
+ result.success && !result.warnings
+ ? undefined
+ : [{ label: "Show Build", run: () => toolWindowService().show("build", true) }],
});
+ if (!result.success) showFailure();
} catch (e) {
clearTimeout(timer);
flush();
@@ -189,7 +194,14 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
lines: appendOutput(s.lines, `${text}\n`, "err"),
messages: [...s.messages, { severity: "error", text, path: null, range: null, code: null }],
}));
- notifications().notify({ group: "run", level: "error", title: "Build failed", body: text, key: "build-finished" });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: "Build failed",
+ body: text,
+ key: "build-finished",
+ });
+ showFailure();
}
} finally {
if (useBuildRun.getState().request === request) useBuildRun.setState({ request: null });
@@ -199,6 +211,35 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
return result;
}
+/** Opens the source of a build message; `focus` moves focus to the editor (otherwise a preview). */
+export function navigateToMessage(m: BuildMessage, focus: boolean) {
+ if (!m.path) return;
+ const start = m.range?.start;
+ void maybeEditorService()
+ ?.openFile(m.path, { selection: start ? { line: start.line, col: start.col } : undefined, focus, preview: !focus })
+ .catch(() => undefined);
+}
+
+export function selectBuildNode(key: string | null) {
+ if (useBuildRun.getState().selected !== key) useBuildRun.setState({ selected: key });
+}
+
+/**
+ * A failed build activates the tool window without focusing it, selects the
+ * first error and navigates to it, as IDEA does by default.
+ */
+function showFailure() {
+ try {
+ toolWindowService().show("build", false);
+ } catch {
+ // No workbench (tests / settings window).
+ }
+ const first = firstError(useBuildRun.getState().messages);
+ if (!first) return;
+ selectBuildNode(first.key);
+ navigateToMessage(first.message, true);
+}
+
export function stopBuild() {
const { request } = useBuildRun.getState();
if (request != null) backend.cancel(request);
diff --git a/src/features/debugger/__tests__/actions.test.ts b/src/features/debugger/__tests__/actions.test.ts
index c323214e9..0fe45b753 100644
--- a/src/features/debugger/__tests__/actions.test.ts
+++ b/src/features/debugger/__tests__/actions.test.ts
@@ -140,7 +140,7 @@ describe("debugger actions (IDEA parity)", () => {
"debug.forceRunToCursor": ["Meta+Alt+F9"],
"debug.showExecutionPoint": ["Alt+F10"],
"debug.setValue": ["F2"],
- "debug.jumpToSource": ["F4"],
+ "debug.jumpToSource": ["F4", "Meta+Down"],
"debug.resetFrame": undefined,
"debug.toggleMethodBreakpoint": undefined,
"debug.toggleFieldWatchpoint": undefined,
@@ -250,4 +250,21 @@ describe("debugger actions (IDEA parity)", () => {
expect(ipc.debugAttachableProcesses).toHaveBeenCalled();
expect(useOverlays.getState().attach?.processes?.map((p) => p.pid)).toEqual([9]);
});
+
+ it("Evaluate prefills the expression at the caret, or the whole selection", async () => {
+ paused();
+ const doc = "total = order.items\nfor i in x:\n pass";
+ editor.current = {
+ ctx: { path: "/p/a.py", language: "python" },
+ view: { state: EditorState.create({ doc, selection: { anchor: doc.indexOf("items") + 2 } }) },
+ };
+ await executeAction("debug.evaluate");
+ expect(useOverlays.getState().evaluate?.expression).toBe("order.items");
+ editor.current = {
+ ctx: { path: "/p/a.py", language: "python" },
+ view: { state: EditorState.create({ doc, selection: { anchor: 0, head: doc.indexOf("\n pass") } }) },
+ };
+ await executeAction("debug.evaluate");
+ expect(useOverlays.getState().evaluate?.expression).toBe("total = order.items\nfor i in x:");
+ });
});
diff --git a/src/features/debugger/__tests__/breakpoints.test.ts b/src/features/debugger/__tests__/breakpoints.test.ts
index 7b5f3413e..9aa2764f6 100644
--- a/src/features/debugger/__tests__/breakpoints.test.ts
+++ b/src/features/debugger/__tests__/breakpoints.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, beforeEach } from "vitest";
import { ChangeSet, EditorState, Text } from "@codemirror/state";
-import { isConditional, makeBreakpoint, mapLines, toBackend, toggleLine } from "../breakpoints/model";
+import { interpolateLog, isConditional, makeBreakpoint, mapLines, toBackend, toggleLine } from "../breakpoints/model";
import {
addBreakpoint,
breakpointsOf,
@@ -85,6 +85,56 @@ describe("breakpoint model", () => {
});
});
+describe("suspend and logging (IDEA's independent options)", () => {
+ it("sends non-suspending breakpoints as logpoints with the hit message and the evaluated template", () => {
+ const list = [
+ makeBreakpoint(1, { suspend: false, logHit: true }),
+ makeBreakpoint(2, { suspend: false, logHit: true, logMessage: "i={i}" }),
+ makeBreakpoint(3, { suspend: false }),
+ makeBreakpoint(4, { logHit: true, logMessage: "i={i}" }),
+ ];
+ expect(toBackend(list, false, "/p/a.py")).toEqual([
+ { line: 1, condition: null, hitCondition: null, logMessage: "Breakpoint reached at a.py:2", enabled: true },
+ {
+ line: 2,
+ condition: null,
+ hitCondition: null,
+ logMessage: "Breakpoint reached at a.py:3\ni={i}",
+ enabled: true,
+ },
+ // Logs nothing and never suspends: no DAP equivalent.
+ { line: 3, condition: null, hitCondition: null, logMessage: null, enabled: false },
+ // Suspending breakpoints log from the UI on stop.
+ { line: 4, condition: null, hitCondition: null, logMessage: null, enabled: true },
+ ]);
+ });
+
+ it("interpolates {expressions} in log templates", async () => {
+ const out = await interpolateLog("a={a} b={ b }", async (e) => {
+ if (e === "b") throw new Error("undefined");
+ return e.toUpperCase();
+ });
+ expect(out).toBe("a=A b=<undefined>");
+ });
+
+ it("migrates stored log messages to non-suspending breakpoints", () => {
+ localStorage.setItem(
+ "openidea.debugger.breakpoints:/old",
+ JSON.stringify({
+ files: {
+ "/x": [
+ { id: "a", line: 1, logMessage: "v={v}" },
+ { id: "b", line: 2 },
+ ],
+ },
+ }),
+ );
+ loadBreakpoints("/old");
+ expect(breakpointsOf("/x")[0]).toMatchObject({ suspend: false, logMessage: "v={v}" });
+ expect(breakpointsOf("/x")[1]!.suspend).toBeUndefined();
+ });
+});
+
describe("breakpoint store", () => {
beforeEach(() => {
localStorage.clear();
diff --git a/src/features/debugger/__tests__/editor.test.ts b/src/features/debugger/__tests__/editor.test.ts
index 91caf776f..58ef03072 100644
--- a/src/features/debugger/__tests__/editor.test.ts
+++ b/src/features/debugger/__tests__/editor.test.ts
@@ -77,7 +77,11 @@ describe("breakpoint click area", () => {
doc: "a\nb",
extensions: [
lineNumbers(),
- gutter({ class: "extra", renderEmptyElements: true, lineMarker: (_v, line) => (line.from > 0 ? new Icon() : null) }),
+ gutter({
+ class: "extra",
+ renderEmptyElements: true,
+ lineMarker: (_v, line) => (line.from > 0 ? new Icon() : null),
+ }),
breakpointGutter(ctx),
],
}),
@@ -93,6 +97,42 @@ describe("breakpoint click area", () => {
});
});
+describe("breakpoint gutter clicks", () => {
+ const click = (view: EditorView, init: MouseEventInit) =>
+ view.dom
+ .querySelector(".cm-lineNumbers .cm-gutterElement:not([style*='hidden'])")!
+ .dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0, ...init }));
+
+ it("⇧-click adds a non-suspending logging breakpoint, ⌥-click a temporary one", () => {
+ localStorage.clear();
+ loadBreakpoints("/proj");
+ const view = makeView("a\nb");
+ click(view, { shiftKey: true });
+ expect(breakpointsOf(ctx.path)[0]).toMatchObject({ line: 0, suspend: false, logHit: true });
+ // Modifier clicks leave an existing breakpoint alone; a plain click removes it.
+ click(view, { altKey: true });
+ click(view, { shiftKey: true });
+ expect(breakpointsOf(ctx.path)).toHaveLength(1);
+ click(view, {});
+ expect(breakpointsOf(ctx.path)).toHaveLength(0);
+ click(view, { altKey: true });
+ expect(breakpointsOf(ctx.path)[0]).toMatchObject({ line: 0, temporary: true });
+ });
+
+ it("middle-click enables / disables an existing breakpoint", () => {
+ localStorage.clear();
+ loadBreakpoints("/proj");
+ const view = makeView("a\nb");
+ click(view, { button: 1 });
+ expect(breakpointsOf(ctx.path)).toHaveLength(0);
+ toggleBreakpoint(ctx.path, 0);
+ click(view, { button: 1 });
+ expect(breakpointsOf(ctx.path)[0]!.enabled).toBe(false);
+ click(view, { button: 1 });
+ expect(breakpointsOf(ctx.path)[0]!.enabled).toBe(true);
+ });
+});
+
describe("execution point", () => {
it("highlights the suspended line and shows inline values", async () => {
const view = makeView("x = 1\ny = x + 1\nprint(y)");
diff --git a/src/features/debugger/__tests__/valueChanges.test.ts b/src/features/debugger/__tests__/valueChanges.test.ts
new file mode 100644
index 000000000..91512d608
--- /dev/null
+++ b/src/features/debugger/__tests__/valueChanges.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { ValueChanges } from "../ui/VariablesView";
+
+describe("changed values (IDEA highlights them after a step)", () => {
+ it("compares with the previous stop in the same scope only", () => {
+ const c = new ValueChanges();
+ c.enter("t1:0", 1);
+ c.record("t1:0", "local:i", "1");
+ c.record("t1:0", "local:s", "'a'");
+ expect(c.changed("t1:0", "local:i", "1")).toBe(false);
+
+ c.enter("t1:0", 2);
+ expect(c.changed("t1:0", "local:i", "2")).toBe(true);
+ expect(c.changed("t1:0", "local:s", "'a'")).toBe(false);
+ // New variables aren't "changed".
+ expect(c.changed("t1:0", "local:n", "0")).toBe(false);
+ // Another frame depth has its own baseline.
+ expect(c.changed("t1:1", "local:i", "2")).toBe(false);
+
+ // Re-rendering in the same stop keeps the baseline.
+ c.record("t1:0", "local:i", "2");
+ c.enter("t1:0", 2);
+ expect(c.changed("t1:0", "local:i", "2")).toBe(true);
+ c.enter("t1:0", 3);
+ expect(c.changed("t1:0", "local:i", "2")).toBe(false);
+ });
+});
diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts
index 24f63a461..b8013ddb7 100644
--- a/src/features/debugger/actions.ts
+++ b/src/features/debugger/actions.ts
@@ -32,6 +32,7 @@ import {
type DebugSession,
} from "./state";
import { focusedDebugView } from "./ui/focusedView";
+import { expressionAt } from "./editor/valueTooltip";
import {
openBreakpointsDialog,
openConfigChooser,
@@ -127,6 +128,16 @@ function cursor(): { path: string; line: number; selection: string } | null {
};
}
+/** Evaluate's initial text, as in IDEA: the selection, else the expression at the caret. */
+function evaluateSeed(): string {
+ const ed = activeEditor();
+ if (!ed) return "";
+ const { state } = ed.view;
+ const sel = state.selection.main;
+ if (!sel.empty) return state.sliceDoc(sel.from, sel.to);
+ return expressionAt(ed.view, sel.head)?.text ?? "";
+}
+
async function startConfig(arg: unknown) {
const root = useProject.getState().project?.root;
if (!root) return;
@@ -243,6 +254,8 @@ export function registerDebugActions(): () => void {
category: "Debug",
icon: "rerun",
when: "debugCanRerun",
+ // ⌘R / Ctrl+F5 rerun only in the Debug tool window (⌘R is Replace in the editor).
+ keyWhen: "activeToolWindow == 'debug'",
run: () => {
const s = activeSession();
if (s) void rerunSession(rootOf(s).id);
@@ -518,10 +531,7 @@ export function registerDebugActions(): () => void {
title: "Evaluate Expression…",
category: "Debug",
when: "debugSessionActive",
- run: () => {
- const c = cursor();
- openEvaluateDialog(c?.selection.split("\n")[0] ?? "");
- },
+ run: () => openEvaluateDialog(evaluateSeed()),
},
{
id: "debug.showToolWindow",
diff --git a/src/features/debugger/breakpoints/model.ts b/src/features/debugger/breakpoints/model.ts
index b5611e258..38a985874 100644
--- a/src/features/debugger/breakpoints/model.ts
+++ b/src/features/debugger/breakpoints/model.ts
@@ -11,6 +11,10 @@ export interface BreakpointEntry {
hitCondition: string | null;
/** Temporary line breakpoint (⌥⇧⌘F8): removed after the first hit. */
temporary?: boolean;
+ /** `false`: the breakpoint never suspends (IDEA's "Suspend" unchecked). Absent means it suspends. */
+ suspend?: boolean;
+ /** Log the IDEA-style "Breakpoint reached at file:line" message on every hit. */
+ logHit?: boolean;
}
export interface BreakpointStatus {
@@ -38,9 +42,48 @@ export function makeBreakpoint(
logMessage: props.logMessage ?? null,
hitCondition: props.hitCondition ?? null,
...(props.temporary ? { temporary: true } : {}),
+ ...(props.suspend === false ? { suspend: false } : {}),
+ ...(props.logHit ? { logHit: true } : {}),
};
}
+export function suspends(b: BreakpointEntry): boolean {
+ return b.suspend !== false;
+}
+
+/** The "Breakpoint hit" message IDEA logs for `path:line` (0-based line). */
+export function hitMessage(path: string, line: number): string {
+ return `Breakpoint reached at ${path.split(/[\\/]/).pop() ?? path}:${line + 1}`;
+}
+
+/** What a hit logs: the hit message and/or the "Evaluate and log" template, one per line. */
+export function logParts(b: BreakpointEntry, path: string): string[] {
+ const parts: string[] = [];
+ if (b.logHit) parts.push(hitMessage(path, b.line));
+ const msg = b.logMessage?.trim();
+ if (msg) parts.push(msg);
+ return parts;
+}
+
+/**
+ * Fills the `{expression}` placeholders of a log template (DAP logpoint syntax)
+ * with `evaluate`; failures render as the error text, like adapters do.
+ */
+export async function interpolateLog(template: string, evaluate: (expr: string) => Promise<string>): Promise<string> {
+ const parts = template.split(/(\{[^{}]+\})/);
+ const out = await Promise.all(
+ parts.map(async (p) => {
+ if (!/^\{[^{}]+\}$/.test(p)) return p;
+ try {
+ return await evaluate(p.slice(1, -1).trim());
+ } catch (e) {
+ return `<${e instanceof Error ? e.message : String(e)}>`;
+ }
+ }),
+ );
+ return out.join("");
+}
+
export function sortByLine<T extends { line: number }>(list: readonly T[]): T[] {
return [...list].sort((a, b) => a.line - b.line);
}
@@ -52,9 +95,9 @@ export function toggleLine(list: readonly BreakpointEntry[], line: number): Brea
: sortByLine([...list, makeBreakpoint(line)]);
}
-/** True when the breakpoint has a condition, hit condition or log message. */
+/** True when the breakpoint has a condition, hit condition or logs something. */
export function isConditional(b: BreakpointEntry): boolean {
- return !!(b.condition?.trim() || b.hitCondition?.trim() || b.logMessage?.trim());
+ return !!(b.condition?.trim() || b.hitCondition?.trim() || b.logMessage?.trim() || b.logHit);
}
/**
@@ -87,15 +130,22 @@ export function mapLines<T extends { line: number }>(
return out;
}
-/** The list sent to the backend; muting disables everything without touching the stored flags. */
-export function toBackend(list: readonly BreakpointEntry[], muted: boolean): Breakpoint[] {
- return list.map((b) => ({
- line: b.line,
- condition: b.condition?.trim() || null,
- hitCondition: b.hitCondition?.trim() || null,
- logMessage: b.logMessage?.trim() || null,
- enabled: b.enabled && !muted,
- }));
+/**
+ * The list sent to the backend; muting disables everything without touching the stored flags.
+ * A non-suspending breakpoint becomes a DAP logpoint; one that logs nothing has no DAP
+ * equivalent and stays disabled. Suspending breakpoints log from the UI when they stop.
+ */
+export function toBackend(list: readonly BreakpointEntry[], muted: boolean, path = ""): Breakpoint[] {
+ return list.map((b) => {
+ const log = suspends(b) ? null : logParts(b, path).join("\n") || null;
+ return {
+ line: b.line,
+ condition: b.condition?.trim() || null,
+ hitCondition: b.hitCondition?.trim() || null,
+ logMessage: log,
+ enabled: b.enabled && !muted && (suspends(b) || log != null),
+ };
+ });
}
export function sameEntries(a: readonly BreakpointEntry[], b: readonly BreakpointEntry[]): boolean {
@@ -109,7 +159,9 @@ export function sameEntries(a: readonly BreakpointEntry[], b: readonly Breakpoin
x.condition === y.condition &&
x.logMessage === y.logMessage &&
x.hitCondition === y.hitCondition &&
- !!x.temporary === !!y.temporary
+ !!x.temporary === !!y.temporary &&
+ suspends(x) === suspends(y) &&
+ !!x.logHit === !!y.logHit
);
});
}
diff --git a/src/features/debugger/breakpoints/store.ts b/src/features/debugger/breakpoints/store.ts
index 932eb960e..60881aef8 100644
--- a/src/features/debugger/breakpoints/store.ts
+++ b/src/features/debugger/breakpoints/store.ts
@@ -59,6 +59,11 @@ function sanitize(raw: unknown): BreakpointEntry[] {
logMessage: typeof b.logMessage === "string" ? b.logMessage : null,
hitCondition: typeof b.hitCondition === "string" ? b.hitCondition : null,
...(b.temporary === true ? { temporary: true } : {}),
+ // Before "Suspend" was its own option, a log message meant "log instead of suspending".
+ ...(b.suspend === false || (b.suspend === undefined && typeof b.logMessage === "string" && b.logMessage.trim())
+ ? { suspend: false }
+ : {}),
+ ...(b.logHit === true ? { logHit: true } : {}),
})),
);
}
@@ -111,7 +116,7 @@ export async function syncFile(path: string) {
list.map((b) => b.id),
);
try {
- const states = await call(commands.debugSetBreakpoints(path, toBackend(list, muted)));
+ const states = await call(commands.debugSetBreakpoints(path, toBackend(list, muted, path)));
applyStates(path, states);
} catch (e) {
console.warn("debugSetBreakpoints failed", e);
diff --git a/src/features/debugger/editor/breakpointGutter.ts b/src/features/debugger/editor/breakpointGutter.ts
index 615e1e62e..c5445fb78 100644
--- a/src/features/debugger/editor/breakpointGutter.ts
+++ b/src/features/debugger/editor/breakpointGutter.ts
@@ -6,10 +6,11 @@
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { Decoration, EditorView, GutterMarker, ViewPlugin, lineNumberMarkers, type ViewUpdate } from "@codemirror/view";
import { editorsFor, mirroredChange, remoteChange, useEditorRegistry, type EditorDocContext } from "@/editor/api";
-import { isConditional, mapLines, type BreakpointEntry, type BreakpointStatus } from "../breakpoints/model";
+import { isConditional, mapLines, suspends, type BreakpointEntry, type BreakpointStatus } from "../breakpoints/model";
import {
addBreakpoint,
breakpointsOf,
+ removeBreakpoint,
setFileBreakpoints,
updateBreakpoint,
useBreakpoints,
@@ -45,7 +46,7 @@ export type BreakpointLook =
export function lookOf(b: BreakpointEntry, status: BreakpointStatus | undefined, muted: boolean, running: boolean) {
if (!b.enabled || muted) return "disabled";
if (running && status && !status.verified) return "unverified";
- if (b.logMessage?.trim()) return "log";
+ if (!suspends(b)) return "log";
if (isConditional(b)) return "conditional";
return running && status?.verified ? "verified" : "normal";
}
@@ -198,29 +199,39 @@ export function breakpointGutter(ctx: EditorDocContext): Extension {
}
}
+ /**
+ * IDEA's gutter clicks: click toggles; on an empty line ⇧-click adds a non-suspending
+ * logging breakpoint and opens its properties, ⌥-click a temporary one. On an existing
+ * breakpoint only a plain (or ⌘/Ctrl) click removes it; middle-click enables/disables.
+ */
onMouseDown = (e: MouseEvent) => {
- if (e.button !== 0 || !inBreakpointArea(e)) return;
+ if ((e.button !== 0 && e.button !== 1) || !inBreakpointArea(e)) return;
const line = lineAtEvent(this.view, e);
if (line == null) return;
- if (!canPlaceBreakpoint(ctx.language) && !breakpointsOf(path).some((b) => b.line === line)) return;
- e.preventDefault();
const special = specialAt(path).find((b) => b.line === line);
- if (special) {
- if (e.altKey) updateSpecial(special.id, { enabled: !special.enabled });
- else removeSpecial(special.id);
+ const bp = breakpointsOf(path).find((b) => b.line === line);
+ if (e.button === 1) {
+ if (!special && !bp) return;
+ e.preventDefault();
+ if (special) updateSpecial(special.id, { enabled: !special.enabled });
+ else if (bp) updateBreakpoint(path, bp.id, { enabled: !bp.enabled });
+ return;
+ }
+ if (!canPlaceBreakpoint(ctx.language) && !bp) return;
+ e.preventDefault();
+ if (special || bp) {
+ if (e.shiftKey || e.altKey) return;
+ if (special) removeSpecial(special.id);
+ else removeBreakpoint(path, bp!.id);
return;
}
if (e.altKey) {
- // ⌥-click enables/disables instead of removing.
- const bp = breakpointsOf(path).find((b) => b.line === line);
- if (bp) updateBreakpoint(path, bp.id, { enabled: !bp.enabled });
- else addBreakpoint(path, line);
+ addBreakpoint(path, line, { temporary: true });
return;
}
if (e.shiftKey) {
- // ⇧-click: logging breakpoint that doesn't suspend.
- const bp = breakpointsOf(path).find((b) => b.line === line) ?? addBreakpoint(path, line);
- openBreakpointPopover(path, bp.id, { x: e.clientX, y: e.clientY }, true);
+ const created = addBreakpoint(path, line, { suspend: false, logHit: true });
+ openBreakpointPopover(path, created.id, { x: e.clientX, y: e.clientY });
return;
}
toggleBreakpointSmart(path, line, ctx.language, this.view.state.doc.toString());
diff --git a/src/features/debugger/editor/editor.module.css b/src/features/debugger/editor/editor.module.css
index 994ab2bb1..b45db337d 100644
--- a/src/features/debugger/editor/editor.module.css
+++ b/src/features/debugger/editor/editor.module.css
@@ -134,7 +134,6 @@
user-select: none;
}
-
/* Data Views › Show value tooltip on mouse hover. */
.valueTooltip {
max-width: 520px;
@@ -144,6 +143,29 @@
white-space: pre-wrap;
word-break: break-word;
}
+.valueTooltipTree {
+ padding: 2px 0;
+ white-space: normal;
+}
+.valueExpand {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 16px;
+ height: 16px;
+ margin-right: 4px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-small);
+ background: transparent;
+ color: var(--fg-muted);
+ vertical-align: -3px;
+ cursor: pointer;
+}
+.valueExpand:hover {
+ background: var(--bg-hover, transparent);
+ color: var(--fg-strong);
+}
.valueName {
color: var(--fg-strong);
}
diff --git a/src/features/debugger/editor/valueTooltip.ts b/src/features/debugger/editor/valueTooltip.ts
index bdec001fc..a8af94adc 100644
--- a/src/features/debugger/editor/valueTooltip.ts
+++ b/src/features/debugger/editor/valueTooltip.ts
@@ -8,6 +8,9 @@ import { hoverTooltip, type EditorView } from "@codemirror/view";
import { workflowSettings } from "@/platform/workflowSettings";
import { activeSession, evaluate } from "../state";
import { inlineValue } from "../values";
+import { tx } from "@/platform/i18n";
+import { iconMarkup } from "@/ui";
+import { mountValueTree } from "../ui/ValueHintTree";
import styles from "./editor.module.css";
const BASE_HOVER = 100;
@@ -42,7 +45,8 @@ export function valueTooltip(): Extension {
if (!session || session.status !== "paused") return null;
const expr = expressionAt(view, pos);
if (!expr) return null;
- if (dbg.valueTooltipDelay > BASE_HOVER) await new Promise((r) => setTimeout(r, dbg.valueTooltipDelay - BASE_HOVER));
+ if (dbg.valueTooltipDelay > BASE_HOVER)
+ await new Promise((r) => setTimeout(r, dbg.valueTooltipDelay - BASE_HOVER));
let value;
try {
value = await evaluate(expr.text, "hover", session);
@@ -56,6 +60,25 @@ export function valueTooltip(): Extension {
create: () => {
const dom = document.createElement("div");
dom.className = styles.valueTooltip!;
+ let tree: { unmount(): void } | null = null;
+ if (value.variablesReference > 0) {
+ // IDEA's value hint: the "+" expands the object into a variables tree in place.
+ const expand = document.createElement("button");
+ expand.type = "button";
+ expand.className = styles.valueExpand!;
+ expand.setAttribute("aria-label", tx("Expand value"));
+ expand.setAttribute("aria-expanded", "false");
+ expand.innerHTML = iconMarkup("chevron-right", 12) ?? "";
+ expand.addEventListener("mousedown", (e) => e.preventDefault());
+ expand.addEventListener("click", () => {
+ if (tree) return;
+ expand.remove();
+ dom.classList.add(styles.valueTooltipTree!);
+ dom.replaceChildren();
+ tree = mountValueTree(dom, expr.text, value, session.id);
+ });
+ dom.append(expand);
+ }
const name = document.createElement("span");
name.className = styles.valueName!;
name.textContent = `${expr.text} = `;
@@ -66,7 +89,7 @@ export function valueTooltip(): Extension {
type.textContent = ` {${value.typeName}}`;
dom.append(type);
}
- return { dom };
+ return { dom, destroy: () => tree?.unmount() };
},
};
},
diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts
index a8dff400a..716836e77 100644
--- a/src/features/debugger/index.ts
+++ b/src/features/debugger/index.ts
@@ -8,7 +8,7 @@ import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { valueTooltip } from "./editor/valueTooltip";
import { registerEditorContribution } from "@/editor/api";
-import { registerOverlay, registerToolWindow } from "@/workbench/contributions";
+import { registerMenuGroup, registerOverlay, registerToolWindow } from "@/workbench/contributions";
import { registerDebugActions } from "./actions";
import { loadBreakpoints } from "./breakpoints/store";
import { loadExceptionBreakpoints } from "./breakpoints/exceptions";
@@ -16,7 +16,7 @@ import { loadSpecialBreakpoints } from "./breakpoints/special";
import { breakpointGutter } from "./editor/breakpointGutter";
import { executionPoint } from "./editor/execution";
import { onHotCodeReplace } from "./hotswap";
-import { handleDebugEvent, loadWatches, publishContext, resetSessions } from "./state";
+import { handleDebugEvent, isLive, loadWatches, publishContext, resetSessions, stopSession, useDebug } from "./state";
import { DebuggerOverlays } from "./ui/Overlays";
export function activate(): () => void {
@@ -38,6 +38,15 @@ export function activate(): () => void {
headerContent: lazyComponent(() => import("./ui/DebugToolWindow").then((m) => m.DebugTabs)),
}),
registerOverlay({ id: "debugger", component: DebuggerOverlays }),
+ // Stop (⌘F2) offers the running debug sessions beside run processes.
+ registerMenuGroup({
+ id: "debugger.stop",
+ menus: ["stopProcess"],
+ items: () =>
+ Object.values(useDebug.getState().sessions)
+ .filter((s) => s.parent == null && isLive(s))
+ .map((s) => ({ label: s.name, verbatim: true, icon: "debug", run: () => void stopSession(s.id) })),
+ }),
registerEditorContribution({
id: "debugger",
order: 60,
diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts
index ce2b83249..f35a50e93 100644
--- a/src/features/debugger/state.ts
+++ b/src/features/debugger/state.ts
@@ -20,7 +20,8 @@ import {
type Variable,
} from "@/platform/ipc";
import { maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
-import { consumeTemporary, refreshStates, resetStatuses } from "./breakpoints/store";
+import { breakpointsOf, consumeTemporary, refreshStates, resetStatuses } from "./breakpoints/store";
+import { interpolateLog, logParts, suspends } from "./breakpoints/model";
import { syncSpecial, useSpecialBreakpoints } from "./breakpoints/special";
import { refreshExceptionFilters } from "./breakpoints/exceptions";
import { missingAdapter } from "./missingAdapter";
@@ -421,12 +422,29 @@ async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean)
patch(id, { frames });
const top = frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0];
if (top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
+ void logSuspendingHit(id, top);
consumeTemporary(top.path, top.line);
}
if (top) selectFrame(id, top.id, reveal);
else updateExecutionPoint();
}
+/**
+ * A suspending breakpoint that also logs: DAP logpoints never suspend, so the
+ * message is evaluated in the stopped frame and printed here instead.
+ */
+async function logSuspendingHit(id: DebugSessionId, frame: StackFrame) {
+ const bp = breakpointsOf(frame.path!).find((b) => b.line === frame.line && b.enabled);
+ if (!bp || !suspends(bp)) return;
+ for (const part of logParts(bp, frame.path!)) {
+ const text = await interpolateLog(part, async (expr) => {
+ const v = await call(commands.debugEvaluateIn(id, frame.id, expr, "repl"));
+ return v.value;
+ });
+ appendConsole(id, "console", `${text}\n`);
+ }
+}
+
async function loadThreads(id: DebugSessionId) {
try {
const threads = await call(commands.debugThreads(id));
diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx
index 791fd6d46..3435e312a 100644
--- a/src/features/debugger/ui/DebugToolWindow.tsx
+++ b/src/features/debugger/ui/DebugToolWindow.tsx
@@ -372,6 +372,8 @@ function VariablesPane({ session }: { session: DebugSession }) {
rows: [],
});
const frame = session.status === "paused" ? session.selectedFrame : null;
+ // Same thread and stack depth across stops: compare like with like.
+ const changeScope = `${session.id}:${session.selectedThread}:${session.frames.findIndex((f) => f.id === frame)}`;
// Scopes + first scope's variables of the selected frame.
useEffect(() => {
@@ -520,6 +522,7 @@ function VariablesPane({ session }: { session: DebugSession }) {
roots={roots}
session={session.id}
generation={stopSeq * 100000 + (frame ?? 0)}
+ changes={{ epoch: stopSeq, scope: changeScope }}
aria-label="Variables"
/>
)}
diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css
index 8f5da2e3d..125ecc169 100644
--- a/src/features/debugger/ui/Overlays.module.css
+++ b/src/features/debugger/ui/Overlays.module.css
@@ -240,3 +240,37 @@
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
}
+
+/* Evaluate: a field that grows with ⇧Enter, like IDEA's expression editor. */
+.evalInputRow {
+ display: flex;
+ align-items: flex-start;
+ gap: 4px;
+}
+.evalInput {
+ flex: 1;
+ min-width: 0;
+ min-height: var(--h-field, 28px);
+ padding: 5px 8px;
+ resize: none;
+ appearance: none;
+ border: 0;
+ border-radius: var(--radius-control, 4px);
+ background: var(--bg-field, var(--bg-button));
+ box-shadow: inset 0 0 0 1px var(--border-button);
+ color: var(--fg-strong);
+ font-family: var(--font-mono);
+ font-size: var(--fs-ui);
+ line-height: 18px;
+ outline: none;
+ -webkit-user-select: text;
+ user-select: text;
+}
+.evalInput:focus {
+ box-shadow:
+ inset 0 0 0 1px var(--focus-ring),
+ 0 0 0 1px var(--focus-ring);
+}
+.evalInput::placeholder {
+ color: var(--fg-faint);
+}
diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx
index 27bc0b61f..a837d02b6 100644
--- a/src/features/debugger/ui/Overlays.tsx
+++ b/src/features/debugger/ui/Overlays.tsx
@@ -1,11 +1,11 @@
/** Debugger popovers and dialogs: breakpoint properties, View Breakpoints, Evaluate, config chooser. */
-import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MutableRefObject } from "react";
import { basename, relativePath, useProject } from "@/platform/project";
import { executeAction } from "@/platform/actions";
import { call, commands, type AttachableProcess, type RunConfig, type Variable } from "@/platform/ipc";
import { maybeEditorService, notifications } from "@/workbench/contributions";
-import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Popup, Toggle, T } from "@/ui";
-import { isConditional, type BreakpointEntry } from "../breakpoints/model";
+import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Menu, Popup, Toggle, T } from "@/ui";
+import { isConditional, suspends, type BreakpointEntry } from "../breakpoints/model";
import {
removeAllBreakpoints,
removeBreakpoint,
@@ -31,6 +31,7 @@ import {
} from "../breakpoints/exceptions";
import { closeBreakpointPopover, useOverlays } from "./popoverStore";
import { VariablesView, type VarRoot } from "./VariablesView";
+import { pushHistory, readHistory } from "./expressionHistory";
import styles from "./Overlays.module.css";
export function DebuggerOverlays() {
@@ -74,33 +75,11 @@ function BreakpointEditor({
at: { x: number; y: number };
focusLog: boolean;
}) {
- const [condition, setCondition] = useState(bp.condition ?? "");
- const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
- const [logEnabled, setLogEnabled] = useState(focusLog || !!bp.logMessage);
- const [logMessage, setLogMessage] = useState(bp.logMessage ?? "");
- const draft = useRef({ condition, hitCondition, logEnabled, logMessage });
- useEffect(() => {
- draft.current = { condition, hitCondition, logEnabled, logMessage };
- });
-
- const commit = () => {
- const d = draft.current;
- updateBreakpoint(path, bp.id, {
- condition: d.condition.trim() || null,
- hitCondition: d.hitCondition.trim() || null,
- logMessage: d.logEnabled ? d.logMessage.trim() || null : null,
- });
- };
+ const commitText = useRef<(() => void) | null>(null);
const close = () => {
- commit();
+ commitText.current?.();
closeBreakpointPopover();
};
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- close();
- }
- };
return (
<Popup open onClose={close} anchor={at} placement="bottom-start" trapFocus aria-label="Breakpoint properties">
@@ -111,50 +90,13 @@ function BreakpointEditor({
{basename(path)}:{bp.line + 1}
</span>
</div>
- <Checkbox
- checked={bp.enabled}
- onChange={(enabled) => updateBreakpoint(path, bp.id, { enabled })}
- label="Enabled"
+ <BreakpointFields
+ path={path}
+ bp={bp}
+ focus={focusLog ? "log" : "condition"}
+ onEnter={close}
+ commitRef={commitText}
/>
- <label className={styles.field}>
- <span className={styles.label}>
- <T>Condition</T>
- </span>
- <Input
- mono
- value={condition}
- onChange={(e) => setCondition(e.target.value)}
- onKeyDown={onKey}
- placeholder="e.g. order.total > 100"
- data-autofocus={focusLog ? undefined : ""}
- aria-label="Condition"
- />
- </label>
- <label className={styles.field}>
- <span className={styles.label}>
- <T>Hit count</T>
- </span>
- <Input
- mono
- value={hitCondition}
- onChange={(e) => setHitCondition(e.target.value)}
- onKeyDown={onKey}
- placeholder="e.g. 5 or >= 3"
- aria-label="Hit count condition"
- />
- </label>
- <Checkbox checked={logEnabled} onChange={setLogEnabled} label="Log message instead of suspending" />
- {logEnabled && (
- <Input
- mono
- value={logMessage}
- onChange={(e) => setLogMessage(e.target.value)}
- onKeyDown={onKey}
- placeholder="Value: {expression}"
- data-autofocus={focusLog ? "" : undefined}
- aria-label="Log message"
- />
- )}
<div className={styles.bpFooter}>
<button
type="button"
@@ -186,6 +128,136 @@ function BreakpointEditor({
);
}
+/**
+ * Line breakpoint properties shared by the gutter popover and the Breakpoints dialog,
+ * like IDEA's: Suspend and the two logging options are independent. Text fields
+ * commit on blur (and through `commitRef` when the popover closes).
+ */
+function BreakpointFields({
+ path,
+ bp,
+ focus,
+ onEnter,
+ commitRef,
+}: {
+ path: string;
+ bp: BreakpointEntry;
+ focus?: "condition" | "log";
+ onEnter?: () => void;
+ commitRef?: MutableRefObject<(() => void) | null>;
+}) {
+ const [condition, setCondition] = useState(bp.condition ?? "");
+ const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
+ const [logEval, setLogEval] = useState(!!bp.logMessage?.trim());
+ const [logMessage, setLogMessage] = useState(bp.logMessage ?? "");
+ const conditionHistory = useMemo(() => readHistory("condition"), []);
+ const historyId = useId();
+ const draft = useRef({ condition, hitCondition, logEval, logMessage });
+ useEffect(() => {
+ draft.current = { condition, hitCondition, logEval, logMessage };
+ });
+ const commitText = () => {
+ const d = draft.current;
+ const cond = d.condition.trim() || null;
+ if (cond) pushHistory("condition", cond);
+ updateBreakpoint(path, bp.id, {
+ condition: cond,
+ hitCondition: d.hitCondition.trim() || null,
+ logMessage: d.logEval ? d.logMessage.trim() || null : null,
+ });
+ };
+ useEffect(() => {
+ if (!commitRef) return;
+ commitRef.current = commitText;
+ return () => {
+ commitRef.current = null;
+ };
+ });
+ const onKey = (e: KeyboardEvent) => {
+ if (onEnter && e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ onEnter();
+ }
+ };
+ return (
+ <>
+ <Checkbox
+ checked={bp.enabled}
+ onChange={(enabled) => updateBreakpoint(path, bp.id, { enabled })}
+ label="Enabled"
+ />
+ <Checkbox
+ checked={suspends(bp)}
+ onChange={(on) => updateBreakpoint(path, bp.id, { suspend: on ? undefined : false })}
+ label="Suspend"
+ />
+ <label className={styles.field}>
+ <span className={styles.label}>
+ <T>Condition</T>
+ </span>
+ <Input
+ mono
+ value={condition}
+ onChange={(e) => setCondition(e.target.value)}
+ onBlur={commitText}
+ onKeyDown={onKey}
+ list={conditionHistory.length ? historyId : undefined}
+ placeholder="e.g. order.total > 100"
+ data-autofocus={focus === "condition" ? "" : undefined}
+ aria-label="Condition"
+ />
+ {conditionHistory.length > 0 && (
+ <datalist id={historyId}>
+ {conditionHistory.map((h) => (
+ <option key={h} value={h} />
+ ))}
+ </datalist>
+ )}
+ </label>
+ <label className={styles.field}>
+ <span className={styles.label}>
+ <T>Hit count</T>
+ </span>
+ <Input
+ mono
+ value={hitCondition}
+ onChange={(e) => setHitCondition(e.target.value)}
+ onBlur={commitText}
+ onKeyDown={onKey}
+ placeholder="e.g. 5 or >= 3"
+ aria-label="Hit count condition"
+ />
+ </label>
+ <Checkbox
+ checked={!!bp.logHit}
+ onChange={(on) => updateBreakpoint(path, bp.id, { logHit: on || undefined })}
+ label={'"Breakpoint hit" message'}
+ />
+ <Checkbox
+ checked={logEval}
+ onChange={(on) => {
+ setLogEval(on);
+ draft.current = { ...draft.current, logEval: on };
+ commitText();
+ }}
+ label="Evaluate and log"
+ />
+ {logEval && (
+ <Input
+ mono
+ value={logMessage}
+ onChange={(e) => setLogMessage(e.target.value)}
+ onBlur={commitText}
+ onKeyDown={onKey}
+ placeholder="Value: {expression}"
+ data-autofocus={focus === "log" ? "" : undefined}
+ aria-label="Evaluate and log"
+ />
+ )}
+ </>
+ );
+}
+
function specialTitle(b: SpecialBreakpoint): string {
return b.kind === "method" ? b.name || "(no method)" : b.label;
}
@@ -411,7 +483,7 @@ function BreakpointsDialog() {
{basename(r.path)}:{r.bp.line + 1}
</span>
<span className={styles.bpDir}>{relativePath(root, r.path)}</span>
- {isConditional(r.bp) && <span className={styles.bpCond}>{r.bp.logMessage ? "log" : "if"}</span>}
+ {isConditional(r.bp) && <span className={styles.bpCond}>{suspends(r.bp) ? "if" : "log"}</span>}
{r.bp.temporary && <span className={styles.bpCond}>temp</span>}
</div>
);
@@ -476,10 +548,6 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
const { path, bp } = row;
const st = useBreakpoints((s) => s.status[bp.id]);
- const [condition, setCondition] = useState(bp.condition ?? "");
- const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
- const [logMessage, setLogMessage] = useState(bp.logMessage ?? "");
- const commit = (patch: Partial<BreakpointEntry>) => updateBreakpoint(path, bp.id, patch);
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
@@ -495,45 +563,12 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
</Button>
</div>
{st && <div className={styles.statusLine}>{st.verified ? "Verified" : (st.message ?? "Not verified")}</div>}
- <Checkbox checked={bp.enabled} onChange={(enabled) => commit({ enabled })} label="Enabled" />
- <Checkbox checked={!!bp.temporary} onChange={(temporary) => commit({ temporary })} label="Remove once hit" />
- <label className={styles.field}>
- <span className={styles.label}>
- <T>Condition</T>
- </span>
- <Input
- mono
- value={condition}
- onChange={(e) => setCondition(e.target.value)}
- onBlur={() => commit({ condition: condition.trim() || null })}
- aria-label="Condition"
- />
- </label>
- <label className={styles.field}>
- <span className={styles.label}>
- <T>Hit count</T>
- </span>
- <Input
- mono
- value={hitCondition}
- onChange={(e) => setHitCondition(e.target.value)}
- onBlur={() => commit({ hitCondition: hitCondition.trim() || null })}
- aria-label="Hit count condition"
- />
- </label>
- <label className={styles.field}>
- <span className={styles.label}>
- <T>Log message</T>
- </span>
- <Input
- mono
- value={logMessage}
- onChange={(e) => setLogMessage(e.target.value)}
- onBlur={() => commit({ logMessage: logMessage.trim() || null })}
- placeholder="Suspends when empty"
- aria-label="Log message"
- />
- </label>
+ <BreakpointFields path={path} bp={bp} />
+ <Checkbox
+ checked={!!bp.temporary}
+ onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
+ label="Remove once hit"
+ />
</div>
);
}
@@ -635,15 +670,29 @@ function EvaluateDialog() {
return <EvaluateDialogInner initial={state.expression} />;
}
+/**
+ * IDEA's Evaluate dialog: Enter evaluates, ⇧Enter adds a line (the field grows),
+ * ⇧⌘Enter / Ctrl+Shift+Enter adds a watch; ↑ on the first line / ↓ on the last walk
+ * the per-project history, which the history button also lists.
+ */
function EvaluateDialogInner({ initial }: { initial: string }) {
const [expression, setExpression] = useState(initial);
const [result, setResult] = useState<VarRoot | null>(null);
+ const [history, setHistory] = useState(() => readHistory("evaluate"));
+ const [historyMenu, setHistoryMenu] = useState(false);
+ const historyPos = useRef(-1);
+ const historyButton = useRef<HTMLSpanElement>(null);
+ const field = useRef<HTMLTextAreaElement>(null);
const session = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
const paused = session?.status === "paused";
const close = () => useOverlays.setState({ evaluate: null });
+ const lines = Math.min(10, expression.split("\n").length);
const run = async () => {
const e = expression.trim();
if (!e) return;
+ pushHistory("evaluate", e);
+ setHistory(readHistory("evaluate"));
+ historyPos.current = -1;
try {
const v: Variable = await evaluate(e, "repl", session ?? null);
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: v, error: null });
@@ -651,6 +700,36 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: null, error: errorText(err) });
}
};
+ const recall = (text: string) => {
+ setExpression(text);
+ requestAnimationFrame(() => {
+ const el = field.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(text.length, text.length);
+ });
+ };
+ const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.nativeEvent.isComposing) return;
+ const el = e.currentTarget;
+ if (e.key === "Enter" && e.shiftKey && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ addWatch(expression);
+ } else if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
+ e.preventDefault();
+ if (paused) void run();
+ } else if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !e.shiftKey && !e.altKey && !e.metaKey) {
+ const before = el.value.slice(0, el.selectionStart);
+ const after = el.value.slice(el.selectionEnd);
+ const up = e.key === "ArrowUp";
+ if (up ? before.includes("\n") : after.includes("\n")) return;
+ const next = historyPos.current + (up ? 1 : -1);
+ if (next < -1 || next >= history.length) return;
+ e.preventDefault();
+ historyPos.current = next;
+ recall(next < 0 ? "" : history[next]!);
+ }
+ };
return (
<Dialog
open
@@ -676,25 +755,49 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
]}
>
<div className={styles.evalBody}>
- <label className={styles.field}>
+ <div className={styles.field}>
<span className={styles.label}>
<T>Expression</T>
</span>
- <Input
- mono
- value={expression}
- onChange={(e) => setExpression(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- void run();
- }
- }}
- data-autofocus=""
- aria-label="Expression"
- placeholder={paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate"}
+ <div className={styles.evalInputRow}>
+ <textarea
+ ref={field}
+ className={styles.evalInput}
+ rows={lines}
+ value={expression}
+ onChange={(e) => {
+ setExpression(e.target.value);
+ historyPos.current = -1;
+ }}
+ onKeyDown={onKeyDown}
+ onFocus={(e) => e.currentTarget.select()}
+ spellCheck={false}
+ autoComplete="off"
+ data-autofocus=""
+ aria-label="Expression"
+ placeholder={paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate"}
+ />
+ <span ref={historyButton}>
+ <IconButton
+ icon="history"
+ title="History"
+ size="small"
+ disabled={!history.length}
+ onClick={() => setHistoryMenu(true)}
+ />
+ </span>
+ </div>
+ <Menu
+ open={historyMenu}
+ onClose={() => setHistoryMenu(false)}
+ anchor={historyButton}
+ placement="bottom-end"
+ aria-label="Expression history"
+ items={history
+ .slice(0, 20)
+ .map((h) => ({ label: h.replace(/\s+/g, " "), verbatim: true, run: () => recall(h) }))}
/>
- </label>
+ </div>
<div className={styles.evalResult}>
{result ? (
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
diff --git a/src/features/debugger/ui/ValueHintTree.tsx b/src/features/debugger/ui/ValueHintTree.tsx
new file mode 100644
index 000000000..b0c631178
--- /dev/null
+++ b/src/features/debugger/ui/ValueHintTree.tsx
@@ -0,0 +1,21 @@
+/** The expanded value hint: an object under the mouse as a variables tree (as IDEA). */
+import { createRoot } from "react-dom/client";
+import type { DebugSessionId, Variable } from "@/platform/ipc";
+import { VariablesView } from "./VariablesView";
+import styles from "./VariablesView.module.css";
+
+export function mountValueTree(host: HTMLElement, expression: string, variable: Variable, session: DebugSessionId) {
+ const root = createRoot(host);
+ root.render(
+ <div className={styles.hint}>
+ <VariablesView
+ roots={[{ key: "hint", kind: "eval", name: expression, variable, error: null }]}
+ session={session}
+ defaultExpanded={["hint"]}
+ autoFocus
+ aria-label={expression}
+ />
+ </div>,
+ );
+ return { unmount: () => queueMicrotask(() => root.unmount()) };
+}
diff --git a/src/features/debugger/ui/VariablesView.module.css b/src/features/debugger/ui/VariablesView.module.css
index 4c6fd4516..86d699f4f 100644
--- a/src/features/debugger/ui/VariablesView.module.css
+++ b/src/features/debugger/ui/VariablesView.module.css
@@ -79,7 +79,6 @@
font-size: var(--fs-ui);
}
-
.editInput {
flex: 1;
min-width: 80px;
@@ -96,3 +95,16 @@
.editInvalid {
border-color: var(--danger);
}
+
+/* Changed since the previous stop. */
+.name.changed {
+ color: var(--debug-changed, var(--link));
+}
+
+/* Expanded value hint in the editor. */
+.hint {
+ display: flex;
+ flex-direction: column;
+ width: 460px;
+ height: 260px;
+}
diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx
index 7aec2f40c..48da7f4b7 100644
--- a/src/features/debugger/ui/VariablesView.tsx
+++ b/src/features/debugger/ui/VariablesView.tsx
@@ -95,19 +95,70 @@ function message(key: string, text: string): VarNode {
};
}
+/**
+ * Values changed since the previous stop (IDEA paints them in a
+ * distinct colour). Values are remembered per
+ * `scope` (e.g. thread + frame depth) so switching frames doesn't compare unrelated locals.
+ */
+export class ValueChanges {
+ private scopes = new Map<string, { epoch: number; prev: Map<string, string>; cur: Map<string, string> }>();
+
+ /** Starts `epoch` for `scope`: the values seen in the earlier epoch become the baseline. */
+ enter(scope: string, epoch: number) {
+ const s = this.scopes.get(scope);
+ if (!s) {
+ if (this.scopes.size >= 64) this.scopes.delete(this.scopes.keys().next().value!);
+ this.scopes.set(scope, { epoch, prev: new Map(), cur: new Map() });
+ } else if (s.epoch !== epoch) {
+ s.prev = s.cur.size ? s.cur : s.prev;
+ s.cur = new Map();
+ s.epoch = epoch;
+ }
+ }
+
+ record(scope: string, key: string, value: string) {
+ this.scopes.get(scope)?.cur.set(key, value);
+ }
+
+ changed(scope: string, key: string, value: string): boolean {
+ const prev = this.scopes.get(scope)?.prev.get(key);
+ return prev !== undefined && prev !== value;
+ }
+}
+
+const tracksChanges = (n: VarNode) => (n.kind === "var" || n.kind === "watch") && !n.error;
+
+/** Shared by every view: the variables pane remounts while the program runs between stops. */
+const valueChanges = new ValueChanges();
+
export interface VariablesViewProps {
roots: VarRoot[];
session: DebugSessionId | null;
/** Changing it drops loaded children (new stop); expansion is kept and re-loaded. */
generation?: number;
+ /** Highlight values changed since the previous `epoch` (stop) within the same `scope`. */
+ changes?: { epoch: number; scope: string };
+ /** Keys of nodes expanded initially (e.g. the root of a value hint). */
+ defaultExpanded?: readonly string[];
+ /** Keyboard focus goes to the tree on mount. */
+ autoFocus?: boolean;
"aria-label"?: string;
className?: string;
}
-export function VariablesView({ roots, session, generation = 0, className, ...aria }: VariablesViewProps) {
+export function VariablesView({
+ roots,
+ session,
+ generation = 0,
+ changes,
+ defaultExpanded,
+ autoFocus,
+ className,
+ ...aria
+}: VariablesViewProps) {
const [cache, setCache] = useState<{ gen: number; map: Map<string, VarNode[]> }>({ gen: generation, map: new Map() });
const children = cache.gen === generation ? cache.map : null;
- const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set(defaultExpanded));
const loading = useRef(new Set<string>());
const tree = useRef<TreeHandle>(null);
@@ -124,6 +175,19 @@ export function VariablesView({ roots, session, generation = 0, className, ...ar
return m;
}, [nodes, children]);
+ if (changes) valueChanges.enter(changes.scope, changes.epoch);
+ const changeScope = changes?.scope;
+ useEffect(() => {
+ if (changeScope == null) return;
+ for (const n of byKey.values()) if (tracksChanges(n)) valueChanges.record(changeScope, n.key, n.value);
+ }, [byKey, changeScope]);
+ const isChanged = (n: VarNode) =>
+ !!changes && tracksChanges(n) && valueChanges.changed(changes.scope, n.key, n.value);
+
+ useEffect(() => {
+ if (autoFocus) tree.current?.focus();
+ }, [autoFocus]);
+
const load = useCallback(
async (node: VarNode) => {
if (session == null || node.reference <= 0) return;
@@ -206,7 +270,11 @@ export function VariablesView({ roots, session, generation = 0, className, ...ar
if (!node || node.kind === "message") return;
e.preventDefault();
const items: MenuItem[] = [];
- if (editable(node)) items.push({ label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) }, { kind: "separator" });
+ if (editable(node))
+ items.push(
+ { label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) },
+ { kind: "separator" },
+ );
if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) });
if (node.kind !== "scope") {
items.push({ label: "Copy Value", icon: "copy", run: () => void navigator.clipboard?.writeText(node.value) });
@@ -219,7 +287,10 @@ export function VariablesView({ roots, session, generation = 0, className, ...ar
icon: "breakpoint-field",
run: () => void addWatchpointFor(session!, node),
});
- items.push({ kind: "separator" }, { label: "Jump to Source", shortcut: "F4", run: () => void jumpToDeclaration(node) });
+ items.push(
+ { kind: "separator" },
+ { label: "Jump to Source", shortcut: "F4", run: () => void jumpToDeclaration(node) },
+ );
}
if (items.length) showContextMenu(e, items);
};
@@ -271,7 +342,7 @@ export function VariablesView({ roots, session, generation = 0, className, ...ar
}}
/>
) : (
- <VarRow node={n} />
+ <VarRow node={n} changed={isChanged(n)} />
)
}
/>
@@ -337,7 +408,7 @@ function nodeIcon(node: VarNode): string {
return node.depth0 ? "variable" : "field";
}
-function VarRow({ node }: { node: VarNode }) {
+function VarRow({ node, changed }: { node: VarNode; changed: boolean }) {
if (node.kind === "message") return <span className={styles.message}>{node.name}</span>;
if (node.kind === "scope")
return (
@@ -350,7 +421,9 @@ function VarRow({ node }: { node: VarNode }) {
return (
<span className={styles.row}>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
- <span className={clsx(styles.name, node.kind === "var" && styles.varName)}>{node.name}</span>
+ <span className={clsx(styles.name, node.kind === "var" && styles.varName, changed && styles.changed)}>
+ {node.name}
+ </span>
<span className={styles.eq}>=</span>
{node.error ? (
<span className={styles.error}>{node.error}</span>
diff --git a/src/features/debugger/ui/expressionHistory.ts b/src/features/debugger/ui/expressionHistory.ts
new file mode 100644
index 000000000..b6cd023e1
--- /dev/null
+++ b/src/features/debugger/ui/expressionHistory.ts
@@ -0,0 +1,38 @@
+/**
+ * Per-project history of expressions typed into the debugger (breakpoint
+ * conditions, Evaluate), most recent first, as IDEA keeps them.
+ */
+import { useProject } from "@/platform/project";
+
+export type HistoryKind = "condition" | "evaluate";
+
+const PREFIX = "openidea.debugger.history.";
+const MAX = 50;
+
+function key(kind: HistoryKind): string | null {
+ const root = useProject.getState().project?.root;
+ return root ? `${PREFIX}${kind}:${root}` : null;
+}
+
+export function readHistory(kind: HistoryKind): string[] {
+ const k = key(kind);
+ if (!k) return [];
+ try {
+ const raw = JSON.parse(localStorage.getItem(k) ?? "[]") as unknown;
+ return Array.isArray(raw) ? raw.filter((e): e is string => typeof e === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function pushHistory(kind: HistoryKind, expression: string) {
+ const e = expression.trim();
+ const k = key(kind);
+ if (!e || !k) return;
+ const next = [e, ...readHistory(kind).filter((h) => h !== e)].slice(0, MAX);
+ try {
+ localStorage.setItem(k, JSON.stringify(next));
+ } catch {
+ // Storage unavailable: no history.
+ }
+}
diff --git a/src/features/project-tree/FileRefactorDialogs.tsx b/src/features/project-tree/FileRefactorDialogs.tsx
index 0971a702b..a05457274 100644
--- a/src/features/project-tree/FileRefactorDialogs.tsx
+++ b/src/features/project-tree/FileRefactorDialogs.tsx
@@ -1,13 +1,23 @@
/**
- * IDEA's Rename (⇧F6) and Move (F6, drag & drop) dialogs for files and
- * folders, with "Search for references" and "Search in comments and strings".
+ * IDEA's Rename (⇧F6), Move (F6, drag & drop, cut & paste) and Copy (copy &
+ * paste, ⌥ drag) dialogs for files and folders, with "Search for references"
+ * and "Search in comments and strings".
*/
import { useEffect, useRef, useState } from "react";
import { create } from "zustand";
import type { FileMove } from "@/bindings";
import { Checkbox, Dialog, Input, Spinner, T } from "@/ui";
import { runFileRefactoring, type FileRefactorOptions } from "./fileRefactor";
-import { isSameOrInside, joinPath, nameOf, parentOf, relativeTo, splitExtension, validateName } from "./paths";
+import {
+ isSameOrInside,
+ joinPath,
+ nameOf,
+ parentOf,
+ relativeTo,
+ splitExtension,
+ uniqueName,
+ validateName,
+} from "./paths";
import { useProjectTree } from "./store";
import styles from "./FileRefactor.module.css";
@@ -28,6 +38,16 @@ export type FileRefactorRequest =
dir?: boolean;
/** Called after the files moved (tree refresh / reveal). */
onDone?: (moves: FileMove[]) => void;
+ }
+ | {
+ kind: "copy";
+ paths: string[];
+ /** Initial target folder. */
+ target: string;
+ /** The single copied item is a folder. */
+ dir?: boolean;
+ /** Copies into `target` (`name`: the single item's new name); false keeps the dialog open. */
+ copy: (target: string, name: string | null, openInEditor: boolean) => Promise<boolean>;
};
const useRequest = create<{ request: (FileRefactorRequest & { seq: number }) | null }>(() => ({ request: null }));
@@ -299,14 +319,133 @@ function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
);
}
-/** Overlay contribution rendering the open Rename / Move dialog. */
+const COPY_OPEN_KEY = "openidea.projectTree.copyOpenInEditor";
+
+function CopyDialog({ request }: { request: Extract<FileRefactorRequest, { kind: "copy" }> }) {
+ const root = useProjectTree((s) => s.root) ?? "";
+ const single = request.paths.length === 1 ? request.paths[0]! : null;
+ const [target, setTarget] = useState(request.target);
+ const dest = resolveTarget(target, root);
+ const listing = useProjectTree((s) => s.listings.get(dest));
+ const [name, setName] = useState(() => {
+ const own = single ? nameOf(single) : "";
+ const taken = new Set((useProjectTree.getState().listings.get(request.target) ?? []).map((e) => fold(e.name)));
+ return single ? uniqueName(own, (n) => taken.has(fold(n)), !!request.dir) : "";
+ });
+ const [openInEditor, setOpenInEditor] = useState(() => {
+ try {
+ return localStorage.getItem(COPY_OPEN_KEY) === "true";
+ } catch {
+ return false;
+ }
+ });
+ const [busy, setBusy] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ const el = input.current;
+ if (!el) return;
+ el.focus();
+ const stem = request.dir ? name : splitExtension(name)[0];
+ el.setSelectionRange(0, stem.length || name.length);
+ // Only on open.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ const siblings = (listing ?? []).map((e) => e.name);
+ const error = request.paths.some((p) => isSameOrInside(dest, p) && dest !== parentOf(p))
+ ? "Cannot copy a folder into itself"
+ : single
+ ? validateName(name, { siblings, caseInsensitive }).error
+ : null;
+ const subject = single
+ ? `Copy ${request.dir ? "directory" : "file"} '${nameOf(single)}'`
+ : `Copy ${request.paths.length} items`;
+ const submit = async () => {
+ if (busy || error) return;
+ try {
+ localStorage.setItem(COPY_OPEN_KEY, String(openInEditor));
+ } catch {
+ /* storage unavailable */
+ }
+ setBusy(true);
+ const ok = await request.copy(dest, single ? name : null, openInEditor && !request.dir);
+ setBusy(false);
+ if (ok) closeFileRefactorDialog();
+ };
+ return (
+ <Dialog
+ open
+ title="Copy"
+ onClose={closeFileRefactorDialog}
+ width={520}
+ buttons={[
+ { label: "OK", role: "default", disabled: busy || !!error, onClick: () => void submit() },
+ { label: "Cancel", role: "cancel" },
+ ]}
+ >
+ <form
+ className={styles.form}
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submit();
+ }}
+ >
+ <div className={styles.subject}>{subject}</div>
+ {single && (
+ <>
+ <label className={styles.fieldLabel} htmlFor="file-copy-name">
+ <T>New name:</T>
+ </label>
+ <Input
+ id="file-copy-name"
+ ref={input}
+ value={name}
+ disabled={busy}
+ invalid={!!error}
+ aria-label="New name"
+ onChange={(e) => setName(e.target.value)}
+ />
+ </>
+ )}
+ <label className={styles.fieldLabel} htmlFor="file-copy-target">
+ <T>To directory:</T>
+ </label>
+ <Input
+ id="file-copy-target"
+ autoFocus={!single}
+ mono
+ value={target}
+ disabled={busy}
+ aria-label="Target directory"
+ onChange={(e) => setTarget(e.target.value)}
+ />
+ <div className={styles.hint}>{relativeTo(root, dest) || (dest === root ? "Project root" : dest)}</div>
+ {error && (
+ <div className={styles.error} role="alert">
+ {error}
+ </div>
+ )}
+ {single && !request.dir && (
+ <div className={styles.options}>
+ <Checkbox label="Open copy in editor" checked={openInEditor} disabled={busy} onChange={setOpenInEditor} />
+ </div>
+ )}
+ </form>
+ </Dialog>
+ );
+}
+
+const fold = (n: string) => (caseInsensitive ? n.toLowerCase() : n);
+
+/** Overlay contribution rendering the open Rename / Move / Copy dialog. */
export function FileRefactorDialogHost() {
const request = useRequest((s) => s.request);
if (!request) return null;
return request.kind === "rename" ? (
<RenameDialog key={request.seq} request={request} />
- ) : (
+ ) : request.kind === "move" ? (
<MoveDialog key={request.seq} request={request} />
+ ) : (
+ <CopyDialog key={request.seq} request={request} />
);
}
diff --git a/src/features/project-tree/ProjectView.test.tsx b/src/features/project-tree/ProjectView.test.tsx
index 1d771651d..4e6b11980 100644
--- a/src/features/project-tree/ProjectView.test.tsx
+++ b/src/features/project-tree/ProjectView.test.tsx
@@ -9,6 +9,7 @@ import { MessagesHost } from "@/workbench/messages";
import { FileRefactorDialogHost } from "./FileRefactorDialogs";
import { setRefactorBackendForTests } from "./fileRefactor";
import { ProjectView } from "./ProjectView";
+import { beginNew } from "./operations";
import { initProjectTree, setViewOption, useProjectTree } from "./store";
const ROOT = "/w/acme";
@@ -70,18 +71,29 @@ describe("ProjectView", () => {
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "Util.kt", "README.md"]));
});
- it("opens files on double click and previews on single click", async () => {
+ it("opens files on double click and previews on single click only when enabled", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const content = row("README.md").querySelector("[data-project-path]")!;
fireEvent.click(content, { detail: 1 });
- expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
+ expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
- act(() => setViewOption("previewTab", false));
- openFile.mockClear();
+ act(() => setViewOption("previewTab", true));
fireEvent.click(content, { detail: 1 });
- expect(openFile).not.toHaveBeenCalled();
+ expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
+ act(() => setViewOption("previewTab", false));
+ });
+
+ it("cancels a new file when its name field loses focus", async () => {
+ const { rows } = setup();
+ await waitFor(() => expect(rows()).toContain("README.md"));
+ await act(() => beginNew("file", ROOT));
+ const input = await screen.findByRole("textbox", { name: "New file name" });
+ fireEvent.change(input, { target: { value: "Notes.md" } });
+ await act(async () => void fireEvent.blur(input));
+ expect(useProjectTree.getState().editing).toBeNull();
+ expect(fs.nodes.has("/w/acme/Notes.md")).toBe(false);
});
it("publishes the focus context key", async () => {
diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx
index 26c2875a4..c2ab0b96c 100644
--- a/src/features/project-tree/ProjectView.tsx
+++ b/src/features/project-tree/ProjectView.tsx
@@ -177,8 +177,10 @@ function InlineEditor({ editing, initial, onDone }: { editing: Editing; initial:
}
}}
onBlur={() => {
+ // Like IDEA's New File popup, clicking elsewhere cancels creating; a rename commits.
+ if (editing.kind === "new") return void finish(false);
const valid = !checkEditingName(value).error && !!value.trim();
- void finish(valid && (editing.kind === "new" || value !== initial));
+ void finish(valid && value !== initial);
}}
/>
{showError && (
diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts
index ecb78ba3a..d6242a1ce 100644
--- a/src/features/project-tree/actions.ts
+++ b/src/features/project-tree/actions.ts
@@ -211,6 +211,8 @@ export function registerProjectActions(): () => void {
category: "Project View",
icon: "trash",
when: FOCUS,
+ // Not while speed search (a popup) owns ⌫.
+ keyWhen: "!popupOpen",
keywords: ["remove", "trash"],
run: ({ arg }) => deleteSelection(nodesFrom(arg)),
},
@@ -324,6 +326,7 @@ export function registerProjectActions(): () => void {
category: "Project View",
icon: "refresh",
when: OPEN,
+ keyWhen: FOCUS,
keywords: ["synchronize", "refresh"],
run: ({ arg }) => reloadFromDisk(nodesFrom(arg)),
},
@@ -333,6 +336,7 @@ export function registerProjectActions(): () => void {
category: "Project View",
icon: "expand-all",
when: OPEN,
+ keyWhen: FOCUS,
run: () => {
const lead = leadNode();
return expandAll(lead?.dir && !lead.root ? lead.path : undefined);
@@ -344,6 +348,7 @@ export function registerProjectActions(): () => void {
category: "Project View",
icon: "collapse-all",
when: OPEN,
+ keyWhen: FOCUS,
run: () => {
collapseAll();
treeHandle.current?.focus();
diff --git a/src/features/project-tree/extraRoots.test.ts b/src/features/project-tree/extraRoots.test.ts
index d8a03e819..402461ed5 100644
--- a/src/features/project-tree/extraRoots.test.ts
+++ b/src/features/project-tree/extraRoots.test.ts
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FileEntry } from "@/bindings";
import { registerProjectViewRoot } from "@/workbench/contributions";
-vi.mock("@/workbench/messages", () => ({ confirm: async () => true }));
+vi.mock("@/workbench/messages", () => ({
+ confirm: async () => true,
+ confirmChecked: async () => ({ checked: false }),
+ ask: async () => ({ button: "cancel", checked: false }),
+}));
vi.mock("@/editor/refactor", () => ({
fileUsages: async () => ({ status: "ok", usages: [] }),
askUsagesDetected: async () => "cancel",
diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts
index 872c5cda2..c2d2f6cd0 100644
--- a/src/features/project-tree/operations.ts
+++ b/src/features/project-tree/operations.ts
@@ -6,7 +6,7 @@ import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
import { maybeEditorService, notifications } from "@/workbench/contributions";
-import { confirm } from "@/workbench/messages";
+import { ask, confirmChecked } from "@/workbench/messages";
import { runFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { projectFs } from "./fs";
@@ -165,7 +165,7 @@ export function openMoveDialog(nodes: ProjectNode[] = selectedNodes(), target?:
openMoveDialogFor(paths, target, paths.length === 1 && movable.some((n) => n.path === paths[0] && n.dir));
}
-function openMoveDialogFor(paths: string[], target?: string, dir?: boolean) {
+function openMoveDialogFor(paths: string[], target?: string, dir?: boolean, done?: () => void) {
if (!paths.length) return;
openFileRefactorDialog({
kind: "move",
@@ -173,6 +173,7 @@ function openMoveDialogFor(paths: string[], target?: string, dir?: boolean) {
dir,
target: target ?? parentOf(paths[0]!),
onDone: (moves) => {
+ done?.();
void afterMove(moves);
if (rememberedOptions("move").openInEditor)
for (const m of moves) if (!get().listings.has(m.to)) void openFile(m.to, { focus: false });
@@ -306,6 +307,16 @@ export function selectionAfterDelete(rows: readonly ProjectNode[], deleted: read
/** Safe delete searches at most this many files, for at most this long. */
const SAFE_DELETE_MAX_FILES = 20;
const SAFE_DELETE_TIMEOUT_MS = 15_000;
+const SAFE_DELETE_PROGRESS_DELAY_MS = 400;
+const SAFE_DELETE_KEY = "openidea.projectTree.safeDelete";
+
+function safeDeleteEnabled(): boolean {
+ try {
+ return localStorage.getItem(SAFE_DELETE_KEY) !== "false";
+ } catch {
+ return true;
+ }
+}
/**
* IDEA's safe delete for files: usages of their top-level symbols from other
@@ -316,15 +327,35 @@ export async function safeToDelete(files: string[]): Promise<boolean> {
if (files.length > SAFE_DELETE_MAX_FILES) return true;
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), SAFE_DELETE_TIMEOUT_MS);
+ // A search that takes a while shows progress the user can skip (delete anyway) or cancel.
+ const progress = new AbortController();
+ const user: { choice: "skip" | "cancel" | null } = { choice: null };
+ const shown = setTimeout(() => {
+ void ask({
+ title: "Delete",
+ body: "Looking for usages…",
+ icon: "info",
+ buttons: [{ id: "skip", label: "Delete Without Search" }],
+ signal: progress.signal,
+ }).then((r) => {
+ if (r.button === "dismissed") return;
+ user.choice = r.button === "skip" ? "skip" : "cancel";
+ abort.abort();
+ });
+ }, SAFE_DELETE_PROGRESS_DELAY_MS);
let result;
try {
result = await fileUsages(files, abort.signal);
} catch {
+ if (user.choice) return user.choice === "skip";
notifications().notify({ level: "warning", title: "Usage search did not finish; nothing was deleted", key: "project.safeDelete" });
return false;
} finally {
clearTimeout(timer);
+ clearTimeout(shown);
+ progress.abort();
}
+ if (user.choice) return user.choice === "skip";
if (result.status !== "ok" || !result.usages.length) return true;
const name = files.length === 1 ? nameOf(files[0]!) : `${files.length} files`;
const subject = files.length === 1 ? `File '${name}'` : `The ${name}`;
@@ -368,9 +399,14 @@ export async function deleteSelection(nodes: ProjectNode[] = selectedNodes()) {
// Invoked from the tree (or its context menu): give the tree its focus back afterwards.
const refocus = typeof document !== "undefined" && !!document.activeElement?.closest('[role="tree"], [role="menu"]');
const folders = nodes.filter((n) => n.dir && paths.includes(n.path)).length;
- const ok = await confirm({
+ const files = nodes.filter((n) => !n.dir && paths.includes(n.path)).map((n) => n.path);
+ // IDEA's Delete dialog: "Safe delete (with usage search)", remembered.
+ const searchable = files.length > 0 && files.length <= SAFE_DELETE_MAX_FILES;
+ const answer = await confirmChecked({
title: "Delete",
ok: "Delete",
+ checkbox: searchable ? "Safe delete (with usage search)" : undefined,
+ checked: searchable && safeDeleteEnabled(),
message: createElement(
Fragment,
null,
@@ -379,9 +415,15 @@ export async function deleteSelection(nodes: ProjectNode[] = selectedNodes()) {
"Items are moved to the Trash.",
),
});
- if (!ok) return;
- const files = nodes.filter((n) => !n.dir && paths.includes(n.path)).map((n) => n.path);
- if (files.length && !(await safeToDelete(files))) return;
+ if (!answer) return;
+ if (searchable) {
+ try {
+ localStorage.setItem(SAFE_DELETE_KEY, String(answer.checked));
+ } catch {
+ /* storage unavailable */
+ }
+ }
+ if (searchable && answer.checked && !(await safeToDelete(files))) return;
const next = selectionAfterDelete(visibleNodes(), paths);
const fs = projectFs(root);
const parents = new Set<string>();
@@ -412,18 +454,47 @@ export function canPaste(): boolean {
return !!get().clipboard?.paths.length;
}
+/** Paste: cut items go through the Move dialog, copied ones through the Copy dialog (IDEA). */
export async function paste(target = targetFolder()) {
const { clipboard } = get();
if (!clipboard || !target) return;
- const done = await transfer(clipboard.paths, target, clipboard.cut ? "move" : "copy");
- if (clipboard.cut && done) setClipboard(null);
+ const isDir = (p: string) => get().listings.has(p) || currentModel().byKey.get(currentModel().keyOfPath.get(p) ?? p)?.dir === true;
+ const single = clipboard.paths.length === 1 && isDir(clipboard.paths[0]!);
+ if (!clipboard.cut) return openCopyDialogFor(clipboard.paths, target, single);
+ const paths = clipboard.paths.filter((p) => parentOf(p) !== target);
+ if (!paths.length) return;
+ openMoveDialogFor(paths, target, single, () => {
+ if (get().clipboard === clipboard) setClipboard(null);
+ });
+}
+
+function openCopyDialogFor(paths: string[], target: string, dir?: boolean) {
+ if (!paths.length) return;
+ void loadDir(target);
+ openFileRefactorDialog({
+ kind: "copy",
+ paths,
+ target,
+ dir,
+ copy: async (to, name, openInEditor) => {
+ const first = await transfer(paths, to, "copy", name ?? undefined);
+ if (typeof first === "string" && openInEditor) void openFile(first, { focus: true });
+ return !!first;
+ },
+ });
}
/**
- * Moves or copies `paths` into `target`. Copies get a non-conflicting name
- * (`Foo copy.kt`); moves refuse to overwrite. Returns whether anything changed.
+ * Moves or copies `paths` into `target`. Copies take `name` (a single item) or
+ * get a non-conflicting name (`Foo copy.kt`); moves refuse to overwrite.
+ * Returns whether anything changed (for copies: the first copy's path).
*/
-export async function transfer(paths: string[], target: string, mode: "move" | "copy"): Promise<boolean> {
+export async function transfer(
+ paths: string[],
+ target: string,
+ mode: "move" | "copy",
+ name?: string,
+): Promise<string | boolean> {
if (mode === "move") return moveInto(paths, target);
const { root } = get();
if (!root) return false;
@@ -434,6 +505,7 @@ export async function transfer(paths: string[], target: string, mode: "move" | "
const touched = new Set<string>([target]);
const errors: string[] = [];
let first: string | null = null;
+ const newName = name;
for (const src of paths) {
const name = nameOf(src);
if (isSameOrInside(target, src) && target !== parentOf(src) && src !== target) {
@@ -441,7 +513,7 @@ export async function transfer(paths: string[], target: string, mode: "move" | "
continue;
}
const srcIsDir = get().listings.has(src) || currentModel().byKey.get(src)?.dir === true;
- const finalName = uniqueName(name, isTaken, srcIsDir);
+ const finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
const to = joinPath(target, finalName);
try {
await fs.copy(src, to);
@@ -458,7 +530,7 @@ export async function transfer(paths: string[], target: string, mode: "move" | "
expandFolder(target);
revealPath(first, false);
}
- return first !== null;
+ return first ?? false;
}
/**
@@ -499,10 +571,8 @@ export async function dropPaths(paths: string[], target: string, copy: boolean)
const node = movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
return openMoveDialogFor(movable, target, node?.dir);
}
- const { root } = get();
- const where = root && target === root ? (get().name ?? nameOf(target)) : relativeTo(root ?? "", target) || target;
- const ok = await confirm({ title: "Copy", ok: "Copy", message: `Copy ${describe(movable)} to '${where}'?` });
- if (ok) await transfer(movable, target, "copy");
+ const node = movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
+ openCopyDialogFor(movable, target, node?.dir);
}
/** Files dropped from the OS: copied into `target` (never moved). */
diff --git a/src/features/project-tree/safeDelete.test.ts b/src/features/project-tree/safeDelete.test.ts
index c3702d485..7a8aee33b 100644
--- a/src/features/project-tree/safeDelete.test.ts
+++ b/src/features/project-tree/safeDelete.test.ts
@@ -11,6 +11,12 @@ vi.mock("@/workbench/contributions", async (orig) => ({
notifications: () => ({ notify }),
}));
+const ask = vi.fn();
+vi.mock("@/workbench/messages", async (orig) => ({
+ ...(await orig<typeof import("@/workbench/messages")>()),
+ ask,
+}));
+
const { safeToDelete } = await import("./operations");
const usage: Location = { path: "/p/main.rs", range: { start: { line: 1, col: 0 }, end: { line: 1, col: 1 } } };
@@ -46,4 +52,27 @@ describe("safe delete of files", () => {
expect(await safeToDelete(["/p/a.rs"])).toBe(false);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "warning" }));
});
+
+ it("lets a slow search be skipped (delete anyway) or cancelled", async () => {
+ vi.useFakeTimers();
+ try {
+ const pending = (_: string[], signal: AbortSignal) =>
+ new Promise((_r, reject) => signal.addEventListener("abort", () => reject(new Error("aborted"))));
+ fileUsages.mockImplementation(pending);
+ ask.mockResolvedValueOnce({ button: "skip", checked: false });
+ const skipped = safeToDelete(["/p/a.rs"]);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(await skipped).toBe(true);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ body: "Looking for usages…" }));
+
+ ask.mockResolvedValueOnce({ button: "cancel", checked: false });
+ const cancelled = safeToDelete(["/p/a.rs"]);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(await cancelled).toBe(false);
+ expect(notify).not.toHaveBeenCalled();
+ } finally {
+ fileUsages.mockReset();
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/src/features/project-tree/store.test.ts b/src/features/project-tree/store.test.ts
index a349dff7c..e03560afa 100644
--- a/src/features/project-tree/store.test.ts
+++ b/src/features/project-tree/store.test.ts
@@ -13,6 +13,7 @@ import {
useProjectTree,
} from "./store";
import { beginNew, commitEditing, copySelection, paste, transfer } from "./operations";
+import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
const ROOT = "/p";
let fs: MemoryFs;
@@ -140,20 +141,30 @@ describe("file operations", () => {
expect(childLabels("/p/docs")).toContain("notes");
});
- it("copies with unique names and moves with cut / paste", async () => {
+ it("pastes copies through the Copy dialog and cut items through the Move dialog", async () => {
await loadDir(ROOT);
await loadDir("/p/docs");
setSelection(new Set(["/p/README.md"]), "/p/README.md");
copySelection(false);
await paste(ROOT);
- expect(fs.nodes.has("/p/README copy.md")).toBe(true);
+ const copy = pendingFileRefactorDialog();
+ expect(copy).toMatchObject({ kind: "copy", paths: ["/p/README.md"], target: ROOT });
+ if (copy?.kind !== "copy") throw new Error("no copy dialog");
+ expect(await copy.copy(ROOT, "NOTES.md", false)).toBe(true);
+ expect(fs.nodes.has("/p/NOTES.md")).toBe(true);
+ // Without a name (several items) copies get a unique name.
+ expect(await transfer(["/p/README.md"], ROOT, "copy")).toBe("/p/README copy.md");
+ closeFileRefactorDialog();
setSelection(new Set(["/p/README.md"]), "/p/README.md");
copySelection(true);
await paste("/p/docs");
- expect(fs.nodes.has("/p/docs/README.md")).toBe(true);
- expect(fs.nodes.has("/p/README.md")).toBe(false);
+ const move = pendingFileRefactorDialog();
+ expect(move).toMatchObject({ kind: "move", paths: ["/p/README.md"], target: "/p/docs" });
+ if (move?.kind !== "move") throw new Error("no move dialog");
+ move.onDone?.([{ from: "/p/README.md", to: "/p/docs/README.md" }]);
expect(useProjectTree.getState().clipboard).toBeNull();
+ closeFileRefactorDialog();
});
it("refuses to move a folder into itself", async () => {
diff --git a/src/features/project-tree/store.ts b/src/features/project-tree/store.ts
index 84e56fa0a..47806a5b0 100644
--- a/src/features/project-tree/store.ts
+++ b/src/features/project-tree/store.ts
@@ -39,7 +39,8 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
autoscrollFromSource: false,
autoscrollToSource: false,
singleClickOpen: false,
- previewTab: true,
+ // IDEA's "Enable Preview Tab" is off by default.
+ previewTab: false,
};
export type Editing =
diff --git a/src/features/run/ConfigChooser.tsx b/src/features/run/ConfigChooser.tsx
index 5a0b9895a..2e7c20660 100644
--- a/src/features/run/ConfigChooser.tsx
+++ b/src/features/run/ConfigChooser.tsx
@@ -1,11 +1,11 @@
-import { useMemo, useState, type KeyboardEvent } from "react";
+import { useEffect, useMemo, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { HighlightedText, Icon, IconButton, List, Popup, SearchField, fuzzyMatch, listNavigate, T } from "@/ui";
import type { RunConfig } from "@/platform/ipc";
import { commandLine, configIcon, groupConfigs } from "./configs";
-import { saveTemporary, selectConfig, startRun, useRun } from "./store";
+import { canDeleteConfig, deleteConfig, saveTemporary, selectConfig, startRun, useRun } from "./store";
import styles from "./Run.module.css";
type Row =
@@ -54,7 +54,19 @@ export function ConfigChooserOverlay() {
return <ConfigChooser />;
}
+/** Numeric mnemonics (IDEA: 1–9 run the Nth configuration while the search is empty). */
+export function mnemonics(rows: readonly Row[]): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const r of rows) {
+ if (r.type !== "config") continue;
+ if (out.size >= 9) break;
+ out.set(r.key, out.size + 1);
+ }
+ return out;
+}
+
function ConfigChooser() {
+ const mode = useRun((s) => s.chooserMode);
const configs = useRun((s) => s.configs);
const selectedId = useRun((s) => s.selectedId);
const temporary = useRun((s) => s.temporary);
@@ -81,8 +93,27 @@ function ConfigChooser() {
useRun.setState({ chooserOpen: false });
};
const clamped = Math.min(active, rows.length - 1);
+ const numbers = useMemo(
+ () => (mode === "select" || query ? new Map<string, number>() : mnemonics(rows)),
+ [mode, query, rows],
+ );
+ // IDEA: holding Shift switches to the alternative executor (Run ⇄ Debug) and updates the caption.
+ const [shift, setShift] = useState(false);
+ useEffect(() => {
+ const track = (e: globalThis.KeyboardEvent) => setShift(e.shiftKey);
+ const reset = () => setShift(false);
+ window.addEventListener("keydown", track, true);
+ window.addEventListener("keyup", track, true);
+ window.addEventListener("blur", reset);
+ return () => {
+ window.removeEventListener("keydown", track, true);
+ window.removeEventListener("keyup", track, true);
+ window.removeEventListener("blur", reset);
+ };
+ }, []);
+ const executor = mode === "select" ? "select" : shift ? (mode === "run" ? "debug" : "run") : mode;
- const activate = (row: Row | undefined, mode: "select" | "run" | "debug" = "select") => {
+ const activate = (row: Row | undefined, how: "select" | "run" | "debug" | "edit" = executor) => {
if (!row) return;
close();
if (row.type === "edit") {
@@ -95,16 +126,44 @@ function ConfigChooser() {
}
if (row.type !== "config") return;
selectConfig(row.config.id);
- if (mode === "run") void startRun(row.config);
- if (mode === "debug") void executeAction("run.debug");
+ if (how === "edit") void executeAction("run.editConfigs", row.config.id);
+ if (how === "run") void startRun(row.config);
+ if (how === "debug") void executeAction("run.debug");
};
const onKeyDown = (e: KeyboardEvent) => {
+ const row = rows[clamped];
if (e.key === "Enter") {
e.preventDefault();
- activate(rows[clamped], e.shiftKey ? "debug" : e.altKey || e.metaKey ? "run" : "select");
+ // The widget (select mode) keeps Shift+Enter = Debug and Alt/⌘+Enter = Run.
+ activate(row, mode !== "select" ? executor : e.shiftKey ? "debug" : e.altKey || e.metaKey ? "run" : "select");
return;
}
+ if (e.key === "F4" && row?.type === "config") {
+ e.preventDefault();
+ activate(row, "edit");
+ return;
+ }
+ const input = e.target as HTMLInputElement;
+ if (
+ e.key === "Delete" &&
+ row?.type === "config" &&
+ canDeleteConfig(row.config.id) &&
+ input.selectionStart === query.length
+ ) {
+ e.preventDefault();
+ void deleteConfig(row.config.id);
+ return;
+ }
+ if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
+ const n = Number(e.code.slice(-1));
+ const target = rows.find((r) => numbers.get(r.key) === n);
+ if (target) {
+ e.preventDefault();
+ activate(target, e.shiftKey ? (mode === "run" ? "debug" : "run") : mode);
+ return;
+ }
+ }
const next = listNavigate(e.key, { items: rows, active: clamped, isSection, wrap: true });
if (next !== null) {
e.preventDefault();
@@ -124,6 +183,11 @@ function ConfigChooser() {
className={styles.chooser}
trapFocus
>
+ {mode !== "select" && (
+ <div className={styles.chooserCaption}>
+ <T>{executor === "debug" ? "Debug" : "Run"}</T>
+ </div>
+ )}
<div className={styles.chooserSearch}>
<SearchField
value={query}
@@ -181,6 +245,7 @@ function ConfigChooser() {
size={13}
className={clsx(styles.chooserIcon, temporary.includes(c.id) && styles.chooserTemporary)}
/>
+ {numbers.size > 0 && <span className={styles.chooserMnemonic}>{numbers.get(r.key) ?? ""}</span>}
<span className={clsx(styles.chooserName, c.id === selectedId && styles.chooserSelected)}>
{r.indices ? <HighlightedText text={c.name} indices={r.indices} /> : c.name}
</span>
@@ -218,6 +283,15 @@ function ConfigChooser() {
}}
/>
</div>
+ {mode !== "select" && (
+ <div className={styles.chooserHint}>
+ <T>
+ {mode === "run"
+ ? "Hold Shift to Debug, F4 to edit, Delete to remove"
+ : "Hold Shift to Run, F4 to edit, Delete to remove"}
+ </T>
+ </div>
+ )}
</Popup>
);
}
diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx
index 4ac2769ac..fd152beae 100644
--- a/src/features/run/ConsoleView.tsx
+++ b/src/features/run/ConsoleView.tsx
@@ -1,8 +1,19 @@
-import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type MouseEvent } from "react";
+import {
+ memo,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ClipboardEvent,
+ type CSSProperties,
+ type KeyboardEvent,
+ type MouseEvent,
+} from "react";
import clsx from "clsx";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useWorkflowSettings } from "@/platform/workflowSettings";
-import { showContextMenu } from "@/ui";
+import { Icon, showContextMenu } from "@/ui";
import type { ConsoleLine, ConsoleModel, SpanStyle } from "./console";
import { findOutputLinks, type OutputLink } from "./links";
import { openTarget, openUrl } from "./navigate";
@@ -62,11 +73,23 @@ const Line = memo(
(a, b) => a.line === b.line && a.length === b.length && a.cwd === b.cwd,
);
-/** A visible console row: one line, or a fold of consecutive lines (Settings › Console). */
-export type DisplayRow = { kind: "line"; index: number } | { kind: "fold"; start: number; count: number; id: number };
+/** A run of folded lines (Settings › Console › Fold lines that contain). */
+export interface Fold {
+ start: number;
+ count: number;
+ /** Id of the first folded line (stable across trimming). */
+ id: number;
+ expanded: boolean;
+}
+
+/**
+ * A visible console row: one line (carrying the fold of the lines after it, IDEA attaches
+ * the `<N internal lines>` placeholder to the previous line), or a fold with no line before it.
+ */
+export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind: "fold"; fold: Fold };
/**
- * Folds runs of at least two consecutive output lines that contain one of
+ * Folds runs of consecutive output lines (one or more) that contain one of
* `patterns`; runs whose first line id is in `expanded` stay open.
*/
export function foldRows(lines: readonly ConsoleLine[], patterns: readonly string[], expanded: ReadonlySet<number>): DisplayRow[] {
@@ -76,13 +99,12 @@ export function foldRows(lines: readonly ConsoleLine[], patterns: readonly strin
if (patterns.length && matches(lines[i]!)) {
let j = i + 1;
while (j < lines.length && matches(lines[j]!)) j++;
- const id = lines[i]!.id;
- if (j - i >= 2 && !expanded.has(id)) {
- rows.push({ kind: "fold", start: i, count: j - i, id });
- i = j;
- continue;
- }
- for (; i < j; i++) rows.push({ kind: "line", index: i });
+ const fold: Fold = { start: i, count: j - i, id: lines[i]!.id, expanded: expanded.has(lines[i]!.id) };
+ const prev = rows[rows.length - 1];
+ if (prev?.kind === "line") prev.fold = fold;
+ else if (!fold.expanded) rows.push({ kind: "fold", fold });
+ if (fold.expanded) for (; i < j; i++) rows.push({ kind: "line", index: i });
+ i = j;
continue;
}
rows.push({ kind: "line", index: i });
@@ -91,6 +113,17 @@ export function foldRows(lines: readonly ConsoleLine[], patterns: readonly strin
return rows;
}
+/** Typed console input (IDEA: type into the console, Enter sends the line). */
+export interface ConsoleInput {
+ /** Typed, not yet sent. */
+ pending: string;
+ onChange(pending: string): void;
+ /** Sends one line (without the newline). */
+ onSubmit(line: string): void;
+ /** Closes stdin (EOF). */
+ onEof(): void;
+}
+
export interface ConsoleViewProps {
model: ConsoleModel;
version: number;
@@ -100,17 +133,31 @@ export interface ConsoleViewProps {
/** Directory relative paths in the output resolve against. */
cwd: string;
onClear?: () => void;
+ /** Set while the process accepts input. */
+ input?: ConsoleInput;
"aria-label"?: string;
}
-export function ConsoleView({ model, version, softWrap, follow, onFollowChange, cwd, onClear, ...aria }: ConsoleViewProps) {
+export function ConsoleView({ model, version, softWrap, follow, onFollowChange, cwd, onClear, input, ...aria }: ConsoleViewProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const lines = model.lines;
const patterns = useWorkflowSettings((s) => s.console.foldPatterns);
const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set());
// eslint-disable-next-line react-hooks/exhaustive-deps -- `version` marks in-place appends to `lines`
- const rows = useMemo(() => foldRows(lines, patterns, expanded), [lines, version, patterns, expanded]);
- const count = rows.length;
+ const folded = useMemo(() => foldRows(lines, patterns, expanded), [lines, version, patterns, expanded]);
+ // Pending input continues the open line (a prompt), or starts a row of its own.
+ const lastRow = folded[folded.length - 1];
+ const inputInline =
+ !!input && !!model.openLine && lastRow?.kind === "line" && !lastRow.fold && lines[lastRow.index] === model.openLine;
+ const inputRow = !!input && !inputInline;
+ const rows = folded;
+ const count = rows.length + (inputRow ? 1 : 0);
+ const toggleFold = (id: number) =>
+ setExpanded((s) => {
+ const next = new Set(s);
+ if (!next.delete(id)) next.add(id);
+ return next;
+ });
const programmatic = useRef(false);
const virtualizer = useVirtualizer({
@@ -120,8 +167,8 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
overscan: 30,
getItemKey: (i) => {
const r = rows[i];
- if (!r) return i;
- return r.kind === "fold" ? `f${r.id}` : (lines[r.index]?.id ?? i);
+ if (!r) return "input";
+ return r.kind === "fold" ? `f${r.fold.id}` : (lines[r.index]?.id ?? i);
},
});
@@ -160,9 +207,56 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
{ label: "Copy All", run: () => void navigator.clipboard?.writeText(model.text()).catch(() => undefined) },
{ kind: "separator" },
{ label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() },
+ ...(input ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }] : []),
]);
};
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (!input || e.nativeEvent.isComposing) return;
+ if (e.key === "d" && e.ctrlKey && !e.metaKey && !e.altKey) {
+ e.preventDefault();
+ input.onEof();
+ } else if (e.key === "Enter" && !e.ctrlKey && !e.metaKey && !e.altKey) {
+ e.preventDefault();
+ input.onSubmit(input.pending);
+ input.onChange("");
+ } else if (e.key === "Backspace" && !e.ctrlKey && !e.metaKey) {
+ e.preventDefault();
+ input.onChange(e.altKey ? input.pending.replace(/\S*\s*$/, "") : [...input.pending].slice(0, -1).join(""));
+ } else if (e.key.length === 1 && [...e.key].length === 1 && !e.ctrlKey && !e.metaKey) {
+ e.preventDefault();
+ input.onChange(input.pending + e.key);
+ }
+ };
+
+ const onPaste = (e: ClipboardEvent) => {
+ if (!input) return;
+ const text = e.clipboardData.getData("text/plain");
+ if (!text) return;
+ e.preventDefault();
+ const parts = (input.pending + text).replace(/\r\n?/g, "\n").split("\n");
+ const rest = parts.pop() ?? "";
+ for (const line of parts) input.onSubmit(line);
+ input.onChange(rest);
+ };
+
+ const pendingInput = input && (
+ <span className={styles.userInput}>
+ {input.pending}
+ <span className={styles.inputCaret} aria-hidden />
+ </span>
+ );
+ const foldButton = (fold: Fold, attached: boolean) =>
+ fold.expanded ? (
+ <button type="button" className={styles.foldToggle} title="Collapse folded lines" aria-label="Collapse folded lines" onClick={() => toggleFold(fold.id)}>
+ <Icon name="chevron-up" size={10} />
+ </button>
+ ) : (
+ <button type="button" className={styles.fold} title="Expand folded lines" onClick={() => toggleFold(fold.id)}>
+ {`${attached ? " " : ""}<${fold.count} internal line${fold.count === 1 ? "" : "s"}>`}
+ </button>
+ );
+
const items = virtualizer.getVirtualItems();
return (
<div
@@ -174,12 +268,26 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
tabIndex={0}
onScroll={onScroll}
onContextMenu={onContextMenu}
+ onKeyDown={onKeyDown}
+ onPaste={onPaste}
data-autofocus=""
>
<div className={styles.consoleInner} style={{ height: virtualizer.getTotalSize() }}>
{items.map((item) => {
const row = rows[item.index];
- if (!row) return null;
+ if (!row) {
+ return (
+ <div
+ key={item.key}
+ data-index={item.index}
+ ref={softWrap ? virtualizer.measureElement : undefined}
+ className={styles.line}
+ style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : ROW }}
+ >
+ {pendingInput}
+ </div>
+ );
+ }
if (row.kind === "fold") {
return (
<div
@@ -189,14 +297,7 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
className={styles.line}
style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : ROW }}
>
- <button
- type="button"
- className={styles.fold}
- title="Expand folded lines"
- onClick={() => setExpanded((s) => new Set(s).add(row.id))}
- >
- {`<${row.count} internal line${row.count === 1 ? "" : "s"}>`}
- </button>
+ {foldButton(row.fold, false)}
</div>
);
}
@@ -211,6 +312,8 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : ROW }}
>
<Line line={line} length={line.text.length} cwd={cwd} />
+ {row.fold && foldButton(row.fold, true)}
+ {inputInline && item.index === rows.length - 1 && pendingInput}
</div>
);
})}
diff --git a/src/features/run/EditConfigsDialog.tsx b/src/features/run/EditConfigsDialog.tsx
index 1ffa54202..6b38d5621 100644
--- a/src/features/run/EditConfigsDialog.tsx
+++ b/src/features/run/EditConfigsDialog.tsx
@@ -343,6 +343,13 @@ function EditConfigsDialog() {
label="Show results in the test runner"
/>
</Field>
+ <Field label="">
+ <Checkbox
+ checked={!!current.allowParallel}
+ onChange={(allowParallel) => update({ allowParallel })}
+ label="Allow multiple instances"
+ />
+ </Field>
<Field label="Debug adapter">
<Select
value={current.debugAdapter ?? ""}
diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css
index 3d14f1389..e70bf6b85 100644
--- a/src/features/run/Run.module.css
+++ b/src/features/run/Run.module.css
@@ -166,26 +166,6 @@
text-decoration-color: currentColor;
}
-/* stdin */
-
-.stdin {
- flex: none;
- display: flex;
- align-items: center;
- gap: 4px;
- height: 28px;
- padding: 0 6px 0 10px;
- border-top: 1px solid var(--border);
-}
-.stdinPrompt {
- color: var(--accent);
- flex: none;
-}
-.stdinInput {
- flex: 1;
- min-width: 0;
-}
-
/* Test runner */
.testPane {
@@ -389,6 +369,25 @@
.chooserTemporary {
opacity: 0.55;
}
+.chooserCaption {
+ padding: 6px 10px 0;
+ color: var(--fg-secondary);
+ font-weight: 500;
+}
+.chooserMnemonic {
+ flex: none;
+ width: 8px;
+ color: var(--fg-subtle);
+ font-family: var(--font-keys);
+ font-size: var(--fs-small);
+}
+/* IDEA's popup ad text. */
+.chooserHint {
+ padding: 4px 10px 0;
+ border-top: 1px solid var(--border-popup);
+ color: var(--fg-faint);
+ font-size: var(--fs-small);
+}
.chooserActions {
display: flex;
margin-right: -4px;
@@ -573,3 +572,41 @@
.fold:hover {
color: var(--fg);
}
+.foldToggle {
+ display: inline-flex;
+ align-items: center;
+ margin-left: 6px;
+ padding: 0 2px;
+ border: none;
+ border-radius: 3px;
+ background: none;
+ color: var(--fg-faint);
+ vertical-align: middle;
+ cursor: pointer;
+}
+.foldToggle:hover {
+ color: var(--fg);
+ background: var(--bg-fold-placeholder);
+}
+
+/* Typed console input: echoed in the same colour once sent. */
+.userInput {
+ color: var(--ansi-green);
+}
+.inputCaret {
+ display: inline-block;
+ width: 1px;
+ height: 1.1em;
+ margin-left: 1px;
+ vertical-align: text-bottom;
+ background: transparent;
+}
+.console:focus .inputCaret {
+ background: var(--fg);
+ animation: caretBlink 1s steps(1) infinite;
+}
+@keyframes caretBlink {
+ 50% {
+ background: transparent;
+ }
+}
diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx
index 26591db42..3a1c03a3e 100644
--- a/src/features/run/RunView.tsx
+++ b/src/features/run/RunView.tsx
@@ -1,12 +1,13 @@
import { useMemo, useState } from "react";
import { useWorkflowSettings } from "@/platform/workflowSettings";
-import { EmptyState, Icon, IconButton, Input, SplitGroup, SplitHandle, SplitPanel, Tabs, type TabItem, T } from "@/ui";
+import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, Tabs, type TabItem, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { ConsoleModel } from "./console";
import { ConsoleView } from "./ConsoleView";
import { runDirectory } from "./navigate";
import {
+ acceptsInput,
clearConsole,
closeSession,
closeStdin,
@@ -15,6 +16,7 @@ import {
rerunSession,
runtime,
sendStdin,
+ setPendingInput,
stopSession,
useRun,
type RunSession,
@@ -33,52 +35,6 @@ function sessionIcon(s: RunSession): string {
return s.config.isTest ? "check" : "run";
}
-function StdinBar({ session }: { session: RunSession }) {
- const [value, setValue] = useState("");
- const disabled = session.status !== "running" || session.stdinClosed;
- return (
- <form
- className={styles.stdin}
- onSubmit={(e) => {
- e.preventDefault();
- if (disabled) return;
- void sendStdin(session.id, value);
- setValue("");
- }}
- >
- <Icon name="chevron-right" size={12} className={styles.stdinPrompt} />
- <Input
- variant="bare"
- mono
- className={styles.stdinInput}
- aria-label="Standard input"
- placeholder={
- session.stdinClosed ? "stdin closed" : disabled ? "Process is not running" : "Send to stdin (Enter)"
- }
- value={value}
- disabled={disabled}
- data-autofocus=""
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "d" && e.ctrlKey) {
- e.preventDefault();
- void closeStdin(session.id);
- }
- }}
- />
- <IconButton
- icon="close"
- size="small"
- iconSize={12}
- title="Close stdin (send EOF)"
- shortcut="⌃D"
- disabled={disabled}
- onClick={() => void closeStdin(session.id)}
- />
- </form>
- );
-}
-
function SessionPanel({ session }: { session: RunSession }) {
const version = useRun((s) => s.versions[session.id] ?? 0);
const rt = runtime(session.id);
@@ -87,7 +43,6 @@ function SessionPanel({ session }: { session: RunSession }) {
const defaultWrap = useWorkflowSettings((s) => s.console.softWrap);
const [wrapOverride, setWrapOverride] = useState<boolean | null>(null);
const softWrap = wrapOverride ?? defaultWrap;
- const [showStdin, setShowStdin] = useState(false);
const [selectedTest, setSelectedTest] = useState<string | null>(null);
const running = session.status === "running" || session.status === "starting";
const cwd = runDirectory(session.config.cwd);
@@ -124,16 +79,31 @@ function SessionPanel({ session }: { session: RunSession }) {
onFollowChange={setFollow}
cwd={cwd}
onClear={() => clearConsole(session.id)}
+ input={
+ !testModel && acceptsInput(session)
+ ? {
+ pending: rt.input,
+ onChange: (text) => setPendingInput(session.id, text),
+ onSubmit: (line) => void sendStdin(session.id, line),
+ onEof: () => void closeStdin(session.id),
+ }
+ : undefined
+ }
aria-label={`${session.config.name} output`}
/>
- {showStdin && <StdinBar session={session} />}
</div>
);
return (
<div className={styles.session}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label="Run actions">
- <IconButton icon="rerun" iconSize={14} title="Rerun" onClick={() => rerunSession(session.id)} />
+ <IconButton
+ icon="rerun"
+ iconSize={14}
+ title="Rerun"
+ shortcut={shortcutLabel("run.rerun")}
+ onClick={() => rerunSession(session.id)}
+ />
{rt.tests && (
<IconButton
icon="rerun"
@@ -162,13 +132,6 @@ function SessionPanel({ session }: { session: RunSession }) {
onClick={() => setFollow((v) => !v)}
/>
<IconButton icon="soft-wrap" iconSize={14} title="Soft-Wrap" pressed={softWrap} onClick={toggleWrap} />
- <IconButton
- icon="keyboard"
- iconSize={14}
- title="Show Input Field"
- pressed={showStdin}
- onClick={() => setShowStdin((v) => !v)}
- />
<IconButton icon="trash" iconSize={14} title="Clear All" onClick={() => clearConsole(session.id)} />
<div className={styles.toolbarSep} />
<IconButton
diff --git a/src/features/run/RunWidget.tsx b/src/features/run/RunWidget.tsx
index 95326de1c..76f06b74b 100644
--- a/src/features/run/RunWidget.tsx
+++ b/src/features/run/RunWidget.tsx
@@ -55,7 +55,11 @@ export function RunWidget() {
aria-haspopup="listbox"
aria-expanded={chooserOpen}
data-run-chooser=""
- onClick={() => void executeAction(selected || configs.length ? "run.chooseConfig" : "run.editConfigs")}
+ onClick={() =>
+ void (selected || configs.length
+ ? executeAction("run.chooseConfig", "select")
+ : executeAction("run.editConfigs"))
+ }
>
{selected && (
// IDEA: the configuration's type icon, with a status dot on its top-right corner while active.
diff --git a/src/features/run/console.ts b/src/features/run/console.ts
index 693154b9e..075a584fe 100644
--- a/src/features/run/console.ts
+++ b/src/features/run/console.ts
@@ -280,6 +280,11 @@ export class ConsoleModel {
this.pendingCR = false;
}
+ /** The last line while it is still being written (no newline yet), e.g. a prompt. */
+ get openLine(): ConsoleLine | null {
+ return this.open;
+ }
+
get size() {
return this.lines.length;
}
diff --git a/src/features/run/dialogs.tsx b/src/features/run/dialogs.tsx
index 3609b581e..2f4aa98da 100644
--- a/src/features/run/dialogs.tsx
+++ b/src/features/run/dialogs.tsx
@@ -14,11 +14,14 @@ interface Pending {
const useRunDialog = create<{ pending: Pending | null }>(() => ({ pending: null }));
-/** IDEA's "Process 'x' Is Running" dialog. Resolves true for Stop and Rerun. */
-export async function confirmRerun(name: string): Promise<boolean> {
+/**
+ * IDEA's "Process 'x' Is Running" dialog, shown when Run starts a configuration
+ * that doesn't allow parallel runs. Resolves true for Stop and Rerun.
+ */
+export async function confirmRerun(name: string, instances = 1): Promise<boolean> {
const answer = await confirmChecked({
title: `Process '${name}' Is Running`,
- message: `Do you want to stop the process '${name}' and run it again?`,
+ message: `'${name}' is not allowed to run in parallel.\nWould you like to stop ${instances > 1 ? `${instances} running instances` : "the running one"}?`,
ok: "Stop and Rerun",
checkbox: "Do not ask again",
});
diff --git a/src/features/run/index.ts b/src/features/run/index.ts
index 00fb44e32..8624da4ec 100644
--- a/src/features/run/index.ts
+++ b/src/features/run/index.ts
@@ -4,12 +4,13 @@
*/
import { registerEditorContribution } from "@/editor/api";
import { executeAction, getAction, registerActions } from "@/platform/actions";
-import { setContext } from "@/platform/context";
+import { getContext, setContext } from "@/platform/context";
import { onIdeEvent, type RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { onWorkflowSettingsChange } from "@/platform/workflowSettings";
-import { showContextMenu, lazyComponent } from "@/ui";
+import { showContextMenu, lazyComponent, type MenuItem } from "@/ui";
import {
+ menuGroupItems,
notifications,
registerMenuGroup,
registerOverlay,
@@ -42,6 +43,7 @@ import {
failedTests,
onRunExited,
rerunFailed,
+ rerunSession,
resetRuns,
runningSessions,
saveUserConfigs,
@@ -64,7 +66,7 @@ async function runSelected() {
await ensureConfigs();
const config = selectedConfig();
if (!config) {
- useRun.setState({ chooserOpen: true });
+ useRun.setState({ chooserOpen: true, chooserMode: "run" });
return;
}
await startRun(config);
@@ -100,7 +102,7 @@ async function debugSelected() {
await ensureConfigs();
const config = selectedConfig();
if (!config) {
- useRun.setState({ chooserOpen: true });
+ useRun.setState({ chooserOpen: true, chooserMode: "debug" });
return;
}
await debugConfig(config);
@@ -134,23 +136,52 @@ function configFromArg(arg: unknown): RunConfig | undefined {
return arg as RunConfig;
}
+/**
+ * IDEA's Stop: in the Run or Debug tool window, the selected tab's process; otherwise the
+ * only running process, or a chooser of every running one (run sessions and the
+ * `stopProcess` items other features contribute, e.g. debug sessions).
+ */
function stopAction() {
+ const ctx = getContext();
+ if (ctx.toolWindowFocus && ctx.activeToolWindow === "debug" && getAction("debug.stop")) {
+ void executeAction("debug.stop");
+ return;
+ }
const running = runningSessions();
- if (running.length === 0) return;
- if (running.length === 1) {
- void stopSession(running[0]!.id);
+ const { activeSession } = useRun.getState();
+ if (ctx.toolWindowFocus && ctx.activeToolWindow === "run") {
+ const active = running.find((s) => s.id === activeSession);
+ if (active) {
+ void stopSession(active.id);
+ return;
+ }
+ }
+ const items = [
+ ...running.map((s): MenuItem => ({ label: s.config.name, verbatim: true, icon: "run", run: () => void stopSession(s.id) })),
+ ...menuGroupItems("stopProcess", { paths: [] }),
+ ].filter((i): i is MenuItem & { run: () => void } => "run" in i && !!i.run);
+ if (items.length === 0) return;
+ if (items.length === 1) {
+ items[0]!.run();
return;
}
const anchor = document.querySelector("[data-run-chooser]")?.getBoundingClientRect();
const at = anchor ? { x: anchor.left, y: anchor.bottom + 4 } : { x: window.innerWidth / 2 - 120, y: 44 };
showContextMenu(at, [
{ kind: "header", label: "Stop Process" },
- ...running.map((s) => ({ label: s.config.name, icon: "stop", run: () => void stopSession(s.id) })),
+ ...items,
{ kind: "separator" },
- { label: "Stop All", icon: "stop", danger: true, run: () => running.forEach((s) => void stopSession(s.id)) },
+ { label: "Stop All", icon: "stop", danger: true, run: () => items.forEach((i) => i.run()) },
]);
}
+/** IDEA's Rerun (⌘R / Ctrl+F5 in the Run tool window): restarts the selected tab without asking. */
+function rerunActive() {
+ const { activeSession, sessions } = useRun.getState();
+ const id = activeSession ?? sessions[sessions.length - 1]?.id;
+ if (id) rerunSession(id);
+}
+
function useRunningCount(): number | null {
return useRun((s) => s.sessions.filter((x) => x.status === "running" || x.status === "starting").length || null);
}
@@ -243,18 +274,27 @@ export function activate(): () => void {
when: "projectOpen",
run: () => stopAction(),
},
+ {
+ id: "run.rerun",
+ title: "Rerun",
+ category: "Run",
+ icon: "rerun",
+ when: "projectOpen && activeToolWindow == 'run'",
+ run: () => rerunActive(),
+ },
{
id: "run.chooseConfig",
title: "Select Run/Debug Configuration…",
+ description: "Run a configuration (hold Shift to debug); the title bar widget passes \"select\" to only select one",
category: "Run",
when: "projectOpen",
- run: async () => {
+ run: async ({ arg }) => {
if (useRun.getState().chooserOpen || chooserJustClosed()) {
useRun.setState({ chooserOpen: false });
return;
}
await ensureConfigs();
- useRun.setState({ chooserOpen: true });
+ useRun.setState({ chooserOpen: true, chooserMode: arg === "select" ? "select" : "run" });
},
},
{
@@ -342,7 +382,7 @@ export function activate(): () => void {
await ensureConfigs();
const target = config !== undefined ? configFromArg(config) : selectedConfig();
if (!target) {
- useRun.setState({ chooserOpen: true });
+ useRun.setState({ chooserOpen: true, chooserMode: "run" });
return;
}
await runWithExecutor(target, executor);
diff --git a/src/features/run/session.test.tsx b/src/features/run/session.test.tsx
new file mode 100644
index 000000000..c4031cc4a
--- /dev/null
+++ b/src/features/run/session.test.tsx
@@ -0,0 +1,177 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { executeAction } from "@/platform/actions";
+import { setContext } from "@/platform/context";
+import type { RunConfig } from "@/platform/ipc";
+import {
+ provideNotificationService,
+ provideToolWindowService,
+ registerMenuGroup,
+ type ToolWindowService,
+} from "@/workbench/contributions";
+import { ConsoleModel } from "./console";
+import { ConsoleView, type ConsoleInput } from "./ConsoleView";
+import { buildRows, mnemonics } from "./ConfigChooser";
+import { activate } from "./index";
+import { resetRuns, startRun, useRun, type RunSession } from "./store";
+
+const confirm = vi.hoisted(() => vi.fn(async () => true));
+vi.mock("./dialogs", () => ({ confirmRerun: confirm, promptValue: vi.fn(), RunDialogsOverlay: () => null }));
+
+const config = (id: string, extra: Partial<RunConfig> = {}): RunConfig => ({
+ id,
+ name: id,
+ kind: "shell",
+ command: "x",
+ args: [],
+ cwd: null,
+ env: {},
+ detected: false,
+ isTest: false,
+ debugAdapter: null,
+ ...extra,
+});
+
+const running = (id: string, c: RunConfig, runId: number | null = null): RunSession => ({
+ id,
+ config: c,
+ runId: runId as RunSession["runId"],
+ status: "running",
+ exitCode: null,
+ startedAt: 0,
+ endedAt: null,
+ stdinClosed: false,
+});
+
+beforeEach(() => {
+ resetRuns();
+ confirm.mockClear();
+ confirm.mockResolvedValue(true);
+ provideToolWindowService({ show: vi.fn(), isVisible: () => true } as unknown as ToolWindowService);
+ provideNotificationService({ notify: () => undefined });
+});
+
+describe("single-instance runs (IDEA restartRunProfile)", () => {
+ it("Run on a running configuration asks, then restarts it in its tab", async () => {
+ const app = config("app");
+ useRun.setState({ sessions: [running("run1", app)] });
+ await startRun(app);
+ expect(confirm).toHaveBeenCalledWith("app", 1);
+ expect(useRun.getState().sessions.map((s) => s.id)).toEqual(["run1"]);
+ });
+
+ it("does nothing when the restart is cancelled", async () => {
+ confirm.mockResolvedValue(false);
+ const app = config("app");
+ useRun.setState({ sessions: [running("run1", app)] });
+ expect(await startRun(app)).toBeNull();
+ expect(useRun.getState().sessions[0]!.status).toBe("running");
+ });
+
+ it("Rerun in the running tab restarts without asking", async () => {
+ const app = config("app");
+ useRun.setState({ sessions: [running("run1", app)] });
+ await startRun(app, "run1");
+ expect(confirm).not.toHaveBeenCalled();
+ expect(useRun.getState().sessions.map((s) => s.id)).toEqual(["run1"]);
+ });
+
+ it("starts another instance when parallel runs are allowed", async () => {
+ const app = config("app", { allowParallel: true });
+ useRun.setState({ sessions: [running("run1", app)] });
+ await startRun(app);
+ expect(confirm).not.toHaveBeenCalled();
+ expect(useRun.getState().sessions).toHaveLength(2);
+ });
+});
+
+describe("Stop", () => {
+ let dispose: () => void;
+ beforeEach(() => {
+ dispose = activate();
+ });
+ afterEach(() => {
+ dispose();
+ setContext("toolWindowFocus", false);
+ setContext("activeToolWindow", "");
+ });
+
+ it("stops the selected tab's process in the focused Run tool window", async () => {
+ setContext("projectOpen", true);
+ useRun.setState({
+ sessions: [running("run1", config("a"), 1), running("run2", config("b"), 2)],
+ activeSession: "run2",
+ });
+ setContext("toolWindowFocus", true);
+ setContext("activeToolWindow", "run");
+ await executeAction("run.stop");
+ expect(useRun.getState().sessions.map((s) => !!s.stopped)).toEqual([false, true]);
+ });
+
+ it("stops the only running process, including a contributed debug session", async () => {
+ setContext("projectOpen", true);
+ const stopDebug = vi.fn();
+ const unregister = registerMenuGroup({
+ id: "test.stop",
+ menus: ["stopProcess"],
+ items: () => [{ label: "dbg", run: stopDebug }],
+ });
+ await executeAction("run.stop");
+ expect(stopDebug).toHaveBeenCalledOnce();
+ unregister();
+ });
+});
+
+describe("configuration chooser", () => {
+ it("numbers the first nine configurations", () => {
+ const configs = Array.from({ length: 11 }, (_, i) => config(`c${i}`));
+ const rows = buildRows(configs, "");
+ const numbers = mnemonics(rows);
+ expect(numbers.size).toBe(9);
+ expect(numbers.get("c:c0")).toBe(1);
+ expect(numbers.get("c:c8")).toBe(9);
+ expect(numbers.has("c:c9")).toBe(false);
+ });
+});
+
+describe("console input", () => {
+ function setup(pending = "") {
+ const model = new ConsoleModel();
+ model.append({ kind: "stdout", text: "Name: " });
+ const input: ConsoleInput = { pending, onChange: vi.fn(), onSubmit: vi.fn(), onEof: vi.fn() };
+ render(
+ <ConsoleView
+ model={model}
+ version={1}
+ softWrap={false}
+ follow
+ onFollowChange={() => undefined}
+ cwd="/p"
+ input={input}
+ />,
+ );
+ return { input, log: screen.getByRole("log") };
+ }
+
+ it("types, erases and sends a line", () => {
+ const { input, log } = setup("ab");
+ fireEvent.keyDown(log, { key: "c" });
+ expect(input.onChange).toHaveBeenLastCalledWith("abc");
+ fireEvent.keyDown(log, { key: "Backspace" });
+ expect(input.onChange).toHaveBeenLastCalledWith("a");
+ fireEvent.keyDown(log, { key: "Enter" });
+ expect(input.onSubmit).toHaveBeenCalledWith("ab");
+ expect(input.onChange).toHaveBeenLastCalledWith("");
+ fireEvent.keyDown(log, { key: "c", metaKey: true });
+ expect(input.onChange).toHaveBeenCalledTimes(3);
+ fireEvent.keyDown(log, { key: "d", ctrlKey: true });
+ expect(input.onEof).toHaveBeenCalledOnce();
+ });
+
+ it("sends the complete lines of a paste and keeps the rest pending", () => {
+ const { input, log } = setup("x");
+ fireEvent.paste(log, { clipboardData: { getData: () => "1\r\n2\n3" } });
+ expect(vi.mocked(input.onSubmit).mock.calls).toEqual([["x1"], ["2"]]);
+ expect(input.onChange).toHaveBeenLastCalledWith("3");
+ });
+});
diff --git a/src/features/run/store.ts b/src/features/run/store.ts
index 78484bf7a..82eb70c57 100644
--- a/src/features/run/store.ts
+++ b/src/features/run/store.ts
@@ -44,6 +44,8 @@ interface SessionRuntime {
lineListeners: Array<(text: string) => void>;
/** Called once the process exited (run executors: collect a coverage report…). */
onExit?: (exitCode: number | null, stopped: boolean) => void;
+ /** User input typed into the console, not yet sent (IDEA: Enter sends the line). */
+ input: string;
}
interface RunState {
@@ -58,6 +60,11 @@ interface RunState {
/** Output version per session (re-render trigger for the console). */
versions: Record<string, number>;
chooserOpen: boolean;
+ /**
+ * What the chooser does with a configuration: `select` it (title bar widget), or `run` /
+ * `debug` it (⌃⌥R; holding Shift swaps the executor, as IDEA).
+ */
+ chooserMode: "select" | "run" | "debug";
editorOpen: boolean;
/** Config to preselect when the edit dialog opens. */
editTarget: string | null;
@@ -75,6 +82,7 @@ export const useRun = create<RunState>(() => ({
activeSession: null,
versions: {},
chooserOpen: false,
+ chooserMode: "select",
editorOpen: false,
editTarget: null,
editDirty: false,
@@ -230,6 +238,26 @@ export async function saveTemporary(id: string): Promise<void> {
selectConfig(id);
}
+/** Whether the chooser's Delete may remove `id` (user and temporary configurations; detected ones come back). */
+export function canDeleteConfig(id: string): boolean {
+ const { configs, temporary } = useRun.getState();
+ const config = configs.find((c) => c.id === id);
+ return !!config && (temporary.includes(id) || !config.detected);
+}
+
+/** Deletes a user or temporary configuration. */
+export async function deleteConfig(id: string): Promise<void> {
+ if (!canDeleteConfig(id)) return;
+ const { configs, temporary, selectedId } = useRun.getState();
+ if (selectedId === id) selectConfig(null);
+ if (temporary.includes(id)) {
+ useRun.setState({ configs: configs.filter((c) => c.id !== id), temporary: temporary.filter((t) => t !== id) });
+ persistTemporary();
+ return;
+ }
+ await saveUserConfigs(configs.filter((c) => !c.detected && !temporary.includes(c.id) && c.id !== id));
+}
+
/** Persists user configurations and reloads the merged list. */
export async function saveUserConfigs(user: RunConfig[]): Promise<void> {
await call(commands.runSaveConfigs(user.map((c) => ({ ...c, detected: false }))));
@@ -303,6 +331,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
flushHandle: null,
generation: 0,
lineListeners: [],
+ input: "",
};
return runtime;
}
@@ -323,13 +352,19 @@ export async function startRun(
} = {},
): Promise<RunSession | null> {
const state = useRun.getState();
- let session =
- (reuse ? state.sessions.find((s) => s.id === reuse) : undefined) ??
- state.sessions.find((s) => s.config.id === config.id && s.status !== "running" && s.status !== "starting");
- if (session && (session.status === "running" || session.status === "starting")) {
- if (workflowSettings().run.confirmRerun && !(await confirmRerun(session.config.name))) return null;
- await stopSession(session.id);
+ const busy = (s: RunSession) => s.status === "running" || s.status === "starting";
+ let session = reuse ? state.sessions.find((s) => s.id === reuse) : undefined;
+ // As in IDEA, a configuration that doesn't allow parallel
+ // runs asks before stopping its running instances; rerunning a tab restarts it without asking.
+ const others = config.allowParallel ? [] : state.sessions.filter((s) => s.config.id === config.id && busy(s) && s.id !== session?.id);
+ if (others.length) {
+ if (workflowSettings().run.confirmRerun && !(await confirmRerun(config.name, others.length + (session && busy(session) ? 1 : 0))))
+ return null;
+ await Promise.all(others.map((s) => stopSession(s.id)));
+ session ??= others[0];
}
+ if (session && busy(session)) await stopSession(session.id);
+ session ??= state.sessions.find((s) => s.config.id === config.id && !busy(s));
try {
await maybeEditorService()?.saveAll();
@@ -600,6 +635,19 @@ export function rerunFailed(sessionId: string): boolean {
return true;
}
+/** Whether the console takes typed input: the process runs and its stdin is open. */
+export function acceptsInput(session: RunSession): boolean {
+ return session.status === "running" && session.runId !== null && !session.stdinClosed;
+}
+
+/** Replaces the pending (typed, unsent) console input. */
+export function setPendingInput(sessionId: string, text: string) {
+ const rt = runtimes.get(sessionId);
+ if (!rt || rt.input === text) return;
+ rt.input = text;
+ bump(sessionId);
+}
+
export async function sendStdin(sessionId: string, text: string): Promise<void> {
const session = getSession(sessionId);
if (!session || session.runId === null || session.status !== "running") return;
@@ -666,6 +714,7 @@ export function resetRuns() {
activeSession: null,
versions: {},
chooserOpen: false,
+ chooserMode: "select",
editorOpen: false,
editTarget: null,
editDirty: false,
diff --git a/src/features/run/workflow.test.ts b/src/features/run/workflow.test.ts
index 15d24048e..825b8f286 100644
--- a/src/features/run/workflow.test.ts
+++ b/src/features/run/workflow.test.ts
@@ -24,18 +24,32 @@ describe("console settings", () => {
expect(m.dropped).toBeGreaterThan(0);
});
- it("folds runs of matching lines", () => {
+ it("folds runs of matching lines onto the previous line, single lines too", () => {
const m = new ConsoleModel();
m.append({ kind: "stderr", text: "Error\n at org.junit.A\n at org.junit.B\n at app.Main\n at org.junit.C\n" });
const rows = foldRows(m.lines, ["at org.junit."], new Set());
- expect(rows.map((r) => (r.kind === "fold" ? `fold${r.count}` : m.lines[r.index]!.text.trim()))).toEqual([
- "Error",
- "fold2",
- "at app.Main",
- "at org.junit.C",
- ]);
- const fold = rows.find((r) => r.kind === "fold")!;
- expect(foldRows(m.lines, ["at org.junit."], new Set([fold.kind === "fold" ? fold.id : 0])).length).toBe(5);
+ const show = (rs: typeof rows) =>
+ rs.map((r) => (r.kind === "fold" ? `fold${r.fold.count}` : m.lines[r.index]!.text.trim() + (r.fold ? ` +${r.fold.count}` : "")));
+ expect(show(rows)).toEqual(["Error +2", "at app.Main +1"]);
+ const first = rows[0]!.kind === "line" ? rows[0]!.fold! : null;
+ const open = foldRows(m.lines, ["at org.junit."], new Set([first!.id]));
+ expect(show(open)).toEqual(["Error +2", "at org.junit.A", "at org.junit.B", "at app.Main +1"]);
+ expect(open[0]!.kind === "line" && open[0]!.fold?.expanded).toBe(true);
+ });
+
+ it("keeps a fold with no line before it as a row of its own", () => {
+ const m = new ConsoleModel();
+ m.append({ kind: "stdout", text: " at org.junit.A\nok\n" });
+ const rows = foldRows(m.lines, ["at org.junit."], new Set());
+ expect(rows.map((r) => r.kind)).toEqual(["fold", "line"]);
+ });
+
+ it("exposes the open (prompt) line", () => {
+ const m = new ConsoleModel();
+ m.append({ kind: "stdout", text: "done\nName: " });
+ expect(m.openLine?.text).toBe("Name: ");
+ m.append({ kind: "stdout", text: "x\n" });
+ expect(m.openLine).toBeNull();
});
});
diff --git a/src/features/search/__tests__/dialogs.test.tsx b/src/features/search/__tests__/dialogs.test.tsx
index c35f1c64a..2ede39e59 100644
--- a/src/features/search/__tests__/dialogs.test.tsx
+++ b/src/features/search/__tests__/dialogs.test.tsx
@@ -134,9 +134,23 @@ describe("Search Everywhere dialog", () => {
fireEvent.keyDown(input, { key: "Tab", shiftKey: true });
fireEvent.keyDown(input, { key: "Tab", shiftKey: true });
expect(useSearchEverywhere.getState().tab).toBe("text");
- act(() => showSearchEverywhere("all", { toggleOnRepeat: true }));
+ // Double Shift on another tab switches to All, keeping the query; on All it toggles the scope.
+ fireEvent.change(input, { target: { value: "kept" } });
+ act(() => showSearchEverywhere("all", { query: "selection" }));
+ expect(useSearchEverywhere.getState()).toMatchObject({ tab: "all", query: "kept", includeNonProject: false });
+ act(() => showSearchEverywhere("all"));
expect(useSearchEverywhere.getState().includeNonProject).toBe(true);
});
+
+ it("searches everywhere when nothing is found in the project", async () => {
+ render(<SearchEverywhereOverlay />);
+ act(() => showSearchEverywhere("symbols", { query: "zzz" }));
+ await tick();
+ expect(useSearchEverywhere.getState()).toMatchObject({ includeNonProject: true, notFound: "zzz" });
+ // A query that no longer contains the not-found one narrows back to the project.
+ fireEvent.change(screen.getByLabelText("Search query"), { target: { value: "other" } });
+ expect(useSearchEverywhere.getState()).toMatchObject({ includeNonProject: false, notFound: null });
+ });
});
describe("Find in Files dialog", () => {
diff --git a/src/features/search/__tests__/recent.test.ts b/src/features/search/__tests__/recent.test.ts
index 3e1001f8b..c1e1c3d1e 100644
--- a/src/features/search/__tests__/recent.test.ts
+++ b/src/features/search/__tests__/recent.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it } from "vitest";
import type { ToolWindowContribution } from "@/workbench/contributions";
import { fromNavigationHistory, recordLocation, renameLocations, type RecentLocation } from "../common/locations";
-import { filterLocations, filterRecentFiles, initialFileIndex, switcherToolWindows } from "../recent/model";
+import {
+ filterLocations,
+ filterRecentFiles,
+ initialFileIndex,
+ switcherPaths,
+ switcherSelection,
+ switcherToolWindows,
+} from "../recent/model";
const loc = (path: string, line: number, extra: Partial<RecentLocation> = {}): RecentLocation => ({
path,
@@ -66,6 +73,19 @@ describe("recent files switcher", () => {
expect(initialFileIndex(items, "/p/src/Main.kt", "m")).toBe(0);
});
+ it("lists only open files in the switcher, most recent first", () => {
+ expect(switcherPaths(["/c", "/x", "/a", "/c"], ["/a", "/b", "/c"])).toEqual(["/c", "/a", "/b"]);
+ });
+
+ it("moves the switcher selection past the end of the files into the tool windows", () => {
+ expect(switcherSelection(1, 0, 3, 2)).toEqual({ column: "files", index: 1 });
+ expect(switcherSelection(1, 2, 3, 2)).toEqual({ column: "tools", index: 0 });
+ expect(switcherSelection(1, 4, 3, 2)).toEqual({ column: "files", index: 0 });
+ expect(switcherSelection(0, -1, 3, 2)).toEqual({ column: "tools", index: 1 });
+ expect(switcherSelection(3, -1, 3, 2)).toEqual({ column: "files", index: 2 });
+ expect(switcherSelection(0, 0, 0, 0)).toBeNull();
+ });
+
it("orders tool windows by stripe", () => {
const tw = (id: string, anchor: ToolWindowContribution["anchor"], order: number, extra: Partial<ToolWindowContribution> = {}) =>
({ id, title: id, icon: "folder", anchor, order, component: () => null, ...extra }) as ToolWindowContribution;
diff --git a/src/features/search/everywhere/SearchEverywhere.tsx b/src/features/search/everywhere/SearchEverywhere.tsx
index dc4daaba8..f8d6a76ba 100644
--- a/src/features/search/everywhere/SearchEverywhere.tsx
+++ b/src/features/search/everywhere/SearchEverywhere.tsx
@@ -44,11 +44,15 @@ import {
} from "./model";
import {
hideSearchEverywhere,
+ onSearchEverywhereQuery,
pushRecentAction,
pushSearchHistory,
searchHistory,
+ selectSearchEverywhereTab,
+ setIncludeNonProject,
setSearchEverywherePreview,
useSearchEverywhere,
+ widenSearchEverywhere,
} from "./store";
import styles from "./SearchEverywhere.module.css";
@@ -133,6 +137,8 @@ function SearchEverywhereDialog() {
inputRef.current?.select();
}, [session]);
+ useEffect(() => onSearchEverywhereQuery(query), [query]);
+
const parsed = useMemo(() => parseLocationQuery(searchQuery), [searchQuery]);
// The All tab interleaves its sources by relevance once there is a query.
const mix = tab === "all" ? parsed.text : undefined;
@@ -156,7 +162,8 @@ function SearchEverywhereDialog() {
const setQuery = (value: string) => {
history.current.pos = -1;
const c = parseCommand(value);
- useSearchEverywhere.setState(c?.kind === "run" ? { tab: c.tab, query: c.rest } : { query: value });
+ if (c?.kind === "run") selectSearchEverywhereTab(c.tab, { query: c.rest });
+ else useSearchEverywhere.setState({ query: value });
};
const browseHistory = (dir: 1 | -1) => {
const h = searchHistory(tab);
@@ -179,7 +186,7 @@ function SearchEverywhereDialog() {
};
const setTab = (t: SeTab) => {
history.current.pos = -1;
- useSearchEverywhere.setState({ tab: t });
+ selectSearchEverywhereTab(t);
inputRef.current?.focus();
};
const cycleTab = (dir: 1 | -1) => {
@@ -202,7 +209,7 @@ function SearchEverywhereDialog() {
case "section":
return;
case "command":
- useSearchEverywhere.setState({ tab: row.tab, query: "" });
+ selectSearchEverywhereTab(row.tab, { query: "" });
inputRef.current?.focus();
return;
case "more": {
@@ -313,6 +320,18 @@ function SearchEverywhereDialog() {
const previewTarget = previewOf(activeRow);
const emptyQuery = !parsed.text.trim();
const showEmpty = !rows.length && snap && !snap.loading && (!emptyQuery || tab !== "all");
+ // Nothing in the project: retry everywhere (IDEA), unless the user picked the scope.
+ const nothingInProject =
+ !!showEmpty &&
+ !emptyQuery &&
+ !listing &&
+ !includeNonProject &&
+ query === debounced &&
+ snap.query === searchQuery &&
+ snap.tab === tab;
+ useEffect(() => {
+ if (nothingInProject) widenSearchEverywhere(searchQuery);
+ }, [nothingInProject, searchQuery]);
const canSplit = activeRow?.kind === "file" || activeRow?.kind === "symbol" || activeRow?.kind === "text";
const onTabKey = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
@@ -352,7 +371,7 @@ function SearchEverywhereDialog() {
className={styles.include}
checked={includeNonProject}
onChange={(v) => {
- useSearchEverywhere.setState({ includeNonProject: v });
+ setIncludeNonProject(v);
inputRef.current?.focus();
}}
label="Include non-project items"
@@ -365,9 +384,8 @@ function SearchEverywhereDialog() {
value={includeNonProject ? "allPlaces" : fileSet}
options={SE_SCOPES}
onChange={(v) => {
- useSearchEverywhere.setState(
- v === "allPlaces" ? { includeNonProject: true } : { includeNonProject: false, fileSet: v },
- );
+ if (v === "allPlaces") setIncludeNonProject(true);
+ else setIncludeNonProject(false, { fileSet: v });
inputRef.current?.focus();
}}
aria-label="Search scope"
diff --git a/src/features/search/everywhere/store.ts b/src/features/search/everywhere/store.ts
index 43a5b90bd..d0efefa29 100644
--- a/src/features/search/everywhere/store.ts
+++ b/src/features/search/everywhere/store.ts
@@ -17,6 +17,12 @@ interface SeState {
session: number;
/** Code preview of the selected result under the list (remembered). */
preview: boolean;
+ /**
+ * IDEA's auto "everywhere": while the user hasn't picked a scope, a query
+ * with no project results widens to non-project items; `notFound` is that query.
+ */
+ autoEverywhere: boolean;
+ notFound: string | null;
}
const PREVIEW_KEY = "openidea.search.everywherePreview.v1";
@@ -30,6 +36,8 @@ export const useSearchEverywhere = create<SeState>(() => ({
ctx: {},
session: 0,
preview: loadJson<unknown>(PREVIEW_KEY, false) === true,
+ autoEverywhere: true,
+ notFound: null,
}));
export function setSearchEverywherePreview(preview: boolean) {
@@ -37,16 +45,15 @@ export function setSearchEverywherePreview(preview: boolean) {
saveJson(PREVIEW_KEY, preview);
}
-/** Opens (or re-targets) the dialog. Re-invoking the same scope toggles "include non-project items", like IDEA. */
-export function showSearchEverywhere(tab: SeTab, opts: { query?: string; toggleOnRepeat?: boolean } = {}) {
+/**
+ * Opens the dialog, or while it is open switches to `tab` (the query is kept);
+ * re-invoking the shown tab toggles "include non-project items", like IDEA.
+ */
+export function showSearchEverywhere(tab: SeTab, opts: { query?: string } = {}) {
const s = useSearchEverywhere.getState();
if (s.open) {
- if (s.tab === tab || (opts.toggleOnRepeat && tab === "all")) {
- useSearchEverywhere.setState({ includeNonProject: !s.includeNonProject });
- } else {
- useSearchEverywhere.setState({ tab });
- }
- if (opts.query !== undefined) useSearchEverywhere.setState({ query: opts.query });
+ if (s.tab === tab) setIncludeNonProject(!s.includeNonProject);
+ else selectSearchEverywhereTab(tab);
return;
}
useSearchEverywhere.setState({
@@ -54,11 +61,40 @@ export function showSearchEverywhere(tab: SeTab, opts: { query?: string; toggleO
tab,
query: opts.query ?? s.query,
includeNonProject: false,
+ autoEverywhere: true,
+ notFound: null,
ctx: { ...getContext(), popupOpen: false },
session: s.session + 1,
});
}
+/** The user's choice of scope: stops widening automatically. */
+export function setIncludeNonProject(includeNonProject: boolean, patch: Partial<SeState> = {}) {
+ useSearchEverywhere.setState({ ...patch, includeNonProject, autoEverywhere: false, notFound: null });
+}
+
+/** Switching tabs drops an automatically widened scope. */
+export function selectSearchEverywhereTab(tab: SeTab, patch: Partial<SeState> = {}) {
+ const s = useSearchEverywhere.getState();
+ const reset = s.autoEverywhere && s.notFound !== null ? { includeNonProject: false, notFound: null } : {};
+ useSearchEverywhere.setState({ ...patch, ...reset, tab });
+}
+
+/** Nothing in the project for `query`: search everywhere instead (as IDEA). */
+export function widenSearchEverywhere(query: string) {
+ const s = useSearchEverywhere.getState();
+ if (!s.autoEverywhere || s.includeNonProject || !query.trim()) return;
+ useSearchEverywhere.setState({ includeNonProject: true, notFound: query });
+}
+
+/** A new query that no longer contains the not-found one narrows back to the project. */
+export function onSearchEverywhereQuery(query: string) {
+ const s = useSearchEverywhere.getState();
+ if (s.notFound === null || !s.autoEverywhere || !s.includeNonProject) return;
+ if (s.notFound.length > 1 && query.includes(s.notFound)) return;
+ useSearchEverywhere.setState({ includeNonProject: false, notFound: null });
+}
+
export function hideSearchEverywhere() {
useSearchEverywhere.setState({ open: false });
}
diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx
index c62a00e30..f109460ac 100644
--- a/src/features/search/find/FindInFiles.tsx
+++ b/src/features/search/find/FindInFiles.tsx
@@ -362,6 +362,8 @@ function FindInFilesDialog() {
width={820}
position="top"
transparentBackdrop
+ // IDEA's Find in Files is a modeless dialog: it survives switching to another app.
+ closeOnDeactivate={false}
aria-label={s.replace ? "Replace in Files" : "Find in Files"}
className={styles.dialog}
>
diff --git a/src/features/search/index.ts b/src/features/search/index.ts
index 47a344278..cb97a80d6 100644
--- a/src/features/search/index.ts
+++ b/src/features/search/index.ts
@@ -71,7 +71,7 @@ function jumpBookmark(dir: 1 | -1) {
export function activate(): void | (() => void) {
const se = (tab: Parameters<typeof showSearchEverywhere>[0]) => () => {
closeAllPopups("everywhere");
- showSearchEverywhere(tab, { query: editorSelectionText() ?? undefined, toggleOnRepeat: tab === "all" });
+ showSearchEverywhere(tab, { query: editorSelectionText() ?? undefined });
};
const disposers: Array<() => void> = [
@@ -87,6 +87,8 @@ export function activate(): void | (() => void) {
title: "Structure",
icon: "toolwindow-structure",
anchor: "left",
+ // Left Bottom (split), as in IDEA: shows below Project.
+ secondary: true,
order: 20,
component: lazyComponent(() => import("./structure/StructureView").then((m) => m.StructureView)),
}),
@@ -94,8 +96,9 @@ export function activate(): void | (() => void) {
id: "bookmarks",
title: "Bookmarks",
icon: "toolwindow-bookmarks",
- // Same anchor as Project/Structure, so it sits in their stripe group (the lower group holds bottom windows).
+ // Left Bottom (split) with Structure, as in IDEA.
anchor: "left",
+ secondary: true,
order: 30,
component: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksView)),
headerActions: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksActions)),
diff --git a/src/features/search/recent/RecentPopups.module.css b/src/features/search/recent/RecentPopups.module.css
index faca7c8bb..516d326fd 100644
--- a/src/features/search/recent/RecentPopups.module.css
+++ b/src/features/search/recent/RecentPopups.module.css
@@ -74,6 +74,7 @@
display: flex;
height: 440px;
min-height: 0;
+ outline: none;
}
.tools {
flex: none;
diff --git a/src/features/search/recent/RecentPopups.tsx b/src/features/search/recent/RecentPopups.tsx
index d13ccaf20..43ec38d3a 100644
--- a/src/features/search/recent/RecentPopups.tsx
+++ b/src/features/search/recent/RecentPopups.tsx
@@ -19,6 +19,8 @@ import {
filterLocations,
filterRecentFiles,
initialFileIndex,
+ switcherPaths,
+ switcherSelection,
switcherToolWindows,
type RecentFileItem,
} from "./model";
@@ -27,7 +29,8 @@ import styles from "./RecentPopups.module.css";
export function RecentPopupsOverlay() {
const open = useRecentPopup((s) => s.open);
- if (open === "files") return <RecentFilesDialog />;
+ const session = useRecentPopup((s) => s.session);
+ if (open === "files") return <RecentFilesDialog key={session} />;
if (open === "locations") return <RecentLocationsDialog />;
return null;
}
@@ -41,7 +44,7 @@ const afterClose = (fn: () => void) => {
};
// ---------------------------------------------------------------------------
-// ⌘E — Switcher
+// ⌘E — Recent Files; ⌃⇥ — Switcher (open editors only, no speed search)
function RecentFilesDialog() {
const editedOnly = useRecentPopup((s) => s.editedOnly);
@@ -51,6 +54,7 @@ function RecentFilesDialog() {
const root = useProject((s) => s.project?.root ?? null);
const toolWindows = useContributions((s) => s.toolWindows);
const [paths, setPaths] = useState<string[] | null>(null);
+ const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set());
const [query, setQuery] = useState("");
const [column, setColumn] = useState<"files" | "tools">("files");
const [fileIndex, setFileIndex] = useState<number | null>(null);
@@ -60,17 +64,26 @@ function RecentFilesDialog() {
useEffect(() => {
let alive = true;
+ const openNow = () => maybeEditorService()?.openPaths?.() ?? [];
call(commands.recentFiles())
- .then((p) => alive && setPaths(p.map(String)))
- .catch(() => alive && setPaths([]));
+ .then((p) => {
+ const recent = p.map(String);
+ if (alive) setPaths(switcher ? switcherPaths(recent, openNow()) : recent);
+ })
+ .catch(() => alive && setPaths(switcher ? openNow() : []));
return () => {
alive = false;
};
- }, []);
+ }, [switcher]);
const files = useMemo(
- () => filterRecentFiles(paths ?? [], query, { root, edited, editedOnly }),
- [paths, query, root, edited, editedOnly],
+ () =>
+ filterRecentFiles(
+ (paths ?? []).filter((p) => !removed.has(p)),
+ query,
+ { root, edited, editedOnly },
+ ),
+ [paths, removed, query, root, edited, editedOnly],
);
const tools = useMemo(() => switcherToolWindows(toolWindows.values(), !!root, query), [toolWindows, root, query]);
const fIndex = files.length
@@ -87,16 +100,37 @@ function RecentFilesDialog() {
if (tw) afterClose(() => toolWindowService().show(tw.id, true));
};
- // Switcher: each ⌃⇥ moves one row (wrapping); releasing Ctrl opens the selection.
+ // IDEA: Delete closes the selected editor (and drops it from the list) or hides the tool window.
+ const removeSelected = () => {
+ if (effectiveColumn === "tools") {
+ const tw = tools[tIndex]?.tw;
+ if (tw) toolWindowService().hide(tw.id);
+ return;
+ }
+ const item = files[fIndex];
+ if (!item) return;
+ maybeEditorService()?.closePath?.(item.path);
+ if (!switcher) void call(commands.removeRecent(item.path)).catch(() => {});
+ setRemoved((r) => new Set(r).add(item.path));
+ setFileIndex(fIndex);
+ };
+
+ // Switcher: each ⌃⇥ moves one row, past the end into the other column; releasing Ctrl opens the selection.
const baseIndex = useRef<number | null>(null);
+ const loaded = paths !== null;
useEffect(() => {
- if (!switcher || !files.length || query) return;
- baseIndex.current ??= step < 0 ? 0 : initialFileIndex(files, activePath, "");
- const n = files.length;
- // eslint-disable-next-line react-hooks/set-state-in-effect -- the switcher step is an external event
- setColumn("files");
- setFileIndex((((baseIndex.current + step) % n) + n) % n);
- }, [switcher, step, files, activePath, query]);
+ if (!switcher || !loaded) return;
+ // ⌃⇥ starts on the previous file, ⌃⇧⇥ on the oldest one.
+ baseIndex.current ??= step < 0 ? files.length : Math.max(0, initialFileIndex(files, activePath, ""));
+ const sel = switcherSelection(baseIndex.current, step, files.length, tools.length);
+ if (!sel) return;
+ // The switcher step is an external event (⌃⇥ pressed again).
+ setColumn(sel.column);
+ if (sel.column === "files") setFileIndex(sel.index);
+ else setToolIndex(sel.index);
+ // Only a new ⌃⇥ press moves the selection, not list changes (Delete).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [switcher, step, loaded]);
const selected = effectiveColumn === "files" ? files[fIndex] : undefined;
const selectedTool = effectiveColumn === "tools" ? tools[tIndex]?.tw : undefined;
useEffect(() => {
@@ -111,7 +145,7 @@ function RecentFilesDialog() {
return () => window.removeEventListener("keyup", onKeyUp, true);
});
- const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
if (e.key === "Enter") {
e.preventDefault();
if (effectiveColumn === "files") openFile(files[fIndex], e.shiftKey);
@@ -124,6 +158,12 @@ function RecentFilesDialog() {
cycleSwitcher(e.shiftKey ? -1 : 1);
return;
}
+ // In Recent Files Backspace edits the speed search text first.
+ if (e.key === "Delete" || (e.key === "Backspace" && !query)) {
+ e.preventDefault();
+ removeSelected();
+ return;
+ }
if (e.key === "Tab" || ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !query)) {
e.preventDefault();
e.stopPropagation();
@@ -151,40 +191,51 @@ function RecentFilesDialog() {
const recentShortcut = shortcutLabel("navigate.recentFiles");
const locationsShortcut = shortcutLabel("navigate.recentLocations");
- const title = editedOnly ? "Recently Edited Files" : "Recent Files";
+ const title = switcher ? "Switcher" : editedOnly ? "Recently Edited Files" : "Recent Files";
const footerPath = selected?.path ?? (selectedTool ? "" : (root ?? ""));
return (
- <Dialog open onClose={hideRecentPopup} width={720} aria-label="Recent Files" className={styles.dialog}>
+ <Dialog open onClose={hideRecentPopup} width={720} aria-label={title} className={styles.dialog}>
<header className={styles.header}>
- <span className={styles.title}>{title}</span>
- <span className={clsx(styles.speed, query && styles.speedActive)}>
- <Icon name="search" size={14} className={styles.filterIcon} />
- <input
- ref={inputRef}
- data-autofocus
- className={styles.filter}
- value={query}
- spellCheck={false}
- autoComplete="off"
- aria-label="Filter recent files"
- onChange={(e) => {
- setQuery(e.target.value);
- setFileIndex(null);
- setToolIndex(0);
- }}
- onKeyDown={onKeyDown}
- />
+ <span className={styles.title}>
+ <T>{title}</T>
</span>
- <Checkbox
- checked={editedOnly}
- onChange={() => {
- showRecentPopup("files");
- inputRef.current?.focus();
- }}
- label={<>Show edited only {recentShortcut && <span className={styles.hint}>{recentShortcut}</span>}</>}
- />
+ {!switcher && (
+ <>
+ <span className={clsx(styles.speed, query && styles.speedActive)}>
+ <Icon name="search" size={14} className={styles.filterIcon} />
+ <input
+ ref={inputRef}
+ data-autofocus
+ className={styles.filter}
+ value={query}
+ spellCheck={false}
+ autoComplete="off"
+ aria-label="Filter recent files"
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setFileIndex(null);
+ setToolIndex(0);
+ }}
+ onKeyDown={onKeyDown}
+ />
+ </span>
+ <Checkbox
+ checked={editedOnly}
+ onChange={() => {
+ showRecentPopup("files");
+ inputRef.current?.focus();
+ }}
+ label={<>Show edited only {recentShortcut && <span className={styles.hint}>{recentShortcut}</span>}</>}
+ />
+ </>
+ )}
</header>
- <div className={styles.columns}>
+ <div
+ className={styles.columns}
+ tabIndex={switcher ? -1 : undefined}
+ data-autofocus={switcher ? "" : undefined}
+ onKeyDown={switcher ? onKeyDown : undefined}
+ >
<div className={styles.tools}>
<List
items={tools}
@@ -200,16 +251,18 @@ function RecentFilesDialog() {
aria-label="Tool windows"
renderItem={(t) => <ToolRow tw={t.tw} indices={t.indices} />}
/>
- <button
- type="button"
- className={styles.locationsLink}
- onClick={() => afterClose(() => showRecentPopup("locations"))}
- >
- <span className={styles.name}>
- <T>Recent Locations</T>
- </span>
- {locationsShortcut && <span className={styles.shortcut}>{locationsShortcut}</span>}
- </button>
+ {!switcher && (
+ <button
+ type="button"
+ className={styles.locationsLink}
+ onClick={() => afterClose(() => showRecentPopup("locations"))}
+ >
+ <span className={styles.name}>
+ <T>Recent Locations</T>
+ </span>
+ {locationsShortcut && <span className={styles.shortcut}>{locationsShortcut}</span>}
+ </button>
+ )}
</div>
<div className={styles.files}>
<List
@@ -223,9 +276,19 @@ function RecentFilesDialog() {
onActivate={(f, _i, e) => openFile(f, e.shiftKey)}
focusable={false}
rowHeight={24}
- aria-label="Recent files"
+ aria-label={switcher ? "Open files" : "Recent files"}
empty={
- paths && <span>{editedOnly ? "No edited files" : query ? "No matching files" : "No recent files"}</span>
+ paths && (
+ <span>
+ {switcher
+ ? "No open files"
+ : editedOnly
+ ? "No edited files"
+ : query
+ ? "No matching files"
+ : "No recent files"}
+ </span>
+ )
}
renderItem={(f) => <RecentFileRow item={f} current={f.path === activePath} />}
/>
diff --git a/src/features/search/recent/model.ts b/src/features/search/recent/model.ts
index 221864d67..ba333139d 100644
--- a/src/features/search/recent/model.ts
+++ b/src/features/search/recent/model.ts
@@ -43,6 +43,31 @@ export function initialFileIndex(items: readonly RecentFileItem[], activePath: s
return 0;
}
+/** Switcher (⌃⇥) files: only open editors, most recently opened first. */
+export function switcherPaths(recent: readonly string[], open: readonly string[]): string[] {
+ const isOpen = new Set(open);
+ const out = [...new Set(recent.filter((p) => isOpen.has(p)))];
+ const listed = new Set(out);
+ for (const p of open) if (!listed.has(p)) out.push(p);
+ return out;
+}
+
+/**
+ * Switcher selection `step` rows away from file row `base`: moving past the end
+ * of one column continues in the other (files, then tool windows), like IDEA.
+ */
+export function switcherSelection(
+ base: number,
+ step: number,
+ files: number,
+ tools: number,
+): { column: "files" | "tools"; index: number } | null {
+ const n = files + tools;
+ if (!n) return null;
+ const at = (((base + step) % n) + n) % n;
+ return at < files ? { column: "files", index: at } : { column: "tools", index: at - files };
+}
+
const ANCHOR_ORDER = { left: 0, bottom: 1, right: 2 } as const;
export function switcherToolWindows(
diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx
index 775e66a1a..8f894c254 100644
--- a/src/features/settings/__tests__/dialog.test.tsx
+++ b/src/features/settings/__tests__/dialog.test.tsx
@@ -76,6 +76,20 @@ describe("Settings dialog", () => {
expect(dialog.querySelectorAll("mark").length).toBeGreaterThan(0);
});
+ it("Esc in the search field clears the filter first; ↓ selects the next page keeping the focus", async () => {
+ const dialog = await openDialog("appearance");
+ const search = within(dialog).getByLabelText("Search settings");
+ fireEvent.change(search, { target: { value: "soft wrap" } });
+ fireEvent.keyDown(search, { key: "Escape" });
+ expect((search as HTMLInputElement).value).toBe("");
+ expect(screen.getByRole("dialog", { name: "Settings" })).toBeInTheDocument();
+ const before = useSettingsDialog.getState().pageId;
+ search.focus();
+ fireEvent.keyDown(search, { key: "ArrowDown" });
+ expect(useSettingsDialog.getState().pageId).not.toBe(before);
+ expect(document.activeElement).toBe(search);
+ });
+
it("stages edits and writes them on Apply", async () => {
const dialog = await openDialog("editor.general");
fireEvent.click(within(dialog).getByRole("checkbox", { name: /Soft-wrap files/ }));
diff --git a/src/features/settings/dialog/SettingsDialog.tsx b/src/features/settings/dialog/SettingsDialog.tsx
index 4ded82ddd..cfab080ef 100644
--- a/src/features/settings/dialog/SettingsDialog.tsx
+++ b/src/features/settings/dialog/SettingsDialog.tsx
@@ -239,9 +239,14 @@ export function SettingsLayout() {
placeholder=""
aria-label="Search settings"
onKeyDown={(e) => {
- if (e.key === "ArrowDown") {
+ // IDEA: Esc clears the filter before it closes the dialog; ↑/↓ move through the pages, focus stays here.
+ if (e.key === "Escape" && query) {
e.preventDefault();
- treeRef.current?.focus();
+ e.stopPropagation();
+ onQuery("");
+ } else if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !e.altKey && !e.metaKey && !e.ctrlKey) {
+ e.preventDefault();
+ treeRef.current?.moveSelection(e.key === "ArrowDown" ? 1 : -1);
}
}}
/>
diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx
index ecfddcabd..3b79ee85f 100644
--- a/src/features/settings/pages/editor/codeStyle.tsx
+++ b/src/features/settings/pages/editor/codeStyle.tsx
@@ -8,7 +8,7 @@
import { useId, useState } from "react";
import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
-import { ENCODING_CHOICES, type LanguageCodeStyle } from "@/platform/editorSettings";
+import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
import { NumberInput, Row } from "../../components/Form";
import { useSetting } from "../../components/context";
import type { PageSpec } from "../spec";
@@ -127,6 +127,8 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
tabSize: own.tabSize ?? base.tabSize,
indent: own.indent ?? own.tabSize ?? base.tabSize,
hardWrapAt: own.hardWrapAt ?? wrap,
+ lineCommentAtFirstColumn: own.lineCommentAtFirstColumn ?? lineCommentDefaults(lang.id).atFirstColumn,
+ lineCommentAddSpace: own.lineCommentAddSpace ?? lineCommentDefaults(lang.id).addSpace,
};
const set = (patch: Partial<LanguageCodeStyle>) => {
const next = { ...own, ...patch };
@@ -183,6 +185,27 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
/>
</Row>
</section>
+ {lang.lineComment && (
+ <section aria-label="Comment Code">
+ <div className={styles.previewTitle}>
+ <T>Comment Code</T>
+ </div>
+ <div className={styles.check}>
+ <Checkbox
+ checked={eff.lineCommentAtFirstColumn}
+ onChange={(v) => set({ lineCommentAtFirstColumn: v })}
+ label="Line comment at first column"
+ />
+ </div>
+ <div className={styles.check}>
+ <Checkbox
+ checked={eff.lineCommentAddSpace}
+ onChange={(v) => set({ lineCommentAddSpace: v })}
+ label="Add a space at line comment start"
+ />
+ </div>
+ </section>
+ )}
<div className={styles.schemeRow}>
<Button size="small" disabled={!all?.[lang.id]} onClick={reset}>
<T>Reset to Language Defaults</T>
@@ -209,7 +232,7 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
group: "Editor",
order: 100,
projectScope: true,
- keywords: ["Tabs and Indents", "Tab size", "Indent", "Use tab character", "Hard wrap at"],
+ keywords: ["Tabs and Indents", "Tab size", "Indent", "Use tab character", "Hard wrap at", "Comment Code", "Line comment at first column"],
component: () => <LanguageStyle lang={lang} />,
}));
}
diff --git a/src/features/settings/pages/editor/general.tsx b/src/features/settings/pages/editor/general.tsx
index 221ff5f5c..5e35c2c9f 100644
--- a/src/features/settings/pages/editor/general.tsx
+++ b/src/features/settings/pages/editor/general.tsx
@@ -504,6 +504,7 @@ const SMART_KEYS = editorPage({
key: `${P}.smartKeys.backspaceUnindent`,
label: "Unindent",
options: [
+ { value: "autoindent", label: "To proper indent position" },
{ value: "nearest", label: "To nearest indent position" },
{ value: "none", label: "Disabled" },
],
diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx
index 35934d22a..d015a4f6d 100644
--- a/src/features/terminal/TerminalView.tsx
+++ b/src/features/terminal/TerminalView.tsx
@@ -18,12 +18,12 @@ import {
type TabItem,
} from "@/ui";
import {
- closePane,
- closeTab,
getSession,
newTab,
publishFocus,
renameTab,
+ requestClosePane,
+ requestCloseTab,
selectTab,
tabTitle,
useTerminals,
@@ -92,7 +92,7 @@ function paneMenu(e: MouseEvent, key: string) {
{ kind: "separator" },
{ kind: "action", action: "terminal.splitRight" },
{ kind: "action", action: "terminal.splitDown" },
- { label: "Close Session", icon: "close", run: () => closePane(key) },
+ { label: "Close Session", icon: "close", run: () => void requestClosePane(key) },
];
if (exited)
items.splice(
@@ -241,10 +241,9 @@ export function TerminalTabs() {
};
});
- const onClose = (id: string) => {
- const last = tabs.length === 1;
- closeTab(id);
- if (last) toolWindowService().hide("terminal");
+ const onClose = async (id: string) => {
+ if (!(await requestCloseTab(id))) return;
+ if (useTerminals.getState().tabs.length === 0) toolWindowService().hide("terminal");
};
const tabMenu = (id: string, e: MouseEvent) => {
@@ -253,11 +252,13 @@ export function TerminalTabs() {
showContextMenu(e, [
{ label: "Rename Session…", icon: "edit", run: () => setRenaming({ id, anchor }) },
{ kind: "separator" },
- { label: "Close Tab", icon: "close", run: () => onClose(id) },
+ { label: "Close Tab", icon: "close", run: () => void onClose(id) },
{
label: "Close Other Tabs",
disabled: tabs.length < 2,
- run: () => tabs.filter((t) => t.id !== id).forEach((t) => closeTab(t.id)),
+ run: async () => {
+ for (const t of tabs.filter((x) => x.id !== id)) if (!(await requestCloseTab(t.id))) return;
+ },
},
]);
};
@@ -301,7 +302,7 @@ export function TerminalTabs() {
if (tab) getSession(tab.activePane)?.focus();
});
}}
- onClose={onClose}
+ onClose={(id) => void onClose(id)}
onContextMenu={tabMenu}
panelIdPrefix={TAB_PREFIX}
trailing={
diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts
index ae1c30df2..66ba36f37 100644
--- a/src/features/terminal/index.ts
+++ b/src/features/terminal/index.ts
@@ -45,7 +45,6 @@ export function activate(): () => void {
icon: "toolwindow-terminal",
anchor: "bottom",
order: 10,
- secondary: true,
component: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalView)),
headerContent: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalTabs)),
}),
@@ -163,11 +162,11 @@ export function activate(): () => void {
const rt = terminalRuntime();
const s = rt?.activeSession();
if (!rt || !s) return;
- const { tabs } = rt.useTerminals.getState();
- const last = tabs.length === 1 && tabs[0]!.panes.length === 1;
- rt.closePane(s.key);
- if (last) toolWindowService().hide(WINDOW);
- else focusActiveSoon();
+ void rt.requestClosePane(s.key).then((closed) => {
+ if (!closed) return;
+ if (rt.useTerminals.getState().tabs.length === 0) toolWindowService().hide(WINDOW);
+ else focusActiveSoon();
+ });
},
},
]),
diff --git a/src/features/terminal/keys.ts b/src/features/terminal/keys.ts
index 8245bb454..bd77624f7 100644
--- a/src/features/terminal/keys.ts
+++ b/src/features/terminal/keys.ts
@@ -5,12 +5,17 @@
* ⌘W, ⌘F (find) and ⌘/⌥ arrow navigation, and Ctrl+Shift+C / V (copy / paste
* on Windows and Linux, where Ctrl+C must reach the shell).
*
+ * With "Override IDE shortcuts" on, a Ctrl or Escape stroke still reaches the IDE when the
+ * keymap binds it to one of IDEA's terminal-allowed actions (Find Action, Go to
+ * File…).
+ *
* Registered on `window` in the capture phase during feature activation, i.e.
* before `installKeyboardDispatcher`, so `stopImmediatePropagation` keeps the
* dispatcher from seeing these strokes. Until the terminal runtime has loaded
* there is no terminal, so there is nothing to handle.
*/
import { executeAction } from "@/platform/actions";
+import { effectiveBindings, strokeOf } from "@/platform/keymap";
import { workflowSettings } from "@/platform/workflowSettings";
import { terminalRuntime } from "./loader";
@@ -21,6 +26,7 @@ export type TerminalKeyResult =
| { kind: "clear" }
| { kind: "close" }
| { kind: "find" }
+ | { kind: "clearSelection" }
| { kind: "pass" };
type KeyLike = Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;
@@ -62,10 +68,63 @@ export function terminalKeyAction(e: KeyLike, hasSelection: boolean): TerminalKe
if (e.code === "Space") return { kind: "send", data: "\x00" };
return { kind: "pass" };
}
- if (!meta && !ctrl && !alt && e.key === "Escape") return { kind: "send", data: "\x1b" };
+ if (!meta && !ctrl && !alt && e.key === "Escape") {
+ // IDEA's Terminal.Escape: a selection is cleared first.
+ return hasSelection && !shift ? { kind: "clearSelection" } : { kind: "send", data: "\x1b" };
+ }
return { kind: "pass" };
}
+/**
+ * Actions whose shortcuts the terminal leaves to the IDE (the same set
+ * IDEA allows). Next/Previous
+ * Tab are left out as on Windows/Linux, where the shell needs those keys.
+ */
+const ALLOWED_ACTION_IDS = new Set([
+ "toolwindow.terminal",
+ "toolwindow.project",
+ "toolwindow.bookmarks",
+ "toolwindow.find",
+ "toolwindow.run",
+ "toolwindow.debug",
+ "toolwindow.problems",
+ "toolwindow.structure",
+ "toolwindow.services",
+ "toolwindow.commit",
+ "toolwindow.git",
+ "toolwindow.hideActive",
+ "toolwindow.hideAll",
+ "toolwindow.maximize",
+ "window.next",
+ "window.previous",
+ "navigate.showBookmarks",
+ "find.inPath",
+ "navigate.findAction",
+ "navigate.gotoFile",
+ "navigate.gotoClass",
+ "navigate.gotoSymbol",
+ "vcs.push",
+ "file.settings",
+ "navigate.recentFiles",
+ "navigate.switcher",
+ "navigate.switcherBack",
+ "terminal.new",
+ "terminal.find",
+ "terminal.clear",
+ "terminal.closeSession",
+ "terminal.splitRight",
+ "terminal.splitDown",
+]);
+
+/** Whether `stroke` starts a binding of an allowed action. */
+export function isAllowedIdeShortcut(stroke: string, bindings: ReadonlyArray<readonly [string, string]>): boolean {
+ return bindings.some(([binding, id]) => {
+ if (!ALLOWED_ACTION_IDS.has(id) || (binding !== stroke && !binding.startsWith(`${stroke} `))) return false;
+ // Ctrl+E stays with the shell (end of line), as in IDEA.
+ return !(id === "navigate.recentFiles" && stroke === "Ctrl+E");
+ });
+}
+
export function installTerminalKeys(target: Window = window): () => void {
const onKeyDown = (e: KeyboardEvent) => {
const rt = terminalRuntime();
@@ -87,6 +146,10 @@ export function installTerminalKeys(target: Window = window): () => void {
// keys it doesn't bind still get to xterm through its own key handling.
const t = workflowSettings().terminal;
if (action.kind === "send" && (e.ctrlKey || e.key === "Escape") && !t.overrideIdeShortcuts) return;
+ if (action.kind === "send" && (e.ctrlKey || e.key === "Escape")) {
+ const stroke = strokeOf(e);
+ if (stroke && isAllowedIdeShortcut(stroke, effectiveBindings())) return;
+ }
// "Move focus to the Editor with Escape": the IDE keymap's Escape (Focus Editor) runs instead.
if (action.kind === "send" && e.key === "Escape" && t.escapeToEditor) return;
switch (action.kind) {
@@ -102,6 +165,9 @@ export function installTerminalKeys(target: Window = window): () => void {
case "copy":
session.copySelection();
break;
+ case "clearSelection":
+ session.clearSelection();
+ break;
case "clear":
session.clear();
break;
diff --git a/src/features/terminal/runtime.ts b/src/features/terminal/runtime.ts
index 6e5938394..fe8bc152d 100644
--- a/src/features/terminal/runtime.ts
+++ b/src/features/terminal/runtime.ts
@@ -7,6 +7,7 @@ export {
closePane,
newTab,
newTabAt,
+ requestClosePane,
sessionForTerminalId,
sessionFromElement,
splitActive,
diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts
index ccdc84de2..ea59ef6a5 100644
--- a/src/features/terminal/session.ts
+++ b/src/features/terminal/session.ts
@@ -377,6 +377,22 @@ export class TerminalSession {
return this.ptyId;
}
+ /**
+ * Whether ending the session would kill something the user started (as IDEA
+ * judges it): a program run instead of a shell always counts;
+ * a shell counts while a command runs in it.
+ */
+ async isBusy(): Promise<boolean> {
+ if (this.snapshot.status !== "running" || this.ptyId === null) return false;
+ const custom = this.opts.command;
+ if (custom && !custom.shell) return true;
+ try {
+ return await call(commands.termIsBusy(this.ptyId));
+ } catch {
+ return false;
+ }
+ }
+
/** Called when the backend reports the PTY exited. */
exited(code: number | null) {
if (this.disposed) return;
@@ -426,6 +442,10 @@ export class TerminalSession {
this.term.paste(text);
}
+ clearSelection() {
+ this.term.clearSelection();
+ }
+
copySelection(): boolean {
const text = this.term.getSelection();
if (!text) return false;
diff --git a/src/features/terminal/store.ts b/src/features/terminal/store.ts
index bf92dce04..86af99763 100644
--- a/src/features/terminal/store.ts
+++ b/src/features/terminal/store.ts
@@ -4,8 +4,10 @@
*/
import { create } from "zustand";
import { setContext } from "@/platform/context";
+import { t } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
+import { confirm } from "@/workbench/messages";
import { TerminalSession, type SessionOptions, type SessionSnapshot } from "./session";
export type SplitOrientation = "horizontal" | "vertical";
@@ -138,6 +140,36 @@ export function closeTab(id: string) {
useTerminals.setState({ tabs: rest, activeTab: nextActive });
}
+/**
+ * Asks before ending sessions that are running a command, like IDEA
+ * (Terminate / Cancel). Resolves true to go ahead.
+ */
+export async function confirmEndSessions(keys: readonly string[], name: string): Promise<boolean> {
+ const busy = await Promise.all(keys.map((k) => sessions.get(k)?.isBusy() ?? false));
+ if (!busy.some(Boolean)) return true;
+ return confirm({
+ title: t("terminal.close.title", { name }),
+ message: t("terminal.close.message", { name }),
+ ok: t("terminal.close.terminate"),
+ });
+}
+
+/** User-initiated Close Tab: confirms first when a command is running. Resolves true if closed. */
+export async function requestCloseTab(id: string): Promise<boolean> {
+ const tab = useTerminals.getState().tabs.find((x) => x.id === id);
+ if (!tab || !(await confirmEndSessions(tab.panes, tabTitle(tab)))) return false;
+ closeTab(id);
+ return true;
+}
+
+/** User-initiated Close Session (one pane): confirms first when a command is running. */
+export async function requestClosePane(key: string): Promise<boolean> {
+ const tab = useTerminals.getState().tabs.find((x) => x.panes.includes(key));
+ if (!tab || !(await confirmEndSessions([key], tabTitle(tab)))) return false;
+ closePane(key);
+ return true;
+}
+
export function closeAll() {
for (const t of useTerminals.getState().tabs) t.panes.forEach(disposeSession);
useTerminals.setState({ tabs: [], activeTab: null, sessions: {} });
diff --git a/src/features/terminal/terminal.test.ts b/src/features/terminal/terminal.test.ts
index b3a4d1cf2..74e20f98f 100644
--- a/src/features/terminal/terminal.test.ts
+++ b/src/features/terminal/terminal.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { terminalKeyAction } from "./keys";
+import { isAllowedIdeShortcut, terminalKeyAction } from "./keys";
import { matchCounter } from "./FindBar";
import { buildSearchDecorations } from "./theme";
import { findTerminalLinks, resolvePath, trimUrl } from "./links";
@@ -132,6 +132,32 @@ describe("terminal keys", () => {
expect(terminalKeyAction(key({ key: "1", metaKey: true }), false)).toEqual({ kind: "pass" });
expect(terminalKeyAction(key({ key: "a" }), false)).toEqual({ kind: "pass" });
});
+
+ it("clears a selection with Escape before sending it", () => {
+ expect(terminalKeyAction(key({ key: "Escape" }), true)).toEqual({ kind: "clearSelection" });
+ expect(terminalKeyAction(key({ key: "Escape", shiftKey: true }), true)).toEqual({ kind: "send", data: "\x1b" });
+ });
+
+ it("lets shortcuts of IDEA's allowed actions reach the IDE", () => {
+ const bindings: Array<[string, string]> = [
+ ["Ctrl+Shift+A", "navigate.findAction"],
+ ["Ctrl+N", "navigate.gotoClass"],
+ ["Ctrl+E", "navigate.recentFiles"],
+ ["Ctrl+K", "vcs.commit"],
+ ["Ctrl+Shift+K", "vcs.push"],
+ ["Shift+Escape", "toolwindow.hideActive"],
+ ["Ctrl+W Ctrl+F", "terminal.find"],
+ ];
+ expect(isAllowedIdeShortcut("Ctrl+Shift+A", bindings)).toBe(true);
+ expect(isAllowedIdeShortcut("Ctrl+N", bindings)).toBe(true);
+ expect(isAllowedIdeShortcut("Ctrl+Shift+K", bindings)).toBe(true);
+ expect(isAllowedIdeShortcut("Shift+Escape", bindings)).toBe(true);
+ expect(isAllowedIdeShortcut("Ctrl+W", bindings)).toBe(true);
+ // Ctrl+E (end of line) and actions outside the list stay with the shell.
+ expect(isAllowedIdeShortcut("Ctrl+E", bindings)).toBe(false);
+ expect(isAllowedIdeShortcut("Ctrl+K", bindings)).toBe(false);
+ expect(isAllowedIdeShortcut("Ctrl+R", bindings)).toBe(false);
+ });
});
describe("tab names", () => {
diff --git a/src/features/vcs/CommitView.module.css b/src/features/vcs/CommitView.module.css
index 1f9c715d2..bfe5eb2e0 100644
--- a/src/features/vcs/CommitView.module.css
+++ b/src/features/vcs/CommitView.module.css
@@ -293,3 +293,37 @@
color: var(--link-hover);
text-decoration: underline;
}
+/* Failed before-commit checks (IDEA's commit checks failure panel). */
+.checkProblems {
+ flex: none;
+ display: flex;
+ gap: 6px;
+ max-height: 120px;
+ overflow: auto;
+ padding: 4px 10px 0;
+ color: var(--fg-secondary);
+ font-size: var(--fs-small);
+ line-height: 1.4;
+}
+.checkProblemsIcon {
+ flex: none;
+ margin-top: 1px;
+ color: var(--warning);
+}
+.checkProblemsList {
+ min-width: 0;
+}
+.checkProblemTitle {
+ color: var(--fg);
+}
+.checkProblemLink {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+}
+.checkProblemLink:hover {
+ text-decoration: underline;
+}
diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx
index 9555c62e7..01bdc97b3 100644
--- a/src/features/vcs/CommitView.tsx
+++ b/src/features/vcs/CommitView.tsx
@@ -1,6 +1,7 @@
/** Commit tool window: change list with inclusion checkboxes, message, stashes. */
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type MouseEvent } from "react";
+import { tx } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import {
@@ -37,13 +38,13 @@ import { applyStash, commitChanges, dropStash, stashChanges } from "./changeOps"
import { CommitOptionsPopup } from "./CommitOptions";
import { useChangelists, withListDefaults } from "./changelists";
import { moveToChangelist } from "./changelistsUi";
-import { messageHistory, setGroupByDir, useCommit, type CommitTab } from "./commitStore";
-import { openDiff, workingDiffData } from "./diffInput";
+import { messageHistory, setAmend, setGroupByDir, useCommit, type CommitTab } from "./commitStore";
+import { openDiff, withChain, workingDiffData } from "./diffInput";
import { KIND_COLOR, KIND_LABEL, formatTime, stashLabel, stripSlash } from "./model";
import { call, commands } from "@/platform/ipc";
import { OperationBanner } from "./operations";
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
-import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
+import { loadStashes, refreshNow, useVcs } from "./store";
import styles from "./CommitView.module.css";
/** MIME type of changed files dragged between change lists (absolute paths, newline-separated). */
@@ -115,9 +116,16 @@ const bottomLeft = (el: HTMLElement) => {
return { x: r.left, y: r.bottom + 2 };
};
-function openNode(n: ChangeNode) {
+/** Opens a file's diff; F7 continues through the other files of its group, in tree order. */
+function openNode(n: ChangeNode, roots: readonly ChangeNode[]) {
if (n.type !== "file" || !n.path) return;
- void openDiff(workingDiffData(n.path), { preview: true });
+ const group = roots.find((g) => g.files.some((f) => f.path === n.files[0]?.path)) ?? null;
+ const paths: string[] = [];
+ const walk = (ns: readonly ChangeNode[]) =>
+ ns.forEach((x) => (x.type === "file" ? x.path && paths.push(x.path) : walk(x.children ?? [])));
+ walk(group ? [group] : [n]);
+ const items = paths.map((p) => workingDiffData(p));
+ void openDiff(withChain(items, Math.max(0, paths.indexOf(n.path))), { preview: true });
}
function listMenu(id: string, active: boolean, paths: string[]): MenuItem[] {
@@ -384,7 +392,7 @@ function ChangesPanel() {
selectedList: nodes.find((n) => n.changelist)?.changelist ?? null,
});
}}
- onActivate={openNode}
+ onActivate={(n) => openNode(n, roots)}
onContextMenu={(node, sel, e: MouseEvent) => {
if (!node) return;
if (node.type === "group" && node.changelist) {
@@ -542,11 +550,23 @@ function CommitMessage({ included }: { included: number }) {
const [optionsOpen, setOptionsOpen] = useState(false);
const [emptyError, setEmptyError] = useState(false);
const [busy, setBusy] = useState(false);
- const amendMessage = useRef<string | null>(null);
+ const historyTick = useCommit((s) => s.historyTick);
+ const checkProblems = useCommit((s) => s.checkProblems);
+
+ // The failed checks concern what was about to be committed: editing it dismisses them.
+ useEffect(() => {
+ if (useCommit.getState().checkProblems.length) useCommit.setState({ checkProblems: [] });
+ }, [message, amend, included]);
useEffect(() => {
if (focusTick) ref.current?.focus();
}, [focusTick]);
+ // Show Commit Message History (⌃M) asks through the store.
+ const [seenHistoryTick, setSeenHistoryTick] = useState(historyTick);
+ if (historyTick !== seenHistoryTick) {
+ setSeenHistoryTick(historyTick);
+ if (messageHistory().length) setHistoryOpen(true);
+ }
const cfg = useWorkflowSettings((s) => s.vcs.commit);
const first = message.split("\n")[0] ?? "";
@@ -555,34 +575,6 @@ function CommitMessage({ included }: { included: number }) {
const margin = cfg.limitBody ? cfg.bodyLimit : cfg.subjectLimit;
const showMargin = cfg.showRightMargin && (cfg.limitBody || cfg.limitSubject);
- const setAmend = async (v: boolean) => {
- useCommit.setState({ amend: v });
- if (v && !useCommit.getState().message.trim()) {
- try {
- const [last] = await call(
- commands.vcsLog(currentRepo(), {
- branch: "HEAD",
- path: null,
- author: null,
- text: null,
- range: null,
- skip: 0,
- limit: 1,
- }),
- );
- if (last && !useCommit.getState().message.trim()) {
- amendMessage.current = last.message;
- useCommit.setState({ message: last.message });
- }
- } catch {
- // No commits yet.
- }
- } else if (!v && amendMessage.current !== null && useCommit.getState().message === amendMessage.current) {
- useCommit.setState({ message: "" });
- amendMessage.current = null;
- }
- };
-
const commit = async (push: boolean) => {
if (busy) return;
// IDEA keeps Commit enabled and reports an empty message at the field.
@@ -594,7 +586,6 @@ function CommitMessage({ included }: { included: number }) {
setBusy(true);
try {
const id = await commitChanges();
- amendMessage.current = null;
if (id !== undefined && push) void executeAction("vcs.push");
} finally {
setBusy(false);
@@ -676,9 +667,30 @@ function CommitMessage({ included }: { included: number }) {
{problems.join(" · ")}
</div>
)}
+ {checkProblems.length > 0 && (
+ <div className={styles.checkProblems} role="alert">
+ <Icon name="warning" size={14} className={styles.checkProblemsIcon} />
+ <div className={styles.checkProblemsList}>
+ {checkProblems.map((p, i) => (
+ <div key={i}>
+ <span className={styles.checkProblemTitle}>{tx(p.title)}</span>
+ {typeof p.text === "string" ? `: ${tx(p.text)}` : p.text}
+ {p.details && (
+ <>
+ {" "}
+ <button type="button" className={styles.checkProblemLink} onClick={p.details.run}>
+ {tx(p.details.label)}
+ </button>
+ </>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
<div className={styles.commitActions}>
<Button variant="primary" disabled={!canCommit} onClick={() => void commit(false)} title="⌘↩">
- {amend ? "Amend Commit" : "Commit"}
+ <T>{checkProblems.length ? "Commit Anyway" : amend ? "Amend Commit" : "Commit"}</T>
</Button>
<Button
className={styles.pushButton}
diff --git a/src/features/vcs/CompareBranches.tsx b/src/features/vcs/CompareBranches.tsx
index f2aacb868..76cc27dcd 100644
--- a/src/features/vcs/CompareBranches.tsx
+++ b/src/features/vcs/CompareBranches.tsx
@@ -12,9 +12,9 @@ import styles from "./common.module.css";
const LIMIT = 2000;
/** Commits reachable from `to` but not from `from` (git's `from..to`), computed by git, unbounded by any window. */
-const commitsBetween = (from: string, to: string) =>
+const commitsBetween = (from: string, to: string, repo: string | null = currentRepo()) =>
call(
- commands.vcsLog(currentRepo(), {
+ commands.vcsLog(repo, {
branch: null,
path: null,
author: null,
@@ -30,6 +30,80 @@ export function showCompareBranches(branch: string) {
openDialog((close) => <CompareDialog branch={branch} current={current} onClose={close} />);
}
+/** IDEA's "View Commits" of a notification: the commits of `from..to`. */
+export function showCommitRange(title: string, from: string, to: string, repo: string | null = currentRepo()) {
+ openDialog((close) => <RangeDialog title={title} from={from} to={to} repo={repo} onClose={close} />);
+}
+
+function RangeDialog(props: { title: string; from: string; to: string; repo: string | null; onClose: () => void }) {
+ const { title, from, to, repo, onClose } = props;
+ const [commits, setCommits] = useState<Commit[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ let alive = true;
+ commitsBetween(from, to, repo)
+ .then((c) => alive && setCommits(c))
+ .catch((e) => alive && setError(e instanceof Error ? e.message : String(e)));
+ return () => {
+ alive = false;
+ };
+ }, [from, to, repo]);
+ return (
+ <Dialog open title={title} onClose={onClose} width={640} buttons={[{ label: "Close", role: "cancel" }]}>
+ <CommitList commits={commits} error={error} onClose={onClose} />
+ </Dialog>
+ );
+}
+
+function CommitList({
+ commits,
+ error,
+ onClose,
+}: {
+ commits: Commit[] | null;
+ error: string | null;
+ onClose: () => void;
+}) {
+ return (
+ <div style={{ height: 320, display: "flex", flexDirection: "column" }}>
+ {error ? (
+ <div className={styles.error} style={{ padding: 14 }}>
+ {error}
+ </div>
+ ) : !commits ? (
+ <div className={styles.empty}>
+ <Spinner size={14} />
+ </div>
+ ) : (
+ <List
+ items={commits}
+ getKey={(c) => c.id}
+ rowHeight={22}
+ aria-label="Commits"
+ className={styles.grow}
+ empty={
+ <span>
+ <T>No commits</T>
+ </span>
+ }
+ onActivate={(c) => {
+ onClose();
+ void executeAction("vcs.showCommit", c.id);
+ }}
+ renderItem={(c) => (
+ <span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
+ <span className={styles.commitHash}>{c.shortId}</span>
+ <span className={styles.commitSubject}>{c.summary}</span>
+ <span className={styles.commitMeta}>{c.author}</span>
+ <span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
+ </span>
+ )}
+ />
+ )}
+ </div>
+ );
+}
+
function CompareDialog({ branch, current, onClose }: { branch: string; current: string; onClose: () => void }) {
const [data, setData] = useState<{ incoming: Commit[]; outgoing: Commit[] } | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -72,42 +146,7 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current:
},
]}
/>
- <div style={{ height: 320, display: "flex", flexDirection: "column" }}>
- {error ? (
- <div className={styles.error} style={{ padding: 14 }}>
- {error}
- </div>
- ) : !data ? (
- <div className={styles.empty}>
- <Spinner size={14} />
- </div>
- ) : (
- <List
- items={list}
- getKey={(c) => c.id}
- rowHeight={22}
- aria-label="Commits"
- className={styles.grow}
- empty={
- <span>
- <T>No commits</T>
- </span>
- }
- onActivate={(c) => {
- onClose();
- void executeAction("vcs.showCommit", c.id);
- }}
- renderItem={(c) => (
- <span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
- <span className={styles.commitHash}>{c.shortId}</span>
- <span className={styles.commitSubject}>{c.summary}</span>
- <span className={styles.commitMeta}>{c.author}</span>
- <span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
- </span>
- )}
- />
- )}
- </div>
+ <CommitList commits={data ? list : null} error={error} onClose={onClose} />
</Dialog>
);
}
diff --git a/src/features/vcs/DiffEditor.module.css b/src/features/vcs/DiffEditor.module.css
index 0e78fb489..9fd99716a 100644
--- a/src/features/vcs/DiffEditor.module.css
+++ b/src/features/vcs/DiffEditor.module.css
@@ -1,4 +1,5 @@
.root {
+ position: relative;
flex: 1;
height: 100%;
min-height: 0;
@@ -207,3 +208,19 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
+
+.navHint {
+ position: absolute;
+ left: 50%;
+ bottom: 40px;
+ transform: translateX(-50%);
+ z-index: 5;
+ padding: 6px 12px;
+ border: 1px solid var(--border-tooltip);
+ border-radius: var(--radius-tooltip);
+ background: var(--bg-tooltip);
+ color: var(--fg-tooltip);
+ box-shadow: var(--shadow-tooltip);
+ font-size: var(--fs-small);
+ pointer-events: none;
+}
diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx
index 049f82359..35a4358d4 100644
--- a/src/features/vcs/DiffEditor.tsx
+++ b/src/features/vcs/DiffEditor.tsx
@@ -18,6 +18,7 @@ import { attachDocument, type DocumentAttachment } from "@/editor/api";
import { setContext } from "@/platform/context";
import { call, commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
+import { tx } from "@/platform/i18n";
import { IconButton, Select, Spinner } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { languageFor, viewerBase } from "./cm";
@@ -32,9 +33,24 @@ import {
type HighlightPolicy,
type IgnorePolicy,
} from "./diffOptions";
-import { diffTitle, isIndex, isWorktree, loadSide, sideFile, sideKey, sideLabel, type DiffData, type DiffSide } from "./diffInput";
+import {
+ chainNeighbour,
+ diffTitle,
+ isIndex,
+ isWorktree,
+ loadSide,
+ openDiff,
+ sideFile,
+ sideKey,
+ sideLabel,
+ type DiffData,
+ type DiffSide,
+} from "./diffInput";
import { diffAnnotations } from "./diffAnnotations";
+import { groupOf } from "./changes";
+import { inclusionGutter } from "./hunkInclusion";
import { hunksOverlapping } from "./hunks";
+import { effectiveKind, stripSlash } from "./model";
import { errorMessage, logConsole, readWorkingText, runOp, saveAll } from "./ops";
import { refreshNow, useVcs } from "./store";
import styles from "./DiffEditor.module.css";
@@ -167,6 +183,11 @@ export function DiffEditor({ input }: { input: EditorInput }) {
setChunkInfo((p) => (p.count === chunks.length && p.current === current ? p : { count: chunks.length, current }));
}, []);
+ // A HEAD ↔ working file diff of a tracked change: blocks can be left out of the commit.
+ const includable = useVcs((s) => {
+ const fs = s.status.find((f) => stripSlash(f.path) === path);
+ return !!fs && groupOf(fs) === "changes" && effectiveKind(fs) === "modified";
+ }) && left.type === "rev" && left.rev === "HEAD" && !left.path && isWorktree(right);
const editableA = !!attached?.a && !attached.a.readOnly;
const editableB = !!attached?.b && !attached.b.readOnly;
const ready = !!attached && !!statics && lang !== null;
@@ -197,6 +218,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
const override = whitespaceDiff(opts.ignore);
const diffConfig = override ? { override } : undefined;
const highlightChanges = opts.highlight === "words";
+ const inclusion = includable ? inclusionGutter(path, textA) : [];
const side = (att: DocumentAttachment | null, editable: boolean, notes?: "left" | "right"): Extension[] => [
viewerBase({ readOnly: !editable }),
lang,
@@ -222,6 +244,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
side(attached.b, editableB, "right"),
listener,
focusTracker("b"),
+ inclusion,
editableB ? hoverRevert((_v, i) => merge && applyChunk(merge, i, "a")) : [],
],
},
@@ -245,6 +268,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
side(attached.b, editableB, "right"),
listener,
focusTracker("b"),
+ inclusion,
unifiedMergeView({
original: textA,
highlightChanges,
@@ -273,7 +297,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}
viewsRef.current = views;
requestAnimationFrame(updateChunkInfo);
- }, [attached, statics, lang, opts.mode, opts.collapse, opts.ignore, opts.highlight, editableA, editableB, updateChunkInfo, data.annotations]);
+ }, [attached, statics, lang, opts.mode, opts.collapse, opts.ignore, opts.highlight, editableA, editableB, updateChunkInfo, data.annotations, includable, path]);
useEffect(
() => () => {
@@ -283,15 +307,31 @@ export function DiffEditor({ input }: { input: EditorInput }) {
[],
);
- // Reveal the requested line once.
+ // Reveal the requested line (or the first / last difference) once.
const revealed = useRef(false);
useEffect(() => {
const v = viewsRef.current?.b;
- if (!v || revealed.current || data.line == null || !ready) return;
+ if (!v || revealed.current || (data.line == null && !data.reveal) || !ready) return;
revealed.current = true;
- const line = v.state.doc.line(Math.min(v.state.doc.lines, Math.max(1, data.line + 1)));
- v.dispatch({ selection: { anchor: line.from }, effects: EditorView.scrollIntoView(line.from, { y: "center" }) });
- }, [ready, statics, data.line]);
+ let at: number | undefined;
+ if (data.line != null) at = v.state.doc.line(Math.min(v.state.doc.lines, Math.max(1, data.line + 1))).from;
+ else {
+ const chunks = getChunks(v.state)?.chunks ?? [];
+ at = (data.reveal === "last" ? chunks[chunks.length - 1] : chunks[0])?.fromB;
+ }
+ if (at === undefined) return;
+ v.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
+ updateChunkInfo();
+ }, [ready, statics, data.line, data.reveal, updateChunkInfo]);
+
+ // IDEA: past the last (first) difference F7 (Shift+F7) first hints, then moves along the chain.
+ const [navHint, setNavHint] = useState<string | null>(null);
+ const pendingFile = useRef<0 | 1 | -1>(0);
+ useEffect(() => {
+ if (!navHint) return;
+ const t = setTimeout(() => setNavHint(null), 2500);
+ return () => clearTimeout(t);
+ }, [navHint]);
const step = useCallback(
(dir: 1 | -1) => {
@@ -299,6 +339,26 @@ export function DiffEditor({ input }: { input: EditorInput }) {
if (!views) return;
// Navigate in the focused pane of a side-by-side diff.
const v = focusedSide.current === "a" && views.a ? views.a : views.b;
+ const onA = v !== views.b;
+ const chunks = getChunks(v.state)?.chunks ?? [];
+ const head = v.state.selection.main.head;
+ const start = (c: Chunk) => (onA ? c.fromA : c.fromB);
+ const more = dir === 1 ? chunks.some((c) => start(c) > head) : chunks.some((c) => start(c) < head);
+ if (!more) {
+ const neighbour = chainNeighbour(data, dir);
+ if (!neighbour) return;
+ if (pendingFile.current === dir) {
+ pendingFile.current = 0;
+ setNavHint(null);
+ void openDiff(neighbour, { preview: true });
+ } else {
+ pendingFile.current = dir;
+ setNavHint(dir === 1 ? "Press again to go to the next file" : "Press again to go to the previous file");
+ }
+ return;
+ }
+ pendingFile.current = 0;
+ setNavHint(null);
(dir === 1 ? goToNextChunk : goToPreviousChunk)({ state: v.state, dispatch: (tr) => v.dispatch(tr) });
if (v !== views.b) {
// Mirror the caret into the right pane so the counter follows.
@@ -309,7 +369,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}
updateChunkInfo();
},
- [updateChunkInfo],
+ [updateChunkInfo, data],
);
const jumpToSource = useCallback(() => {
@@ -529,6 +589,11 @@ export function DiffEditor({ input }: { input: EditorInput }) {
aria-label={diffTitle(data)}
role="region"
/>
+ {navHint && (
+ <div className={styles.navHint} role="status">
+ {tx(navHint)}
+ </div>
+ )}
</div>
);
}
diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx
index 895014c1e..9a684ddf2 100644
--- a/src/features/vcs/GitLog.tsx
+++ b/src/features/vcs/GitLog.tsx
@@ -31,7 +31,7 @@ import {
type MenuItem,
T,
} from "@/ui";
-import { commitFileDiffData, openDiff } from "./diffInput";
+import { commitFileDiffData, openDiff, withChain } from "./diffInput";
import { laneColor, type GraphRow } from "./graph";
import {
extendCommitSelection,
@@ -733,7 +733,15 @@ function CommitDetails({ commits }: { commits: Commit[] }) {
</div>
);
- const open = (f: ChangedFile) => void openDiff(commitFileDiffData(commit, f));
+ const open = (f: ChangedFile) => {
+ const all = files ?? [f];
+ void openDiff(
+ withChain(
+ all.map((x) => commitFileDiffData(commit, x)),
+ Math.max(0, all.indexOf(f)),
+ ),
+ );
+ };
const [subject, ...bodyLines] = commit.message.replace(/\s+$/, "").split("\n");
const body = bodyLines.join("\n").replace(/^\n+/, "");
diff --git a/src/features/vcs/MergeEditor.tsx b/src/features/vcs/MergeEditor.tsx
index 1f307db52..4b8e64d55 100644
--- a/src/features/vcs/MergeEditor.tsx
+++ b/src/features/vcs/MergeEditor.tsx
@@ -1,17 +1,26 @@
/** Three-pane merge conflict editor: Yours | Result | Theirs. */
import { useCallback, useEffect, useRef, useState } from "react";
import clsx from "clsx";
-import { RangeSetBuilder, StateField, type EditorState, type Extension } from "@codemirror/state";
+import { Facet, RangeSetBuilder, StateField, type EditorState, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { history, historyKeymap } from "@codemirror/commands";
import { keymap } from "@codemirror/view";
import { unifiedMergeView } from "@codemirror/merge";
+import type { MergeSides } from "@/bindings";
+import { useTxTemplate } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { Button, IconButton, Spinner, T } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { languageFor, viewerBase } from "./cm";
import { confirmDialog } from "./dialogs";
-import { parseConflicts, resolutionText, resolveAll, type ConflictBlock, type Resolution } from "./conflicts";
+import {
+ mergeTitles,
+ parseConflicts,
+ resolutionText,
+ resolveAll,
+ type ConflictBlock,
+ type Resolution,
+} from "./conflicts";
import { baseName } from "./model";
import { errorMessage, readWorkingText, runOp, writeFileText } from "./ops";
import { refreshNow } from "./store";
@@ -20,9 +29,12 @@ import styles from "./MergeEditor.module.css";
import type { MergeData } from "./mergeKind";
export { MERGE_KIND, mergeInput, type MergeData } from "./mergeKind";
+/** The user's commit is the `>>>>>>>` section (a rebase): "Yours" takes it. */
+const reversedSides = Facet.define<boolean, boolean>({ combine: (v) => v.some(Boolean) });
+
function resolveBlock(view: EditorView, block: ConflictBlock, how: Resolution) {
view.dispatch({
- changes: { from: block.from, to: block.to, insert: resolutionText(block, how) },
+ changes: { from: block.from, to: block.to, insert: resolutionText(block, how, view.state.facet(reversedSides)) },
userEvent: "input.resolve",
});
}
@@ -75,6 +87,7 @@ function decorate(state: EditorState): { blocks: ConflictBlock[]; deco: Decorati
const blocks = parseConflicts(state.doc.toString());
const b = new RangeSetBuilder<Decoration>();
const doc = state.doc;
+ const [yours, theirs] = state.facet(reversedSides) ? [theirsLine, oursLine] : [oursLine, theirsLine];
blocks.forEach((blk, i) => {
b.add(blk.from, blk.from, Decoration.widget({ widget: new ActionsWidget(i, blk), block: true, side: -1 }));
const endLine = doc.lineAt(Math.max(blk.from, blk.to - 1)).number;
@@ -82,9 +95,9 @@ function decorate(state: EditorState): { blocks: ConflictBlock[]; deco: Decorati
const line = doc.line(n);
const deco =
line.from >= blk.oursFrom && line.from < blk.oursTo
- ? oursLine
+ ? yours
: line.from >= blk.theirsFrom && line.from < blk.theirsTo
- ? theirsLine
+ ? theirs
: markerLine;
b.add(line.from, line.from, deco);
}
@@ -135,6 +148,7 @@ export function MergeEditor({ input }: { input: EditorInput }) {
theirs: string;
base: string | null;
working: string;
+ sides: MergeSides;
} | null>(null);
const [error, setError] = useState<string | null>(null);
const [lang, setLang] = useState<Extension | null>(null);
@@ -144,11 +158,13 @@ export function MergeEditor({ input }: { input: EditorInput }) {
const resultRef = useRef<HTMLDivElement>(null);
const theirsRef = useRef<HTMLDivElement>(null);
const resultView = useRef<EditorView | null>(null);
+ const txt = useTxTemplate();
+ const titles = mergeTitles(state?.sides);
const load = useCallback(async () => {
try {
const [v, working] = await Promise.all([call(commands.vcsConflictVersions(path)), readWorkingText(path)]);
- setState({ ours: v.ours ?? "", theirs: v.theirs ?? "", base: v.base, working: working ?? "" });
+ setState({ ours: v.ours ?? "", theirs: v.theirs ?? "", base: v.base, working: working ?? "", sides: v.sides });
setError(null);
} catch (e) {
setError(errorMessage(e));
@@ -183,6 +199,7 @@ export function MergeEditor({ input }: { input: EditorInput }) {
history(),
keymap.of(historyKeymap),
lang,
+ reversedSides.of(state.sides.reversed),
conflictField,
resultTheme,
EditorView.updateListener.of((u) => {
@@ -221,7 +238,10 @@ export function MergeEditor({ input }: { input: EditorInput }) {
const v = resultView.current;
if (!v) return;
const text = v.state.doc.toString();
- v.dispatch({ changes: { from: 0, to: text.length, insert: resolveAll(text, how) }, userEvent: "input.resolve" });
+ v.dispatch({
+ changes: { from: 0, to: text.length, insert: resolveAll(text, how, v.state.facet(reversedSides)) },
+ userEvent: "input.resolve",
+ });
};
const apply = async () => {
@@ -292,15 +312,11 @@ export function MergeEditor({ input }: { input: EditorInput }) {
</Button>
</div>
<div className={styles.labels}>
- <span>
- <T>Yours (current branch)</T>
- </span>
+ <span>{txt(titles.yours)}</span>
<span>
<T>Result</T>
</span>
- <span>
- <T>Theirs (incoming)</T>
- </span>
+ <span>{txt(titles.theirs)}</span>
</div>
{!state || lang === null ? (
<div className={styles.message}>
diff --git a/src/features/vcs/__tests__/changes.test.ts b/src/features/vcs/__tests__/changes.test.ts
index 73abd0e90..6503942b0 100644
--- a/src/features/vcs/__tests__/changes.test.ts
+++ b/src/features/vcs/__tests__/changes.test.ts
@@ -5,7 +5,9 @@ import {
buildChangeTree,
commitRepos,
initialCheck,
+ hunkIncluded,
planCommit,
+ toggledHunk,
type CheckState,
type ChangeNode,
} from "../changes";
@@ -143,4 +145,28 @@ describe("commit inclusion", () => {
expect(aggregateCheck([status[0]!, status[4]!], checks)).toMatchObject({ checked: false, indeterminate: true });
expect(aggregateCheck([status[1]!], checks)).toMatchObject({ checked: false, indeterminate: true });
});
+
+ it("commits a file with excluded blocks partially, without staging it", () => {
+ const checks = new Map<string, CheckState>([["/r/src/main/kotlin/App.kt", "hunks"]]);
+ const plan = planCommit(status, checks);
+ expect(plan.partial).toEqual(["/r/src/main/kotlin/App.kt"]);
+ expect(plan.stage).not.toContain("/r/src/main/kotlin/App.kt");
+ expect(plan.included.map((f) => f.relPath)).toContain("src/main/kotlin/App.kt");
+ expect(aggregateCheck([status[0]!], checks)).toMatchObject({ checked: false, indeterminate: true });
+ });
+
+ it("toggles single blocks: tri-state file, all in → all, all out → none", () => {
+ const all = ["a", "b", "c"];
+ const one = toggledHunk("all", undefined, all, "b");
+ expect(one).toEqual({ check: "hunks", excluded: new Set(["b"]) });
+ expect(hunkIncluded(one.check, one.excluded, "a")).toBe(true);
+ expect(hunkIncluded(one.check, one.excluded, "b")).toBe(false);
+ expect(toggledHunk(one.check, one.excluded, all, "b")).toEqual({ check: "all", excluded: new Set() });
+ // From an unchecked file, ticking one block includes just that block.
+ const picked = toggledHunk("none", undefined, all, "c");
+ expect(picked).toEqual({ check: "hunks", excluded: new Set(["a", "b"]) });
+ expect(toggledHunk("hunks", new Set(["a", "b"]), all, "c").check).toBe("none");
+ // Keys of blocks that no longer exist are dropped.
+ expect(toggledHunk("hunks", new Set(["gone", "a"]), all, "b").excluded).toEqual(new Set(["a", "b"]));
+ });
});
diff --git a/src/features/vcs/__tests__/conflicts.test.ts b/src/features/vcs/__tests__/conflicts.test.ts
index 3dc57fe53..fc32ac029 100644
--- a/src/features/vcs/__tests__/conflicts.test.ts
+++ b/src/features/vcs/__tests__/conflicts.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { blockAt, parseConflicts, resolveAll, resolutionText } from "../conflicts";
+import { blockAt, mergeTitles, parseConflicts, resolveAll, resolutionText } from "../conflicts";
const text = [
"keep\n",
@@ -41,4 +41,36 @@ describe("parseConflicts", () => {
expect(resolutionText(a!, "both")).toBe("ours 1\nours 2\ntheirs\n");
expect(resolutionText(a!, "base")).toBe("base\n");
});
+
+ it("swaps sides during a rebase, where the user's commit is the >>>>>>> section", () => {
+ expect(resolveAll(text, "ours", true)).toBe("keep\ntheirs\ntail\nonly theirs\n");
+ expect(resolveAll(text, "theirs", true)).toBe("keep\nours 1\nours 2\ntail\n");
+ const [a] = parseConflicts(text);
+ expect(resolutionText(a!, "both", true)).toBe("theirs\nours 1\nours 2\n");
+ expect(resolutionText(a!, "base", true)).toBe("base\n");
+ });
+});
+
+describe("mergeTitles", () => {
+ const sides = (operation: string | null, extra: Record<string, string | boolean | null> = {}) => ({
+ operation,
+ reversed: operation === "rebase",
+ branch: "feature",
+ commit: "abc12345",
+ otherBranch: "main",
+ ...extra,
+ });
+ it("names the sides like IDEA for each operation", () => {
+ expect(mergeTitles(sides("rebase"))).toEqual({
+ yours: "Rebasing abc12345 from feature",
+ theirs: "Already rebased commits and commits from main",
+ });
+ expect(mergeTitles(sides("rebase", { otherBranch: null })).theirs).toBe("Already rebased commits");
+ expect(mergeTitles(sides("merge"))).toEqual({ yours: "Changes from feature", theirs: "Changes from main" });
+ expect(mergeTitles(sides("cherry-pick"))).toEqual({
+ yours: "Local Changes",
+ theirs: "Changes from cherry-pick abc12345",
+ });
+ expect(mergeTitles(null)).toEqual({ yours: "Your version", theirs: "Theirs (incoming)" });
+ });
});
diff --git a/src/features/vcs/__tests__/diffChain.test.ts b/src/features/vcs/__tests__/diffChain.test.ts
new file mode 100644
index 000000000..4b3e36983
--- /dev/null
+++ b/src/features/vcs/__tests__/diffChain.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { chainNeighbour, withChain, type DiffData } from "../diffInput";
+
+const diff = (path: string): DiffData => ({ path, left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } });
+
+describe("diff chain", () => {
+ const items = [diff("/r/a"), diff("/r/b"), diff("/r/c")];
+
+ it("moves to the neighbouring file, revealing the nearest difference", () => {
+ const b = withChain(items, 1);
+ expect(b.path).toBe("/r/b");
+ const next = chainNeighbour(b, 1)!;
+ expect(next).toMatchObject({ path: "/r/c", reveal: "first" });
+ expect(chainNeighbour(b, -1)).toMatchObject({ path: "/r/a", reveal: "last" });
+ // The neighbour keeps the chain, so F7 can continue from it.
+ expect(chainNeighbour(next, -1)).toMatchObject({ path: "/r/b" });
+ });
+
+ it("stops at the ends and without a chain", () => {
+ expect(chainNeighbour(withChain(items, 2), 1)).toBeNull();
+ expect(chainNeighbour(withChain(items, 0), -1)).toBeNull();
+ expect(chainNeighbour(withChain([diff("/r/a")], 0), 1)).toBeNull();
+ expect(chainNeighbour(diff("/r/a"), 1)).toBeNull();
+ });
+});
diff --git a/src/features/vcs/__tests__/hunks.test.ts b/src/features/vcs/__tests__/hunks.test.ts
index 9db005118..be2185632 100644
--- a/src/features/vcs/__tests__/hunks.test.ts
+++ b/src/features/vcs/__tests__/hunks.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
-import { EditorState } from "@codemirror/state";
+import { EditorSelection, EditorState } from "@codemirror/state";
import type { LineHunk } from "@/bindings";
-import { applyRollback, hunkAtLine, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
-import { editorHunks, hunkAtPos, hunkField, setHunksEffect } from "../gutter";
+import { applyRollback, hunkAtLine, hunkKeys, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
+import { editorHunks, hunkAtPos, hunkField, hunksInSelection, setHunksEffect } from "../gutter";
const h = (kind: LineHunk["kind"], start: number, lines: number, oldStart: number, oldLines: number, oldText: string): LineHunk => ({
kind,
@@ -148,3 +148,32 @@ describe("change markers in folds", () => {
expect(hunkAtPos(state, state.doc.line(1).from)?.kind).toBe("deleted");
});
});
+
+describe("hunkKeys", () => {
+ it("identifies blocks by content, not position", () => {
+ const a = hunkKeys("x\nB\nc\n", [h("modified", 1, 1, 1, 1, "b\n")]);
+ // The same block two lines further down (lines inserted above it) keeps its key.
+ const b = hunkKeys("new\nnew\nx\nB\nc\n", [h("added", 0, 2, 0, 0, ""), h("modified", 3, 1, 1, 1, "b\n")]);
+ expect(b[1]).toBe(a[0]);
+ expect(b[0]).not.toBe(b[1]);
+ // Identical blocks get distinct keys.
+ const twice = hunkKeys("B\nB\n", [h("modified", 0, 1, 0, 1, "b\n"), h("modified", 1, 1, 1, 1, "b\n")]);
+ expect(twice[0]).not.toBe(twice[1]);
+ });
+});
+
+describe("hunksInSelection (Rollback Lines)", () => {
+ const hunks = [h("modified", 1, 1, 1, 1, "b\n"), h("deleted", 3, 0, 3, 1, "d\n"), h("added", 4, 1, 5, 0, "")];
+ const at = (from: number, to = from) => {
+ let state = EditorState.create({ doc: "a\nB\nc\ne\nX\n", extensions: hunkField });
+ state = state.update({ effects: setHunksEffect.of(hunks), selection: EditorSelection.single(from, to) }).state;
+ return hunksInSelection(state).map((x) => x.start);
+ };
+ it("takes the hunks on the caret's line or touched by the selection", () => {
+ expect(at(0)).toEqual([]);
+ expect(at(3)).toEqual([1]);
+ // The deletion's marker is on the line after the removed block.
+ expect(at(7)).toEqual([3]);
+ expect(at(2, 9)).toEqual([1, 3, 4]);
+ });
+});
diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx
index 8ca8316f0..8c6dba502 100644
--- a/src/features/vcs/actions.tsx
+++ b/src/features/vcs/actions.tsx
@@ -1,5 +1,5 @@
/** VCS actions (ids match keymaps/intellij-macos.ts where bound). */
-import { registerActions, type Action } from "@/platform/actions";
+import { executeAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { activeEditor, editorsFor } from "@/editor/api";
import { Menu, type MenuItem } from "@/ui";
@@ -7,13 +7,20 @@ import { editorService, maybeEditorService, notifications, toolWindowService } f
import { annotationsShown, toggleAnnotations } from "./blame";
import { showBranchesPopup } from "./BranchWidget";
import { checkoutRevision, newBranch } from "./branchOps";
-import { addToVcs, isNestedRepoEntry, rollbackCandidates, showRollbackDialog, stashChanges } from "./changeOps";
-import { useCommit } from "./commitStore";
+import {
+ addToVcs,
+ commitChanges,
+ isNestedRepoEntry,
+ rollbackCandidates,
+ showRollbackDialog,
+ stashChanges,
+} from "./changeOps";
+import { setAmend, useCommit } from "./commitStore";
import { gotoConflict, resolveAtCaret, showConflictsDialog } from "./conflictsUi";
import { focusedDiffNavigator } from "./diffNavigator";
import { openDiff, workingDiffData } from "./diffInput";
import { openDialog } from "./dialogs";
-import { gotoChange } from "./gutter";
+import { gotoChange, rollbackSelectedLines } from "./gutter";
import { openLocalHistory } from "./localHistoryKind";
import { revealCommit, setLogFilters, useGitLog, emptyFilters } from "./logStore";
import { allRepos, runRemote } from "./ops";
@@ -23,6 +30,7 @@ import { showCloneDialog } from "./clone";
import { refreshNow, repoName } from "./store";
const VCS = "vcsAvailable";
+const IN_COMMIT_WINDOW = "vcsAvailable && activeToolWindow == commit";
function argPath(arg: unknown): string | undefined {
if (typeof arg === "string") return arg;
@@ -126,6 +134,38 @@ export function registerVcsActions(): () => void {
when: VCS,
run: () => showCommitWindow(),
},
+ {
+ id: "vcs.commitAndPush",
+ title: "Commit and Push…",
+ category: "Git",
+ icon: "git-push",
+ when: VCS,
+ run: async () => {
+ const { message, amend } = useCommit.getState();
+ // Nothing to commit with yet: IDEA shows the commit window with the message field focused.
+ if (!message.trim() && !amend) return showCommitWindow();
+ const id = await commitChanges();
+ if (id !== undefined) void executeAction("vcs.push");
+ },
+ },
+ {
+ id: "vcs.toggleAmend",
+ title: "Amend Commit",
+ category: "Git",
+ when: VCS,
+ keyWhen: IN_COMMIT_WINDOW,
+ toggled: () => useCommit.getState().amend,
+ run: () => void setAmend(!useCommit.getState().amend),
+ },
+ {
+ id: "vcs.showMessageHistory",
+ title: "Show Commit Message History",
+ category: "Git",
+ icon: "history",
+ when: VCS,
+ keyWhen: IN_COMMIT_WINDOW,
+ run: () => useCommit.setState((s) => ({ historyTick: s.historyTick + 1 })),
+ },
{
id: "vcs.clone",
title: "Get from Version Control…",
@@ -169,6 +209,9 @@ export function registerVcsActions(): () => void {
keywords: ["revert", "discard"],
run: ({ arg }) => {
const explicit = argPaths(arg);
+ // IDEA: in the editor, with the caret on changed lines, ⌥⌘Z is Rollback Lines.
+ const ed = activeEditor();
+ if (!explicit?.length && ed?.view.hasFocus && rollbackSelectedLines(ed.view)) return;
const sel = useCommit.getState().selection;
const paths = explicit?.length ? explicit : commitWindowFocused() && sel.length ? sel : undefined;
if (paths) {
diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts
index 039c924c2..36392ea9f 100644
--- a/src/features/vcs/branchOps.ts
+++ b/src/features/vcs/branchOps.ts
@@ -1,10 +1,12 @@
/** Branch operations (checkout, create, merge, rebase, update, delete) with recents and favorites. */
import { create } from "zustand";
-import type { Branch } from "@/bindings";
+import type { Branch, CheckoutOptions } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
+import { ask } from "@/workbench/messages";
import { isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
+import { showCommitRange } from "./CompareBranches";
import { confirmDialog, promptText } from "./dialogs";
import { runOp, runRemote, saveAll } from "./ops";
import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
@@ -43,13 +45,89 @@ export function validateBranchName(name: string): string | null {
return null;
}
-export async function checkoutBranch(name: string) {
- const previous = useVcs.getState().branch?.head;
- await saveAll();
- const ok = await runOp(`Checkout ${name}`, () => call(commands.vcsCheckout(currentRepo(), name, false)), {
- success: () => `Checked out ${useVcs.getState().branch?.head ?? name}`,
+/** IDEA's Smart Checkout dialog; the chosen mode, or null for Don't Checkout. */
+async function askSmartCheckout(files: readonly string[]): Promise<CheckoutOptions["mode"] | null> {
+ const list = files.slice(0, 20).join("\n") + (files.length > 20 ? "\n…" : "");
+ const r = await ask({
+ title: "Git Checkout Problem",
+ body: `Your local changes to the following files would be overwritten by checkout:\n${list}\n\nSmart Checkout can stash the changes, checkout and unstash them after that.`,
+ icon: "warning",
+ width: 520,
+ buttons: [
+ { id: "smart", label: "Smart Checkout", primary: true },
+ { id: "force", label: "Force Checkout" },
+ { id: "cancel", label: "Don't Checkout" },
+ ],
});
- if (ok !== undefined) {
+ return r.button === "smart" || r.button === "force" ? r.button : null;
+}
+
+/**
+ * Checks out `rev` as IDEA does: local changes in the way open the Smart Checkout
+ * dialog, and a remote branch whose local namesake has commits of its own asks whether
+ * to rebase that branch onto the remote or drop its commits (one that is only behind is
+ * fast-forwarded). Resolves true once switched.
+ */
+async function performCheckout(rev: string, success: () => string): Promise<boolean> {
+ await saveAll();
+ let options: CheckoutOptions = { mode: "normal", diverged: null };
+ for (;;) {
+ const opts = options;
+ const outcome = await runOp(`Checkout ${rev}`, () => call(commands.vcsCheckout(currentRepo(), rev, false, opts)));
+ if (!outcome) return false;
+ switch (outcome.kind) {
+ case "done":
+ notifications().notify({ group: "vcs", level: "info", title: success() });
+ return true;
+ case "conflicts":
+ notifications().notify({
+ group: "vcs",
+ level: "warning",
+ title: `${success()}, with conflicts`,
+ body: outcome.files.join("\n"),
+ actions: [{ label: "Resolve Conflicts…", run: () => void executeAction("vcs.resolveConflicts") }],
+ });
+ await openConflictsInstead();
+ return true;
+ case "localChanges": {
+ const mode = await askSmartCheckout(outcome.files);
+ if (!mode) return false;
+ options = { ...options, mode };
+ continue;
+ }
+ case "localBranchAhead": {
+ const { local, remote } = outcome;
+ const r = await ask({
+ title: `Checkout ${remote}`,
+ body: `Local branch '${local}' has commits that do not exist in '${remote}'. Rebase '${local}' onto '${remote}', or drop local commits?`,
+ buttons: [
+ { id: "rebase", label: "Rebase onto Remote", primary: true },
+ { id: "reset", label: "Drop Local Commits" },
+ ],
+ });
+ if (r.button !== "rebase" && r.button !== "reset") return false;
+ options = { ...options, diverged: r.button };
+ continue;
+ }
+ }
+ }
+}
+
+/** Checkout of a commit or tag (detached HEAD) with Smart Checkout. */
+export async function checkoutDetached(rev: string, label: string) {
+ await performCheckout(rev, () => `Checked out ${label} (detached HEAD)`);
+}
+
+export async function checkoutBranch(name: string) {
+ const state = useVcs.getState();
+ const previous = state.branch?.head;
+ // A local namesake tracking another branch: IDEA asks for a new local name instead.
+ if (state.branches.some((b) => b.remote && b.name === name)) {
+ const local = state.branches.find((b) => !b.remote && b.name === shortRemoteName(name));
+ if (local?.upstream && local.upstream !== name) return newBranch(name);
+ }
+ const ok = await performCheckout(name, () => `Checked out ${useVcs.getState().branch?.head ?? name}`);
+ if (ok) {
rememberBranch(previous);
await refreshNow();
rememberBranch(useVcs.getState().branch?.head);
@@ -91,10 +169,7 @@ export async function checkoutRevision() {
validate: (v) => (v.trim() ? null : "Enter a revision"),
});
if (!r) return;
- await saveAll();
- await runOp(`Checkout ${r.value}`, () => call(commands.vcsCheckout(currentRepo(), r.value, false)), {
- success: `Checked out ${r.value}`,
- });
+ await performCheckout(r.value, () => `Checked out ${r.value}`);
}
function conflictActions(message: string) {
@@ -157,28 +232,50 @@ export async function renameBranch(name: string) {
}
}
+/**
+ * Delete Branch as IDEA does it: no confirmation; a branch that is not fully merged is
+ * deleted anyway and the notification says so, offering View Commits. Restore recreates
+ * the branch (with its upstream); Delete Tracked Branch removes the remote branch too.
+ */
export async function deleteBranch(name: string) {
- const ok = await confirmDialog({
- title: "Delete Branch",
- message: `Delete local branch '${name}'?`,
- okLabel: "Delete",
- danger: true,
- });
- if (!ok) return;
- await runOp(`Delete branch ${name}`, () => call(commands.vcsDeleteBranch(currentRepo(), name, false)), {
- success: `Deleted branch ${name}`,
- errorActions: (m) =>
- /not fully merged/i.test(m)
+ const repo = currentRepo();
+ const deleted = await runOp(`Delete branch ${name}`, () => call(commands.vcsDeleteBranch(repo, name)));
+ if (!deleted) return;
+ const tracked = deleted.upstream;
+ const otherTracking = useVcs.getState().branches.some((b) => !b.remote && b.name !== name && b.upstream === tracked);
+ const key = `vcs.deleted.${name}`;
+ const done = () => notifications().expire?.(key);
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ key,
+ title: `Deleted branch ${name}`,
+ body: deleted.unmerged ? "Unmerged commits were discarded" : undefined,
+ actions: [
+ {
+ label: "Restore",
+ run: () => {
+ done();
+ void runOp(`Restore branch ${name}`, () => call(commands.vcsRestoreBranch(repo, deleted)), {
+ success: `Restored branch ${name}`,
+ });
+ },
+ },
+ ...(deleted.unmerged
+ ? [{ label: "View Commits", run: () => showCommitRange(`Commits of ${name}`, "HEAD", deleted.tip) }]
+ : []),
+ ...(tracked && !otherTracking
? [
{
- label: "Force Delete",
- run: () =>
- void runOp(`Force delete ${name}`, () => call(commands.vcsDeleteBranch(currentRepo(), name, true)), {
- success: `Deleted branch ${name}`,
- }),
+ label: "Delete Tracked Branch",
+ run: () => {
+ done();
+ void deleteRemoteBranch(tracked);
+ },
},
]
- : [],
+ : []),
+ ],
});
}
@@ -198,9 +295,8 @@ export async function deleteRemoteBranch(name: string) {
export async function checkoutAndRebase(name: string) {
const current = useVcs.getState().branch?.head;
if (!current) return;
- await saveAll();
- const ok = await runOp(`Checkout ${name}`, () => call(commands.vcsCheckout(currentRepo(), name, false)));
- if (ok === undefined) return;
+ const ok = await performCheckout(name, () => `Checked out ${name}`);
+ if (!ok) return;
rememberBranch(current);
rememberBranch(name);
await refreshNow();
diff --git a/src/features/vcs/changeOps.tsx b/src/features/vcs/changeOps.tsx
index 7855ce389..831034cce 100644
--- a/src/features/vcs/changeOps.tsx
+++ b/src/features/vcs/changeOps.tsx
@@ -1,15 +1,16 @@
/** Local change operations: commit, rollback, add, stash. */
import { useState } from "react";
-import type { FileStatus } from "@/bindings";
+import type { FileStatus, PartialCommitFile } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, fileIconName } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { commitRepos, groupOf, planCommit, renamedFromPath } from "./changes";
import { useChangelists, withListDefaults } from "./changelists";
import { runCommitChecks } from "./commitChecks";
-import { rememberMessage, useCommit } from "./commitStore";
+import { forgetAmendDraft, rememberMessage, useCommit } from "./commitStore";
import { confirmDialog, openDialog, promptText } from "./dialogs";
-import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
+import { hunkKeys } from "./hunks";
+import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, rootOf, stripSlash } from "./model";
import { logConsole, runOp, saveAll } from "./ops";
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
@@ -47,17 +48,30 @@ export async function commitChanges(): Promise<string | undefined> {
return undefined;
}
const candidates = plan.included.map((f) => ({ path: stripSlash(f.path), exists: effectiveKind(f) !== "deleted" }));
- if (!(await runCommitChecks(candidates, amend))) return undefined;
+ // IDEA: failed checks show in the commit panel; the next Commit ("Commit Anyway") skips them.
+ if (!useCommit.getState().checkProblems.length) {
+ const problems = await runCommitChecks(candidates, amend);
+ if (problems.length) {
+ useCommit.setState({ checkProblems: problems });
+ return undefined;
+ }
+ }
+ const partial = await partialCommitFiles(plan.partial);
// Like IDEA, every repository with included changes gets a commit with the same message.
- const repos = commitRepos(plan.included, useVcs.getState().roots, currentRepo());
+ const roots = useVcs.getState().roots;
+ const repos = commitRepos(plan.included, roots, currentRepo());
const id = await runOp(
amend ? "Amend commit" : "Commit",
async () => {
if (plan.unstage.length) await call(commands.vcsUnstage(plan.unstage));
- if (plan.stage.length) await call(commands.vcsStage(plan.stage));
- const options = { amend, signOff, author: author.trim() || null, runHooks };
+ const stage = [...plan.stage, ...partial.whole];
+ if (stage.length) await call(commands.vcsStage(stage));
let id = "";
- for (const repo of repos) id = await call(commands.vcsCommit(repo, message.trim(), options));
+ for (const repo of repos) {
+ const files = partial.files.filter((f) => (rootOf(f.path, roots) ?? null) === repo || repos.length === 1);
+ const options = { amend, signOff, author: author.trim() || null, runHooks, partial: files };
+ id = await call(commands.vcsCommit(repo, message.trim(), options));
+ }
return id;
},
{
@@ -71,11 +85,37 @@ export async function commitChanges(): Promise<string | undefined> {
);
if (id !== undefined) {
rememberMessage(message);
- useCommit.setState({ message: "", amend: false, checks: new Map() });
+ forgetAmendDraft();
+ useCommit.setState({ message: "", amend: false, checks: new Map(), excludedHunks: new Map(), checkProblems: [] });
}
return id;
}
+/**
+ * The included blocks of files committed partially, as hunk ranges against HEAD of the
+ * text on disk (saved just before). A file whose blocks are all included again (e.g. it
+ * was edited since) is committed whole.
+ */
+async function partialCommitFiles(paths: readonly string[]): Promise<{ files: PartialCommitFile[]; whole: string[] }> {
+ const files: PartialCommitFile[] = [];
+ const whole: string[] = [];
+ const excludedHunks = useCommit.getState().excludedHunks;
+ for (const path of paths) {
+ const [head, disk] = await Promise.all([call(commands.vcsFileAt(path, "HEAD")), call(commands.fsReadText(path))]);
+ const hunks = await commands.vcsDiffHunks(head ?? "", disk);
+ const keys = hunkKeys(disk, hunks);
+ const excluded = excludedHunks.get(path) ?? excludedHunks.get(`${path}/`);
+ const chosen = hunks.filter((_, i) => !excluded?.has(keys[i]!));
+ if (chosen.length === hunks.length) whole.push(path);
+ else
+ files.push({
+ path,
+ hunks: chosen.map(({ start, lines, oldStart, oldLines }) => ({ start, lines, oldStart, oldLines })),
+ });
+ }
+ return { files, whole };
+}
+
/** Files the Rollback action applies to by default. */
export function rollbackCandidates(
paths?: readonly string[],
diff --git a/src/features/vcs/changes.ts b/src/features/vcs/changes.ts
index f0b3c47ad..d4bd0a5b7 100644
--- a/src/features/vcs/changes.ts
+++ b/src/features/vcs/changes.ts
@@ -13,9 +13,11 @@ export const GROUP_LABEL: Record<GroupId, string> = {
/**
* Inclusion of a file in the next commit:
* `all` – stage everything before committing; `none` – keep out (unstage);
- * `staged` – commit only what is already staged (partially staged files).
+ * `staged` – commit only what is already staged (partially staged files);
+ * `hunks` – commit only the changed blocks not excluded in the diff (IDEA's partial
+ * commit; see `excludedHunks`), through a temporary index.
*/
-export type CheckState = "all" | "none" | "staged";
+export type CheckState = "all" | "none" | "staged" | "hunks";
export interface ChangeNode {
key: string;
@@ -68,7 +70,7 @@ export function aggregateCheck(files: readonly FileStatus[], checks: ReadonlyMap
for (const f of files) {
const c = checkOf(f, checks);
if (c !== "none") on++;
- if (c === "staged") partial = true;
+ if (c === "staged" || c === "hunks") partial = true;
}
return { checked: on > 0 && on === files.length && !partial, indeterminate: (on > 0 && on < files.length) || partial, on };
}
@@ -256,6 +258,8 @@ export interface CommitPlan {
unstage: string[];
/** Files that end up in the commit. */
included: FileStatus[];
+ /** Absolute paths of included files committed with only some of their hunks. */
+ partial: string[];
}
/**
@@ -282,7 +286,7 @@ export function renamedFromPath(fs: FileStatus): string | null {
/** What to stage / unstage so the index holds exactly the included changes. */
export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<string, CheckState>): CommitPlan {
- const plan: CommitPlan = { stage: [], unstage: [], included: [] };
+ const plan: CommitPlan = { stage: [], unstage: [], included: [], partial: [] };
for (const fs of status) {
if (!groupOf(fs)) continue;
const c = checkOf(fs, checks);
@@ -298,11 +302,39 @@ export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<st
}
if (c === "all" && fs.unstaged) plan.stage.push(path);
if (c === "staged" && !fs.staged) continue;
+ if (c === "hunks") plan.partial.push(path);
plan.included.push(fs);
}
return plan;
}
+/**
+ * Toggling the checkbox of one changed block (`key`, one of `all`) in the diff: the file's
+ * new inclusion and excluded blocks. All blocks back in → `all`; none left → `none`.
+ */
+export function toggledHunk(
+ current: CheckState,
+ excluded: ReadonlySet<string> | undefined,
+ all: readonly string[],
+ key: string,
+): { check: CheckState; excluded: Set<string> } {
+ const out = new Set(
+ current === "none" ? all : current === "hunks" ? [...(excluded ?? [])].filter((k) => all.includes(k)) : [],
+ );
+ if (out.has(key)) out.delete(key);
+ else out.add(key);
+ if (!out.size) return { check: "all", excluded: out };
+ if (all.every((k) => out.has(k))) return { check: "none", excluded: new Set() };
+ return { check: "hunks", excluded: out };
+}
+
+/** Whether a changed block is included, given its file's inclusion. */
+export function hunkIncluded(check: CheckState, excluded: ReadonlySet<string> | undefined, key: string): boolean {
+ if (check === "none") return false;
+ if (check === "hunks") return !excluded?.has(key);
+ return true;
+}
+
/** Toggling a checkbox: anything included → none; none → all. */
export function toggledCheck(current: CheckState): CheckState {
return current === "none" ? "all" : "none";
diff --git a/src/features/vcs/commitChecks.tsx b/src/features/vcs/commitChecks.tsx
index 3119a30d0..ea45664c7 100644
--- a/src/features/vcs/commitChecks.tsx
+++ b/src/features/vcs/commitChecks.tsx
@@ -10,7 +10,6 @@ import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import { maybeEditorService, toolWindowService } from "@/workbench/contributions";
-import { ask } from "@/workbench/messages";
import { baseName, relTo } from "./model";
import { logConsole } from "./ops";
import { currentRepo, useVcs } from "./store";
@@ -160,23 +159,17 @@ async function modifyFile(path: string, mods: Modifications) {
}
// ---------------------------------------------------------------------------
-// Dialogs
+// Problems
-type Choice = "commit" | "review" | "cancel";
-
-async function choiceDialog(title: string, body: ReactNode, reviewLabel?: string): Promise<Choice> {
- const r = await ask({
- title,
- body,
- icon: "warning",
- width: 520,
- buttons: [
- // IDEA's check-in handlers default to Review when there is something to review.
- ...(reviewLabel ? [{ id: "review", label: reviewLabel, primary: true }] : []),
- { id: "commit", label: "Commit Anyway", primary: !reviewLabel },
- ],
- });
- return r.button as Choice;
+/**
+ * A failed before-commit check, shown in the commit panel (as IDEA)
+ * while the Commit button turns into "Commit Anyway".
+ */
+export interface CommitProblem {
+ title: string;
+ text: ReactNode;
+ /** "Review" / "Show details" link. */
+ details?: { label: string; run: () => void };
}
function plural(n: number, word: string) {
@@ -193,26 +186,26 @@ export interface CommitCandidate {
}
/**
- * Runs the configured before-commit modifications and checks for the files
- * about to be committed. Resolves false when the user cancels the commit.
+ * Runs the configured before-commit modifications and checks for the files about to
+ * be committed. Resolves the problems found; the commit goes ahead only without any.
*/
-export async function runCommitChecks(files: readonly CommitCandidate[], amend: boolean): Promise<boolean> {
+export async function runCommitChecks(files: readonly CommitCandidate[], amend: boolean): Promise<CommitProblem[]> {
const { commit, git } = workflowSettings().vcs;
const branch = useVcs.getState().branch;
+ const problems: CommitProblem[] = [];
if (git.warnDetachedHead && branch && (!branch.head || branch.operation === "rebase")) {
const rebase = branch.operation === "rebase";
- const choice = await choiceDialog(
- rebase ? "Commit During Rebase" : "Commit in Detached HEAD",
- rebase
+ problems.push({
+ title: rebase ? "Commit during rebase" : "Commit in detached HEAD",
+ text: rebase
? "A rebase is in progress. The commit will become part of the rebased history; usually you continue the rebase instead."
: "HEAD is detached: the commit won't belong to any branch and may be lost after checking out another branch. Create a branch first to keep it.",
- );
- if (choice !== "commit") return false;
+ });
}
const existing = files.filter((f) => f.exists).map((f) => f.path);
- if (!isTauri() || !existing.length) return true;
+ if (!isTauri() || !existing.length) return problems;
const mods: Modifications = {
reformat: commit.reformat,
@@ -252,16 +245,20 @@ export async function runCommitChecks(files: readonly CommitCandidate[], amend:
const parts = [errors && plural(errors, "error"), warnings && plural(warnings, "warning")]
.filter(Boolean)
.join(" and ");
- const choice = await choiceDialog("Code Analysis", `${parts} found in ${plural(n, "file")}.`, "Review");
- if (choice === "review") {
- try {
- toolWindowService().show("problems", true);
- } catch {
- // no Problems tool window
- }
- return false;
- }
- if (choice === "cancel") return false;
+ problems.push({
+ title: "Code analysis",
+ text: `${parts} found in ${plural(n, "file")}`,
+ details: {
+ label: "Review",
+ run: () => {
+ try {
+ toolWindowService().show("problems", true);
+ } catch {
+ // no Problems tool window
+ }
+ },
+ },
+ });
}
}
@@ -280,30 +277,31 @@ export async function runCommitChecks(files: readonly CommitCandidate[], amend:
}
}
if (hits.length) {
- const choice = await choiceDialog(
- "TODO",
- <>
- <div>{plural(hits.length, "TODO item")} found in the changed lines:</div>
- <ul className={styles.todoList}>
- {hits.slice(0, 20).map((h, i) => (
- <li key={i}>
- <button
- type="button"
- className={styles.linkButton}
- onClick={() =>
- void maybeEditorService()?.openFile(h.path, { selection: { line: h.line, col: 0 }, focus: true })
- }
- >
- {relTo(root, h.path)}:{h.line + 1}
- </button>{" "}
- {h.text}
- </li>
- ))}
- {hits.length > 20 && <li>…</li>}
- </ul>
- </>,
- );
- if (choice !== "commit") return false;
+ problems.push({
+ title: "TODO",
+ text: (
+ <>
+ <div>{plural(hits.length, "TODO item")} found in the changed lines:</div>
+ <ul className={styles.todoList}>
+ {hits.slice(0, 20).map((h, i) => (
+ <li key={i}>
+ <button
+ type="button"
+ className={styles.linkButton}
+ onClick={() =>
+ void maybeEditorService()?.openFile(h.path, { selection: { line: h.line, col: 0 }, focus: true })
+ }
+ >
+ {relTo(root, h.path)}:{h.line + 1}
+ </button>{" "}
+ {h.text}
+ </li>
+ ))}
+ {hits.length > 20 && <li>…</li>}
+ </ul>
+ </>
+ ),
+ });
}
}
@@ -319,18 +317,19 @@ export async function runCommitChecks(files: readonly CommitCandidate[], amend:
}
}
if (crlf.length) {
- const choice = await choiceDialog(
- "Line Separators Warning",
- <>
- {plural(crlf.length, "file")} ({crlf.slice(0, 5).map(baseName).join(", ")}
- {crlf.length > 5 ? ", …" : ""}) contain CRLF line separators and core.autocrlf is not set, so they would be
- committed with CRLF. Convert them with the line separator widget in the status bar, or set{" "}
- <code>git config core.autocrlf input</code>.
- </>,
- );
- if (choice !== "commit") return false;
+ problems.push({
+ title: "Line separators",
+ text: (
+ <>
+ {plural(crlf.length, "file")} ({crlf.slice(0, 5).map(baseName).join(", ")}
+ {crlf.length > 5 ? ", …" : ""}) contain CRLF line separators and core.autocrlf is not set, so they would be
+ committed with CRLF. Convert them with the line separator widget in the status bar, or set{" "}
+ <code>git config core.autocrlf input</code>.
+ </>
+ ),
+ });
}
}
}
- return true;
+ return problems;
}
diff --git a/src/features/vcs/commitStore.ts b/src/features/vcs/commitStore.ts
index 03a7d416c..d73b6e873 100644
--- a/src/features/vcs/commitStore.ts
+++ b/src/features/vcs/commitStore.ts
@@ -2,7 +2,8 @@
import { create } from "zustand";
import { call, commands } from "@/platform/ipc";
import type { CheckState } from "./changes";
-import { useVcs } from "./store";
+import type { CommitProblem } from "./commitChecks";
+import { currentRepo, useVcs } from "./store";
interface CommitState {
message: string;
@@ -15,10 +16,16 @@ interface CommitState {
groupByDir: boolean;
/** User overrides of the inclusion checkboxes (absolute path → state). */
checks: Map<string, CheckState>;
+ /** Changed blocks left out of the commit (absolute path → `hunkKeys`) of `hunks` files. */
+ excludedHunks: Map<string, Set<string>>;
/** Absolute paths selected in the changes tree. */
selection: string[];
/** Bumped to focus the message field. */
focusTick: number;
+ /** Bumped to open the commit message history popup. */
+ historyTick: number;
+ /** Failed before-commit checks; while any are shown, Commit means "Commit Anyway". */
+ checkProblems: CommitProblem[];
tab: CommitTab;
/** Change list of the selected tree node (list actions without an argument). */
selectedList: string | null;
@@ -36,8 +43,11 @@ export const useCommit = create<CommitState>(() => ({
runHooks: true,
groupByDir: readBool("openidea.vcs.groupByDir", false),
checks: new Map(),
+ excludedHunks: new Map(),
selection: [],
focusTick: 0,
+ historyTick: 0,
+ checkProblems: [],
tab: "changes",
selectedList: null,
selectedShelf: null,
@@ -85,6 +95,51 @@ export function rememberMessage(message: string) {
}
}
+/** The message typed before Amend replaced it, and the amended commit's message. */
+let amendData: { before: string; amend: string } | null = null;
+
+/**
+ * Amend checkbox, as in IDEA: checking it replaces the message
+ * with the last commit's (the draft is kept in the message history and restored when
+ * Amend is unchecked again, unless the amend message was edited meanwhile).
+ */
+export async function setAmend(on: boolean) {
+ useCommit.setState({ amend: on });
+ if (!on) {
+ const data = amendData;
+ amendData = null;
+ if (data && useCommit.getState().message === data.amend) useCommit.setState({ message: data.before });
+ return;
+ }
+ let last: string | undefined;
+ try {
+ const [head] = await call(
+ commands.vcsLog(currentRepo(), {
+ branch: "HEAD",
+ path: null,
+ author: null,
+ text: null,
+ range: null,
+ skip: 0,
+ limit: 1,
+ }),
+ );
+ last = head?.message.replace(/\s+$/, "");
+ } catch {
+ // No commits yet.
+ }
+ const before = useCommit.getState().message;
+ if (!last || !useCommit.getState().amend || before.trim() === last.trim()) return;
+ rememberMessage(before);
+ amendData = { before, amend: last };
+ useCommit.setState((s) => ({ message: last, focusTick: s.focusTick + 1 }));
+}
+
+/** After a commit: nothing to restore. */
+export function forgetAmendDraft() {
+ amendData = null;
+}
+
/** Operations whose commit message git prepares in `.git/MERGE_MSG`. */
const PREPARED_MESSAGE_OPS = new Set(["merge", "cherry-pick", "revert"]);
@@ -117,10 +172,12 @@ export function installPreparedMessage(): () => void {
return useVcs.subscribe((s, prev) => {
if (s.root !== prev.root) {
// Another repository: nothing typed or ticked for the previous one carries over (Amend least of all).
+ amendData = null;
useCommit.setState({
message: "",
amend: false,
checks: new Map(),
+ excludedHunks: new Map(),
selection: [],
tab: "changes",
selectedList: null,
diff --git a/src/features/vcs/common.module.css b/src/features/vcs/common.module.css
index 638c378c9..5f152961c 100644
--- a/src/features/vcs/common.module.css
+++ b/src/features/vcs/common.module.css
@@ -215,3 +215,8 @@
min-width: 0;
min-height: 0;
}
+/* Push dialog: the editable target branch. */
+.targetInput {
+ width: 220px;
+ margin-left: 6px;
+}
diff --git a/src/features/vcs/conflicts.ts b/src/features/vcs/conflicts.ts
index 6227336a1..6591743ad 100644
--- a/src/features/vcs/conflicts.ts
+++ b/src/features/vcs/conflicts.ts
@@ -1,4 +1,5 @@
/** Git conflict marker parsing and resolution (pure). */
+import type { MergeSides } from "@/bindings";
export interface ConflictBlock {
/** Offset of the `<<<<<<<` line start. */
@@ -75,30 +76,35 @@ export function parseConflicts(text: string): ConflictBlock[] {
return out;
}
+/** A choice in user terms: "ours" is the user's work ("Accept Yours"). */
export type Resolution = "ours" | "theirs" | "both" | "base";
-export function resolutionText(block: ConflictBlock, how: Resolution): string {
+/**
+ * Text replacing `block`. With `reversed` (a rebase, where git writes the upstream as
+ * the `<<<<<<<` section and the user's commit as `>>>>>>>`) the sides swap, as IDEA does.
+ */
+export function resolutionText(block: ConflictBlock, how: Resolution, reversed = false): string {
+ const yours = reversed ? block.theirs : block.ours;
+ const theirs = reversed ? block.ours : block.theirs;
switch (how) {
case "ours":
- return block.ours;
+ return yours;
case "theirs":
- return block.theirs;
+ return theirs;
case "base":
return block.base ?? "";
- case "both": {
- const a = block.ours;
- return a && !a.endsWith("\n") ? `${a}\n${block.theirs}` : a + block.theirs;
- }
+ case "both":
+ return yours && !yours.endsWith("\n") ? `${yours}\n${theirs}` : yours + theirs;
}
}
/** Resolves every block the same way. */
-export function resolveAll(text: string, how: Resolution): string {
+export function resolveAll(text: string, how: Resolution, reversed = false): string {
const blocks = parseConflicts(text);
let out = "";
let pos = 0;
for (const b of blocks) {
- out += text.slice(pos, b.from) + resolutionText(b, how);
+ out += text.slice(pos, b.from) + resolutionText(b, how, reversed);
pos = b.to;
}
return out + text.slice(pos);
@@ -107,3 +113,35 @@ export function resolveAll(text: string, how: Resolution): string {
export function blockAt(blocks: readonly ConflictBlock[], offset: number): ConflictBlock | undefined {
return blocks.find((b) => b.from <= offset && offset < Math.max(b.to, b.from + 1));
}
+
+/**
+ * Merge editor pane titles for the operation in progress (as IDEA
+ * labels them). English source text, to be passed through `txTemplate`.
+ */
+export function mergeTitles(sides: MergeSides | null | undefined): { yours: string; theirs: string } {
+ const branch = sides?.branch ?? null;
+ const commit = sides?.commit ?? null;
+ const other = sides?.otherBranch ?? null;
+ switch (sides?.operation) {
+ case "rebase":
+ return {
+ yours: commit && branch ? `Rebasing ${commit} from ${branch}` : "Your changes",
+ theirs: other ? `Already rebased commits and commits from ${other}` : "Already rebased commits",
+ };
+ case "merge":
+ return {
+ yours: branch ? `Changes from ${branch}` : "Your version",
+ theirs: other ? `Changes from ${other}` : commit ? `Changes from ${commit}` : "Changes from diverging branches",
+ };
+ case "cherry-pick":
+ return {
+ yours: "Local Changes",
+ theirs: commit ? `Changes from cherry-pick ${commit}` : "Changes from cherry-pick",
+ };
+ default:
+ return {
+ yours: branch ? `Your version, branch ${branch}` : "Your version",
+ theirs: commit ? `Changes from ${commit}` : "Theirs (incoming)",
+ };
+ }
+}
diff --git a/src/features/vcs/conflictsUi.tsx b/src/features/vcs/conflictsUi.tsx
index 689f2502b..28d693f02 100644
--- a/src/features/vcs/conflictsUi.tsx
+++ b/src/features/vcs/conflictsUi.tsx
@@ -148,7 +148,8 @@ export function resolveAtCaret(how: Resolution): boolean {
return false;
}
view.dispatch({
- changes: { from: block.from, to: block.to, insert: resolutionText(block, how) },
+ // During a rebase the user's commit is git's "theirs" section, as in the merge editor.
+ changes: { from: block.from, to: block.to, insert: resolutionText(block, how, inProgress() === "rebase") },
userEvent: "input.resolve",
scrollIntoView: true,
});
diff --git a/src/features/vcs/diffInput.ts b/src/features/vcs/diffInput.ts
index c3daa5ce0..4700a3810 100644
--- a/src/features/vcs/diffInput.ts
+++ b/src/features/vcs/diffInput.ts
@@ -40,6 +40,13 @@ export interface DiffData {
title?: string;
/** Notes shown under lines (unified mode shows the right side's only). */
annotations?: DiffAnnotation[];
+ /**
+ * The files of the change this diff belongs to (IDEA's diff request chain): F7 / Shift+F7
+ * past the last / first difference move to the next / previous one. Entries carry no chain.
+ */
+ chain?: DiffData[];
+ /** Select the first or last difference once shown (moving along the chain). */
+ reveal?: "first" | "last";
}
export const DIFF_KIND = "diff";
@@ -83,8 +90,25 @@ export function sideLabel(s: DiffSide): string {
}
}
+const diffKey = (data: DiffData) => `diff:${data.path}:${sideKey(data.left)}:${sideKey(data.right)}`;
+
export function diffInput(data: DiffData): EditorInput {
- return { kind: DIFF_KIND, key: `diff:${data.path}:${sideKey(data.left)}:${sideKey(data.right)}`, path: data.path, data };
+ return { kind: DIFF_KIND, key: diffKey(data), path: data.path, data };
+}
+
+/** `items` as a chain: each entry knows its siblings. */
+export function withChain(items: readonly DiffData[], index: number): DiffData {
+ const chain = items.length > 1 ? items.map(({ chain: _c, reveal: _r, ...d }) => d) : undefined;
+ return { ...items[index]!, chain };
+}
+
+/** The neighbour of `data` in its chain (`dir` 1: next, -1: previous), revealing the nearest difference. */
+export function chainNeighbour(data: DiffData, dir: 1 | -1): DiffData | null {
+ const chain = data.chain;
+ if (!chain) return null;
+ const index = chain.findIndex((d) => diffKey(d) === diffKey(data));
+ const next = index < 0 ? undefined : chain[index + dir];
+ return next ? { ...next, chain, reveal: dir === 1 ? "first" : "last" } : null;
}
export function diffTitle(data: DiffData): string {
diff --git a/src/features/vcs/gutter.ts b/src/features/vcs/gutter.ts
index bca98acfb..a5c2d654d 100644
--- a/src/features/vcs/gutter.ts
+++ b/src/features/vcs/gutter.ts
@@ -288,3 +288,31 @@ export function gotoChange(view: EditorView, dir: 1 | -1): EditorHunk | undefine
view.focus();
return target;
}
+
+/** Hunks touched by the selection (a deletion counts on the line its marker is on). */
+export function hunksInSelection(state: EditorState): EditorHunk[] {
+ const doc = state.doc;
+ return editorHunks(state).filter((h) =>
+ state.selection.ranges.some((r) => {
+ const first = doc.lineAt(r.from).from;
+ const last = doc.lineAt(r.to).to;
+ if (h.kind === "deleted" || h.to <= h.from) {
+ const marker = doc.lineAt(Math.min(h.from, doc.length)).from;
+ return first <= marker && marker <= last;
+ }
+ return h.from <= last && first < h.to;
+ }),
+ );
+}
+
+/** IDEA's Rollback Lines: restores the hunks touched by the selection; false when there are none. */
+export function rollbackSelectedLines(view: EditorView): boolean {
+ const hunks = hunksInSelection(view.state);
+ if (!hunks.length) return false;
+ view.dispatch({
+ changes: hunks.map((h) => ({ from: h.from, to: h.to, insert: h.oldText })),
+ userEvent: "input.rollback",
+ scrollIntoView: true,
+ });
+ return true;
+}
diff --git a/src/features/vcs/historyActions.tsx b/src/features/vcs/historyActions.tsx
index 4a8ad4272..310efa85b 100644
--- a/src/features/vcs/historyActions.tsx
+++ b/src/features/vcs/historyActions.tsx
@@ -7,7 +7,7 @@ import { getContext, setContext } from "@/platform/context";
import { call, commands } from "@/platform/ipc";
import { notifications, toolWindowService } from "@/workbench/contributions";
import { executeAction, registerActions, type Action } from "@/platform/actions";
-import { newBranch, rebaseOnto } from "./branchOps";
+import { checkoutDetached, newBranch, rebaseOnto } from "./branchOps";
import { openUrl } from "./issueLinks";
import { commitWebUrl } from "./model";
import {
@@ -31,7 +31,6 @@ import {
showResetDialog,
showTagDialog,
} from "./operations";
-import { runOp, saveAll } from "./ops";
import {
dropCommits,
editCommitMessage,
@@ -121,10 +120,7 @@ function shelfArg(arg: unknown) {
}
async function checkoutCommit(c: Commit) {
- await saveAll();
- await runOp(`Checkout ${c.shortId}`, () => call(commands.vcsCheckout(currentRepo(), c.id, false)), {
- success: `Checked out ${c.shortId} (detached HEAD)`,
- });
+ await checkoutDetached(c.id, c.shortId);
}
/** Keeps `vcsOperation` (rebase / merge / cherry-pick / revert / am / "") in sync for `when` clauses. */
diff --git a/src/features/vcs/hunkInclusion.ts b/src/features/vcs/hunkInclusion.ts
new file mode 100644
index 000000000..0377951e3
--- /dev/null
+++ b/src/features/vcs/hunkInclusion.ts
@@ -0,0 +1,162 @@
+/**
+ * Partial commit by changed block (as IDEA):
+ * in a local-changes diff each changed block gets a gutter checkbox that includes it in
+ * the next commit or leaves it out; the file's checkbox in the commit tree goes
+ * tri-state. `commitChanges` then commits only the included blocks.
+ */
+import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
+import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
+import type { LineHunk } from "@/bindings";
+import { tx } from "@/platform/i18n";
+import { commands } from "@/platform/ipc";
+import { checkOf, hunkIncluded, toggledHunk } from "./changes";
+import { useChangelists, withListDefaults } from "./changelists";
+import { useCommit } from "./commitStore";
+import { hunkKeys } from "./hunks";
+import { statusOf, useVcs } from "./store";
+
+interface Block {
+ /** 0-based line of the right side the checkbox sits on. */
+ line: number;
+ key: string;
+}
+
+const setBlocks = StateEffect.define<Block[]>();
+/** Inclusion changed elsewhere (the commit tree, another diff): redraw. */
+const refresh = StateEffect.define<null>();
+
+const blocksField = StateField.define<Block[]>({
+ create: () => [],
+ update: (v, tr) => tr.effects.find((e) => e.is(setBlocks))?.value ?? v,
+});
+
+/** The effective inclusion of `path` (change list defaults applied). */
+function inclusionOf(path: string) {
+ const fs = statusOf(path);
+ if (!fs) return null;
+ const { status, root } = useVcs.getState();
+ const { checks, excludedHunks } = useCommit.getState();
+ const effective = withListDefaults(status, root ?? "", useChangelists.getState().state, checks);
+ return { key: fs.path, check: checkOf(fs, effective), excluded: excludedHunks.get(fs.path) };
+}
+
+/** Includes / excludes one changed block of `path`; `all` are the keys of every block. */
+export function toggleBlock(path: string, all: readonly string[], key: string) {
+ const cur = inclusionOf(path);
+ if (!cur) return;
+ const next = toggledHunk(cur.check, cur.excluded, all, key);
+ const { checks, excludedHunks } = useCommit.getState();
+ const nextChecks = new Map(checks).set(cur.key, next.check);
+ const nextExcluded = new Map(excludedHunks);
+ if (next.excluded.size) nextExcluded.set(cur.key, next.excluded);
+ else nextExcluded.delete(cur.key);
+ useCommit.setState({ checks: nextChecks, excludedHunks: nextExcluded });
+}
+
+class CheckboxMarker extends GutterMarker {
+ constructor(
+ readonly path: string,
+ readonly key: string,
+ readonly all: readonly string[],
+ readonly checked: boolean,
+ ) {
+ super();
+ }
+ eq(o: CheckboxMarker) {
+ return o.key === this.key && o.checked === this.checked && o.all.length === this.all.length;
+ }
+ toDOM() {
+ const box = document.createElement("input");
+ box.type = "checkbox";
+ box.className = "cm-include-hunk";
+ box.checked = this.checked;
+ box.setAttribute("aria-label", tx("Include in commit"));
+ box.title = tx("Include in commit");
+ box.onmousedown = (e) => e.stopPropagation();
+ box.onchange = () => toggleBlock(this.path, this.all, this.key);
+ return box;
+ }
+}
+
+const theme = EditorView.baseTheme({
+ ".cm-include-gutter .cm-gutterElement": { display: "flex", alignItems: "center", padding: "0 2px" },
+ ".cm-include-hunk": { margin: 0, width: "12px", height: "12px", accentColor: "var(--accent)", cursor: "pointer" },
+});
+
+/**
+ * Inclusion checkboxes for the changed blocks of `path` (right side of a HEAD ↔ working
+ * file diff, `base` being the HEAD text). Blocks follow the backend's hunks, which are
+ * what a partial commit applies.
+ */
+export function inclusionGutter(path: string, base: string): Extension {
+ const compute = ViewPlugin.fromClass(
+ class {
+ timer: ReturnType<typeof setTimeout> | null = null;
+ seq = 0;
+ live = true;
+ unsubscribe: () => void;
+ constructor(readonly view: EditorView) {
+ this.schedule(0);
+ this.unsubscribe = useCommit.subscribe((s, p) => {
+ if (s.checks !== p.checks || s.excludedHunks !== p.excludedHunks)
+ queueMicrotask(() => this.live && this.view.dispatch({ effects: refresh.of(null) }));
+ });
+ }
+ update(u: ViewUpdate) {
+ if (u.docChanged) this.schedule(250);
+ }
+ schedule(delay: number) {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(() => void this.run(), delay);
+ }
+ async run() {
+ const seq = ++this.seq;
+ const text = this.view.state.doc.toString();
+ let hunks: LineHunk[];
+ try {
+ hunks = await commands.vcsDiffHunks(base, text);
+ } catch {
+ return;
+ }
+ if (seq !== this.seq || !this.live) return;
+ const keys = hunkKeys(text, hunks);
+ const lines = this.view.state.doc.lines;
+ const blocks = hunks.map((h, i) => ({ line: Math.min(h.start, lines - 1), key: keys[i]! }));
+ this.view.dispatch({ effects: setBlocks.of(blocks) });
+ }
+ destroy() {
+ if (this.timer) clearTimeout(this.timer);
+ this.unsubscribe();
+ this.live = false;
+ }
+ },
+ );
+ const markers = (view: EditorView) => {
+ const blocks = view.state.field(blocksField);
+ const cur = inclusionOf(path);
+ if (!cur || !blocks.length) return RangeSet.empty;
+ const all = blocks.map((b) => b.key);
+ const doc = view.state.doc;
+ const seen = new Set<number>();
+ const ranges = [];
+ for (const b of blocks) {
+ // Two blocks on one line (a deletion right before a change) share the first box.
+ if (seen.has(b.line)) continue;
+ seen.add(b.line);
+ const checked = hunkIncluded(cur.check, cur.excluded, b.key);
+ ranges.push(new CheckboxMarker(path, b.key, all, checked).range(doc.line(b.line + 1).from));
+ }
+ return RangeSet.of(ranges, true);
+ };
+ return [
+ blocksField,
+ compute,
+ theme,
+ gutter({
+ class: "cm-include-gutter",
+ markers,
+ lineMarkerChange: (u) =>
+ u.docChanged || u.transactions.some((t) => t.effects.some((e) => e.is(setBlocks) || e.is(refresh))),
+ }),
+ ];
+}
diff --git a/src/features/vcs/hunks.ts b/src/features/vcs/hunks.ts
index cc7322296..f0cc5e455 100644
--- a/src/features/vcs/hunks.ts
+++ b/src/features/vcs/hunks.ts
@@ -99,3 +99,20 @@ export function hunksOverlapping(
});
return out;
}
+
+/**
+ * Identity of a changed block that survives edits elsewhere in the file: its old and
+ * new text (an FNV-1a hash), plus how often the same block occurs before it.
+ */
+export function hunkKeys(text: string, hunks: readonly Pick<LineHunk, "start" | "lines" | "oldText">[]): string[] {
+ const seen = new Map<string, number>();
+ return hunks.map((h) => {
+ const body = `${h.oldText}\u0000${currentHunkText(text, h)}`;
+ let x = 0x811c9dc5;
+ for (let i = 0; i < body.length; i++) x = Math.imul(x ^ body.charCodeAt(i), 0x01000193);
+ const base = `${(x >>> 0).toString(36)}:${body.length}`;
+ const n = seen.get(base) ?? 0;
+ seen.set(base, n + 1);
+ return `${base}:${n}`;
+ });
+}
diff --git a/src/features/vcs/ops.ts b/src/features/vcs/ops.ts
index c8c54d292..2416b14b1 100644
--- a/src/features/vcs/ops.ts
+++ b/src/features/vcs/ops.ts
@@ -179,6 +179,7 @@ export async function runRemote(
// Every repository is tried; the failures are reported together. A pull skips the
// repositories that have nothing to pull from (detached HEAD, e.g. submodules; no upstream).
const failures: string[] = [];
+ const updated: UpdatedRange[] = [];
for (const repo of repos) {
const name = repos.length > 1 && repo ? repoName(repo) : null;
if (name) logConsole("info", name);
@@ -190,7 +191,10 @@ export async function runRemote(
}
}
try {
+ const before = op.op === "pull" ? await headCommit(repo) : null;
await call(commands.vcsRemote(repo, request, op, channel));
+ const after = before ? await headCommit(repo) : null;
+ if (before && after && before !== after) updated.push({ repo, from: before, to: after });
} catch (e) {
if (isCancelled(e) || !name) throw e;
logConsole("err", errorMessage(e));
@@ -199,13 +203,15 @@ export async function runRemote(
}
if (failures.length) throw new Error(failures.join("\n"));
lastRemoteError = null;
- notifications().notify({
- group: "vcs",
- level: "info",
- key: "vcs.remote",
- title: `${doneTitle} successful`,
- body: lastLine && !/%/.test(lastLine) ? lastLine : undefined,
- });
+ if (op.op === "pull") await notifyUpdated(updated);
+ else
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ key: "vcs.remote",
+ title: `${doneTitle} successful`,
+ body: lastLine && !/%/.test(lastLine) ? lastLine : undefined,
+ });
return true;
} catch (e) {
const cancelled = isCancelled(e);
@@ -227,6 +233,65 @@ export async function runRemote(
}
}
+interface UpdatedRange {
+ repo: string | null;
+ from: string;
+ to: string;
+}
+
+const headCommit = (repo: string | null) =>
+ call(commands.vcsBranchInfo(repo)).then(
+ (i) => i.headCommit,
+ () => null,
+ );
+
+const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
+
+/** IDEA's Update Project result: "N files updated in M commits" with View Commits. */
+async function notifyUpdated(updated: readonly UpdatedRange[]) {
+ if (!updated.length) {
+ notifications().notify({ group: "vcs", level: "info", key: "vcs.remote", title: "All files are up-to-date" });
+ return;
+ }
+ let files = 0;
+ let commits = 0;
+ await Promise.all(
+ updated.map(async ({ repo, from, to }) => {
+ const [changed, log] = await Promise.all([
+ call(commands.vcsDiffRevisions(repo, from, to)).catch(() => []),
+ call(
+ commands.vcsLog(repo, {
+ branch: null,
+ path: null,
+ author: null,
+ text: null,
+ range: `${from}..${to}`,
+ skip: 0,
+ limit: 0,
+ }),
+ ).catch(() => []),
+ ]);
+ files += changed.length;
+ commits += log.length;
+ }),
+ );
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ key: "vcs.remote",
+ title: `${plural(files, "file")} updated in ${plural(commits, "commit")}`,
+ actions: [
+ {
+ label: "View Commits",
+ run: () => {
+ const { repo, from, to } = updated.find((u) => u.repo === currentRepo()) ?? updated[0]!;
+ void import("./CompareBranches").then((m) => m.showCommitRange("Update Info", from, to, repo));
+ },
+ },
+ ],
+ });
+}
+
// ---------------------------------------------------------------------------
// Local history operations (continue / abort / cherry-pick / revert / reset)
diff --git a/src/features/vcs/remoteUi.tsx b/src/features/vcs/remoteUi.tsx
index 91c24e602..920abc942 100644
--- a/src/features/vcs/remoteUi.tsx
+++ b/src/features/vcs/remoteUi.tsx
@@ -5,7 +5,8 @@ import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
-import { Checkbox, Dialog, List, Select, Spinner, T } from "@/ui";
+import { Checkbox, Dialog, Input, List, Select, Spinner, T } from "@/ui";
+import { ask } from "@/workbench/messages";
import { openDialog } from "./dialogs";
import { formatTime } from "./model";
import { allRepos, lastRemoteFailure, runRemote, saveAll } from "./ops";
@@ -301,14 +302,28 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
};
}, [head, upstream, explicit, revision]);
- const target = upstream ? upstream.slice(upstream.indexOf("/") + 1) : head;
+ const remote = upstream ? upstream.slice(0, upstream.indexOf("/")) : null;
+ const defaultTarget = upstream ? upstream.slice(upstream.indexOf("/") + 1) : head;
+ // IDEA's push target is editable: another name pushes to that branch of the same remote.
+ const [targetName, setTargetName] = useState(defaultTarget ?? "");
+ const edited = targetName.trim();
+ const retarget = !!head && !!edited && edited !== defaultTarget;
+ const target = retarget ? edited : defaultTarget;
+ const targetLabel = retarget ? `${remote ? `${remote}/` : ""}${edited}` : (upstream ?? "new remote branch");
const protectedTarget = !!target && isProtectedBranch(target);
const push = async () => {
+ if (force && !protectedTarget && !(await confirmForcePush(remote ? `${remote}/${target}` : (target ?? "")))) return;
onClose();
- if (explicit && head) {
+ if ((explicit || retarget) && head) {
await runRemote(
- { op: "pushBranch", branch: head, revision, force_with_lease: force && !protectedTarget },
- `${revision ? `${head} up to ${revision.slice(0, 8)}` : head} → ${upstream ?? "new remote branch"}`,
+ {
+ op: "pushBranch",
+ branch: head,
+ revision,
+ force_with_lease: force && !protectedTarget,
+ target: retarget ? edited : null,
+ },
+ `${revision ? `${head} up to ${revision.slice(0, 8)}` : head} → ${targetLabel}`,
);
return;
}
@@ -339,7 +354,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
label="Force (with lease)"
/>
</span>
- {!explicit && (
+ {!explicit && !retarget && (
<>
<Checkbox
checked={setUpstream || !upstream}
@@ -377,10 +392,20 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
{!head
? "HEAD is detached; check out a branch to push."
: upstream
- ? `${head}${revision ? ` up to ${revision.slice(0, 8)}` : ""} → ${upstream}`
+ ? `${head}${revision ? ` up to ${revision.slice(0, 8)}` : ""} → ${remote}/`
: revision
- ? `${head} has no upstream: commits up to ${revision.slice(0, 8)} will be pushed as a new branch.`
- : `${head} has no upstream: it will be pushed as a new branch and tracked.`}
+ ? `${head} has no upstream: commits up to ${revision.slice(0, 8)} will be pushed as a new branch:`
+ : `${head} has no upstream: it will be pushed as a new branch and tracked:`}
+ {head && (
+ <Input
+ aria-label="Target branch"
+ mono
+ value={targetName}
+ onChange={(e) => setTargetName(e.target.value)}
+ className={styles.targetInput}
+ />
+ )}
+ {retarget && <span className={styles.hint}> {tx("New")}</span>}
</div>
<div style={{ height: 300, display: "flex", flexDirection: "column", padding: "0 14px 14px" }}>
{error ? (
@@ -412,6 +437,38 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
);
}
+const SILENT_FORCE_PUSH_KEY = "openidea.vcs.silentForcePushTargets";
+
+function silentForcePushTargets(): string[] {
+ try {
+ const v: unknown = JSON.parse(localStorage.getItem(SILENT_FORCE_PUSH_KEY) ?? "[]");
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+/** IDEA's force push confirmation, with "Don't warn about this target". */
+async function confirmForcePush(target: string): Promise<boolean> {
+ if (target && silentForcePushTargets().includes(target)) return true;
+ const r = await ask({
+ title: "Force Push",
+ body: `You're going to force push to '${target}'. It may overwrite commits at the remote. Are you sure you want to proceed?`,
+ icon: "warning",
+ checkbox: target ? "Don't warn about this target" : undefined,
+ buttons: [{ id: "force", label: "Force Push", primary: true }],
+ });
+ if (r.button !== "force") return false;
+ if (r.checked && target) {
+ try {
+ localStorage.setItem(SILENT_FORCE_PUSH_KEY, JSON.stringify([...silentForcePushTargets(), target]));
+ } catch {
+ // Not remembered: the next force push asks again.
+ }
+ }
+ return true;
+}
+
/** Settings › Git › Protected branches: `;`/`,`-separated globs (`*`, `?`). */
export function isProtectedBranch(branch: string, patterns = workflowSettings().vcs.git.protectedBranches): boolean {
return patterns
diff --git a/src/platform/colorScheme.test.ts b/src/platform/colorScheme.test.ts
index 55cda8be4..b6ac2d926 100644
--- a/src/platform/colorScheme.test.ts
+++ b/src/platform/colorScheme.test.ts
@@ -24,7 +24,7 @@ describe("color schemes", () => {
it("coerces editor settings to their defaults' shape", () => {
const v = validateEditorExtras({ tabs: { tabLimit: "x", placement: "none" }, codeStyle: { languages: { go: { useTab: true } } } });
- expect(v.tabs.tabLimit).toBe(10);
+ expect(v.tabs.tabLimit).toBe(30);
expect(v.tabs.placement).toBe("none");
expect(v.codeStyle.languages.go).toEqual({ useTab: true });
expect(v.general.softWrapFiles).toContain("*.md");
diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts
index 833e44f4e..b06fb0078 100644
--- a/src/platform/editorSettings.ts
+++ b/src/platform/editorSettings.ts
@@ -20,6 +20,34 @@ export interface LanguageCodeStyle {
tabSize?: number;
indent?: number;
hardWrapAt?: number;
+ /** Code Generation › Comment Code (unset: the language's default, see `lineCommentDefaults`). */
+ lineCommentAtFirstColumn?: boolean;
+ lineCommentAddSpace?: boolean;
+}
+
+/**
+ * IDEA's per-language Comment Code defaults: line comments at the first column
+ * without a space, except where the language's code
+ * style says otherwise (Python's indented `# `; Go and Rust's indented `// `).
+ */
+const LINE_COMMENT_DEFAULTS: Record<string, { atFirstColumn: boolean; addSpace: boolean }> = {
+ python: { atFirstColumn: false, addSpace: true },
+ go: { atFirstColumn: false, addSpace: true },
+ rust: { atFirstColumn: false, addSpace: true },
+};
+
+export function lineCommentDefaults(language: string | undefined): { atFirstColumn: boolean; addSpace: boolean } {
+ return (language && LINE_COMMENT_DEFAULTS[language]) || { atFirstColumn: true, addSpace: false };
+}
+
+/** Effective Comment Code style of a language: Code Style override, else the language default. */
+export function lineCommentStyleFor(prefs: EditorExtras, language: string | undefined): { atFirstColumn: boolean; addSpace: boolean } {
+ const base = lineCommentDefaults(language);
+ const own = language ? prefs.codeStyle.languages[language] : undefined;
+ return {
+ atFirstColumn: typeof own?.lineCommentAtFirstColumn === "boolean" ? own.lineCommentAtFirstColumn : base.atFirstColumn,
+ addSpace: typeof own?.lineCommentAddSpace === "boolean" ? own.lineCommentAddSpace : base.addSpace,
+ };
}
export const EDITOR_EXTRA_DEFAULTS = {
@@ -52,16 +80,16 @@ export const EDITOR_EXTRA_DEFAULTS = {
intentionBulb: true,
distractionFreeWidth: 80,
},
- breadcrumbs: { show: false, placement: "bottom", disabledLanguages: [] as string[] },
+ breadcrumbs: { show: true, placement: "bottom", disabledLanguages: [] as string[] },
completion: {
matchCase: true,
caseSensitivity: "first",
autoPopup: true,
insertOnSpecialKeys: false,
- showDocumentation: true,
+ showDocumentation: false,
documentationDelay: 500,
parameterInfo: true,
- parameterInfoDelay: 300,
+ parameterInfoDelay: 1000,
},
autoImport: { addUnambiguous: false, optimizeOnTheFly: false },
folding: { showOutline: true, fileHeader: true, imports: true, docComments: false },
@@ -73,9 +101,9 @@ export const EDITOR_EXTRA_DEFAULTS = {
showCloseButton: true,
previewTab: true,
openAtEnd: false,
- tabLimit: 10,
- closingPolicy: "unchanged",
- activateOnClose: "mru",
+ tabLimit: 30,
+ closingPolicy: "lru",
+ activateOnClose: "left",
},
smartKeys: {
smartHome: true,
@@ -83,10 +111,10 @@ export const EDITOR_EXTRA_DEFAULTS = {
pairBrackets: true,
pairQuotes: true,
surroundSelection: true,
- tabOutOfPair: false,
+ tabOutOfPair: true,
reformatOnPaste: "indentBlock",
smartIndent: true,
- backspaceUnindent: "nearest",
+ backspaceUnindent: "autoindent",
},
codeEditing: {
highlightUsages: true,
diff --git a/src/platform/keymap.test.ts b/src/platform/keymap.test.ts
index 5af49cb63..58b9fe451 100644
--- a/src/platform/keymap.test.ts
+++ b/src/platform/keymap.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { formatBinding, installKeyboardDispatcher, normalizeBinding, strokeOf, useKeymap } from "./keymap";
+import { formatBinding, installKeyboardDispatcher, isAltGrTyping, normalizeBinding, strokeOf, useKeymap } from "./keymap";
import { executeAction, registerAction } from "./actions";
+import { usePlatform } from "./platformInfo";
describe("keymap", () => {
it("normalizes modifier order and case", () => {
@@ -65,5 +66,144 @@ describe("keymap", () => {
expect(await executeAction("t.keyGated")).toBe(true);
expect(run).toHaveBeenCalledOnce();
});
+
+ it("waits 2s for a chord's second stroke and swallows a wrong one", async () => {
+ vi.useFakeTimers();
+ try {
+ const chord = vi.fn();
+ registerAction({ id: "t.chord2", title: "chord2", run: chord });
+ useKeymap.setState({ overrides: { "t.chord2": ["Meta+K Meta+C"] } });
+ uninstall = installKeyboardDispatcher(window);
+ const press = (code: string, init: KeyboardEventInit) => {
+ const e = new KeyboardEvent("keydown", { code, bubbles: true, cancelable: true, ...init });
+ window.dispatchEvent(e);
+ return e;
+ };
+ press("KeyK", { key: "k", metaKey: true });
+ vi.advanceTimersByTime(1900);
+ press("KeyC", { key: "c", metaKey: true });
+ await Promise.resolve();
+ expect(chord).toHaveBeenCalledOnce();
+
+ press("KeyK", { key: "k", metaKey: true });
+ expect(press("KeyX", { key: "x" }).defaultPrevented).toBe(true);
+ // The chord is over: the next stroke is an ordinary key again.
+ expect(press("KeyC", { key: "c", metaKey: true }).defaultPrevented).toBe(false);
+
+ press("KeyK", { key: "k", metaKey: true });
+ vi.advanceTimersByTime(2001);
+ press("KeyC", { key: "c", metaKey: true });
+ await Promise.resolve();
+ expect(chord).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ });
+
+ describe("double Shift", () => {
+ let uninstall = () => {};
+ afterEach(() => uninstall());
+
+ function setup() {
+ const run = vi.fn();
+ registerAction({ id: "t.doubleShift", title: "double shift", run });
+ useKeymap.setState({ overrides: { "t.doubleShift": ["Shift Shift"] } });
+ let t = 1000;
+ uninstall = installKeyboardDispatcher(window, () => t);
+ const at = (ms: number) => (t = ms);
+ const shift = (type: "keydown" | "keyup", ms: number) => {
+ at(ms);
+ window.dispatchEvent(new KeyboardEvent(type, { key: "Shift", code: "ShiftLeft", shiftKey: type === "keydown" }));
+ };
+ const tap = (ms: number, hold = 50) => {
+ shift("keydown", ms);
+ shift("keyup", ms + hold);
+ };
+ return { run, at, shift, tap };
+ }
+
+ it("fires on the second release when every step is within 300ms", async () => {
+ const { run, tap } = setup();
+ tap(1000);
+ tap(1200);
+ await Promise.resolve();
+ expect(run).toHaveBeenCalledOnce();
+ });
+
+ it("ignores slow steps", () => {
+ const { run, tap, shift } = setup();
+ tap(1000);
+ tap(1400);
+ expect(run).not.toHaveBeenCalled();
+ shift("keydown", 2000);
+ shift("keyup", 2400); // held too long
+ tap(2500);
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("ignores Shift tapped right after typing", () => {
+ const { run, tap, at } = setup();
+ at(990);
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "a", code: "KeyA" }));
+ tap(1000);
+ tap(1150);
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("is cancelled by a click or another key while Shift is held", () => {
+ const { run, tap, shift } = setup();
+ shift("keydown", 1000);
+ window.dispatchEvent(new MouseEvent("mousedown", { shiftKey: true }));
+ shift("keyup", 1100);
+ tap(1200);
+ expect(run).not.toHaveBeenCalled();
+
+ shift("keydown", 3000);
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", code: "ArrowDown", shiftKey: true }));
+ shift("keyup", 3100);
+ tap(3400);
+ expect(run).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("AltGr", () => {
+ let uninstall = () => {};
+ afterEach(() => {
+ uninstall();
+ usePlatform.setState({ os: "macos" });
+ document.body.innerHTML = "";
+ });
+
+ const altGr = (key: string, code: string, target: EventTarget) => {
+ const e = new KeyboardEvent("keydown", { key, code, ctrlKey: true, altKey: true, bubbles: true, cancelable: true });
+ Object.defineProperty(e, "getModifierState", { value: (k: string) => k === "AltGraph" });
+ target.dispatchEvent(e);
+ return e;
+ };
+
+ it("lets AltGr characters reach text fields on Windows / Linux", async () => {
+ usePlatform.setState({ os: "windows" });
+ const run = vi.fn();
+ registerAction({ id: "t.altGr", title: "altGr", run });
+ useKeymap.setState({ overrides: { "t.altGr": ["Ctrl+Alt+0"] } });
+ uninstall = installKeyboardDispatcher(window);
+ const input = document.body.appendChild(document.createElement("textarea"));
+ expect(altGr("}", "Digit0", input).defaultPrevented).toBe(false);
+ await Promise.resolve();
+ expect(run).not.toHaveBeenCalled();
+ // No AltGr character on that key (or not typing): it is the shortcut.
+ altGr("0", "Digit0", input);
+ altGr("}", "Digit0", document.body);
+ await Promise.resolve();
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it("never applies on macOS, where ⌥ shortcuts type symbols", () => {
+ usePlatform.setState({ os: "macos" });
+ const input = document.createElement("input");
+ const e = { key: "ƒ", code: "KeyF", target: input, metaKey: false, ctrlKey: false, altKey: true, shiftKey: false, getModifierState: () => true };
+ expect(isAltGrTyping(e)).toBe(false);
+ });
});
});
diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts
index 9f658a403..81caa76f4 100644
--- a/src/platform/keymap.ts
+++ b/src/platform/keymap.ts
@@ -245,8 +245,12 @@ export function shortcutLabel(actionId: string): string | undefined {
// ---------------------------------------------------------------------------
// Dispatcher
-const CHORD_TIMEOUT = 1200;
-const DOUBLE_TAP_MS = 350;
+/** How long IDEA waits for the second stroke of a chord. */
+const CHORD_TIMEOUT = 2000;
+/** IDEA's double-modifier timing: each press/release step. */
+const DOUBLE_TAP_STEP_MS = 300;
+/** A Shift tap this soon after typing another key is part of typing, not a gesture. */
+const DOUBLE_TAP_TYPING_GUARD_MS = 100;
function isPlainTextField(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
@@ -255,6 +259,30 @@ function isPlainTextField(target: EventTarget | null): boolean {
return el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable;
}
+function isTextTarget(target: EventTarget | null): boolean {
+ const el = target as HTMLElement | null;
+ if (!el || !el.tagName) return false;
+ return !!el.closest?.(".cm-editor") || el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable;
+}
+
+/**
+ * AltGr (reported as Ctrl+Alt on Windows) typing a character into a text field
+ * or editor, e.g. `}` on a German or `ł` on a Polish layout: the character wins
+ * over a Ctrl+Alt shortcut on the same key, as in IDEA.
+ */
+export function isAltGrTyping(
+ e: Pick<KeyboardEvent, "key" | "code" | "target" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey"> & {
+ getModifierState?: (key: string) => boolean;
+ },
+): boolean {
+ if (isMacHost() || !e.getModifierState?.("AltGraph")) return false;
+ if (e.key !== "Dead" && e.key.length !== 1) return false;
+ if (!isTextTarget(e.target)) return false;
+ // Ctrl+Alt+L on a layout with no AltGr character there still reports `l`: that is a shortcut.
+ const key = strokeOf(e)?.split("+").pop();
+ return e.key === "Dead" || e.key.toUpperCase() !== key;
+}
+
function runIfEnabled(id: string): boolean {
const action = getAction(id);
if (!action || !isActionKeyEnabled(action)) return false;
@@ -264,37 +292,55 @@ function runIfEnabled(id: string): boolean {
/**
* Installs the global keydown dispatcher (capture phase, so IDE shortcuts win
- * over CodeMirror defaults). Returns an uninstall function.
+ * over CodeMirror defaults). Returns an uninstall function. `now` is the clock
+ * for the double-Shift gesture.
*/
-export function installKeyboardDispatcher(target: Window = window): () => void {
+export function installKeyboardDispatcher(target: Window = window, now: () => number = () => performance.now()): () => void {
let pending: string[] = [];
let pendingTimer: ReturnType<typeof setTimeout> | undefined;
- let lastShiftUp = 0;
- let shiftClean = false;
+ // Double Shift: 0 idle, 1 pressed, 2 released, 3 pressed again; fires on the second release.
+ let shiftStep = 0;
+ let shiftAt = 0;
+ let otherKeyAt = -Infinity;
const reset = () => {
pending = [];
clearTimeout(pendingTimer);
};
+ const resetShift = () => {
+ shiftStep = 0;
+ };
+
+ const onShiftDown = (e: KeyboardEvent) => {
+ const t = now();
+ if (e.repeat || e.metaKey || e.ctrlKey || e.altKey || t - otherKeyAt < DOUBLE_TAP_TYPING_GUARD_MS) return resetShift();
+ if (shiftStep !== 0 && t - shiftAt > DOUBLE_TAP_STEP_MS) resetShift();
+ if (shiftStep === 0 || shiftStep === 2) {
+ shiftStep++;
+ shiftAt = t;
+ } else {
+ resetShift();
+ }
+ };
const onKeyDown = (e: KeyboardEvent) => {
if (suspended > 0) {
reset();
- shiftClean = false;
- return;
- }
- if (e.key === "Shift") {
- shiftClean = !e.repeat && !e.metaKey && !e.ctrlKey && !e.altKey;
+ resetShift();
return;
}
- shiftClean = false;
- lastShiftUp = 0;
+ if (e.key === "Shift") return onShiftDown(e);
+ resetShift();
+ otherKeyAt = e.key === "Escape" || e.key === "Tab" ? -Infinity : now();
if (e.isComposing) return;
const stroke = strokeOf(e);
if (!stroke) return;
-
- const hasCommandMod = e.metaKey || e.ctrlKey || e.altKey;
- if (!hasCommandMod && isPlainTextField(e.target) && !/^(Shift\+)?(F\d{1,2}|Escape)$/.test(stroke)) return;
+ const chord = pending.length > 0;
+ if (!chord) {
+ if (isAltGrTyping(e)) return;
+ const hasCommandMod = e.metaKey || e.ctrlKey || e.altKey;
+ if (!hasCommandMod && isPlainTextField(e.target) && !/^(Shift\+)?(F\d{1,2}|Escape)$/.test(stroke)) return;
+ }
const seq = [...pending, stroke].join(" ");
const bindings = effectiveBindings();
@@ -319,32 +365,46 @@ export function installKeyboardDispatcher(target: Window = window): () => void {
pendingTimer = setTimeout(reset, CHORD_TIMEOUT);
return;
}
+ // A second stroke that completes no chord is swallowed, as in IDEA, not typed.
+ if (chord) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
reset();
};
const onKeyUp = (e: KeyboardEvent) => {
- if (suspended > 0 || e.key !== "Shift" || !shiftClean) return;
- const now = performance.now();
- if (lastShiftUp && now - lastShiftUp < DOUBLE_TAP_MS) {
- lastShiftUp = 0;
- const target = effectiveBindings().find(([b]) => b === "Shift Shift");
- if (target) runIfEnabled(target[1]);
- } else {
- lastShiftUp = now;
+ if (suspended > 0 || e.key !== "Shift" || shiftStep === 0) return;
+ const t = now();
+ if (e.metaKey || e.ctrlKey || e.altKey || t - shiftAt > DOUBLE_TAP_STEP_MS) return resetShift();
+ if (shiftStep === 1) {
+ shiftStep = 2;
+ shiftAt = t;
+ return;
}
+ const fire = shiftStep === 3;
+ resetShift();
+ if (!fire) return;
+ const ids = effectiveBindings().filter(([b]) => b === "Shift Shift").map(([, id]) => id);
+ for (const id of ids.reverse()) if (runIfEnabled(id)) return;
};
+ // Shift+click (extend a selection) is not half of a double Shift.
+ const onMouseDown = () => resetShift();
+
const onBlur = () => {
reset();
- lastShiftUp = 0;
+ resetShift();
};
target.addEventListener("keydown", onKeyDown, true);
target.addEventListener("keyup", onKeyUp, true);
+ target.addEventListener("mousedown", onMouseDown, true);
target.addEventListener("blur", onBlur);
return () => {
target.removeEventListener("keydown", onKeyDown, true);
target.removeEventListener("keyup", onKeyUp, true);
+ target.removeEventListener("mousedown", onMouseDown, true);
target.removeEventListener("blur", onBlur);
};
}
diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts
new file mode 100644
index 000000000..f60c61ee2
--- /dev/null
+++ b/src/platform/keymaps/ideaParity.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { intellijMacos } from "./intellij-macos";
+import { intellijWindows } from "./intellij-windows";
+
+/** Bindings checked against IDEA's `$default.xml` (Windows) and `Mac OS X 10.5+.xml`. */
+describe("IDEA keymap parity", () => {
+ it.each([
+ ["code.splitLine", ["Meta+Enter"], ["Ctrl+Enter"]],
+ ["editor.scrollToCenter", ["Ctrl+L"], ["Ctrl+M"]],
+ ["editor.codeBlockStart", ["Meta+Alt+["], ["Ctrl+["]],
+ ["editor.codeBlockEnd", ["Meta+Alt+]"], ["Ctrl+]"]],
+ ["view.zoomIn", ["Ctrl+Alt+="], ["Alt+Shift+="]],
+ ["view.zoomOut", ["Ctrl+Alt+-"], ["Alt+Shift+-"]],
+ ["view.resetZoom", ["Ctrl+Alt+0"], ["Alt+Shift+0"]],
+ ["vcs.changelist.move", ["Meta+Shift+M"], ["Alt+Shift+M"]],
+ ["vcs.changelist.edit", ["F2", "Shift+F6"], ["F2", "Shift+F6"]],
+ ["code.quickDocumentation", ["F1", "Ctrl+J"], ["Ctrl+Q"]],
+ // Git.Branches: the macOS keymaps remove ⇧⌘` (it cycles windows there).
+ ["vcs.branches", [], ["Ctrl+Shift+`"]],
+ ["debug.resume", ["Meta+Alt+R", "F9"], ["F9"]],
+ ["code.quickDefinition", ["Alt+Space", "Meta+Y"], ["Ctrl+Shift+I"]],
+ ["editor.copyPath", ["Meta+Shift+C"], ["Ctrl+Shift+C"]],
+ ["project.open", ["F4", "Meta+Down"], ["F4"]],
+ ["project.delete", ["Delete", "Backspace", "Meta+Backspace"], ["Delete"]],
+ ["file.reloadFromDisk", ["Meta+Alt+Y"], ["Ctrl+Alt+Y"]],
+ ["project.reloadFromDisk", ["Meta+Alt+Y"], ["Ctrl+Alt+Y"]],
+ ["project.expandAll", ["Meta+="], ["Ctrl+="]],
+ ["project.collapseAll", ["Meta+-"], ["Ctrl+-"]],
+ ["navigate.searchText", ["Meta+Alt+Shift+E"], ["Ctrl+Alt+Shift+E"]],
+ ["window.next", ["Meta+Alt+`"], ["Ctrl+Alt+]"]],
+ ["window.previous", ["Meta+Alt+Shift+`"], ["Ctrl+Alt+["]],
+ ["code.commentBlock", ["Meta+Alt+/", "Ctrl+Shift+/"], ["Ctrl+Shift+/"]],
+ ["navigate.typeDeclaration", ["Meta+Shift+B", "Ctrl+Shift+B"], ["Ctrl+Shift+B"]],
+ ["find.next", ["Meta+G"], ["F3", "Ctrl+L"]],
+ ["find.previous", ["Meta+Shift+G"], ["Shift+F3", "Ctrl+Shift+L"]],
+ ["project.copy", ["Meta+C"], ["Ctrl+C", "Ctrl+Insert"]],
+ ["project.cut", ["Meta+X"], ["Ctrl+X", "Shift+Delete"]],
+ ["project.paste", ["Meta+V"], ["Ctrl+V", "Shift+Insert"]],
+ ])("%s", (id, mac, win) => {
+ expect(intellijMacos[id]).toEqual(mac);
+ expect(intellijWindows[id]).toEqual(win);
+ });
+
+ // Later entries win a shared key while their `when` / `keyWhen` holds.
+ const order = (km: Record<string, string[]>, earlier: string, later: string) => {
+ const ids = Object.keys(km);
+ expect(ids.indexOf(earlier), `${earlier} before ${later}`).toBeLessThan(ids.indexOf(later));
+ };
+
+ it.each([intellijMacos, intellijWindows])("lets scoped actions win shared keys", (km) => {
+ order(km, "code.splitLine", "http.runRequest");
+ order(km, "code.splitLine", "db.execute");
+ order(km, "editor.copyPath", "project.copyAbsolutePath");
+ order(km, "file.reloadFromDisk", "project.reloadFromDisk");
+ order(km, "code.unfold", "project.expandAll");
+ order(km, "code.fold", "project.collapseAll");
+ order(km, "navigate.nextError", "vcs.changelist.edit");
+ order(km, "debug.setValue", "vcs.changelist.edit");
+ });
+});
diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts
index 03e41d194..a6f608976 100644
--- a/src/platform/keymaps/intellij-macos.ts
+++ b/src/platform/keymaps/intellij-macos.ts
@@ -9,6 +9,7 @@ export const intellijMacos: Record<string, string[]> = {
"navigate.gotoFile": ["Meta+Shift+O"],
"navigate.gotoSymbol": ["Meta+Alt+O"],
"navigate.findAction": ["Meta+Shift+A"],
+ "navigate.searchText": ["Meta+Alt+Shift+E"],
"navigate.navigationBar": ["Meta+Up", "Alt+Home"],
"navigate.switcher": ["Ctrl+Tab"],
"navigate.switcherBack": ["Ctrl+Shift+Tab"],
@@ -19,7 +20,7 @@ export const intellijMacos: Record<string, string[]> = {
"navigate.gotoLine": ["Meta+L"],
"navigate.declaration": ["Meta+B"],
"navigate.implementation": ["Meta+Alt+B"],
- "navigate.typeDeclaration": ["Meta+Shift+B"],
+ "navigate.typeDeclaration": ["Meta+Shift+B", "Ctrl+Shift+B"],
"navigate.fileStructure": ["Meta+F12"],
"navigate.nextError": ["F2"],
"navigate.prevError": ["Shift+F2"],
@@ -49,13 +50,13 @@ export const intellijMacos: Record<string, string[]> = {
// Code
"code.completion": ["Ctrl+Space"],
"code.parameterInfo": ["Meta+P"],
- "code.quickDocumentation": ["F1"],
- "code.quickDefinition": ["Alt+Space"],
+ "code.quickDocumentation": ["F1", "Ctrl+J"],
+ "code.quickDefinition": ["Alt+Space", "Meta+Y"],
"code.showIntentions": ["Alt+Enter"],
"code.reformat": ["Meta+Alt+L"],
"code.optimizeImports": ["Ctrl+Alt+O"],
"code.commentLine": ["Meta+/"],
- "code.commentBlock": ["Meta+Alt+/"],
+ "code.commentBlock": ["Meta+Alt+/", "Ctrl+Shift+/"],
"code.extendSelection": ["Alt+Up"],
"code.shrinkSelection": ["Alt+Down"],
"code.duplicateLine": ["Meta+D"],
@@ -77,6 +78,14 @@ export const intellijMacos: Record<string, string[]> = {
"code.addCaretsToLineEnds": ["Alt+Shift+G"],
"code.startNewLine": ["Shift+Enter"],
"code.startNewLineBefore": ["Meta+Alt+Enter"],
+ // Before the HTTP / SQL consoles' ⌘↵ (Run), which wins there.
+ "code.splitLine": ["Meta+Enter"],
+ "editor.scrollToCenter": ["Ctrl+L"],
+ "editor.codeBlockStart": ["Meta+Alt+["],
+ "editor.codeBlockEnd": ["Meta+Alt+]"],
+ // IDEA clones carets with ⌥⌥↑ / ⌥⌥↓ (double modifier); no single-stroke default.
+ "editor.cloneCaretAbove": [],
+ "editor.cloneCaretBelow": [],
"code.joinLines": ["Ctrl+Shift+J"],
"code.toggleCase": ["Meta+Shift+U"],
"code.pasteFromHistory": ["Meta+Shift+V"],
@@ -105,26 +114,36 @@ export const intellijMacos: Record<string, string[]> = {
"file.openProject": ["Meta+Shift+Alt+O"],
"file.newScratchFile": ["Meta+Shift+N"],
"editor.closeTab": ["Meta+W"],
+ "toolwindow.closeContent": ["Meta+W"],
"editor.reopenClosedTab": [],
"file.toggleReadOnly": [],
"editor.nextTab": ["Ctrl+Right", "Meta+Shift+]"],
"editor.prevTab": ["Ctrl+Left", "Meta+Shift+["],
"editor.splitRight": ["Meta+\\"],
"window.toggleFullScreen": ["Meta+Ctrl+F"],
+ "window.next": ["Meta+Alt+`"],
+ "window.previous": ["Meta+Alt+Shift+`"],
+ "file.reloadFromDisk": ["Meta+Alt+Y"],
+ // Before the project view's ⇧⌘C (Copy Absolute Path), which wins there.
+ "editor.copyPath": ["Meta+Shift+C"],
// Project view (when: projectViewFocus)
"project.newFile": ["Meta+N"],
"project.rename": ["Shift+F6"],
"project.move": ["F6"],
- "project.delete": ["Delete", "Meta+Backspace"],
+ "project.delete": ["Delete", "Backspace", "Meta+Backspace"],
"project.copy": ["Meta+C"],
"project.cut": ["Meta+X"],
"project.paste": ["Meta+V"],
"project.copyAbsolutePath": ["Meta+Shift+C"],
- "project.open": ["F4"],
+ "project.open": ["F4", "Meta+Down"],
"project.findUsages": ["Alt+F7"],
"project.reformatCode": ["Meta+Alt+L"],
"project.optimizeImports": ["Ctrl+Alt+O"],
+ // After Fold / Unfold and File › Reload from Disk: keyWhen limits these to the project view.
+ "project.reloadFromDisk": ["Meta+Alt+Y"],
+ "project.expandAll": ["Meta+="],
+ "project.collapseAll": ["Meta+-"],
// Tool windows
"toolwindow.project": ["Meta+1"],
@@ -162,11 +181,14 @@ export const intellijMacos: Record<string, string[]> = {
"web.openInBrowser": ["Ctrl+Shift+R"],
"run.debugContext": ["Ctrl+Shift+D"],
"run.stop": ["Meta+F2"],
+ // Rerun in the Run / Debug tool window only (when / keyWhen); Meta+R stays with the editor elsewhere.
+ "run.rerun": ["Meta+R"],
+ "debug.rerun": ["Meta+R"],
"run.chooseConfig": ["Ctrl+Alt+R"],
"run.editConfigs": ["Ctrl+Alt+Shift+R"],
"debug.toggleBreakpoint": ["Meta+F8"],
"debug.viewBreakpoints": ["Meta+Shift+F8"],
- "debug.resume": ["Meta+Alt+R"],
+ "debug.resume": ["Meta+Alt+R", "F9"],
"debug.stepOver": ["F8"],
"debug.stepInto": ["F7"],
"debug.stepOut": ["Shift+F8"],
@@ -179,13 +201,16 @@ export const intellijMacos: Record<string, string[]> = {
"debug.toggleTemporaryBreakpoint": ["Meta+Alt+Shift+F8"],
"debug.attachToProcess": ["Alt+Shift+F5"],
"debug.setValue": ["F2"],
- "debug.jumpToSource": ["F4"],
+ "debug.jumpToSource": ["F4", "Meta+Down"],
"debug.evaluate": ["Alt+F8"],
// VCS
"vcs.operations": ["Ctrl+V"],
"vcs.commit": ["Meta+K"],
"vcs.push": ["Meta+Shift+K"],
+ "vcs.commitAndPush": ["Meta+Alt+K"],
+ "vcs.toggleAmend": ["Ctrl+Alt+M"],
+ "vcs.showMessageHistory": ["Ctrl+M"],
"vcs.update": ["Meta+T"],
"vcs.rollback": ["Meta+Alt+Z"],
"vcs.showDiff": ["Meta+D"],
@@ -195,8 +220,8 @@ export const intellijMacos: Record<string, string[]> = {
"vcs.annotate": [],
"vcs.localHistory": [],
// Commit tool window (change lists) and Git log; keyWhen limits them to those tool windows.
- "vcs.changelist.move": ["F6"],
- "vcs.changelist.edit": ["Shift+F6"],
+ "vcs.changelist.move": ["Meta+Shift+M"],
+ "vcs.changelist.edit": ["F2", "Shift+F6"],
"vcs.log.copyRevision": ["Meta+Alt+Shift+C"],
// View › Appearance › Zoom IDE
"view.zoomIn": ["Ctrl+Alt+="],
diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts
index 24817fb64..cef0c1028 100644
--- a/src/platform/keymaps/intellij-windows.ts
+++ b/src/platform/keymaps/intellij-windows.ts
@@ -10,6 +10,7 @@ export const intellijWindows: Record<string, string[]> = {
"navigate.gotoFile": ["Ctrl+Shift+N"],
"navigate.gotoSymbol": ["Ctrl+Alt+Shift+N"],
"navigate.findAction": ["Ctrl+Shift+A"],
+ "navigate.searchText": ["Ctrl+Alt+Shift+E"],
"navigate.navigationBar": ["Alt+Home"],
"navigate.switcher": ["Ctrl+Tab"],
"navigate.switcherBack": ["Ctrl+Shift+Tab"],
@@ -39,8 +40,8 @@ export const intellijWindows: Record<string, string[]> = {
// Find
"find.inFile": ["Ctrl+F"],
"find.replaceInFile": ["Ctrl+R"],
- "find.next": ["F3"],
- "find.previous": ["Shift+F3"],
+ "find.next": ["F3", "Ctrl+L"],
+ "find.previous": ["Shift+F3", "Ctrl+Shift+L"],
"find.inPath": ["Ctrl+Shift+F"],
"find.replaceInPath": ["Ctrl+Shift+R"],
"find.usages": ["Alt+F7"],
@@ -78,6 +79,14 @@ export const intellijWindows: Record<string, string[]> = {
"code.addCaretsToLineEnds": ["Alt+Shift+G"],
"code.startNewLine": ["Shift+Enter"],
"code.startNewLineBefore": ["Ctrl+Alt+Enter"],
+ // Before the HTTP / SQL consoles' Ctrl+Enter (Run), which wins there.
+ "code.splitLine": ["Ctrl+Enter"],
+ "editor.scrollToCenter": ["Ctrl+M"],
+ "editor.codeBlockStart": ["Ctrl+["],
+ "editor.codeBlockEnd": ["Ctrl+]"],
+ // IDEA clones carets with Ctrl, Ctrl+Up / Down (double modifier); no single-stroke default.
+ "editor.cloneCaretAbove": [],
+ "editor.cloneCaretBelow": [],
"code.joinLines": ["Ctrl+Shift+J"],
"code.toggleCase": ["Ctrl+Shift+U"],
"code.pasteFromHistory": ["Ctrl+Shift+V"],
@@ -106,26 +115,36 @@ export const intellijWindows: Record<string, string[]> = {
"file.openProject": [],
"file.newScratchFile": ["Ctrl+Alt+Shift+Insert"],
"editor.closeTab": ["Ctrl+F4"],
+ "toolwindow.closeContent": ["Ctrl+F4"],
"editor.reopenClosedTab": [],
"file.toggleReadOnly": [],
"editor.nextTab": ["Alt+Right"],
"editor.prevTab": ["Alt+Left"],
"editor.splitRight": [],
"window.toggleFullScreen": [],
+ "window.next": ["Ctrl+Alt+]"],
+ "window.previous": ["Ctrl+Alt+["],
+ "file.reloadFromDisk": ["Ctrl+Alt+Y"],
+ // Before the project view's Ctrl+Shift+C (Copy Absolute Path), which wins there.
+ "editor.copyPath": ["Ctrl+Shift+C"],
// Project view (when: projectViewFocus)
"project.newFile": ["Alt+Insert"],
"project.rename": ["Shift+F6"],
"project.move": ["F6"],
"project.delete": ["Delete"],
- "project.copy": ["Ctrl+C"],
- "project.cut": ["Ctrl+X"],
- "project.paste": ["Ctrl+V"],
+ "project.copy": ["Ctrl+C", "Ctrl+Insert"],
+ "project.cut": ["Ctrl+X", "Shift+Delete"],
+ "project.paste": ["Ctrl+V", "Shift+Insert"],
"project.copyAbsolutePath": ["Ctrl+Shift+C"],
"project.open": ["F4"],
"project.findUsages": ["Alt+F7"],
"project.reformatCode": ["Ctrl+Alt+L"],
"project.optimizeImports": ["Ctrl+Alt+O"],
+ // After Fold / Unfold and File › Reload from Disk: keyWhen limits these to the project view.
+ "project.reloadFromDisk": ["Ctrl+Alt+Y"],
+ "project.expandAll": ["Ctrl+="],
+ "project.collapseAll": ["Ctrl+-"],
// Tool windows
"toolwindow.project": ["Alt+1"],
@@ -160,6 +179,9 @@ export const intellijWindows: Record<string, string[]> = {
"web.openInBrowser": ["Ctrl+Shift+F10"],
"run.debugContext": [],
"run.stop": ["Ctrl+F2"],
+ // Rerun in the Run / Debug tool window only (when / keyWhen); Ctrl+F5 stays with the editor elsewhere.
+ "run.rerun": ["Ctrl+F5"],
+ "debug.rerun": ["Ctrl+F5"],
"run.chooseConfig": ["Alt+Shift+F10"],
"run.editConfigs": [],
"debug.toggleBreakpoint": ["Ctrl+F8"],
@@ -184,21 +206,24 @@ export const intellijWindows: Record<string, string[]> = {
"vcs.operations": ["Alt+`"],
"vcs.commit": ["Ctrl+K"],
"vcs.push": ["Ctrl+Shift+K"],
+ "vcs.commitAndPush": ["Ctrl+Alt+K"],
+ "vcs.toggleAmend": ["Alt+M"],
+ "vcs.showMessageHistory": ["Ctrl+M"],
"vcs.update": ["Ctrl+T"],
"vcs.rollback": ["Ctrl+Alt+Z"],
"vcs.showDiff": ["Ctrl+D"],
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
- "vcs.branches": [],
+ "vcs.branches": ["Ctrl+Shift+`"],
"vcs.annotate": [],
"vcs.localHistory": [],
- "vcs.changelist.move": ["F6"],
- "vcs.changelist.edit": ["Shift+F6"],
+ "vcs.changelist.move": ["Alt+Shift+M"],
+ "vcs.changelist.edit": ["F2", "Shift+F6"],
"vcs.log.copyRevision": ["Ctrl+Alt+Shift+C"],
// View › Appearance › Zoom IDE
- "view.zoomIn": ["Ctrl+Alt+="],
- "view.zoomOut": ["Ctrl+Alt+-"],
- "view.resetZoom": ["Ctrl+Alt+0"],
+ "view.zoomIn": ["Alt+Shift+="],
+ "view.zoomOut": ["Alt+Shift+-"],
+ "view.resetZoom": ["Alt+Shift+0"],
// Diff viewer (after Debug: F7 / ⇧F7 / F4 there win while a diff is focused)
"diff.nextDifference": ["F7"],
"diff.prevDifference": ["Shift+F7"],
diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts
index 6883ae584..4f5df3354 100644
--- a/src/platform/keymaps/vscode-macos.ts
+++ b/src/platform/keymaps/vscode-macos.ts
@@ -109,6 +109,7 @@ export const vscodeMacos: Record<string, string[]> = {
"file.openProject": ["Meta+O"],
"file.newScratchFile": [],
"editor.closeTab": ["Meta+W"],
+ "toolwindow.closeContent": ["Meta+W"],
"editor.reopenClosedTab": ["Meta+Shift+T"],
"file.toggleReadOnly": [],
"editor.nextTab": ["Meta+Alt+Right", "Meta+Shift+]"],
@@ -116,6 +117,17 @@ export const vscodeMacos: Record<string, string[]> = {
"editor.splitRight": ["Meta+\\"],
"editor.toggleZen": ["Meta+K Z"],
"window.toggleFullScreen": ["Meta+Ctrl+F"],
+ "window.next": [],
+ "window.previous": [],
+ "file.reloadFromDisk": [],
+ "editor.copyPath": ["Meta+K P"],
+ "navigate.searchText": [],
+ "code.splitLine": [],
+ "editor.scrollToCenter": [],
+ "editor.codeBlockStart": [],
+ "editor.codeBlockEnd": [],
+ "editor.cloneCaretAbove": ["Meta+Alt+Up"],
+ "editor.cloneCaretBelow": ["Meta+Alt+Down"],
// Explorer (when: projectViewFocus)
"project.newFile": [],
@@ -127,6 +139,9 @@ export const vscodeMacos: Record<string, string[]> = {
"project.paste": ["Meta+V"],
"project.copyAbsolutePath": ["Meta+Alt+C"],
"project.open": ["Meta+Down"],
+ "project.reloadFromDisk": [],
+ "project.expandAll": [],
+ "project.collapseAll": [],
"project.findUsages": ["Alt+Shift+F12"],
"project.reformatCode": ["Alt+Shift+F"],
"project.optimizeImports": ["Alt+Shift+O"],
@@ -165,6 +180,8 @@ export const vscodeMacos: Record<string, string[]> = {
"run.stop": ["Shift+F5"],
"run.chooseConfig": [],
"run.editConfigs": [],
+ "run.rerun": [],
+ "web.openInBrowser": [],
"debug.toggleBreakpoint": ["F9"],
"debug.viewBreakpoints": [],
"debug.resume": ["F5"],
@@ -182,11 +199,15 @@ export const vscodeMacos: Record<string, string[]> = {
"debug.setValue": ["F2"],
"debug.jumpToSource": [],
"debug.evaluate": [],
+ "debug.rerun": [],
// VCS
"vcs.operations": [],
"vcs.commit": [],
"vcs.push": [],
+ "vcs.commitAndPush": [],
+ "vcs.toggleAmend": [],
+ "vcs.showMessageHistory": [],
"vcs.update": [],
"vcs.rollback": [],
"vcs.showDiff": [],
diff --git a/src/platform/keymaps/vscode-windows.ts b/src/platform/keymaps/vscode-windows.ts
index 6146cbb88..931d15bda 100644
--- a/src/platform/keymaps/vscode-windows.ts
+++ b/src/platform/keymaps/vscode-windows.ts
@@ -32,6 +32,7 @@ export const vscodeWindows: Record<string, string[]> = {
"code.joinLines": [],
"file.openProject": ["Ctrl+K Ctrl+O"],
"editor.closeTab": ["Ctrl+W", "Ctrl+F4"],
+ "toolwindow.closeContent": ["Ctrl+W", "Ctrl+F4"],
"editor.nextTab": ["Ctrl+PageDown"],
"editor.prevTab": ["Ctrl+PageUp"],
"window.toggleFullScreen": ["F11"],
diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json
index 9b82ba2ca..9112762f7 100644
--- a/src/platform/locales/en.json
+++ b/src/platform/locales/en.json
@@ -252,6 +252,9 @@
"menu.toolwindow.run": "Run",
"menu.toolwindow.structure": "Structure",
"menu.toolwindow.terminal": "Terminal",
+ "terminal.close.title": "Process '{name}' Is Running",
+ "terminal.close.message": "Do you want to terminate the process '{name}'?",
+ "terminal.close.terminate": "Terminate",
"menu.vcs.annotate": "Annotate with Git Blame",
"menu.vcs.branches": "Branches…",
"menu.vcs.commit": "Commit…",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index acf5e0e65..ad97b4aaf 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -154,6 +154,8 @@
"Bold": "粗体",
"Bookmarks": "书签",
"Bottom": "底部",
+ "Bottom Left": "底部左侧",
+ "Bottom Right": "底部右侧",
"Branch": "分支",
"Branch '{name}' has no tracked branch": "分支 '{name}' 没有跟踪分支",
"Branch, %": "分支,%",
@@ -995,6 +997,8 @@
"Leave": "保留",
"Leave a comment (optional)": "留下评论(可选)",
"Leave a comment (required)": "留下评论(必填)",
+ "Left Bottom": "左下",
+ "Left Top": "左上",
"Limit body line": "限制正文行",
"Limit history to": "历史记录限制为",
"Limit subject line": "限制主题行",
@@ -1330,6 +1334,8 @@
"Passed as -s (mirrors, servers, proxies).": "以 -s 传入(镜像、服务器、代理)。",
"Passed to rustfmt when reformatting, e.g. --edition 2024": "重新格式化时传递给 rustfmt,例如 --edition 2024",
"Passed to the JVM running jdtls (java.jdt.ls.vmargs), e.g. -Xmx2g. A Lombok agent is added automatically when the project uses Lombok.": "传递给运行 jdtls 的 JVM (java.jdt.ls.vmargs),例如 -Xmx2g。项目使用 Lombok 时会自动添加 Lombok 代理。",
+ "Right Bottom": "右下",
+ "Right Top": "右上",
"Runs jdtls only, like IDEA's JDK for importer; the project keeps compiling and running with the Project JDK. jdtls needs JDK 21 or newer (recent releases 25). The jdtls executable itself is set in Language Servers.": "仅用于运行 jdtls(类似 IDEA 的「导入器 JDK」);项目仍使用项目 JDK 编译和运行。jdtls 需要 JDK 21 或更高版本(较新版本需要 25)。jdtls 可执行文件本身在「语言服务器」中设置。",
"Language server JDK": "语言服务器 JDK",
"Password": "密码",
@@ -1608,6 +1614,9 @@
"Reset Shortcuts": "重置快捷键",
"Reset Zoom": "重置缩放",
"Reset to Language Defaults": "重置为语言默认值",
+ "Comment Code": "注释代码",
+ "Line comment at first column": "在第一列添加行注释",
+ "Add a space at line comment start": "在行注释开头添加空格",
"Reset type": "重置类型",
"Resize right tool window bar": "调整右侧工具窗口栏大小",
"Resize tool window bar": "调整工具窗口栏大小",
@@ -2087,6 +2096,7 @@
"To commit:": "到提交:",
"To directory:": "目标目录:",
"To nearest indent position": "到最近的缩进位置",
+ "To proper indent position": "到正确的缩进位置",
"Toggle 'Skip Tests' Mode": "切换“跳过测试”模式",
"Toggle Bookmark": "切换书签",
"Toggle Field Watchpoint": "切换字段监视点",
@@ -2384,5 +2394,62 @@
"Installed Shells": "已安装的 Shell",
"Installed shells": "已安装的 Shell",
"Shell Path": "Shell 路径",
- "New Predefined Session": "新建预定义会话"
+ "New Predefined Session": "新建预定义会话",
+ "Suspend": "挂起",
+ "\"Breakpoint hit\" message": "“已到达断点”消息",
+ "Evaluate and log": "计算并记录",
+ "History": "历史记录",
+ "Expand value": "展开值",
+ "Expression history": "表达式历史记录",
+ "Allow multiple instances": "允许多个实例",
+ "Hold Shift to Debug, F4 to edit, Delete to remove": "按住 Shift 调试,F4 编辑,Delete 删除",
+ "Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 运行,F4 编辑,Delete 删除",
+ "Send EOF": "发送 EOF",
+ "Collapse folded lines": "折叠行",
+ "Close Tool Window Tab": "关闭工具窗口标签页",
+ "No open files": "没有打开的文件",
+ "Open files": "打开的文件",
+ "New name:": "新名称:",
+ "Open copy in editor": "在编辑器中打开副本",
+ "Safe delete (with usage search)": "安全删除(搜索用法)",
+ "Looking for usages…": "正在查找用法…",
+ "Delete Without Search": "不搜索直接删除",
+ "Rebasing {commit} from {branch}": "正在变基 {branch} 中的 {commit}",
+ "Already rebased commits and commits from {branch}": "已变基的提交和来自 {branch} 的提交",
+ "Already rebased commits": "已变基的提交",
+ "Changes from {name}": "来自 {name} 的更改",
+ "Your changes": "您的更改",
+ "Changes from diverging branches": "来自分叉分支的更改",
+ "Local Changes": "本地更改",
+ "Changes from cherry-pick {commit}": "来自拣选 {commit} 的更改",
+ "Changes from cherry-pick": "来自拣选的更改",
+ "Your version, branch {branch}": "您的版本,分支 {branch}",
+ "Git Checkout Problem": "Git 签出问题",
+ "Smart Checkout": "智能签出",
+ "Force Checkout": "强制签出",
+ "Don't Checkout": "不签出",
+ "Rebase onto Remote": "变基到远程",
+ "Drop Local Commits": "丢弃本地提交",
+ "Checkout {name}": "签出 {name}",
+ "Restore": "恢复",
+ "View Commits": "查看提交",
+ "Delete Tracked Branch": "删除跟踪的分支",
+ "Deleted branch {name}": "已删除分支 {name}",
+ "Unmerged commits were discarded": "未合并的提交已被丢弃",
+ "Restored branch {name}": "已恢复分支 {name}",
+ "Commits of {name}": "{name} 的提交",
+ "All files are up-to-date": "所有文件都是最新的",
+ "Update Info": "更新信息",
+ "Press again to go to the next file": "再按一次转到下一个文件",
+ "Press again to go to the previous file": "再按一次转到上一个文件",
+ "Include in commit": "包含在提交中",
+ "Code analysis": "代码分析",
+ "Line separators": "行分隔符",
+ "Commit during rebase": "在变基期间提交",
+ "Commit in detached HEAD": "在分离的 HEAD 上提交",
+ "Amend Commit": "修正提交",
+ "Show Commit Message History": "显示提交消息历史记录",
+ "Don't warn about this target": "不再对此目标发出警告",
+ "Target branch": "目标分支",
+ "Checked out {name}": "已签出 {name}"
}
diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json
index c1c4f04bc..5c04ca9ee 100644
--- a/src/platform/locales/zh.json
+++ b/src/platform/locales/zh.json
@@ -252,6 +252,9 @@
"menu.toolwindow.run": "运行",
"menu.toolwindow.structure": "结构",
"menu.toolwindow.terminal": "终端",
+ "terminal.close.title": "进程“{name}”正在运行",
+ "terminal.close.message": "是否要终止进程“{name}”?",
+ "terminal.close.terminate": "终止",
"menu.vcs.annotate": "使用 Git Blame 注解",
"menu.vcs.branches": "分支…",
"menu.vcs.commit": "提交…",
diff --git a/src/ui/Dialog.tsx b/src/ui/Dialog.tsx
index 3e893b2a4..b15dfc672 100644
--- a/src/ui/Dialog.tsx
+++ b/src/ui/Dialog.tsx
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { usePlatform } from "@/platform/platformInfo";
import { Button, IconButton } from "./Button";
import { Icon } from "./icons";
-import { FOCUSABLE, openLayer, trapTab } from "./popupState";
+import { FOCUSABLE, onWindowDeactivate, openLayer, trapTab } from "./popupState";
import { useTx } from "@/platform/i18n";
import styles from "./Dialog.module.css";
@@ -116,6 +116,8 @@ export interface DialogProps {
"aria-label"?: string;
/** Close when clicking outside (default: only for `top` popups). */
dismissOnBackdrop?: boolean;
+ /** Close when the app window loses focus (default: popups only; never modal dialogs). */
+ closeOnDeactivate?: boolean;
/** @deprecated Dialogs never dim the window behind them; kept for call sites. */
transparentBackdrop?: boolean;
/** @deprecated Every centred dialog has window chrome; kept for call sites. */
@@ -193,6 +195,7 @@ function DialogInner({
position = "center",
className,
dismissOnBackdrop,
+ closeOnDeactivate,
platform: platformOverride,
icon,
...aria
@@ -224,6 +227,12 @@ function DialogInner({
};
}, []);
+ const cancelOnDeactivate = closeOnDeactivate ?? popup;
+ useEffect(() => {
+ if (!cancelOnDeactivate) return;
+ return onWindowDeactivate(() => onCloseRef.current());
+ }, [cancelOnDeactivate]);
+
useEffect(() => {
const layer = openLayer(() => ref.current);
const previous = document.activeElement as HTMLElement | null;
diff --git a/src/ui/Input.module.css b/src/ui/Input.module.css
index 2d517b879..b2c3955cb 100644
--- a/src/ui/Input.module.css
+++ b/src/ui/Input.module.css
@@ -79,6 +79,20 @@
/* The frame's focus ring stands in for the global :focus-visible outline. */
outline: none;
}
+.multiline {
+ height: auto;
+ align-items: flex-start;
+ padding-block: 4px;
+}
+.multiline .leading {
+ margin-top: 3px;
+}
+.searchArea {
+ resize: none;
+ font-family: inherit;
+ line-height: 20px;
+ padding: 0;
+}
.invalid .searchInput {
color: var(--danger);
}
diff --git a/src/ui/Input.tsx b/src/ui/Input.tsx
index bb2e8ddc9..8243cbbd3 100644
--- a/src/ui/Input.tsx
+++ b/src/ui/Input.tsx
@@ -1,4 +1,4 @@
-import { forwardRef, type InputHTMLAttributes, type ReactNode } from "react";
+import { forwardRef, type InputHTMLAttributes, type ReactNode, type Ref, type TextareaHTMLAttributes } from "react";
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { IconButton } from "./Button";
@@ -74,6 +74,8 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
ref,
) {
const tx = useTx();
+ // A multi-line query (e.g. Find over a multi-line selection) is shown as such.
+ const lines = value.split("\n").length;
return (
<div
className={clsx(
@@ -81,24 +83,42 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
variant === "framed" && styles.framed,
size === "large" && styles.large,
invalid && styles.invalid,
+ lines > 1 && styles.multiline,
className,
)}
data-invalid={invalid || undefined}
>
{leadingIcon && <Icon name={leadingIcon} size={size === "large" ? 15 : 14} className={styles.leading} />}
- <input
- ref={ref}
- className={styles.searchInput}
- value={value}
- spellCheck={false}
- autoComplete="off"
- autoCorrect="off"
- autoCapitalize="off"
- aria-invalid={invalid || undefined}
- placeholder={tx(placeholder)}
- onChange={(e) => onChange(e.target.value)}
- {...rest}
- />
+ {lines > 1 ? (
+ <textarea
+ ref={ref as unknown as Ref<HTMLTextAreaElement>}
+ className={clsx(styles.searchInput, styles.searchArea)}
+ rows={Math.min(lines, 5)}
+ value={value}
+ spellCheck={false}
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="off"
+ aria-invalid={invalid || undefined}
+ placeholder={tx(placeholder)}
+ onChange={(e) => onChange(e.target.value)}
+ {...(rest as TextareaHTMLAttributes<HTMLTextAreaElement>)}
+ />
+ ) : (
+ <input
+ ref={ref}
+ className={styles.searchInput}
+ value={value}
+ spellCheck={false}
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="off"
+ aria-invalid={invalid || undefined}
+ placeholder={tx(placeholder)}
+ onChange={(e) => onChange(e.target.value)}
+ {...rest}
+ />
+ )}
{trailing}
{clearable && value && (
<IconButton icon="close" title="Clear" size="small" iconSize={12} tabIndex={-1} onClick={() => onChange("")} />
diff --git a/src/ui/Popup.test.tsx b/src/ui/Popup.test.tsx
index f70dc2908..b135322f8 100644
--- a/src/ui/Popup.test.tsx
+++ b/src/ui/Popup.test.tsx
@@ -57,6 +57,25 @@ describe("Popup", () => {
expect(onClose).toHaveBeenCalledWith("outside");
});
+ it("closes when the app window is deactivated, but not when focus moves into a frame", () => {
+ vi.useFakeTimers();
+ const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
+ try {
+ const onClose = vi.fn();
+ render(<Harness onClose={onClose} />);
+ fireEvent.blur(window);
+ act(() => void vi.runAllTimers());
+ expect(onClose).not.toHaveBeenCalled();
+ hasFocus.mockReturnValue(false);
+ fireEvent.blur(window);
+ act(() => void vi.runAllTimers());
+ expect(onClose).toHaveBeenCalledWith("outside");
+ } finally {
+ hasFocus.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
it("only the top-most layer handles Escape", () => {
const outer = vi.fn();
const inner = vi.fn();
@@ -109,6 +128,34 @@ describe("Menu", () => {
});
});
+describe("Dialog deactivation", () => {
+ it("closes popups but not modal dialogs when the app window loses focus", () => {
+ vi.useFakeTimers();
+ const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(false);
+ try {
+ const popup = vi.fn();
+ const modal = vi.fn();
+ render(
+ <>
+ <Dialog open onClose={modal} title="Modal">
+ <p>body</p>
+ </Dialog>
+ <Dialog open onClose={popup} position="top" aria-label="Popup">
+ <p>body</p>
+ </Dialog>
+ </>,
+ );
+ fireEvent.blur(window);
+ act(() => void vi.runAllTimers());
+ expect(popup).toHaveBeenCalledTimes(1);
+ expect(modal).not.toHaveBeenCalled();
+ } finally {
+ hasFocus.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+});
+
describe("Dialog initial focus", () => {
it("focuses the first control of the content, not the header close button", () => {
render(
diff --git a/src/ui/Popup.tsx b/src/ui/Popup.tsx
index 17accb844..7bb6b266f 100644
--- a/src/ui/Popup.tsx
+++ b/src/ui/Popup.tsx
@@ -1,6 +1,7 @@
/**
- * Anchored popover: portal + flip/shift positioning, Escape / outside-click
- * dismissal (top-most popup only), optional focus trap and focus restore.
+ * Anchored popover: portal + flip/shift positioning, Escape / outside-click /
+ * window-deactivation dismissal (top-most popup only for Escape), optional
+ * focus trap and focus restore.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, type CSSProperties, type ReactNode, type RefObject } from "react";
import { createPortal } from "react-dom";
@@ -15,7 +16,7 @@ import {
type Placement,
type VirtualElement,
} from "@floating-ui/react-dom";
-import { FOCUSABLE, openLayer, trapTab } from "./popupState";
+import { FOCUSABLE, onWindowDeactivate, openLayer, trapTab } from "./popupState";
import styles from "./Popup.module.css";
export type PopupAnchor = Element | VirtualElement | RefObject<Element | null> | { x: number; y: number } | null;
@@ -37,6 +38,8 @@ export interface PopupProps {
autoFocus?: boolean;
restoreFocus?: boolean;
closeOnOutsideClick?: boolean;
+ /** Close (as "outside") when the app window loses focus, like IDEA popups (default true). */
+ closeOnDeactivate?: boolean;
/** Match the anchor's width (dropdowns). */
matchWidth?: boolean;
/** Plain surface without border/shadow styling. */
@@ -71,6 +74,7 @@ function PopupInner({
autoFocus = true,
restoreFocus = true,
closeOnOutsideClick = true,
+ closeOnDeactivate = true,
matchWidth = false,
unstyled = false,
...aria
@@ -129,7 +133,9 @@ function PopupInner({
};
document.addEventListener("keydown", onKey);
document.addEventListener("pointerdown", onPointer, true);
+ const stopDeactivate = closeOnDeactivate ? onWindowDeactivate(() => onCloseRef.current("outside")) : undefined;
return () => {
+ stopDeactivate?.();
document.removeEventListener("keydown", onKey);
document.removeEventListener("pointerdown", onPointer, true);
layer.release();
diff --git a/src/ui/Tabs.test.tsx b/src/ui/Tabs.test.tsx
index 9ef0dd7e7..df66673b8 100644
--- a/src/ui/Tabs.test.tsx
+++ b/src/ui/Tabs.test.tsx
@@ -1,5 +1,6 @@
-import { describe, expect, it } from "vitest";
-import { dropIndex, revealHorizontally } from "./Tabs";
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { dropIndex, revealHorizontally, TabStripRegistry, Tabs, type TabStripHandle } from "./Tabs";
describe("dropIndex", () => {
it("finds the insertion index from tab midpoints", () => {
@@ -39,3 +40,40 @@ describe("revealHorizontally", () => {
expect(scroller.scrollLeft).toBe(40);
});
});
+
+describe("Tabs interactions", () => {
+ const items = [
+ { id: "a", label: "A" },
+ { id: "b", label: "B" },
+ { id: "c", label: "C", closable: false },
+ ];
+
+ it("Alt+click on a close button closes the other tabs", () => {
+ const onClose = vi.fn();
+ const onCloseOthers = vi.fn();
+ render(<Tabs items={items} activeId="a" onSelect={() => {}} onClose={onClose} onCloseOthers={onCloseOthers} />);
+ const close = screen.getAllByRole("button", { name: "Close Tab" })[1]!;
+ fireEvent.click(close, { altKey: true });
+ expect(onCloseOthers).toHaveBeenCalledWith("b");
+ fireEvent.click(close);
+ expect(onClose).toHaveBeenCalledWith("b");
+ });
+
+ it("lets a container close the selected tab when it is closable", () => {
+ const handles: TabStripHandle[] = [];
+ const register = (h: TabStripHandle) => (handles.push(h), () => void handles.splice(handles.indexOf(h), 1));
+ const onClose = vi.fn();
+ const ui = (activeId: string) => (
+ <TabStripRegistry.Provider value={register}>
+ <Tabs items={items} activeId={activeId} onSelect={() => {}} onClose={onClose} />
+ </TabStripRegistry.Provider>
+ );
+ const { rerender, unmount } = render(ui("b"));
+ expect(handles[0]!.closeSelected()).toBe(true);
+ expect(onClose).toHaveBeenCalledWith("b");
+ rerender(ui("c"));
+ expect(handles[0]!.closeSelected()).toBe(false);
+ unmount();
+ expect(handles).toHaveLength(0);
+ });
+});
diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx
index f3dcb0c05..a48fd6a84 100644
--- a/src/ui/Tabs.tsx
+++ b/src/ui/Tabs.tsx
@@ -4,6 +4,8 @@
* an overflow dropdown listing every tab when they don't fit.
*/
import {
+ createContext,
+ useContext,
useEffect,
useLayoutEffect,
useRef,
@@ -59,11 +61,25 @@ export function dropIndex(x: number, rects: ReadonlyArray<{ left: number; width:
return rects.length;
}
+/** A tab strip as seen from its container: close the selected tab if it can be closed. */
+export interface TabStripHandle {
+ closeSelected(): boolean;
+}
+
+/**
+ * Lets a container (a tool window header) reach the tab strips rendered inside
+ * it: each `Tabs` registers itself with the nearest provided function.
+ */
+export const TabStripRegistry = createContext<((handle: TabStripHandle) => () => void) | null>(null);
+
export interface TabsProps {
items: TabItem[];
activeId: string | null;
onSelect: (id: string) => void;
onClose?: (id: string) => void;
+ /** Alt+click on a close button (IDEA: close all other tabs). */
+ onCloseOthers?: (id: string) => void;
+ onDoubleClick?: (id: string) => void;
onContextMenu?: (id: string, e: MouseEvent) => void;
/** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */
variant?: "editor" | "compact";
@@ -82,6 +98,8 @@ export function Tabs({
activeId,
onSelect,
onClose,
+ onCloseOthers,
+ onDoubleClick,
onContextMenu,
variant = "editor",
trailing,
@@ -98,6 +116,25 @@ export function Tabs({
const [drop, setDrop] = useState<number | null>(null);
const [dragging, setDragging] = useState<string | null>(null);
+ const register = useContext(TabStripRegistry);
+ const latest = useRef({ items, activeId, onClose });
+ useLayoutEffect(() => {
+ latest.current = { items, activeId, onClose };
+ });
+ useEffect(
+ () =>
+ register?.({
+ closeSelected: () => {
+ const { items, activeId, onClose } = latest.current;
+ const item = items.find((it) => it.id === activeId);
+ if (!item || !onClose || item.closable === false) return false;
+ onClose(item.id);
+ return true;
+ },
+ }),
+ [register],
+ );
+
const accepts = (e: DragEvent) => !!dnd && [...e.dataTransfer.types].includes(dnd.type);
const indexAt = (x: number) =>
dropIndex(
@@ -248,6 +285,7 @@ export function Tabs({
className={styles.tabButton}
style={item.color ? { color: item.color } : undefined}
onClick={() => onSelect(item.id)}
+ onDoubleClick={onDoubleClick ? () => onDoubleClick(item.id) : undefined}
onKeyDown={(e) => onKeyDown(e, index, item)}
{...tooltipAttrs(item.tooltip)}
>
@@ -270,7 +308,8 @@ export function Tabs({
className={styles.close}
onClick={(e) => {
e.stopPropagation();
- onClose!(item.id);
+ if (e.altKey && onCloseOthers) onCloseOthers(item.id);
+ else onClose!(item.id);
}}
/>
</span>
diff --git a/src/ui/Tree.tsx b/src/ui/Tree.tsx
index a8033d3ca..73d0f436b 100644
--- a/src/ui/Tree.tsx
+++ b/src/ui/Tree.tsx
@@ -44,6 +44,8 @@ export interface TreeHandle {
/** Selects `key` (must be visible, i.e. ancestors expanded) and scrolls to it. */
reveal(key: string): void;
leadKey(): string | null;
+ /** Selects the next (1) / previous (-1) row, for a filter field that keeps the focus (Settings search). */
+ moveSelection(dir: 1 | -1): void;
}
export interface TreeProps<T> {
@@ -263,6 +265,14 @@ export function Tree<T>(props: TreeProps<T>) {
virtualizer.scrollToIndex(i, { align: "center" });
},
leadKey: () => lead,
+ moveSelection: (dir: 1 | -1) => {
+ const key = lead != null && selected.has(lead) ? lead : ([...selected][0] ?? null);
+ const from = key != null ? (indexOfKey.get(key) ?? -1) : -1;
+ const i = from < 0 ? step(-1, 1) : step(from, dir);
+ if (i < 0 || i === from || !rows[i]) return;
+ selectIndex(i);
+ virtualizer.scrollToIndex(i);
+ },
}));
const findMatch = (from: number, dir: 1 | -1, inclusive: boolean, q = query, wrap = true): number => {
diff --git a/src/ui/popupState.ts b/src/ui/popupState.ts
index 16986e319..14aeab9ea 100644
--- a/src/ui/popupState.ts
+++ b/src/ui/popupState.ts
@@ -61,6 +61,25 @@ export function acquirePopup(): () => void {
};
}
+/**
+ * Calls `fn` when the app window is deactivated (IDEA cancels popups then).
+ * Focus moving into one of our own frames also blurs the window: ignored.
+ */
+export function onWindowDeactivate(fn: () => void): () => void {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const onBlur = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ if (!document.hasFocus()) fn();
+ }, 0);
+ };
+ window.addEventListener("blur", onBlur);
+ return () => {
+ clearTimeout(timer);
+ window.removeEventListener("blur", onBlur);
+ };
+}
+
export function isPopupOpen(): boolean {
return layers.length + anonymous > 0;
}
diff --git a/src/workbench/Notifications.tsx b/src/workbench/Notifications.tsx
index f0abd2489..0a2d6bcc3 100644
--- a/src/workbench/Notifications.tsx
+++ b/src/workbench/Notifications.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useTxTemplate } from "@/platform/i18n";
import { EmptyState, IconButton, Toast, T } from "@/ui";
import {
@@ -20,15 +20,37 @@ function timeLabel(t: number) {
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
+function subscribeWindowFocus(onChange: () => void) {
+ window.addEventListener("focus", onChange);
+ window.addEventListener("blur", onChange);
+ return () => {
+ window.removeEventListener("focus", onChange);
+ window.removeEventListener("blur", onChange);
+ };
+}
+
+/** Whether the app window is active (focused). */
+function useWindowActive(): boolean {
+ return useSyncExternalStore(subscribeWindowFocus, () => document.hasFocus(), () => true);
+}
+
function Balloon({ n }: { n: IdeNotification }) {
const [hover, setHover] = useState(false);
+ const active = useWindowActive();
+ const remaining = useRef<number | null>(null);
const txt = useTxTemplate();
+ // IDEA's smart fade-out: the clock runs only while the window is active and the balloon not hovered.
useEffect(() => {
const ms = BALLOON_TIMEOUT[n.level];
- if (n.sticky || ms === null || hover) return;
- const t = setTimeout(() => dismissBalloon(n.id), ms);
- return () => clearTimeout(t);
- }, [n.id, n.level, n.sticky, hover]);
+ if (n.sticky || ms === null || hover || !active) return;
+ const left = remaining.current ?? ms;
+ const start = Date.now();
+ const t = setTimeout(() => dismissBalloon(n.id), left);
+ return () => {
+ clearTimeout(t);
+ remaining.current = Math.max(1, left - (Date.now() - start));
+ };
+ }, [n.id, n.level, n.sticky, hover, active]);
return (
<Toast
className={styles.balloon}
diff --git a/src/workbench/Workbench.test.tsx b/src/workbench/Workbench.test.tsx
index 132c4f934..69eb3777d 100644
--- a/src/workbench/Workbench.test.tsx
+++ b/src/workbench/Workbench.test.tsx
@@ -13,8 +13,17 @@ import {
useNotifications,
} from "./notificationStore";
import { installTaskEvents, useTasks } from "./tasks";
-import { ToolWindowStripe } from "./toolwindows/ToolWindows";
-import { isToolWindowVisible, loadToolWindowLayout, showToolWindow } from "./toolwindows/store";
+import { ToolWindowLayout, ToolWindowStripe } from "./toolwindows/ToolWindows";
+import { isToolWindowVisible, loadToolWindowLayout, showToolWindow, type SlotRecord } from "./toolwindows/store";
+
+const NO_SLOTS: SlotRecord = {
+ left: null,
+ "left-split": null,
+ bottom: null,
+ "bottom-split": null,
+ right: null,
+ "right-split": null,
+};
const item = (id: string, align: "left" | "right", priority: number): StatusItemContribution => ({
id,
@@ -68,7 +77,14 @@ describe("background tasks", () => {
const dispose = registerStatusItem({ id: "workbench.tasks", align: "right", priority: 0, component: TaskStatus });
render(<StatusBar />);
act(() => {
- emitLocalIdeEvent({ type: "task", id: 6, title: "Publish Diagnostics", message: null, fraction: null, done: false });
+ emitLocalIdeEvent({
+ type: "task",
+ id: 6,
+ title: "Publish Diagnostics",
+ message: null,
+ fraction: null,
+ done: false,
+ });
emitLocalIdeEvent({ type: "task", id: 7, title: "Building index", message: null, fraction: 0.5, done: false });
});
expect(screen.queryByText("Building index")).toBeNull();
@@ -92,10 +108,12 @@ describe("notifications", () => {
afterEach(() => {
clearNotifications();
vi.useRealTimers();
+ vi.restoreAllMocks();
});
it("shows balloons; info auto-dismisses, errors stay", () => {
vi.useFakeTimers();
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
render(<Balloons />);
act(() => {
notify({ level: "info", title: "Saved" });
@@ -111,6 +129,26 @@ describe("notifications", () => {
expect(useNotifications.getState().items).toHaveLength(2);
});
+ it("pauses the balloon timeout while the app window is inactive", () => {
+ vi.useFakeTimers();
+ const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
+ try {
+ render(<Balloons />);
+ act(() => notify({ level: "info", title: "Indexed" }));
+ act(() => vi.advanceTimersByTime(BALLOON_TIMEOUT.info! - 1000));
+ hasFocus.mockReturnValue(false);
+ act(() => void fireEvent.blur(window));
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(screen.getByText("Indexed")).toBeInTheDocument();
+ hasFocus.mockReturnValue(true);
+ act(() => void fireEvent.focus(window));
+ act(() => vi.advanceTimersByTime(1100));
+ expect(screen.queryByText("Indexed")).toBeNull();
+ } finally {
+ hasFocus.mockRestore();
+ }
+ });
+
it("replaces notifications with the same key and subscribes to backend notify events", () => {
const uninstall = installNotifyEvents();
notify({ level: "warning", title: "LSP missing", key: "lsp" });
@@ -157,7 +195,7 @@ describe("tool window stripe", () => {
{ id: "project", title: "Project", icon: "folder", anchor: "left" as const, component: C },
{ id: "terminal", title: "Terminal", icon: "terminal", anchor: "bottom" as const, component: C },
];
- render(<ToolWindowStripe side="left" windows={windows} visible={{ left: "project", right: null, bottom: null }} />);
+ render(<ToolWindowStripe side="left" windows={windows} visible={{ ...NO_SLOTS, left: "project" }} />);
const project = screen.getByRole("button", { name: "Project" });
expect(project).toHaveAttribute("aria-pressed", "true");
expect(project).toHaveAttribute("aria-keyshortcuts", "⌘1");
@@ -165,6 +203,78 @@ describe("tool window stripe", () => {
expect(isToolWindowVisible("terminal")).toBe(true);
disposers.forEach((d) => d());
});
+
+ it("groups buttons by area as IDEA's New UI stripes do", () => {
+ const C = () => null;
+ const windows = [
+ { id: "project", title: "Project", icon: "folder", anchor: "left" as const, component: C },
+ {
+ id: "structure",
+ title: "Structure",
+ icon: "structure",
+ anchor: "left" as const,
+ secondary: true,
+ component: C,
+ },
+ { id: "terminal", title: "Terminal", icon: "terminal", anchor: "bottom" as const, component: C },
+ { id: "db", title: "Database", icon: "db", anchor: "right" as const, component: C },
+ { id: "services", title: "Services", icon: "s", anchor: "bottom" as const, secondary: true, component: C },
+ ];
+ const ids = (slot: string) =>
+ [...document.querySelectorAll(`[data-stripe-slot="${slot}"] [data-stripe-button]`)].map((b) =>
+ b.getAttribute("data-stripe-button"),
+ );
+ const { unmount } = render(
+ <>
+ <ToolWindowStripe side="left" windows={windows} visible={NO_SLOTS} />
+ <ToolWindowStripe side="right" windows={windows} visible={NO_SLOTS} />
+ </>,
+ );
+ expect(ids("left")).toEqual(["project"]);
+ expect(ids("left-split")).toEqual(["structure"]);
+ expect(ids("bottom")).toEqual(["terminal"]);
+ expect(ids("right")).toEqual(["db"]);
+ expect(ids("bottom-split")).toEqual(["services"]);
+ // Only the left stripe has split windows: one separator.
+ expect(document.querySelectorAll("[data-stripe-separator]")).toHaveLength(1);
+ unmount();
+ });
+});
+
+describe("tool window split areas", () => {
+ it("renders both areas of a side with a splitter", () => {
+ const disposers = [
+ registerToolWindow({
+ id: "project",
+ title: "Project",
+ icon: "folder",
+ anchor: "left",
+ requiresProject: false,
+ component: () => <div>tree</div>,
+ }),
+ registerToolWindow({
+ id: "structure",
+ title: "Structure",
+ icon: "structure",
+ anchor: "left",
+ secondary: true,
+ requiresProject: false,
+ component: () => <div>members</div>,
+ }),
+ ];
+ loadToolWindowLayout("/split");
+ const { container, unmount } = render(<ToolWindowLayout editor={<div>editor</div>} />);
+ const splitter = container.querySelector('[data-split-handle="left"]')!;
+ expect(splitter).toHaveAttribute("hidden");
+ act(() => showToolWindow("structure"));
+ expect(screen.getByText("tree")).toBeVisible();
+ expect(screen.getByText("members")).toBeInTheDocument();
+ expect(splitter).not.toHaveAttribute("hidden");
+ expect(container.querySelector('[data-slot="left"]')!.nextElementSibling).toBe(splitter);
+ expect(container.querySelector('[data-slot="left-split"]')).not.toHaveAttribute("hidden");
+ unmount();
+ disposers.forEach((d) => d());
+ });
});
describe("workbench shell", () => {
diff --git a/src/workbench/activate.ts b/src/workbench/activate.ts
index d030e8c84..199417490 100644
--- a/src/workbench/activate.ts
+++ b/src/workbench/activate.ts
@@ -25,7 +25,12 @@ import { registerShellActions } from "./shellActions";
import { TaskStatus } from "./StatusBar";
import { installTaskEvents } from "./tasks";
import { installToolWindowActions } from "./toolwindows/actions";
-import { loadToolWindowLayout, setFocusedToolWindow, toolWindowServiceImpl } from "./toolwindows/store";
+import {
+ installToolWindowLayoutSync,
+ loadToolWindowLayout,
+ setFocusedToolWindow,
+ toolWindowServiceImpl,
+} from "./toolwindows/store";
export function activateWorkbench(): () => void {
provideToolWindowService(toolWindowServiceImpl);
@@ -49,6 +54,7 @@ export function activateWorkbench(): () => void {
unsubProject,
registerShellActions(),
installToolWindowActions(),
+ installToolWindowLayoutSync(),
installDistractionFree(),
installFocusTracking(setFocusedToolWindow),
installTaskEvents(),
diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts
index 3af2a6bda..9d43af875 100644
--- a/src/workbench/contributions.ts
+++ b/src/workbench/contributions.ts
@@ -22,8 +22,12 @@ export interface ToolWindowContribution {
/** Icon name from `ui/icons`. */
icon: string;
anchor: ToolWindowAnchor;
- /** Order within its stripe; lower first. Bottom-of-stripe group when `secondary`. */
+ /** Order within its stripe group; lower first. */
order?: number;
+ /**
+ * Docks in the side's split area (IDEA `secondary` / `isSplit`): Left Bottom,
+ * Bottom Right or Right Bottom, so it can show beside the primary window.
+ */
secondary?: boolean;
component: ComponentType<{ id: string }>;
/** Extra header controls, right-aligned (shown on hover like IDEA). */
@@ -303,6 +307,10 @@ export interface EditorService {
saveAll(): Promise<void>;
/** Move keyboard focus to the active editor (used by Escape from tool windows). */
focus?(): void;
+ /** Paths of the documents open in editor tabs (all panes, tab order). */
+ openPaths?(): string[];
+ /** Closes every tab showing `path`. */
+ closePath?(path: string): void;
}
export interface ToolWindowService {
@@ -512,8 +520,10 @@ export function projectViewRoots(map: ReadonlyMap<string, ProjectViewRootContrib
// editor tab context menus (IDEA's EditorPopupMenu / ProjectViewPopupMenu /
// EditorTabPopupMenu / EditorGutterPopupMenu groups), e.g. "Run 'hi.ts'" from features/run.
// `openIn` is the Open In › submenu those three menus share (Browser › from features/web).
+// `stopProcess` is the Stop chooser (as IDEA): one item per running process
+// a feature can stop (features/run: run sessions, features/debugger: debug sessions).
-export type ContextMenuId = "editor" | "projectView" | "editorTab" | "editorGutter" | "openIn";
+export type ContextMenuId = "editor" | "projectView" | "editorTab" | "editorGutter" | "openIn" | "stopProcess";
export interface MenuGroupContext {
/** Files / directories the menu is for (absolute paths; a virtual URI for virtual documents). */
diff --git a/src/workbench/distractionFree.test.tsx b/src/workbench/distractionFree.test.tsx
index cc563c91e..e56c05f42 100644
--- a/src/workbench/distractionFree.test.tsx
+++ b/src/workbench/distractionFree.test.tsx
@@ -78,7 +78,7 @@ describe("distraction free mode", () => {
it("persists the layout to restore, not the hidden one", () => {
setDistractionFree(true);
showToolWindow("structure");
- expect(savedVisible()).toEqual({ left: "project", bottom: "terminal", right: null });
+ expect(savedVisible()).toMatchObject({ left: "project", bottom: "terminal", right: null });
// An app restart (no session) loads the normal layout.
resetDistractionFree();
resetToolWindowLayout();
diff --git a/src/workbench/messages.test.tsx b/src/workbench/messages.test.tsx
index a20ba3e9d..37d4b5c36 100644
--- a/src/workbench/messages.test.tsx
+++ b/src/workbench/messages.test.tsx
@@ -64,4 +64,24 @@ describe("message dialogs", () => {
await act(async () => void fireEvent.click(screen.getByRole("button", { name: "Delete" })));
expect(result).toEqual({ checked: true });
});
+
+ it("starts with the given checkbox state and can be dismissed from outside", async () => {
+ render(<MessagesHost />);
+ const abort = new AbortController();
+ let result: MessageResult | undefined;
+ act(() => {
+ void ask({
+ title: "Delete",
+ body: "Delete 'a'?",
+ checkbox: "Safe delete",
+ checked: true,
+ signal: abort.signal,
+ buttons: [{ id: "ok", label: "Delete", primary: true }],
+ }).then((r) => (result = r));
+ });
+ expect(screen.getByRole("checkbox", { name: "Safe delete" })).toBeChecked();
+ await act(async () => abort.abort());
+ expect(result).toEqual({ button: "dismissed", checked: true });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
});
diff --git a/src/workbench/messages.tsx b/src/workbench/messages.tsx
index 6b2feec75..6ccf89f96 100644
--- a/src/workbench/messages.tsx
+++ b/src/workbench/messages.tsx
@@ -29,6 +29,10 @@ export interface MessageRequest {
cancel?: boolean;
/** "Don't ask again" and similar, shown under the text. */
checkbox?: string;
+ /** Initial state of `checkbox` (default unchecked). */
+ checked?: boolean;
+ /** Closes the dialog from outside (work finished meanwhile): resolves with button `dismissed`. */
+ signal?: AbortSignal;
/** Defaults to `question`. */
icon?: MessageIconKind;
width?: number;
@@ -54,19 +58,18 @@ let seq = 0;
export const ask: Ask = (request) =>
new Promise((resolve) => {
const id = ++seq;
- useMessages.setState((s) => ({
- stack: [
- ...s.stack,
- {
- ...request,
- id,
- resolve: (r) => {
- useMessages.setState((st) => ({ stack: st.stack.filter((m) => m.id !== id) }));
- resolve(r);
- },
- },
- ],
- }));
+ let settled = false;
+ const finish = (r: MessageResult) => {
+ if (settled) return;
+ settled = true;
+ request.signal?.removeEventListener("abort", onAbort);
+ useMessages.setState((st) => ({ stack: st.stack.filter((m) => m.id !== id) }));
+ resolve(r);
+ };
+ const onAbort = () => finish({ button: "dismissed", checked: !!request.checked });
+ if (request.signal?.aborted) return onAbort();
+ request.signal?.addEventListener("abort", onAbort);
+ useMessages.setState((s) => ({ stack: [...s.stack, { ...request, id, resolve: finish }] }));
});
export interface ConfirmOptions {
@@ -76,6 +79,8 @@ export interface ConfirmOptions {
ok: string;
icon?: MessageIconKind;
checkbox?: string;
+ /** Initial state of `checkbox`. */
+ checked?: boolean;
}
/** OK / Cancel question; resolves `null` when cancelled, else the checkbox state. */
@@ -85,13 +90,14 @@ export async function confirmChecked(opts: ConfirmOptions): Promise<{ checked: b
body: opts.message,
icon: opts.icon,
checkbox: opts.checkbox,
+ checked: opts.checked,
buttons: [{ id: "ok", label: opts.ok, primary: true }],
});
return r.button === "ok" ? { checked: r.checked } : null;
}
/** OK / Cancel question; resolves true for OK. */
-export async function confirm(opts: Omit<ConfirmOptions, "checkbox">): Promise<boolean> {
+export async function confirm(opts: Omit<ConfirmOptions, "checkbox" | "checked">): Promise<boolean> {
return (await confirmChecked(opts)) !== null;
}
@@ -118,7 +124,7 @@ export function MessagesHost() {
}
function MessageDialog({ message }: { message: Pending }) {
- const [checked, setChecked] = useState(false);
+ const [checked, setChecked] = useState(!!message.checked);
const done = (button: string) => message.resolve({ button, checked });
const declared: DialogButton[] = message.buttons.map((b) => ({
label: b.label,
diff --git a/src/workbench/notificationStore.ts b/src/workbench/notificationStore.ts
index 2e7e22aca..f9bebf61f 100644
--- a/src/workbench/notificationStore.ts
+++ b/src/workbench/notificationStore.ts
@@ -85,7 +85,8 @@ interface NotificationState {
export const useNotifications = create<NotificationState>(() => ({ items: [] }));
-export const BALLOON_TIMEOUT: Record<NotificationLevel, number | null> = { info: 6000, warning: 10000, error: null };
+/** IDEA fades balloons out after 10 s; errors stay until dismissed (as IDEA's sticky error groups). */
+export const BALLOON_TIMEOUT: Record<NotificationLevel, number | null> = { info: 10000, warning: 10000, error: null };
const MAX_HISTORY = 200;
let seq = 0;
diff --git a/src/workbench/toolwindows/ToolWindows.module.css b/src/workbench/toolwindows/ToolWindows.module.css
index 866bed734..02d0a6d97 100644
--- a/src/workbench/toolwindows/ToolWindows.module.css
+++ b/src/workbench/toolwindows/ToolWindows.module.css
@@ -46,6 +46,35 @@
grid-area: editor;
}
+/* A side: primary and split areas, each an island; stacked on the left and right, side by side at the bottom. */
+.side {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+}
+.sideRow {
+ flex-direction: row;
+}
+/* --split-a / --split-b: the stored ratio (SidePanel), moved directly while the splitter is dragged. */
+.areaFirst {
+ flex: var(--split-a, 1) 1 0px;
+}
+.areaSecond {
+ flex: var(--split-b, 1) 1 0px;
+}
+.island[hidden] {
+ display: none;
+}
+.side > .splitGap {
+ flex: none;
+ height: var(--island-gap);
+}
+.sideRow > .splitGap {
+ height: auto;
+ width: var(--island-gap);
+}
+
/* Islands: rounded surfaces on the frame background, separated by gaps. */
.island {
position: relative;
@@ -168,6 +197,21 @@
.stripeSpacer {
flex: 1;
}
+.stripeGroup {
+ flex: none;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: inherit;
+}
+/* Between a stripe group's primary and split windows. */
+.stripeSeparator {
+ flex: none;
+ width: 16px;
+ height: 1px;
+ margin: 2px 0;
+ background: var(--border);
+}
.stripeButton {
position: relative;
flex: none;
diff --git a/src/workbench/toolwindows/ToolWindows.tsx b/src/workbench/toolwindows/ToolWindows.tsx
index 72bf4122b..84ccd395f 100644
--- a/src/workbench/toolwindows/ToolWindows.tsx
+++ b/src/workbench/toolwindows/ToolWindows.tsx
@@ -17,23 +17,30 @@ import { shortcutLabel } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { Icon, IconButton, Menu, showContextMenu, tooltipAttrs, type MenuItem, T } from "@/ui";
import { FOCUSABLE } from "@/ui/popupState";
+import { TabStripRegistry } from "@/ui/Tabs";
import { useContributions, type ToolWindowAnchor, type ToolWindowContribution } from "../contributions";
import { useDistractionFree } from "../distractionFree";
import {
hideToolWindow,
+ MAX_SPLIT,
+ MIN_SPLIT,
moveToolWindow,
placed,
resetToolWindowPlacements,
hasStripeButton,
removeFromStripe,
setToolWindowSize,
+ setToolWindowSplit,
showToolWindow,
- stripeGroupOf,
+ SLOTS,
+ slotOf,
toggleMaximizeToolWindow,
toggleToolWindow,
useToolWindowLayout,
- type StripeGroup,
+ type SlotRecord,
+ type ToolWindowSlot,
} from "./store";
+import { contentTabRegistry } from "./content";
import styles from "./ToolWindows.module.css";
import { tx } from "@/platform/i18n";
@@ -56,14 +63,14 @@ export function useToolWindows(): ToolWindowContribution[] {
);
}
-/** Visible window per anchor, ignoring ids that aren't registered (yet). */
-export function useEffectiveVisible(windows: ToolWindowContribution[]): Record<ToolWindowAnchor, string | null> {
+/** Visible window per area, ignoring ids that aren't registered (yet) or don't dock there. */
+export function useEffectiveVisible(windows: ToolWindowContribution[]): SlotRecord {
const visible = useToolWindowLayout((s) => s.visible);
return useMemo(() => {
- const out: Record<ToolWindowAnchor, string | null> = { left: null, right: null, bottom: null };
- for (const a of ["left", "right", "bottom"] as const) {
- const id = visible[a];
- if (id && windows.some((w) => w.id === id && w.anchor === a)) out[a] = id;
+ const out = {} as SlotRecord;
+ for (const slot of SLOTS) {
+ const id = visible[slot];
+ out[slot] = id && windows.some((w) => w.id === id && slotOf(w) === slot) ? id : null;
}
return out;
}, [visible, windows]);
@@ -72,25 +79,28 @@ export function useEffectiveVisible(windows: ToolWindowContribution[]): Record<T
// ---------------------------------------------------------------------------
// Stripes
-const GROUP_LABELS: Array<[StripeGroup, string]> = [
- ["left-top", "Left Top"],
- ["left-bottom", "Bottom"],
- ["right-top", "Right Top"],
- ["right-bottom", "Right Bottom"],
+/** IDEA's Move To anchors (New UI: no top). */
+const MOVE_TARGETS: Array<[ToolWindowSlot, string]> = [
+ ["left", "Left Top"],
+ ["left-split", "Left Bottom"],
+ ["bottom", "Bottom Left"],
+ ["bottom-split", "Bottom Right"],
+ ["right-split", "Right Bottom"],
+ ["right", "Right Top"],
];
/** "Move to" submenu (IDEA: tool window options › Move To). */
export function moveToMenu(tw: ToolWindowContribution): MenuItem {
- const current = stripeGroupOf(tw);
+ const current = slotOf(tw);
return {
label: "Move To",
submenu: [
- ...GROUP_LABELS.map(([group, label]): MenuItem => ({
- id: group,
+ ...MOVE_TARGETS.map(([slot, label]): MenuItem => ({
+ id: slot,
label,
- checked: group === current ? true : undefined,
- disabled: group === current,
- run: () => moveToolWindow(tw.id, group),
+ checked: slot === current ? true : undefined,
+ disabled: slot === current,
+ run: () => moveToolWindow(tw.id, slot),
})),
{ kind: "separator" },
{ label: "Restore Default Layout", run: resetToolWindowPlacements },
@@ -253,7 +263,7 @@ function StripeHandle({
// Stripe button drag. Pointer events rather than HTML5 drag and drop: with the window's native
// file drop enabled, the webview never sees dragover / drop for drags that start inside it.
-type StripeDrop = { group: StripeGroup; before: string | null };
+type StripeDrop = { slot: ToolWindowSlot; before: string | null };
const useStripeDrag = create<{ id: string | null; drop: StripeDrop | null }>(() => ({ id: null, drop: null }));
@@ -262,23 +272,34 @@ const DRAG_THRESHOLD = 4;
/** Set when a drag ends on its own button, so the click that follows doesn't toggle the window. */
let dragEnded = false;
-/** Drop position under the pointer: a stripe group and the button to insert before (null: at the end). */
+/**
+ * Stripe groups (IDEA New UI): each stripe's upper group holds its side,
+ * primary windows then split ones after a separator; the lower group of the
+ * left stripe holds Bottom Left, that of the right stripe Bottom Right.
+ */
+function lowerSlot(side: StripeSide): ToolWindowSlot {
+ return side === "left" ? "bottom" : "bottom-split";
+}
+
+const middle = (r: DOMRect) => r.top + r.height / 2;
+
+/** Drop position under the pointer: an area and the button to insert before (null: at the end). */
function stripeDropAt(x: number, y: number): StripeDrop | null {
const nav = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-stripe-side]");
const side = nav?.dataset.stripeSide;
if (!nav || (side !== "left" && side !== "right")) return null;
const spacer = nav.querySelector<HTMLElement>("[data-stripe-spacer]")?.getBoundingClientRect();
- const lower = !!spacer && y > spacer.top + spacer.height / 2;
+ const separator = nav.querySelector<HTMLElement>("[data-stripe-separator]")?.getBoundingClientRect();
+ const slot: ToolWindowSlot =
+ spacer && y > middle(spacer) ? lowerSlot(side) : separator && y > middle(separator) ? `${side}-split` : side;
let before: string | null = null;
- for (const b of nav.querySelectorAll<HTMLElement>("[data-stripe-button]")) {
- const r = b.getBoundingClientRect();
- if (spacer && r.top > spacer.top !== lower) continue;
- if (y < r.top + r.height / 2) {
+ for (const b of nav.querySelectorAll<HTMLElement>(`[data-stripe-slot="${slot}"] [data-stripe-button]`)) {
+ if (y < middle(b.getBoundingClientRect())) {
before = b.dataset.stripeButton!;
break;
}
}
- return { group: `${side}-${lower ? "bottom" : "top"}`, before };
+ return { slot, before };
}
function startStripeDrag(e: PointerEvent<HTMLButtonElement>, id: string) {
@@ -308,7 +329,7 @@ function startStripeDrag(e: PointerEvent<HTMLButtonElement>, id: string) {
place(ev.clientX, ev.clientY);
const drop = stripeDropAt(ev.clientX, ev.clientY);
const cur = useStripeDrag.getState().drop;
- if (drop?.group !== cur?.group || drop?.before !== cur?.before) useStripeDrag.setState({ drop });
+ if (drop?.slot !== cur?.slot || drop?.before !== cur?.before) useStripeDrag.setState({ drop });
};
const finish = (commit: boolean) => {
window.removeEventListener("pointermove", onMove);
@@ -321,7 +342,7 @@ function startStripeDrag(e: PointerEvent<HTMLButtonElement>, id: string) {
useStripeDrag.setState({ id: null, drop: null });
dragEnded = true;
setTimeout(() => (dragEnded = false));
- if (commit && drop && drop.before !== id) moveToolWindow(id, drop.group, drop.before);
+ if (commit && drop && drop.before !== id) moveToolWindow(id, drop.slot, drop.before);
};
const onUp = () => finish(true);
const onCancel = () => finish(false);
@@ -455,38 +476,41 @@ export function ToolWindowStripe({
showNames = true,
buttonWidth,
}: {
- side: "left" | "right";
+ side: StripeSide;
windows: ToolWindowContribution[];
- visible: Record<ToolWindowAnchor, string | null>;
+ visible: SlotRecord;
/** Tool window names under the icons (IDEA "Show Tool Window Names"). */
showNames?: boolean;
/** Button width with names, px. */
buttonWidth?: number;
}) {
- const isActive = (w: ToolWindowContribution) => visible[w.anchor] === w.id;
+ const isActive = (w: ToolWindowContribution) => visible[slotOf(w)] === w.id;
const stripeButtons = useToolWindowLayout((s) => s.stripeButtons);
const onStripe = windows.filter((w) => hasStripeButton(w, stripeButtons) || isActive(w));
- // Left stripe: left windows on top; bottom-anchored windows in the lower group (IDEA new UI).
- const top = onStripe.filter((w) => stripeGroupOf(w) === `${side}-top`);
- const bottom = onStripe.filter((w) => stripeGroupOf(w) === `${side}-bottom`);
+ const inSlot = (slot: ToolWindowSlot) => onStripe.filter((w) => slotOf(w) === slot);
+ const primary = inSlot(side);
+ const split = inSlot(`${side}-split`);
+ const lower = inSlot(lowerSlot(side));
const moreWindows = windows.filter((w) => !onStripe.includes(w));
const focused = useToolWindowLayout((s) => s.focused);
const drop = useStripeDrag((s) => s.drop);
+ // While a button is dragged the separator shows even without split windows, as a drop target.
+ const dragging = useStripeDrag((s) => !!s.id);
- const indicator = (group: StripeGroup, before: string | null) =>
- drop && drop.group === group && drop.before === before ? (
+ const indicator = (slot: ToolWindowSlot, before: string | null) =>
+ drop && drop.slot === slot && drop.before === before ? (
<div className={styles.stripeDrop} aria-hidden="true" />
) : null;
- const renderGroup = (group: StripeGroup, list: ToolWindowContribution[]) => (
- <>
+ const renderGroup = (slot: ToolWindowSlot, list: ToolWindowContribution[]) => (
+ <div className={styles.stripeGroup} data-stripe-slot={slot}>
{list.map((w) => (
<div key={w.id} className={styles.stripeSlot}>
- {indicator(group, w.id)}
+ {indicator(slot, w.id)}
<StripeButton tw={w} active={isActive(w)} focused={focused === w.id} side={side} showName={showNames} />
</div>
))}
- <div className={styles.stripeSlot}>{indicator(group, null)}</div>
- </>
+ <div className={styles.stripeSlot}>{indicator(slot, null)}</div>
+ </div>
);
return (
@@ -503,10 +527,16 @@ export function ToolWindowStripe({
)}
onKeyDown={onStripeKeyDown}
>
- {renderGroup(`${side}-top`, top)}
+ {renderGroup(side, primary)}
+ {(split.length > 0 || dragging) && (
+ <>
+ <div className={styles.stripeSeparator} data-stripe-separator="" role="separator" />
+ {renderGroup(`${side}-split`, split)}
+ </>
+ )}
{side === "left" && <StripeMore windows={moreWindows} />}
<div className={styles.stripeSpacer} data-stripe-spacer="" />
- {renderGroup(`${side}-bottom`, bottom)}
+ {renderGroup(lowerSlot(side), lower)}
</nav>
);
}
@@ -606,7 +636,9 @@ function ToolWindowView({ tw, hidden }: { tw: ToolWindowContribution; hidden: bo
)}
{Tabs && (
<div className={clsx(styles.headerContent, tw.tabsReplaceTitle && styles.headerContentOnly)}>
- <Tabs id={tw.id} />
+ <TabStripRegistry.Provider value={contentTabRegistry(tw.id)}>
+ <Tabs id={tw.id} />
+ </TabStripRegistry.Provider>
</div>
)}
<div className={styles.headerSpacer} />
@@ -647,55 +679,158 @@ function ToolWindowView({ tw, hidden }: { tw: ToolWindowContribution; hidden: bo
);
}
-function AnchorPanel({
+const MIN: Record<ToolWindowAnchor, number> = { left: 140, right: 160, bottom: 90 };
+const MAXIMIZED: Record<ToolWindowAnchor, string> = { left: "82%", right: "82%", bottom: "88%" };
+/** The editor keeps at least this much room when a tool window is resized (see the grid template). */
+const EDITOR_MIN = { width: 200, height: 60 };
+/** Smallest area when a side is split: stacked (left / right) and side by side (bottom). */
+const SPLIT_MIN = { stacked: 60, sideBySide: 120 };
+const KEY_STEP = 10;
+
+/**
+ * Splitter between the primary and split areas of a side: horizontal on the
+ * left and right (areas stacked), vertical at the bottom (side by side).
+ * Moves CSS variables while dragging; the ratio is stored on release.
+ */
+function SplitHandle({ anchor, hidden }: { anchor: ToolWindowAnchor; hidden: boolean }) {
+ const stacked = anchor !== "bottom";
+ const measure = (el: HTMLElement) => {
+ const side = el.parentElement;
+ const first = el.previousElementSibling as HTMLElement | null;
+ const second = el.nextElementSibling as HTMLElement | null;
+ if (!side || !first || !second) return null;
+ const size = (e: HTMLElement) => (stacked ? e.offsetHeight : e.offsetWidth);
+ const total = size(first) + size(second);
+ if (total <= 0) return null;
+ const min = Math.min(stacked ? SPLIT_MIN.stacked : SPLIT_MIN.sideBySide, total / 2);
+ return { side, first: size(first), total, clamp: (px: number) => Math.min(total - min, Math.max(min, px)) };
+ };
+ const apply = (side: HTMLElement, ratio: number) => {
+ side.style.setProperty("--split-a", String(ratio));
+ side.style.setProperty("--split-b", String(1 - ratio));
+ };
+ const ratioOf = (px: number, total: number) => Math.min(MAX_SPLIT, Math.max(MIN_SPLIT, px / total));
+
+ const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
+ const el = e.currentTarget;
+ const m = measure(el);
+ if (e.button !== 0 || !m) return;
+ e.preventDefault();
+ el.setPointerCapture(e.pointerId);
+ const origin = stacked ? e.clientY : e.clientX;
+ const cursor = document.body.style.cursor;
+ document.body.style.cursor = stacked ? "row-resize" : "col-resize";
+ let ratio: number | null = null;
+ const move = (ev: globalThis.PointerEvent) => {
+ ratio = ratioOf(m.clamp(m.first + (stacked ? ev.clientY : ev.clientX) - origin), m.total);
+ apply(m.side, ratio);
+ };
+ const end = () => {
+ el.removeEventListener("pointermove", move);
+ el.removeEventListener("pointerup", end);
+ el.removeEventListener("pointercancel", end);
+ document.body.style.cursor = cursor;
+ if (ratio !== null) setToolWindowSplit(anchor, ratio);
+ // Back to the store's value (unchanged when the ratio was clamped to it).
+ apply(m.side, useToolWindowLayout.getState().splits[anchor]);
+ };
+ el.addEventListener("pointermove", move);
+ el.addEventListener("pointerup", end);
+ el.addEventListener("pointercancel", end);
+ };
+
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
+ const dir = (stacked ? ["ArrowUp", "ArrowDown"] : ["ArrowLeft", "ArrowRight"]).indexOf(e.key);
+ const m = measure(e.currentTarget);
+ if (dir < 0 || !m) return;
+ e.preventDefault();
+ setToolWindowSplit(anchor, ratioOf(m.clamp(m.first + (dir ? 1 : -1) * KEY_STEP), m.total));
+ };
+
+ return (
+ <div
+ role="separator"
+ aria-orientation={stacked ? "horizontal" : "vertical"}
+ aria-label={`Resize ${anchor} tool window split`}
+ tabIndex={0}
+ hidden={hidden}
+ className={clsx(styles.gap, styles.splitGap)}
+ data-split-handle={anchor}
+ onPointerDown={onPointerDown}
+ onKeyDown={onKeyDown}
+ />
+ );
+}
+
+/**
+ * One side's tool windows: the primary area and the split area, each an
+ * island; with both showing they share the side at the stored ratio.
+ */
+function SidePanel({
anchor,
windows,
- visibleId,
+ visible,
}: {
anchor: ToolWindowAnchor;
windows: ToolWindowContribution[];
- visibleId: string | null;
+ visible: SlotRecord;
}) {
const mounted = useToolWindowLayout((s) => s.mounted);
- const list = windows.filter((w) => w.anchor === anchor && (mounted.has(w.id) || w.id === visibleId));
+ const ratio = useToolWindowLayout((s) => s.splits[anchor]);
+ const area = (slot: ToolWindowSlot, className: string | undefined) => {
+ const visibleId = visible[slot];
+ const list = windows.filter((w) => slotOf(w) === slot && (mounted.has(w.id) || w.id === visibleId));
+ if (!list.length) return null;
+ return (
+ <div className={clsx(styles.island, styles.anchor, className)} data-slot={slot} hidden={!visibleId}>
+ {list.map((w) => (
+ <ToolWindowView key={w.id} tw={w} hidden={w.id !== visibleId} />
+ ))}
+ </div>
+ );
+ };
+ const style = { "--split-a": ratio, "--split-b": 1 - ratio } as CSSProperties;
return (
- <div className={clsx(styles.island, styles.anchor)} data-anchor={anchor}>
- {list.map((w) => (
- <ToolWindowView key={w.id} tw={w} hidden={w.id !== visibleId} />
- ))}
+ <div className={clsx(styles.side, anchor === "bottom" && styles.sideRow)} data-anchor={anchor} style={style}>
+ {area(anchor, styles.areaFirst)}
+ <SplitHandle anchor={anchor} hidden={!visible[anchor] || !visible[`${anchor}-split`]} />
+ {area(`${anchor}-split`, styles.areaSecond)}
</div>
);
}
-const MIN: Record<ToolWindowAnchor, number> = { left: 140, right: 160, bottom: 90 };
-const MAXIMIZED: Record<ToolWindowAnchor, string> = { left: "82%", right: "82%", bottom: "88%" };
-/** The editor keeps at least this much room when a tool window is resized (see the grid template). */
-const EDITOR_MIN = { width: 200, height: 60 };
-const KEY_STEP = 10;
+/** Windows shown on side `a`, primary area first. */
+function visibleOn(visible: SlotRecord, a: ToolWindowAnchor): string[] {
+ return [visible[a], visible[`${a}-split`]].filter((id): id is string => !!id);
+}
+
+const sideVisible = (visible: SlotRecord, a: ToolWindowAnchor) => !!(visible[a] || visible[`${a}-split`]);
/** Writes the grid's track variables from the store; the grid itself squeezes tracks when the window is small. */
-function syncTracks(grid: HTMLElement, visible: Record<ToolWindowAnchor, string | null>) {
+function syncTracks(grid: HTMLElement, visible: SlotRecord) {
const s = useToolWindowLayout.getState();
for (const a of ["left", "right", "bottom"] as const) {
- const size = !visible[a] ? "0px" : s.maximized === a ? MAXIMIZED[a] : `${s.sizes[a]}px`;
+ const shown = sideVisible(visible, a);
+ const size = !shown ? "0px" : s.maximized === a ? MAXIMIZED[a] : `${s.sizes[a]}px`;
grid.style.setProperty(`--tw-${a}`, size);
- grid.style.setProperty(`--gap-${a}`, visible[a] ? "var(--island-gap)" : "0px");
+ grid.style.setProperty(`--gap-${a}`, shown ? "var(--island-gap)" : "0px");
}
}
/**
- * Resize handle in the gap next to an anchor's island. Moves only a CSS variable
+ * Resize handle in the gap next to a side's islands. Moves only a CSS variable
* while dragging; the remembered size is stored on release.
*/
function GapHandle({
anchor,
- visibleId,
+ visibleIds,
gridRef,
editorRef,
sync,
}: {
anchor: ToolWindowAnchor;
- visibleId: string | null;
+ /** Windows shown on this side (primary and split area). */
+ visibleIds: string[];
gridRef: RefObject<HTMLDivElement | null>;
editorRef: RefObject<HTMLDivElement | null>;
sync: () => void;
@@ -713,7 +848,7 @@ function GapHandle({
const clamp = (raw: number, max: number) => Math.min(max, Math.max(MIN[anchor], raw));
const commit = (px: number) => {
const s = useToolWindowLayout.getState();
- if (visibleId && s.maximized === anchor) toggleMaximizeToolWindow(visibleId);
+ if (visibleIds[0] && s.maximized === anchor) toggleMaximizeToolWindow(visibleIds[0]);
setToolWindowSize(anchor, px);
sync();
};
@@ -721,7 +856,7 @@ function GapHandle({
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
const grid = gridRef.current;
const m = measure();
- if (e.button !== 0 || !grid || !m || !visibleId) return;
+ if (e.button !== 0 || !grid || !m || !visibleIds.length) return;
// No focus (and so no focus ring) or text selection from a mouse drag.
e.preventDefault();
const el = e.currentTarget;
@@ -741,7 +876,7 @@ function GapHandle({
el.removeEventListener("pointerup", end);
el.removeEventListener("pointercancel", end);
document.body.style.cursor = cursor;
- if (next === 0) hideToolWindow(visibleId);
+ if (next === 0) visibleIds.forEach(hideToolWindow);
else if (next !== m.size) commit(next);
else sync();
};
@@ -765,7 +900,7 @@ function GapHandle({
aria-orientation={vertical ? "vertical" : "horizontal"}
aria-label={`Resize ${anchor} tool window`}
tabIndex={0}
- hidden={!visibleId}
+ hidden={!visibleIds.length}
className={styles.gap}
data-gap={anchor}
onPointerDown={onPointerDown}
@@ -830,9 +965,13 @@ export function ToolWindowLayout({ editor }: { editor: ReactNode }) {
const sizes = useToolWindowLayout((s) => s.sizes);
const maximized = useToolWindowLayout((s) => s.maximized);
const stripeButtons = useToolWindowLayout((s) => s.stripeButtons);
- const hasRight = windows.some(
- (w) => w.anchor === "right" && (hasStripeButton(w, stripeButtons) || visible.right === w.id),
- );
+ // The right stripe holds the right side's windows and Bottom Right.
+ const hasRight = windows.some((w) => {
+ const slot = slotOf(w);
+ return (
+ (w.anchor === "right" || slot === "bottom-split") && (hasStripeButton(w, stripeButtons) || visible[slot] === w.id)
+ );
+ });
// While a stripe button is dragged, an empty right stripe shows as a drop target.
const dragging = useStripeDrag((s) => !!s.id);
const rightStripe = bars && (hasRight || dragging);
@@ -844,7 +983,13 @@ export function ToolWindowLayout({ editor }: { editor: ReactNode }) {
useLayoutEffect(sync, [visible, sizes, maximized]);
const gap = (anchor: ToolWindowAnchor) => (
- <GapHandle anchor={anchor} visibleId={visible[anchor]} gridRef={gridRef} editorRef={editorRef} sync={sync} />
+ <GapHandle
+ anchor={anchor}
+ visibleIds={visibleOn(visible, anchor)}
+ gridRef={gridRef}
+ editorRef={editorRef}
+ sync={sync}
+ />
);
return (
<div
@@ -854,15 +999,15 @@ export function ToolWindowLayout({ editor }: { editor: ReactNode }) {
{bars && stripe("left")}
{bars && stripeHandle("left")}
<div ref={gridRef} className={clsx(styles.grid, widescreen && styles.widescreen)}>
- <AnchorPanel anchor="left" windows={windows} visibleId={visible.left} />
+ <SidePanel anchor="left" windows={windows} visible={visible} />
{gap("left")}
<div ref={editorRef} className={clsx(styles.island, styles.editorIsland)}>
{editor}
</div>
{gap("right")}
- <AnchorPanel anchor="right" windows={windows} visibleId={visible.right} />
+ <SidePanel anchor="right" windows={windows} visible={visible} />
{gap("bottom")}
- <AnchorPanel anchor="bottom" windows={windows} visibleId={visible.bottom} />
+ <SidePanel anchor="bottom" windows={windows} visible={visible} />
</div>
{rightStripe && stripeHandle("right")}
{rightStripe && stripe("right")}
diff --git a/src/workbench/toolwindows/actions.ts b/src/workbench/toolwindows/actions.ts
index 3196a9510..bcc13f0c5 100644
--- a/src/workbench/toolwindows/actions.ts
+++ b/src/workbench/toolwindows/actions.ts
@@ -1,10 +1,12 @@
import { registerAction, registerActions } from "@/platform/actions";
import { useContributions } from "../contributions";
import { focusEditor } from "../focus";
+import { closeSelectedContent } from "./content";
import {
activateToolWindow,
hideActiveToolWindow,
hideAllToolWindows,
+ hideToolWindow,
jumpToLastToolWindow,
useToolWindowLayout,
toggleMaximizeToolWindow,
@@ -52,12 +54,25 @@ export function installToolWindowActions(): () => void {
run: jumpToLastToolWindow,
},
{
+ // IDEA: also from the editor, hiding the last active window if it is still shown.
id: "toolwindow.hideActive",
title: "Hide Active Tool Window",
category: "Window",
- when: "toolWindowFocus && !popupOpen",
+ when: "projectOpen && !popupOpen",
run: hideActiveToolWindow,
},
+ {
+ // Close Content, as IDEA (⌘W / Ctrl+F4 in a tool window): the selected closable tab, else the window.
+ id: "toolwindow.closeContent",
+ title: "Close Tool Window Tab",
+ category: "Window",
+ when: "toolWindowFocus && !popupOpen",
+ run: () => {
+ const s = useToolWindowLayout.getState();
+ const id = s.focused ?? s.lastActive;
+ if (id && !closeSelectedContent(id)) hideToolWindow(id);
+ },
+ },
{
id: "toolwindow.focusEditor",
title: "Focus Editor",
diff --git a/src/workbench/toolwindows/content.test.ts b/src/workbench/toolwindows/content.test.ts
new file mode 100644
index 000000000..dc1d1e0cd
--- /dev/null
+++ b/src/workbench/toolwindows/content.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { closeSelectedContent, contentTabRegistry } from "./content";
+
+describe("tool window content tabs", () => {
+ it("closes the selected tab of the first strip that can, else reports false", () => {
+ const closed: string[] = [];
+ const register = contentTabRegistry("run");
+ expect(contentTabRegistry("run")).toBe(register);
+ const disposeA = register({ closeSelected: () => false });
+ const disposeB = register({ closeSelected: () => (closed.push("b"), true) });
+ expect(closeSelectedContent("run")).toBe(true);
+ expect(closed).toEqual(["b"]);
+ disposeB();
+ expect(closeSelectedContent("run")).toBe(false);
+ disposeA();
+ expect(closeSelectedContent("other")).toBe(false);
+ });
+});
diff --git a/src/workbench/toolwindows/content.ts b/src/workbench/toolwindows/content.ts
new file mode 100644
index 000000000..04fa219a2
--- /dev/null
+++ b/src/workbench/toolwindows/content.ts
@@ -0,0 +1,26 @@
+import type { TabStripHandle } from "@/ui/Tabs";
+
+/** Content tab strips rendered in each tool window's header (Run sessions, Find tabs, terminals…). */
+const strips = new Map<string, Set<TabStripHandle>>();
+const registries = new Map<string, (handle: TabStripHandle) => () => void>();
+
+/** The `TabStripRegistry` value for tool window `id` (stable per id). */
+export function contentTabRegistry(id: string): (handle: TabStripHandle) => () => void {
+ let fn = registries.get(id);
+ if (!fn) {
+ fn = (handle) => {
+ let set = strips.get(id);
+ if (!set) strips.set(id, (set = new Set()));
+ set.add(handle);
+ return () => void set.delete(handle);
+ };
+ registries.set(id, fn);
+ }
+ return fn;
+}
+
+/** Closes the selected content tab of tool window `id`; false when it has none that can be closed. */
+export function closeSelectedContent(id: string): boolean {
+ for (const strip of strips.get(id) ?? []) if (strip.closeSelected()) return true;
+ return false;
+}
diff --git a/src/workbench/toolwindows/store.test.ts b/src/workbench/toolwindows/store.test.ts
index 56ac9da32..fb3066c97 100644
--- a/src/workbench/toolwindows/store.test.ts
+++ b/src/workbench/toolwindows/store.test.ts
@@ -14,7 +14,11 @@ import {
isToolWindowVisible,
loadToolWindowLayout,
moveToolWindow,
+ installToolWindowLayoutSync,
resetToolWindowPlacements,
+ setToolWindowSplit,
+ slotOfId,
+ toggleMaximizeToolWindow,
sanitizePlacements,
resetToolWindowLayout,
setFocusedToolWindow,
@@ -159,9 +163,9 @@ describe("tool window actions", () => {
});
describe("tool window placement", () => {
- it("moves a window to another stripe group, keeps it visible and persists", () => {
+ it("moves a window to another area, keeps it visible and persists", () => {
showToolWindow("structure");
- moveToolWindow("structure", "right-top");
+ moveToolWindow("structure", "right");
expect(anchorOf("structure")).toBe("right");
expect(useToolWindowLayout.getState().visible).toMatchObject({ left: null, right: "structure" });
expect(getContext()["toolWindow.structure.visible"]).toBe(true);
@@ -172,31 +176,149 @@ describe("tool window placement", () => {
expect(anchorOf("structure")).toBe("left");
});
- it("orders windows within the target group", () => {
- moveToolWindow("terminal", "left-top", "project");
+ it("orders windows within the target area", () => {
+ moveToolWindow("terminal", "left", "project");
const p = useToolWindowLayout.getState().placements;
- expect(p.terminal).toMatchObject({ anchor: "left" });
+ expect(p.terminal).toMatchObject({ anchor: "left", split: false });
expect(p.terminal!.order!).toBeLessThan(p.project!.order!);
- moveToolWindow("terminal", "left-bottom");
+ moveToolWindow("terminal", "bottom");
expect(anchorOf("terminal")).toBe("bottom");
});
it("restores the default layout", () => {
- moveToolWindow("project", "right-bottom");
- expect(useToolWindowLayout.getState().placements.project).toMatchObject({ anchor: "right", secondary: true });
+ moveToolWindow("project", "right-split");
+ expect(useToolWindowLayout.getState().placements.project).toMatchObject({ anchor: "right", split: true });
+ expect(slotOfId("project")).toBe("right-split");
resetToolWindowPlacements();
- expect(anchorOf("project")).toBe("left");
+ expect(slotOfId("project")).toBe("left");
});
it("sanitizes stored placements", () => {
- expect(sanitizePlacements({ a: { anchor: "top" }, b: { anchor: "bottom", order: 5, secondary: 1 }, c: null })).toEqual({
- b: { anchor: "bottom", order: 5, secondary: true },
+ expect(
+ sanitizePlacements({ a: { anchor: "top" }, b: { anchor: "bottom", order: 5, split: true }, c: null }),
+ ).toEqual({
+ b: { anchor: "bottom", order: 5, split: true },
});
});
});
+describe("split areas", () => {
+ beforeEach(() => {
+ disposers.push(
+ registerToolWindow({
+ id: "bookmarks",
+ title: "Bookmarks",
+ icon: "bookmark",
+ anchor: "left",
+ secondary: true,
+ component: Empty,
+ }),
+ );
+ });
+
+ it("shows one window per area, both areas of a side at once", () => {
+ showToolWindow("bookmarks");
+ expect(isToolWindowVisible("project")).toBe(true);
+ expect(isToolWindowVisible("bookmarks")).toBe(true);
+ expect(useToolWindowLayout.getState().visible).toMatchObject({ left: "project", "left-split": "bookmarks" });
+ showToolWindow("structure");
+ expect(isToolWindowVisible("project")).toBe(false);
+ expect(isToolWindowVisible("bookmarks")).toBe(true);
+ });
+
+ it("Move To places a window in any of the six areas", () => {
+ showToolWindow("terminal");
+ moveToolWindow("terminal", "bottom-split");
+ expect(useToolWindowLayout.getState().visible).toMatchObject({ bottom: null, "bottom-split": "terminal" });
+ showToolWindow("problems");
+ expect(isToolWindowVisible("terminal")).toBe(true);
+ expect(isToolWindowVisible("problems")).toBe(true);
+ moveToolWindow("bookmarks", "left");
+ expect(slotOfId("bookmarks")).toBe("left");
+ // An explicit primary placement on its own side overrides the contribution's split default.
+ loadToolWindowLayout("/work/a");
+ expect(slotOfId("bookmarks")).toBe("left");
+ expect(isToolWindowVisible("terminal")).toBe(true);
+ });
+
+ it("keeps the side maximized while its other area shows a window", () => {
+ showToolWindow("bookmarks");
+ toggleMaximizeToolWindow("project");
+ hideToolWindow("bookmarks");
+ expect(useToolWindowLayout.getState().maximized).toBe("left");
+ hideToolWindow("project");
+ expect(useToolWindowLayout.getState().maximized).toBeNull();
+ });
+
+ it("hide all stashes and restores both areas", () => {
+ showToolWindow("bookmarks");
+ hideAllToolWindows();
+ expect(isToolWindowVisible("bookmarks")).toBe(false);
+ hideAllToolWindows();
+ expect(isToolWindowVisible("project")).toBe(true);
+ expect(isToolWindowVisible("bookmarks")).toBe(true);
+ });
+
+ it("persists the split ratio, clamped", () => {
+ setToolWindowSplit("left", 0.3);
+ setToolWindowSplit("bottom", 5);
+ loadToolWindowLayout("/work/a");
+ expect(useToolWindowLayout.getState().splits).toMatchObject({ left: 0.3, bottom: 0.9, right: 0.5 });
+ });
+
+ it("migrates a layout saved with one area per side", () => {
+ localStorage.setItem(
+ "openidea.layout.v1:/work/old",
+ JSON.stringify({
+ visible: { left: "bookmarks", right: "terminal", bottom: "problems" },
+ sizes: { left: 300, right: 300, bottom: 200 },
+ placements: {
+ // Old "Right Bottom" stripe group: now the Right Bottom area.
+ terminal: { anchor: "right", secondary: true, order: 10 },
+ // Renumbered in the old bottom group with the contribution's flag: meaningless there.
+ problems: { anchor: "bottom", secondary: true, order: 20 },
+ bookmarks: { anchor: "left", order: 30 },
+ },
+ }),
+ );
+ loadToolWindowLayout("/work/old");
+ expect(slotOfId("terminal")).toBe("right-split");
+ expect(slotOfId("problems")).toBe("bottom");
+ expect(slotOfId("bookmarks")).toBe("left-split");
+ expect(isToolWindowVisible("bookmarks")).toBe(true);
+ expect(isToolWindowVisible("terminal")).toBe(true);
+ expect(isToolWindowVisible("problems")).toBe(true);
+ expect(useToolWindowLayout.getState().sizes.left).toBe(300);
+ showToolWindow("project");
+ expect(JSON.parse(localStorage.getItem("openidea.layout.v1:/work/old")!)).toMatchObject({
+ v: 2,
+ visible: { left: "project", "left-split": "bookmarks", "right-split": "terminal" },
+ });
+ });
+
+ it("moves a late-registered window recorded in the wrong area to its own", () => {
+ const sync = installToolWindowLayoutSync();
+ localStorage.setItem("openidea.layout.v1:/work/late", JSON.stringify({ visible: { left: "late" } }));
+ loadToolWindowLayout("/work/late");
+ expect(useToolWindowLayout.getState().visible.left).toBe("late");
+ disposers.push(
+ registerToolWindow({ id: "late", title: "Late", icon: "x", anchor: "left", secondary: true, component: Empty }),
+ );
+ expect(useToolWindowLayout.getState().visible).toMatchObject({ left: null, "left-split": "late" });
+ expect(getContext()["toolWindow.late.visible"]).toBe(true);
+ sync();
+ });
+});
+
describe("stripe buttons", () => {
- const find = { id: "find", title: "Find", icon: "search", anchor: "bottom" as const, component: Empty, stripe: "onUse" as const };
+ const find = {
+ id: "find",
+ title: "Find",
+ icon: "search",
+ anchor: "bottom" as const,
+ component: Empty,
+ stripe: "onUse" as const,
+ };
const buttons = () => useToolWindowLayout.getState().stripeButtons;
it("adds an on-use window's button when opened and removes it on Hide, persisted per project", () => {
diff --git a/src/workbench/toolwindows/store.ts b/src/workbench/toolwindows/store.ts
index 8e571517f..cec63b835 100644
--- a/src/workbench/toolwindows/store.ts
+++ b/src/workbench/toolwindows/store.ts
@@ -1,7 +1,8 @@
/**
- * Tool window layout state, IDEA semantics: at most one visible window per
- * anchor; showing another window on the same anchor replaces it. Layout
- * (visible windows + sizes) is persisted per project root in localStorage.
+ * Tool window layout state, IDEA semantics: each side (left / right / bottom)
+ * has a primary and a split area, each showing at most one window; showing
+ * another window in the same area replaces it. Layout (visible windows,
+ * sizes, split ratios, placements) is persisted per project root in localStorage.
*/
import { create } from "zustand";
import { setContext } from "@/platform/context";
@@ -15,47 +16,89 @@ import { focusEditor } from "../focus";
export const ANCHORS: readonly ToolWindowAnchor[] = ["left", "bottom", "right"];
+/** Where a window docks: a side's primary area, or its split area (IDEA's `isSplit`). */
+export type ToolWindowSlot = ToolWindowAnchor | `${ToolWindowAnchor}-split`;
+export const SLOTS: readonly ToolWindowSlot[] = [
+ "left",
+ "left-split",
+ "bottom",
+ "bottom-split",
+ "right",
+ "right-split",
+];
+export type SlotRecord = Record<ToolWindowSlot, string | null>;
+
export const DEFAULT_SIZES: Record<ToolWindowAnchor, number> = { left: 240, right: 300, bottom: 280 };
-const DEFAULT_VISIBLE: Record<ToolWindowAnchor, string | null> = { left: "project", right: null, bottom: null };
+/** Share of a side taken by its primary area when both areas show (IDEA's sideWeight). */
+export const DEFAULT_SPLIT = 0.5;
+const DEFAULT_SPLITS: Record<ToolWindowAnchor, number> = {
+ left: DEFAULT_SPLIT,
+ right: DEFAULT_SPLIT,
+ bottom: DEFAULT_SPLIT,
+};
+const NONE: SlotRecord = {
+ left: null,
+ "left-split": null,
+ bottom: null,
+ "bottom-split": null,
+ right: null,
+ "right-split": null,
+};
+const DEFAULT_VISIBLE: SlotRecord = { ...NONE, left: "project" };
const STORAGE_PREFIX = "openidea.layout.v1:";
+/** Stored layout format: 1 = one area per side (no `v` field), 2 = primary + split areas. */
+const LAYOUT_VERSION = 2;
-/** User placement of a tool window (dragged to another stripe / "Move to"), overriding the contribution. */
+/** User placement of a tool window (dragged on the stripes / "Move To"), overriding the contribution. */
export interface ToolWindowPlacement {
anchor: ToolWindowAnchor;
- secondary?: boolean;
+ /** Split area; unset: the contribution's `secondary` when on its own side, else primary. */
+ split?: boolean;
order?: number;
}
-/** Stripe groups: top / bottom part of the left and right stripes. */
-export type StripeGroup = "left-top" | "left-bottom" | "right-top" | "right-bottom";
+export function slotOf(tw: Pick<ToolWindowContribution, "anchor" | "secondary">): ToolWindowSlot {
+ return tw.secondary ? `${tw.anchor}-split` : tw.anchor;
+}
+
+export function slotAnchor(slot: ToolWindowSlot): ToolWindowAnchor {
+ return slot.replace("-split", "") as ToolWindowAnchor;
+}
+
+export function isSplitSlot(slot: ToolWindowSlot): boolean {
+ return slot.endsWith("-split");
+}
export interface ToolWindowLayoutState {
scope: string;
- visible: Record<ToolWindowAnchor, string | null>;
+ visible: SlotRecord;
sizes: Record<ToolWindowAnchor, number>;
+ /** Per side: the primary area's share when both areas show. */
+ splits: Record<ToolWindowAnchor, number>;
maximized: ToolWindowAnchor | null;
/** Tool window containing DOM focus. */
focused: string | null;
/** Most recently activated window (target of Shift+Escape). */
lastActive: string | null;
- /** Windows shown at least once; kept mounted while hidden on their anchor. */
+ /** Windows shown at least once; kept mounted while hidden in their area. */
mounted: ReadonlySet<string>;
/** Bumped to ask a panel to take focus. */
focusRequest: { id: string; seq: number } | null;
/** Visible set stashed by "Hide All" so pressing it again restores. */
- stashed: Record<ToolWindowAnchor, string | null> | null;
+ stashed: SlotRecord | null;
/** Per-window placement overrides (persisted). */
placements: Readonly<Record<string, ToolWindowPlacement>>;
/** User choice of stripe buttons (opened → added, "Hide" → removed); persisted. */
stripeButtons: Readonly<Record<string, boolean>>;
/** Layout before Distraction Free Mode; restored on exit and persisted in place of `visible` meanwhile. */
- distractionFreeStash: Record<ToolWindowAnchor, string | null> | null;
+ distractionFreeStash: SlotRecord | null;
}
const initial = (): ToolWindowLayoutState => ({
scope: "",
visible: { ...DEFAULT_VISIBLE },
sizes: { ...DEFAULT_SIZES },
+ splits: { ...DEFAULT_SPLITS },
maximized: null,
focused: null,
lastActive: null,
@@ -71,78 +114,73 @@ export const useToolWindowLayout = create<ToolWindowLayoutState>(initial);
let focusSeq = 0;
-export function anchorOf(id: string): ToolWindowAnchor | undefined {
- const tw = useContributions.getState().toolWindows.get(id);
- if (!tw) return undefined;
- return useToolWindowLayout.getState().placements[id]?.anchor ?? tw.anchor;
-}
-
/** The contribution with the user's placement applied. */
-export function placed(tw: ToolWindowContribution, placements: Readonly<Record<string, ToolWindowPlacement>>): ToolWindowContribution {
+export function placed(
+ tw: ToolWindowContribution,
+ placements: Readonly<Record<string, ToolWindowPlacement>>,
+): ToolWindowContribution {
const p = placements[tw.id];
if (!p) return tw;
- return { ...tw, anchor: p.anchor, secondary: p.secondary ?? false, order: p.order ?? tw.order };
-}
-
-/** Which stripe group shows a (placed) window. Bottom windows sit in the left stripe's lower group (IDEA new UI). */
-export function stripeGroupOf(tw: Pick<ToolWindowContribution, "anchor" | "secondary">): StripeGroup {
- if (tw.anchor === "bottom") return "left-bottom";
- // The left stripe's lower group is the bottom anchor; a left window there would light up alongside a bottom one.
- if (tw.anchor === "left") return "left-top";
- return `${tw.anchor}-${tw.secondary ? "bottom" : "top"}` as StripeGroup;
-}
-
-function groupPlacement(group: StripeGroup): Omit<ToolWindowPlacement, "order"> {
- switch (group) {
- case "left-top":
- return { anchor: "left" };
- case "left-bottom":
- return { anchor: "bottom" };
- case "right-top":
- return { anchor: "right" };
- case "right-bottom":
- return { anchor: "right", secondary: true };
- }
+ const secondary = p.split ?? (p.anchor === tw.anchor && !!tw.secondary);
+ return { ...tw, anchor: p.anchor, secondary, order: p.order ?? tw.order };
+}
+
+/** The area a registered window docks in, with the user's placement applied. */
+export function slotOfId(id: string): ToolWindowSlot | undefined {
+ const tw = useContributions.getState().toolWindows.get(id);
+ return tw && slotOf(placed(tw, useToolWindowLayout.getState().placements));
+}
+
+export function anchorOf(id: string): ToolWindowAnchor | undefined {
+ const slot = slotOfId(id);
+ return slot && slotAnchor(slot);
+}
+
+/** The other area of the same side. */
+function partnerSlot(slot: ToolWindowSlot): ToolWindowSlot {
+ return isSplitSlot(slot) ? slotAnchor(slot) : `${slot as ToolWindowAnchor}-split`;
}
const byOrder = (a: ToolWindowContribution, b: ToolWindowContribution) =>
(a.order ?? 100) - (b.order ?? 100) || a.title.localeCompare(b.title);
/**
- * Moves a tool window to a stripe group, before `before` (or last). Orders of
- * the target group are renumbered so the drop position sticks. A visible
- * window stays visible at its new anchor (replacing what was shown there).
+ * Moves a tool window to an area (stripe group / "Move To"), before `before`
+ * (or last). Orders of the target area are renumbered so the drop position
+ * sticks. A visible window stays visible in its new area (replacing what was
+ * shown there).
*/
-export function moveToolWindow(id: string, group: StripeGroup, before: string | null = null) {
+export function moveToolWindow(id: string, slot: ToolWindowSlot, before: string | null = null) {
const contributions = useContributions.getState().toolWindows;
- const tw = contributions.get(id);
- if (!tw) return;
+ if (!contributions.has(id)) return;
const s = useToolWindowLayout.getState();
- const oldAnchor = anchorOf(id)!;
- const wasVisible = s.visible[oldAnchor] === id;
+ const oldSlot = slotOfId(id)!;
+ const wasVisible = s.visible[oldSlot] === id;
const members = [...contributions.values()]
.map((w) => placed(w, s.placements))
- .filter((w) => w.id !== id && stripeGroupOf(w) === group)
+ .filter((w) => w.id !== id && slotOf(w) === slot)
.sort(byOrder);
const at = before ? members.findIndex((w) => w.id === before) : -1;
const ids = members.map((w) => w.id);
ids.splice(at >= 0 ? at : ids.length, 0, id);
const placements: Record<string, ToolWindowPlacement> = { ...s.placements };
ids.forEach((wid, i) => {
- const current = placed(contributions.get(wid)!, s.placements);
- const target = wid === id ? groupPlacement(group) : { anchor: current.anchor, secondary: current.secondary };
- placements[wid] = { ...target, order: (i + 1) * 10 };
+ const order = (i + 1) * 10;
+ placements[wid] =
+ wid === id
+ ? { anchor: slotAnchor(slot), split: isSplitSlot(slot), order }
+ : { ...(s.placements[wid] ?? { anchor: contributions.get(wid)!.anchor }), order };
});
- const newAnchor = placements[id]!.anchor;
const visible = { ...s.visible };
- if (wasVisible && oldAnchor !== newAnchor) {
- visible[oldAnchor] = null;
- visible[newAnchor] = id;
+ if (wasVisible && oldSlot !== slot) {
+ visible[oldSlot] = null;
+ visible[slot] = id;
}
+ const oldAnchor = slotAnchor(oldSlot);
update({
placements,
visible,
- maximized: wasVisible && s.maximized === oldAnchor ? null : s.maximized,
+ maximized: wasVisible && s.maximized === oldAnchor && oldAnchor !== slotAnchor(slot) ? null : s.maximized,
});
}
@@ -150,10 +188,10 @@ export function moveToolWindow(id: string, group: StripeGroup, before: string |
export function resetToolWindowPlacements() {
const s = useToolWindowLayout.getState();
const visible = { ...s.visible };
- // Windows shown at an anchor they no longer belong to are hidden.
- for (const a of ANCHORS) {
- const id = visible[a];
- if (id && useContributions.getState().toolWindows.get(id)?.anchor !== a) visible[a] = null;
+ // Windows shown in an area they no longer belong to are hidden.
+ for (const slot of SLOTS) {
+ const tw = visible[slot] ? useContributions.getState().toolWindows.get(visible[slot]!) : undefined;
+ if (tw && slotOf(tw) !== slot) visible[slot] = null;
}
update({ placements: {}, stripeButtons: {}, visible });
}
@@ -162,23 +200,33 @@ function storageKey(scope: string) {
return STORAGE_PREFIX + scope;
}
-function readStorage(
- scope: string,
-): Partial<Pick<ToolWindowLayoutState, "visible" | "sizes" | "placements" | "stripeButtons">> | null {
+function readStorage(scope: string): Record<string, unknown> | null {
try {
const raw = localStorage.getItem(storageKey(scope));
- return raw ? JSON.parse(raw) : null;
+ const v: unknown = raw ? JSON.parse(raw) : null;
+ return v && typeof v === "object" ? (v as Record<string, unknown>) : null;
} catch {
return null;
}
}
function persist() {
- const { scope, visible: current, sizes, placements, stripeButtons, distractionFreeStash } = useToolWindowLayout.getState();
+ const {
+ scope,
+ visible: current,
+ sizes,
+ splits,
+ placements,
+ stripeButtons,
+ distractionFreeStash,
+ } = useToolWindowLayout.getState();
// Distraction Free Mode is not saved: the layout to restore is.
const visible = distractionFreeStash ?? current;
try {
- localStorage.setItem(storageKey(scope), JSON.stringify({ visible, sizes, placements, stripeButtons }));
+ localStorage.setItem(
+ storageKey(scope),
+ JSON.stringify({ v: LAYOUT_VERSION, visible, sizes, splits, placements, stripeButtons }),
+ );
} catch {
/* storage unavailable */
}
@@ -195,15 +243,43 @@ function sanitizeSizes(sizes: unknown): Record<ToolWindowAnchor, number> {
return out;
}
-export function sanitizePlacements(raw: unknown): Record<string, ToolWindowPlacement> {
+export const MIN_SPLIT = 0.1;
+export const MAX_SPLIT = 0.9;
+
+function sanitizeSplits(splits: unknown): Record<ToolWindowAnchor, number> {
+ const out = { ...DEFAULT_SPLITS };
+ if (splits && typeof splits === "object") {
+ for (const a of ANCHORS) {
+ const v = (splits as Record<string, unknown>)[a];
+ if (typeof v === "number" && v >= MIN_SPLIT && v <= MAX_SPLIT) out[a] = v;
+ }
+ }
+ return out;
+}
+
+/**
+ * Stored placements. Format 1 had no split areas: `secondary` only picked the
+ * lower group of the right stripe, which is now the Right Bottom area; on the
+ * left and bottom it meant nothing, so the contribution's default applies.
+ */
+export function sanitizePlacements(raw: unknown, version = LAYOUT_VERSION): Record<string, ToolWindowPlacement> {
const out: Record<string, ToolWindowPlacement> = {};
if (!raw || typeof raw !== "object") return out;
for (const [id, v] of Object.entries(raw as Record<string, unknown>)) {
- const p = v as Partial<ToolWindowPlacement> | null;
+ const p = v as { anchor?: unknown; split?: unknown; secondary?: unknown; order?: unknown } | null;
if (!p || !ANCHORS.includes(p.anchor as ToolWindowAnchor)) continue;
+ const anchor = p.anchor as ToolWindowAnchor;
+ const split =
+ version >= 2
+ ? typeof p.split === "boolean"
+ ? p.split
+ : undefined
+ : anchor === "right" && p.secondary
+ ? true
+ : undefined;
out[id] = {
- anchor: p.anchor as ToolWindowAnchor,
- ...(p.secondary ? { secondary: true } : {}),
+ anchor,
+ ...(split !== undefined ? { split } : {}),
...(typeof p.order === "number" && isFinite(p.order) ? { order: p.order } : {}),
};
}
@@ -217,33 +293,79 @@ function sanitizeStripeButtons(raw: unknown): Record<string, boolean> {
return out;
}
+function sanitizeVisible(raw: unknown): SlotRecord {
+ if (!raw || typeof raw !== "object") return { ...DEFAULT_VISIBLE };
+ const out = { ...NONE };
+ for (const slot of SLOTS) {
+ const v = (raw as Record<string, unknown>)[slot];
+ out[slot] = typeof v === "string" ? v : null;
+ }
+ return out;
+}
+
+/**
+ * Moves visible windows recorded in an area they don't dock in (a layout
+ * saved before a window became split, or before split areas existed) to
+ * their area, unless that area already shows another window. Null: no change.
+ */
+function reconcile(visible: SlotRecord, placements: Readonly<Record<string, ToolWindowPlacement>>): SlotRecord | null {
+ const windows = useContributions.getState().toolWindows;
+ let out: SlotRecord | null = null;
+ for (const slot of SLOTS) {
+ const id = visible[slot];
+ const tw = id ? windows.get(id) : undefined;
+ if (!tw) continue;
+ const home = slotOf(placed(tw, placements));
+ if (home === slot) continue;
+ out ??= { ...visible };
+ out[slot] = null;
+ if (!out[home]) out[home] = id;
+ }
+ return out;
+}
+
/** Loads the layout saved for `scope` (a project root; "" without a project). */
export function loadToolWindowLayout(scope: string) {
const saved = readStorage(scope);
- const visible = { ...DEFAULT_VISIBLE };
- if (saved?.visible && typeof saved.visible === "object") {
- for (const a of ANCHORS) {
- const v = (saved.visible as Record<string, unknown>)[a];
- visible[a] = typeof v === "string" ? v : null;
- }
- }
+ const version = typeof saved?.v === "number" ? saved.v : 1;
+ const placements = sanitizePlacements(saved?.placements, version);
+ let visible = sanitizeVisible(saved?.visible);
+ visible = reconcile(visible, placements) ?? visible;
useToolWindowLayout.setState({
...initial(),
scope,
visible,
sizes: sanitizeSizes(saved?.sizes),
- placements: sanitizePlacements(saved?.placements),
+ splits: sanitizeSplits(saved?.splits),
+ placements,
stripeButtons: sanitizeStripeButtons(saved?.stripeButtons),
mounted: new Set(Object.values(visible).filter((v): v is string => !!v)),
});
publishVisibility();
}
+/**
+ * Keeps the layout in step with tool window registrations: windows that
+ * register after the layout loaded get their visibility context, and a
+ * visible window recorded in the wrong area moves to its own.
+ */
+export function installToolWindowLayoutSync(): () => void {
+ return useContributions.subscribe((c, prev) => {
+ if (c.toolWindows === prev.toolWindows) return;
+ const s = useToolWindowLayout.getState();
+ const visible = reconcile(s.visible, s.placements);
+ if (visible) {
+ const mounted = new Set(s.mounted);
+ for (const id of Object.values(visible)) if (id) mounted.add(id);
+ update({ visible, mounted }, !!s.scope && !s.distractionFreeStash);
+ } else publishVisibility();
+ });
+}
+
function publishVisibility() {
- const { visible } = useToolWindowLayout.getState();
- for (const id of useContributions.getState().toolWindows.keys()) {
- const a = anchorOf(id);
- setContext(`toolWindow.${id}.visible`, !!a && visible[a] === id);
+ const { visible, placements } = useToolWindowLayout.getState();
+ for (const tw of useContributions.getState().toolWindows.values()) {
+ setContext(`toolWindow.${tw.id}.visible`, visible[slotOf(placed(tw, placements))] === tw.id);
}
}
@@ -254,8 +376,8 @@ function update(patch: Partial<ToolWindowLayoutState>, save = true) {
}
export function isToolWindowVisible(id: string): boolean {
- const a = anchorOf(id);
- return !!a && useToolWindowLayout.getState().visible[a] === id;
+ const slot = slotOfId(id);
+ return !!slot && useToolWindowLayout.getState().visible[slot] === id;
}
/** Last shown or focused tool window, kept after it is hidden (Jump to Last Tool Window). */
@@ -272,13 +394,14 @@ export function jumpToLastToolWindow() {
}
export function showToolWindow(id: string, focus = false) {
- const a = anchorOf(id);
- if (!a) return;
+ const slot = slotOfId(id);
+ if (!slot) return;
+ const a = slotAnchor(slot);
lastUsed = id;
const s = useToolWindowLayout.getState();
const mounted = s.mounted.has(id) ? s.mounted : new Set(s.mounted).add(id);
update({
- visible: { ...s.visible, [a]: id },
+ visible: { ...s.visible, [slot]: id },
// Opening a window puts its button on the stripe (IDEA).
stripeButtons: s.stripeButtons[id] ? s.stripeButtons : { ...s.stripeButtons, [id]: true },
mounted,
@@ -290,13 +413,15 @@ export function showToolWindow(id: string, focus = false) {
}
export function hideToolWindow(id: string) {
- const a = anchorOf(id);
+ const slot = slotOfId(id);
const s = useToolWindowLayout.getState();
- if (!a || s.visible[a] !== id) return;
+ if (!slot || s.visible[slot] !== id) return;
const hadFocus = s.focused === id || isFocusWithinToolWindow(id);
+ // The side stays maximized while its other area still shows a window.
+ const sideEmpty = !s.visible[partnerSlot(slot)];
update({
- visible: { ...s.visible, [a]: null },
- maximized: s.maximized === a ? null : s.maximized,
+ visible: { ...s.visible, [slot]: null },
+ maximized: s.maximized === slotAnchor(slot) && sideEmpty ? null : s.maximized,
lastActive: s.lastActive === id ? null : s.lastActive,
});
if (hadFocus) focusEditor();
@@ -337,10 +462,10 @@ export function focusToolWindow(id: string) {
/** Hides every visible window; called again with nothing visible, restores them. */
export function hideAllToolWindows() {
const s = useToolWindowLayout.getState();
- const anyVisible = ANCHORS.some((a) => s.visible[a]);
+ const anyVisible = SLOTS.some((slot) => s.visible[slot]);
if (anyVisible) {
const hadFocus = !!s.focused;
- update({ stashed: { ...s.visible }, visible: { left: null, right: null, bottom: null }, maximized: null });
+ update({ stashed: { ...s.visible }, visible: { ...NONE }, maximized: null });
if (hadFocus) focusEditor();
} else if (s.stashed) {
update({ visible: { ...s.stashed }, stashed: null });
@@ -358,7 +483,7 @@ export function enterDistractionFreeLayout() {
const hadFocus = !!s.focused;
update({
distractionFreeStash: { ...s.visible },
- visible: { left: null, right: null, bottom: null },
+ visible: { ...NONE },
maximized: null,
stashed: null,
});
@@ -388,6 +513,14 @@ export function setToolWindowSize(anchor: ToolWindowAnchor, px: number) {
update({ sizes: { ...s.sizes, [anchor]: v } });
}
+/** Share of `anchor`'s side given to its primary area when both areas show. */
+export function setToolWindowSplit(anchor: ToolWindowAnchor, ratio: number) {
+ const s = useToolWindowLayout.getState();
+ const v = Math.min(MAX_SPLIT, Math.max(MIN_SPLIT, Math.round(ratio * 1000) / 1000));
+ if (!isFinite(v) || s.splits[anchor] === v) return;
+ update({ splits: { ...s.splits, [anchor]: v } });
+}
+
export function toggleMaximizeToolWindow(id: string) {
const a = anchorOf(id);
if (!a) return;