Compare commits

...
Author SHA1 Message Date
l0ng-ai 0bfd8ede7f fix(run): detect Spring Boot applications from Spring Boot on the classpath
A @SpringBootApplication main class was only offered as a Spring Boot configuration when its
module, or a parent POM, applied spring-boot-maven-plugin. Modules that get Spring Boot as a
dependency (directly, from a parent such as spring-boot-starter-parent, or through the BOM)
but don't package with the plugin stayed plain Java applications. A module now counts when its
build, or a parent build in the project, references Spring Boot outside <pluginManagement>;
Gradle modules count with an org.springframework.boot dependency as well.
2026-11-20 13:58:24 +08:00
l0ng-ai 9fe1dd8d7b feat(run): expand multi-line run configuration fields into a larger editor (#4704)
VM options and the other multi-line run configuration fields get an Expand button (Shift+Enter) opening a resizable editor where each line stays on one visual line and scrolls sideways, so a long JVM argument isn't wrapped into what looks like several. OK applies; Cancel or OK without edits leaves the field unchanged.
2026-11-20 13:49:43 +08:00
langxpandkradme c0b243f020 feat(maven): add POM artifact and managed-version navigation (#4699)
Go to Declaration on a dependency, plugin or <parent> in a POM opens the artifact's own POM (a workspace module with matching coordinates first, then the local repository), and unversioned dependencies and plugins get a gutter icon that opens the management entry supplying their version, through active profiles (including JDK-activated ones), parent POMs, imported BOMs and plugin management. Maven element values are underlined whole, and contributed definition/hover providers that decline a position let the next one answer. Review fix: a BOM import without a version no longer ends the management search.

Co-authored-by: kradme <[email protected]>
2026-11-20 13:45:47 +08:00
l0ng-ai 96f3818bf2 feat(vcs): setting to hide the Generate Commit Message with Agent button (#4701)
Version Control > Commit > Commit Message Generation gets "Show the Generate Commit Message with Agent button" (on by default). Off hides the button above the commit message in the Commit tool window and dialog; the action stays available from Find Action and its shortcut.
2026-11-20 13:29:32 +08:00
l0ng-ai adf17d030e feat(workbench): open projects in a new tab of the current window by default (#4700)
"Open project in" gets "New tab in current window", and Don't ask again in the Open Project dialog now remembers New Tab too, so opening further projects adds project tabs to the current window without asking. A window without its own project, or a remote project, falls back to a new window. Attach stays a one-off choice.
2026-11-20 13:26:06 +08:00
l0ng-ai 815bebf4ec fix(editor): keep in-file Find responsive in large files (#4698)
CodeMirror compares a plain-text query one character at a time; a pass over a 50 MB log took ~850 ms and each find-bar keystroke runs several, freezing the editor for seconds. Plain-text queries now run as an escaped regular expression (~35 ms per pass) with a literal replacement. Find Previous no longer uses CodeMirror's quadratic backward regex search; one forward pass finds the previous match.
2026-11-20 13:19:51 +08:00
l0ng-ai 2b75b79ea0 fix(run): import a Maven module by its artifactId before a same-named folder (#4696)
IDEA names a Maven module after its artifactId. The JetBrains run-configuration importer accepted a folder name or an artifactId in one breadth-first search, so a project folder named like a child module's artifactId resolved to the root module. Search artifactIds first, then folder names, then the Gradle source-set fallback.
2026-11-20 13:07:13 +08:00
38 changed files with 1923 additions and 178 deletions

No files matched your search

+13 -1
View File
@@ -82,11 +82,23 @@ pub fn load_linked(
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
) -> BuildModel {
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
}
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
pub fn load_linked_with_jdk(
root: &Path,
cache_dir: &Path,
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
maven_jdk_version: Option<u32>,
) -> BuildModel {
let maven = maven::has_projects(root, settings).then(|| {
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
let repo = maven_repo.or_else(maven::default_local_repo);
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
// The user settings' profiles can be chosen too (`-P` applies to them as well).
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
File diff suppressed because it is too large. Load diff
+3
View File
@@ -176,6 +176,8 @@ pub struct CommitSettings {
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
/// Show the Generate Commit Message with Agent button above the commit message.
pub agent_button: bool,
}
impl Default for CommitSettings {
@@ -201,6 +203,7 @@ impl Default for CommitSettings {
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
agent_button: true,
}
}
}
+118 -21
View File
@@ -8,30 +8,79 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::maven::PomGoto;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
fn join_err(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// POM gutters in several editors refresh together. A very short cache lets those
/// requests share one reactor scan without serving a stale module list after edits settle.
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
type MavenModuleCache = HashMap<String, (Instant, Vec<ide_build::maven::ModulePom>)>;
static MAVEN_MODULES: OnceLock<Mutex<MavenModuleCache>> = OnceLock::new();
fn maven_modules(
project: &Project,
settings: &Settings,
options: &PomNavigationOptions,
) -> Vec<ide_build::maven::ModulePom> {
let key = format!(
"{}\0{:?}\0{:?}\0{:?}\0{:?}",
project.root.display(),
project.build_cache_dir(),
settings.languages.java.maven.linked_projects,
options.profiles,
options.jdk_version
);
let cache = MAVEN_MODULES.get_or_init(|| Mutex::new(HashMap::new()));
if let Some((_at, modules)) = cache.lock().ok().and_then(|mut cache| {
let fresh = cache.get(&key).filter(|(at, _)| at.elapsed() < MAVEN_MODULE_CACHE_TTL).cloned();
if fresh.is_none() {
cache.remove(&key);
}
fresh
}) {
return modules;
}
let model = load(&project.root, &project.build_cache_dir(), settings).maven.unwrap_or_default();
let modules = model
.projects
.into_iter()
.map(|p| ide_build::maven::ModulePom {
group_id: p.group_id,
artifact_id: p.artifact_id,
version: p.version,
pom: project.root.join(&p.pom),
})
.collect::<Vec<_>>();
if let Ok(mut cache) = cache.lock() {
cache.insert(key, (Instant::now(), modules.clone()));
}
modules
}
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
/// the Maven home and options from Settings › Maven.
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
let mut model = ide_build::load_linked(
let jdk = ide_sdk::apply::project_jdk(root, settings);
let mut model = ide_build::load_linked_with_jdk(
root,
cache,
ide_sdk::apply::maven_local_repository(root, settings),
&settings.languages.java.maven,
&settings.languages.java.gradle,
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major),
);
let jdk = ide_sdk::apply::project_jdk(root, settings);
if let Some(m) = &mut model.maven {
let mvn = ide_sdk::apply::maven_command(root, settings);
let options = ide_sdk::apply::maven_options(root, settings);
@@ -77,6 +126,23 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// POM navigation follows the same profile choices as the last Maven sync and
/// resolves JDK-activated profiles with the project's selected Maven runtime.
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
let mut profiles = settings.languages.java.maven.profiles(&[]);
for profile in ide_build::maven_profiles(&project.build_cache_dir()) {
if !profiles.contains(&profile) {
profiles.push(profile);
}
}
PomNavigationOptions {
local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings)
.or_else(ide_build::maven::default_local_repo),
profiles,
jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major),
}
}
/// Build and Run use the same selected toolchain and module-local runtime discovery.
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
let kind = match plan.system {
@@ -547,8 +613,9 @@ pub async fn maven_dependency_declaration(
}
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
/// `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
/// entry providing the dependency's / plugin's version, along the parent chain.
/// `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
/// (a project module first, then the local repository). A dependency without a
/// resolvable artifact POM falls back to its management entry.
#[command(trust = trusted)]
pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult<Option<PomGoto>> {
// `pom` is project-relative, or absolute for a parent POM opened from the local repository.
@@ -561,26 +628,55 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
let settings = project.settings.effective();
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings)
.or_else(ide_build::maven::default_local_repo);
let modules = || {
let model = load(&project.root, &project.build_cache_dir(), &settings).maven.unwrap_or_default();
model
.projects
.into_iter()
.map(|p| ide_build::maven::ModulePom {
group_id: p.group_id,
artifact_id: p.artifact_id,
pom: project.root.join(&p.pom),
})
.collect()
};
Ok(ide_build::maven::goto_declaration_in(&text, &path, pos, repo, modules))
let options = pom_navigation_options(&project, &settings);
let module_options = options.clone();
let modules = || maven_modules(&project, &settings, &module_options);
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
})
.await
.map_err(join_err)?
}
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
/// the management declarations that actually supply their versions, including
/// parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn maven_managed_declarations(
host: &Host,
window: &str,
pom: String,
request: RequestId,
) -> IdeResult<Vec<PomManagedDeclaration>> {
let project = host.project(window)?;
let cancel = host.begin_project_read_request(window, request);
let result = tokio::task::spawn_blocking(move || {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let given = Path::new(&pom);
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
let settings = project.settings.effective();
let options = pom_navigation_options(&project, &settings);
let cancelled = cancel.clone();
let module_options = options.clone();
let modules = || {
if cancelled.is_cancelled() {
return Vec::new();
}
maven_modules(&project, &settings, &module_options)
};
let declarations = ide_build::maven::managed_declarations_with(&text, &path, options, modules);
if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(declarations) }
})
.await;
host.end_request(request);
match result {
Ok(result) => result,
Err(error) => Err(join_err(error)),
}
}
/// How long completion waits for Maven Central before answering from the local repository.
const CENTRAL_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
@@ -1333,4 +1429,5 @@ ide_command::domain!(
maven_dependency_declaration,
maven_exclude_dependency,
maven_goto_declaration,
maven_managed_declarations,
);
+20 -6
View File
@@ -631,9 +631,11 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
}
}
/// The module has main sources, and its build applies the Spring Boot plugin: its own build
/// file, or a build above it in `build` that applies it to its modules (a parent POM's
/// `<build><plugins>`, Gradle's `subprojects` / `allprojects`).
/// The module has main sources and Spring Boot on its classpath, as far as its build files
/// tell: its own build, or a build above it in `build` that hands Spring Boot to its modules,
/// references it (a dependency, the starter parent, the BOM or the plugin). A Maven module that
/// depends on Spring Boot through a parent or another module is a Spring Boot application even
/// without the packaging plugin; only `<pluginManagement>` alone doesn't count.
fn applies_spring_boot(build: &Path, module: &Path) -> bool {
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
return false;
@@ -642,15 +644,19 @@ fn applies_spring_boot(build: &Path, module: &Path) -> bool {
if pom.contains("<packaging>pom</packaging>") {
return false;
}
if pom.contains("spring-boot-maven-plugin") {
if references_spring_boot(&without_plugin_management(&pom)) {
return true;
}
} else if GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| applies_boot_gradle_plugin(&text)) {
} else if GRADLE_BUILDS
.iter()
.filter_map(|n| read(&module.join(n)))
.any(|text| applies_boot_gradle_plugin(&text) || text.contains("org.springframework.boot:"))
{
return true;
}
module.ancestors().skip(1).take_while(|dir| dir.starts_with(build)).any(|dir| {
if let Some(pom) = read(&dir.join("pom.xml")) {
return without_plugin_management(&pom).contains("spring-boot-maven-plugin");
return references_spring_boot(&without_plugin_management(&pom));
}
GRADLE_BUILDS.iter().filter_map(|n| read(&dir.join(n))).any(|text| {
(text.contains("subprojects") || text.contains("allprojects")) && applies_boot_gradle_plugin(&text)
@@ -658,6 +664,14 @@ fn applies_spring_boot(build: &Path, module: &Path) -> bool {
})
}
/// A POM (without its `<pluginManagement>`) referencing Spring Boot: a dependency or the parent
/// (`org.springframework.boot`), a starter, the BOM import or the plugin.
fn references_spring_boot(pom: &str) -> bool {
["org.springframework.boot", "spring-boot-starter", "spring-boot-dependencies", "spring-boot-maven-plugin"]
.iter()
.any(|m| pom.contains(m))
}
/// A Gradle build applying the plugin (`id("org.springframework.boot")`, `apply plugin: '…'`),
/// not only depending on Spring Boot (`org.springframework.boot:…`).
fn applies_boot_gradle_plugin(text: &str) -> bool {
+6 -2
View File
@@ -1112,8 +1112,12 @@ fn module_count(root: &Path) -> usize {
/// named after its `artifactId` (usually its folder), a Gradle one `<project>.<path>.<source set>`.
fn module_dir(root: &Path, name: &str) -> Option<String> {
let folder = |dir: &Path| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let exact = |dir: &Path| folder(dir) == name || pom_artifact(dir).is_some_and(|a| a == name);
if let Some(dir) = find_module(root, &exact) {
// A Maven module is named after its artifactId, so that match wins over a folder of the same
// name anywhere above it (a checkout folder named like a child module's artifactId).
if let Some(dir) = find_module(root, &|dir: &Path| pom_artifact(dir).is_some_and(|a| a == name)) {
return Some(dir);
}
if let Some(dir) = find_module(root, &|dir: &Path| folder(dir) == name) {
return Some(dir);
}
let gradle = name.strip_suffix(".main").or_else(|| name.strip_suffix(".test")).unwrap_or(name);
+38 -6
View File
@@ -380,27 +380,59 @@ fn a_root_build_disables_the_nested_scan() {
}
#[test]
fn spring_boot_applications_need_the_plugin_and_a_main() {
fn spring_boot_applications_need_spring_boot_and_a_main() {
let main =
"package demo;\n@SpringBootApplication\npublic class App {\n public static void main(String[] args) {}\n}\n";
// A library using Spring Boot without the plugin, a configuration class without `main`,
// the annotation in a comment, a parent POM.
// A module without Spring Boot in its build, a configuration class without `main`, the
// annotation in a comment, a parent POM.
let dir = project(&[
("lib/pom.xml", "<project><dependencies>spring-boot-starter</dependencies></project>"),
("lib/src/main/java/demo/App.java", main),
("plain/pom.xml", "<project><dependencies>commons-lang3</dependencies></project>"),
("plain/src/main/java/demo/App.java", main),
("svc/pom.xml", BOOT_POM),
("svc/src/main/java/demo/Config.java", "package demo;\n@SpringBootApplication\npublic class Config {}\n"),
(
"svc/src/main/java/demo/Old.java",
"package demo;\n// @SpringBootApplication\nclass Old { public static void main(String[] a) {} }\n",
),
("gr/build.gradle", "dependencies { implementation 'org.springframework.boot:spring-boot-starter' }\n"),
("gr/build.gradle", "dependencies { implementation 'com.google.guava:guava:33.0.0-jre' }\n"),
("gr/src/main/java/demo/App.java", main),
]);
let c = detect(dir.path());
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
}
/// Spring Boot on the classpath is enough, as for IntelliJ IDEA: a module depending on a
/// starter (directly or through its parent POM) without the packaging plugin, and Gradle's
/// dependency on `org.springframework.boot:…`.
#[test]
fn spring_boot_applications_without_the_plugin() {
let main =
"package demo;\n@SpringBootApplication\npublic class App {\n public static void main(String[] args) {}\n}\n";
let dir = project(&[
(
"lib/pom.xml",
"<project><dependencies><dependency><groupId>org.springframework.boot</groupId>\
<artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>",
),
("lib/src/main/java/demo/App.java", main),
("gr/build.gradle", "dependencies { implementation 'org.springframework.boot:spring-boot-starter' }\n"),
("gr/src/main/java/demo/App.java", main),
]);
let c = detect(dir.path());
assert_eq!(find(&c, "application:lib:demo.App").kind, "spring-boot");
assert_eq!(find(&c, "application:gr:demo.App").kind, "spring-boot");
let parent = "<project><packaging>pom</packaging><modules><module>job</module></modules>\
<parent><groupId>org.springframework.boot</groupId>\
<artifactId>spring-boot-starter-parent</artifactId></parent></project>";
let dir = project(&[
("pom.xml", parent),
("job/pom.xml", "<project><artifactId>job</artifactId></project>"),
("job/src/main/java/demo/App.java", main),
]);
assert_eq!(find(&detect(dir.path()), "application:job:demo.App").kind, "spring-boot");
}
#[test]
fn spring_boot_modules_inherit_the_plugin_from_their_parent_build() {
let main = |pkg: &str, ann: &str, cls: &str| {
+32
View File
@@ -860,6 +860,38 @@ fn java_applications_and_spring_boot_keep_their_module() {
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
}
/// A checkout folder named like a child module's artifactId: IDEA's module is the child.
#[test]
fn maven_module_artifact_wins_over_a_folder_of_the_same_name() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("demo-service");
write(
&root,
"pom.xml",
"<project><artifactId>demo-service-parent</artifactId><packaging>pom</packaging></project>",
);
write(
&root,
"app-web/pom.xml",
"<project><parent><artifactId>demo-service-parent</artifactId></parent><artifactId>demo-service</artifactId></project>",
);
write(
&root,
".run/Demo.run.xml",
&run_file(
"Demo",
r#"<configuration name="Demo" type="Application" factoryName="Application">
<module name="demo-service" />
<option name="MAIN_CLASS_NAME" value="com.example.Demo" />
</configuration>"#,
),
);
let r = import_from(&root, &[]);
assert_eq!(get(&r, "Demo").extras.module.as_deref(), Some("app-web"));
}
/// IDEA writes the working directory as a URL. On Windows `file://$PROJECT_DIR$`
/// expands to `file://C:/project`, where the drive letter sits where the authority
/// belongs; read as a path that is `C:project`, which resolves against the project
+1
View File
@@ -850,6 +850,7 @@ mod tests {
"agent": "",
"agentModel": "",
"agentEffort": "",
"agentButton": true,
})
);
}
+1
View File
@@ -375,6 +375,7 @@ maven_dependency_completion trusted project_host bin
maven_dependency_declaration trusted project_host bindings async
maven_exclude_dependency trusted project_host bindings async
maven_goto_declaration trusted project_host bindings async
maven_managed_declarations trusted project_host bindings async
mcp_agent_run_closed trusted project_host bindings sync
mcp_background_projects always project_host bindings sync
mcp_regenerate_token outside_restricted project_host bindings sync
+21 -2
View File
@@ -960,8 +960,9 @@ export const commands = {
mavenExcludeDependency: (pom: string, dependency: ArtifactKey, exclusion: ArtifactKey) => typedError<Location, IdeError>(__TAURI_INVOKE("maven_exclude_dependency", { pom, dependency, exclusion })),
/**
* The go-to-declaration target at `pos` of a Maven POM: the definition of the
* `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
* entry providing the dependency's / plugin's version, along the parent chain.
* `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
* (a project module first, then the local repository). A dependency without a
* resolvable artifact POM falls back to its management entry.
*/
mavenGotoDeclaration: (pom: string, pos: Pos) => typedError<{
/**
@@ -975,6 +976,12 @@ export const commands = {
/** The declaration as named for the user (`example.version`, `com.example:example-lib`). */
label: string,
} | null, IdeError>(__TAURI_INVOKE("maven_goto_declaration", { pom, pos })),
/**
* Gutter targets of the unversioned dependencies and plugins in a Maven POM:
* the management declarations that actually supply their versions, including
* parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
*/
mavenManagedDeclarations: (pom: string, request: RequestId) => typedError<PomManagedDeclaration[], IdeError>(__TAURI_INVOKE("maven_managed_declarations", { pom, request })),
/** The user closed the Run tool window tab of an agent command (`run_command`). */
mcpAgentRunClosed: (name: string) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_agent_run_closed", { name })),
/**
@@ -3770,6 +3777,8 @@ export type CommitSettings = {
agentModel?: string,
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort?: string,
/** Show the Generate Commit Message with Agent button above the commit message. */
agentButton?: boolean,
};
export type Commit_Deserialize = {
@@ -9751,6 +9760,16 @@ export type PomGotoKind =
/** The POM of the artifact itself: a project module's, else the local repository's. */
"artifactPom";
/** A dependency or plugin whose version comes from a management declaration. */
export type PomManagedDeclaration = {
/** 0-based line of the `<dependency>` or `<plugin>` declaration. */
line: number,
/** The interpolated version the management entry provides, when it has one. */
version: string | null,
/** The management entry, possibly in a parent POM or an imported BOM. */
target: PomGoto,
};
/** A 0-based line / UTF-16 column position. */
export type Pos = {
line: number,
+15 -1
View File
@@ -490,7 +490,11 @@ export type ContributedFormatter = (
range: { from: number; to: number } | null,
) => Array<{ from: number; to: number; insert: string }>;
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
export type ContributedDefinition = (view: EditorView, pos: number) => boolean;
export interface ContributedDefinition {
(view: EditorView, pos: number): boolean;
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
canHandle?(state: EditorState, pos: number): boolean;
}
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
export type ContributedHover = (
state: EditorState,
@@ -501,6 +505,16 @@ export function contributedAt<T>(state: EditorState, key: string, pos: number):
return state.languageDataAt<T>(key, pos)[0];
}
/**
* Every provider registered for a contributed language-data key at `pos`. A provider may
* be present for the document but decline this particular position (the MyBatis SQL
* provider on a Maven POM, for example), so callers that dispatch a request must not stop
* at the first entry when it returns "not handled".
*/
export function contributedAtAll<T>(state: EditorState, key: string, pos: number): readonly T[] {
return state.languageDataAt<T>(key, pos);
}
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
export interface ContributedIntention {
id: string;
+34
View File
@@ -171,6 +171,40 @@ describe("find in selection", () => {
});
});
describe("plain-text queries", () => {
it("match regex syntax and line breaks literally, case-insensitively", () => {
const v = make("a.b(c)[d]$ x A.B(C)[D]$ axb\nend\n1 + 1 = 2", { search: "a.b(c)[d]$" });
expect(countMatches(v.state).total).toBe(2);
expect(countMatches(make("one\ntwo\none two", { search: "one\ntwo" }).state).total).toBe(1);
expect(countMatches(make("1+1 11", { search: "1+1" }).state).total).toBe(1);
expect(countMatches(make("a/b a\\b", { search: "a\\b" }).state).total).toBe(1);
});
it("replace with `$` and backslashes as written", () => {
const v = make("cost: x; cost: y", { search: "cost", replace: "$& $1 $$ \\n" });
replaceAll(v);
expect(v.state.doc.toString()).toBe("$& $1 $$ \\n: x; $& $1 $$ \\n: y");
const w = make("cost", { search: "cost", replace: "$" });
replaceNext(w, true);
replaceNext(w, true);
expect(w.state.doc.toString()).toBe("$");
});
it("previous wraps from the start to the last match, skipping the selected one", () => {
const v = make("ab ab ab", { search: "ab" });
v.dispatch({ selection: { anchor: 0, head: 2 } });
findPrevious(v);
expect(sel(v)).toEqual([6, 8]);
findPrevious(v);
expect(sel(v)).toEqual([3, 5]);
const only = make("x ab", { search: "ab" });
only.dispatch({ selection: { anchor: 2, head: 4 } });
expect(findPrevious(only)).toBe(false);
expect(sel(only)).toEqual([2, 4]);
expect(findPrevious(make("x", { search: "ab" }))).toBe(false);
});
});
describe("search context, exclude and preserve case", () => {
const lang = StreamLanguage.define<null>({
token(stream) {
+31 -5
View File
@@ -17,12 +17,12 @@ import {
type ChangeDesc,
type EditorState,
type Extension,
type SelectionRange,
} from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import {
SearchQuery,
findNext as cmFindNext,
findPrevious as cmFindPrevious,
getSearchQuery,
replaceAll as cmReplaceAll,
replaceNext as cmReplaceNext,
@@ -240,15 +240,21 @@ export interface FindQueryOptions extends FindOptions {
inChanges?: boolean;
}
/** The characters a regular expression treats as syntax (`-` only inside a class, which never opens here). */
const REGEX_SYNTAX = /[\\^$.*+?()[\]{}|/]/g;
export function makeQuery(o: FindQueryOptions) {
// CodeMirror compares a plain-text query one character at a time; the same text as an escaped
// regular expression runs on the engine's matcher, over 20× faster in a large file, so every
// keystroke in the bar stays responsive. Its replacement escapes `$` to stay literal too.
return new SearchQuery({
search: o.search,
search: o.regexp ? o.search : o.search.replace(REGEX_SYNTAX, "\\$&"),
// Plain-text search and replace are literal (`\n` is not a newline), as in IDEA.
literal: !o.regexp,
caseSensitive: o.caseSensitive,
wholeWord: o.wholeWord,
regexp: o.regexp,
replace: o.replace,
regexp: true,
replace: o.regexp ? o.replace : o.replace.replaceAll("$", "$$$$"),
test: testFor(o.context ?? "any", !!o.inChanges),
});
}
@@ -345,8 +351,28 @@ export function findNext(view: EditorView): boolean {
return view.state.field(findScope, false) ? step(view, true) : cmFindNext(view);
}
/** The last match in `from`–`to` other than `skip`. */
function lastMatch(state: EditorState, from: number, to: number, skip?: SelectionRange): Match | null {
const cursor = getSearchQuery(state).getCursor(state, from, to);
let last: Match | null = null;
for (let r = cursor.next(); !r.done; r = cursor.next())
if (!skip || r.value.from !== skip.from || r.value.to !== skip.to) last = r.value as Match;
return last;
}
/**
* The match before the selection, wrapping to the end. CodeMirror finds it by scanning ever larger
* chunks backwards, quadratic in the distance to the match; one forward pass is linear.
*/
export function findPrevious(view: EditorView): boolean {
return view.state.field(findScope, false) ? step(view, false) : cmFindPrevious(view);
const { state } = view;
if (state.field(findScope, false)) return step(view, false);
if (!getSearchQuery(state).valid) return false;
const main = state.selection.main;
const m = lastMatch(state, 0, main.from) ?? lastMatch(state, main.from, state.doc.length, main);
if (!m) return false;
selectMatch(view, m);
return true;
}
/** The text replacing `m`, keeping its case when `preserve` is set. */
+21 -5
View File
@@ -21,20 +21,36 @@ const target: Location = {
range: { start: { line: 3, col: 4 }, end: { line: 3, col: 9 } },
};
const views: EditorView[] = [];
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n") {
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n", path = `/p/${doc}.${language}`) {
const view = new EditorView({
state: EditorState.create({
doc: text,
extensions: [
lspDoc.of({ doc, path: `/p/${doc}.${language}`, language, uiMode: language, readOnly: false }),
navigationExtension(),
],
extensions: [lspDoc.of({ doc, path, language, uiMode: language, readOnly: false }), navigationExtension()],
}),
parent: document.body,
});
views.push(view);
return view;
}
it("uses the whole Maven element value for the navigation underline", () => {
const text = " <artifactId>cdf-parent</artifactId>\n <version>${revision}</version>";
const view = editor(1, "xml", text, "/p/pom.xml");
const parent = text.indexOf("cdf-parent");
for (const offset of [parent, parent + 3, parent + 4, parent + "cdf-parent".length]) {
const range = navigationWord(view, offset)!;
expect(view.state.sliceDoc(range.from, range.to)).toBe("cdf-parent");
}
const revision = text.indexOf("${revision}");
const range = navigationWord(view, revision + 4)!;
expect(view.state.sliceDoc(range.from, range.to)).toBe("${revision}");
const multiline = "<artifactId>\n cdf-parent\n </artifactId>";
const multilineView = editor(2, "xml", multiline, "/p/multiline/pom.xml");
const multilineRange = navigationWord(multilineView, multiline.indexOf("parent"))!;
expect(multilineView.state.sliceDoc(multilineRange.from, multilineRange.to)).toBe("cdf-parent");
});
let off: () => void;
beforeEach(() => {
vi.useFakeTimers();
+54 -2
View File
@@ -5,6 +5,7 @@
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { onEditorEvent } from "@/editor/api";
import { isMavenPom } from "@/platform/buildFiles";
import { commands, IpcError, onIdeEvent, type GotoKind, type Location } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { onServerSettled } from "./availability";
@@ -54,9 +55,60 @@ export function isConfigurationDocument(view: EditorView): boolean {
return language === "yaml" || language === "properties";
}
/** Configuration names include hyphens and dots even when the editor's
* language word rules split them. Share this range between decoration and lookup. */
const XML_VALUE_SCAN_LINES = 256;
/** The text of the XML element, trimmed to the value itself. */
function pomElementValueAt(view: EditorView, offset: number): { from: number; to: number } | null {
const doc = view.state.doc;
const line = doc.lineAt(offset);
let open = -1;
const onLine = line.text.lastIndexOf(">", offset - line.from);
if (onLine >= 0) open = line.from + onLine;
else {
for (let number = line.number - 1; number >= 1 && line.number - number <= XML_VALUE_SCAN_LINES; number--) {
const previous = doc.line(number);
const col = previous.text.lastIndexOf(">");
if (col >= 0) {
open = previous.from + col;
break;
}
}
}
if (open < 0 || offset <= open) return null;
const afterOpen = doc.lineAt(Math.min(open + 1, doc.length));
let close = -1;
for (
let number = afterOpen.number;
number <= doc.lines && number - afterOpen.number <= XML_VALUE_SCAN_LINES;
number++
) {
const current = doc.line(number);
const col = current.text.indexOf("<", number === afterOpen.number ? open + 1 - current.from : 0);
if (col >= 0) {
close = current.from + col;
break;
}
}
if (close < 0 || offset > close) return null;
let from = open + 1;
let to = close;
const raw = doc.sliceString(from, to);
from += raw.length - raw.trimStart().length;
to -= raw.length - raw.trimEnd().length;
return from < to ? { from, to } : null;
}
/** Configuration names include hyphens and dots even when the editor's language word
* rules split them. Maven element values use the whole value (`cdf-parent`, not its
* hyphenated words). Share this range between decoration and lookup. */
export function navigationWord(view: EditorView, offset: number): { from: number; to: number } | null {
const doc = docOf(view);
if (doc && isMavenPom(doc.path)) {
const value = pomElementValueAt(view, offset);
if (value) return value;
}
if (!isConfigurationDocument(view)) return view.state.wordAt(offset);
const line = view.state.doc.lineAt(offset);
const nameChar = /[\p{L}\p{N}_.$-]/u;
+3 -4
View File
@@ -35,7 +35,7 @@ import { basename } from "@/platform/project";
import { iconNode } from "@/ui/iconNode";
import { applyCodeAction, quickFixesAt } from "./intentions";
import { editorPrefs } from "@/platform/editorSettings";
import { CONTRIBUTED_HOVER, contributedAt, type ContributedHover } from "@/editor/api";
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
import { languageSemantics } from "./semantic";
@@ -47,10 +47,9 @@ function constructAt(state: EditorView["state"], pos: number, language: string |
}
export async function requestHover(view: EditorView, pos: number): Promise<Hover | null> {
const own = contributedAt<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos);
if (own) {
for (const own of contributedAtAll<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos)) {
const h = own(view.state, pos);
if (!h) return null;
if (!h) continue;
const range = { start: offsetToPos(view.state.doc, h.from), end: offsetToPos(view.state.doc, h.to) };
return { contents: { kind: "markdown", value: h.markdown }, range };
}
+10 -4
View File
@@ -46,8 +46,8 @@ import {
} from "@/platform/ipc";
import {
CONTRIBUTED_DEFINITION,
contributedAtAll,
activeEditor,
contributedAt,
whenSynced,
type ContributedDefinition,
type EditorDocContext,
@@ -444,8 +444,12 @@ async function gotoResolved(
done: () => void,
) {
if (kind === "definition" || kind === "declaration") {
const own = contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
if (own?.(view, offset)) return;
// More than one feature can attach a definition provider to the same file (the
// MyBatis SQL support and the Maven POM navigator both see XML). Providers decline
// positions they do not own, so try every one instead of letting the first false
// result hide the real target.
const own = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
if (own.some((definition) => definition(view, offset))) return;
if (showPhpConstructDocumentation(view, offset)) return;
const before = view.state.doc;
const plugin = await contributedNavigation(view, offset).catch(() => null);
@@ -873,7 +877,9 @@ async function probeNavigation(
const plugin = await contributedNavigation(view, offset).catch(() => null);
if (plugin) return { info: null, plugin };
const doc = docOf(view);
let navigable = !!contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
let navigable = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset).some(
(definition) => definition.canHandle?.(view.state, offset) ?? true,
);
if (!navigable && doc) {
const pos = offsetToPos(view.state.doc, offset);
let fromSyntax = false;
+50 -1
View File
@@ -1,6 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import {
CONTRIBUTED_DEFINITION,
CONTRIBUTED_HOVER,
type ContributedDefinition,
type ContributedHover,
} from "@/editor/api";
import type { commands, Location } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { resetNavigationModifier } from "@/platform/navigationModifier";
@@ -18,7 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const { gotoTargets, navigationExtension } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { quickDefinition } = await import("./hover");
const { quickDefinition, requestHover } = await import("./hover");
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
const { closePopup } = await import("./popupStore");
const { provideEditorService } = await import("@/workbench/contributions");
@@ -97,6 +103,49 @@ afterEach(() => {
vi.restoreAllMocks();
});
it("tries a later contributed definition when an earlier provider declines", async () => {
const declined = vi.fn<ContributedDefinition>(() => false);
const handled = vi.fn<ContributedDefinition>((_view, _pos) => {
openFile("/p/Handled.java", {});
return true;
});
view = new EditorView({
state: EditorState.create({
doc: "maven",
extensions: [
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: declined }]),
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: handled }]),
],
}),
parent: document.body,
});
await gotoTargets(view, "definition", 0);
expect(declined).toHaveBeenCalledOnce();
expect(handled).toHaveBeenCalledOnce();
expect(openFile).toHaveBeenCalledWith("/p/Handled.java", {});
expect(lspGoto).not.toHaveBeenCalled();
});
it("tries a later contributed hover when an earlier provider declines", async () => {
const declined = vi.fn<ContributedHover>(() => null);
const handled = vi.fn<ContributedHover>(() => ({ from: 1, to: 3, markdown: "handled" }));
view = new EditorView({
state: EditorState.create({
doc: "maven",
extensions: [
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: declined }]),
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: handled }]),
],
}),
parent: document.body,
});
expect((await requestHover(view, 1))?.contents.value).toBe("handled");
expect(declined).toHaveBeenCalledOnce();
expect(handled).toHaveBeenCalledOnce();
});
describe.each(cases)("shared definition requests in $language", (c) => {
it("lets a click reuse the hover probe's request for the same word", async () => {
editor(c);
+17 -2
View File
@@ -6,6 +6,8 @@
import { createElement } from "react";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { clearContext, setContext } from "@/platform/context";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { executeAction } from "@/platform/actions";
import { lazyComponent, lazyWhen } from "@/ui";
import { isVirtualUri } from "@/platform/virtualDocs";
@@ -47,6 +49,18 @@ import { replyActions } from "./replyActions";
export { activateSettingsPages } from "./settingsPages";
function trackAgentButtonSetting(): () => void {
setContext("commitAgentButton", workflowSettings().vcs.commit.agentButton);
const stop = onWorkflowSettingsChange(
(s) => s.vcs.commit.agentButton,
(on) => setContext("commitAgentButton", on),
);
return () => {
stop();
clearContext("commitAgentButton");
};
}
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
disconnect();
@@ -153,12 +167,13 @@ export function activate(): () => void {
accepts: (type) => type === TASK_DRAG,
drop: ({ payload }) => void executeAction("agents.openTaskInEditor", payload),
}),
// The button above the commit message (the Commit tool window and dialog).
// The button above the commit message (the Commit tool window and dialog), unless turned off.
trackAgentButtonSetting(),
registerMenuSlotItem("commitMessage", {
action: "agents.generateCommitMessage",
label: "Generate Commit Message with Agent",
icon: "toolwindow-agents",
when: "projectOpen && vcsAvailable",
when: "projectOpen && vcsAvailable && commitAgentButton",
}),
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
registerMenuGroup({
@@ -0,0 +1,18 @@
/* IDEA's Navigate to Managing Dependency icon in the shared editor icon area. */
.managedMarker {
width: 14px;
height: 14px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: var(--radius-small);
background: transparent;
cursor: pointer;
}
.managedMarker:hover,
.managedMarker:focus-visible {
background: var(--bg-hover);
}
+87 -7
View File
@@ -1,10 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
const ipc = vi.hoisted(() => ({ mavenGotoDeclaration: vi.fn() }));
const ipc = vi.hoisted(() => ({
mavenGotoDeclaration: vi.fn(),
mavenManagedDeclarations: vi.fn(),
cancelRequest: vi.fn(),
}));
const workbench = vi.hoisted(() => ({ openFile: vi.fn() }));
const hints = vi.hoisted(() => ({ showHint: vi.fn() }));
vi.mock("@/platform/ipc", () => ({
isTauri: () => false,
isCancelled: () => false,
nextRequestId: () => 7,
onIdeEvent: () => () => {},
call: async (p: Promise<{ status: string; data?: unknown; error?: unknown }>) => {
const r = await p;
if (r.status !== "ok") throw r.error;
@@ -16,15 +25,25 @@ vi.mock("@/workbench/contributions", () => ({
editorService: () => workbench,
}));
vi.mock("@/editor/lsp/hint", () => ({ showHint: hints.showHint }));
vi.mock("@/editor/api", () => ({
CONTRIBUTED_DEFINITION: "openideaDefinition",
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/api")>()),
whenSynced: () => Promise.resolve(),
}));
import { EditorState } from "@codemirror/state";
import { inArtifactElement, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import type { ContributedDefinition } from "@/editor/api";
import { inArtifactElement, placeManagedMarks, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
const DEFINITION = "openideaDefinition";
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
vi.clearAllMocks();
});
/** An editor state over `text` with the contribution for `path` installed. */
function state(text: string, path = "/p/app/pom.xml") {
@@ -32,20 +51,22 @@ function state(text: string, path = "/p/app/pom.xml") {
doc: text,
extensions: [
pomNavigationExtension({
doc: 1,
path,
language: "xml",
uiMode: "XML",
readOnly: false,
} as Parameters<typeof pomNavigationExtension>[0]),
iconAreaExtension,
],
});
}
const definitionAt = (s: ReturnType<typeof state>, pos: number) =>
s.languageDataAt<(v: { state: typeof s }, p: number) => boolean>(DEFINITION, pos)[0];
s.languageDataAt<ContributedDefinition>(DEFINITION, pos)[0];
/** The definition only reads `view.state`; a bare handle is enough. */
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s }, pos);
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s } as EditorView, pos);
const pom = `<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
@@ -130,6 +151,13 @@ describe("POM go to declaration", () => {
expect(definitionAt(s, pom.indexOf("<parent>"))).toBeUndefined();
});
it("declines non-navigation POM positions without invoking the definition", () => {
const s = state(pom);
const definition = definitionAt(s, pom.indexOf("<artifactId>other-lib"))!;
expect(definition.canHandle?.(s, pom.indexOf("<artifactId>other-lib"))).toBe(true);
expect(definition.canHandle?.(s, pom.indexOf("<modelVersion>"))).toBe(false);
});
it("opens the declaration the backend resolved", async () => {
const target = {
path: "/p/pom.xml",
@@ -152,6 +180,58 @@ describe("POM go to declaration", () => {
});
});
it("places one managed-dependency marker per backend line", () => {
const s = state(pom);
const target = {
path: "/p/pom.xml",
range: { start: { line: 1, col: 2 }, end: { line: 1, col: 8 } },
kind: "managedDependency" as const,
label: "com.example:other-lib",
};
expect(
placeManagedMarks(s.doc, [
{ line: 15, version: "1.2.3", target },
{ line: 15, version: "ignored", target },
{ line: 999, version: null, target },
]),
).toEqual([{ pos: s.doc.line(16).from, link: { line: 15, version: "1.2.3", target } }]);
});
it("opens the managing declaration from its gutter icon", async () => {
const target = {
path: "/p/pom.xml",
range: { start: { line: 4, col: 6 }, end: { line: 4, col: 14 } },
kind: "managedDependency" as const,
label: "com.example:other-lib",
};
ipc.mavenManagedDeclarations.mockResolvedValue({
status: "ok",
data: [
{ line: pom.slice(0, pom.indexOf("<artifactId>other-lib")).split("\n").length - 1, version: "1.0", target },
],
});
view = new EditorView({ state: state(pom), parent: document.body });
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledWith("/p/app/pom.xml", 7));
await vi.waitFor(() => expect(view!.dom.querySelector("[data-managed-dependency]")).not.toBeNull());
fireEvent.click(view.dom.querySelector("[data-managed-dependency]")!);
await vi.waitFor(() =>
expect(workbench.openFile).toHaveBeenCalledWith("/p/pom.xml", {
selection: { line: 4, col: 6, endLine: 4, endCol: 14 },
}),
);
});
it("cancels an in-flight gutter refresh when the document changes", async () => {
let finish!: (value: unknown) => void;
ipc.mavenManagedDeclarations.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
view = new EditorView({ state: state(pom), parent: document.body });
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledOnce());
view.dispatch({ changes: { from: 0, insert: " " } });
await vi.waitFor(() => expect(ipc.cancelRequest).toHaveBeenCalledWith(7));
finish({ status: "ok", data: [] });
});
it("says so when nothing resolves, without navigating", async () => {
ipc.mavenGotoDeclaration.mockResolvedValue({ status: "ok", data: null });
const s = state(pom);
+224 -23
View File
@@ -2,21 +2,41 @@
* Go to declaration in `pom.xml`: ⌘/Ctrl-click (or ⌘B) on a `${property}` reference
* opens the `<properties>` entry that defines it — the POM's own, else one inherited
* along the parent chain (a parent POM outside the project opens from the local
* repository, read-only as a plain file) — and a dependency / plugin whose version a
* `<dependencyManagement>` / `<pluginManagement>` entry provides opens that managing
* declaration; otherwise a dependency, plugin or `<parent>` opens the artifact's own POM
* (a project module's, else the local repository's). The backend resolves both with the build model's POM reader and parent
* resolver; here only cheap eligibility is computed (a reference span, an artifact
* element), so the ⌘-hover underline stays out of the rest of the file, and nothing
* resolves to no jump at all: an unresolvable property or parent never navigates
* somewhere unrelated.
* repository, read-only as a plain file). A dependency, plugin or `<parent>` opens the
* artifact's own POM (a project module first, then the local repository). Unversioned
* declarations also get IDEA's "Navigate to managing dependency" gutter icon, which
* opens the exact `<dependencyManagement>` / `<pluginManagement>` entry — including
* one in a parent POM or imported BOM — that controls the version. The backend does
* the resolution; here only cheap eligibility is computed, so the ⌘-hover underline
* stays out of the rest of the file and no marker promises a target that does not exist.
*/
import { EditorState, type Extension } from "@codemirror/state";
import { CONTRIBUTED_DEFINITION, type ContributedDefinition, type EditorDocContext, whenSynced } from "@/editor/api";
import { EditorState, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import {
CONTRIBUTED_DEFINITION,
iconAreaSource,
mapLineStart,
onEditorEvent,
whenSynced,
type ContributedDefinition,
type EditorDocContext,
} from "@/editor/api";
import { showHint } from "@/editor/lsp/hint";
import { isMavenPom } from "@/platform/buildFiles";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import {
call,
commands,
isCancelled,
nextRequestId,
onIdeEvent,
type PomGoto,
type PomManagedDeclaration,
type RequestId,
} from "@/platform/ipc";
import { gutterIconMarkup } from "@/ui";
import { editorService } from "@/workbench/contributions";
import styles from "./PomNavigation.module.css";
/** The `${property}` reference covering `at`, if any (clicking the `$` counts). */
export function propertyRefAt(text: string, at: number): { from: number; to: number } | null {
@@ -43,9 +63,193 @@ export function inArtifactElement(text: string, at: number): boolean {
return inside("dependency", text, at) || inside("plugin", text, at) || inside("parent", text, at);
}
export interface ManagedMark {
pos: number;
link: PomManagedDeclaration;
}
/** Places the backend's 0-based lines in a document, one icon per declaration line. */
export function placeManagedMarks(doc: Text, links: readonly PomManagedDeclaration[]): ManagedMark[] {
const seen = new Set<number>();
const out: ManagedMark[] = [];
for (const link of links) {
if (!Number.isInteger(link.line) || link.line < 0 || link.line >= doc.lines || seen.has(link.line)) continue;
seen.add(link.line);
out.push({ pos: doc.line(link.line + 1).from, link });
}
return out;
}
const setManagedMarks = StateEffect.define<ManagedMark[]>();
const managedMarksField = StateField.define<ManagedMark[]>({
create: () => [],
update(value, tr) {
for (const effect of tr.effects) if (effect.is(setManagedMarks)) return effect.value;
if (!tr.docChanged || !value.length) return value;
return value.map((mark) => ({ ...mark, pos: mapLineStart(tr, mark.pos) }));
},
});
const fileName = (path: string) => path.split(/[\\/]/).pop() || path;
function managedTitle(link: PomManagedDeclaration): string {
const location = `${fileName(link.target.path)}:${link.target.range.start.line + 1}`;
return link.version ? tx`Managed version ${link.version} in ${location}` : tx`Managed in ${location}`;
}
class ManagedMarker extends GutterMarker {
constructor(
readonly mark: ManagedMark,
readonly open: () => void,
) {
super();
}
override eq(other: GutterMarker): boolean {
const a = this.mark.link;
const b = other instanceof ManagedMarker ? other.mark.link : null;
return (
!!b &&
a.version === b.version &&
a.target.path === b.target.path &&
a.target.range.start.line === b.target.range.start.line &&
a.target.range.start.col === b.target.range.start.col
);
}
override toDOM(): Node {
const button = document.createElement("button");
button.type = "button";
button.className = styles.managedMarker ?? "";
button.dataset.managedDependency = "";
button.title = managedTitle(this.mark.link);
button.setAttribute("aria-label", button.title);
button.innerHTML = gutterIconMarkup("gutter-navigate") ?? "";
// Keep the editor caret where it was; a normal click then runs the navigation,
// so the icon also works from the keyboard.
button.addEventListener("mousedown", (event) => {
event.preventDefault();
event.stopPropagation();
});
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.open();
});
return button;
}
}
function openGoto(goto: PomGoto): Promise<void> | void {
return editorService().openFile(goto.path, {
selection: {
line: goto.range.start.line,
col: goto.range.start.col,
endLine: goto.range.end.line,
endCol: goto.range.end.col,
},
});
}
function openManaged(view: EditorView, target: PomGoto): void {
void Promise.resolve(openGoto(target)).catch((e: unknown) =>
showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" }),
);
}
/** The icon area is shared with run, inheritance and plugin markers; press handling is source-scoped. */
function managedGutter(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
return [
managedMarksField,
ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
private generation = 0;
private inFlight: RequestId | undefined;
private off: () => void;
constructor(readonly view: EditorView) {
this.schedule(0);
const offEditor = onEditorEvent((event) => {
if (
(event.type === "docChanged" || event.type === "docSaved") &&
event.path !== ctx.path &&
isMavenPom(event.path)
)
this.schedule(500);
});
const offFiles = onIdeEvent("fsChanged", (event) => {
if ([...event.created, ...event.modified, ...event.removed].some(isMavenPom)) this.schedule(500);
});
const offRoots = onIdeEvent("projectRootsChanged", () => this.schedule(300));
const offSettings = onIdeEvent("settingsChanged", (event) => {
if (event.key.startsWith("languages.java.")) this.schedule(300);
});
this.off = () => {
offEditor();
offFiles();
offRoots();
offSettings();
};
}
update(update: ViewUpdate) {
if (update.docChanged) this.schedule();
}
schedule(delay = 300) {
clearTimeout(this.timer);
if (this.inFlight !== undefined) {
void commands.cancelRequest(this.inFlight);
this.inFlight = undefined;
}
this.timer = setTimeout(() => void this.refresh(), delay);
}
async refresh() {
const generation = ++this.generation;
const current = this.view.state.doc;
const request = nextRequestId();
this.inFlight = request;
try {
await whenSynced(this.view);
if (generation !== this.generation || this.view.state.doc !== current) return;
const links = await call(commands.mavenManagedDeclarations(ctx.path, request));
if (generation !== this.generation || this.inFlight !== request || this.view.state.doc !== current) return;
this.view.dispatch({ effects: setManagedMarks.of(placeManagedMarks(current, links)) });
} catch (e) {
if (!isCancelled(e) && generation === this.generation) console.debug("[POM managed dependencies]", e);
} finally {
if (this.inFlight === request) this.inFlight = undefined;
}
}
destroy() {
this.off();
clearTimeout(this.timer);
if (this.inFlight !== undefined) void commands.cancelRequest(this.inFlight);
this.generation++;
}
},
),
iconAreaSource.of({
order: 25,
markers: (view) =>
RangeSet.of(
view.state
.field(managedMarksField)
.map((mark) => new ManagedMarker(mark, () => openManaged(view, mark.link.target)).range(mark.pos)),
true,
),
}),
];
}
/** Go to declaration in a POM of the project (or an opened parent POM of the local repository). */
export function pomNavigationExtension(ctx: EditorDocContext): Extension {
if (ctx.virtual || !/(^|\/)pom\.xml$/.test(ctx.path)) return [];
if (ctx.virtual || !isMavenPom(ctx.path)) return [];
const eligible = (state: EditorState, pos: number) => {
const text = state.doc.toString();
return propertyRefAt(text, pos) !== null || inArtifactElement(text, pos);
@@ -69,14 +273,7 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
return;
}
if (view.state.doc !== doc) return; // The user kept typing while the POM resolved.
void editorService().openFile(goto.path, {
selection: {
line: goto.range.start.line,
col: goto.range.start.col,
endLine: goto.range.end.line,
endCol: goto.range.end.col,
},
});
void openGoto(goto);
})
.catch((e: unknown) =>
showHint(view, e instanceof Error ? e.message : String(e), {
@@ -85,7 +282,11 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
);
return true;
};
return EditorState.languageData.of((state, pos) =>
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
);
definition.canHandle = eligible;
return [
EditorState.languageData.of((state, pos) =>
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
),
managedGutter(ctx),
];
}
+4 -1
View File
@@ -108,7 +108,7 @@ function inspections(path: string, sql: SqlText): Extension {
}
function definition(path: string, sql: SqlText): ContributedDefinition {
return (view, pos) => {
const handle: ContributedDefinition = (view, pos) => {
if (sql.at && !sql.at(view.state, pos)) return false;
const r = resolver(path, view.state, sql).resolveAt(pos);
const sym = r?.symbol;
@@ -143,6 +143,9 @@ function definition(path: string, sql: SqlText): ContributedDefinition {
return true;
}
};
const at = sql.at;
if (at) handle.canHandle = (state, pos) => at(state, pos);
return handle;
}
const code = (s: string) => `\`${s.replace(/`/g, "")}\``;
+7 -8
View File
@@ -33,6 +33,7 @@ import {
} from "@/ui";
import { useContributions, type RunConfigTypeContribution } from "@/workbench/contributions";
import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch";
import { ExpandableTextarea } from "./ExpandableTextarea";
import {
commandLine,
compoundCycle,
@@ -817,7 +818,6 @@ function TypeField({
invalid: boolean;
onChange: (value: string) => void;
}) {
const tx = useTx();
const root = useProject((s) => s.project?.root ?? null);
const listId = `run-field-${field.key}`;
const [loaded, setLoaded] = useState<ReadonlyArray<{ value: string; label: string; detail?: string }>>([]);
@@ -848,14 +848,13 @@ function TypeField({
return <Checkbox checked={value === "true"} onChange={(on) => onChange(on ? "true" : "")} label={field.label} />;
if (field.control === "textarea")
return (
<textarea
className={clsx(styles.textarea, invalid && styles.textareaInvalid)}
aria-label={tx(field.label)}
spellCheck={false}
<ExpandableTextarea
label={field.label}
value={value}
placeholder={tx(field.placeholder)}
rows={field.rows ?? 4}
onChange={(e) => onChange(e.target.value)}
placeholder={field.placeholder}
rows={field.rows}
invalid={invalid}
onChange={onChange}
/>
);
const suggestions = field.suggestions?.(all, params) ?? [];
@@ -0,0 +1,37 @@
import { afterEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { ExpandableTextarea } from "./ExpandableTextarea";
afterEach(cleanup);
const LONG = "-Ddemo.endpoint=https://example.com/demo/environments/local/feature-flags/configuration/versions/current";
const VALUE = `-Xmx512m\n${LONG}\n-Ddemo.mode=local`;
function editors() {
return screen.getAllByRole("textbox", { name: "VM options" }) as HTMLTextAreaElement[];
}
it("edits in an expanded editor that keeps each line on one visual line", () => {
const onChange = vi.fn();
render(<ExpandableTextarea label="VM options" value={VALUE} onChange={onChange} />);
fireEvent.click(screen.getByRole("button", { name: "Expand (⇧⏎)" }));
const expanded = editors()[1]!;
expect(expanded.value).toBe(VALUE);
expect(expanded.getAttribute("wrap")).toBe("off");
fireEvent.change(expanded, { target: { value: `${VALUE}\n-Dextra=1` } });
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(onChange).toHaveBeenCalledWith(`${VALUE}\n-Dextra=1`);
expect(editors()).toHaveLength(1);
});
it("leaves the value alone on Cancel or OK without edits, and opens with Shift+Enter", () => {
const onChange = vi.fn();
render(<ExpandableTextarea label="VM options" value={VALUE} onChange={onChange} />);
fireEvent.keyDown(editors()[0]!, { key: "Enter", shiftKey: true });
fireEvent.change(editors()[1]!, { target: { value: "-Xmx1g" } });
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(editors()).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Expand (⇧⏎)" }));
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(onChange).not.toHaveBeenCalled();
});
+100
View File
@@ -0,0 +1,100 @@
import { useState } from "react";
import clsx from "clsx";
import { useTx } from "@/platform/i18n";
import { Dialog, IconButton } from "@/ui";
import styles from "./Run.module.css";
/**
* A run configuration's multi-line field (VM options, say) with an Expand button (⇧⏎) that
* edits it in a larger editor where each line stays on one visual line and scrolls sideways,
* so one long argument isn't mistaken for several.
*/
export function ExpandableTextarea({
label,
value,
placeholder,
rows,
invalid,
onChange,
}: {
label: string;
value: string;
placeholder?: string;
rows?: number;
invalid?: boolean;
onChange: (value: string) => void;
}) {
const tx = useTx();
const [expanded, setExpanded] = useState(false);
return (
<div className={styles.textareaWithButton}>
<textarea
className={clsx(styles.textarea, invalid && styles.textareaInvalid)}
aria-label={tx(label)}
spellCheck={false}
value={value}
placeholder={tx(placeholder)}
rows={rows ?? 4}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey) {
e.preventDefault();
setExpanded(true);
}
}}
/>
<IconButton icon="expand-all" size="small" iconSize={14} title="Expand (⇧⏎)" onClick={() => setExpanded(true)} />
{expanded && (
<ExpandedTextDialog label={label} value={value} onOk={onChange} onClose={() => setExpanded(false)} />
)}
</div>
);
}
function ExpandedTextDialog({
label,
value,
onOk,
onClose,
}: {
label: string;
value: string;
onOk: (value: string) => void;
onClose: () => void;
}) {
const tx = useTx();
const [text, setText] = useState(value);
return (
<Dialog
open
title={tx(label)}
onClose={onClose}
width={720}
resizable="both"
minWidth={360}
minHeight={220}
buttons={[
{
label: "OK",
role: "default",
onClick: () => {
if (text !== value) onOk(text);
onClose();
},
},
{ label: "Cancel", role: "cancel" },
]}
>
<textarea
className={clsx(styles.textarea, styles.expandedTextarea)}
aria-label={tx(label)}
spellCheck={false}
wrap="off"
rows={14}
value={text}
autoFocus
onChange={(e) => setText(e.target.value)}
/>
</Dialog>
);
}
+23
View File
@@ -848,6 +848,29 @@
font-size: var(--fs-ui);
outline: none;
}
.textareaWithButton {
display: flex;
align-items: flex-start;
gap: var(--space-1-5);
min-width: 0;
}
.textareaWithButton > textarea {
flex: 1;
min-width: 0;
}
.textareaWithButton > button {
flex-shrink: 0;
}
/* One visual line per line of text: a long argument scrolls instead of wrapping. */
.expandedTextarea {
width: 100%;
height: 100%;
min-height: 160px;
box-sizing: border-box;
resize: none;
white-space: pre;
overflow: auto;
}
.textarea:focus {
box-shadow: inset 0 0 0 1px var(--focus-ring);
}
@@ -200,4 +200,5 @@ describe("appearance & behavior settings", () => {
it("loads an old attach setting as ask", () => {
expect(validateGeneralExtras({ openProjectIn: "attach" }).openProjectIn).toBe("ask");
expect(validateGeneralExtras({ openProjectIn: "tab" }).openProjectIn).toBe("tab");
});
@@ -10,7 +10,7 @@ import { ZOOM_LIMITS } from "@/platform/zoom";
import { validateIconThemeOptionsMap } from "@/platform/iconThemeOptions";
export type Antialiasing = "subpixel" | "greyscale" | "none";
export type OpenProjectIn = "ask" | "new" | "same";
export type OpenProjectIn = "ask" | "new" | "same" | "tab";
export type NotificationDisplay = "balloon" | "sticky" | "none";
export type NavigationBarPosition = "top" | "statusBar" | "hidden";
export type BackgroundImageFill = "scale" | "plain" | "tile";
@@ -306,7 +306,7 @@ export function validateGeneralExtras(raw: unknown): GeneralExtras {
const d = DEFAULT_GENERAL_EXTRAS;
const df = obj(g.dateFormat);
return {
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same"] as const, d.openProjectIn),
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same", "tab"] as const, d.openProjectIn),
updateSource: oneOf(g.updateSource, ["auto", "github", "cnb"] as const, d.updateSource),
autoCheckUpdates: bool(g.autoCheckUpdates, d.autoCheckUpdates),
showWhatsNewAfterUpdate: bool(g.showWhatsNewAfterUpdate, d.showWhatsNewAfterUpdate),
+1
View File
@@ -575,6 +575,7 @@ function ToolWindowsGrid() {
const OPEN_IN: Array<{ value: OpenProjectIn; label: string }> = [
{ value: "new", label: "New window" },
{ value: "same", label: "Current window" },
{ value: "tab", label: "New tab in current window" },
{ value: "ask", label: "Ask" },
];
+5
View File
@@ -643,6 +643,11 @@ export const VCS_PAGES: PageSpec[] = [
{
title: "Commit Message Generation",
options: [
{
kind: "toggle",
key: "vcs.commit.agentButton",
label: "Show the Generate Commit Message with Agent button",
},
{
kind: "custom",
label: "Agent",
+5
View File
@@ -4,3 +4,8 @@ export function isGradleBuildInput(path: string): boolean {
path,
);
}
/** A project POM or a POM installed in the local Maven repository. */
export function isMavenPom(path: string): boolean {
return /(^|[\\/])(?:pom\.xml|[^\\/]+\.pom)$/i.test(path);
}
+5 -1
View File
@@ -2265,6 +2265,7 @@
"Finished": "Finished",
"Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.",
"Generate Commit Message with Agent": "Generate Commit Message with Agent",
"Show the Generate Commit Message with Agent button": "Show the Generate Commit Message with Agent button",
"Has the coding agent you work with review the changes about to be committed and write the commit message.": "Has the coding agent you work with review the changes about to be committed and write the commit message.",
"No changes to describe": "No changes to describe",
"Include changes in the commit first.": "Include changes in the commit first.",
@@ -2632,6 +2633,7 @@
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
"New Tab": "New Tab",
"New tab in current window": "New tab in current window",
"Show Only Widgets": "Show Only Widgets",
"Update failed": "Update failed",
"Updating branches": "Updating branches",
@@ -2728,5 +2730,7 @@
"Caret": "Caret",
"Code Structure": "Code Structure",
"Presentation": "Presentation",
"Code Assistance": "Code Assistance"
"Code Assistance": "Code Assistance",
"Managed version {version} in {location}": "Managed version {version} in {location}",
"Managed in {location}": "Managed in {location}"
}
+5 -1
View File
@@ -1911,6 +1911,7 @@
"New name": "新名称",
"New terminal sessions run the interpreter's virtualenv activate script.": "新的终端会话会运行解释器的 virtualenv 激活脚本。",
"New window": "新窗口",
"New tab in current window": "当前窗口的新标签页",
"New…": "新建…",
"Next Bookmark": "下一个书签",
"Next Change": "下一个更改",
@@ -8666,6 +8667,7 @@
"Exited with code {code}": "退出代码 {code}",
"Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "仅当标签页不可见时通知。用 Ctrl-C 停止的命令、shell 启动和短命令保持安静;非零退出始终报告退出代码。",
"Generate Commit Message with Agent": "使用智能体生成提交消息",
"Show the Generate Commit Message with Agent button": "显示“使用智能体生成提交消息”按钮",
"Has the coding agent you work with review the changes about to be committed and write the commit message.": "让您正在使用的编程智能体审查即将提交的更改并撰写提交消息。",
"No changes to describe": "没有可描述的更改",
"Include changes in the commit first.": "请先在提交中包含更改。",
@@ -9094,5 +9096,7 @@
"Remove All Watches": "移除所有监视",
"GitHub account": "GitHub 账号",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
"github-username": "GitHub 用户名"
"github-username": "GitHub 用户名",
"Managed version {version} in {location}": "版本 {version} 由 {location} 管理",
"Managed in {location}": "由 {location} 管理"
}
+4
View File
@@ -69,6 +69,8 @@ export interface CommitSettingsValid {
agentModel: string;
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort: string;
/** Show the Generate Commit Message with Agent button above the commit message. */
agentButton: boolean;
}
export interface VcsSettingsValid {
@@ -316,6 +318,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
agent: "",
agentModel: "",
agentEffort: "",
agentButton: true,
},
confirmation: {
onCreate: "ask",
@@ -488,6 +491,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
agent: text(c.agent, d.commit.agent),
agentModel: text(c.agentModel, d.commit.agentModel),
agentEffort: text(c.agentEffort, d.commit.agentEffort),
agentButton: bool(c.agentButton, d.commit.agentButton),
},
confirmation: {
onCreate: oneOf(conf.onCreate, confirm, d.confirmation.onCreate),
+13 -2
View File
@@ -23,7 +23,8 @@ beforeEach(() => {
lightEdit: false,
});
});
it.each(["attach", "tab"] as const)("offers %s for this open without remembering it", async (button) => {
it("offers attach for this open without remembering it", async () => {
const button = "attach";
vi.mocked(ask).mockResolvedValue({ button, checked: true });
expect(await chooseProjectWindow("B")).toBe(button);
const prompt = vi.mocked(ask).mock.calls[0]![0];
@@ -49,8 +50,18 @@ it("treats a stored attach policy as ask", () => {
useProject.setState({ settings: { general: { openProjectIn: "attach" } } } as never);
expect(openPolicy()).toBe("ask");
});
it.each(["new", "same"] as const)("remembers %s", async (mode) => {
it.each(["new", "same", "tab"] as const)("remembers %s", async (mode) => {
vi.mocked(ask).mockResolvedValue({ button: mode, checked: true });
await chooseProjectWindow("B");
expect(commands.settingsSet).toHaveBeenCalledWith("global", "general.openProjectIn", JSON.stringify(mode));
});
it("opens a project tab by policy, or a new window when this one can't take one", async () => {
useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never);
expect(openPolicy()).toBe("tab");
expect(await chooseProjectWindow("B")).toBe("tab");
expect(await chooseProjectWindow("remote", false)).toBe("new");
useProject.setState({ project: null, lightEdit: true });
expect(await chooseProjectWindow("B")).toBe("new");
expect(ask).not.toHaveBeenCalled();
});
+6 -4
View File
@@ -7,9 +7,9 @@ import { ask } from "./messages";
import { maybeEditorService } from "./contributions";
/** "Open project in": `new` | `same` | `ask`. */
export function openPolicy(): "ask" | "new" | "same" {
export function openPolicy(): "ask" | "new" | "same" | "tab" {
const v = useProject.getState().settings?.general?.openProjectIn;
return v === "new" || v === "same" ? v : "ask";
return v === "new" || v === "same" || v === "tab" ? v : "ask";
}
/**
@@ -26,6 +26,8 @@ export async function chooseProjectWindow(
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
const canAdd = allowAttach && !!project && !isRemoteWindow();
const mode = openPolicy();
// A project tab needs this window's project beside it; without one, a new window is the closest.
if (mode === "tab") return canAdd ? "tab" : "new";
if (mode !== "ask") return mode;
const r = await ask({
title: t("app.window.askTitle"),
@@ -46,9 +48,9 @@ export async function chooseProjectWindow(
],
checkbox: t("app.window.askRemember"),
});
// "Attach" and "New Tab" are one-off: "Open project in" has no value for them, so Don't ask again ignores both.
// "Attach" is one-off, as in IDEA: "Open project in" has no value for it, so Don't ask again ignores it.
if (r.button !== "same" && r.button !== "new" && r.button !== "attach" && r.button !== "tab") return null;
if (r.checked && (r.button === "same" || r.button === "new")) {
if (r.checked && r.button !== "attach") {
try {
useProject.setState({
settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(r.button))),