Compare commits

...
Author SHA1 Message Date
l0ng-ai bd79458f59 fix(editor): refresh Java inheritance markers after Maven import 2026-11-23 23:19:09 +08:00
l0ng-ai aec1382e79 fix(agents): keep the prompt box free of scrollbars until it reaches its height limit (#5472)
After one exchange, a new session's empty prompt box showed a horizontal scrollbar and a vertical thumb (visible with always-on scrollbars): the CodeMirror scroller kept a fixed height slightly taller than its content and allowed horizontal overflow. The scroller now sizes to its wrapped text, never scrolls horizontally, and scrolls vertically only past its 280 px limit.
2026-11-23 22:02:22 +08:00
l0ng-ai 999d84b189 fix(run): resolve Java launches in attached projects (#5471)
Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way.
2026-11-23 22:01:15 +08:00
jiejie1133 9fda9b92c2 fix(editor): edit a repeated template variable from one caret (#5443)
After expanding Java `fori`, the three occurrences of `i` were all editing selections, so arrow keys moved three carets. The shared snippet engine now selects only the first occurrence of each variable and mirrors edits to the others, for every live template and language and for LSP snippets with repeated placeholders; the Java-specific handling is gone.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-23 21:41:18 +08:00
fun90andfun90 261eb03009 fix(markdown): open preview links to another file at the linked heading (#5422)
Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <[email protected]>
2026-11-23 21:21:17 +08:00
l0ng-ai db8b553364 fix(editor): merge inheritance gutter markers by line and kind (#5470)
Lombok-generated members (@SuperBuilder, @Data) put one override/implemented marker per generated method on the annotation line, filling the gutter. Markers of the same kind on a line now collapse into one icon with a combined tooltip; clicking it opens the target chooser (a single target still opens directly). Applies to all four inheritance marker kinds.
2026-11-23 21:19:14 +08:00
langxpandkradme 2494b2efdf fix(libraries): reveal classes from unlisted classifier jars (#5414)
Select Opened File could not reveal a class opened from a dependency JAR that used a Maven classifier and was absent from External Libraries. The document knew its exact archive, but the Project view only searches registered archive roots.
External Libraries now adds the exact archive referenced by the active library document, labels it with its Maven coordinate when available, and removes the temporary entry once the build model lists the same archive.

Co-authored-by: kradme <[email protected]>
2026-11-23 21:13:35 +08:00
Muuandmuutot d78ce7ec66 fix(editor): offer contributed Copy Path links in the tab and library menus (#5400)
Copy Path/Reference… built a different submenu per entry point: the project view and the editor caret chooser list the contributed copy items (features/vcs: Path From Repository Root, GitHub Link), while the editor tab menu and the External Libraries menu hand-wrote theirs and silently dropped every contribution. Both hand-written submenus now append the same `copyPath` menu group, so all four entry points agree — and future contributions appear everywhere at once.

Co-authored-by: muutot <[email protected]>
2026-11-23 21:10:34 +08:00
Bert Verhelstandbertyhell 9df9499bf5 fix(project-view): open files on single click when preview tabs are enabled (#5419)
With **Settings › Editor › General › Editor Tabs › Enable preview tab** on, a single click on a file in the Project view now opens it in the preview tab, and the next single click reuses that tab. Before, the click did nothing. The cause was two switches that weren't connected. The Project view checked its own "Enable Preview Tab" view option, which was off by default and only reachable from the view's ⋮ menu. The Settings checkbox was a separate setting, `editor.tabs.previewTab`, which was only read when a preview tab was created.
IntelliJ IDEA documents these as two ways into one setting, so this PR makes them one. The Project view reads `editor.tabs.previewTab` for single click and for Autoscroll to Source. Its ⋮ › Behavior › Enable Preview Tab item and the `project.option.previewTab` action (the id is unchanged) now write that setting. The old view option is removed from the saved Project view options when they load.
What existing users will see:
- Defaults (Settings on, view option off): single click now opens a preview tab. This is the fix. The editor setting already defaulted to on, so users who never changed anything get single-click preview after this change.
- Both on: no change.
- Both off: no change.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 21:10:08 +08:00
53 changed files with 1836 additions and 517 deletions

No files matched your search

+2
View File
@@ -324,6 +324,8 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
+2 -1
View File
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
mut config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+10 -5
View File
@@ -1,6 +1,6 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
mod workspace;
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use crate::ops::Channel;
@@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
@@ -952,16 +952,18 @@ pub async fn build_run(
items: Vec::new(),
});
}
let mut launch_caches = Vec::new();
let plan = if let Some(id) = cmake {
launch_caches.push(cache.clone());
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
cmake_plan(&root, kind, &configs, &id)?
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let member_cache = workspace::cache_at(&root, &cache, member);
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -985,6 +987,7 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
launch_caches.push(cache.clone());
match compile::plan(
&root,
&model,
@@ -1007,7 +1010,9 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
+23 -6
View File
@@ -1,12 +1,33 @@
use super::*;
use std::path::PathBuf;
pub(super) struct Scope {
pub(in crate::ops) struct Scope {
pub root: PathBuf,
pub cache: PathBuf,
pub settings: Settings,
}
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let root = workspace
.as_ref()
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
.unwrap_or(&project.root);
Ok(Scope {
cache: cache_at(&project.root, &project.build_cache_dir(), root),
settings: if root == &project.root {
project.settings.effective()
} else {
project.settings.for_project(root).effective()
},
root: root.clone(),
})
}
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
}
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
}
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
cache: cache_at(window_root, cache, &root),
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
+57 -62
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::load;
use super::build::{load, with_profiles, workspace};
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
let module = project.root.join(module);
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
project.java_launch_snapshots.lock().initialize();
let model = load(&project.root, &project.build_cache_dir(), &settings);
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
let prefer_maven = settings.languages.java.maven.delegate_build;
launches.snapshots.lock().initialize();
let root = &scope.root;
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(&project.root, &project.build_cache_dir(), &module),
cache::has_record(root, &scope.cache, &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, prefer_maven, is_maven)
(model, external, delegated, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
// The modules of the launches sharing this build also share its classpath probe.
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
let outputs = launches.snapshots.lock().build(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
);
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
Ok(_) => {}
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load(&root, &cache, &settings);
let model = load_launch_model(&scope);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
let build_ms = started.elapsed().as_millis();
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let project = project.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
Some(server) => {
info.project_root = server.classpath.project_root;
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
let is_maven = model
.maven
.as_ref()
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
if !is_maven {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let classpath = compile::module_classpath(
&project.root,
&model,
&module,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
)?;
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -445,10 +440,10 @@ fn apply_library_classpath(
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
async fn build_members(
project: &std::sync::Arc<crate::Project>,
scope: &std::sync::Arc<workspace::Scope>,
model: &std::sync::Arc<BuildModel>,
module: &Path,
test: bool,
prefer_maven: bool,
waiting: &cache::WaitingGuard,
cancel: &CancellationToken,
) -> IdeResult<Vec<cache::Member>> {
@@ -456,10 +451,11 @@ async fn build_members(
if others.is_empty() {
return Ok(Vec::new());
}
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let joining = {
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -500,8 +496,7 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
let is_maven = is_maven_module(root, model, &o.module);
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
+24
View File
@@ -64,6 +64,30 @@ pub(super) struct Member {
pub rebuild_on_jdt_errors: bool,
}
/// Launches share a build only within the same workspace project's cache.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
pub(in crate::ops) struct Launches {
pub waiting: Waiting,
pub snapshots: Mutex<Session>,
}
impl Sessions {
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
self.0
.lock()
.entry(cache.to_owned())
.or_insert_with(|| {
Arc::new(Launches {
waiting: Waiting::default(),
snapshots: Mutex::new(Session::new(cache.to_owned())),
})
})
.clone()
}
}
/// Java launches from their start until their build: one launch's Maven run also builds
/// the modules of launches still waiting (configurations started together, #3971).
#[derive(Default)]
+4 -1
View File
@@ -242,7 +242,10 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
if jvm && member.is_some() && config.cwd.is_none() {
config.cwd = Some(owner.into());
} else if config.extras.module.is_none() && !jvm {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
+4 -12
View File
@@ -51,10 +51,8 @@ pub struct Project {
pub(crate) member_excludes: MemberExcludes,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Superseded launch snapshots retained until this project session ends.
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
/// Java launches waiting for their build, which can share one Maven run.
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
/// Pending launches and retained snapshots, scoped to each workspace project.
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Database tool window: data sources and their connections.
@@ -641,10 +639,7 @@ impl Host {
detected_roots,
member_excludes,
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
@@ -891,10 +886,7 @@ impl Host {
detected_roots: Arc::default(),
member_excludes: Arc::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
+101
View File
@@ -6,6 +6,107 @@ use std::{
time::Duration,
};
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn java_launch_builds_the_owning_workspace_reactor() {
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::{fs, os::unix::fs::PermissionsExt};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let config_dir = base.join("config");
let primary = base.join("primary");
let sibling = base.join("spring");
let nested = primary.join("nested");
let roots = [&primary, &sibling, &nested];
for (i, root) in roots.into_iter().enumerate() {
fs::create_dir_all(root.join("app")).unwrap();
fs::write(
root.join("pom.xml"),
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
)
.unwrap();
let wrapper = root.join("mvnw");
fs::write(
&wrapper,
r#"#!/bin/sh
set -eu
printf '%s\n' "$*" >> calls
mkdir -p app/target/classes
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
scope=runtime
for arg in "$@"; do
case "$arg" in
-Dmdep.includeScope=*) scope="${arg#*=}";;
esac
done
for arg in "$@"; do
case "$arg" in
-Dmdep.outputFile=*)
touch "app/$scope.jar"
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
esac
done
"#,
)
.unwrap();
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
SettingsStore::load(&config_dir, Some(root))
.set(
SettingsScope::Project,
"languages.java.maven.activeProfiles",
serde_json::json!(format!("member-{i}")),
)
.unwrap();
}
// Exercise the build-tool classpath fallback without starting an installed server.
let global = SettingsStore::load(&config_dir, None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(HostConfig {
config_dir,
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
for root in roots {
host.trust.decide(root, true, false).unwrap();
}
host.open_project("main", &primary).unwrap();
for root in [&sibling, &nested] {
ops::project::attach_workspace(&host, "main", root).unwrap();
}
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
let temp = tempfile::tempdir().unwrap();
+6 -8
View File
@@ -8,6 +8,7 @@
use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::ErrorKind;
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -646,10 +647,8 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
/// Open editors may have cached empty tokens or inheritance results during the import.
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,10 +665,9 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+9 -7
View File
@@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_semantic_tokens() {
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
@@ -3175,20 +3175,22 @@ async fn a_project_update_refreshes_java_semantic_tokens() {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
assert!(refreshes().is_empty());
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
// A later import may add tokens and implementation targets to open editors.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
}
#[tokio::test(flavor = "multi_thread")]
+57
View File
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
}
}
}
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
await prepare(page, true, false);
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
const scroller = page.locator(".cm-scroller").filter({ has: box });
const overflow = () =>
scroller.evaluate((el) => ({
x: el.scrollWidth - el.clientWidth,
y: el.scrollHeight - el.clientHeight,
}));
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Reply with OK.");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Start", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState({
entries: new Map([
[
id,
[
{ type: "user", text: "Reply with OK.", attachments: [] },
{ type: "agent", text: "OK" },
],
],
]),
});
}, task.id);
await expect(page.getByText("OK", { exact: true })).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect(scroller).toHaveCSS("overflow-x", "hidden");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Short draft");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("word".repeat(2000));
await expect(scroller).toHaveCSS("overflow-y", "auto");
await expect
.poll(async () => {
const { x, y } = await overflow();
return x === 0 && y > 0;
})
.toBe(true);
await box.fill("");
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
});
+39
View File
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
for (const mode of ["Preview Only", "Editor and Preview"]) {
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
const path = "/dev/acme-api/linked-heading.md";
const heading = "5.2 状态机";
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
const editor = await openFromTree(page, "README.md");
await page.evaluate(
async ({ path, target }) => {
const backendModule = "/src/editor/core/backend.ts";
const routeModule = "/src/platform/tauriCore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
docBackend().files.set(path, target);
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
);
},
{ path, target },
);
await editor.locator(".cm-content").focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(destinationTab).toHaveCount(0);
await preview.getByRole("link", { name: "Linked heading" }).click();
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
if (mode === "Editor and Preview") {
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
}
});
}
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
+9
View File
@@ -37,6 +37,15 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
});
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
await page.setViewportSize({ width: 720, height: 480 });
const menu = page.getByRole("menu", { name: "Context menu" });
+2
View File
@@ -9197,6 +9197,8 @@ export type LogcatLine = {
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" |
/** An import or classpath update may have changed inheritance search results. */
"inheritance" |
/** The Dart server published a document's Flutter outline. */
"flutterOutline";
+82
View File
@@ -0,0 +1,82 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
let view: EditorView;
afterEach(() => view.destroy());
function expand(snippet: string) {
view = new EditorView({
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
parent: document.body,
});
applySnippet(view, [{ from: 0, to: 0, snippet }]);
}
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
const doc = () => view.state.doc.toString();
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
describe("linked snippets", () => {
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
expect(selected()).toEqual(["x"]);
expect(view.state.selection.main.from).toBe(0);
type("name");
expect(doc()).toBe("name/name y/y");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["y"]);
expect(view.state.selection.main.from).toBe("name/name ".length);
type("label");
expect(doc()).toBe("name/name label/label");
});
it("tracks adjacent empty occurrences and the next variable independently", () => {
expand("${1}${1}${2:end}${0}");
expect(selected()).toEqual([""]);
type("x");
type("y");
expect(doc()).toBe("xyxyend");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["end"]);
type("!");
expect(doc()).toBe("xyxy!");
});
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
expand("${1:x}/${1:x}${0}");
if (key === "Escape") {
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
}
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
const { head } = view.state.selection.main;
expect(head).toBe(key === "Escape" ? 1 : doc().length);
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
expect(doc()).toBe("changed/x");
});
it("keeps a repeated last placeholder active until the end of the snippet", () => {
expand("${1:one} ${2:two}/${2:two}");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["two"]);
type("new");
expect(doc()).toBe("one new/new");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
it("keeps fields linked after a separate edit before the snippet", () => {
expand("call(${1:arg}, ${1:arg})${0}");
const prefix = "import call;\n";
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
expect(selected()).toEqual(["arg"]);
type("value");
expect(doc()).toBe(prefix + "call(value, value)");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
});
+346
View File
@@ -0,0 +1,346 @@
import {
clearSnippet,
closeCompletion,
completionStatus,
pickedCompletion,
snippet,
type Completion,
} from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
ChangeSet,
EditorSelection,
EditorState,
MapMode,
Prec,
StateEffect,
StateField,
Text,
type ChangeSpec,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
import { isExternalChange } from "@/editor/api";
interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface SnippetRange {
from: number;
to: number;
field: number;
}
interface Segment extends SnippetRange {
site: number;
primary: boolean;
}
interface ActiveSnippet {
segments: readonly Segment[];
active: number;
last: number;
mainSite: number;
completion: boolean;
}
const setSnippet = StateEffect.define<ActiveSnippet | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
function primarySegments(value: ActiveSnippet, field = value.active) {
return value.segments.filter((segment) => segment.field === field && segment.primary);
}
function contains(range: SnippetRange, from: number, to: number): boolean {
return range.from <= from && to <= range.to;
}
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
const primaries = primarySegments(value);
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
}
const fields = StateField.define<ActiveSnippet | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((effect) => effect.is(setSnippet));
if (next) return next.value;
if (!value) return null;
if (tr.docChanged) {
const segments: Segment[] = [];
for (const segment of value.segments) {
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
segments.push({ ...segment, from, to });
}
value = { ...value, segments };
}
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
},
provide: (field) =>
EditorView.decorations.from(field, (value) =>
value
? Decoration.set(
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
true,
)
: Decoration.none,
),
});
// Keep the edit and its mirrors in one history entry.
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
const value = tr.startState.field(fields, false);
if (
!value ||
!tr.docChanged ||
isExternalChange(tr) ||
tr.isUserEvent("undo") ||
tr.isUserEvent("redo") ||
tr.effects.some((effect) => effect.is(setSnippet))
)
return tr;
const primaries = primarySegments(value);
const edited = new Map<Segment, number>();
let outside = false;
let touchesOtherSegment = false;
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
const segment = primaries.find((range) => contains(range, from, to));
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
else {
outside = true;
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
}
}, true);
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
const changes: ChangeSpec[] = [];
const replacements = new Map<number, Text>();
let typedOffset = 0;
let mirrorOffset = 0;
// Map in source order so neighboring stops keep their own boundaries even when they touch.
const segments = value.segments.map((segment) => {
const start = segment.from + typedOffset;
const from = start + mirrorOffset;
let length = segment.to - segment.from;
const delta = edited.get(segment);
if (delta !== undefined) {
length += delta;
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
typedOffset += delta;
} else if (segment.field === value.active && !segment.primary) {
const insert = replacements.get(segment.site);
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
changes.push({ from: start, to: start + length, insert });
mirrorOffset += insert.length - length;
length = insert.length;
}
}
return { ...segment, from, to: from + length };
});
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
const next = { ...value, segments };
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
});
function clearLinkedSnippet(view: EditorView): boolean {
if (!view.state.field(fields, false)) return false;
view.dispatch({ effects: setSnippet.of(null) });
return true;
}
export const escapeSnippet: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearLinkedSnippet(view) || clearSnippet(view);
};
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
return EditorSelection.create(
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
value.mainSite,
);
}
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
if (active < 0 || active > value.last) return false;
view.dispatch({
selection: fieldSelection(value, active),
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
const value = state.field(fields, false);
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
}
export const nextLiveSnippetField: Command = (view) => {
const value = view.state.field(fields, false);
return !!value && !value.completion && selectField(view, value, value.active + 1);
};
const linkedSnippetExtension = [
fields,
mirrorEdits,
Prec.highest(
keymap.of([
{
key: "Tab",
run: (view) => {
const value = view.state.field(fields);
return (
!!value &&
!view.state.readOnly &&
completionStatus(view.state) !== "active" &&
selectField(view, value, value.active + 1)
);
},
shift: (view) => {
const value = view.state.field(fields);
return !!value && selectField(view, value, value.active - 1);
},
},
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
]),
),
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const segment = value.segments.find((range) => contains(range, pos, pos));
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
},
}),
];
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
return tr.effects
.map(({ value }) => value)
.find((value) => {
return value && typeof value.active === "number" && Array.isArray(value.ranges);
});
}
export function snippetFieldMoved(tr: Transaction): number | undefined {
const linked = tr.effects.find((effect) => effect.is(setSnippet));
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
return codeMirrorSnippet(tr)?.active;
}
/** Render with CodeMirror to keep its snippet syntax and indentation. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
const state = EditorState.create({
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
selection: EditorSelection.cursor(to),
extensions: [indentUnit.of(source.facet(indentUnit))],
});
let insert = Text.empty;
let ranges: SnippetRange[] = [];
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
snippet(site.snippet + "#{}")(
{
state,
dispatch(tr) {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
},
},
null,
from,
to,
);
const end = ranges.at(-1);
const seen = new Set<number>();
const segments = ranges.slice(0, -1).map((range) => {
const primary = !seen.has(range.field);
seen.add(range.field);
return { ...range, primary };
});
return { ...site, offset: from, insert, segments, end };
}
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
const { state } = view;
const { main } = state.selection;
const entries = sites.map((site) =>
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
);
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
const { snippet: source, from, to } = sites[0]!;
clearLinkedSnippet(view);
snippet(source)(view, completion, from, to);
return;
}
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
const needsEnd = entries.some(({ segments }) =>
segments.some((segment) => segment.field === last && !segment.primary),
);
if (needsEnd) last++;
const segments = entries.flatMap((entry, site) => {
const offset = changes.mapPos(entry.from, -1) - entry.offset;
const ranges = [...entry.segments];
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
});
const value = {
segments,
active: 0,
last,
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
completion: !!completion,
};
clearSnippet(view);
view.dispatch({
changes,
selection: fieldSelection(value, 0),
effects: [
setSnippet.of(last > 0 ? value : null),
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
],
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
userEvent: completion ? "input.complete" : undefined,
scrollIntoView: true,
});
}
+41
View File
@@ -8,6 +8,7 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerTextEditorWrapper,
setProjectViewLead,
useProjectViewLead,
@@ -579,6 +580,46 @@ describe("EditorController", () => {
useProject.setState({ project: null, settings: null });
});
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
const dispose = registerActions(
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
id,
title: id,
run: () => undefined,
})),
);
const links = registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
});
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const s = useTabs.getState();
const pane = s.panes[s.activePane]!;
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
(i) => i.label === "Copy Path/Reference…",
)!.submenu!;
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"GitHub Link",
]);
} finally {
dispose();
links();
useProject.setState({ project: null, settings: null });
}
});
it.each(["editor", "tab"])(
"offers grouped Git actions in the %s menu and preserves action enablement",
async (menu) => {
+3
View File
@@ -2324,6 +2324,9 @@ export class EditorController implements SlotHost {
},
] as MenuItem[])
: []),
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
{ kind: "separator" },
...menuGroupItems("copyPath", { paths: [path] }),
],
},
{ kind: "separator" },
+17
View File
@@ -297,6 +297,23 @@ describe("applying completions", () => {
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("edits repeated LSP placeholders from one selection", () => {
const { view, req } = setup("lo|", "", [EditorState.allowMultipleSelections.of(true)]);
const completion = makeCompletion(
item({ kind: "snippet", insertText: "log(${1:value}, $1, ${2:label})$0", isSnippet: true }),
req,
);
apply(view, completion, 0);
expect(view.state.selection.ranges).toHaveLength(1);
expect(view.state.doc.toString()).toBe("log(value, value, label)");
view.dispatch(view.state.replaceSelection("name"));
expect(view.state.doc.toString()).toBe("log(name, name, label)");
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Enter" }), "editor")).toBe(false);
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
const { from, to } = view.state.selection.main;
expect(view.state.sliceDoc(from, to)).toBe("label");
});
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
const executed: string[] = [];
setInvokeRoute((cmd) => {
+3 -2
View File
@@ -16,7 +16,6 @@ import {
moveCompletionSelection,
pickedCompletion,
selectedCompletion,
snippet,
startCompletion,
type Completion,
type CompletionContext,
@@ -53,6 +52,7 @@ import {
typeColumnText,
withoutDuplicates,
} from "./completionItems";
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet";
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
@@ -296,7 +296,8 @@ export function applyLspCompletion(
start = tr.changes.mapPos(start, 1);
end = tr.changes.mapPos(end, 1);
}
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
// signature help says there is nothing to pass.
const head = view.state.selection.main.head;
+3 -1
View File
@@ -4,6 +4,7 @@
* it follows the caret and closes when the server reports no signature;
* ⇥ / ⇧⇥ move to the next / previous argument.
*/
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import {
@@ -289,7 +290,8 @@ function moveToArgument(view: EditorView, dir: 1 | -1): boolean {
if (!state.field(signatureField, false) || state.readOnly) return false;
if (state.selection.ranges.length > 1 || completionStatus(state) === "active") return false;
// Snippet / template fields and the in-place rename own ⇥.
if (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)) return false;
if (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
return false;
if (inplaceRenameActive(state)) return false;
const head = state.selection.main.head;
const to = argumentStop(state.doc.toString(), head, dir);
+8 -2
View File
@@ -193,11 +193,17 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
const hasField = nodes.some(
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
);
const defaults = new Map<number, string>();
for (const node of nodes) {
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
}
let out = "";
for (const n of nodes) {
if (n.t === "text") out += escapeText(n.v);
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
else {
const v = vars[n.name];
if (v !== undefined) out += escapeText(v);
+72 -35
View File
@@ -11,7 +11,7 @@
* of the file in batches; results are cached per document text, and markers
* follow their lines in between.
* The cache outlives the editor view (switching tabs remounts it) until other
* files change or a language server settles: on some servers (jdtls) every
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
* implementation search walks the whole workspace, so asking again is costly.
* Library sources ask no inheritors from the server (`isLibrarySource`).
*/
@@ -25,6 +25,7 @@ import { isNavigating, onNavigation } from "@/editor/lsp/foreground";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
import { openPopup } from "@/editor/lsp/popupStore";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
commands,
isCancelled,
@@ -118,11 +119,15 @@ function watchChanges() {
// documents: re-render them instead of waiting for an edit or a settling server.
for (const plugin of live) plugin.refreshSoon();
});
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
// Answers (outlines too) given while a server was starting or importing may be incomplete.
const refreshCaches = () => {
docMarkers.clear();
forgetInheritanceGraph();
for (const plugin of live) plugin.refreshSoon();
};
onServerSettled(refreshCaches);
onIdeEvent("lspRefresh", (e) => {
if (e.kind === "inheritance") refreshCaches();
});
// Go to Declaration and the like go first: in-flight marker requests are cancelled and
// asked again once the navigation is done.
@@ -542,13 +547,32 @@ async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Loc
}
}
/** Opens the single target, or the chooser over several. */
/** Resolves each declaration's targets before opening the shared chooser. */
export async function openMarkerTargets(
marker: LineMarker,
markers: readonly [LineMarker, ...LineMarker[]],
anchor: { x: number; y: number },
doc: DocId | null = null,
) {
const targets = await markerTargets(marker, doc);
const [first] = markers;
const merged = markers.length > 1;
let targets: DeclarationTarget[] = (
await Promise.all(
markers.map(async (marker) => {
const locations = await markerTargets(marker, doc);
// Generated methods can share a source location. Keep their names visible in the chooser.
return merged && marker.method ? locations.map((target) => ({ ...target, name: marker.name })) : locations;
}),
)
).flat();
if (merged) {
const seen = new Set<string>();
targets = targets.filter(({ path, range, name }) => {
const key = JSON.stringify([path, range.start.line, range.start.col, name]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
if (targets.length === 1) {
await navigateTo(targets[0]!);
return;
@@ -556,9 +580,9 @@ export async function openMarkerTargets(
openPopup({
kind: "list",
anchor,
title: marker.chooserTitle,
title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle,
items: await locationItems(targets),
pin: pinToFind(marker.name, targets),
pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets),
});
}
@@ -587,41 +611,50 @@ function place(doc: Text, markers: readonly LineMarker[]): PlacedMarker[] {
}
const sameMarkers = (a: readonly PlacedMarker[], b: readonly PlacedMarker[]) =>
a.length === b.length &&
a.every(
(m, i) => m.pos === b[i]!.pos && m.marker.kind === b[i]!.marker.kind && m.marker.tooltip === b[i]!.marker.tooltip,
);
a.length === b.length && a.every((m, i) => m.pos === b[i]!.pos && m.marker === b[i]!.marker);
class InheritanceMarker extends GutterMarker {
constructor(readonly marker: LineMarker) {
readonly kind: LineMarker["kind"];
readonly tooltip: string;
constructor(readonly markers: readonly [LineMarker, ...LineMarker[]]) {
super();
const [first] = markers;
this.kind = first.kind;
this.tooltip =
markers.length === 1 ? first.tooltip : [...new Set(markers.map((m) => `${m.name} — ${m.tooltip}`))].join("\n");
}
override eq(other: GutterMarker): boolean {
return (
other instanceof InheritanceMarker &&
other.marker.kind === this.marker.kind &&
other.marker.tooltip === this.marker.tooltip
);
return other instanceof InheritanceMarker && other.kind === this.kind && other.tooltip === this.tooltip;
}
override toDOM(): Node {
const el = document.createElement("div");
el.className = `${styles.marker} cm-openidea-lineMarker-${this.marker.kind}`;
el.dataset.kind = this.marker.kind;
el.title = this.marker.tooltip;
el.className = `${styles.marker} cm-openidea-lineMarker-${this.kind}`;
el.dataset.kind = this.kind;
el.title = this.tooltip;
el.setAttribute("role", "button");
el.setAttribute("aria-label", this.marker.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.marker.kind]) ?? "";
el.setAttribute("aria-label", this.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.kind]) ?? "";
return el;
}
}
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<GutterMarker>>();
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<InheritanceMarker>>();
function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
function markerSet(placed: readonly PlacedMarker[]): RangeSet<InheritanceMarker> {
let set = gutterMarkers.get(placed);
if (!set) {
const groups = new Map<string, { pos: number; markers: [LineMarker, ...LineMarker[]] }>();
for (const { pos, marker } of placed) {
const key = `${pos}:${marker.kind}`;
const group = groups.get(key);
if (group) group.markers.push(marker);
else groups.set(key, { pos, markers: [marker] });
}
set = RangeSet.of(
placed.map((m) => new InheritanceMarker(m.marker).range(m.pos)),
[...groups.values()].map(({ pos, markers }) => new InheritanceMarker(markers).range(pos)),
true,
);
gutterMarkers.set(placed, set);
@@ -829,10 +862,14 @@ export function markerDeps(
};
}
function markerAt(view: EditorView, lineFrom: number, el: Element | null): LineMarker | null {
const onLine = view.state.field(markersField).filter((m) => m.pos === lineFrom);
const kind = (el?.closest(`.${styles.marker}`) as HTMLElement | null)?.dataset.kind;
return (onLine.find((m) => m.marker.kind === kind) ?? (onLine.length === 1 ? onLine[0] : null))?.marker ?? null;
function markerAt(view: EditorView, lineFrom: number, kind: string | undefined): InheritanceMarker | undefined {
let match: InheritanceMarker | undefined;
markerSet(view.state.field(markersField)).between(lineFrom, lineFrom, (pos, _to, marker) => {
if (pos !== lineFrom || marker.kind !== kind) return;
match = marker;
return false;
});
return match;
}
export function implementationGutter(ctx: EditorDocContext): Extension {
@@ -846,13 +883,13 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
markers: (view) => markerSet(view.state.field(markersField)),
mousedown: (view, block, e) => {
if (e.button !== 0) return false;
const target = e.target instanceof Element ? e.target : null;
if (!target?.closest(`.${styles.marker}`)) return false;
const marker = markerAt(view, block.from, target);
const target = e.target instanceof Element ? e.target.closest<HTMLElement>(`.${styles.marker}`) : null;
if (!target) return false;
const marker = markerAt(view, block.from, target.dataset.kind);
if (!marker) return false;
e.preventDefault();
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
const rect = target.getBoundingClientRect();
void openMarkerTargets(marker.markers, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
return true;
},
}),
+202 -32
View File
@@ -1,27 +1,45 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import { lspDoc } from "@/editor/lsp/lsp";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
IpcError,
commands,
type ClassInheritance,
type HierarchyItem,
type IdeEvent,
type Location,
type OutlineItem,
type Pos,
type SymbolKind,
} from "@/platform/ipc";
import { setInvokeRoute } from "@/platform/tauriCore";
const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi.fn() }));
const ideListeners = vi.hoisted(() => new Map<string, Set<(event: IdeEvent) => void>>());
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
onIdeEvent: (type: string, listener: (event: IdeEvent) => void) => {
let listeners = ideListeners.get(type);
if (!listeners) ideListeners.set(type, (listeners = new Set()));
listeners.add(listener);
return () => listeners.delete(listener);
},
}));
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
locationItems: async (locs: Location[]) => locs.map((l, i) => ({ id: `${i}`, label: l.path, run: () => {} })),
locationItems: async (locs: DeclarationTarget[]) =>
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path, run: () => {} })),
}));
vi.mock("@/editor/lsp/popupStore", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/popupStore")>()),
openPopup: nav.openPopup,
}));
import { candidateKey, markerCandidates, type MarkerCandidate } from "./lineMarkers";
import { candidateKey, markerCandidates, type LineMarker, type MarkerCandidate } from "./lineMarkers";
import { Text } from "@codemirror/state";
import {
affectsMarkers,
@@ -29,6 +47,7 @@ import {
emptyCache,
enabledGroups,
fillMarkers,
implementationGutter,
libraryCandidates,
markerBatches,
markerDeps,
@@ -539,16 +558,18 @@ describe("clicking a marker", () => {
it("navigates to a single target", async () => {
const target = loc("/p/Circle.java", 0, 13);
await openMarkerTargets(
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
],
{ x: 1, y: 2 },
);
expect(nav.navigateTo).toHaveBeenCalledWith(target);
@@ -562,16 +583,18 @@ describe("clicking a marker", () => {
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
await openMarkerTargets(
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
[
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
],
{ x: 1, y: 2 },
7,
);
@@ -585,16 +608,18 @@ describe("clicking a marker", () => {
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
expect(candidateKey(candidate())).toBe("0:17:Shape");
await openMarkerTargets(
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
],
{ x: 1, y: 2 },
);
expect(nav.navigateTo).not.toHaveBeenCalled();
@@ -609,6 +634,151 @@ describe("clicking a marker", () => {
});
});
describe("inheritance gutter", () => {
it.each([
{ type: "interface", source: SHAPE, outline: SHAPE_OUTLINE },
{ type: "abstract class", source: BASE, outline: BASE_OUTLINE },
])(
"refreshes implementation and override markers when a Java project update finishes ($type)",
async ({ source, outline }) => {
vi.useFakeTimers();
let indexed = false;
const target = "/p/service/target/generated-sources/example/ServiceImpl.java";
const queries = vi.fn<MarkerDeps["implementations"]>(async (positions) =>
positions.map(({ line }) => (indexed ? [loc(target, line + 2)] : [])),
);
setInvokeRoute(async (command, args) => {
if (command === "doc_outline") return outline;
if (command === "lsp_type_hierarchy") {
throw { kind: "unavailable", message: "no type hierarchy", data: null };
}
if (command === "lsp_implementations") return queries((args as { positions: Pos[] }).positions);
return null;
});
const ctx = { doc: 12, path: `/p/api/${outline[0]!.name}.java`, language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
doc: Text.of(source),
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
const kinds = () =>
[...view.dom.querySelectorAll<HTMLElement>('[class*="cm-openidea-lineMarker-"]')].map((el) => el.dataset.kind);
const emit = (event: IdeEvent) => {
for (const listener of ideListeners.get(event.type) ?? []) listener(event);
};
try {
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
expect(kinds()).toEqual([]);
indexed = true;
emit({ type: "lspRefresh", server: 1, kind: "semanticTokens" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
emit({ type: "lspRefresh", server: 1, kind: "inheritance" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(2);
expect(kinds()).toEqual(["implemented", "implemented", "overridden"]);
} finally {
view.destroy();
setInvokeRoute(null);
vi.useRealTimers();
}
},
);
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
{ kind: "implementing", language: "go", declaration: "type Square struct{}" },
{ kind: "implemented", language: "rust", declaration: "trait Shape { fn area(); fn label(); }" },
] as const)("merges $language $kind markers by line and kind", async ({ kind, language, declaration }) => {
vi.useFakeTimers();
nav.navigateTo.mockClear();
nav.openPopup.mockClear();
const ctx = { doc: 1, path: `/p/gutter-${kind}`, language, uiMode: null, readOnly: false };
const doc = Text.of([declaration, "another declaration"]);
const markers = markersOf(ctx.path, doc);
const otherKind = kind === "overridden" ? "overriding" : "overridden";
const inputs = [
{ kind, name: "build", line: 0 },
{ kind: otherKind, name: "other", line: 0 },
{ kind, name: "self", line: 0 },
{ kind, name: "build", line: 0 },
{ kind, name: "later", line: 1 },
] as const;
const candidates = inputs.map(({ name, line }, i): MarkerCandidate => ({
name,
line,
symbol: `${name}(${i})`,
col: 0,
method: true,
abstract: false,
inheritable: false,
overriding: false,
owner: null,
}));
markers.outline = { items: [], candidates };
inputs.forEach((input, i) => {
const marker: LineMarker = {
...input,
col: 0,
method: true,
targets: [
loc(
language === "java" && input.kind === kind && input.line === 0 ? "/p/BaseOrder.java" : `/p/${input.name}`,
2,
),
],
tooltip: `Target for ${input.name}`,
chooserTitle: input.name,
};
const group = marker.kind === "implemented" || marker.kind === "overridden" ? "inheritors" : "supers";
markers.cache.entries.set(candidateKey(candidates[i]!), { [group]: marker });
});
const view = new EditorView({
doc,
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
try {
await vi.advanceTimersByTimeAsync(500);
const icons = [...view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`)];
expect(icons).toHaveLength(2);
expect(icons[0]!.title).toContain("Target for build");
expect(icons[0]!.title).toContain("Target for self");
expect(icons[0]!.title).not.toContain("Target for later");
expect(icons[0]!.parentElement!.querySelector(`.cm-openidea-lineMarker-${otherKind}`)).not.toBeNull();
fireEvent.mouseDown(icons[0]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).not.toHaveBeenCalled();
expect(nav.openPopup.mock.calls[0]![0].items.map((item: { label: string }) => item.label)).toEqual([
"build",
"self",
]);
// CodeMirror finds the clicked line by the gutter row's screen position.
const block = view.lineBlockAt(doc.line(2).from);
vi.spyOn(icons[1]!.parentElement!, "getBoundingClientRect").mockReturnValue(
new DOMRect(0, view.documentTop + block.top, 10, block.height),
);
fireEvent.mouseDown(icons[1]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).toHaveBeenCalledWith(loc("/p/later", 2));
view.dispatch({ changes: { from: doc.line(1).to, to: doc.line(2).from, insert: " " } });
const joined = view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`);
expect(joined).toHaveLength(1);
expect(joined[0]!.title).toContain("Target for later");
} finally {
view.destroy();
vi.useRealTimers();
}
});
});
describe("overriders of a type's methods from its subtypes", () => {
// Shapes and names as jdtls answers them (outline names carry the signature).
const REPO = [
+2
View File
@@ -36,7 +36,9 @@
outline: none;
}
.field :global(.cm-scroller) {
height: auto;
max-height: 280px;
overflow-x: hidden;
overflow-y: auto;
font-family: inherit;
line-height: 1.5;
+1 -1
View File
@@ -140,7 +140,6 @@ export async function javaLaunchConfig(
root: string,
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
const cwd = rc.cwd ? join(root, rc.cwd) : root;
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
@@ -155,6 +154,7 @@ export async function javaLaunchConfig(
},
},
);
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
group: "run",
+72 -20
View File
@@ -17,14 +17,40 @@ import {
isLibraryPath,
registerEditorContribution,
setLibraryRoots,
useEditorRegistry,
} from "@/editor/api";
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { libraryArchiveRoot } from "@/platform/virtualDocs";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import { goModNavigationExtension } from "./goModNavigation";
export const EXTERNAL_LIBRARIES_LABEL = "External Libraries";
/** A jdtls URI's `maven.*` attributes, as the group label used by build dependencies. */
function archiveGroupName(uri: string, fallback: string): string {
let query = uri.split("?")[1] ?? "";
try {
query = decodeURIComponent(query);
} catch {
return fallback;
}
const field = (name: string) => new RegExp(`maven\\.${name}=/([^=]+)=`).exec(query)?.[1];
const [group, artifact, version] = [field("groupId"), field("artifactId"), field("version")];
if (!group || !artifact || !version) return fallback;
const classifier = field("classifier");
return `Maven: ${group}:${artifact}:${version}${classifier ? `:${classifier}` : ""}`;
}
/** A class opened from a jar the build model has not listed yet; show its exact archive. */
export function openedLibraryGroup(uri: string, groups: readonly LibraryGroup[]): LibraryGroup | null {
const archive = libraryArchiveRoot(uri);
if (!archive || groups.some((group) => group.roots.some((root) => root.path === archive))) return null;
const separator = Math.max(archive.lastIndexOf("/"), archive.lastIndexOf("\\"));
const name = archive.slice(separator + 1, -1) || archive;
return { name: archiveGroupName(uri, name), kind: "classpath", roots: [{ name, path: archive }] };
}
const GROUP_ICONS: Record<string, string> = {
python: "file-python",
jdk: "file-java",
@@ -174,6 +200,10 @@ export function activate(): () => void {
let shown = "";
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
/** The last build/SDK result, before archives opened from the editor are added. */
let backendGroups: LibraryGroup[] = [];
/** One group per opened archive, so the build model can replace each archive independently. */
let openedGroups: LibraryGroup[] = [];
let request: RequestId | undefined;
/** The project whose libraries are shown (and `settled`). */
let shownFor: string | null = null;
@@ -184,8 +214,36 @@ export function activate(): () => void {
shown = "";
shownGroups = [];
settled = [];
backendGroups = [];
openedGroups = [];
shownFor = null;
};
const render = (groups: LibraryGroup[]) => {
backendGroups = groups;
const covered = new Set(groups.flatMap((g) => g.roots.map((r) => r.path)));
openedGroups = openedGroups.filter((g) => !g.roots.some((r) => covered.has(r.path)));
const all = mergeLibraryGroups([...groups, ...openedGroups]);
const key = JSON.stringify(all);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(all) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = all;
const root = librariesRoot(all);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
all.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
};
const refresh = () => {
const id = ++seq;
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
@@ -200,26 +258,7 @@ export function activate(): () => void {
let collected: LibraryGroup[] = [];
const show = (groups: LibraryGroup[]) => {
if (id !== seq) return;
const key = JSON.stringify(groups);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(groups) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = groups;
const root = librariesRoot(groups);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
groups.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
render(groups);
};
const channel = new Channel<LibraryGroup[]>();
channel.onmessage = (groups) => {
@@ -242,6 +281,13 @@ export function activate(): () => void {
});
};
refresh();
const showOpenedLibrary = (path: string | null) => {
if (!path || !shownFor) return;
const group = openedLibraryGroup(path, shownGroups);
if (!group) return;
openedGroups.push(group);
render(backendGroups);
};
const disposeGoMod = registerEditorContribution({
id: "libraries.goModNavigation",
extensions: goModNavigationExtension((path, version) => goModuleRoot(shownGroups, path, version), isLibraryPath),
@@ -252,6 +298,11 @@ export function activate(): () => void {
const unsub = useProject.subscribe((s, prev) => {
if (sdkKey(s) !== sdkKey(prev)) refresh();
});
const unsubEditor = useEditorRegistry.subscribe((s, prev) => {
const path = s.active?.ctx.path ?? null;
if (path !== (prev.active?.ctx.path ?? null)) showOpenedLibrary(path);
});
showOpenedLibrary(useEditorRegistry.getState().active?.ctx.path ?? null);
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubFs = onIdeEvent("fsChanged", (e) => {
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
@@ -268,6 +319,7 @@ export function activate(): () => void {
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
clearTimeout(timer);
unsub();
unsubEditor();
unsubFs();
unsubRoots();
disposeActions();
+22 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
import { librariesRoot, touchesManifest } from "./index";
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
import { mergeLibraryGroups } from "@/platform/libraries";
describe("External Libraries", () => {
@@ -116,6 +116,27 @@ describe("External Libraries", () => {
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
});
it("adds the classifier jar opened from a library class when the build model omits it", () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.groupId=/com.example=/=/maven.artifactId=/demo-lib=/=/maven.version=/1.0=/=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
expect(openedLibraryGroup(uri, [])).toEqual({
name: "Maven: com.example:demo-lib:1.0:jdk21",
kind: "classpath",
roots: [
{
name: "demo-lib-1.0-jdk21.jar",
path: "/m2/com/example/demo-lib/1.0/demo-lib-1.0-jdk21.jar!",
},
],
});
});
it("does not duplicate an archive the build model already lists", () => {
const uri = "jdt://contents/a.jar/p/C.class?=demo/%5C/m2%5C/a.jar%3Cp%28C.class";
const group = { name: "a.jar", kind: "maven", roots: [{ name: "a.jar", path: "/m2/a.jar!" }] };
expect(openedLibraryGroup(uri, [group])).toBeNull();
});
it("refreshes on manifest changes outside node_modules", () => {
expect(touchesManifest(["/p/src/main.rs", "/p/Cargo.toml"])).toBe(true);
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
+59 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LibraryGroup } from "@/bindings";
const results: LibraryGroup[][] = [];
@@ -31,6 +31,7 @@ vi.mock("@/platform/ipc", () => ({
}));
const { activate } = await import("./index");
const { useEditorRegistry } = await import("@/editor/api");
const { useProject } = await import("@/platform/project");
const { useProjectViewRoots } = await import("@/workbench/contributions");
const { executeAction } = await import("@/platform/actions");
@@ -42,6 +43,13 @@ const rust = (version: string): LibraryGroup => ({
});
describe("External Libraries refresh", () => {
afterEach(() => {
results.length = 0;
streamed.length = 0;
hang = false;
useEditorRegistry.setState({ active: null });
});
it("replaces the node in place when the libraries change", async () => {
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
@@ -86,4 +94,54 @@ describe("External Libraries refresh", () => {
dispose();
}
});
it("keeps other opened archives with the same name when the build lists one of them", async () => {
const first = "/first/library.jar!";
const second = "/second/library.jar!";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
const dispose = activate();
const paths = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.flatMap((group) => group.children?.map((root) => root.path) ?? [])
.sort();
try {
for (const archive of [first, second]) {
useEditorRegistry.setState({ active: { ctx: { path: `jar:file://${archive}/p/Example.class` } } as never });
}
await vi.waitFor(() => expect(paths()).toEqual([first, second]));
results.push([{ name: "Build dependency", kind: "gradle", roots: [{ name: "library.jar", path: first }] }]);
await executeAction("libraries.reload");
await vi.waitFor(() =>
expect(useProjectViewRoots.getState().roots.get("externalLibraries")?.children?.[0]?.label).toBe(
"Build dependency",
),
);
expect(paths()).toEqual([first, second]);
} finally {
dispose();
}
});
it("shows the exact classifier jar of the library class opened in the editor", async () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
useEditorRegistry.setState({ active: { ctx: { path: uri } } as never });
results.push([]);
const dispose = activate();
const labels = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.[0]?.children?.map((g) => g.label);
await vi.waitFor(() => expect(labels()).toContain("demo-lib-1.0-jdk21.jar"));
dispose();
});
});
+36 -13
View File
@@ -2,7 +2,17 @@ import { shortcutLabel } from "@/platform/keymap";
import { IconButton, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
import { userScopes } from "@/platform/scopes";
import { VIEW_MODES, setScopeView, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
import { useEditorPrefs } from "@/platform/editorSettings";
import {
VIEW_MODES,
previewTabEnabled,
setPreviewTabEnabled,
setScopeView,
setViewMode,
setViewOption,
useProjectTree,
type ViewOptions,
} from "./store";
import type { SortKey } from "./model";
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
@@ -35,9 +45,22 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
}
/** The on / off view options. */
export type ToggleOption = {
type ViewToggle = {
[K in keyof ViewOptions]-?: ViewOptions[K] extends boolean ? K : never;
}[keyof ViewOptions];
/** The view's switches, plus the editor's preview tab setting it shares (as in IDEA). */
export type ToggleOption = ViewToggle | "previewTab";
const toggleState = (key: ToggleOption, options: ViewOptions, preview: boolean) =>
key === "previewTab" ? preview : options[key];
export const isToggled = (key: ToggleOption) =>
toggleState(key, useProjectTree.getState().options, previewTabEnabled());
export function flipToggle(key: ToggleOption) {
if (key === "previewTab") void setPreviewTabEnabled(!previewTabEnabled());
else setViewOption(key, !useProjectTree.getState().options[key]);
}
const APPEARANCE_OPTIONS: Array<[ToggleOption, string]> = [
["showHidden", "Show Hidden Files"],
@@ -90,22 +113,26 @@ export const SORT_LABELS: Array<[key: SortKey, actionLabel: string, menuLabel: s
/** Project view options in the header's "⋮" menu. */
export function useProjectHeaderMenu(): MenuItem[] {
const options = useProjectTree((s) => s.options);
const preview = useEditorPrefs().tabs.previewTab;
const option = (key: ToggleOption, label: string): MenuItem => ({
id: key,
label,
checked: toggleState(key, options, preview),
run: () => flipToggle(key),
});
const unity = useProjectTree((s) => s.mode === "unity");
return [
{
label: "Behavior",
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label, options)),
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label)),
},
{
label: "Appearance",
submenu: [
...(unity
? [
option("showUnityMeta", "Show Meta Files", options),
option("showUnityGenerated", "Show Generated Files", options),
]
? [option("showUnityMeta", "Show Meta Files"), option("showUnityGenerated", "Show Generated Files")]
: []),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label, options)),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label)),
],
},
{
@@ -118,12 +145,8 @@ export function useProjectHeaderMenu(): MenuItem[] {
run: () => setViewOption("sortBy", sortBy),
})),
{ kind: "separator" },
option(...FOLDERS_FIRST, options),
option(...FOLDERS_FIRST),
],
},
];
}
function option(key: ToggleOption, label: string, options: ViewOptions): MenuItem {
return { id: key, label, checked: options[key], run: () => setViewOption(key, !options[key]) };
}
+51 -14
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { installRepeatedDoubleClick } from "@/platform/doubleClick";
import { getContext, setContext } from "@/platform/context";
@@ -22,13 +22,17 @@ import { beginNew, canPaste } from "./operations";
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
import type { OutlineItem } from "@/bindings";
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
import { ProjectHeaderActions } from "./HeaderActions";
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { loadOutline } from "./store";
const ipc = vi.hoisted(() => ({
docOpen: vi.fn(),
docClose: vi.fn(),
docOutline: vi.fn(),
settingsSet: vi.fn(),
}));
vi.mock("@/bindings", async (orig) => {
const real = await orig<typeof import("@/bindings")>();
@@ -58,6 +62,11 @@ const deferred = <T,>() => {
};
const ROOT = "/w/acme";
const initialSettings = useProject.getState().settings;
/** Settings › Editor › General › Editor Tabs › Enable preview tab. */
const previewTabSettings = (on: boolean) => ({ editor: { tabs: { previewTab: on } } });
const setPreviewTabSetting = (on: boolean) => act(() => useProject.setState({ settings: previewTabSettings(on) }));
let fs: MemoryFs;
let openFile: ReturnType<typeof vi.fn>;
let dispose: () => void;
@@ -98,6 +107,7 @@ beforeEach(() => {
afterEach(() => {
dispose();
useProject.setState({ settings: initialSettings });
setProjectFsForTests(null);
uninstallDispatcher?.();
uninstallDispatcher = null;
@@ -293,21 +303,48 @@ describe("ProjectView", () => {
}
});
it("opens files on double click and previews on single click only when enabled", async () => {
it("opens files on double click and previews on single click while the editor's preview tab is on", 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).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
act(() => setViewOption("previewTab", true));
// Settings › Editor › General › Editor Tabs › Enable preview tab is on by default.
fireEvent.click(content, { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
openFile.mockClear();
fireEvent.click(content, { detail: 3 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", false));
setPreviewTabSetting(false);
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
});
it("toggles the editor's preview tab setting from the Behavior menu and its action", async () => {
ipc.settingsSet.mockImplementation(async (_scope: string, _key: string, value: string) =>
ok(previewTabSettings(JSON.parse(value) as boolean)),
);
const { result } = renderHook(() => useProjectHeaderMenu());
type Item = Extract<MenuItem, { id?: string }>;
const behavior = () => (result.current[0] as Item).submenu as Item[];
const item = () => behavior().find((i) => i.id === "previewTab")!;
expect(item().checked).toBe(true);
act(() => item().run!());
await waitFor(() => expect(item().checked).toBe(false));
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.tabs.previewTab", "false");
const action = getAction("project.option.previewTab")!;
expect(action.toggled!()).toBe(false);
act(() => void executeAction(action.id));
await waitFor(() => expect(item().checked).toBe(true));
});
it("drops the former view-only preview tab option from saved view options", () => {
localStorage.setItem("openidea.projectTree.options", JSON.stringify({ previewTab: true, singleClickOpen: true }));
vi.resetModules();
return import("./store").then(({ useProjectTree: fresh }) => {
expect(fresh.getState().options).not.toHaveProperty("previewTab");
expect(fresh.getState().options.singleClickOpen).toBe(true);
});
});
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
@@ -737,17 +774,17 @@ describe("Show Members", () => {
},
);
it("autoscrolls to source without handing files to another application", async () => {
it.each([true, false])("autoscrolls to source with preview tabs set to %s", async (preview) => {
const { rows, row } = setup();
setPreviewTabSetting(preview);
act(() => {
setViewOption("autoscrollToSource", true);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
});
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview, focus: false, external: false }),
);
});
@@ -760,14 +797,14 @@ describe("Show Members", () => {
setViewOption("showMembers", true);
setViewOption("autoscrollToSource", false);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
useProject.setState({ settings: previewTabSettings(false) });
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(rows()).toContain("main"));
const content = () => row("main").querySelector("[data-project-key]")!;
fireEvent.click(content(), { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", true));
setPreviewTabSetting(true);
fireEvent.click(content(), { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith(
APP,
+5 -7
View File
@@ -91,6 +91,7 @@ import {
explainHiddenPath,
loadDir,
loadOutline,
previewTabEnabled,
revealPath,
selectModel,
setDropTarget,
@@ -584,13 +585,10 @@ export function ProjectView() {
setSelection(next, lead?.key ?? null);
const { options: o } = useProjectTree.getState();
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
const opts = { preview: previewTabEnabled(), focus: false, external: false };
if (lead.member) {
void revealRange(
lead.path,
{ start: lead.member.selection_range.start },
{ preview: o.previewTab, focus: false, external: false },
);
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
} else void openFile(lead.path, opts);
}, []);
const onActivate = useCallback((node: ProjectNode) => {
@@ -633,7 +631,7 @@ export function ProjectView() {
if (o.singleClickExpand) toggleExpanded(node);
return;
}
if (!o.singleClickOpen && !o.previewTab) return;
if (!o.singleClickOpen && !previewTabEnabled()) return;
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
else void openFile(node.path, opts);
+3 -3
View File
@@ -6,7 +6,7 @@ import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fil
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
import { OPTION_LABELS, SORT_LABELS } from "./HeaderActions";
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
import { openNewPopup } from "./newPopupModel";
import type { ProjectNode } from "./model";
@@ -191,8 +191,8 @@ export function registerProjectActions(): () => void {
category: "View",
// IDEA's former name of Always Select Opened File.
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
toggled: () => useProjectTree.getState().options[key],
run: () => setViewOption(key, !useProjectTree.getState().options[key]),
toggled: () => isToggled(key),
run: () => flipToggle(key),
}));
const modes: Action[] = VIEW_MODES.map(([mode, label]) => ({
@@ -145,6 +145,22 @@ describe("project view context menu", () => {
]);
});
it("lists contributed links in Copy Path/Reference… of library files too", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
}),
);
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"-",
"Link /root/.m2/lib.jar",
]);
});
it("groups clipboard, search, file changes, formatting and history actions for a file", () => {
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
expect(labels(items)).toEqual([
+2
View File
@@ -512,6 +512,8 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
run: () => void copyPaths("absolute", nodes),
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
{ kind: "separator" },
+20 -4
View File
@@ -13,6 +13,8 @@ import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx, txPart } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -57,8 +59,6 @@ export interface ViewOptions extends TreeOptions {
singleClickOpen: boolean;
/** Single click on a folder row expands / collapses it. */
singleClickExpand: boolean;
/** Single click shows files in the preview tab (IDEA's "Enable Preview Tab"). */
previewTab: boolean;
/** Show a file's declarations as expandable rows below it. */
showMembers: boolean;
/** Show the location of each project root beside its name. */
@@ -73,8 +73,6 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
autoscrollToSource: false,
singleClickOpen: false,
singleClickExpand: false,
// IDEA's "Enable Preview Tab" is off by default.
previewTab: false,
showMembers: false,
showRootPaths: true,
horizontalScroll: true,
@@ -82,6 +80,8 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
function storedOptions(): ViewOptions {
const options = { ...DEFAULT_VIEW_OPTIONS, ...readJson<Partial<ViewOptions>>(OPTIONS_KEY) };
// Former view-only switch, now the editor's preview tab setting (`previewTabEnabled`).
delete (options as { previewTab?: unknown }).previewTab;
if (!["name", "type", "modified"].includes(options.sortBy)) options.sortBy = "name";
return options;
}
@@ -502,6 +502,22 @@ export function setViewOption<K extends keyof ViewOptions>(key: K, value: ViewOp
writeJson(OPTIONS_KEY, options);
}
/** Single click shows files in the preview tab: IDEA's "Enable Preview Tab" is the editor's own setting. */
export const previewTabEnabled = () => editorPrefs().tabs.previewTab;
export async function setPreviewTabEnabled(on: boolean): Promise<void> {
try {
const settings = await call(commands.settingsSet("global", "editor.tabs.previewTab", JSON.stringify(on)));
useProject.setState({ settings });
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
}
// ---------------------------------------------------------------------------
// Loading
+49 -2
View File
@@ -3,8 +3,8 @@ import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems, projectContext } from "./contextRun";
import { OPTIMISTIC, produceContext, produceContextChoices, type ToolEnv } from "./producers";
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
import { useRun } from "./store";
import type { RunTarget } from "./targets";
@@ -115,6 +115,53 @@ describe("run context menu group", () => {
expect(contextMenuItems("projectView", { paths: [`${ROOT}/src/components`], dirs: [true] })).toEqual([]);
});
it("routes an attached Spring Boot main and its tests through the member's Maven build", () => {
const member = "/work/spring";
const project = useProject.getState().project!;
useProject.setState({ project: { ...project, workspace: { version: 1, name: "app", projects: [ROOT, member] } } });
const maven: RunConfig = { ...npmTest, kind: "maven", command: "mvn", args: ["test"], debugAdapter: null };
useRun.setState({
configs: [
{ ...maven, id: "maven:test" },
{ ...maven, id: "member:test", cwd: member },
],
});
const content = [
"package demo;",
"import org.springframework.boot.SpringApplication;",
"import org.springframework.boot.autoconfigure.SpringBootApplication;",
"@SpringBootApplication",
"public class App {",
" public static void main(String[] args) { SpringApplication.run(App.class, args); }",
"}",
].join("\n");
const main = { ...projectContext(), path: `${member}/src/main/java/demo/App.java`, content, line: 5 };
expect(produceContext(main, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: member,
args: ["-cp", "${classpath}", "demo.App"],
});
expect(
produceContext(
{
...main,
path: `${member}/src/test/java/demo/AppTest.java`,
content: "package demo;\nclass AppTest {\n @Test\n void starts() {}\n}",
line: 3,
},
OPTIMISTIC,
)?.config,
).toMatchObject({
kind: "maven",
cwd: member,
args: ["test", "-Dtest=demo.AppTest#starts", "-Dsurefire.failIfNoSpecifiedTests=false"],
});
expect(produceContext({ ...main, path: `${ROOT}/src/main/java/demo/App.java` }, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: "",
});
});
it("shows nothing when no producer matches or for several paths", () => {
expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]);
expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual(
+4 -3
View File
@@ -50,15 +50,16 @@ async function ensureConfigs() {
}
/** The focused editor's file, text and caret line. */
/** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */
/** Attached projects, Project Structure content roots and external Gradle modules. */
export function projectContentRoots(): string[] {
const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure));
const { project, settings } = useProject.getState();
const own = effectiveContentRoots(validateProjectStructure(settings?.projectStructure));
// The build model keeps the folders of modules outside the project absolute.
const gradle = (useBuildModel.getState().model?.gradle ?? [])
.flatMap((g) => g.projects)
.map((p) => p.dir)
.filter((d) => isAbsolute(d));
return [...new Set([...own, ...gradle])];
return [...new Set([...(project?.workspace?.projects ?? []), ...own, ...gradle])];
}
const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p);
+22
View File
@@ -68,6 +68,7 @@ beforeEach(() => {
afterEach(() => {
resetRuns();
_resetI18nForTests();
useProject.setState({ project: null });
});
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
@@ -142,6 +143,27 @@ it("finds the source module for an old saved configuration without a module", as
);
});
it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => {
const root = "/p";
const member = "/other/spring";
const module = `${member}/web`;
useProject.setState({
project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never,
});
ipc.findFiles.mockResolvedValueOnce({
status: "ok",
data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }],
});
const session = await startRun({ ...config, cwd });
expect(session?.status).toBe("running");
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number));
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd: cwd ?? module, module }),
expect.anything(),
expect.any(Number),
);
});
it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => {
const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"];
const boot = { ...config, kind: "spring-boot", args };
@@ -1,9 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerAction } from "@/platform/actions";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, undo } from "@codemirror/commands";
import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, redo, standardKeymap, undo } from "@codemirror/commands";
import { nextOccurrence, occurrenceSearch } from "@/editor/core/cm/editing";
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { completedSyntaxState } from "@/test/syntax";
import { languages } from "@codemirror/language-data";
import {
@@ -284,14 +285,55 @@ describe("surround with", () => {
describe("template fields", () => {
const selected = (v: EditorView) => v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to);
it("edits the Java fori index from a single caret and lets the initializer be edited separately", async () => {
const doc = "class Main {\n void f() {\n fori\n }\n}";
const v = await editor("java", doc, doc.indexOf("fori") + 4, [history(), keymap.of(standardKeymap)]);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(1);
expect(selected(v)).toBe("i");
expect(v.state.selection.main.from).toBe(v.state.doc.toString().indexOf("int i") + "int ".length);
const expanded = v.state.doc.toString();
v.dispatch(v.state.replaceSelection("index"));
const renamed = expanded.replace(/\bi\b/g, "index");
expect(v.state.doc.toString()).toBe(renamed);
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(expanded);
expect(redo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(renamed);
const afterZero = renamed.indexOf(" = 0") + " = 0".length;
while (v.state.selection.main.head < afterZero) expect(press(v, "ArrowRight")).toBe(true);
expect(v.state.selection.main.head).toBe(afterZero);
expect(v.state.selection.ranges).toHaveLength(1);
expect(press(v, "Backspace")).toBe(true);
v.dispatch(v.state.replaceSelection("1"));
expect(v.state.doc.toString()).toBe(renamed.replace(" = 0", " = 1"));
});
it("keeps one index caret per Java fori expansion", async () => {
const doc = "class Main {\n void f() {\n fori\n fori\n }\n}";
const v = await editor("java", doc);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.mainIndex).toBe(1);
v.dispatch(v.state.replaceSelection("index"));
expect(v.state.doc.toString().match(/\bindex\b/g)).toHaveLength(6);
expect(press(v, "Enter")).toBe(true);
expect(v.state.selection.ranges.every((range) => range.empty)).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["index", "index"]);
});
it("links fields and advances all carets through separately indented expansions", async () => {
const doc = "function first() {\n fori\n}\nfunction second() {\n fori\n}";
const v = await editor("typescript", doc, undefined, [history()]);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
const before = v.state.selection;
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(Array(6).fill("i"));
expect(v.state.selection.mainIndex).toBe(3);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["i", "i"]);
expect(v.state.selection.mainIndex).toBe(1);
expect(v.state.doc.line(3).text).toBe(" ");
expect(v.state.doc.line(8).text).toBe(" ");
@@ -301,7 +343,7 @@ describe("template fields", () => {
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.ranges.every((r) => v.state.sliceDoc(r.head, r.head + 7) === ".length")).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges).toHaveLength(6);
expect(v.state.selection.ranges).toHaveLength(2);
expect(tab(v)).toBe(true);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => r.head)).toEqual([v.state.doc.line(3).to, v.state.doc.line(8).to]);
@@ -365,15 +407,36 @@ describe("template fields", () => {
await tick();
expect(press(v, "Escape")).toBe(true);
expect(v.state.selection.main.empty).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(true);
expect(hasLinkedSnippetField(v.state, 1)).toBe(true);
expect(press(v, "Escape")).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(false);
expect(hasLinkedSnippetField(v.state, 1)).toBe(false);
// Outside a template Enter and Esc are left to the editor.
expect(press(v, "Escape")).toBe(false);
});
});
describe("⌘J Insert Live Template", () => {
it.each([
{ label: "sout", insert: "System.out.println();" },
{ label: "fori", insert: "for (int i = 0; i < ; i++) {" },
])("replaces a backward selection when picking $label", async ({ label, insert }) => {
const text = "class Main {\n void f() {\n payload\n leftover\n return;\n }\n}";
const from = text.indexOf("payload");
const to = text.indexOf("leftover") + "leftover".length;
const v = await editor("java", text, from, [autocompletion()]);
v.dispatch({ selection: { anchor: to, head: from } });
insertLiveTemplate(v);
const result = await templateCompletionSource(new CompletionContext(v.state, from, true));
const option = result?.options.find((candidate) => candidate.label === label);
if (typeof option?.apply !== "function") throw new Error("Expected a live template completion");
option.apply(v, option, result!.from, from);
expect(v.state.doc.line(3).text.trim()).toBe(insert);
expect(v.state.doc.toString()).not.toMatch(/payload|leftover/);
expect(v.state.doc.toString()).toContain("return;");
expect(v.state.selection.ranges).toHaveLength(1);
});
it("opens a lookup restricted to live templates and ends with it", async () => {
const v = await editor("typescript", "function f() {\n ", undefined, [autocompletion()]);
const exclusive = () =>
+11 -71
View File
@@ -4,13 +4,11 @@
* application / field navigation.
*/
import {
clearSnippet,
closeCompletion,
completionStatus,
nextSnippetField,
pickedCompletion,
prevSnippetField,
snippet,
snippetKeymap,
startCompletion,
type Completion,
@@ -18,16 +16,7 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import {
EditorSelection,
EditorState,
Facet,
Prec,
StateEffect,
StateField,
type Extension,
type Transaction,
} from "@codemirror/state";
import { EditorSelection, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, keymap, type Command } from "@codemirror/view";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
@@ -50,14 +39,7 @@ import { showChooser, type ChooserItem } from "./popup/store";
import { expandEmmetAtCaret } from "./emmet/editor";
import { hasEmmet, loadEmmet } from "./emmet/model";
import { readClipboardPlainText } from "@/platform/clipboard";
import {
applyMulticaretSnippet,
clearMulticaretSnippet,
hasMulticaretSnippet,
moveMulticaretField,
multicaretFieldMoved,
multicaretSnippetExtension,
} from "./multicaretSnippet";
import { applySnippet, escapeSnippet, nextLiveSnippetField, snippetFieldMoved } from "@/editor/core/cm/linkedSnippet";
export interface TemplateDocInfo {
path: string;
@@ -149,23 +131,19 @@ async function expandAtSites(
const clipboard = needsClipboard(t) ? await readClipboard() : "";
if (view.state.doc !== state.doc || !view.state.selection.eq(state.selection) || view.state.readOnly) return;
let expansions = sites.map(({ from }) => expansionAt(state, t, from, clipboard, opts));
if (sites.length === 1) {
const { from, to } = sites[0]!;
clearMulticaretSnippet(view);
snippet(expansions[0]!.snippet)(view, null, from, to);
} else {
if (sites.length > 1) {
// A variable stays editable everywhere if any caret needs it as a tab stop.
const editable = new Set(expansions.flatMap((e) => e.fields));
if (expansions.some((e) => e.fields.length !== editable.size)) {
const variables = t.variables?.map((v) => (editable.has(v.name) ? { ...v, skipIfDefined: false } : v));
expansions = sites.map(({ from }) => expansionAt(state, { ...t, variables }, from, clipboard, opts));
}
applyMulticaretSnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
}
const exp = expansions[0]!;
applySnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
if (view.state.field(fieldCompletion, false) !== undefined)
view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
if (exp.completeFirst) setTimeout(() => startCompletion(view), 0);
@@ -189,63 +167,29 @@ const fieldCompletion = StateField.define<readonly boolean[]>({
update: (value, tr) => tr.effects.find((e) => e.is(setFieldCompletion))?.value ?? value,
});
/**
* The snippet field a transaction moves to. CodeMirror doesn't expose it; its
* snippet-state effect carries the active snippet (`{ ranges, active }`).
*/
function movedToField(tr: Transaction): number | null {
for (const e of tr.effects) {
const v = e.value as { active?: unknown; ranges?: unknown } | null;
if (v && typeof v === "object" && typeof v.active === "number" && Array.isArray(v.ranges)) return v.active;
}
return null;
}
/** Moving to a field that asks for completion opens it, as IDEA does. */
const completeOnFieldMove = EditorView.updateListener.of((u) => {
if (u.docChanged) return;
const flags = u.state.field(fieldCompletion);
const field = u.transactions.map((tr) => multicaretFieldMoved(tr) ?? movedToField(tr)).findLast((i) => i !== null);
const field = u.transactions.map((tr) => snippetFieldMoved(tr)).findLast((i) => i !== undefined);
if (field == null || !flags[field]) return;
setTimeout(() => {
if (u.view.state.selection === u.state.selection) startCompletion(u.view);
}, 0);
});
/**
* Esc in a template, as in IDEA: first drops the selection (closing the lookup)
* or closes the lookup; only with neither does it leave the template.
*/
export const escapeTemplate: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearMulticaretSnippet(view) || clearSnippet(view);
};
const unlessLookup =
(cmd: Command): Command =>
(view) =>
completionStatus(view.state) === "active" ? false : cmd(view);
const nextMulticaretField = moveMulticaretField(1);
/**
* Whether the active snippet came from a live template or Emmet, where Enter moves to the
* next field. A completion's snippet (an LSP `<tag>$1</tag>$0`) keeps Enter for new lines.
*/
const templateSnippet = StateField.define<boolean>({
create: () => false,
update: (value, tr) => (movedToField(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
update: (value, tr) => (snippetFieldMoved(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
});
/** Tab moves to the next field; Enter too in templates (the lookup's while it is open). */
@@ -255,7 +199,7 @@ const templateFieldKeys = snippetKeymap.of([
key: "Enter",
run: unlessLookup((view) => view.state.field(templateSnippet, false) === true && nextSnippetField(view)),
},
{ key: "Escape", run: escapeTemplate },
{ key: "Escape", run: escapeSnippet },
]);
// ---------------------------------------------------------------------------
@@ -672,7 +616,6 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
fieldCompletion,
templateSnippet,
completeOnFieldMove,
multicaretSnippetExtension,
templateFieldKeys,
templateLookup,
endTemplateLookup,
@@ -685,14 +628,11 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
]),
Prec.high(
keymap.of([
{ key: "Enter", run: unlessLookup(nextMulticaretField) },
{ key: "Escape", run: (view) => hasMulticaretSnippet(view.state) && escapeTemplate(view) },
{ key: "Enter", run: unlessLookup(nextLiveSnippetField) },
{
key: "Tab",
shift: moveMulticaretField(-1),
run: (view) => {
if (view.state.readOnly || completionStatus(view.state) === "active") return false;
if (nextMulticaretField(view)) return true;
if (expandPostfixAtCaret(view)) return true;
if (useLiveTemplateOptions.getState().expandWithTab && expandLiveTemplateAtCaret(view)) return true;
return expandEmmetAtCaret(view, ctx.language);
-180
View File
@@ -1,180 +0,0 @@
import { clearSnippet, nextSnippetField, snippet } from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
EditorSelection,
EditorState,
MapMode,
StateEffect,
StateField,
Text,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type Command } from "@codemirror/view";
export interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface ActiveFields {
groups: readonly EditorSelection[];
active: number;
}
const setFields = StateEffect.define<ActiveFields | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
const fields = StateField.define<ActiveFields | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((e) => e.is(setFields));
if (next) return next.value;
if (!value) return null;
const { active } = value;
let { groups } = value;
if (tr.docChanged) {
const mapped: EditorSelection[] = [];
for (const group of groups) {
const ranges = [];
for (const range of group.ranges) {
const from = tr.changes.mapPos(range.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(range.to, 1, MapMode.TrackDel);
if (from === null || to === null) return null;
ranges.push(EditorSelection.range(from, to));
}
mapped.push(EditorSelection.create(ranges, group.mainIndex));
}
groups = mapped;
}
const current = groups[active]!.ranges;
if (tr.selection && !tr.selection.ranges.every((r) => current.some((f) => f.from <= r.from && r.to <= f.to)))
return null;
return groups === value.groups ? value : { groups, active };
},
provide: (field) =>
EditorView.decorations.from(field, (v) =>
v
? Decoration.set(
v.groups.flatMap((g) => g.ranges.map((r) => (r.empty ? fieldCursor : fieldMark).range(r.from, r.to))),
true,
)
: Decoration.none,
),
});
export const hasMulticaretSnippet = (state: EditorState) => !!state.field(fields, false);
export function multicaretFieldMoved(tr: Transaction): number | undefined {
return tr.effects.find((e) => e.is(setFields))?.value?.active;
}
export const clearMulticaretSnippet: Command = (view) => {
if (!hasMulticaretSnippet(view.state)) return false;
view.dispatch({ effects: setFields.of(null) });
return true;
};
function selectField(view: EditorView, value: ActiveFields, active: number): boolean {
const selection = value.groups[active];
if (!selection) return false;
view.dispatch({
selection,
effects: setFields.of(active === value.groups.length - 1 ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export const moveMulticaretField =
(direction: 1 | -1): Command =>
(view) => {
const value = view.state.field(fields, false);
return value ? selectField(view, value, value.active + direction) : false;
};
export const multicaretSnippetExtension = [
fields,
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const index = value.groups.findIndex((g) => g.ranges.some((r) => r.from <= pos && pos <= r.to));
return index !== value.active && selectField(view, value, index);
},
}),
];
/** Ask CodeMirror to render each snippet in its line's indentation and expose its tab stops. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
let state = EditorState.create({
doc: line.text,
selection: EditorSelection.cursor(to),
extensions: [EditorState.allowMultipleSelections.of(true), indentUnit.of(source.facet(indentUnit))],
});
const dispatch = (tr: Transaction) => {
state = tr.state;
};
let insert = Text.empty;
snippet(site.snippet)(
{
state,
dispatch: (tr) => {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
dispatch(tr);
},
},
null,
from,
to,
);
const groups = [];
do {
groups.push(state.selection);
} while (nextSnippetField({ state, dispatch }));
return { from: site.from, to: site.to, offset: from, insert, groups };
}
export function applyMulticaretSnippet(view: EditorView, sites: readonly SnippetSite[]) {
const { state } = view;
const entries = sites.map((site) => instantiate(state, site));
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
const groups = entries[0]!.groups.map((_, field) => {
let main = 0;
const ranges = entries.flatMap((entry, i) => {
const group = entry.groups[field]!;
const offset = changes.mapPos(entry.from, -1) - entry.offset;
if (i < state.selection.mainIndex) main += group.ranges.length;
return group.ranges.map((r) => EditorSelection.range(r.from + offset, r.to + offset));
});
return EditorSelection.create(ranges, main);
});
clearSnippet(view);
view.dispatch({
changes,
selection: groups[0]!,
effects: setFields.of(groups.length > 1 ? { groups, active: 0 } : null),
annotations: isolateHistory.of("full"),
scrollIntoView: true,
});
}
+6 -4
View File
@@ -10,6 +10,7 @@ export const BINARY_KIND = "binary";
const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", "avif"]);
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdown", "mkd", "mkdn", "mdwn"]);
const MARKDOWN_SOURCE_EXTENSIONS = new Set([...MARKDOWN_EXTENSIONS, "mdx", "ronn", "workbook"]);
function extension(path: string): string {
const name = path.slice(path.lastIndexOf("/") + 1);
@@ -21,12 +22,13 @@ export const isImagePath = (path: string) => IMAGE_EXTENSIONS.has(extension(path
export const isSvgPath = (path: string) => extension(path) === "svg";
/**
* Whether `path` gets the Markdown preview, decided synchronously so a tab never opens
* without it first: Markdown by Settings › File Types.
* Whether `path` gets the Markdown preview under Settings › File Types.
* The source check also includes Markdown extensions that open in the editor alone.
*/
export function isMarkdownPath(path: string): boolean {
export function isMarkdownPath(path: string, mode: "preview" | "source" = "preview"): boolean {
const { settings, project } = useProject.getState();
return hasFileType(path, ["markdown"], MARKDOWN_EXTENSIONS, settings?.files, project?.root ?? null);
const extensions = mode === "source" ? MARKDOWN_SOURCE_EXTENSIONS : MARKDOWN_EXTENSIONS;
return hasFileType(path, ["markdown"], extensions, settings?.files, project?.root ?? null);
}
/** Whether the file's name matches one of `patterns` (`*.xlsx`); Windows/macOS match case-insensitively. */
@@ -50,6 +50,7 @@ import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
import {
ANCHOR_PREFIX,
createMarkdownRenderer,
headingLine,
previewLineAtOffset,
previewOffsetForLine,
resolveLink,
@@ -59,6 +60,7 @@ import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
import styles from "./Markdown.module.css";
import { tx } from "@/platform/i18n";
import { wheelZoomStep } from "@/platform/wheelZoom";
import { isMarkdownPath } from "../fileKinds";
import { attachPanZoom } from "../panZoom";
/** Loaded local images by absolute path (data URLs), shared by all previews. */
@@ -76,6 +78,18 @@ function imageUrl(path: string): Promise<string> {
return p;
}
/**
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
* edits included) or else the file on disk; undefined when the file is not Markdown, cannot be
* read or has no such heading.
*/
async function anchorLine(path: string, anchor: string): Promise<number | undefined> {
if (!isMarkdownPath(path, "source")) return undefined;
const open = editorsFor(path)[0];
const text = open ? open.view.state.doc.toString() : await call(commands.fsReadText(path)).catch(() => null);
return (text === null ? null : headingLine(text, anchor)) ?? undefined;
}
function openExternal(url: string) {
if (isTauri()) void import("@tauri-apps/plugin-opener").then((m) => m.openUrl(url)).catch(() => {});
else window.open(url, "_blank", "noopener");
@@ -209,6 +223,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const html = useMemo(() => render(deferred), [render, deferred]);
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
const ref = useRef<HTMLDivElement>(null);
const linkRequest = useRef(0);
const blocks = useRef<ReturnType<typeof blocksOf>>([]);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
@@ -223,7 +238,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
/** `<details>` the reader opened or closed, by position: each edit re-renders them as written. */
const toggled = useRef(new Map<number, boolean>());
useLayoutEffect(() => toggled.current.clear(), [path]);
useLayoutEffect(() => {
toggled.current.clear();
return () => {
linkRequest.current++;
};
}, [path]);
useLayoutEffect(() => {
ref.current?.querySelectorAll("details").forEach((d, i) => {
const open = toggled.current.get(i);
@@ -382,6 +402,8 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
useLayoutEffect(() => {
const root = ref.current;
if (!root || caretSeq === seenCaret.current) return;
// First-open navigation can arrive before the destination's deferred Markdown is rendered.
if (!sync && deferred !== text) return;
seenCaret.current = caretSeq;
if (sync) return;
if (find && find.currentMatchIndex >= 0) {
@@ -403,7 +425,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
restoreRetry.current = null;
}
setShownLine(path, caretLine);
}, [caretSeq, caretLine, sync, path, find]);
}, [caretSeq, caretLine, sync, path, find, deferred, text]);
// Search (⌘F) and selection occurrence highlights in the preview.
useLayoutEffect(() => {
@@ -542,6 +564,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
e.preventDefault();
const target = resolveLink(path, a.getAttribute("href") ?? "");
if (!target) return;
const request = ++linkRequest.current;
const scrollTo = (id: string) => {
const root = ref.current;
if (!root) return;
@@ -555,10 +578,14 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
else if (target.kind === "anchor") scrollTo(target.id);
else if (target.path === path && target.anchor) scrollTo(target.anchor);
else
void maybeEditorService()?.openFile(target.path, {
focus: true,
...(target.line !== undefined ? { selection: { line: target.line, col: 0 } } : {}),
});
void (async () => {
const line = target.line ?? (target.anchor ? await anchorLine(target.path, target.anchor) : undefined);
if (request !== linkRequest.current) return;
await maybeEditorService()?.openFile(target.path, {
focus: true,
...(line !== undefined ? { selection: { line, col: 0 } } : {}),
});
})();
};
return (
@@ -0,0 +1,140 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, editorContributions, type EditorDocContext } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import { useContextKeys } from "@/platform/context";
import { useProject } from "@/platform/project";
import type { Settings } from "@/platform/ipc";
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
import { MarkdownEditor } from "./MarkdownEditor";
import { useMarkdownModes } from "./modes";
const openFile = vi.fn(async () => {});
const targetText = "# 成交对账\n\n正文\n\n## 5.2 状态机\n";
const disk: Record<string, string | Promise<string>> = {
"/p/b.md": targetText,
"/p/c.txt": targetText,
"/p/alias.mkdn": targetText,
"/p/assigned.txt": targetText,
"/p/plain.md": targetText,
"/p/source.mdx": targetText,
};
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ openFile }),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
return {
...ipc,
commands: { ...ipc.commands, fsReadText: (path: string) => ({ readText: path }) },
call: (request: unknown) => {
const path = (request as { readText?: string } | null)?.readText;
if (path === undefined) return ipc.call(request as never);
return path in disk ? Promise.resolve(disk[path]) : Promise.reject(new Error("missing"));
},
};
});
const ctx: EditorDocContext = { doc: 1, path: "/p/a.md", language: "markdown", uiMode: null, readOnly: false };
const doc = [
"[disk](b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)",
"[open](d.md#52-状态机)",
"[line](b.md#L3)",
"[none](b.md#missing)",
"[text](c.txt#52-状态机)",
"[alias](alias.mkdn#52-状态机)",
"[assigned](assigned.txt#52-状态机)",
"[plain](plain.md#52-状态机)",
"[source](source.mdx#52-状态机)",
"",
].join("\n\n");
describe("preview links to a heading in another file", () => {
const disposers: Array<() => void> = [];
const views: EditorView[] = [];
beforeEach(() => {
openFile.mockClear();
const settings = useProject.getState().settings;
useProject.setState({
settings: {
files: { fileTypeOverrides: { "/p/assigned.txt": "markdown", "/p/plain.md": "plaintext" } },
} as Settings,
});
disposers.push(() => useProject.setState({ settings }));
disposers.push(registerMarkdownLiveSource());
useContextKeys.setState({ projectOpen: true, textEditorActive: true });
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const view = new EditorView({ state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(ctx)] }) });
// An open editor's unsaved text wins over the file on disk.
const other = new EditorView({ state: EditorState.create({ doc: "# D\n\nnew line\n\n## 5.2 状态机\n" }) });
views.push(view, other);
for (const handle of [
{ view, ctx },
{ view: other, ctx: { ...ctx, doc: 2, path: "/p/d.md" } },
]) {
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
}
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } })));
});
afterEach(() => {
cleanup();
for (const view of views.splice(0)) view.destroy();
for (const dispose of disposers.splice(0).reverse()) dispose();
useLiveMarkdown.setState({}, true);
useContextKeys.setState({}, true);
});
const renderPreview = async () => {
render(
<MarkdownEditor path={ctx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => expect(preview.querySelectorAll("a")).toHaveLength(9));
};
it("opens the file at the heading line", async () => {
await renderPreview();
const click = async (name: string) => {
openFile.mockClear();
fireEvent.click(screen.getByText(name));
await waitFor(() => expect(openFile).toHaveBeenCalledTimes(1));
return openFile.mock.calls[0];
};
expect(await click("disk")).toEqual(["/p/b.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("open")).toEqual(["/p/d.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("line")).toEqual(["/p/b.md", { focus: true, selection: { line: 2, col: 0 } }]);
expect(await click("none")).toEqual(["/p/b.md", { focus: true }]);
expect(await click("text")).toEqual(["/p/c.txt", { focus: true }]);
expect(await click("alias")).toEqual(["/p/alias.mkdn", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("assigned")).toEqual(["/p/assigned.txt", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("plain")).toEqual(["/p/plain.md", { focus: true }]);
expect(await click("source")).toEqual(["/p/source.mdx", { focus: true, selection: { line: 4, col: 0 } }]);
});
it("keeps a slow heading lookup from superseding a newer link", async () => {
await renderPreview();
let resolve!: (text: string) => void;
disk["/p/b.md"] = new Promise<string>((done) => {
resolve = done;
});
try {
fireEvent.click(screen.getByText("disk"));
fireEvent.click(screen.getByText("line"));
await waitFor(() =>
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/b.md", { focus: true, selection: { line: 2, col: 0 } }),
);
await act(async () => resolve(targetText));
expect(openFile).toHaveBeenCalledTimes(1);
} finally {
disk["/p/b.md"] = targetText;
}
});
});
@@ -5,6 +5,7 @@ import { renderMath } from "@/editor/lsp/markdownMath";
import {
createMarkdownRenderer,
frontMatter,
headingLine,
joinPath,
previewLineAtOffset,
previewOffsetForLine,
@@ -286,6 +287,36 @@ describe("markdown preview rendering", () => {
expect(slugify("Hello, World! v2")).toBe("hello-world-v2");
});
it("finds the source line of a heading anchor, as a link from another file opens there", () => {
const text = [
"---",
"title: x",
"---",
"# 成交对账",
"",
"```md",
"## 5.2 状态机",
"```",
"",
"## 5.2 状态机",
"",
"正文",
"",
"## 5.2 状态机",
"",
"### 4.1 Dubbo(`otcs-t0-server` client)",
].join("\n");
expect(headingLine(text, "成交对账")).toBe(3);
expect(headingLine(text, "52-状态机")).toBe(9);
expect(headingLine(text, "52-状态机-1")).toBe(13);
expect(headingLine(text, "user-content-52-状态机")).toBe(9);
expect(headingLine(text, "41-dubbootcs-t0-server-client")).toBe(15);
const link = resolveLink("/repo/a.md", "b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA");
expect(link).toEqual({ kind: "file", path: "/repo/b.md", anchor: "52-状态机" });
expect(headingLine(text, "missing")).toBeNull();
expect(headingLine(text, "")).toBeNull();
});
it("resolves links against the file", () => {
const file = "/repo/docs/guide.md";
expect(resolveLink(file, "https://x.dev")).toEqual({ kind: "external", url: "https://x.dev" });
+29 -4
View File
@@ -69,6 +69,14 @@ export function slugify(text: string): string {
.replace(/\s/g, "-");
}
/** The id of the next heading titled `text`, counting repeats in `slugs` as GitHub does (`a`, `a-1`, `a-2`…). */
function headingId(slugs: Map<string, number>, text: string): string {
const base = slugify(text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
return n ? `${base}-${n}` : base;
}
const countLines = (s: string) => {
let n = 0;
for (let i = s.indexOf("\n"); i >= 0; i = s.indexOf("\n", i + 1)) n++;
@@ -161,10 +169,8 @@ function blocks(text: string): { line: number; html: string }[] {
const list = Object.assign([token], { links: tokens.links }) as TokensList;
let body = marked.parser(list);
if (token.type === "heading") {
const base = slugify((token as Token & { text: string }).text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${n ? `${base}-${n}` : base}">`);
const id = headingId(slugs, (token as Token & { text: string }).text);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${id}">`);
}
group ??= { line: start, html: "" };
group.html += body;
@@ -193,6 +199,25 @@ const wrap = (line: number, html: string) => `<div data-line="${line}">${html}</
const sanitizeWhole = (all: readonly { line: number; html: string }[]) =>
purify().sanitize(all.map((b) => wrap(b.line, b.html)).join(""), SANITIZE);
/**
* 0-based source line of the heading the preview gives the anchor `anchor` (with or without
* {@link ANCHOR_PREFIX}), or null when no heading has it. Lets a link to another file open at
* that heading.
*/
export function headingLine(text: string, anchor: string): number | null {
const want = slugify(anchor.startsWith(ANCHOR_PREFIX) ? anchor.slice(ANCHOR_PREFIX.length) : anchor);
if (!want) return null;
const front = frontMatter(text);
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
const slugs = new Map<string, number>();
let line = front?.lines ?? 0;
for (const token of marked.lexer(body)) {
if (token.type === "heading" && headingId(slugs, (token as Token & { text: string }).text) === want) return line;
line += countLines(token.raw);
}
return null;
}
export function renderMarkdown(text: string): string {
return sanitizeWhole(blocks(text));
}
+11 -2
View File
@@ -14,6 +14,7 @@ import {
type RequestId,
} from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { useBuildPresentation } from "@/platform/projectPresentation";
import { isRemoteWindow } from "@/platform/remote";
@@ -198,6 +199,7 @@ export async function findJavaModule(config: RunConfig): Promise<string | null>
/** Module directories (as {@link jvmModuleDir}) of the project's sources declaring the class `binaryName`. */
export async function classModules(binaryName: string): Promise<string[]> {
const root = useProject.getState().project?.root;
const outer = binaryName.split("$")[0]!;
const simple = outer.slice(outer.lastIndexOf(".") + 1);
const pkg = outer.slice(0, Math.max(0, outer.lastIndexOf(".")));
@@ -210,7 +212,7 @@ export async function classModules(binaryName: string): Promise<string[]> {
for (const file of matches) {
const text = await call(commands.fsReadText(file.path));
const sourcePackage = /^\s*package\s+([\w.]+)\s*[;\r\n]/m.exec(text)?.[1] ?? "";
if (sourcePackage === pkg) modules.add(jvmModuleDir(file.relPath, configs));
if (sourcePackage === pkg) modules.add(jvmModuleDir(root ? relativePath(root, file.path) : file.relPath, configs));
}
return [...modules];
}
@@ -291,5 +293,12 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep
}
if (parsed.classpath && !info.classPaths.length)
throw new Error(tx("The classpath is empty: is the module imported by the Java language server?"));
return { module, info, resolved: resolveJavaCommand(config, info) };
const resolved = resolveJavaCommand({ ...config, module }, info);
const project = useProject.getState().project;
if (resolved.cwd == null && project?.workspace) {
const path = /^(?:[A-Za-z]:)?\//.test(module) ? module : `${project.root}/${module}`;
const owner = projectFolder(project, path);
if (owner && owner.root !== project.root) resolved.cwd = path;
}
return { module, info, resolved };
}
+1
View File
@@ -2821,6 +2821,7 @@
"Accepts mcpServers, servers, or a single server JSON object.": "Accepts mcpServers, servers, or a single server JSON object.",
"Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents.",
"Related Symbol…": "Related Symbol…",
"Choose Inheritance Target ({count} found)": "Choose Inheritance Target ({count} found)",
"Choose Target": "Choose Target",
"No related symbols": "No related symbols",
"Header": "Header",
+1
View File
@@ -9180,6 +9180,7 @@
"Accepts mcpServers, servers, or a single server JSON object.": "支持 mcpServers、servers 或单个服务器 JSON 对象。",
"Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。",
"Related Symbol…": "相关符号…",
"Choose Inheritance Target ({count} found)": "选择继承目标(找到 {count} 个)",
"Choose Target": "选择目标",
"No related symbols": "没有相关符号",
"Header": "头文件",
+6
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
gitRevisionOf,
isVirtualUri,
libraryArchiveRoot,
libraryEntryPaths,
virtualContainer,
virtualName,
@@ -130,6 +131,11 @@ describe("libraryEntryPaths", () => {
]),
).toEqual([`${SOURCES}!/org/x/Y.java`, `${GRADLE}/sourceHash/a-1.0.jar!/org/x/Y.class`]);
});
it("names the archive that contains a library document", () => {
expect(libraryArchiveRoot(JDT)).toBe("/m2/spring-boot-4.1.1.jar!");
expect(libraryArchiveRoot("untitled:Untitled-1")).toBeNull();
});
});
describe("Git revision URIs", () => {
+7
View File
@@ -185,3 +185,10 @@ export function libraryEntryPaths(uri: string, archives: readonly string[] = [])
if (jar.endsWith("/jrt-fs.jar")) return [`${parentDir(jar)}/src.zip!/${module}/${stem}.java`];
return jarCandidates(jar, stem, archives);
}
/** The archive root (`<jar>!`) containing a library document, when it has one. */
export function libraryArchiveRoot(uri: string): string | null {
const entry = libraryEntryPaths(uri)[0];
const separator = entry?.indexOf("!/") ?? -1;
return entry && separator > 0 ? `${entry.slice(0, separator)}!` : null;
}