дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
11
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
bd87994559 | ||
|
|
4a620287c8 | ||
|
|
607812d8fa | ||
|
|
90f9d4ffd0 | ||
|
|
0f359ddf3b | ||
|
|
51a6b40314 | ||
|
|
bd5af356f4 | ||
|
|
d3cb8513be | ||
|
|
29d1a52d91 | ||
|
|
5b24b61b49 | ||
|
|
1dd8ea9b3b |
No files matched your search
@@ -79,6 +79,8 @@ pub struct JavaBuild<'a> {
|
||||
/// Changes when the jar does, so models recorded by an older extension are prepared again.
|
||||
pub jar_version: &'a str,
|
||||
pub local_repo: Option<PathBuf>,
|
||||
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
|
||||
pub ignored_maven_compile_goals: &'a [String],
|
||||
pub service: &'a JavaBuildService,
|
||||
/// The JDK home that compiles for a release, when Maven's environment names none.
|
||||
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
|
||||
@@ -558,7 +560,7 @@ impl JavaBuild<'_> {
|
||||
}
|
||||
};
|
||||
for (project, test) in &projects {
|
||||
if let Some(reason) = project.unsupported(*test) {
|
||||
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
|
||||
return Ok(Built::Unsupported(reason));
|
||||
}
|
||||
// A launch of a Java module runs it from the module path, which the language server reports.
|
||||
|
||||
@@ -105,13 +105,26 @@ impl ProjectModel {
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
// Keep the recorded model intact: adding or removing a project override must also
|
||||
// affect an already prepared model. Gradle tasks never use Maven overrides.
|
||||
let other_compilers: Vec<&str> = self
|
||||
.other_compilers
|
||||
.iter()
|
||||
.filter(|execution| {
|
||||
!(self.gradle_path.is_none()
|
||||
&& execution.split_once('@').is_some_and(|(goal, _)| {
|
||||
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
|
||||
}))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
|
||||
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
|
||||
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.other_compilers, project.other_compilers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
|
||||
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{jar}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
for unmatched in [
|
||||
"",
|
||||
"*",
|
||||
"org.apache.maven.plugins:maven-jar-plugin",
|
||||
"maven-jar-plugin:jar",
|
||||
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
|
||||
"org.apache.maven.plugins:*:jar",
|
||||
] {
|
||||
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
|
||||
}
|
||||
project.other_compilers.push(format!("{kotlin}@compile"));
|
||||
let reason = project.unsupported(false, &[jar.into()]).unwrap();
|
||||
assert!(reason.contains(kotlin));
|
||||
assert!(!reason.contains(jar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let ignored = [goal.into()];
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
project.gradle_path = Some(":app".into());
|
||||
assert!(project.unsupported(false, &ignored).is_some());
|
||||
project.gradle_path = None;
|
||||
project.problems.push("unresolved dependency".into());
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
|
||||
project.problems.clear();
|
||||
project.test_generators.push("org.example:generator:test@tests".into());
|
||||
assert_eq!(project.unsupported(false, &ignored), None);
|
||||
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
|
||||
project.test_generators.clear();
|
||||
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
|
||||
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
|
||||
project.main.compiler =
|
||||
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
@@ -169,6 +238,17 @@ impl Fixture {
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
match self.try_build(target, &[]) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
@@ -177,18 +257,12 @@ impl Fixture {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
@@ -213,6 +287,37 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
|
||||
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
|
||||
"<executions><execution><id>early-jar</id><phase>compile</phase>",
|
||||
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("lib/src/main/java/l/L.java", "package l; public class L {}"),
|
||||
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let module = f.root.join("app");
|
||||
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
f.steps();
|
||||
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
|
||||
assert!(output.failure.is_none(), "{:?}", output.messages);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(!f.root.join("app/target/app-1.jar").exists());
|
||||
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -583,6 +688,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals: &[],
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
|
||||
@@ -1430,6 +1430,10 @@ pub struct CustomColorScheme {
|
||||
pub struct EditorSettings {
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
|
||||
#[serde(deserialize_with = "code_insight_limit_mb")]
|
||||
#[specta(type = u8)]
|
||||
pub max_code_insight_file_size_mb: u8,
|
||||
pub line_height: f32,
|
||||
pub tab_size: u32,
|
||||
pub insert_spaces: bool,
|
||||
@@ -1483,11 +1487,23 @@ pub struct EditorSettings {
|
||||
pub encodings: EncodingSettings,
|
||||
}
|
||||
|
||||
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
|
||||
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
|
||||
|
||||
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
|
||||
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
|
||||
line_height: 22.0,
|
||||
tab_size: 4,
|
||||
insert_spaces: true,
|
||||
@@ -2138,6 +2154,8 @@ pub struct MavenSettings {
|
||||
pub active_profiles: String,
|
||||
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
|
||||
pub delegate_build: bool,
|
||||
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
|
||||
pub ignored_compile_goals: Vec<String>,
|
||||
/// Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
/// from a library class's Download Sources banner.
|
||||
|
||||
@@ -335,6 +335,7 @@ impl ServiceBuild<'_> {
|
||||
jar: &jar,
|
||||
jar_version: &version,
|
||||
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
|
||||
ignored_maven_compile_goals: &settings.languages.java.maven.ignored_compile_goals,
|
||||
service: self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
|
||||
@@ -1983,7 +1983,7 @@ pub async fn lsp_source_action_text(
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
if text.len() as u64 > project.documents.max_code_insight_bytes() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
@@ -2005,7 +2005,7 @@ pub async fn lsp_snapshot_diagnostics(
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
if text.len() as u64 > project.documents.max_code_insight_bytes() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
@@ -2028,7 +2028,7 @@ pub async fn lsp_snapshot_completion(
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
if text.len() as u64 > project.documents.max_code_insight_bytes() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
|
||||
@@ -467,10 +467,11 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
|
||||
return Ok(PythonStubLinks { candidates: watched, ..Default::default() });
|
||||
};
|
||||
// A counterpart too large to parse still opens; it just gets no markers.
|
||||
let limit = project.documents.max_code_insight_bytes();
|
||||
let other = match project.documents.text_of(&counterpart) {
|
||||
Some(text) => Some(text).filter(|t| t.len() as u64 <= ide_vfs::LARGE_FILE_THRESHOLD),
|
||||
Some(text) => Some(text).filter(|t| t.len() as u64 <= limit),
|
||||
None => std::fs::metadata(&counterpart)
|
||||
.is_ok_and(|m| m.len() <= ide_vfs::LARGE_FILE_THRESHOLD)
|
||||
.is_ok_and(|m| m.len() <= limit)
|
||||
.then(|| project.text_of(&counterpart))
|
||||
.transpose()?,
|
||||
};
|
||||
|
||||
@@ -709,7 +709,7 @@ fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<Pyte
|
||||
}
|
||||
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
|
||||
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
|
||||
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
if meta.len() > project.documents.max_code_insight_bytes() {
|
||||
return None;
|
||||
}
|
||||
let stamp = (meta.modified().ok()?, meta.len());
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
/// Files above this size open with reduced editor features.
|
||||
/// Default size limit for callers loading text without project editor settings.
|
||||
pub const LARGE_FILE_THRESHOLD: u64 = 5 * 1024 * 1024;
|
||||
/// Files above this size open read-only.
|
||||
pub const READ_ONLY_THRESHOLD: u64 = 50 * 1024 * 1024;
|
||||
@@ -226,19 +226,9 @@ fn archive_bytes(path: &Path) -> IdeResult<Option<(Vec<u8>, f64)>> {
|
||||
crate::read_archive_entry(&archive, &entry).map(Some)
|
||||
}
|
||||
|
||||
pub(crate) fn load_text(path: &Path) -> IdeResult<LoadedText> {
|
||||
if let Some((bytes, mtime_ms)) = archive_bytes(path)? {
|
||||
let len = bytes.len() as u64;
|
||||
let (text, enc, has_bom, binary) = decode_owned(bytes);
|
||||
return Ok(LoadedText {
|
||||
text,
|
||||
encoding: encoding_label(enc),
|
||||
has_bom,
|
||||
binary,
|
||||
large: len > LARGE_FILE_THRESHOLD,
|
||||
too_large: len > READ_ONLY_THRESHOLD,
|
||||
mtime_ms,
|
||||
});
|
||||
fn source_bytes(path: &Path) -> IdeResult<(Vec<u8>, f64)> {
|
||||
if let Some(entry) = archive_bytes(path)? {
|
||||
return Ok(entry);
|
||||
}
|
||||
let meta = fs::metadata(path)?;
|
||||
if meta.is_dir() {
|
||||
@@ -251,17 +241,22 @@ pub(crate) fn load_text(path: &Path) -> IdeResult<LoadedText> {
|
||||
meta.len() / (1024 * 1024)
|
||||
)));
|
||||
}
|
||||
let bytes = fs::read(path)?;
|
||||
Ok((fs::read(path)?, mtime_ms(&meta)))
|
||||
}
|
||||
|
||||
pub(crate) fn load_text(path: &Path) -> IdeResult<LoadedText> {
|
||||
let (bytes, mtime_ms) = source_bytes(path)?;
|
||||
let len = bytes.len() as u64;
|
||||
let (text, enc, has_bom, binary) = decode_owned(bytes);
|
||||
Ok(LoadedText {
|
||||
source_bytes: len,
|
||||
text,
|
||||
encoding: encoding_label(enc),
|
||||
has_bom,
|
||||
binary,
|
||||
large: len > LARGE_FILE_THRESHOLD,
|
||||
too_large: len > READ_ONLY_THRESHOLD,
|
||||
mtime_ms: mtime_ms(&meta),
|
||||
mtime_ms,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -300,6 +295,7 @@ pub(crate) fn load_text_bounded(
|
||||
return Err(IdeError::invalid("decoded document is too large"));
|
||||
}
|
||||
Ok(LoadedText {
|
||||
source_bytes: len,
|
||||
text,
|
||||
encoding: encoding_label(enc),
|
||||
has_bom,
|
||||
@@ -315,21 +311,23 @@ pub(crate) fn load_text_bounded(
|
||||
pub(crate) fn load_text_as(path: &Path, encoding: &str) -> IdeResult<LoadedText> {
|
||||
let enc = Encoding::for_label(encoding.trim().as_bytes())
|
||||
.ok_or_else(|| IdeError::invalid(format!("unknown encoding {encoding:?}")))?;
|
||||
let mut loaded = load_text(path)?;
|
||||
let bytes = match archive_bytes(path)? {
|
||||
Some((bytes, _)) => bytes,
|
||||
None => fs::read(path)?,
|
||||
};
|
||||
let (bytes, mtime_ms) = source_bytes(path)?;
|
||||
let len = bytes.len() as u64;
|
||||
let (body, has_bom) = match Encoding::for_bom(&bytes) {
|
||||
Some((bom_enc, len)) if bom_enc == enc => (&bytes[len..], true),
|
||||
_ => (&bytes[..], false),
|
||||
};
|
||||
let (text, _) = enc.decode_without_bom_handling(body);
|
||||
loaded.text = text.into_owned();
|
||||
loaded.encoding = encoding_label(enc);
|
||||
loaded.has_bom = has_bom;
|
||||
loaded.binary = false;
|
||||
Ok(loaded)
|
||||
Ok(LoadedText {
|
||||
text: text.into_owned(),
|
||||
source_bytes: len,
|
||||
encoding: encoding_label(enc),
|
||||
has_bom,
|
||||
binary: false,
|
||||
large: len > LARGE_FILE_THRESHOLD,
|
||||
too_large: len > READ_ONLY_THRESHOLD,
|
||||
mtime_ms,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encodes `text` to bytes in `encoding` (a WHATWG label). Fails rather than
|
||||
|
||||
@@ -215,12 +215,15 @@ pub(crate) fn read_dir_with(
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LoadedText {
|
||||
pub text: String,
|
||||
/// Size of the bytes read from disk or the archive entry, before decoding.
|
||||
#[serde(skip)]
|
||||
pub source_bytes: u64,
|
||||
/// WHATWG encoding label, e.g. `utf-8`, `gbk`, `utf-16le`.
|
||||
pub encoding: String,
|
||||
pub has_bom: bool,
|
||||
/// File looked binary; `text` is empty and the UI should show a placeholder.
|
||||
pub binary: bool,
|
||||
/// File exceeds [`LARGE_FILE_THRESHOLD`]: expensive features are disabled.
|
||||
/// File exceeds the code insight limit for this load.
|
||||
#[specta(optional)]
|
||||
pub large: bool,
|
||||
/// File exceeds [`READ_ONLY_THRESHOLD`]: opened read-only.
|
||||
@@ -228,6 +231,14 @@ pub struct LoadedText {
|
||||
pub mtime_ms: f64,
|
||||
}
|
||||
|
||||
impl LoadedText {
|
||||
/// Classifies this load using the editor's limit, including the hard read-only boundary.
|
||||
pub fn with_code_insight_limit(mut self, max_bytes: u64) -> Self {
|
||||
self.large = self.too_large || self.source_bytes > max_bytes;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads a text file, detecting BOM / encoding (chardetng) and binary content.
|
||||
///
|
||||
/// Files over [`LARGE_FILE_THRESHOLD`] load with `large`, over
|
||||
|
||||
@@ -29,10 +29,14 @@ pub struct DocumentInfo {
|
||||
/// (archive entries, JDT sources with an editable attachment encoding,
|
||||
/// Git revisions); false for server-generated content (decompiled code).
|
||||
pub can_reload_encoding: bool,
|
||||
/// Marks files above `ide_vfs::LARGE_FILE_THRESHOLD` for reduced editor
|
||||
/// Marks files above the editor's code insight size limit for reduced editor
|
||||
/// features such as disabling language servers and folding.
|
||||
#[specta(optional)]
|
||||
pub large: bool,
|
||||
/// File exceeds the hard editing limit independently of the code insight preference.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub too_large: bool,
|
||||
/// Effective `.editorconfig` properties, when any section applies.
|
||||
#[specta(optional)]
|
||||
pub editorconfig: Option<EditorConfigProps>,
|
||||
@@ -159,7 +163,9 @@ struct DocState {
|
||||
has_bom: bool,
|
||||
native_to_ascii: bool,
|
||||
read_only: bool,
|
||||
/// Analysis observers register when the document opens, so this stays fixed until close.
|
||||
large: bool,
|
||||
too_large: bool,
|
||||
editorconfig: Option<EditorConfigProps>,
|
||||
/// Observers were told about this document (not binary / too large).
|
||||
observed: bool,
|
||||
@@ -180,7 +186,7 @@ struct DocState {
|
||||
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
|
||||
external_writes: u64,
|
||||
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
|
||||
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
|
||||
/// `None` above the fixed snapshot budget, for virtual documents, and once a pending encoding,
|
||||
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
|
||||
clean_text: Option<Document>,
|
||||
closed: bool,
|
||||
@@ -190,11 +196,11 @@ struct DocState {
|
||||
|
||||
impl DocState {
|
||||
/// The buffer matches the file on disk again, read or written at `mtime`.
|
||||
fn synced(&mut self, mtime: f64) {
|
||||
fn synced(&mut self, mtime: f64, source_bytes: u64) {
|
||||
self.disk_mtime = mtime;
|
||||
self.disk_len = disk_len(&self.path);
|
||||
self.disk_len = source_bytes;
|
||||
self.disk_conflict = false;
|
||||
self.clean_text = (!self.large).then(|| self.doc.clone());
|
||||
self.clean_text = clean_snapshot(&self.doc, source_bytes);
|
||||
}
|
||||
|
||||
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
|
||||
@@ -227,6 +233,12 @@ impl DocState {
|
||||
}
|
||||
}
|
||||
|
||||
const CLEAN_SNAPSHOT_LIMIT: u64 = 5 * 1024 * 1024;
|
||||
|
||||
fn clean_snapshot(doc: &Document, source_bytes: u64) -> Option<Document> {
|
||||
(source_bytes <= CLEAN_SNAPSHOT_LIMIT).then(|| doc.clone())
|
||||
}
|
||||
|
||||
fn keys_for(path: &Path) -> Vec<PathBuf> {
|
||||
let mut keys = vec![path.to_path_buf()];
|
||||
if let Ok(canonical) = dunce::canonicalize(path)
|
||||
@@ -337,14 +349,15 @@ impl Documents {
|
||||
pub fn reload_properties(&self) {
|
||||
for id in self.open_documents() {
|
||||
let result = self.with_doc(id, |st| {
|
||||
let enabled = self.file_defaults().native_to_ascii_for(&st.path);
|
||||
let defaults = self.file_defaults();
|
||||
let enabled = defaults.native_to_ascii_for(&st.path);
|
||||
if st.dirty || st.uri.is_some() || st.binary || enabled == st.native_to_ascii {
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, enabled)?;
|
||||
self.replace_locked(id, st, &loaded.text)?;
|
||||
st.native_to_ascii = enabled;
|
||||
st.synced(loaded.mtime_ms);
|
||||
st.synced(loaded.mtime_ms, loaded.source_bytes);
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = result {
|
||||
@@ -427,11 +440,13 @@ impl Documents {
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
Ok(loaded)
|
||||
Ok(loaded.with_code_insight_limit(defaults.max_code_insight_bytes))
|
||||
}
|
||||
|
||||
pub fn load_file_as(&self, path: &Path, encoding: &str) -> IdeResult<ide_vfs::LoadedText> {
|
||||
Self::load_as(path, encoding, self.native_to_ascii_for(path))
|
||||
let defaults = self.file_defaults();
|
||||
Self::load_as(path, encoding, defaults.native_to_ascii_for(path))
|
||||
.map(|loaded| loaded.with_code_insight_limit(defaults.max_code_insight_bytes))
|
||||
}
|
||||
|
||||
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
|
||||
@@ -444,7 +459,8 @@ impl Documents {
|
||||
let path_abs = absolute(path);
|
||||
let configured = defaults.configured_encoding_for(&path_abs);
|
||||
if configured.source == EncodingSource::File {
|
||||
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
|
||||
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?
|
||||
.with_code_insight_limit(defaults.max_code_insight_bytes);
|
||||
// The bytes are not text in that encoding (the file changed outside the IDE):
|
||||
// open it as if nothing was chosen, rather than show and save broken characters.
|
||||
// A single-byte encoding decodes any bytes, so this only catches the others.
|
||||
@@ -457,13 +473,18 @@ impl Documents {
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
Ok((loaded, false))
|
||||
Ok((loaded.with_code_insight_limit(defaults.max_code_insight_bytes), false))
|
||||
}
|
||||
|
||||
pub fn file_defaults(&self) -> FileDefaults {
|
||||
self.defaults.read().clone()
|
||||
}
|
||||
|
||||
/// Maximum source bytes for analysis of a disk file or an in-memory snapshot.
|
||||
pub fn max_code_insight_bytes(&self) -> u64 {
|
||||
self.defaults.read().max_code_insight_bytes
|
||||
}
|
||||
|
||||
pub fn add_observer(&self, observer: std::sync::Arc<dyn DocumentObserver>) {
|
||||
self.observers.write().push(observer);
|
||||
}
|
||||
@@ -515,6 +536,7 @@ impl Documents {
|
||||
dirty: st.dirty,
|
||||
can_reload_encoding: st.can_reload_encoding,
|
||||
large: st.large,
|
||||
too_large: st.too_large,
|
||||
editorconfig: st.editorconfig.clone(),
|
||||
uri: st.uri.clone(),
|
||||
ui_mode: st.ui_mode.clone(),
|
||||
@@ -578,6 +600,7 @@ impl Documents {
|
||||
// The loaded text doubles as the IPC copy when normalization had nothing
|
||||
// to do, so a huge file is held at most twice (rope + response).
|
||||
let ipc_text = (!loaded.text.contains('\r')).then_some(loaded.text);
|
||||
let clean_text = clean_snapshot(&doc, loaded.source_bytes);
|
||||
let state = DocState {
|
||||
path: path.to_path_buf(),
|
||||
doc,
|
||||
@@ -588,6 +611,7 @@ impl Documents {
|
||||
native_to_ascii: !loaded.binary && defaults.native_to_ascii_for(path),
|
||||
read_only: !observed || !writable,
|
||||
large: loaded.large,
|
||||
too_large: loaded.too_large,
|
||||
editorconfig,
|
||||
observed,
|
||||
binary: loaded.binary,
|
||||
@@ -596,15 +620,13 @@ impl Documents {
|
||||
encoding_chosen,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_len: loaded.source_bytes,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
clean_text,
|
||||
closed: false,
|
||||
uri: None,
|
||||
};
|
||||
let mut state = state;
|
||||
state.clean_text = (!state.large).then(|| state.doc.clone());
|
||||
let slot: Slot = Arc::new(Mutex::new(state));
|
||||
let st = slot.lock();
|
||||
let id = {
|
||||
@@ -655,7 +677,7 @@ impl Documents {
|
||||
if let Some(info) = self.reopen(&key) {
|
||||
return Ok(info);
|
||||
}
|
||||
let large = text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD;
|
||||
let max_code_insight_bytes = self.max_code_insight_bytes();
|
||||
let state = DocState {
|
||||
path: key.clone(),
|
||||
doc: Document::new(text),
|
||||
@@ -665,7 +687,8 @@ impl Documents {
|
||||
has_bom,
|
||||
native_to_ascii: false,
|
||||
read_only: true,
|
||||
large,
|
||||
large: text.len() as u64 > max_code_insight_bytes,
|
||||
too_large: false,
|
||||
editorconfig: None,
|
||||
observed: true,
|
||||
binary: false,
|
||||
@@ -728,6 +751,7 @@ impl Documents {
|
||||
native_to_ascii: false,
|
||||
read_only: false,
|
||||
large: false,
|
||||
too_large: false,
|
||||
editorconfig: None,
|
||||
observed: true,
|
||||
binary: false,
|
||||
@@ -1060,7 +1084,7 @@ impl Documents {
|
||||
} else {
|
||||
ide_vfs::save_text(&st.path, &text, &st.encoding, st.has_bom)?
|
||||
};
|
||||
st.synced(mtime);
|
||||
st.synced(mtime, disk_len(&st.path));
|
||||
self.set_dirty(doc, st, false);
|
||||
if st.observed {
|
||||
let text = st.doc.text();
|
||||
@@ -1143,7 +1167,7 @@ impl Documents {
|
||||
st.ui_mode = ui_mode;
|
||||
st.editorconfig = if defaults.editorconfig { self.editorconfig.resolve(&st.path) } else { None };
|
||||
st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
|
||||
st.synced(mtime);
|
||||
st.synced(mtime, disk_len(&st.path));
|
||||
self.set_dirty(doc, st, false);
|
||||
let info = Self::info(doc, st);
|
||||
if st.observed {
|
||||
@@ -1359,14 +1383,15 @@ impl Documents {
|
||||
if st.dirty {
|
||||
return Err(IdeError::invalid("save or revert the unsaved changes before reloading"));
|
||||
}
|
||||
let enabled = self.file_defaults().native_to_ascii_for(&st.path);
|
||||
let defaults = self.file_defaults();
|
||||
let enabled = defaults.native_to_ascii_for(&st.path);
|
||||
let loaded = Self::load_as(&st.path, encoding, enabled)?;
|
||||
st.native_to_ascii = enabled;
|
||||
st.encoding = loaded.encoding.clone();
|
||||
st.encoding_chosen = true;
|
||||
st.has_bom = loaded.has_bom;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
st.synced(loaded.mtime_ms, loaded.source_bytes);
|
||||
// Reloading is not an edit: the buffer matches the file again.
|
||||
self.set_dirty(doc, st, false);
|
||||
return Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom });
|
||||
@@ -1443,7 +1468,7 @@ impl Documents {
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.encoding_unsaved = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
st.synced(loaded.mtime_ms, loaded.source_bytes);
|
||||
self.set_dirty(doc, st, false);
|
||||
self.announce_encoding(doc, st, before);
|
||||
Ok(())
|
||||
@@ -1511,7 +1536,6 @@ impl Documents {
|
||||
self.replace_locked(doc, st, text)?;
|
||||
st.encoding = encoding.to_owned();
|
||||
st.has_bom = has_bom;
|
||||
st.large = text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD;
|
||||
// Reloading is not an edit: the buffer matches its source again.
|
||||
self.set_dirty(doc, st, false);
|
||||
Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom })
|
||||
@@ -1606,10 +1630,10 @@ impl Documents {
|
||||
self.disk_conflict(id, st, Some(&meta));
|
||||
return Ok(());
|
||||
}
|
||||
let defaults = self.file_defaults();
|
||||
let loaded = if force_clean {
|
||||
Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?
|
||||
} else {
|
||||
let defaults = self.file_defaults();
|
||||
let native_to_ascii = defaults.native_to_ascii_for(&st.path);
|
||||
let loaded = if st.encoding_chosen {
|
||||
Self::load_as(&st.path, &st.encoding, native_to_ascii)?
|
||||
@@ -1633,11 +1657,10 @@ impl Documents {
|
||||
let before = Self::encoding_state(st);
|
||||
st.encoding = loaded.encoding;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.large = loaded.large;
|
||||
let ec_eol = st.editorconfig.as_ref().and_then(|ec| ec.end_of_line);
|
||||
st.doc.set_line_ending(ec_eol.unwrap_or_else(|| LineEnding::detect(&loaded.text)));
|
||||
self.replace_locked(id, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
st.synced(loaded.mtime_ms, loaded.source_bytes);
|
||||
self.announce_encoding(id, st, before);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
@@ -800,12 +800,13 @@ impl Documents {
|
||||
state.encoding_chosen = before.encoding_chosen;
|
||||
state.has_bom = before.has_bom;
|
||||
state.doc.set_line_ending(before.doc.line_ending());
|
||||
let mtime = fs::metadata(&state.path).map(|m| ide_vfs::mtime_ms(&m)).unwrap_or(0.0);
|
||||
let (mtime, len) =
|
||||
fs::metadata(&state.path).map(|m| (ide_vfs::mtime_ms(&m), m.len())).unwrap_or_default();
|
||||
let disk_failed =
|
||||
text_path(&state.path).is_ok_and(|path| failed_paths.iter().any(|failed| path.starts_with(failed)));
|
||||
let dirty = disk_failed || (before.dirty && differs_from_disk(state)?);
|
||||
let disk_conflict = state.disk_conflict;
|
||||
state.synced(mtime);
|
||||
state.synced(mtime, len);
|
||||
if dirty {
|
||||
// The restored buffer differs from the file: no text of it is known to be clean,
|
||||
// and a warned external change must still stop autosave.
|
||||
@@ -856,7 +857,7 @@ impl Documents {
|
||||
self.replace_locked(id, state, &loaded.text)?;
|
||||
state.encoding = loaded.encoding;
|
||||
state.has_bom = loaded.has_bom;
|
||||
state.synced(loaded.mtime_ms);
|
||||
state.synced(loaded.mtime_ms, loaded.source_bytes);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FileDefaults {
|
||||
/// Upper bound on the source byte count for document analysis.
|
||||
pub max_code_insight_bytes: u64,
|
||||
/// Encoding of new files (WHATWG label).
|
||||
pub encoding: String,
|
||||
/// Write a BOM into new UTF-8 files.
|
||||
@@ -71,6 +73,7 @@ impl FileDefaults {
|
||||
};
|
||||
let utf8_bom = enc.utf8_bom == "always" || (cfg!(windows) && enc.utf8_bom == "windows");
|
||||
Self {
|
||||
max_code_insight_bytes: u64::from(s.editor.max_code_insight_file_size_mb) * 1024 * 1024,
|
||||
encoding: normalize(&enc.project),
|
||||
utf8_bom,
|
||||
line_ending,
|
||||
|
||||
@@ -948,6 +948,36 @@ mod tests {
|
||||
assert!(SettingsStore::load(&cfg, Some(&proj)).effective().editor.custom_schemes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_are_loaded_per_project_and_can_be_cleared() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cfg = tmp.path().join("cfg");
|
||||
let project = tmp.path().join("project");
|
||||
let other = tmp.path().join("other");
|
||||
std::fs::create_dir_all(project.join(".openidea")).unwrap();
|
||||
std::fs::write(
|
||||
project.join(".openidea/settings.toml"),
|
||||
"[languages.java.maven]\nignoredCompileGoals = [\"org.apache.maven.plugins:maven-jar-plugin:jar\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
let store = SettingsStore::load(&cfg, Some(&project));
|
||||
assert_eq!(
|
||||
store.effective().languages.java.maven.ignored_compile_goals,
|
||||
["org.apache.maven.plugins:maven-jar-plugin:jar"]
|
||||
);
|
||||
assert!(!store.effective().languages.java.maven.delegate_build);
|
||||
assert!(
|
||||
SettingsStore::load(&cfg, Some(&other)).effective().languages.java.maven.ignored_compile_goals.is_empty()
|
||||
);
|
||||
store
|
||||
.set(SettingsScope::Global, "languages.java.maven.ignoredCompileGoals", json!(["org.example:checks:check"]))
|
||||
.unwrap();
|
||||
store.set(SettingsScope::Project, "languages.java.maven.ignoredCompileGoals", json!([])).unwrap();
|
||||
assert!(
|
||||
SettingsStore::load(&cfg, Some(&project)).effective().languages.java.maven.ignored_compile_goals.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_interpreter_list_and_its_view_options_are_user_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1176,6 +1206,25 @@ mod tests {
|
||||
assert_eq!(reloaded, store.effective());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_insight_limit_validates_both_layers_and_survives_reload() {
|
||||
let cfg = tempfile::tempdir().unwrap();
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let store = SettingsStore::load(cfg.path(), Some(project.path()));
|
||||
let key = "editor.maxCodeInsightFileSizeMb";
|
||||
let limit = |s: Settings| serde_json::to_value(s).unwrap()["editor"]["maxCodeInsightFileSizeMb"].clone();
|
||||
assert_eq!(limit(store.effective()), json!(5));
|
||||
assert_eq!(limit(store.set(SettingsScope::Global, key, json!(1)).unwrap()), json!(1));
|
||||
assert_eq!(limit(store.set(SettingsScope::Project, key, json!(50)).unwrap()), json!(50));
|
||||
store.set(SettingsScope::Project, "editor.tabSize", json!(8)).unwrap();
|
||||
for bad in [json!(0), json!(51), json!(1.5), json!("10")] {
|
||||
let settings = store.set(SettingsScope::Project, key, bad).unwrap();
|
||||
assert_eq!(settings.editor.tab_size, 8);
|
||||
assert_eq!(limit(settings), json!(5));
|
||||
}
|
||||
assert_eq!(limit(SettingsStore::load(cfg.path(), Some(project.path())).effective()), json!(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unset_settings_keep_their_defaults_json_shape() {
|
||||
// `SettingsStore::set` validates a key path against this JSON: a new field that
|
||||
|
||||
@@ -947,6 +947,69 @@ fn observers_receive_byte_edits() {
|
||||
assert_eq!(snap.language, LanguageId::new("rust"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_insight_limit_uses_file_bytes_for_disk_and_virtual_documents() {
|
||||
use ide_core::settings::Settings;
|
||||
use ide_workspace::FileDefaults;
|
||||
|
||||
let f = fixture();
|
||||
let set_limit = |mb| {
|
||||
let settings: Settings = serde_json::from_value(serde_json::json!({
|
||||
"editor": {"maxCodeInsightFileSizeMb": mb},
|
||||
}))
|
||||
.unwrap();
|
||||
f.docs.set_file_defaults(FileDefaults::from_settings(&settings, Some(&f.root)));
|
||||
};
|
||||
set_limit(1);
|
||||
let path = f.root.join("data.go");
|
||||
// The on-disk UTF-16LE bytes cross 1 MiB, although the decoded buffer is smaller.
|
||||
let decoded = "x".repeat(512 * 1024);
|
||||
fs::write(&path, ide_vfs::encode(&decoded, "utf-16le", true).unwrap()).unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert!(doc.large && !doc.too_large && !doc.read_only);
|
||||
assert!(f.docs.load_file_as(&path, "utf-16le").unwrap().large);
|
||||
f.docs.close(doc.id);
|
||||
set_limit(2);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert!(!reopened.large);
|
||||
set_limit(1);
|
||||
f.docs.set_encoding(reopened.id, "utf-16le", true).unwrap();
|
||||
assert!(!f.docs.snapshot(reopened.id).unwrap().large, "reloading retains the open document's limit");
|
||||
fs::write(&path, ide_vfs::encode(&(decoded + "y"), "utf-16le", true).unwrap()).unwrap();
|
||||
f.docs.sync_after_disk_change();
|
||||
assert!(!f.docs.snapshot(reopened.id).unwrap().large);
|
||||
f.docs.close(reopened.id);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert!(reopened.large, "reopening applies the new limit");
|
||||
fs::write(&path, ide_vfs::encode("small", "utf-16le", true).unwrap()).unwrap();
|
||||
f.docs.sync_after_disk_change();
|
||||
assert!(f.docs.snapshot(reopened.id).unwrap().large, "observers still use the decision made on open");
|
||||
f.docs.close(reopened.id);
|
||||
let small = f.docs.open(&path).unwrap();
|
||||
assert!(!small.large);
|
||||
set_limit(2);
|
||||
let mut text = "x".repeat(2 * 1024 * 1024);
|
||||
let doc = f.docs.open_virtual("test://bytes", LanguageId::new("go"), &text, "utf-8", false, true).unwrap();
|
||||
assert!(!doc.large, "the configured limit is inclusive");
|
||||
set_limit(1);
|
||||
f.docs.replace_virtual(doc.id, &text, "utf-8", false).unwrap();
|
||||
assert!(!f.docs.snapshot(doc.id).unwrap().large);
|
||||
text.push('x');
|
||||
f.docs.replace_virtual(doc.id, &text, "utf-8", false).unwrap();
|
||||
assert!(!f.docs.snapshot(doc.id).unwrap().large);
|
||||
f.docs.close(doc.id);
|
||||
text.pop();
|
||||
let reopened = f.docs.open_virtual("test://bytes", LanguageId::new("go"), &text, "utf-8", false, true).unwrap();
|
||||
assert!(reopened.large);
|
||||
|
||||
// A user raising the threshold can open a previously degraded file with full analysis.
|
||||
let larger = f.root.join("generated.pb.go");
|
||||
fs::write(&larger, "x".repeat(5 * 1024 * 1024 + 1)).unwrap();
|
||||
set_limit(6);
|
||||
let doc = f.docs.open(&larger).unwrap();
|
||||
assert!(!doc.large && !doc.read_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_files_degrade() {
|
||||
let f = fixture();
|
||||
@@ -1678,6 +1741,34 @@ fn undo_back_to_the_disk_text_leaves_the_document_clean() {
|
||||
assert!(f.docs.is_dirty(id).unwrap(), "line ending still differs from the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_clean_snapshot_keeps_its_file_byte_limit_when_code_insight_changes() {
|
||||
// UTF-16 source bytes determine the snapshot budget, even when the rope is smaller.
|
||||
for (insight_limit, units, expect_clean) in [(1, 1024 * 1024, true), (50, 5 * 1024 * 1024 / 2, false)] {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.max_code_insight_bytes = insight_limit * 1024 * 1024;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
let path = f.root.join("undo.txt");
|
||||
let bytes = ide_vfs::encode(&"x".repeat(units), "utf-16le", true).unwrap();
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.large, expect_clean);
|
||||
let undo = |version| {
|
||||
let version = f.docs.edit(doc.id, version, change(0, 0, "a")).unwrap();
|
||||
let version = f.docs.edit(doc.id, version, change(0, 1, "")).unwrap();
|
||||
assert_eq!(!f.docs.is_dirty(doc.id).unwrap(), expect_clean);
|
||||
version
|
||||
};
|
||||
let version = undo(doc.version);
|
||||
let version = f.docs.edit(doc.id, version, change(0, 0, "b")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
undo(version);
|
||||
f.docs.discard_and_reload(doc.id).unwrap();
|
||||
undo(f.docs.snapshot(doc.id).unwrap().version);
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer undone back to the disk text follows a checkout instead of warning about it.
|
||||
#[test]
|
||||
fn undo_back_to_the_disk_text_reloads_on_checkout() {
|
||||
|
||||
@@ -138,6 +138,8 @@ Settings › Appearance & Behavior › Appearance, unless noted.
|
||||
| `inlayHints` | `true` | Show inlay hints. |
|
||||
| `formatOnSave` | `false` | Reformat code on save (Tools › Actions on Save). |
|
||||
|
||||
In **Editor › General**, `maxCodeInsightFileSizeMb` sets the largest file eligible for syntax highlighting and language-server features. The default is 5 MiB. Choose a whole number from 1 to 50 and reopen the file. For example, set `maxCodeInsightFileSizeMb = 10` in `[editor]` to enable highlighting in a 9 MiB generated Go file.
|
||||
|
||||
Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completion]`, `[editor.tabs]`, `[editor.codeStyle]` and `[editor.encodings]` hold the options of the matching Editor pages.
|
||||
|
||||
`[editor.encodings.mappings]` in a project's `.openidea/settings.toml` gives a file or a folder its own encoding. Keys are paths relative to the project, with `/` separators. Choosing an encoding in the status bar adds the file here; after **Convert**, once the file is saved.
|
||||
|
||||
@@ -138,6 +138,8 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
| `inlayHints` | `true` | 显示嵌入提示。 |
|
||||
| `formatOnSave` | `false` | 保存时重新格式化代码(工具 › 保存时操作)。 |
|
||||
|
||||
在**编辑器 › 常规**中,`maxCodeInsightFileSizeMb` 控制可启用语法高亮和语言服务器功能的最大文件大小。默认值为 5 MiB,可设置为 1 到 50 之间的整数,重新打开文件后生效。例如,在 `[editor]` 下设置 `maxCodeInsightFileSizeMb = 10`,即可为 9 MiB 的 Go 生成文件启用高亮。
|
||||
|
||||
`[editor.general]`、`[editor.appearance]`、`[editor.completion]`、`[editor.tabs]`、`[editor.codeStyle]`、`[editor.encodings]` 等子表保存对应编辑器页面的选项。
|
||||
|
||||
项目 `.openidea/settings.toml` 中的 `[editor.encodings.mappings]` 为单个文件或文件夹指定编码。键是相对于项目的路径,使用 `/` 分隔。在状态栏中选择编码时,该文件会被添加到这里;使用 **Convert** 时,在保存文件之后添加。
|
||||
|
||||
@@ -44,6 +44,18 @@ test("Gradle keeps the local installation with Distribution and saves edits in p
|
||||
|
||||
await expect(distribution).toHaveText("Gradle wrapper");
|
||||
await expect(installation).toHaveCount(0);
|
||||
const fields = userHome.or(runUsing).or(distribution).or(jvm);
|
||||
for (const width of [1120, 800, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
const edges = await fields.evaluateAll((elements) =>
|
||||
elements.map((element) => {
|
||||
const { left, right } = element.getBoundingClientRect();
|
||||
return [Math.round(left), Math.round(right)];
|
||||
}),
|
||||
);
|
||||
expect(edges).toHaveLength(4);
|
||||
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
|
||||
}
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Local installation", exact: true }).click();
|
||||
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
|
||||
@@ -74,6 +74,47 @@ test("settings forms share control columns and keep font metrics on one row", as
|
||||
}
|
||||
});
|
||||
|
||||
test("toolchain, encoding and Subversion settings align field frames across sections", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const body = page.getByRole("dialog", { name: "Settings", exact: true }).locator("[class*='pageBody']");
|
||||
for (const [id, title, count] of [
|
||||
["languages.go", "Go", 2],
|
||||
["languages.java", "Java", 4],
|
||||
["languages.rust", "Rust", 4],
|
||||
["languages.node", "JavaScript Runtime", 4],
|
||||
["languages.php", "PHP", 4],
|
||||
["build.maven", "Maven", 8],
|
||||
["editor.fileEncodings", "File Encodings", 4],
|
||||
["vcs.svn", "Subversion", 2],
|
||||
] as const) {
|
||||
await selectPage(page, id);
|
||||
await expect(page.getByLabel("Breadcrumb").locator('[aria-current="page"]')).toHaveText(title);
|
||||
if (id === "vcs.svn") {
|
||||
await body.getByRole("checkbox", { name: "Use custom configuration directory" }).check();
|
||||
await expect(body.getByRole("textbox", { name: /Configuration directory/ })).toBeEnabled();
|
||||
}
|
||||
const fields = body
|
||||
.getByRole("button")
|
||||
.and(body.locator("[aria-haspopup='listbox']"))
|
||||
.or(body.getByRole("textbox"))
|
||||
.or(body.getByRole("combobox"))
|
||||
.and(body.locator(':not([aria-label="Thread count"])'));
|
||||
await expect(fields).toHaveCount(count);
|
||||
for (const width of [1200, 800, 520]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
for (const group of [fields, body.getByRole("button", { name: "Browse…", exact: true })]) {
|
||||
const edges = await group.evaluateAll((elements) =>
|
||||
elements.map((element) => {
|
||||
const { left, right } = element.getBoundingClientRect();
|
||||
return [Math.round(left), Math.round(right)];
|
||||
}),
|
||||
);
|
||||
for (const edge of edges.slice(1)) expect(edge, `${id} at ${width}px`).toEqual(edges[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const locale of ["en", "zh"]) {
|
||||
test(`${locale} forms fit narrow settings panes without horizontal scrolling`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
|
||||
@@ -117,6 +117,29 @@ test("Live Templates gives the editor the full settings pane width and keeps var
|
||||
expect(await variables.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
|
||||
});
|
||||
|
||||
test("Project settings aligns the visible fields and their browse buttons", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+;");
|
||||
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
|
||||
const fields = dialog
|
||||
.getByRole("button", { name: /^(Project SDK|Project language level|Language server JDK)$/ })
|
||||
.or(dialog.getByRole("textbox", { name: "Compiler output" }));
|
||||
const browse = dialog.getByRole("button", { name: "Browse…" });
|
||||
await expect(fields).toHaveCount(4);
|
||||
await expect(browse).toHaveCount(3);
|
||||
for (const width of [1400, 800, 520]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
for (const group of [fields, browse]) {
|
||||
const edges = await group.evaluateAll((elements) =>
|
||||
elements.map((element) => {
|
||||
const { left, right } = element.getBoundingClientRect();
|
||||
return [Math.round(left), Math.round(right)];
|
||||
}),
|
||||
);
|
||||
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("Project Structure keeps every details pane usable in a compact window", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+;");
|
||||
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
|
||||
|
||||
@@ -26,6 +26,26 @@ The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar h
|
||||
OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs,
|
||||
settings or generator inputs change, then compiles the launch's modules with the server.
|
||||
|
||||
### Ignoring Maven goals during IDE compilation
|
||||
|
||||
When the project binds a goal to a compile phase and local runs can skip its output, add the
|
||||
goal to the project's `.openidea/settings.toml`. For example, local runs may not need a release JAR.
|
||||
|
||||
```toml
|
||||
[languages.java.maven]
|
||||
delegateBuild = false
|
||||
ignoredCompileGoals = ["org.apache.maven.plugins:maven-jar-plugin:jar"]
|
||||
```
|
||||
|
||||
The list defaults to empty. Each entry matches all executions of exactly one `groupId:artifactId:goal`
|
||||
in `compile`, `process-classes`, `test-compile` or `process-test-classes`. The IDE's javac build skips
|
||||
those executions. Leave out goals whose output local runs require, including bytecode enhancement,
|
||||
compilation of another language and source generation.
|
||||
|
||||
The IDE reads the list on every build, including builds that use a cached model. The project list
|
||||
overrides the global list. Set `ignoredCompileGoals = []` to clear inherited entries. This applies
|
||||
only to the IDE's Maven javac build. Dependency and resource preparation can still invoke Maven.
|
||||
|
||||
Gradle builds get the same model from an init script instead
|
||||
(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with
|
||||
`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run
|
||||
|
||||
Створено
+1
-1
@@ -105,7 +105,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-openidea-mybatis"
|
||||
version = "0.4.2"
|
||||
version = "0.4.3"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "openidea-plugin-openidea-mybatis"
|
||||
version = "0.4.2"
|
||||
version = "0.4.3"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
bcf00a07cfc9a894d3effd88a3dbc4d000ac2abc057358db1afe17f9fde93710
|
||||
9df4fce831ca53f8e26ae3148c2525c42f8d2473c88da344b0890c85dcac13d6
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "openidea.mybatis"
|
||||
name = "MyBatis Navigator"
|
||||
version = "0.4.2"
|
||||
version = "0.4.3"
|
||||
description = "Jumps between MyBatis mapper interfaces and their XML statements, resultMaps, sql/include fragments, namespaces or annotation SQL (gutter arrows and Go to Definition), completes statement and sql ids and #{parameters}."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
change-notes = "0.4.2 — the XML named like the mapper interface is found by its file name, and a found XML is kept, so gutter arrows no longer go missing in large projects. 0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion."
|
||||
change-notes = "0.4.3 — navigate between Kotlin mapper interfaces and XML statements. 0.4.2 — the XML named like the mapper interface is found by its file name, and a found XML is kept, so gutter arrows no longer go missing in large projects. 0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion."
|
||||
categories = ["frameworks"]
|
||||
engines.openidea = "^1.4"
|
||||
wasm = "dist/plugin.wasm"
|
||||
@@ -16,3 +16,7 @@ required = ["project.read"]
|
||||
[[contributes.providers]]
|
||||
kinds = ["definition", "line-markers", "completion"]
|
||||
languages = ["java", "xml"]
|
||||
|
||||
[[contributes.providers]]
|
||||
kinds = ["definition", "line-markers"]
|
||||
languages = ["kotlin"]
|
||||
@@ -0,0 +1,206 @@
|
||||
use super::{MapperInterface, Named, Param, Positions, ident, skip_comment, skip_string};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Token<'a> {
|
||||
text: &'a str,
|
||||
start: usize,
|
||||
}
|
||||
|
||||
impl<'a> Token<'a> {
|
||||
fn name(self) -> &'a str {
|
||||
self.text.trim_matches('`')
|
||||
}
|
||||
|
||||
fn is_name(self) -> bool {
|
||||
self.text.starts_with('`') || self.text.starts_with(|c: char| c.is_alphabetic() || c == '_')
|
||||
}
|
||||
|
||||
fn named(self, positions: &mut Positions<'_>) -> Named {
|
||||
let start = self.start + usize::from(self.text.starts_with('`'));
|
||||
let name = self.name();
|
||||
Named { name: name.to_owned(), range: positions.range(start, start + name.len()) }
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_block_comment(text: &str) -> usize {
|
||||
let mut rest = &text[2..];
|
||||
let mut depth = 1;
|
||||
while let Some(at) = rest.find(['/', '*']) {
|
||||
rest = &rest[at..];
|
||||
if let Some(next) = rest.strip_prefix("/*") {
|
||||
depth += 1;
|
||||
rest = next;
|
||||
} else if let Some(next) = rest.strip_prefix("*/") {
|
||||
depth -= 1;
|
||||
rest = next;
|
||||
if depth == 0 {
|
||||
return text.len() - rest.len();
|
||||
}
|
||||
} else {
|
||||
rest = &rest[1..];
|
||||
}
|
||||
}
|
||||
text.len()
|
||||
}
|
||||
|
||||
fn tokens(text: &str) -> Vec<Token<'_>> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < text.len() {
|
||||
let rest = &text[at..];
|
||||
let c = rest.chars().next().unwrap();
|
||||
let end = if c.is_whitespace() {
|
||||
at += c.len_utf8();
|
||||
continue;
|
||||
} else if rest.starts_with("//") {
|
||||
at = skip_comment(bytes, at);
|
||||
continue;
|
||||
} else if rest.starts_with("/*") {
|
||||
at += skip_block_comment(rest);
|
||||
continue;
|
||||
} else if let Some(raw) = rest.strip_prefix("\"\"\"") {
|
||||
raw.find("\"\"\"").map_or(text.len(), |end| at + end + 6)
|
||||
} else if matches!(c, '"' | '\'') {
|
||||
skip_string(bytes, at)
|
||||
} else if let Some(quoted) = rest.strip_prefix('`') {
|
||||
quoted.find('`').map_or(at + 1, |end| at + end + 2)
|
||||
} else if ident(c) {
|
||||
rest.find(|c| !ident(c)).map_or(text.len(), |end| at + end)
|
||||
} else {
|
||||
at + c.len_utf8()
|
||||
};
|
||||
out.push(Token { text: &text[at..end], start: at });
|
||||
at = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn package(tokens: &[Token<'_>]) -> String {
|
||||
let Some(start) = tokens.iter().position(|t| t.text == "package") else { return String::new() };
|
||||
let mut parts = Vec::new();
|
||||
let mut names = tokens[start + 1..].iter();
|
||||
while let Some(name) = names.next().filter(|t| t.is_name()) {
|
||||
parts.push(name.name());
|
||||
if names.next().map(|t| t.text) != Some(".") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
parts.join(".")
|
||||
}
|
||||
|
||||
fn method_name<'a>(tokens: &[Token<'a>]) -> Option<(Token<'a>, usize)> {
|
||||
let mut generics = 0usize;
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
match t.text {
|
||||
"<" => generics += 1,
|
||||
">" => generics = generics.saturating_sub(1),
|
||||
"(" if generics == 0 => {
|
||||
let name = *tokens.get(i.checked_sub(1)?)?;
|
||||
return name.is_name().then_some((name, i));
|
||||
}
|
||||
"fun" | "val" | "var" | "interface" | "class" | "object" | "{" | "}" | ";" | "=" => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn parameters(tokens: &[Token<'_>], positions: &mut Positions<'_>) -> Vec<Param> {
|
||||
let mut params = Vec::new();
|
||||
let mut nested = 0usize;
|
||||
let mut generics = 0usize;
|
||||
let mut first = 0;
|
||||
let mut name = None;
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
match t.text {
|
||||
"(" | "[" | "{" => nested += 1,
|
||||
")" if nested == 0 => {
|
||||
params.extend(name);
|
||||
break;
|
||||
}
|
||||
")" | "]" | "}" => nested = nested.saturating_sub(1),
|
||||
"<" if nested == 0 => generics += 1,
|
||||
">" if nested == 0 => generics = generics.saturating_sub(1),
|
||||
"," if nested == 0 && generics == 0 => {
|
||||
params.extend(name.take());
|
||||
first = i + 1;
|
||||
}
|
||||
":" if nested == 0 && generics == 0 && name.is_none() && i > first => {
|
||||
let candidate = tokens[i - 1];
|
||||
if !candidate.is_name() || (i >= 2 && tokens[i - 2].text == "@") {
|
||||
continue;
|
||||
}
|
||||
let explicit = tokens[first..i].windows(3).find_map(|args| match args {
|
||||
[param, open, value] if param.text == "Param" && open.text == "(" => {
|
||||
Some((*value, value.text.strip_prefix('"')?.strip_suffix('"')?))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Named { name: label, range } = if let Some((token, label)) = explicit {
|
||||
let start = token.start + 1;
|
||||
Named { name: label.to_owned(), range: positions.range(start, start + label.len()) }
|
||||
} else {
|
||||
candidate.named(positions)
|
||||
};
|
||||
name = Some(Param { name: label, range });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// Read named interfaces and their direct members. Kotlin's `fun` introduces
|
||||
/// a declaration even when there are no semicolons or explicit return types.
|
||||
pub(super) fn parse(text: &str) -> Vec<MapperInterface> {
|
||||
if !text.contains("interface") {
|
||||
return Vec::new();
|
||||
}
|
||||
let tokens = tokens(text);
|
||||
let package = package(&tokens);
|
||||
let mut positions = Positions::new(text);
|
||||
let mut output: Vec<MapperInterface> = Vec::new();
|
||||
let mut pending = false;
|
||||
let mut inside_interface = false;
|
||||
let mut braces = 0usize;
|
||||
let mut parens = 0usize;
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
match t.text {
|
||||
"(" => parens += 1,
|
||||
")" => parens = parens.saturating_sub(1),
|
||||
"{" if parens == 0 => {
|
||||
if braces == 0 {
|
||||
inside_interface = std::mem::take(&mut pending);
|
||||
}
|
||||
braces += 1;
|
||||
}
|
||||
"}" if parens == 0 => {
|
||||
braces = braces.saturating_sub(1);
|
||||
if braces == 0 {
|
||||
inside_interface = false;
|
||||
}
|
||||
}
|
||||
"interface" if braces == 0 && parens == 0 => {
|
||||
if let Some(name) = tokens.get(i + 1).filter(|t| t.is_name()) {
|
||||
let decl = name.named(&mut positions);
|
||||
let name = if package.is_empty() { decl.name.clone() } else { format!("{package}.{}", decl.name) };
|
||||
output.push(MapperInterface { name: Some(name), decl: Some(decl), ..MapperInterface::default() });
|
||||
pending = true;
|
||||
}
|
||||
}
|
||||
"fun" if braces == 1 && parens == 0 && inside_interface => {
|
||||
if let Some((name, parens)) = method_name(&tokens[i + 1..]) {
|
||||
let method = name.named(&mut positions);
|
||||
let params = parameters(&tokens[i + parens + 2..], &mut positions);
|
||||
output.last_mut().unwrap().methods.push((method, params));
|
||||
}
|
||||
}
|
||||
"class" | "object" | "fun" | "val" | "var" | "typealias" | ";" if braces == 0 && parens == 0 => {
|
||||
pending = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
@@ -12,6 +12,8 @@ use openidea_plugin::{
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
mod kotlin;
|
||||
|
||||
/// How long a namespace without an XML file is not looked up again.
|
||||
const INDEX_TTL: Duration = Duration::from_secs(30);
|
||||
/// Lookups kept per project before the expired ones are dropped.
|
||||
@@ -57,7 +59,7 @@ pub struct Param {
|
||||
}
|
||||
|
||||
/// `#{…}` / `${…}` inside one method's `@Select`/`@Insert`/`@Update`/`@Delete`
|
||||
/// SQL strings: `method` indexes `MapperJava::methods`, `strings` covers the
|
||||
/// SQL strings: `method` indexes `MapperInterface::methods`, `strings` covers the
|
||||
/// SQL string literals, each `Named` in `params` covers one whole `#{…}` /
|
||||
/// `${…}` match.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -67,7 +69,7 @@ pub struct AnnotationSql {
|
||||
pub params: Vec<Named>,
|
||||
}
|
||||
|
||||
/// `@ResultMap("…")` on one method: `method` indexes `MapperJava::methods`,
|
||||
/// `@ResultMap("…")` on one method: `method` indexes `MapperInterface::methods`,
|
||||
/// `name` covers the id string (quotes excluded).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResultMapRef {
|
||||
@@ -75,9 +77,9 @@ pub struct ResultMapRef {
|
||||
pub name: Named,
|
||||
}
|
||||
|
||||
/// A Java interface.
|
||||
/// A mapper interface.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MapperJava {
|
||||
pub struct MapperInterface {
|
||||
/// Fully qualified name.
|
||||
pub name: Option<String>,
|
||||
/// The interface's own name (for `<mapper namespace>` targets).
|
||||
@@ -589,10 +591,10 @@ fn result_map_of(head: &str) -> (Vec<LitSpan>, Vec<LitSpan>) {
|
||||
}
|
||||
|
||||
/// The interface's name and methods (with their parameter names).
|
||||
pub fn parse_java(text: &str) -> MapperJava {
|
||||
pub fn parse_java(text: &str) -> MapperInterface {
|
||||
let package =
|
||||
text.lines().find_map(|l| l.trim().strip_prefix("package ").map(|p| p.trim_end_matches(';').trim().to_owned()));
|
||||
let Some(i) = text.find("interface ") else { return MapperJava::default() };
|
||||
let Some(i) = text.find("interface ") else { return MapperInterface::default() };
|
||||
let rest = &text[i + 10..];
|
||||
let indent = rest.len() - rest.trim_start().len();
|
||||
let simple: String = rest[indent..].chars().take_while(|c| ident(*c)).collect();
|
||||
@@ -688,7 +690,7 @@ pub fn parse_java(text: &str) -> MapperJava {
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
MapperJava { name, decl, methods, annotation_sql, result_refs, result_ids }
|
||||
MapperInterface { name, decl, methods, annotation_sql, result_refs, result_ids }
|
||||
}
|
||||
|
||||
/// `namespace="com.acme.UserMapper"` in an XML file, either quote.
|
||||
@@ -723,10 +725,13 @@ fn is_under(path: &str, root: &str) -> bool {
|
||||
.is_some_and(|rest| rest.is_empty() || root.ends_with(['/', '\\']) || rest.starts_with(['/', '\\']))
|
||||
}
|
||||
|
||||
type FileIndex = BTreeMap<String, BTreeMap<String, (Instant, Option<String>)>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Navigator {
|
||||
/// project root → namespace → (when it was looked up, the XML mapping it, if any).
|
||||
xml_index: BTreeMap<String, BTreeMap<String, (Instant, Option<String>)>>,
|
||||
xml_index: FileIndex,
|
||||
kotlin_index: FileIndex,
|
||||
/// Other mappers looked up for the file being linked (see [`MAX_OTHER_MAPPERS`]).
|
||||
other_mappers: BTreeSet<String>,
|
||||
}
|
||||
@@ -778,16 +783,66 @@ impl Navigator {
|
||||
hit
|
||||
}
|
||||
|
||||
/// The interface `namespace` names (`com.acme.UserMapper` → `**/com/acme/UserMapper.java`).
|
||||
fn java_for(project: &Project, namespace: &str) -> Option<(String, MapperJava)> {
|
||||
// A Java name only: anything else would be read as a glob.
|
||||
/// Resolve the declaration by its package and name. A Kotlin interface can
|
||||
/// live outside a package-named directory or in a differently named file.
|
||||
fn interface_for(&mut self, project: &Project, namespace: &str) -> Option<(String, MapperInterface)> {
|
||||
if namespace.is_empty() || !namespace.chars().all(|c| ident(c) || c == '.') {
|
||||
return None;
|
||||
}
|
||||
let rel = format!("**/{}.java", namespace.replace('.', "/"));
|
||||
let path = project.find_files(&rel, 1).ok()?.into_iter().next()?;
|
||||
let java = parse_java(&project.read_file(&path).ok()?);
|
||||
(java.name.as_deref() == Some(namespace)).then_some((path, java))
|
||||
let java = project.find_files(&rel, 1).ok().and_then(|paths| paths.into_iter().next());
|
||||
if let Some(path) = java
|
||||
&& let Ok(text) = project.read_file(&path)
|
||||
{
|
||||
let mapper = parse_java(&text);
|
||||
if mapper.name.as_deref() == Some(namespace) {
|
||||
return Some((path, mapper));
|
||||
}
|
||||
}
|
||||
let read = |path: &str| {
|
||||
kotlin::parse(&project.read_file(path).ok()?)
|
||||
.into_iter()
|
||||
.find(|mapper| mapper.name.as_deref() == Some(namespace))
|
||||
};
|
||||
let simple = namespace.rsplit('.').next()?;
|
||||
let paths = project.find_files(&format!("**/{simple}.kt"), MAX_MAPPERS).unwrap_or_default();
|
||||
let resolve = |path: String| {
|
||||
let mapper = read(&path)?;
|
||||
Some((path, mapper))
|
||||
};
|
||||
if let Some(found) = paths.into_iter().find_map(resolve) {
|
||||
return Some(found);
|
||||
}
|
||||
let root = project.root().ok()?;
|
||||
match self.kotlin_index.get(&root).and_then(|m| m.get(namespace)) {
|
||||
Some((_, Some(path))) => {
|
||||
if let Some(mapper) = read(path) {
|
||||
return Some((path.clone(), mapper));
|
||||
}
|
||||
}
|
||||
Some((at, None)) if at.elapsed() < INDEX_TTL => return None,
|
||||
_ => {}
|
||||
}
|
||||
if project.find_files("**/*.kt", 1).ok()?.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = simple.replace('$', "\\$");
|
||||
let query = TextQuery {
|
||||
pattern: format!(r"\binterface\s+`?{name}`?\b"),
|
||||
regex: true,
|
||||
case_sensitive: true,
|
||||
include: vec!["**/*.kt".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let search = project.search_text(&query, MAX_MAPPERS).ok()?;
|
||||
let paths: BTreeSet<_> = search.matches.into_iter().map(|m| m.location.path).collect();
|
||||
let hit = paths.into_iter().find_map(resolve);
|
||||
let index = self.kotlin_index.entry(root).or_default();
|
||||
if index.len() >= MAX_INDEXED {
|
||||
index.retain(|_, (at, _)| at.elapsed() < INDEX_TTL);
|
||||
}
|
||||
index.insert(namespace.to_owned(), (Instant::now(), hit.as_ref().map(|(path, _)| path.clone())));
|
||||
hit
|
||||
}
|
||||
|
||||
/// Where `resultMap="…"` / `<include refid="…">` points: a `<resultMap id>` /
|
||||
@@ -876,9 +931,9 @@ impl Navigator {
|
||||
let Some(ns) = xml.namespace.clone() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
// `<mapper namespace>` → the interface; statement ids → methods.
|
||||
if let Some((path, java)) = Self::java_for(&project, &ns.name) {
|
||||
if let Some((path, mapper)) = self.interface_for(&project, &ns.name) {
|
||||
let simple = ns.name.rsplit('.').next().unwrap_or(&ns.name).to_owned();
|
||||
if let Some(decl) = java.decl {
|
||||
if let Some(decl) = mapper.decl {
|
||||
out.push((
|
||||
ns.clone(),
|
||||
Location { path: path.clone(), range: decl.range },
|
||||
@@ -886,7 +941,7 @@ impl Navigator {
|
||||
));
|
||||
}
|
||||
out.extend(xml.statements.iter().filter_map(|s| {
|
||||
let (m, _) = java.methods.iter().find(|(m, _)| m.name == s.name)?;
|
||||
let (m, _) = mapper.methods.iter().find(|(m, _)| m.name == s.name)?;
|
||||
let tip = format!("{simple}.{}()", m.name);
|
||||
Some((s.clone(), Location { path: path.clone(), range: m.range }, tip))
|
||||
}));
|
||||
@@ -907,43 +962,56 @@ impl Navigator {
|
||||
out.sort_by_key(|a| a.0.range.start);
|
||||
out
|
||||
} else {
|
||||
let java = parse_java(&doc.text);
|
||||
let Some(name) = java.name.clone() else { return Vec::new() };
|
||||
let simple = name.rsplit('.').next().unwrap_or(&name).to_owned();
|
||||
// `@ResultMap("…")`: the `@Results(id = "…")` in this file when
|
||||
// present, else the XML mapper's `<resultMap>`. Needs no XML for
|
||||
// pure-annotation mappers.
|
||||
let xml = self.xml_for(&project, &name);
|
||||
let mut out: Vec<(Named, Location, String)> = Vec::new();
|
||||
for r in &java.result_refs {
|
||||
if let Some((method, def)) = java.result_ids.iter().find(|(_, d)| d.name == r.name.name) {
|
||||
let (m, _) = &java.methods[*method];
|
||||
out.push((
|
||||
r.name.clone(),
|
||||
Location { path: doc.path.clone(), range: def.range },
|
||||
format!("{simple}.{}(): {}", m.name, def.name),
|
||||
));
|
||||
} else if let Some((path, xml)) = &xml
|
||||
&& let Some(def) = xml.result_maps.iter().find(|m| m.name == r.name.name)
|
||||
{
|
||||
let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_owned();
|
||||
out.push((
|
||||
r.name.clone(),
|
||||
Location { path: path.clone(), range: def.range },
|
||||
format!("{file}: {}", def.name),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some((path, xml)) = xml {
|
||||
let file = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned();
|
||||
out.extend(java.methods.into_iter().filter_map(|(m, _)| {
|
||||
let s = xml.statements.iter().find(|s| s.name == m.name)?;
|
||||
Some((m, Location { path: path.clone(), range: s.range }, format!("{file}: {}", s.name)))
|
||||
}));
|
||||
}
|
||||
out
|
||||
let interfaces = match doc.language.as_str() {
|
||||
"kotlin" => kotlin::parse(&doc.text).into_iter().filter(|m| !m.methods.is_empty()).collect(),
|
||||
"java" => vec![parse_java(&doc.text)],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
interfaces.into_iter().flat_map(|mapper| self.interface_links(doc, &project, mapper)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn interface_links(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
project: &Project,
|
||||
mapper: MapperInterface,
|
||||
) -> Vec<(Named, Location, String)> {
|
||||
let Some(name) = mapper.name.as_ref() else { return Vec::new() };
|
||||
let simple = name.rsplit('.').next().unwrap_or(name).to_owned();
|
||||
// `@ResultMap("…")`: the `@Results(id = "…")` in this file when
|
||||
// present, else the XML mapper's `<resultMap>`. Needs no XML for
|
||||
// pure-annotation mappers.
|
||||
let xml = self.xml_for(project, name);
|
||||
let mut out: Vec<(Named, Location, String)> = Vec::new();
|
||||
for r in &mapper.result_refs {
|
||||
if let Some((method, def)) = mapper.result_ids.iter().find(|(_, d)| d.name == r.name.name) {
|
||||
let (m, _) = &mapper.methods[*method];
|
||||
out.push((
|
||||
r.name.clone(),
|
||||
Location { path: doc.path.clone(), range: def.range },
|
||||
format!("{simple}.{}(): {}", m.name, def.name),
|
||||
));
|
||||
} else if let Some((path, xml)) = &xml
|
||||
&& let Some(def) = xml.result_maps.iter().find(|m| m.name == r.name.name)
|
||||
{
|
||||
let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_owned();
|
||||
out.push((
|
||||
r.name.clone(),
|
||||
Location { path: path.clone(), range: def.range },
|
||||
format!("{file}: {}", def.name),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some((path, xml)) = xml {
|
||||
let file = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned();
|
||||
out.extend(mapper.methods.into_iter().filter_map(|(m, _)| {
|
||||
let s = xml.statements.iter().find(|s| s.name == m.name)?;
|
||||
Some((m, Location { path: path.clone(), range: s.range }, format!("{file}: {}", s.name)))
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(r: Range, p: Position) -> bool {
|
||||
@@ -1002,7 +1070,7 @@ impl Providers for Navigator {
|
||||
let xml = parse_xml(&doc.text);
|
||||
let Some(ns) = xml.namespace.clone().map(|n| n.name) else { return Vec::new() };
|
||||
let Some(project) = project_of(&doc.path) else { return Vec::new() };
|
||||
let Some((_, java)) = Self::java_for(&project, &ns) else { return Vec::new() };
|
||||
let Some((_, mapper)) = self.interface_for(&project, &ns) else { return Vec::new() };
|
||||
let line_start = before.rfind('\n').map_or(0, |i| i + 1);
|
||||
let line = &before[line_start..];
|
||||
// Inside `id="…` of a statement tag: the interface's unmapped methods.
|
||||
@@ -1012,7 +1080,7 @@ impl Providers for Navigator {
|
||||
{
|
||||
let typed = &line[i + 4..];
|
||||
let Some(start) = replace_start(at, typed) else { return Vec::new() };
|
||||
return java
|
||||
return mapper
|
||||
.methods
|
||||
.iter()
|
||||
.filter(|(m, _)| m.name.starts_with(typed) && !xml.statements.iter().any(|s| s.name == m.name))
|
||||
@@ -1048,7 +1116,8 @@ impl Providers for Navigator {
|
||||
let typed = &before[i + 2..];
|
||||
let here = position(&doc.text, cursor);
|
||||
let statement = xml.statements.iter().rev().find(|s| s.range.start < here);
|
||||
let Some((_, params)) = statement.and_then(|s| java.methods.iter().find(|(m, _)| m.name == s.name)) else {
|
||||
let Some((_, params)) = statement.and_then(|s| mapper.methods.iter().find(|(m, _)| m.name == s.name))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(start) = replace_start(at, typed) else { return Vec::new() };
|
||||
@@ -1256,6 +1325,74 @@ mod tests {
|
||||
Document { path: path.into(), language: language.into(), version: 1, text: text.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigates_between_kotlin_and_xml() {
|
||||
const KOTLIN: &str = concat!(
|
||||
"package com.acme\n",
|
||||
"interface UserMapper : BaseMapper<User> {\n",
|
||||
" @MapperHint(\"😀\") fun findById(@Param(\"id\") userId: Long): User?\n",
|
||||
" fun insert(user: User): Int\n",
|
||||
" fun <T> search(values: Map<String, T>, limit: Int): List<User>\n",
|
||||
" object Other { fun unrelated() {} }\n",
|
||||
"}\n",
|
||||
);
|
||||
let host = MockHost::install();
|
||||
let kotlin_path = "module/src/main/kotlin/UserMapper.kt";
|
||||
let xml_path = "module/src/main/resources/mapper/UserMapper.xml";
|
||||
host.add_file(kotlin_path, KOTLIN);
|
||||
add_mapper(&host, xml_path, XML);
|
||||
let kotlin = doc(&format!("/project/{kotlin_path}"), "kotlin", KOTLIN);
|
||||
let xml = doc(&format!("/project/{xml_path}"), "xml", XML);
|
||||
let mut navigator = Navigator::default();
|
||||
let marker_lines = |markers: Vec<LineMarker>| markers.iter().map(|m| m.line).collect::<Vec<_>>();
|
||||
assert_eq!(marker_lines(navigator.line_markers(&kotlin)), [2, 3]);
|
||||
assert_eq!(marker_lines(navigator.line_markers(&xml)), [1, 2, 5]);
|
||||
|
||||
let from_kotlin = navigator.definition(&kotlin, Position::new(2, 26));
|
||||
assert_eq!(from_kotlin[0].path, xml.path);
|
||||
assert_eq!(from_kotlin[0].range.start, Position::new(2, 14));
|
||||
let namespace = navigator.definition(&xml, Position::new(1, 25));
|
||||
assert_eq!(namespace[0].path, kotlin.path);
|
||||
assert_eq!(namespace[0].range.start, Position::new(1, 10));
|
||||
let statement = navigator.definition(&xml, Position::new(2, 16));
|
||||
assert_eq!(statement[0].path, kotlin.path);
|
||||
assert_eq!(statement[0].range.start, Position::new(2, 26));
|
||||
|
||||
let items = navigator.completion(&xml, Position::new(8, 14), None);
|
||||
assert_eq!(items.iter().map(|c| c.label.as_str()).collect::<Vec<_>>(), ["search"]);
|
||||
let xml = doc(&xml.path, "xml", &XML.replace("#{id}", "#{"));
|
||||
let params = navigator.completion(&xml, Position::new(3, 38), None);
|
||||
assert_eq!(params.iter().map(|c| c.label.as_str()).collect::<Vec<_>>(), ["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_kotlin_mapper_in_a_differently_named_file() {
|
||||
let host = MockHost::install();
|
||||
let path = "module/src/main/kotlin/Mappers.kt";
|
||||
host.add_file(path, "package com.acme\n/* /* nested */ interface Fake */\ninterface Empty\ninterface UserMapper { fun findById(): User }\n");
|
||||
host.on_search(move |query, _| {
|
||||
assert_eq!(query.include, ["**/*.kt"]);
|
||||
assert!(query.pattern.contains("UserMapper"));
|
||||
Ok(TextSearch {
|
||||
matches: vec![TextMatch {
|
||||
location: Location {
|
||||
path: format!("/project/{path}"),
|
||||
range: Range::new(Position::new(3, 0), Position::new(3, 0)),
|
||||
},
|
||||
line: String::new(),
|
||||
}],
|
||||
limit_hit: false,
|
||||
})
|
||||
});
|
||||
let mut navigator = Navigator::default();
|
||||
let xml = doc("/project/UserMapper.xml", "xml", XML);
|
||||
let namespace = navigator.definition(&xml, Position::new(1, 25));
|
||||
assert_eq!(namespace[0].path, format!("/project/{path}"));
|
||||
assert_eq!(namespace[0].range.start, Position::new(3, 10));
|
||||
let statement = navigator.definition(&xml, Position::new(2, 16));
|
||||
assert_eq!(statement[0].range.start, Position::new(3, 27));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigates_both_ways() {
|
||||
let _host = setup();
|
||||
@@ -1668,9 +1805,10 @@ mod tests {
|
||||
assert!(pattern.contains(r"a\|b\.x\[0\]"), "{pattern}");
|
||||
let _host = setup();
|
||||
let project = host::projects().unwrap().remove(0);
|
||||
assert!(Navigator::java_for(&project, "com.acme.UserMapper").is_some());
|
||||
assert!(Navigator::java_for(&project, "com.*.UserMapper").is_none());
|
||||
assert!(Navigator::java_for(&project, "").is_none());
|
||||
let mut navigator = Navigator::default();
|
||||
assert!(navigator.interface_for(&project, "com.acme.UserMapper").is_some());
|
||||
assert!(navigator.interface_for(&project, "com.*.UserMapper").is_none());
|
||||
assert!(navigator.interface_for(&project, "").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8681,10 +8681,12 @@ export type DocumentInfo = {
|
||||
*/
|
||||
canReloadEncoding: boolean,
|
||||
/**
|
||||
* Marks files above `ide_vfs::LARGE_FILE_THRESHOLD` for reduced editor
|
||||
* Marks files above the editor's code insight size limit for reduced editor
|
||||
* features such as disabling language servers and folding.
|
||||
*/
|
||||
large?: boolean,
|
||||
/** File exceeds the hard editing limit independently of the code insight preference. */
|
||||
tooLarge?: boolean,
|
||||
/** Effective `.editorconfig` properties, when any section applies. */
|
||||
editorconfig?: EditorConfigProps | null,
|
||||
/**
|
||||
@@ -8928,6 +8930,8 @@ export type EditorSettings = EditorSettings_Serialize | EditorSettings_Deseriali
|
||||
export type EditorSettings_Deserialize = {
|
||||
fontFamily?: string,
|
||||
fontSize?: number | null,
|
||||
/** Largest document (in MiB) eligible for syntax analysis and language-server features. */
|
||||
maxCodeInsightFileSizeMb?: number,
|
||||
lineHeight?: number | null,
|
||||
tabSize?: number,
|
||||
insertSpaces?: boolean,
|
||||
@@ -8988,6 +8992,8 @@ export type EditorSettings_Deserialize = {
|
||||
export type EditorSettings_Serialize = {
|
||||
fontFamily: string,
|
||||
fontSize: number | null,
|
||||
/** Largest document (in MiB) eligible for syntax analysis and language-server features. */
|
||||
maxCodeInsightFileSizeMb: number,
|
||||
lineHeight: number | null,
|
||||
tabSize: number,
|
||||
insertSpaces: boolean,
|
||||
@@ -12484,6 +12490,8 @@ export type MavenSettings = {
|
||||
activeProfiles?: string,
|
||||
/** Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). */
|
||||
delegateBuild?: boolean,
|
||||
/** Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default. */
|
||||
ignoredCompileGoals?: string[],
|
||||
/**
|
||||
* Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
* project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
|
||||
@@ -71,6 +71,8 @@ export interface EditorDocContext {
|
||||
/** `@codemirror/language-data` name, e.g. `Rust`, if any. */
|
||||
uiMode: string | null;
|
||||
readOnly: boolean;
|
||||
/** The document exceeded the backend's code insight limit when opened. */
|
||||
large?: boolean;
|
||||
/**
|
||||
* A read-only virtual document (library class contents from a language
|
||||
* server); `path` is then its URI, not a file: skip file-based features
|
||||
|
||||
@@ -2,7 +2,21 @@
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { EditorSelection, type EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { indentSelection, moveLineDown, moveLineUp } from "@codemirror/commands";
|
||||
import {
|
||||
cursorCharLeft,
|
||||
cursorCharRight,
|
||||
cursorLineBoundaryBackward,
|
||||
cursorLineBoundaryForward,
|
||||
cursorLineStart,
|
||||
indentSelection,
|
||||
moveLineDown,
|
||||
moveLineUp,
|
||||
selectCharLeft,
|
||||
selectCharRight,
|
||||
selectLineBoundaryBackward,
|
||||
selectLineBoundaryForward,
|
||||
selectLineStart,
|
||||
} from "@codemirror/commands";
|
||||
import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
|
||||
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
@@ -112,10 +126,14 @@ import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
|
||||
import {
|
||||
cloneCaretAbove,
|
||||
cloneCaretBelow,
|
||||
cursorLineDown,
|
||||
cursorLineUp,
|
||||
moveDownAndScroll,
|
||||
moveDownAndScrollWithSelection,
|
||||
moveUpAndScroll,
|
||||
moveUpAndScrollWithSelection,
|
||||
selectLineDown,
|
||||
selectLineUp,
|
||||
} from "./cm/verticalMotion";
|
||||
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
|
||||
import { cyclicExpandWord } from "./wordCompletion";
|
||||
@@ -885,6 +903,10 @@ export function registerEditorActions(): () => void {
|
||||
});
|
||||
const edit = diffText(true);
|
||||
const caret = diffText(false);
|
||||
const lineStart = (view: EditorView, select: boolean) => {
|
||||
if (!editorPrefs().smartKeys.smartHome) return (select ? selectLineStart : cursorLineStart)(view);
|
||||
return (select ? selectLineBoundaryBackward : cursorLineBoundaryBackward)(view);
|
||||
};
|
||||
const activePaneTab = () => {
|
||||
const s = useTabs.getState();
|
||||
const pane = s.panes[s.activePane];
|
||||
@@ -1105,12 +1127,12 @@ export function registerEditorActions(): () => void {
|
||||
icon: "paste",
|
||||
}),
|
||||
// Copy once in the format Settings › Editor › General › Rich-Text Copy doesn't give.
|
||||
text("code.copyAsPlainText", "Copy as Plain Text", (v) => copyAs(v, "plain"), {
|
||||
caret("code.copyAsPlainText", "Copy as Plain Text", (v) => copyAs(v, "plain"), {
|
||||
category: "Edit",
|
||||
icon: "copy",
|
||||
keywords: ["without formatting", "rich text"],
|
||||
}),
|
||||
text("code.copyAsRichText", "Copy as Rich Text", (v) => copyAs(v, "rich"), {
|
||||
caret("code.copyAsRichText", "Copy as Rich Text", (v) => copyAs(v, "rich"), {
|
||||
category: "Edit",
|
||||
icon: "copy",
|
||||
keywords: ["html", "syntax colors", "formatting"],
|
||||
@@ -1203,6 +1225,64 @@ export function registerEditorActions(): () => void {
|
||||
edit("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
|
||||
edit("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
|
||||
edit("code.splitLine", "Split Line", (v) => splitLine(v)),
|
||||
caret("editor.up", "Move Caret Up", (v) => (isStickySelection(v.state) ? selectLineUp : cursorLineUp)(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["up", "cursorUp"],
|
||||
}),
|
||||
caret("editor.down", "Move Caret Down", (v) => (isStickySelection(v.state) ? selectLineDown : cursorLineDown)(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["down", "cursorDown"],
|
||||
}),
|
||||
caret("editor.left", "Move Caret Left", (v) => (isStickySelection(v.state) ? selectCharLeft : cursorCharLeft)(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["left", "cursorLeft"],
|
||||
}),
|
||||
caret(
|
||||
"editor.right",
|
||||
"Move Caret Right",
|
||||
(v) => (isStickySelection(v.state) ? selectCharRight : cursorCharRight)(v),
|
||||
{
|
||||
category: "Editor Actions",
|
||||
keywords: ["right", "cursorRight"],
|
||||
},
|
||||
),
|
||||
caret("editor.lineStart", "Move Caret to Line Start", (v) => lineStart(v, isStickySelection(v.state)), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["line start", "home", "cursorHome"],
|
||||
}),
|
||||
caret(
|
||||
"editor.lineEnd",
|
||||
"Move Caret to Line End",
|
||||
(v) => (isStickySelection(v.state) ? selectLineBoundaryForward : cursorLineBoundaryForward)(v),
|
||||
{
|
||||
category: "Editor Actions",
|
||||
keywords: ["line end", "end", "cursorEnd"],
|
||||
},
|
||||
),
|
||||
caret("editor.upWithSelection", "Move Caret Up with Selection", (v) => selectLineUp(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["up with selection", "cursorUpSelect"],
|
||||
}),
|
||||
caret("editor.downWithSelection", "Move Caret Down with Selection", (v) => selectLineDown(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["down with selection", "cursorDownSelect"],
|
||||
}),
|
||||
caret("editor.leftWithSelection", "Move Caret Left with Selection", (v) => selectCharLeft(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["left with selection", "cursorLeftSelect"],
|
||||
}),
|
||||
caret("editor.rightWithSelection", "Move Caret Right with Selection", (v) => selectCharRight(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["right with selection", "cursorRightSelect"],
|
||||
}),
|
||||
caret("editor.lineStartWithSelection", "Move Caret to Line Start with Selection", (v) => lineStart(v, true), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["line start with selection", "home", "cursorHomeSelect"],
|
||||
}),
|
||||
caret("editor.lineEndWithSelection", "Move Caret to Line End with Selection", (v) => selectLineBoundaryForward(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["line end with selection", "end", "cursorEndSelect"],
|
||||
}),
|
||||
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { _setFocusedCellEditor } from "@/editor/api";
|
||||
import { matchActions } from "@/features/search/everywhere/model";
|
||||
import { resolveActionId } from "@/features/vim/rc";
|
||||
import { allActions, executeAction, getAction, registerAction } from "@/platform/actions";
|
||||
import { useContextKeys } from "@/platform/context";
|
||||
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
|
||||
import { IDEA_ACTIONS } from "@/platform/ideaActions";
|
||||
import { parseIdeaKeymap } from "@/platform/ideaKeymap";
|
||||
import { installKeyboardDispatcher, normalizeBinding, PRESETS, useKeymap } from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerEditorActions } from "./actions";
|
||||
import { stickySelectionField, toggleStickySelection } from "./cm/stickySelection";
|
||||
import { visibleGoalColumns } from "./cm/verticalMotion";
|
||||
|
||||
const ACTIONS = [
|
||||
["editor.up", "EditorUp", "Move Caret Up"],
|
||||
["editor.down", "EditorDown", "Move Caret Down"],
|
||||
["editor.left", "EditorLeft", "Move Caret Left"],
|
||||
["editor.right", "EditorRight", "Move Caret Right"],
|
||||
["editor.lineStart", "EditorLineStart", "Move Caret to Line Start"],
|
||||
["editor.lineEnd", "EditorLineEnd", "Move Caret to Line End"],
|
||||
["editor.upWithSelection", "EditorUpWithSelection", "Move Caret Up with Selection"],
|
||||
["editor.downWithSelection", "EditorDownWithSelection", "Move Caret Down with Selection"],
|
||||
["editor.leftWithSelection", "EditorLeftWithSelection", "Move Caret Left with Selection"],
|
||||
["editor.rightWithSelection", "EditorRightWithSelection", "Move Caret Right with Selection"],
|
||||
["editor.lineStartWithSelection", "EditorLineStartWithSelection", "Move Caret to Line Start with Selection"],
|
||||
["editor.lineEndWithSelection", "EditorLineEndWithSelection", "Move Caret to Line End with Selection"],
|
||||
] as const;
|
||||
|
||||
let dispose: () => void;
|
||||
let uninstall: (() => void) | null = null;
|
||||
const views: EditorView[] = [];
|
||||
const initialKeymap = useKeymap.getState();
|
||||
const initialSettings = useProject.getState().settings;
|
||||
|
||||
function makeView(doc: string, anchor: number, head = anchor, readOnly = false): EditorView {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: EditorSelection.range(anchor, head),
|
||||
extensions: [visibleGoalColumns, stickySelectionField, ...(readOnly ? [EditorState.readOnly.of(true)] : [])],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dispose = registerEditorActions();
|
||||
useContextKeys.setState({ textEditorActive: true, editorTextFocus: true }, true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
uninstall?.();
|
||||
uninstall = null;
|
||||
dispose();
|
||||
_setFocusedCellEditor(null);
|
||||
while (views.length) {
|
||||
const v = views.pop()!;
|
||||
v.destroy();
|
||||
v.dom.remove();
|
||||
}
|
||||
useContextKeys.setState({}, true);
|
||||
useKeymap.setState({
|
||||
preset: initialKeymap.preset,
|
||||
overrides: initialKeymap.overrides,
|
||||
extensions: initialKeymap.extensions,
|
||||
});
|
||||
useProject.setState({ settings: initialSettings });
|
||||
_resetI18nForTests();
|
||||
});
|
||||
|
||||
describe("Caret movement actions", () => {
|
||||
it("registers all 12 actions in Editor Actions and makes them discoverable in Find Action", () => {
|
||||
for (const [id, , title] of ACTIONS) {
|
||||
expect(getAction(id)).toMatchObject({ title, category: "Editor Actions" });
|
||||
expect(getAction(id)?.hidden).not.toBe(true);
|
||||
}
|
||||
const search = (query: string) =>
|
||||
matchActions(allActions(), query, { isEnabled: () => true, recent: [] }).map((item) => item.id);
|
||||
expect(search("Up")).toContain("editor.up");
|
||||
expect(search("Down")).toContain("editor.down");
|
||||
expect(search("Left")).toContain("editor.left");
|
||||
expect(search("Right")).toContain("editor.right");
|
||||
expect(search("Line Start")).toContain("editor.lineStart");
|
||||
expect(search("Line End")).toContain("editor.lineEnd");
|
||||
expect(search("Up with Selection")).toContain("editor.upWithSelection");
|
||||
expect(search("Down with Selection")).toContain("editor.downWithSelection");
|
||||
expect(search("Left with Selection")).toContain("editor.leftWithSelection");
|
||||
expect(search("Right with Selection")).toContain("editor.rightWithSelection");
|
||||
expect(search("Line Start with Selection")).toContain("editor.lineStartWithSelection");
|
||||
expect(search("Line End with Selection")).toContain("editor.lineEndWithSelection");
|
||||
});
|
||||
|
||||
it("maps IDEA action ids for IdeaVim and imported keymaps without default shortcuts", () => {
|
||||
for (const [id, ideaId] of ACTIONS) {
|
||||
expect(IDEA_ACTIONS[ideaId]).toBe(id);
|
||||
expect(resolveActionId(ideaId)).toBe(id);
|
||||
for (const keymap of Object.values(PRESETS)) expect(keymap[id] ?? []).toEqual([]);
|
||||
}
|
||||
|
||||
const xml = `<keymap version="1" name="HomeRow" parent="VSCode (macOS)">
|
||||
<action id="EditorUp"><keyboard-shortcut first-keystroke="meta k"/></action>
|
||||
<action id="EditorDown"><keyboard-shortcut first-keystroke="meta j"/></action>
|
||||
<action id="EditorLeft"><keyboard-shortcut first-keystroke="control h"/></action>
|
||||
<action id="EditorRight"><keyboard-shortcut first-keystroke="control l"/></action>
|
||||
<action id="EditorLineStart"><keyboard-shortcut first-keystroke="meta h"/></action>
|
||||
<action id="EditorLineEnd"><keyboard-shortcut first-keystroke="meta l"/></action>
|
||||
<action id="EditorUpWithSelection"><keyboard-shortcut first-keystroke="shift meta k"/></action>
|
||||
<action id="EditorDownWithSelection"><keyboard-shortcut first-keystroke="shift meta j"/></action>
|
||||
<action id="EditorLeftWithSelection"><keyboard-shortcut first-keystroke="shift control h"/></action>
|
||||
<action id="EditorRightWithSelection"><keyboard-shortcut first-keystroke="shift control l"/></action>
|
||||
<action id="EditorLineStartWithSelection"><keyboard-shortcut first-keystroke="shift meta h"/></action>
|
||||
<action id="EditorLineEndWithSelection"><keyboard-shortcut first-keystroke="shift meta l"/></action>
|
||||
</keymap>`;
|
||||
const parsed = parseIdeaKeymap(xml);
|
||||
expect(parsed.unknownActions).toEqual([]);
|
||||
expect(parsed.overrides["editor.up"]).toEqual([normalizeBinding("Meta+K")]);
|
||||
expect(parsed.overrides["editor.lineStartWithSelection"]).toEqual([normalizeBinding("Meta+Shift+H")]);
|
||||
expect(parsed.overrides["editor.lineEndWithSelection"]).toEqual([normalizeBinding("Meta+Shift+L")]);
|
||||
});
|
||||
|
||||
it("moves and selects with Up, Down, Left, Right, Line Start and Line End", async () => {
|
||||
const view = makeView("alpha\n beta\ngamma", 12); // " be|ta"
|
||||
_setFocusedCellEditor(view);
|
||||
|
||||
await executeAction("editor.left");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 11, head: 11 });
|
||||
|
||||
await executeAction("editor.right");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 12, head: 12 });
|
||||
|
||||
await executeAction("editor.up");
|
||||
expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(1);
|
||||
|
||||
await executeAction("editor.down");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 12, head: 12 });
|
||||
|
||||
// Smart Home enabled: first goes to indentation, second to column 0.
|
||||
useProject.setState({ settings: { ...initialSettings, editor: { smartKeys: { smartHome: true } } } });
|
||||
await executeAction("editor.lineStart");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 10, head: 10 });
|
||||
await executeAction("editor.lineStart");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 6 });
|
||||
|
||||
await executeAction("editor.lineEnd");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 14, head: 14 });
|
||||
|
||||
// Smart Home disabled: goes straight to column 0.
|
||||
useProject.setState({ settings: { ...initialSettings, editor: { smartKeys: { smartHome: false } } } });
|
||||
await executeAction("editor.lineStart");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 6 });
|
||||
|
||||
await executeAction("editor.rightWithSelection");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 7 });
|
||||
|
||||
await executeAction("editor.lineEndWithSelection");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 14 });
|
||||
|
||||
await executeAction("editor.leftWithSelection");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 13 });
|
||||
|
||||
await executeAction("editor.lineStartWithSelection");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 6 });
|
||||
|
||||
await executeAction("editor.downWithSelection");
|
||||
expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(3);
|
||||
expect(view.state.selection.main.anchor).toBe(6);
|
||||
|
||||
await executeAction("editor.upWithSelection");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 6, head: 6 });
|
||||
});
|
||||
|
||||
it("extends the selection on plain moves while sticky selection is active", async () => {
|
||||
const view = makeView("first\n second", 10); // " se|cond"
|
||||
_setFocusedCellEditor(view);
|
||||
expect(toggleStickySelection(view)).toBe(true);
|
||||
|
||||
await executeAction("editor.right");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 10, head: 11 });
|
||||
|
||||
await executeAction("editor.lineEnd");
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 10, head: 14 });
|
||||
|
||||
await executeAction("editor.up");
|
||||
expect(view.state.selection.main.anchor).toBe(10);
|
||||
expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(1);
|
||||
});
|
||||
|
||||
it("moves the caret on the focused diff pane (editable and read-only sides)", async () => {
|
||||
const editable = makeView("one\ntwo", 5); // "t|wo"
|
||||
const readonly = makeView("old\nnew", 5, 5, true);
|
||||
useContextKeys.setState({ diffEditorFocus: true }, true);
|
||||
|
||||
editable.focus();
|
||||
await executeAction("editor.up");
|
||||
expect(editable.state.selection.main).toMatchObject({ anchor: 1, head: 1 });
|
||||
|
||||
readonly.focus();
|
||||
await executeAction("editor.lineEnd");
|
||||
expect(readonly.state.selection.main).toMatchObject({ anchor: 7, head: 7 });
|
||||
});
|
||||
|
||||
it("replaces preset chords and conflicting preset bindings when overridden in keymapOverrides", async () => {
|
||||
const view = makeView("line1\nline2", 8); // "li|ne2"
|
||||
_setFocusedCellEditor(view);
|
||||
|
||||
const copyPath = vi.fn();
|
||||
const hideActive = vi.fn();
|
||||
const commit = vi.fn();
|
||||
const cutLineEnd = vi.fn();
|
||||
const cleanup = [
|
||||
registerAction({ id: "editor.copyPath", title: "Copy Path", run: copyPath }),
|
||||
registerAction({ id: "toolwindow.hideActive", title: "Hide Active", run: hideActive }),
|
||||
registerAction({ id: "vcs.commit", title: "Commit", run: commit }),
|
||||
registerAction({
|
||||
id: "code.cutLineEnd",
|
||||
title: "Cut Line End",
|
||||
keyWhen: "editorTextFocus || diffEditorFocus",
|
||||
run: cutLineEnd,
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
const press = (init: KeyboardEventInit) =>
|
||||
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||
|
||||
// VS Code (macOS): Meta+K starts chords (`Meta+K P` etc.), Meta+J is `toolwindow.hideActive`.
|
||||
useKeymap.setState({
|
||||
preset: "vscode-macos",
|
||||
overrides: {
|
||||
"editor.up": ["Meta+K"],
|
||||
"editor.down": ["Meta+J"],
|
||||
},
|
||||
});
|
||||
press({ key: "k", code: "KeyK", metaKey: true });
|
||||
await Promise.resolve();
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 2, head: 2 });
|
||||
expect(copyPath).not.toHaveBeenCalled();
|
||||
|
||||
press({ key: "j", code: "KeyJ", metaKey: true });
|
||||
await Promise.resolve();
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 8, head: 8 });
|
||||
expect(hideActive).not.toHaveBeenCalled();
|
||||
|
||||
// IntelliJ (macOS): Meta+K is `vcs.commit` (listed after `editor.up`), Ctrl+K has `keyWhen`.
|
||||
useKeymap.setState({
|
||||
preset: "intellij-macos",
|
||||
overrides: {
|
||||
"editor.up": ["Meta+K", "Ctrl+K"],
|
||||
},
|
||||
});
|
||||
press({ key: "k", code: "KeyK", metaKey: true });
|
||||
await Promise.resolve();
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 2, head: 2 });
|
||||
expect(commit).not.toHaveBeenCalled();
|
||||
|
||||
// Move back down, then test overriding a keyWhen-gated preset shortcut (`Ctrl+K`).
|
||||
await executeAction("editor.down");
|
||||
press({ key: "k", code: "KeyK", ctrlKey: true });
|
||||
await Promise.resolve();
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 2, head: 2 });
|
||||
expect(cutLineEnd).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
for (const fn of cleanup) fn();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["en", "Move Caret Up", "Move Caret to Line Start with Selection"],
|
||||
["zh", "将光标向上移动", "将光标移至行首并选择"],
|
||||
["zh-TW", "將游標向上移動", "將游標移至行首並選擇"],
|
||||
])("has searchable %s titles", async (locale, upTitle, lineStartSelTitle) => {
|
||||
await setLocale(locale);
|
||||
expect(getAction("editor.up")?.title).toBe(upTitle);
|
||||
expect(getAction("editor.lineStartWithSelection")?.title).toBe(lineStartSelTitle);
|
||||
});
|
||||
});
|
||||
@@ -513,6 +513,10 @@ const richCopy = (byDefault: boolean) =>
|
||||
const richCopyByDefault = richCopy(true);
|
||||
const plainCopyByDefault = richCopy(false);
|
||||
|
||||
export function richTextCopyExtension(byDefault: boolean): Extension {
|
||||
return byDefault ? richCopyByDefault : plainCopyByDefault;
|
||||
}
|
||||
|
||||
// --- caret / scrolling / mouse ----------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -916,7 +920,7 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
if (g.caretScroll === "center") out.push(centerCaret);
|
||||
// Before rich-text copy: record selections, but own no-selection line copies and cuts.
|
||||
out.push(clipboardHistoryExtension(k));
|
||||
out.push(g.richTextCopy ? richCopyByDefault : plainCopyByDefault);
|
||||
out.push(richTextCopyExtension(g.richTextCopy));
|
||||
if (!g.highlightModifiedLines || !g.highlightModifiedLinesInScrollbar)
|
||||
out.push(
|
||||
changeMarkerDisplay.of({
|
||||
|
||||
@@ -98,8 +98,6 @@ export function prefsOf(settings: EditorSettings | undefined): EditorExtras {
|
||||
return editorPrefs({ editor: settings });
|
||||
}
|
||||
|
||||
export { HEAVY_LIMIT } from "@/editor/api";
|
||||
|
||||
export interface EffectiveIndent {
|
||||
tabSize: number;
|
||||
insertSpaces: boolean;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { foldedRanges, indentUnit, language as languageFacet } from "@codemirror
|
||||
import { HEAVY_LIMIT, onEditorEvent, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api";
|
||||
import { createMemoryBackend, type MemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
import { heavyExtension } from "../cm/setup";
|
||||
import { DocumentManager, ModifiedRanges, saveCleanupChanges, useDocMeta } from "./document";
|
||||
import { EditorSlot, type SlotHost } from "./slot";
|
||||
import { formatOptionsOf } from "@/editor/lsp/format";
|
||||
@@ -146,12 +147,97 @@ describe("DocumentManager + slots", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Palette.kt", "fun greet() {}", 1],
|
||||
["demo.py", "def greet(): pass", 0],
|
||||
["demo.ex", "defmodule Demo do\nend", 1],
|
||||
["Large.kt", " ".repeat(HEAVY_LIMIT + 1), 1],
|
||||
])("debounces backend highlights after an edit burst in %s", async (name, text, requests) => {
|
||||
["allowed by the backend", HEAVY_LIMIT + 1, false, true],
|
||||
["blocked by the backend", 128, true, false],
|
||||
] as const)("loads Go syntax for documents %s", async (_case, size, large, allowed) => {
|
||||
const path = "/p/service.pb.go";
|
||||
const { backend, manager, frame } = setup({ [path]: "package p\n".padEnd(size, " ") });
|
||||
const open = backend.open.bind(backend);
|
||||
vi.spyOn(backend, "open").mockImplementation(async (file) => ({ ...(await open(file)), uiMode: "Go", large }));
|
||||
const folding = vi.spyOn(backend, "folding");
|
||||
try {
|
||||
const model = await manager.acquire(path);
|
||||
await model.loadLanguage();
|
||||
await frame();
|
||||
expect(Boolean(model.language)).toBe(allowed);
|
||||
expect(!!model.ctx().large).toBe(large);
|
||||
expect(model.getMeta().readOnly).toBe(false);
|
||||
expect(model.getMeta().banner).toBe(allowed ? null : "codeInsightDisabled");
|
||||
if (large) expect(folding).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains the per-line decoration limit independently of language support", () => {
|
||||
expect(heavyExtension(HEAVY_LIMIT)).not.toEqual([]);
|
||||
expect(heavyExtension(HEAVY_LIMIT + 1)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[false, "codeInsightDisabled"],
|
||||
[true, "tooLarge"],
|
||||
] as const)("distinguishes the editing limit from the insight limit (tooLarge=%s)", async (tooLarge, banner) => {
|
||||
const path = "/p/generated.go";
|
||||
const { backend, manager } = setup({ [path]: "package p" });
|
||||
const open = backend.open.bind(backend);
|
||||
vi.spyOn(backend, "open").mockImplementation(async (file) => ({
|
||||
...(await open(file)),
|
||||
readOnly: true,
|
||||
large: true,
|
||||
tooLarge,
|
||||
}));
|
||||
try {
|
||||
const model = await manager.acquire(path);
|
||||
expect(model.getMeta().banner).toBe(banner);
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([false, true])("honours the backend size flag in a read-only virtual document (large=%s)", async (large) => {
|
||||
const uri = "git:/project/logic.pb.go";
|
||||
const { backend, manager } = setup({ [uri]: "package p" });
|
||||
const openVirtual = backend.openVirtual.bind(backend);
|
||||
vi.spyOn(backend, "openVirtual").mockImplementation(async (path) => ({
|
||||
...(await openVirtual(path)),
|
||||
uiMode: "Go",
|
||||
large,
|
||||
}));
|
||||
try {
|
||||
const model = await manager.acquire(uri);
|
||||
await model.loadLanguage();
|
||||
expect(Boolean(model.language)).toBe(!large);
|
||||
expect(model.ctx().virtual).toBe(true);
|
||||
expect(model.getMeta().banner).toBeNull();
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("enables language support for an untitled buffer without a size flag", async () => {
|
||||
const { backend, manager } = setup({});
|
||||
try {
|
||||
const model = manager.adopt(await backend.openUntitled(null));
|
||||
model.setLanguage("go", "Go");
|
||||
await model.loadLanguage();
|
||||
expect(model.language).not.toBeNull();
|
||||
expect(model.ctx().large).toBeFalsy();
|
||||
expect(model.ctx().virtual).toBeFalsy();
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Palette.kt", "fun greet() {}", 1, false],
|
||||
["demo.py", "def greet(): pass", 0, false],
|
||||
["demo.ex", "defmodule Demo do\nend", 1, false],
|
||||
["Large.kt", " ".repeat(HEAVY_LIMIT + 1), 0, true],
|
||||
] as const)("debounces backend highlights after an edit burst in %s", async (name, text, requests, large) => {
|
||||
const { backend, manager, frame } = setup({ [`/p/${name}`]: text });
|
||||
const open = backend.open.bind(backend);
|
||||
vi.spyOn(backend, "open").mockImplementation(async (file) => ({ ...(await open(file)), large }));
|
||||
const highlights = vi.spyOn(backend, "highlights");
|
||||
try {
|
||||
const model = await manager.acquire(`/p/${name}`);
|
||||
|
||||
@@ -58,7 +58,6 @@ import {
|
||||
readOnlyExtension,
|
||||
stickyExtension,
|
||||
wrapExtension,
|
||||
HEAVY_LIMIT,
|
||||
} from "../cm/setup";
|
||||
import { localAppearanceField, setMethodLines, softWrapActive } from "../cm/prefs";
|
||||
import type { EditorSlot } from "./slot";
|
||||
@@ -114,7 +113,7 @@ export function docCommentFolds(state: EditorState, info: LanguageInfo | undefin
|
||||
);
|
||||
}
|
||||
|
||||
export type Banner = "binary" | "tooLarge" | "readOnly" | "library" | null;
|
||||
export type Banner = "binary" | "tooLarge" | "codeInsightDisabled" | "readOnly" | "library" | null;
|
||||
|
||||
/** A view attached to a document outside the tab system (see `attachment.ts`). */
|
||||
export interface DocAttachmentTarget {
|
||||
@@ -156,11 +155,10 @@ function bannerFor(info: DocumentInfo): Banner {
|
||||
// Virtual documents (library classes) get their own notice from the editor area.
|
||||
if (info.uri) return null;
|
||||
if (isLibraryPath(info.path)) return "library";
|
||||
if (!info.readOnly) return null;
|
||||
if (!info.text.length) return "binary";
|
||||
// The backend makes files above its size limit read-only and flags them `large`.
|
||||
if (info.large) return "tooLarge";
|
||||
return "readOnly";
|
||||
if (info.readOnly && !info.text.length) return "binary";
|
||||
if (info.tooLarge ?? (info.readOnly && info.large)) return "tooLarge";
|
||||
if (info.large) return "codeInsightDisabled";
|
||||
return info.readOnly ? "readOnly" : null;
|
||||
}
|
||||
|
||||
/** Ranges touched since the last save (in current-document coordinates). */
|
||||
@@ -301,8 +299,8 @@ export class DocModel {
|
||||
editorconfig: EditorConfigProps | null = null;
|
||||
desc: LanguageDescription | null;
|
||||
language: LanguageSupport | null;
|
||||
/** Too large for language support (no CodeMirror language, backend highlighting only). */
|
||||
private large: boolean;
|
||||
/** The backend's code insight size decision when the document was opened. */
|
||||
private readonly large: boolean;
|
||||
/** The backend's mode for this file over its language's (an Angular project's templates). */
|
||||
private ownUiMode: string | null;
|
||||
lastFocused: EditorSlot | null = null;
|
||||
@@ -328,13 +326,11 @@ export class DocModel {
|
||||
this.virtual = !!info.uri && !isUntitledUri(info.path);
|
||||
this.info = languageInfo(info.language);
|
||||
this.editorconfig = info.editorconfig ?? null;
|
||||
// `large`: the backend skips LSP and syntax trees for it; heavy UI features follow.
|
||||
const large = !!info.large || info.text.length > HEAVY_LIMIT;
|
||||
this.large = large;
|
||||
this.large = !!info.large;
|
||||
// The document's own mode (an Angular project's templates) wins over the language's.
|
||||
this.ownUiMode = info.uiMode ?? null;
|
||||
const uiMode = this.ownUiMode ?? this.info?.uiMode ?? null;
|
||||
this.desc = large ? null : findLanguageDescription(uiMode, info.path);
|
||||
this.desc = this.large ? null : findLanguageDescription(uiMode, info.path);
|
||||
this.language = loadedSupport(this.desc);
|
||||
this.meta = {
|
||||
doc: info.id,
|
||||
@@ -429,6 +425,7 @@ export class DocModel {
|
||||
language: this.meta.language,
|
||||
uiMode: this.meta.uiMode,
|
||||
readOnly: this.meta.readOnly,
|
||||
...(this.large ? { large: true } : {}),
|
||||
...(this.virtual ? { virtual: true } : {}),
|
||||
};
|
||||
}
|
||||
@@ -698,7 +695,7 @@ export class DocModel {
|
||||
// --- background refresh (folding ranges, outline) -------------------------
|
||||
|
||||
scheduleRefresh(delay = REFRESH_DELAY) {
|
||||
if (this.meta.banner === "binary" || this.meta.banner === "tooLarge") return;
|
||||
if (this.large || this.meta.banner === "binary") return;
|
||||
clearTimeout(this.refreshTimer);
|
||||
this.refreshTimer = setTimeout(() => void this.refresh(), delay);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useLibrarySources } from "../librarySources";
|
||||
const TEXT = {
|
||||
binary: "This file appears to be binary and is shown read-only.",
|
||||
tooLarge: "The file is too large: editing and code insight are disabled.",
|
||||
codeInsightDisabled: "Code insight is disabled for this file because of its size.",
|
||||
readOnly: "The file is read-only.",
|
||||
library: "Library source (read-only).",
|
||||
} as const;
|
||||
|
||||
@@ -5,6 +5,21 @@ import { useDocMeta, type DocMeta } from "../model/document";
|
||||
import { documentBanner, EditorBanners, VirtualBanner } from "./Banner";
|
||||
|
||||
describe("editor banners", () => {
|
||||
it.each([
|
||||
["codeInsightDisabled", "Code insight is disabled for this file because of its size."],
|
||||
["tooLarge", "The file is too large: editing and code insight are disabled."],
|
||||
] as const)("explains the restrictions for %s", (banner, message) => {
|
||||
const off = registerEditorBanner(documentBanner);
|
||||
const path = "/p/large.go";
|
||||
act(() => useDocMeta.setState({ [path]: { banner } as DocMeta }));
|
||||
try {
|
||||
render(<EditorBanners path={path} />);
|
||||
expect(screen.getByRole("status").textContent).toBe(message);
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["jdt://contents/lib.jar/p/Lib.class", true, "Decompiled .class file: sources are not available."],
|
||||
["csharp:/p/App.csproj/decompiled/Lib.cs", true, "Decompiled assembly (read-only)."],
|
||||
|
||||
@@ -71,7 +71,7 @@ export function lspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
intentionsExtension(),
|
||||
inlayExtension(),
|
||||
inlineCompletionExtension(),
|
||||
semanticExtension(),
|
||||
semanticExtension(ctx),
|
||||
usagesLensExtension(),
|
||||
autoImportExtension(),
|
||||
jsxAttrValueExtension(ctx.language),
|
||||
@@ -109,7 +109,7 @@ export function cellLspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
* (revisions) get nothing from the semantic extension (`docOf` is null).
|
||||
*/
|
||||
export function diffLspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension(), semanticExtension()];
|
||||
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension(), semanticExtension(ctx)];
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
|
||||
@@ -47,6 +47,13 @@ async function editor(extensions: Extension[]) {
|
||||
}
|
||||
|
||||
describe("semantic decorations vs the syntax highlighter", () => {
|
||||
it("skips semantic highlighting for documents above the backend's code insight limit", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = await editor([semanticExtension({ large: true })]);
|
||||
expect(lspSemanticTokens).not.toHaveBeenCalled();
|
||||
expect(view.contentDOM.querySelector(".cm-sem-property")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps semantic roles inside supplemental backend syntax marks", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = await editor([syntaxHighlightField, syntaxHighlighting(openideaHighlightStyle), semanticExtension()]);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { syntaxTree } from "@codemirror/language";
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { commands, type SemanticTokens } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { debounce, docOf, isUnavailable, lspRequest } from "../lsp";
|
||||
@@ -335,7 +336,8 @@ const semanticPlugin = ViewPlugin.fromClass(
|
||||
},
|
||||
);
|
||||
|
||||
export function semanticExtension(): Extension {
|
||||
export function semanticExtension(ctx?: Pick<EditorDocContext, "large">): Extension {
|
||||
if (ctx?.large) return [];
|
||||
// Higher-precedence decoration sources create the *inner* DOM nodes, so this
|
||||
// must outrank Lezer's highlighter for Color Scheme attributes to win.
|
||||
// `Prec.highest`, not `Prec.high`: the
|
||||
|
||||
@@ -26,7 +26,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: AGENT_PLUGINS_PAGE,
|
||||
title: "Plugins",
|
||||
group: AGENTS_GROUP,
|
||||
order: 470,
|
||||
order: 480,
|
||||
keywords: ["agent plugins", "plugin.json", "marketplace", "bundles", "claude-plugin", "codex-plugin", "gemini"],
|
||||
component: lazyComponent(() => import("./AgentPluginsPage").then((m) => m.AgentPluginsPage)),
|
||||
},
|
||||
@@ -34,7 +34,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: MCP_PAGE,
|
||||
title: "MCP Connections",
|
||||
group: AGENTS_GROUP,
|
||||
order: 475,
|
||||
order: 464,
|
||||
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
|
||||
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
|
||||
},
|
||||
@@ -42,7 +42,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: SKILLS_PAGE,
|
||||
title: "Skills",
|
||||
group: AGENTS_GROUP,
|
||||
order: 480,
|
||||
order: 470,
|
||||
keywords: ["skills", "skill", "skill.md", "agents", "slash commands", "auto", "slash only"],
|
||||
component: lazyComponent(() => import("./SkillsPage").then((m) => m.SkillsPage)),
|
||||
},
|
||||
@@ -50,7 +50,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: MEMORY_PAGE,
|
||||
title: "Memory",
|
||||
group: AGENTS_GROUP,
|
||||
order: 485,
|
||||
order: 475,
|
||||
keywords: ["memory", "memories", "agents.md", "claude.md", "instructions", "rules", "auto memory"],
|
||||
component: lazyComponent(() => import("./MemoryPage").then((m) => m.MemoryPage)),
|
||||
},
|
||||
@@ -58,7 +58,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: AUTOMATIONS_PAGE,
|
||||
title: "Automations",
|
||||
group: AGENTS_GROUP,
|
||||
order: 488,
|
||||
order: 485,
|
||||
keywords: ["automations", "cron", "schedule", "loop", "send later", "daemon", "worktree", "reboot"],
|
||||
component: lazyComponent(() => import("./AutomationsSettingsPage").then((m) => m.AutomationsSettingsPage)),
|
||||
},
|
||||
@@ -66,7 +66,7 @@ export function activateSettingsPages(): () => void {
|
||||
id: POLICY_PAGE,
|
||||
title: "Command Rules",
|
||||
group: AGENTS_GROUP,
|
||||
order: 490,
|
||||
order: 462,
|
||||
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "exec"],
|
||||
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
|
||||
},
|
||||
|
||||
@@ -645,8 +645,6 @@ type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" | "toolOutput"
|
||||
|
||||
/** Entry events that arrived while their conversation loaded, applied on top of the copy it loads. */
|
||||
const arrivedWhileLoading = new Map<string, EntryEvent[]>();
|
||||
/** Whether the message each task streams now is the agent's reply, known without its conversation. */
|
||||
const streamingReply = new Map<string, { index: number; reply: boolean }>();
|
||||
|
||||
/** `entries` with the event applied; `null` when the copy can't take it. */
|
||||
function applyEntryEvent(entries: AgentEntry[], e: EntryEvent): AgentEntry[] | null {
|
||||
@@ -691,7 +689,7 @@ function forgetClosed(taskId: string) {
|
||||
if (idx >= 0) closedTaskMru.splice(idx, 1);
|
||||
}
|
||||
|
||||
function clearTaskMaps(taskId: string, clearStreaming = false) {
|
||||
function clearTaskMaps(taskId: string) {
|
||||
forgetClosed(taskId);
|
||||
for (const key of [...arrivedWhileLoading.keys()]) {
|
||||
if (isTaskKey(key, taskId)) arrivedWhileLoading.delete(key);
|
||||
@@ -701,7 +699,6 @@ function clearTaskMaps(taskId: string, clearStreaming = false) {
|
||||
for (const key of [...positions.keys()]) {
|
||||
if (isTaskKey(key, taskId)) positions.delete(key);
|
||||
}
|
||||
if (clearStreaming) streamingReply.delete(taskId);
|
||||
cancelScheduledChanges(taskId);
|
||||
const last = changeRefreshes.get(taskId);
|
||||
if (last) last.cache.dropped = true;
|
||||
@@ -793,7 +790,6 @@ export function releaseClosedTaskCache(taskId: string) {
|
||||
export function disconnect() {
|
||||
generation++;
|
||||
arrivedWhileLoading.clear();
|
||||
streamingReply.clear();
|
||||
modelFlights.clear();
|
||||
closedTaskMru.length = 0;
|
||||
clearChangeRefreshes();
|
||||
@@ -864,7 +860,7 @@ function onEvent(e: AgentEvent) {
|
||||
break;
|
||||
}
|
||||
case "removed": {
|
||||
clearTaskMaps(e.id, true);
|
||||
clearTaskMaps(e.id);
|
||||
const tasks = new Map(s.tasks);
|
||||
tasks.delete(e.id);
|
||||
const composers = new Map(s.composers);
|
||||
@@ -914,30 +910,13 @@ function onEvent(e: AgentEvent) {
|
||||
break;
|
||||
}
|
||||
case "entry": {
|
||||
if (
|
||||
!e.subagent &&
|
||||
((e.entry.type === "agent" && e.entry.text.trim()) ||
|
||||
e.entry.type === "error" ||
|
||||
(e.entry.type === "permission" && e.entry.chosen === null))
|
||||
) {
|
||||
markUnread(e.task);
|
||||
}
|
||||
if (!e.subagent) streamingReply.set(e.task, { index: e.index, reply: e.entry.type === "agent" });
|
||||
onEntryEvent(s, e);
|
||||
if (e.entry.type === "tool" && e.entry.status === "completed" && e.entry.diffs.length) {
|
||||
scheduleChanges(e.task);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "append": {
|
||||
if (!e.subagent && e.text.trim()) {
|
||||
const shown = s.entries.get(entriesKey(e.task, null))?.[e.index];
|
||||
const streaming = streamingReply.get(e.task);
|
||||
if (shown ? shown.type === "agent" : streaming?.index === e.index && streaming.reply) markUnread(e.task);
|
||||
}
|
||||
onEntryEvent(s, e);
|
||||
break;
|
||||
}
|
||||
case "append":
|
||||
case "toolOutput": {
|
||||
onEntryEvent(s, e);
|
||||
break;
|
||||
|
||||
@@ -103,6 +103,10 @@ const task = (id: string, status: AgentTask["status"] = "running"): AgentTask =>
|
||||
const emit = (event: AgentEvent) => act(() => backend.channel!.onmessage(event));
|
||||
const reply = (id = "one", text = "New reply") =>
|
||||
emit({ type: "entry", task: id, subagent: null, index: 0, entry: { type: "agent", text } });
|
||||
const finished = (id = "one") => {
|
||||
emit({ type: "task", task: { ...task(id, "ready"), unread: true } });
|
||||
emit({ type: "attention", task: id, eventId: `${id}:finished:1`, reason: "finished" });
|
||||
};
|
||||
const visible: Array<() => void> = [];
|
||||
const show = (id = "one") => {
|
||||
let hide!: () => void;
|
||||
@@ -194,22 +198,18 @@ describe("in-flight change reads", () => {
|
||||
});
|
||||
|
||||
describe("agent unread activity", () => {
|
||||
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
|
||||
it.each([false, true])("waits for completion before marking a streaming reply unread (cached: %s)", (cached) => {
|
||||
if (cached) useAgents.setState({ entries: new Map([["one", []]]) });
|
||||
reply("one", "Working");
|
||||
emit({ type: "append", task: "one", subagent: null, index: 0, from: 7, text: " on it" });
|
||||
if (cached) expect(useAgents.getState().entries.get("one")).toEqual([{ type: "agent", text: "Working on it" }]);
|
||||
else expect(useAgents.getState().entries.has("one")).toBe(false);
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
reply();
|
||||
reply("one", "New reply, streamed further");
|
||||
reply("two");
|
||||
expect([...useAgents.getState().unread]).toEqual(["one", "two"]);
|
||||
expect(useAgents.getState().entries.size).toBe(0);
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tracks a reply that streams on as appends, but not a thought", () => {
|
||||
reply("one", "");
|
||||
emit({ type: "append", task: "one", subagent: null, index: 0, from: 0, text: "Done" });
|
||||
emit({ type: "entry", task: "two", subagent: null, index: 0, entry: { type: "thought", text: "" } });
|
||||
emit({ type: "append", task: "two", subagent: null, index: 0, from: 0, text: "Hmm" });
|
||||
finished();
|
||||
expect([...useAgents.getState().unread]).toEqual(["one"]);
|
||||
expect(backend.notify).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -244,11 +244,13 @@ describe("agent unread activity", () => {
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
});
|
||||
|
||||
it("ignores user messages, thoughts, empty replies and subagent streaming", () => {
|
||||
it("keeps transcript entries and subagent activity from raising unread on their own", () => {
|
||||
const entries: AgentEntry[] = [
|
||||
{ type: "user", text: "Do this", attachments: [] },
|
||||
{ type: "thought", text: "Thinking" },
|
||||
{ type: "agent", text: " " },
|
||||
{ type: "permission", id: 1, title: "Run command", options: [], chosen: null },
|
||||
{ type: "error", message: "Retrying" },
|
||||
];
|
||||
for (const entry of entries) emit({ type: "entry", task: "one", subagent: null, index: 0, entry });
|
||||
emit({ type: "entry", task: "one", subagent: "child", index: 0, entry: { type: "agent", text: "Working" } });
|
||||
@@ -257,47 +259,46 @@ describe("agent unread activity", () => {
|
||||
});
|
||||
|
||||
it("clears only the viewed task and keeps reading while either split shows it", () => {
|
||||
reply();
|
||||
reply("two");
|
||||
finished();
|
||||
finished("two");
|
||||
const hide = show();
|
||||
show();
|
||||
hide();
|
||||
reply();
|
||||
emit({ type: "task", task: task("one", "ready") });
|
||||
finished();
|
||||
expect([...useAgents.getState().unread]).toEqual(["two"]);
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
expect(backend.notify).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps a visible session unread while the window is unfocused, then clears on focus", () => {
|
||||
vi.mocked(document.hasFocus).mockReturnValue(false);
|
||||
reply();
|
||||
finished();
|
||||
show();
|
||||
expect(useAgents.getState().unread.has("one")).toBe(true);
|
||||
vi.mocked(document.hasFocus).mockReturnValue(true);
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
reply();
|
||||
finished();
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not read hidden windows and removes focus listeners when the session closes", () => {
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
|
||||
const hide = show();
|
||||
reply();
|
||||
finished();
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(useAgents.getState().unread.has("one")).toBe(true);
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
|
||||
fireEvent(document, new Event("visibilitychange"));
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
hide();
|
||||
reply();
|
||||
finished();
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(useAgents.getState().unread.has("one")).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans up archived and deleted tasks, ignores late replies, and resets on project switch", async () => {
|
||||
reply();
|
||||
reply("two");
|
||||
finished();
|
||||
finished("two");
|
||||
emit({ type: "task", task: task("one", "archived") });
|
||||
reply();
|
||||
expect([...useAgents.getState().unread]).toEqual(["two"]);
|
||||
@@ -305,7 +306,7 @@ describe("agent unread activity", () => {
|
||||
reply("two");
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
emit({ type: "task", task: task("one") });
|
||||
reply();
|
||||
finished();
|
||||
const oldChannel = backend.channel!;
|
||||
disconnect();
|
||||
backend.tasks = [task("other")];
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { RootFolder } from "@/platform/languageSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useBuildPresentation } from "@/platform/projectPresentation";
|
||||
import { useProjectRoots } from "@/platform/projectRoots";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { newMenuItems } from "./contextMenu";
|
||||
@@ -56,6 +57,24 @@ describe("New › Package", () => {
|
||||
expect(packageKindAt("py/src", [], py)).toBe("python");
|
||||
});
|
||||
|
||||
it("is offered inside a root marked by hand in a Maven or Gradle module", () => {
|
||||
const marked = [...MAVEN, root("src", "source", null), root("tools/gen", "test", null)];
|
||||
expect(packageKindAt("src/com", marked)).toBeNull();
|
||||
try {
|
||||
useBuildPresentation.setState({ modules: new Map([["", "maven"]]) });
|
||||
expect(packageKindAt("src", marked)).toBe("jvm");
|
||||
expect(packageKindAt("src/com/wyh", marked)).toBe("jvm");
|
||||
expect(packageKindAt("tools/gen", marked)).toBe("jvm");
|
||||
useBuildPresentation.setState({ modules: new Map([["app", "gradle"]]) });
|
||||
expect(packageKindAt("src", marked)).toBeNull();
|
||||
expect(packageKindAt("app/src", [root("app/src", "source", null)])).toBe("jvm");
|
||||
// Resources roots stay plain directories.
|
||||
expect(packageKindAt("app/res", [root("app/res", "resources", null)])).toBeNull();
|
||||
} finally {
|
||||
useBuildPresentation.setState({ modules: new Map() });
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the default layout a Gradle sync reports", () => {
|
||||
// Package in java roots, Directory in resources, as before.
|
||||
const synced = [
|
||||
|
||||
@@ -85,6 +85,27 @@ async function openDialog(page?: string) {
|
||||
}
|
||||
|
||||
describe("Settings dialog", () => {
|
||||
it("applies a whole-number code insight file size limit from Editor General", async () => {
|
||||
const dialog = await openDialog("editor.general");
|
||||
const limit = within(dialog).getByLabelText("Maximum file size for code insight");
|
||||
const apply = within(dialog).getByRole("button", { name: "Apply" });
|
||||
expect(limit).toHaveValue("5");
|
||||
expect(within(dialog).getByText("Reopen files to apply the new limit.")).toBeInTheDocument();
|
||||
|
||||
for (const invalid of ["0", "51", "2.5"]) {
|
||||
fireEvent.change(limit, { target: { value: invalid } });
|
||||
expect(limit).toHaveAttribute("aria-invalid", "true");
|
||||
fireEvent.blur(limit);
|
||||
expect(limit).toHaveValue("5");
|
||||
expect(apply).toBeDisabled();
|
||||
}
|
||||
fireEvent.change(limit, { target: { value: "10" } });
|
||||
expect(settingsSet).not.toHaveBeenCalled();
|
||||
await act(async () => fireEvent.click(apply));
|
||||
expect(settingsSet).toHaveBeenCalledWith("global", "editor.maxCodeInsightFileSizeMb", "10");
|
||||
expect(validateSettings(useProject.getState().settings).editor.maxCodeInsightFileSizeMb).toBe(10);
|
||||
});
|
||||
|
||||
it("copies the current Settings page path through the IDEA action", async () => {
|
||||
expect(getAction("settings.copyPath")).toMatchObject({
|
||||
title: "Copy Settings Path",
|
||||
|
||||
@@ -64,6 +64,7 @@ describe("languages settings", () => {
|
||||
threads: "2C",
|
||||
activeProfiles: "",
|
||||
delegateBuild: false,
|
||||
ignoredCompileGoals: [],
|
||||
downloadSources: false,
|
||||
updateSnapshots: false,
|
||||
runTestsUsing: "ide",
|
||||
@@ -72,6 +73,14 @@ describe("languages settings", () => {
|
||||
expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe("");
|
||||
});
|
||||
|
||||
it("preserves explicit Maven compile-goal overrides without enabling delegation", () => {
|
||||
const goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
const settings = validateSettings({ languages: { java: { maven: { ignoredCompileGoals: [goal] } } } });
|
||||
expect(settings.languages.java.maven).toMatchObject({ ignoredCompileGoals: [goal], delegateBuild: false });
|
||||
expect(validateSettings(settings).languages.java.maven.ignoredCompileGoals).toEqual([goal]);
|
||||
expect(validateSettings({}).languages.java.maven.ignoredCompileGoals).toEqual([]);
|
||||
});
|
||||
|
||||
it("defaults the Maven runner JRE to the project JDK and preserves a chosen JDK", () => {
|
||||
expect(validateSettings({}).languages.java.maven.runnerJre).toBe("");
|
||||
expect(validateSettings({}).languages.java.maven.delegateBuild).toBe(false);
|
||||
|
||||
@@ -38,9 +38,17 @@
|
||||
min-width: 0;
|
||||
}
|
||||
.formGroup > .row,
|
||||
.formGroup > .formGroup {
|
||||
.formGroup > .formGroup,
|
||||
.formGroup > .section,
|
||||
.formGroup > .section > .sectionBody {
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
.formGroup > .section {
|
||||
display: grid;
|
||||
}
|
||||
.formGroup > .section > * {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.formGroup > .stacked,
|
||||
.formGroup > .toggleRow {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useCallback, useEffect, useId, useMemo, useState } from "react";
|
||||
import { call, commands, type FlutterVersion, type Sdk } from "@/platform/ipc";
|
||||
import { IconButton, Input, type SelectOption, T } from "@/ui";
|
||||
import { JAVA_LANGUAGE_LEVELS, PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
|
||||
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
|
||||
import { FormGroup, GlobListEditor, Row, Section, Select, Toggle, type RowProps } from "../components/Form";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
|
||||
@@ -19,6 +19,14 @@ import { mavenHomeProblem } from "./mavenHome";
|
||||
import { PathField, PathInput } from "./PathInput";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
function FieldRow({ children, ...row }: RowProps) {
|
||||
return (
|
||||
<Row {...row}>
|
||||
<span className={styles.alignedField}>{children}</span>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
function SdkRow({
|
||||
k,
|
||||
label,
|
||||
@@ -47,9 +55,9 @@ function RunTargetRow({ language }: { language: "php" | "node" }) {
|
||||
if (target && target !== "local" && !targets.some((t) => t.id === target))
|
||||
options.push({ value: target, label: tx`Run in target ${target}` });
|
||||
return (
|
||||
<Row label="Run in target">
|
||||
<FieldRow label="Run in target">
|
||||
<Select value={target ?? ""} options={options} onChange={setTarget} aria-label="Run in target" />
|
||||
</Row>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -80,19 +88,19 @@ export function NodePage() {
|
||||
[list],
|
||||
);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section>
|
||||
<Row
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section stackFields>
|
||||
<FieldRow
|
||||
label="Preferred runtime"
|
||||
hint="Runs JavaScript and TypeScript files from the gutter and the editor's Run action."
|
||||
>
|
||||
<Select value={runtime} options={RUNTIME_OPTIONS} onChange={setRuntime} aria-label="Preferred runtime" />
|
||||
</Row>
|
||||
<Row label="Package manager" hint="Used by the npm run configurations detected from package.json scripts.">
|
||||
</FieldRow>
|
||||
<FieldRow label="Package manager" hint="Used by the npm run configurations detected from package.json scripts.">
|
||||
<Select value={pm} options={pmOptions} onChange={setPm} aria-label="Package manager" />
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
<Section title="Node.js">
|
||||
<Section title="Node.js" stackFields>
|
||||
<SdkRow
|
||||
k="languages.node.interpreter"
|
||||
label="Node interpreter"
|
||||
@@ -105,7 +113,7 @@ export function NodePage() {
|
||||
/>
|
||||
<RunTargetRow language="node" />
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -162,14 +170,14 @@ export function PhpPage() {
|
||||
const selected = list.find((s) => s.path === (interpreter || pathPhp));
|
||||
const xdebug = useXdebug(selected);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section>
|
||||
<Row
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section stackFields>
|
||||
<FieldRow
|
||||
label="PHP language level"
|
||||
hint="The PHP version Intelephense checks the code against: newer syntax and functions are reported. Auto uses config.platform.php from composer.json, else the lowest version require.php allows."
|
||||
>
|
||||
<Select value={level} options={PHP_LEVEL_OPTIONS} onChange={setLevel} aria-label="PHP language level" />
|
||||
</Row>
|
||||
</FieldRow>
|
||||
<Row
|
||||
label="Include paths"
|
||||
stacked
|
||||
@@ -200,7 +208,7 @@ export function PhpPage() {
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
<Section title="PHPStan">
|
||||
<Section title="PHPStan" stackFields>
|
||||
<PathInput
|
||||
k="languages.php.phpstanConfig"
|
||||
label="Configuration file"
|
||||
@@ -210,7 +218,7 @@ export function PhpPage() {
|
||||
file
|
||||
/>
|
||||
</Section>
|
||||
<Section title="CLI Interpreter">
|
||||
<Section title="CLI Interpreter" stackFields>
|
||||
<RunTargetRow language="php" />
|
||||
<SdkRow
|
||||
k="languages.php.interpreter"
|
||||
@@ -225,7 +233,7 @@ export function PhpPage() {
|
||||
{selected?.version && <Row label="Version">{selected.version}</Row>}
|
||||
{xdebug !== undefined && <Row label="Xdebug">{xdebug ?? <T>Not installed</T>}</Row>}
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -263,8 +271,8 @@ export function RustPage() {
|
||||
const selected = list.find((s) => s.path === toolchain);
|
||||
const argsId = useId();
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section title="Toolchain">
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section title="Toolchain" stackFields>
|
||||
<SdkRow
|
||||
k="languages.rust.toolchain"
|
||||
label="Toolchain location"
|
||||
@@ -284,8 +292,8 @@ export function RustPage() {
|
||||
hint="Sources of std for navigation and completion (RUST_SRC_PATH)."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="External Linters">
|
||||
<Row label="External tool">
|
||||
<Section title="External Linters" stackFields>
|
||||
<FieldRow label="External tool">
|
||||
<Select
|
||||
value={checkCommand}
|
||||
options={[
|
||||
@@ -295,7 +303,7 @@ export function RustPage() {
|
||||
onChange={setCheckCommand}
|
||||
aria-label="External tool"
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
<Toggle
|
||||
label="Run external linter on save"
|
||||
checked={checkOnSave}
|
||||
@@ -303,8 +311,8 @@ export function RustPage() {
|
||||
hint="rust-analyzer runs the tool after each save and reports its diagnostics."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Rustfmt">
|
||||
<Row
|
||||
<Section title="Rustfmt" stackFields>
|
||||
<FieldRow
|
||||
label="Additional arguments"
|
||||
htmlFor={argsId}
|
||||
hint="Passed to rustfmt when reformatting, e.g. --edition 2024"
|
||||
@@ -316,9 +324,9 @@ export function RustPage() {
|
||||
value={rustfmtArgs}
|
||||
onChange={(e) => setRustfmtArgs(e.target.value)}
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -330,8 +338,8 @@ export function GoPage() {
|
||||
const { list } = useDetected("go");
|
||||
const defaultGopath = list.find((s) => s.extra)?.extra;
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section title="GOROOT">
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section title="GOROOT" stackFields>
|
||||
<SdkRow
|
||||
k="languages.go.goroot"
|
||||
label="GOROOT"
|
||||
@@ -344,7 +352,7 @@ export function GoPage() {
|
||||
hint="Go SDK used by gopls and the go run / test configurations."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="GOPATH">
|
||||
<Section title="GOPATH" stackFields>
|
||||
<PathInput
|
||||
k="languages.go.gopath"
|
||||
label="Project GOPATH"
|
||||
@@ -352,7 +360,7 @@ export function GoPage() {
|
||||
title="Select GOPATH"
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Formatting">
|
||||
<Section title="Formatting" stackFields>
|
||||
<Toggle
|
||||
label="Format with gofumpt"
|
||||
checked={gofumpt}
|
||||
@@ -360,7 +368,7 @@ export function GoPage() {
|
||||
hint="gopls applies gofumpt's stricter rules on top of gofmt when reformatting."
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -385,8 +393,8 @@ export function JavaPage() {
|
||||
);
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section title="Project JDK">
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section title="Project JDK" stackFields>
|
||||
<SdkRow
|
||||
k="languages.java.jdk"
|
||||
label="SDK"
|
||||
@@ -398,7 +406,7 @@ export function JavaPage() {
|
||||
aria-label="Project JDK"
|
||||
hint="Compiles and runs the project: Run/Debug and JAVA_HOME for Maven and Gradle; it also runs jdtls when new enough for it."
|
||||
/>
|
||||
<Row
|
||||
<FieldRow
|
||||
label="Language level"
|
||||
hint="Java source and bytecode compliance level when no build descriptor overrides it."
|
||||
>
|
||||
@@ -408,9 +416,9 @@ export function JavaPage() {
|
||||
onChange={setLanguageLevel}
|
||||
aria-label="Java language level"
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
<Section title="Language Server">
|
||||
<Section title="Language Server" stackFields>
|
||||
<Toggle
|
||||
label="Share JDT LS across builds"
|
||||
checked={shared}
|
||||
@@ -434,7 +442,7 @@ export function JavaPage() {
|
||||
hint={jdtls.hint}
|
||||
minJava={jdtls.minJava}
|
||||
/>
|
||||
<Row
|
||||
<FieldRow
|
||||
label="JVM options"
|
||||
htmlFor={id}
|
||||
hint="Passed to the JVM running jdtls (java.jdt.ls.vmargs), e.g. -Xmx4g. jdtls runs with -XX:+UseG1GC -XX:G1PeriodicGCInterval=60000 -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=30 -Xmx2G -Xms100m by default; an option set here replaces the default for the same setting, and another collector (e.g. -XX:+UseZGC) replaces the default collector options. A Lombok agent is added automatically: the one installed in Language Servers, else, when the project uses Lombok (its build, an inherited parent POM or Gradle build, or its sources' imports), the newest from the Maven / Gradle caches."
|
||||
@@ -447,9 +455,9 @@ export function JavaPage() {
|
||||
placeholder="-Xmx4g"
|
||||
onChange={(e) => setVmArgs(e.target.value)}
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -461,8 +469,8 @@ export function GradlePage() {
|
||||
const [runUsing, setRunUsing] = useSetting<string>("languages.java.gradle.runUsing");
|
||||
const local = distribution === "local";
|
||||
return (
|
||||
<div className={styles.gradleSettings}>
|
||||
<Section>
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section stackFields>
|
||||
<PathInput
|
||||
k="languages.java.gradle.userHome"
|
||||
label="Gradle user home"
|
||||
@@ -471,8 +479,8 @@ export function GradlePage() {
|
||||
hint="Sets GRADLE_USER_HOME. Empty uses Gradle's default."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Build and Run">
|
||||
<Row
|
||||
<Section title="Build and Run" stackFields>
|
||||
<FieldRow
|
||||
label="Build and run using"
|
||||
hint="Gradle runs a main class as a JavaExec task on its source set's runtime classpath (Gradle's resource processing included). OpenIDEA launches it on the Java language server's classpath."
|
||||
>
|
||||
@@ -485,9 +493,9 @@ export function GradlePage() {
|
||||
{ value: "ide", label: "OpenIDEA" },
|
||||
]}
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
<Section title="Gradle runtime">
|
||||
<Section title="Gradle runtime" stackFields>
|
||||
<Row
|
||||
label="Distribution"
|
||||
hint={
|
||||
@@ -496,7 +504,7 @@ export function GradlePage() {
|
||||
: "Uses the Gradle wrapper when present, otherwise the project-pinned mise/asdf Gradle, then Gradle on PATH."
|
||||
}
|
||||
>
|
||||
<div className={styles.gradleDistribution}>
|
||||
<div className={local ? styles.localDistribution : styles.alignedField}>
|
||||
<Select
|
||||
value={distribution}
|
||||
onChange={setDistribution}
|
||||
@@ -527,7 +535,7 @@ export function GradlePage() {
|
||||
hint="JDK used for Gradle sync, tasks, run configurations and tests. An explicit JAVA_HOME in a run configuration takes precedence."
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -544,8 +552,8 @@ export function MavenPage() {
|
||||
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={styles.mavenSettings}>
|
||||
<Section>
|
||||
<FormGroup className={styles.toolchainSettings}>
|
||||
<Section stackFields>
|
||||
<Toggle
|
||||
label="Always update snapshots"
|
||||
checked={updateSnapshots}
|
||||
@@ -617,7 +625,7 @@ export function MavenPage() {
|
||||
hint="Passed as -t; selects the JDKs Maven compiles with."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Importing">
|
||||
<Section title="Importing" stackFields>
|
||||
<Toggle
|
||||
label="Automatically download sources"
|
||||
checked={downloadSources}
|
||||
@@ -632,7 +640,7 @@ export function MavenPage() {
|
||||
onChange={setDelegateBuild}
|
||||
hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server."
|
||||
/>
|
||||
<Row
|
||||
<FieldRow
|
||||
label="Run tests using"
|
||||
hint="OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources."
|
||||
>
|
||||
@@ -645,7 +653,7 @@ export function MavenPage() {
|
||||
{ value: "maven", label: "Maven" },
|
||||
]}
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
<SdkRow
|
||||
k="languages.java.maven.runnerJre"
|
||||
label="JRE"
|
||||
@@ -656,7 +664,7 @@ export function MavenPage() {
|
||||
aria-label="JRE"
|
||||
hint="JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence."
|
||||
/>
|
||||
<Row
|
||||
<FieldRow
|
||||
label="Active profiles"
|
||||
htmlFor={`${id}-profiles`}
|
||||
hint="Comma-separated profiles (-P), combined with Maven tool window choices; !id excludes a profile. A run configuration’s own -P replaces these profiles."
|
||||
@@ -670,9 +678,9 @@ export function MavenPage() {
|
||||
onChange={(e) => setActiveProfiles(e.target.value)}
|
||||
aria-label="Active profiles"
|
||||
/>
|
||||
</Row>
|
||||
</FieldRow>
|
||||
</Section>
|
||||
<Section>
|
||||
<Section stackFields>
|
||||
<Toggle
|
||||
label="Use Maven Daemon (mvnd)"
|
||||
checked={daemon}
|
||||
@@ -687,7 +695,7 @@ export function MavenPage() {
|
||||
hint="The mvnd home (or its executable). Empty = $MVND_HOME, else mvnd on PATH."
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ import {
|
||||
type ProjectStructureValid,
|
||||
} from "@/platform/languageSettings";
|
||||
import { initProjectRoots, useDetectedRoots } from "@/platform/projectRoots";
|
||||
import { Row, SearchLabel, Section } from "../components/Form";
|
||||
import { FormGroup, Row, SearchLabel, Section } from "../components/Form";
|
||||
import { detectSdks, forgetSdk, rememberSdk, useSdks, type SdkKind } from "./api";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { DownloadJdkDialog } from "./DownloadJdkDialog";
|
||||
@@ -340,8 +340,8 @@ function ProjectSection() {
|
||||
const outId = useId();
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section title="Project">
|
||||
<FormGroup className={styles.projectSettings}>
|
||||
<Section title="Project" stackFields>
|
||||
<Row label="Project name" hint={root ?? "No project is currently open."}>
|
||||
<span className={styles.path}>{name || "Default Project"}</span>
|
||||
</Row>
|
||||
@@ -364,19 +364,21 @@ function ProjectSection() {
|
||||
label="Language level"
|
||||
hint="Default Java language level for source code assistance and compilation across project modules."
|
||||
>
|
||||
<Select
|
||||
value={languageLevel ?? ""}
|
||||
options={PROJECT_JAVA_LEVEL_OPTIONS}
|
||||
onChange={setLanguageLevel}
|
||||
aria-label="Project language level"
|
||||
/>
|
||||
<span className={styles.alignedField}>
|
||||
<Select
|
||||
value={languageLevel ?? ""}
|
||||
options={PROJECT_JAVA_LEVEL_OPTIONS}
|
||||
onChange={setLanguageLevel}
|
||||
aria-label="Project language level"
|
||||
/>
|
||||
</span>
|
||||
</Row>
|
||||
<Row
|
||||
label="Compiler output"
|
||||
htmlFor={outId}
|
||||
hint="Default directory where compiled classes are placed when not managed by Maven or Gradle."
|
||||
>
|
||||
<span className={styles.pathRow}>
|
||||
<span className={styles.alignedField}>
|
||||
<Input
|
||||
id={outId}
|
||||
mono
|
||||
@@ -386,6 +388,7 @@ function ProjectSection() {
|
||||
onChange={(e) => setCompilerOutput(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
className={styles.alignedBrowse}
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
@@ -401,7 +404,7 @@ function ProjectSection() {
|
||||
</span>
|
||||
</Row>
|
||||
</Section>
|
||||
<Section title="Language Server">
|
||||
<Section title="Language Server" stackFields>
|
||||
<Row label="JDK" hint={jdtls.hint}>
|
||||
<SdkField
|
||||
kind="jdk"
|
||||
@@ -416,7 +419,7 @@ function ProjectSection() {
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,38 @@
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.projectSettings {
|
||||
container: settings-content / inline-size;
|
||||
row-gap: var(--space-2);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.toolchainSettings {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.projectSettings .sdkField,
|
||||
.toolchainSettings .sdkField,
|
||||
.toolchainSettings .pathRow,
|
||||
.localDistribution,
|
||||
.alignedField {
|
||||
display: grid;
|
||||
/* Reserve the refresh and browse columns even on rows with fewer actions. */
|
||||
grid-template-columns: minmax(0, 1fr) repeat(2, 20px);
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
min-width: 0;
|
||||
}
|
||||
.alignedField > :first-child,
|
||||
.localDistribution > :first-child {
|
||||
max-width: none;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.alignedBrowse,
|
||||
.toolchainSettings .pathRow > button {
|
||||
grid-column: 3;
|
||||
}
|
||||
/* Editable ComboBox (Maven home): a text field with the combo's arrow inside its frame. */
|
||||
.sdkEditable {
|
||||
display: inline-flex;
|
||||
@@ -59,10 +91,8 @@
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.mavenSettings .sdkField,
|
||||
.mavenSettings .sdkEditable {
|
||||
.toolchainSettings .sdkEditable {
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.mavenThreads {
|
||||
@@ -328,28 +358,20 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.gradleSettings .pathRow {
|
||||
max-width: 560px;
|
||||
.localDistribution {
|
||||
grid-template-columns: minmax(0, 180px) minmax(0, 1fr) repeat(2, 20px);
|
||||
}
|
||||
|
||||
.gradleSettings .sdkField {
|
||||
min-width: 0;
|
||||
.localDistribution > .pathRow {
|
||||
grid-column: 2 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
|
||||
.gradleDistribution {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 560px;
|
||||
}
|
||||
|
||||
.gradleDistribution > :first-child {
|
||||
flex: 0 1 180px;
|
||||
}
|
||||
|
||||
.gradleDistribution > .pathRow {
|
||||
flex: 1 1 230px;
|
||||
@container settings-content (max-width: 600px) {
|
||||
.localDistribution {
|
||||
grid-template-columns: minmax(0, 1fr) repeat(2, 20px);
|
||||
}
|
||||
.localDistribution > .pathRow {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Project Structure */
|
||||
|
||||
@@ -52,3 +52,37 @@
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Share the input, browse and Test columns across both Subversion paths. */
|
||||
section > :has(> .svnPath) {
|
||||
grid-template-columns: fit-content(45%) minmax(0, 1fr) 20px max-content;
|
||||
}
|
||||
|
||||
.svnPath > div {
|
||||
grid-column: 2 / -1;
|
||||
}
|
||||
|
||||
.svnPath > div:first-of-type {
|
||||
display: grid;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
|
||||
.svnPath input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.svnConfig > label {
|
||||
padding-inline-start: var(--space-4);
|
||||
}
|
||||
|
||||
@container settings-content (max-width: 440px) {
|
||||
section > :has(> .svnPath) {
|
||||
grid-template-columns: minmax(0, 1fr) 20px max-content;
|
||||
}
|
||||
|
||||
.svnPath > label,
|
||||
.svnPath > div {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
max-width: 760px;
|
||||
}
|
||||
|
||||
.alignedFields button[aria-haspopup="listbox"] {
|
||||
width: min(320px, 100%);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -630,6 +630,7 @@ const ENCODINGS: SelectOption[] = ENCODING_CHOICES.map(([value, label]) => ({ va
|
||||
|
||||
const ENCODINGS_PAGE = editorPage({
|
||||
id: "editor.fileEncodings",
|
||||
alignFields: true,
|
||||
title: "File Encodings",
|
||||
order: 27,
|
||||
projectScope: true,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { MAX_CODE_INSIGHT_FILE_SIZE_MB } from "@/platform/editorSettings";
|
||||
import { commands, isTauri } from "@/platform/ipc";
|
||||
import { Checkbox, Icon, Radio, type IconName } from "@/ui";
|
||||
import { Row, SearchLabel, Select } from "../../components/Form";
|
||||
@@ -207,6 +208,20 @@ const GENERAL = editorPage({
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Large Files",
|
||||
items: [
|
||||
{
|
||||
t: "number",
|
||||
key: `${P}.maxCodeInsightFileSizeMb`,
|
||||
label: "Maximum file size for code insight",
|
||||
min: 1,
|
||||
max: MAX_CODE_INSIGHT_FILE_SIZE_MB,
|
||||
unit: "MiB",
|
||||
hint: "Reopen files to apply the new limit.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Save Files",
|
||||
items: [
|
||||
|
||||
@@ -10,7 +10,7 @@ import clsx from "clsx";
|
||||
import { Checkbox, Input, T, type SelectOption } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { NumberInput, Row, SearchLabel, Section, Select } from "../../components/Form";
|
||||
import { FormGroup, NumberInput, Row, SearchLabel, Section, Select } from "../../components/Form";
|
||||
import { useLabelMatch, usePageContext, useSetting } from "../../components/context";
|
||||
import type { PageSpec } from "../spec";
|
||||
import styles from "./Editor.module.css";
|
||||
@@ -67,6 +67,7 @@ export interface EditorPageDef {
|
||||
keywords?: string[];
|
||||
projectScope?: boolean;
|
||||
sections: EditorSection[];
|
||||
alignFields?: boolean;
|
||||
/** Rendered below the sections (previews, tables). */
|
||||
footer?: ComponentType;
|
||||
}
|
||||
@@ -324,18 +325,15 @@ export function ItemView({ item }: { item: Item }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function EditorSections({ sections }: { sections: EditorSection[] }) {
|
||||
return (
|
||||
<>
|
||||
{sections.map((s, i) => (
|
||||
<Section key={s.title ?? i} title={s.title}>
|
||||
{s.items.map((item, j) => (
|
||||
<ItemView key={itemKey(item, j)} item={item} />
|
||||
))}
|
||||
</Section>
|
||||
export function EditorSections({ sections, alignFields }: Pick<EditorPageDef, "sections" | "alignFields">) {
|
||||
const body = sections.map((s, i) => (
|
||||
<Section key={s.title ?? i} title={s.title} stackFields={alignFields}>
|
||||
{s.items.map((item, j) => (
|
||||
<ItemView key={itemKey(item, j)} item={item} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
</Section>
|
||||
));
|
||||
return alignFields ? <FormGroup className={styles.alignedFields}>{body}</FormGroup> : <>{body}</>;
|
||||
}
|
||||
|
||||
/** Search texts of an item tree (labels, option labels, custom keywords). */
|
||||
@@ -365,7 +363,7 @@ export function editorPage(def: EditorPageDef): PageSpec {
|
||||
const Footer = def.footer;
|
||||
const Page = () => (
|
||||
<div className={styles.page}>
|
||||
<EditorSections sections={def.sections} />
|
||||
<EditorSections sections={def.sections} alignFields={def.alignFields} />
|
||||
{Footer && <Footer />}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -289,7 +289,7 @@ export const MCP_SERVER_PAGE: PageSpec = {
|
||||
id: "agents.mcpServer",
|
||||
title: "IDE MCP Server",
|
||||
group: "Agents",
|
||||
order: 470,
|
||||
order: 466,
|
||||
keywords: [
|
||||
"mcp",
|
||||
"model context protocol",
|
||||
|
||||
@@ -385,47 +385,44 @@ function SvnExecutableRow() {
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={gitStyles.executable}>
|
||||
<Row
|
||||
label="Path to Subversion executable"
|
||||
htmlFor={id}
|
||||
hint={
|
||||
result ? (
|
||||
<span className={clsx(gitStyles.testResult, result.ok ? styles.ok : styles.error)} role="status">
|
||||
{result.text}
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className={gitStyles.executableControls}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
value={path}
|
||||
placeholder={detected ? tx`Auto-detected: ${detected}` : "Auto-detected"}
|
||||
onChange={(e) => {
|
||||
setPath(e.target.value);
|
||||
setResult(null);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const chosen = await choosePath({ directory: false, defaultPath: path || detected || undefined });
|
||||
if (chosen) {
|
||||
setPath(chosen);
|
||||
setResult(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button disabled={testing || !isTauri()} onClick={() => void test()}>
|
||||
<T>Test</T>
|
||||
</Button>
|
||||
</div>
|
||||
</Row>
|
||||
</div>
|
||||
<Row
|
||||
className={gitStyles.svnPath}
|
||||
label="Path to Subversion executable"
|
||||
htmlFor={id}
|
||||
hint={
|
||||
result ? (
|
||||
<span className={clsx(gitStyles.testResult, result.ok ? styles.ok : styles.error)} role="status">
|
||||
{result.text}
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
value={path}
|
||||
placeholder={detected ? tx`Auto-detected: ${detected}` : "Auto-detected"}
|
||||
onChange={(e) => {
|
||||
setPath(e.target.value);
|
||||
setResult(null);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const chosen = await choosePath({ directory: false, defaultPath: path || detected || undefined });
|
||||
if (chosen) {
|
||||
setPath(chosen);
|
||||
setResult(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button disabled={testing || !isTauri()} onClick={() => void test()}>
|
||||
<T>Test</T>
|
||||
</Button>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -436,30 +433,26 @@ function SvnConfigDirRow() {
|
||||
return (
|
||||
<>
|
||||
<BoundToggle k="vcs.svn.useCustomConfigDir" label="Use custom configuration directory" />
|
||||
<Indented>
|
||||
<Row label="Configuration directory" htmlFor={id}>
|
||||
<div className={gitStyles.executableControls}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
disabled={!custom}
|
||||
value={dir}
|
||||
placeholder="~/.subversion"
|
||||
onChange={(e) => setDir(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
disabled={!custom}
|
||||
onClick={async () => {
|
||||
const chosen = await choosePath({ directory: true, defaultPath: dir || undefined });
|
||||
if (chosen) setDir(chosen);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Row>
|
||||
</Indented>
|
||||
<Row label="Configuration directory" htmlFor={id} className={clsx(gitStyles.svnPath, gitStyles.svnConfig)}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
disabled={!custom}
|
||||
value={dir}
|
||||
placeholder="~/.subversion"
|
||||
onChange={(e) => setDir(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
disabled={!custom}
|
||||
onClick={async () => {
|
||||
const chosen = await choosePath({ directory: true, defaultPath: dir || undefined });
|
||||
if (chosen) setDir(chosen);
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ import { softWrapActive } from "@/editor/core/cm/prefs";
|
||||
import { FindPanel, searchAgain, seedFind, type FindTarget } from "@/editor/core/view/FindBar";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { getContext, setContext } from "@/platform/context";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { reducedMotion } from "@/platform/motion";
|
||||
@@ -109,8 +109,8 @@ import {
|
||||
import { useGitDiffEntries } from "./gitDiffEntries";
|
||||
import { diffAnnotations } from "./diffAnnotations";
|
||||
import { setAllInOneDiff } from "./allInOneDiff";
|
||||
import { annotationsShown, blameSlot, toggleAnnotations } from "./blame";
|
||||
import { diffBlameTarget } from "./diffBlame";
|
||||
import { annotationsShown, blameSlot } from "./blame";
|
||||
import { diffBlamePane, toggleDiffBlame } from "./diffBlame";
|
||||
import { changedChainNeighbour } from "./diffNavigation";
|
||||
import { movedCodeHighlights } from "./movedCode";
|
||||
import {
|
||||
@@ -1732,15 +1732,13 @@ function TwoPaneDiff({
|
||||
]);
|
||||
};
|
||||
/** Annotate with Git Blame for a pane, by that side's own revision. */
|
||||
const blameItems = (pane: DiffViewerPane) => {
|
||||
const target = diffBlameTarget(pane.side === "left" ? left : right, path, !!getContext().vcsAvailable);
|
||||
const blameItems = (viewer: DiffViewerHost, pane: DiffViewerPane) => {
|
||||
const target = diffBlamePane(viewer, pane);
|
||||
if (!target) return [];
|
||||
const view = pane.view;
|
||||
const text = target.revision ? view.state.doc.toString() : undefined;
|
||||
return [
|
||||
{
|
||||
label: annotationsShown(view) ? "Close Annotations" : annotateLabel(target.path),
|
||||
run: () => void toggleAnnotations(view, target.path, text, target.revision),
|
||||
label: annotationsShown(target.view) ? "Close Annotations" : annotateLabel(target.path),
|
||||
run: () => void toggleDiffBlame(target),
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -1782,7 +1780,7 @@ function TwoPaneDiff({
|
||||
const groups = [
|
||||
...(hit ? contribs.map((c) => c.contextMenuItems?.({ side: hit.side, line }) ?? []) : []),
|
||||
inclusion,
|
||||
blameItems(pane),
|
||||
blameItems(viewer, pane),
|
||||
].filter((g) => g.length);
|
||||
if (!groups.length) return;
|
||||
e.preventDefault();
|
||||
|
||||
@@ -233,6 +233,7 @@ function WorktreeForm({
|
||||
level: "warning",
|
||||
title: tx("Some worktree configuration could not be copied"),
|
||||
body: result.copyWarning,
|
||||
userInitiated: true,
|
||||
});
|
||||
}
|
||||
if (result.setupWarning) {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createElement } from "react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import type { Branch, BranchInfo, ProjectInfo, Worktree } from "@/bindings";
|
||||
const mocks = vi.hoisted(() => ({
|
||||
prompt: vi.fn(),
|
||||
@@ -312,6 +315,7 @@ it("shows a partial failure without claiming that the rename failed", async () =
|
||||
expect(mocks.notify).toHaveBeenCalledExactlyOnceWith({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
userInitiated: true,
|
||||
title: "Rename branch topic",
|
||||
body: message,
|
||||
});
|
||||
@@ -411,7 +415,9 @@ it("checks every affected repository before moving any HEAD", async () => {
|
||||
await checkoutRevision({ repos });
|
||||
expect(mocks.hasCommit.mock.calls).toEqual(repos.map((root) => [root, "release"]));
|
||||
expect(mocks.checkout).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ body: "Revision was not found in nested" }));
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userInitiated: true, body: "Revision was not found in nested" }),
|
||||
);
|
||||
|
||||
mocks.hasCommit.mockResolvedValue(ok(true));
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "done" }));
|
||||
@@ -478,32 +484,19 @@ it("does not open the worktree when the checkout offer is declined", async () =>
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the files git would remove when untracked ones block the checkout", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md"], removed: true }));
|
||||
await checkoutBranch(local("feature/x"));
|
||||
it.each([
|
||||
[true, "removed"],
|
||||
[false, "overwritten"],
|
||||
])("shows the files that checkout would affect in an error dialog (%s)", async (removed, verb) => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md", "dir/new.txt"], removed }));
|
||||
render(createElement(MessagesHost));
|
||||
const checkout = checkoutBranch(local("feature/x"));
|
||||
const dialog = await screen.findByRole("dialog", { name: "Untracked files prevent checkout" });
|
||||
expect(dialog).toHaveTextContent(`The following untracked working tree files would be ${verb} by checkout:`);
|
||||
expect(dialog).toHaveTextContent("TEST.md dir/new.txt");
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "OK" }));
|
||||
await checkout;
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be removed by checkout:\nTEST.md",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still says overwritten when untracked files would be overwritten", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["dir/new.txt"], removed: false }));
|
||||
await checkoutBranch(local("feature/x"));
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be overwritten by checkout:\ndir/new.txt",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the branch when the worktree question is turned down", async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { registerEditorActions } from "@/editor/core/actions";
|
||||
@@ -36,6 +36,36 @@ function pane(doc: string, readOnly: boolean, anchor = 0, head = anchor): Editor
|
||||
}
|
||||
|
||||
describe("text actions in a diff", () => {
|
||||
it("copies the focused read-only selection in the requested format", async () => {
|
||||
const view = pane("let a = 1;", true, 4, 9);
|
||||
const clipboard = new Map<string, string>();
|
||||
const copy = vi.fn(() => {
|
||||
const event = new Event("copy", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, "clipboardData", {
|
||||
value: {
|
||||
setData: (type: string, value: string) => clipboard.set(type, value),
|
||||
clearData: () => clipboard.clear(),
|
||||
},
|
||||
});
|
||||
document.activeElement?.dispatchEvent(event);
|
||||
return true;
|
||||
});
|
||||
Object.defineProperty(document, "execCommand", { configurable: true, value: copy });
|
||||
try {
|
||||
await executeAction("code.copyAsRichText");
|
||||
expect(clipboard.get("text/plain")).toBe("a = 1");
|
||||
expect(clipboard.get("text/html")).toContain("<pre");
|
||||
clipboard.clear();
|
||||
await executeAction("code.copyAsPlainText");
|
||||
expect(clipboard.get("text/plain")).toBe("a = 1");
|
||||
expect(clipboard.has("text/html")).toBe(false);
|
||||
expect(copy).toHaveBeenCalledTimes(2);
|
||||
expect(document.activeElement).toBe(view.contentDOM);
|
||||
} finally {
|
||||
Reflect.deleteProperty(document, "execCommand");
|
||||
}
|
||||
});
|
||||
|
||||
it("edit the focused editable side", async () => {
|
||||
const view = pane("let a = 1;\nlet b = 2;", false);
|
||||
expect(await executeAction("code.commentLine")).toBe(true);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ContextMenuHost, iconMarkup } from "@/ui";
|
||||
const probe = vi.fn();
|
||||
const openFile = vi.fn();
|
||||
const openInput = vi.fn();
|
||||
const blame = vi.fn();
|
||||
const texts: Record<string, string> = { HEAD: "a\n", abc123: "a\n" };
|
||||
let working = "a\n";
|
||||
let workingEol = "lf";
|
||||
@@ -22,6 +23,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
...real.commands,
|
||||
fsProbe: (path: string) => probe(path),
|
||||
vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),
|
||||
vcsBlame: (...args: unknown[]) => blame(...args),
|
||||
fsReadText: () => Promise.resolve({ status: "ok", data: working }),
|
||||
},
|
||||
};
|
||||
@@ -58,6 +60,7 @@ import { useVcs } from "../store";
|
||||
import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { registerCompareActions } from "../compare";
|
||||
import { registerVcsActions } from "../actions";
|
||||
|
||||
/** Git Log opens a commit's file: both sides are revisions. */
|
||||
const input = {
|
||||
@@ -83,6 +86,37 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("Diff toolbar", () => {
|
||||
it("annotates the focused revision with the configured shortcut and toggles it off", async () => {
|
||||
const keymap = useKeymap.getState();
|
||||
const unregister = registerVcsActions();
|
||||
const uninstall = installKeyboardDispatcher(window);
|
||||
const vcsAvailable = useVcs.getState().available;
|
||||
applyKeymapSettings("intellij-macos", { "vcs.annotate": ["F8"] });
|
||||
setContext("vcsAvailable", true);
|
||||
blame.mockReset().mockResolvedValue({ status: "ok", data: [] });
|
||||
texts.abc123 = "b\n";
|
||||
const mounted = render(<DiffEditor input={input} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(2));
|
||||
const [left, right] = mounted.container.querySelectorAll<HTMLElement>(".cm-content");
|
||||
right!.focus();
|
||||
fireEvent.keyDown(right!, { key: "F8", code: "F8" });
|
||||
await waitFor(() => expect(blame).toHaveBeenCalledExactlyOnceWith("/p/a.ts", "b\n", "abc123"));
|
||||
await waitFor(() => expect(right!.closest(".cm-editor")?.querySelector(".cm-vcs-blame")).toBeTruthy());
|
||||
expect(left!.closest(".cm-editor")?.querySelector(".cm-vcs-blame")).toBeNull();
|
||||
fireEvent.keyDown(right!, { key: "F8", code: "F8" });
|
||||
await waitFor(() => expect(right!.closest(".cm-editor")?.querySelector(".cm-vcs-blame")).toBeNull());
|
||||
expect(blame).toHaveBeenCalledTimes(1);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
uninstall();
|
||||
unregister();
|
||||
setContext("vcsAvailable", vcsAvailable);
|
||||
useKeymap.setState(keymap);
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the displayed revisions in a separate window through the registered action", async () => {
|
||||
const run = vi.fn();
|
||||
const off = registerAction({ id: "vcs.showDiffInNewWindow", title: "Show Diff in New Window", run });
|
||||
|
||||
@@ -269,6 +269,17 @@ describe("Checkout and Update", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a failed HEAD read before the update", async () => {
|
||||
mocks.checkout.mockResolvedValue({ status: "ok", data: { kind: "done" } });
|
||||
mocks.head.mockResolvedValue({ status: "error", error: { kind: "io", message: "Cannot read HEAD" } });
|
||||
await checkoutAndUpdate(branch("topic"));
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "error", userInitiated: true, body: "Cannot read HEAD" }),
|
||||
);
|
||||
expect(mocks.updateCurrent).not.toHaveBeenCalled();
|
||||
expect(mocks.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates nothing when the checkout did not happen", async () => {
|
||||
mocks.checkout.mockResolvedValue({ status: "error", error: { kind: "failed", message: "nope" } });
|
||||
await checkoutAndUpdate(branch("topic"));
|
||||
|
||||
@@ -61,6 +61,7 @@ import { TOGGLE_IGNORED_FILES } from "./ignoredFiles";
|
||||
import { commitTargetsGit, currentPlan } from "./commitSelection";
|
||||
import { canRevertResolved, gotoConflict, resolveAtCaret, revertResolved, showConflictsDialog } from "./conflictsUi";
|
||||
import { focusedDiffNavigator } from "./diffNavigator";
|
||||
import { diffBlamePane, toggleDiffBlame } from "./diffBlame";
|
||||
import { showDiffWindow } from "./DiffWindow";
|
||||
import {
|
||||
changeNodeDiff,
|
||||
@@ -370,6 +371,11 @@ function showGitWindow() {
|
||||
|
||||
async function annotate(arg: unknown) {
|
||||
const path = argPath(arg);
|
||||
if (!path && getContext().diffEditorFocus) {
|
||||
const pane = focusedBlamePane();
|
||||
if (pane) await toggleDiffBlame(pane);
|
||||
return;
|
||||
}
|
||||
let handle = activeEditor();
|
||||
if (path && handle?.ctx.path !== path) {
|
||||
await editorService().openFile(path, { focus: true });
|
||||
@@ -382,6 +388,11 @@ async function annotate(arg: unknown) {
|
||||
await toggleAnnotations(handle.view, handle.ctx.path);
|
||||
}
|
||||
|
||||
function focusedBlamePane() {
|
||||
const viewer = focusedDiffNavigator()?.viewer?.();
|
||||
return viewer ? diffBlamePane(viewer, viewer.focusedPane()) : null;
|
||||
}
|
||||
|
||||
/** VCS Operations popup: the change and file entries, then Git's own, then Local History. */
|
||||
const OPERATIONS: MenuItem[] = [
|
||||
{ kind: "header", label: "Git" },
|
||||
@@ -1070,12 +1081,17 @@ export function registerVcsActions(): () => void {
|
||||
when: VCS,
|
||||
keywords: ["blame", "annotations"],
|
||||
toggled: () => {
|
||||
if (getContext().diffEditorFocus) {
|
||||
const pane = focusedBlamePane();
|
||||
return !!pane && annotationsShown(pane.view);
|
||||
}
|
||||
const ed = activeEditor();
|
||||
return !!ed && annotationsShown(ed.view);
|
||||
},
|
||||
// As in IDEA, a file Git has no commit of (unversioned, ignored, or added and not yet
|
||||
// committed) has nothing to annotate; shown annotations can always be closed.
|
||||
enabled: ({ arg }) => {
|
||||
enabled: ({ arg, ctx }) => {
|
||||
if (!argPath(arg) && ctx.diffEditorFocus) return !!focusedBlamePane();
|
||||
const ed = activeEditor();
|
||||
const path = argPath(arg) ?? ed?.ctx.path;
|
||||
if (!path || (ed?.ctx.path === path && annotationsShown(ed.view))) return true;
|
||||
|
||||
@@ -19,7 +19,7 @@ import { notifications } from "@/workbench/contributions";
|
||||
import { openWorktree } from "./openWorktree";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { activeRepository } from "./activeRepository";
|
||||
import { ask, confirmChecked } from "@/workbench/messages";
|
||||
import { ask, confirmChecked, showError } from "@/workbench/messages";
|
||||
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
import { showCommitRanges } from "./CompareBranches";
|
||||
import type { AffectedFiles } from "./LocalChangesReviewDialog";
|
||||
@@ -27,6 +27,7 @@ import { confirmDialog, promptText } from "./dialogs";
|
||||
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
|
||||
import {
|
||||
errorMessage,
|
||||
logConsole,
|
||||
runBranchUpdates,
|
||||
runGitOperation,
|
||||
runOp,
|
||||
@@ -206,6 +207,7 @@ async function reviewCheckout<T>(
|
||||
const shelved = workflowSettings().vcs.git.saveChangesPolicy === "shelve";
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
userInitiated: true,
|
||||
level: "warning",
|
||||
title: tx("Could not restore local changes after checkout"),
|
||||
body: outcome.message,
|
||||
@@ -221,6 +223,7 @@ async function reviewCheckout<T>(
|
||||
const shelved = opts.mode === "smart" && workflowSettings().vcs.git.saveChangesPolicy === "shelve";
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
userInitiated: true,
|
||||
level: "warning",
|
||||
title: `${success()}, with conflicts`,
|
||||
body: outcome.files.join("\n"),
|
||||
@@ -241,12 +244,9 @@ async function reviewCheckout<T>(
|
||||
const body = outcome.removed
|
||||
? tx`The following untracked working tree files would be removed by checkout:\n${files}\nPlease move or remove them before you switch branches.`
|
||||
: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`;
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body,
|
||||
});
|
||||
logConsole("err", body);
|
||||
// oxlint-disable-next-line no-await-in-loop -- acknowledge the blocked checkout before a possible multi-root rollback
|
||||
await showError(tx("Untracked files prevent checkout"), body);
|
||||
return undefined;
|
||||
}
|
||||
case "localChanges": {
|
||||
@@ -604,6 +604,7 @@ export async function checkoutRevision(scope?: CheckoutRevisionScope) {
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
userInitiated: true,
|
||||
title: tx`Could not check out ${label}`,
|
||||
body: names ? tx`Revision was not found in ${names}` : tx("Revision was not found"),
|
||||
});
|
||||
@@ -784,7 +785,13 @@ export async function renameBranch(branch: Branch) {
|
||||
success: tx`Renamed branch ${name} to ${to}`,
|
||||
onError: (message) => {
|
||||
// Unsetting the upstream can fail after the rename has succeeded.
|
||||
notifications().notify({ group: "vcs", level: "error", title: tx`Rename branch ${name}`, body: message });
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
userInitiated: true,
|
||||
level: "error",
|
||||
title: tx`Rename branch ${name}`,
|
||||
body: message,
|
||||
});
|
||||
return true;
|
||||
},
|
||||
},
|
||||
@@ -1420,7 +1427,12 @@ export async function checkoutAndUpdate(branch: NamedBranch, roots?: readonly st
|
||||
if (useProject.getState().project !== project) return;
|
||||
const repos: readonly (string | null)[] = roots ?? [currentRepo()];
|
||||
const heads = await Promise.all(
|
||||
repos.map(async (repo) => [repo, await call(commands.vcsBranchInfo(repo)).catch(() => null)] as const),
|
||||
repos.map(async (repo) => {
|
||||
const head = await runOp(tx("Read repository HEAD"), () => call(commands.vcsBranchInfo(repo)), {
|
||||
refresh: false,
|
||||
});
|
||||
return [repo, head] as const;
|
||||
}),
|
||||
);
|
||||
if (useProject.getState().project !== project) return;
|
||||
const targets = heads
|
||||
|
||||
@@ -43,7 +43,7 @@ import { occurrenceSearch } from "@/editor/core/cm/editing";
|
||||
import { findExtension } from "@/editor/core/cm/find";
|
||||
import { overviewLane } from "@/editor/core/cm/lanes";
|
||||
import { LINE_INSET } from "@/editor/core/cm/lineInset";
|
||||
import { caretExtension } from "@/editor/core/cm/prefs";
|
||||
import { caretExtension, richTextCopyExtension } from "@/editor/core/cm/prefs";
|
||||
import { fontExtension, tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { caretStyles, findLocals, findStyles, markWidgetStyles, overviewStyles } from "@/editor/core/cm/theme";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
@@ -671,6 +671,7 @@ export function viewerBase(opts: {
|
||||
// Add Selection for Next Occurrence, Clone Caret: several carets, as in the editor.
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
occurrenceSearch,
|
||||
richTextCopyExtension(false),
|
||||
// Non-editable revision panes still need keyboard selection and copy.
|
||||
opts.readOnly ? EditorView.contentAttributes.of({ tabindex: "0" }) : [],
|
||||
];
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { DiffSide } from "./diffInput";
|
||||
import type { DiffViewerHost, DiffViewerPane } from "./diffViewerProviders";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { toggleAnnotations } from "./blame";
|
||||
|
||||
/** What `git blame` annotates a diff side with. */
|
||||
export interface DiffBlameTarget {
|
||||
@@ -8,6 +12,21 @@ export interface DiffBlameTarget {
|
||||
revision?: string;
|
||||
}
|
||||
|
||||
export interface DiffBlamePane extends DiffBlameTarget {
|
||||
view: EditorView;
|
||||
}
|
||||
|
||||
export function diffBlamePane(host: DiffViewerHost, pane: DiffViewerPane): DiffBlamePane | null {
|
||||
const { path, left, right } = host.data;
|
||||
const target = diffBlameTarget(pane.side === "left" ? left : right, path, !!getContext().vcsAvailable);
|
||||
if (!target) return null;
|
||||
return { ...target, view: pane.view };
|
||||
}
|
||||
|
||||
export function toggleDiffBlame({ view, path, revision }: DiffBlamePane) {
|
||||
return toggleAnnotations(view, path, revision ? view.state.doc.toString() : undefined, revision);
|
||||
}
|
||||
|
||||
/**
|
||||
* The blame for one side of a diff: a revision blames its own history, the working file the
|
||||
* file on disk; Compare Files, Local History and plain texts are not Git content.
|
||||
|
||||
@@ -139,8 +139,7 @@ export async function saveAll() {
|
||||
try {
|
||||
await saveDiffWindows();
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
notify({
|
||||
level: "error",
|
||||
title: tx("Could not save diff"),
|
||||
body: errorMessage(error),
|
||||
|
||||
@@ -44,6 +44,7 @@ import { registerRstLiveSource } from "./rst/live";
|
||||
import { rstModes, RstLayoutActions } from "./rst/RstLayoutActions";
|
||||
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
|
||||
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
|
||||
import { markdownPreviewFontActions } from "./markdown/previewFontActions";
|
||||
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
|
||||
|
||||
const titleOf = (input: EditorInput) => basename(input.path ?? input.key);
|
||||
@@ -197,7 +198,7 @@ export function activate(): () => void {
|
||||
items: (_menu, { paths: [path] }) =>
|
||||
path === activeEditor()?.ctx.path && canExtractImages() ? [{ kind: "action", action: EXTRACT_IMAGES }] : [],
|
||||
}),
|
||||
registerActions([...imageActions(), ...markdownActions()]),
|
||||
registerActions([...imageActions(), ...markdownActions(), ...markdownPreviewFontActions()]),
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -94,6 +94,7 @@ import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { create } from "zustand";
|
||||
import { isMarkdownPath, isMdxPath } from "../fileKinds";
|
||||
@@ -1360,6 +1361,8 @@ function MarkdownPreview({
|
||||
root.removeEventListener("wheel", onWheel, { capture: true });
|
||||
root.removeEventListener("wheel", onPreviewWheel);
|
||||
release();
|
||||
const focused = document.activeElement;
|
||||
if (!focused || focused === document.body || root.contains(focused)) setContext("markdownPreviewFocus", false);
|
||||
};
|
||||
}, [path]);
|
||||
|
||||
@@ -1442,6 +1445,10 @@ function MarkdownPreview({
|
||||
tabIndex={-1}
|
||||
role="document"
|
||||
aria-label={tx("Markdown preview")}
|
||||
onFocus={() => setContext("markdownPreviewFocus", true)}
|
||||
onBlur={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("markdownPreviewFocus", false);
|
||||
}}
|
||||
onClick={onClick}
|
||||
onScroll={onScroll}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { stepFocusedSurfaceFontZoom } from "@/workbench/contributions";
|
||||
|
||||
/**
|
||||
* Increase / Decrease Preview Font Size: the focused Markdown preview takes the zoom keys
|
||||
* (⌘/Ctrl+= and ⌘/Ctrl+-) that expand and collapse folds in the editor, as in IntelliJ IDEA.
|
||||
*/
|
||||
export function markdownPreviewFontActions(): Action[] {
|
||||
const action = (id: string, title: string, delta: number): Action => ({
|
||||
id,
|
||||
title,
|
||||
category: "Markdown",
|
||||
keywords: ["zoom", "font size"],
|
||||
when: "markdownPreviewFocus",
|
||||
keyWhen: "markdownPreviewFocus",
|
||||
run: () => void stepFocusedSurfaceFontZoom(delta),
|
||||
});
|
||||
return [
|
||||
action("markdown.preview.increaseFontSize", "Increase Preview Font Size", 1),
|
||||
action("markdown.preview.decreaseFontSize", "Decrease Preview Font Size", -1),
|
||||
];
|
||||
}
|
||||
@@ -13,7 +13,8 @@ import {
|
||||
import { fontZoom, resetAllEditorsFontZoom, setFontZoom } from "@/editor/core/cm/prefs";
|
||||
import { fontExtension } from "@/editor/core/cm/setup";
|
||||
import type { EditorSlot } from "@/editor/core/model/slot";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { applyKeymapSettings, installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { useContextKeys } from "@/platform/context";
|
||||
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
|
||||
import { intellijWindows } from "@/platform/keymaps/intellij-windows";
|
||||
@@ -37,6 +38,7 @@ const { registerEditorActions } = await import("@/editor/core/actions");
|
||||
const { registerMarkdownLiveSource, useLiveMarkdown } = await import("./live");
|
||||
const { MarkdownEditor } = await import("./MarkdownEditor");
|
||||
const { useMarkdownModes } = await import("./modes");
|
||||
const { markdownPreviewFontActions } = await import("./previewFontActions");
|
||||
|
||||
const mdCtx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false };
|
||||
const tsCtx: EditorDocContext = { doc: 2, path: "/p/a.ts", language: "typescript", uiMode: null, readOnly: false };
|
||||
@@ -244,6 +246,51 @@ describe("editor font size actions", () => {
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
|
||||
});
|
||||
|
||||
it("takes ⌘/Ctrl+= and ⌘/Ctrl+- in the focused preview, leaving them to fold in the editor (#7380)", async () => {
|
||||
const md = open(mdCtx);
|
||||
activate(md);
|
||||
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "split" } })));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
disposers.push(registerActions(markdownPreviewFontActions()));
|
||||
const unfold = vi.fn();
|
||||
const fold = vi.fn();
|
||||
disposers.push(
|
||||
registerActions([
|
||||
{ id: "code.unfold", title: "Expand", keyWhen: "editorFocus", run: unfold },
|
||||
{ id: "code.fold", title: "Collapse", keyWhen: "editorFocus", run: fold },
|
||||
]),
|
||||
);
|
||||
disposers.push(installKeyboardDispatcher(window));
|
||||
const press = async (preset: string, key: string, mod: "metaKey" | "ctrlKey") => {
|
||||
applyKeymapSettings(preset, {});
|
||||
document.activeElement!.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key, code: key === "=" ? "Equal" : "Minus", [mod]: true, bubbles: true }),
|
||||
);
|
||||
await act(() => Promise.resolve());
|
||||
};
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
|
||||
act(() => preview.focus());
|
||||
await press("intellij-macos", "=", "metaKey");
|
||||
await press("intellij-windows", "=", "ctrlKey");
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("2px");
|
||||
await press("intellij-macos", "-", "metaKey");
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("1px");
|
||||
expect(unfold).not.toHaveBeenCalled();
|
||||
expect(fold).not.toHaveBeenCalled();
|
||||
|
||||
act(() => preview.blur());
|
||||
expect(useContextKeys.getState().markdownPreviewFocus).toBe(false);
|
||||
act(() => md.contentDOM.focus());
|
||||
await press("intellij-windows", "=", "ctrlKey");
|
||||
expect(unfold).toHaveBeenCalledOnce();
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("1px");
|
||||
});
|
||||
|
||||
it("sizes embedded excalidraw.svg, graph SVGs and raster images so they scale with font zoom", async () => {
|
||||
const box = (img: HTMLImageElement) => img.closest<HTMLElement>(".image-zoom")!;
|
||||
const excalidrawSvg =
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { EDITOR_EXTRA_DEFAULTS, validateEditorExtras } from "./editorSettings";
|
||||
|
||||
it("reads whole-number code insight limits from 1 to 50 MiB and defaults to 5", () => {
|
||||
expect(validateEditorExtras(undefined).maxCodeInsightFileSizeMb).toBe(5);
|
||||
for (const value of [1, 10, 50]) {
|
||||
expect(validateEditorExtras({ maxCodeInsightFileSizeMb: value }).maxCodeInsightFileSizeMb).toBe(value);
|
||||
}
|
||||
for (const value of [0, 51, 3.5, "10"]) {
|
||||
expect(validateEditorExtras({ maxCodeInsightFileSizeMb: value }).maxCodeInsightFileSizeMb).toBe(5);
|
||||
}
|
||||
});
|
||||
|
||||
it("has no encoding mappings unless the settings name some", () => {
|
||||
expect(EDITOR_EXTRA_DEFAULTS.encodings.mappings).toEqual({});
|
||||
expect(validateEditorExtras(undefined).encodings.mappings).toEqual({});
|
||||
|
||||
@@ -113,7 +113,10 @@ export function lineCommentStyleFor(
|
||||
};
|
||||
}
|
||||
|
||||
export const MAX_CODE_INSIGHT_FILE_SIZE_MB = 50;
|
||||
|
||||
export const EDITOR_EXTRA_DEFAULTS = {
|
||||
maxCodeInsightFileSizeMb: 5,
|
||||
customSchemes: {} as CustomColorSchemes,
|
||||
colorOverrides: {} as Record<string, Record<string, TextAttributesOverride>>,
|
||||
/** Color Scheme › Language Defaults › Semantic highlighting (rainbow locals / parameters). */
|
||||
@@ -353,6 +356,10 @@ export function fontWeightVars(main: unknown, bold: unknown): Record<"--fw-code"
|
||||
|
||||
export function validateEditorExtras(raw: unknown): EditorExtras {
|
||||
const out = coerceLike(raw, EDITOR_EXTRA_DEFAULTS);
|
||||
const limit = out.maxCodeInsightFileSizeMb;
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CODE_INSIGHT_FILE_SIZE_MB) {
|
||||
out.maxCodeInsightFileSizeMb = EDITOR_EXTRA_DEFAULTS.maxCodeInsightFileSizeMb;
|
||||
}
|
||||
if (!["active", "all"].includes(out.general.wheelZoomScope)) out.general.wheelZoomScope = "active";
|
||||
if (!["ask", "always", "never"].includes(out.autoImport.importsOnPaste)) out.autoImport.importsOnPaste = "ask";
|
||||
if (!["above", "caret", "trim"].includes(out.smartKeys.linePasteMode)) out.smartKeys.linePasteMode = "above";
|
||||
|
||||
@@ -136,6 +136,18 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
|
||||
ToggleZenMode: "view.toggleZenMode",
|
||||
EditorIncreaseFontSizeGlobal: "editor.increaseFontSizeAll",
|
||||
EditorDecreaseFontSizeGlobal: "editor.decreaseFontSizeAll",
|
||||
EditorUp: "editor.up",
|
||||
EditorDown: "editor.down",
|
||||
EditorLeft: "editor.left",
|
||||
EditorRight: "editor.right",
|
||||
EditorLineStart: "editor.lineStart",
|
||||
EditorLineEnd: "editor.lineEnd",
|
||||
EditorUpWithSelection: "editor.upWithSelection",
|
||||
EditorDownWithSelection: "editor.downWithSelection",
|
||||
EditorLeftWithSelection: "editor.leftWithSelection",
|
||||
EditorRightWithSelection: "editor.rightWithSelection",
|
||||
EditorLineStartWithSelection: "editor.lineStartWithSelection",
|
||||
EditorLineEndWithSelection: "editor.lineEndWithSelection",
|
||||
EditorDeleteLine: "code.deleteLine",
|
||||
EditorScrollUp: "editor.scrollUp",
|
||||
EditorScrollDown: "editor.scrollDown",
|
||||
|
||||
@@ -265,10 +265,14 @@ function cachedBindings() {
|
||||
bindingsCache.extensions === extensions
|
||||
)
|
||||
return bindingsCache;
|
||||
const merged: Keymap = { ...usableExtensionBindings(extensions), ...platformPreset(preset), ...overrides };
|
||||
const pairs = Object.entries(merged).flatMap(([id, keys]) =>
|
||||
keys.map((k) => [normalizeBinding(k), id] as [string, string]),
|
||||
);
|
||||
const base: Keymap = { ...usableExtensionBindings(extensions), ...platformPreset(preset) };
|
||||
// Keep overridden actions after preset/extension entries even when the action id already exists in the preset,
|
||||
// so user overrides win over preset bindings on the same keystroke.
|
||||
const entries: Array<[string, string[]]> = [
|
||||
...Object.entries(base).filter(([id]) => !Object.hasOwn(overrides, id)),
|
||||
...Object.entries(overrides),
|
||||
];
|
||||
const pairs = entries.flatMap(([id, keys]) => keys.map((k) => [normalizeBinding(k), id] as [string, string]));
|
||||
const hasWheel = pairs.some(([binding, id]) => isWheelBinding(binding) && supportsWheelShortcut(id));
|
||||
bindingsCache = { preset, overrides, extensions, os, pairs, hasWheel };
|
||||
return bindingsCache;
|
||||
@@ -893,18 +897,23 @@ export function installKeyboardDispatcher(
|
||||
// in the project view instead of reaching the Git log's Edit Commit
|
||||
// Message. An unmatching `keyWhen` fails the enablement check below, and
|
||||
// when no `keyWhen` matches, the preset/override order decides as before.
|
||||
const { overrides } = useKeymap.getState();
|
||||
const isOverridden = (id: string) => Object.hasOwn(overrides, id);
|
||||
const keyWhenMatches = (id: string) => {
|
||||
const action = getAction(id);
|
||||
return !!action?.keyWhen && evaluateWhen(action.keyWhen, ctx);
|
||||
};
|
||||
const ordered = exact.reverse();
|
||||
const preferred: string[] = [];
|
||||
const fallback: string[] = [];
|
||||
const overridePreferred: string[] = [];
|
||||
const overrideFallback: string[] = [];
|
||||
const presetPreferred: string[] = [];
|
||||
const presetFallback: string[] = [];
|
||||
for (const id of ordered) {
|
||||
if (keyWhenMatches(id)) preferred.push(id);
|
||||
else fallback.push(id);
|
||||
const specific = keyWhenMatches(id);
|
||||
if (isOverridden(id)) (specific ? overridePreferred : overrideFallback).push(id);
|
||||
else (specific ? presetPreferred : presetFallback).push(id);
|
||||
}
|
||||
for (const id of [...preferred, ...fallback]) {
|
||||
for (const id of [...overridePreferred, ...overrideFallback, ...presetPreferred, ...presetFallback]) {
|
||||
const action = getAction(id);
|
||||
if (action && actionEnabledForKey(action, e) && (!restricted || isForwardableAction(id, e.target))) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -174,5 +174,8 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"toolwindow.resizeUp": [],
|
||||
"toolwindow.resizeDown": [],
|
||||
"editor.decreaseFontSize": ["Meta+-"],
|
||||
// Increase / Decrease Font Size already take these keys, and zoom the focused Markdown preview.
|
||||
"markdown.preview.increaseFontSize": [],
|
||||
"markdown.preview.decreaseFontSize": [],
|
||||
"editor.increaseFontSize": ["Meta+="],
|
||||
};
|
||||
@@ -178,5 +178,8 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"toolwindow.resizeUp": [],
|
||||
"toolwindow.resizeDown": [],
|
||||
"editor.decreaseFontSize": ["Ctrl+-"],
|
||||
// Increase / Decrease Font Size already take these keys, and zoom the focused Markdown preview.
|
||||
"markdown.preview.increaseFontSize": [],
|
||||
"markdown.preview.decreaseFontSize": [],
|
||||
"editor.increaseFontSize": ["Ctrl+="],
|
||||
};
|
||||
@@ -136,6 +136,19 @@ describe("IDEA keymap parity", () => {
|
||||
// Back / Forward also carry the mouse side buttons (`<mouse-shortcut keystroke="button4"/>`).
|
||||
["editor.codeBlockStartWithSelection", ["Meta+Alt+Shift+["], ["Ctrl+Shift+["]],
|
||||
["editor.codeBlockEndWithSelection", ["Meta+Alt+Shift+]"], ["Ctrl+Shift+]"]],
|
||||
// Plain caret moves and their With Selection variants stay unbound so CodeMirror handles arrows and Home/End by default.
|
||||
["editor.up", [], []],
|
||||
["editor.down", [], []],
|
||||
["editor.left", [], []],
|
||||
["editor.right", [], []],
|
||||
["editor.lineStart", [], []],
|
||||
["editor.lineEnd", [], []],
|
||||
["editor.upWithSelection", [], []],
|
||||
["editor.downWithSelection", [], []],
|
||||
["editor.leftWithSelection", [], []],
|
||||
["editor.rightWithSelection", [], []],
|
||||
["editor.lineStartWithSelection", [], []],
|
||||
["editor.lineEndWithSelection", [], []],
|
||||
// EditorForwardParagraph / EditorBackwardParagraph (and with Selection) have no shortcut.
|
||||
["editor.paragraphForward", [], []],
|
||||
["editor.paragraphBackward", [], []],
|
||||
|
||||
@@ -141,6 +141,18 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"code.startNewLineBefore": ["Meta+Alt+Enter"],
|
||||
// Before the HTTP / SQL consoles' ⌘↵ (Run), which wins there.
|
||||
"code.splitLine": ["Meta+Enter"],
|
||||
"editor.up": [],
|
||||
"editor.down": [],
|
||||
"editor.left": [],
|
||||
"editor.right": [],
|
||||
"editor.lineStart": [],
|
||||
"editor.lineEnd": [],
|
||||
"editor.upWithSelection": [],
|
||||
"editor.downWithSelection": [],
|
||||
"editor.leftWithSelection": [],
|
||||
"editor.rightWithSelection": [],
|
||||
"editor.lineStartWithSelection": [],
|
||||
"editor.lineEndWithSelection": [],
|
||||
"editor.scrollToCenter": ["Ctrl+L"],
|
||||
"tree.scrollToCenter": [],
|
||||
"editor.scrollUp": [],
|
||||
@@ -455,6 +467,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"code.expressionTypeInfo": ["Ctrl+Shift+P"],
|
||||
"code.implementMethods": ["Ctrl+I"],
|
||||
"code.overrideMethods": ["Ctrl+O"],
|
||||
"markdown.preview.increaseFontSize": ["Meta+="],
|
||||
"markdown.preview.decreaseFontSize": ["Meta+-"],
|
||||
"image.zoomIn": ["Meta+="],
|
||||
"image.zoomOut": ["Meta+-"],
|
||||
"image.actualSize": ["Meta+/"],
|
||||
|
||||
@@ -142,6 +142,18 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"code.startNewLineBefore": ["Ctrl+Alt+Enter"],
|
||||
// Before the HTTP / SQL consoles' Ctrl+Enter (Run), which wins there.
|
||||
"code.splitLine": ["Ctrl+Enter"],
|
||||
"editor.up": [],
|
||||
"editor.down": [],
|
||||
"editor.left": [],
|
||||
"editor.right": [],
|
||||
"editor.lineStart": [],
|
||||
"editor.lineEnd": [],
|
||||
"editor.upWithSelection": [],
|
||||
"editor.downWithSelection": [],
|
||||
"editor.leftWithSelection": [],
|
||||
"editor.rightWithSelection": [],
|
||||
"editor.lineStartWithSelection": [],
|
||||
"editor.lineEndWithSelection": [],
|
||||
"editor.scrollToCenter": ["Ctrl+M"],
|
||||
"tree.scrollToCenter": [],
|
||||
"editor.scrollUp": ["Ctrl+Up"],
|
||||
@@ -453,6 +465,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"code.expressionTypeInfo": ["Ctrl+Shift+P"],
|
||||
"code.implementMethods": ["Ctrl+I"],
|
||||
"code.overrideMethods": ["Ctrl+O"],
|
||||
"markdown.preview.increaseFontSize": ["Ctrl+="],
|
||||
"markdown.preview.decreaseFontSize": ["Ctrl+-"],
|
||||
"image.zoomIn": ["Ctrl+="],
|
||||
"image.zoomOut": ["Ctrl+-"],
|
||||
"image.actualSize": ["Ctrl+/"],
|
||||
|
||||
@@ -274,6 +274,18 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"editor.copyPath": ["Meta+K P"],
|
||||
"navigate.searchText": [],
|
||||
"code.splitLine": [],
|
||||
"editor.up": [],
|
||||
"editor.down": [],
|
||||
"editor.left": [],
|
||||
"editor.right": [],
|
||||
"editor.lineStart": [],
|
||||
"editor.lineEnd": [],
|
||||
"editor.upWithSelection": [],
|
||||
"editor.downWithSelection": [],
|
||||
"editor.leftWithSelection": [],
|
||||
"editor.rightWithSelection": [],
|
||||
"editor.lineStartWithSelection": [],
|
||||
"editor.lineEndWithSelection": [],
|
||||
"editor.scrollToCenter": [],
|
||||
"tree.scrollToCenter": [],
|
||||
"editor.scrollUp": [],
|
||||
@@ -458,6 +470,8 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"code.expressionTypeInfo": [],
|
||||
"code.implementMethods": [],
|
||||
"code.overrideMethods": [],
|
||||
"markdown.preview.increaseFontSize": [],
|
||||
"markdown.preview.decreaseFontSize": [],
|
||||
"image.zoomIn": [],
|
||||
"image.zoomOut": [],
|
||||
"image.actualSize": [],
|
||||
|
||||
@@ -57,6 +57,8 @@ export const vscodeWindows: Record<string, string[]> = {
|
||||
"code.expressionTypeInfo": [],
|
||||
"code.implementMethods": [],
|
||||
"code.overrideMethods": [],
|
||||
"markdown.preview.increaseFontSize": [],
|
||||
"markdown.preview.decreaseFontSize": [],
|
||||
"image.zoomIn": [],
|
||||
"image.zoomOut": [],
|
||||
"image.actualSize": [],
|
||||
|
||||
@@ -262,6 +262,8 @@ export interface LanguagesValid {
|
||||
activeProfiles: string;
|
||||
/** Delegate IDE build/run actions to Maven (`javac`) instead of jdtls (ECJ). */
|
||||
delegateBuild: boolean;
|
||||
/** Exact Maven goals the IDE may skip in compile phases. */
|
||||
ignoredCompileGoals: string[];
|
||||
/** Download dependencies' `-sources.jar` when jdtls imports the project. */
|
||||
downloadSources: boolean;
|
||||
/** Always update snapshots: `-U` on Maven runs, `java.maven.updateSnapshots` for jdtls. */
|
||||
@@ -381,6 +383,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
|
||||
threads: "",
|
||||
activeProfiles: "",
|
||||
delegateBuild: false,
|
||||
ignoredCompileGoals: [],
|
||||
downloadSources: false,
|
||||
updateSnapshots: false,
|
||||
runTestsUsing: "ide",
|
||||
@@ -612,6 +615,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
|
||||
threads: text(maven.threads, d.java.maven.threads),
|
||||
activeProfiles: text(maven.activeProfiles, d.java.maven.activeProfiles),
|
||||
delegateBuild: bool(maven.delegateBuild, d.java.maven.delegateBuild),
|
||||
ignoredCompileGoals: strings(maven.ignoredCompileGoals),
|
||||
downloadSources: bool(maven.downloadSources, d.java.maven.downloadSources),
|
||||
updateSnapshots: bool(maven.updateSnapshots, d.java.maven.updateSnapshots),
|
||||
runTestsUsing: oneOf(maven.runTestsUsing, ["ide", "maven"] as const, d.java.maven.runTestsUsing),
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{
|
||||
"Large Files": "Large Files",
|
||||
"Maximum file size for code insight": "Maximum file size for code insight",
|
||||
"Reopen files to apply the new limit.": "Reopen files to apply the new limit.",
|
||||
"Code insight is disabled for this file because of its size.": "Code insight is disabled for this file because of its size.",
|
||||
"Duplicate Template": "Duplicate Template",
|
||||
"No SQL client": "No SQL client",
|
||||
"The saved DuckDB driver is unavailable.": "The saved DuckDB driver is unavailable.",
|
||||
@@ -5154,5 +5158,7 @@
|
||||
"Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.": "Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.",
|
||||
"Code insight for {container} reads its last build. Without one yet, it is built in the background.": "Code insight for {container} reads its last build. Without one yet, it is built in the background.",
|
||||
"Background build for code insight failed": "Background build for code insight failed",
|
||||
"Code insight reads what it built. Run shows the whole build log.": "Code insight reads what it built. Run shows the whole build log."
|
||||
"Code insight reads what it built. Run shows the whole build log.": "Code insight reads what it built. Run shows the whole build log.",
|
||||
"Increase Preview Font Size": "Increase Preview Font Size",
|
||||
"Decrease Preview Font Size": "Decrease Preview Font Size"
|
||||
}
|
||||
@@ -720,6 +720,18 @@
|
||||
"Move Down and Scroll with Selection": "向下移動並捲動並選擇",
|
||||
"Scroll to Top": "捲動到頂部",
|
||||
"Scroll to Bottom": "捲動到底部",
|
||||
"Move Caret Up": "將游標向上移動",
|
||||
"Move Caret Down": "將游標向下移動",
|
||||
"Move Caret Left": "將游標向左移動",
|
||||
"Move Caret Right": "將游標向右移動",
|
||||
"Move Caret to Line Start": "將游標移至行首",
|
||||
"Move Caret to Line End": "將游標移至行尾",
|
||||
"Move Caret Up with Selection": "將游標向上移動並選擇",
|
||||
"Move Caret Down with Selection": "將游標向下移動並選擇",
|
||||
"Move Caret Left with Selection": "將游標向左移動並選擇",
|
||||
"Move Caret Right with Selection": "將游標向右移動並選擇",
|
||||
"Move Caret to Line Start with Selection": "將游標移至行首並選擇",
|
||||
"Move Caret to Line End with Selection": "將游標移至行尾並選擇",
|
||||
"Move Caret to Page Top": "將游標移至頁面頂部",
|
||||
"Move Caret to Page Bottom": "將游標移至頁面底部",
|
||||
"Move Caret to Page Top with Selection": "將游標移至頁面頂部並選擇",
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
{
|
||||
"Not verified": "未验证",
|
||||
"No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one": "此行的代码尚未加载。如果模块加载后仍未绑定,调试信息可能以另一条路径记录了此文件(经过符号链接,或以 /tmp 代替 /private/tmp):请设置从该路径到此路径的源映射",
|
||||
"Large Files": "大文件",
|
||||
"Maximum file size for code insight": "启用代码分析的最大文件大小",
|
||||
"Reopen files to apply the new limit.": "重新打开文件后,新的大小限制生效。",
|
||||
"Code insight is disabled for this file because of its size.": "此文件超过大小限制,已停用代码分析。",
|
||||
"{name} ({runtime} Simulator)": "{name}({runtime} 模拟器)",
|
||||
"App.xcodeproj": "App.xcodeproj",
|
||||
"Xcode App": "Xcode 应用",
|
||||
@@ -1172,6 +1176,18 @@
|
||||
"Move Down and Scroll with Selection": "向下移动并滚动并选择",
|
||||
"Scroll to Top": "滚动到顶部",
|
||||
"Scroll to Bottom": "滚动到底部",
|
||||
"Move Caret Up": "将光标向上移动",
|
||||
"Move Caret Down": "将光标向下移动",
|
||||
"Move Caret Left": "将光标向左移动",
|
||||
"Move Caret Right": "将光标向右移动",
|
||||
"Move Caret to Line Start": "将光标移至行首",
|
||||
"Move Caret to Line End": "将光标移至行尾",
|
||||
"Move Caret Up with Selection": "将光标向上移动并选择",
|
||||
"Move Caret Down with Selection": "将光标向下移动并选择",
|
||||
"Move Caret Left with Selection": "将光标向左移动并选择",
|
||||
"Move Caret Right with Selection": "将光标向右移动并选择",
|
||||
"Move Caret to Line Start with Selection": "将光标移至行首并选择",
|
||||
"Move Caret to Line End with Selection": "将光标移至行尾并选择",
|
||||
"Move Caret to Page Top": "将光标移至页面顶部",
|
||||
"Move Caret to Page Bottom": "将光标移至页面底部",
|
||||
"Move Caret to Page Top with Selection": "将光标移至页面顶部并选择",
|
||||
@@ -12034,5 +12050,7 @@
|
||||
"Language server updates are available": "语言服务器有可用更新",
|
||||
"Vue Language Server version": "Vue 语言服务器版本",
|
||||
"Auto uses 3.0.x for Vue 2 projects and the latest release for Vue 3.": "自动选择时,Vue 2 项目使用 3.0.x,Vue 3 项目使用最新版本。",
|
||||
"Enter latest, 3.0.x, or an exact Vue Language Server version.": "请输入 latest、3.0.x 或 Vue 语言服务器的具体版本。"
|
||||
"Enter latest, 3.0.x, or an exact Vue Language Server version.": "请输入 latest、3.0.x 或 Vue 语言服务器的具体版本。",
|
||||
"Increase Preview Font Size": "增大预览字体",
|
||||
"Decrease Preview Font Size": "减小预览字体"
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Shared folder-role, module-glyph, and package-icon resolution for Project and Commit trees. */
|
||||
import { effectiveRoots, rootFor, rootRole, type FolderRole, type RootFolder } from "@/platform/languageSettings";
|
||||
import { basename, relativePath } from "@/platform/project";
|
||||
import { moduleFolderIcon, type BuildPresentation } from "@/platform/projectPresentation";
|
||||
import { moduleFolderIcon, useBuildPresentation, type BuildPresentation } from "@/platform/projectPresentation";
|
||||
import type { AttachedProject } from "@/platform/projectRoots";
|
||||
import { folderIconName, themedFolderIconName, type FolderKind, type IconName } from "./icons";
|
||||
|
||||
@@ -53,16 +53,35 @@ export function projectScopeForPath(
|
||||
};
|
||||
}
|
||||
|
||||
/** Inside a Java / Kotlin source or test root, where IDEA shows "Package" instead of "Directory". */
|
||||
export function isJvmSourcePackage(rel: string, roots: readonly RootFolder[]): boolean {
|
||||
const root = rootFor(roots, rel);
|
||||
if (root?.kind === "excluded") return false;
|
||||
return (
|
||||
(root?.kind === "source" || root?.kind === "test") &&
|
||||
(JVM_BUILD.test(root.detectedFrom ?? "") || JVM_DIR.test(root.path))
|
||||
/** `path` (absolute) or `rel` (project-relative) lies in one of the Maven / Gradle modules. */
|
||||
function inBuildModule(
|
||||
path: string | null,
|
||||
rel: string,
|
||||
modules: BuildPresentation["modules"],
|
||||
attachedMember = false,
|
||||
): boolean {
|
||||
return [...modules.keys()].some((dir) =>
|
||||
isAbsolute(dir)
|
||||
? path !== null && (path === dir || path.startsWith(`${dir}/`))
|
||||
: !attachedMember && (!dir || rel === dir || rel.startsWith(`${dir}/`)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inside a Java / Kotlin source or test root, where IDEA shows "Package" instead of "Directory".
|
||||
* A folder marked as a root by hand holds packages too when it is in a Maven / Gradle module.
|
||||
*/
|
||||
export function isJvmSourcePackage(
|
||||
rel: string,
|
||||
roots: readonly RootFolder[],
|
||||
modules: BuildPresentation["modules"] = useBuildPresentation.getState().modules,
|
||||
): boolean {
|
||||
const root = rootFor(roots, rel);
|
||||
if (root?.kind !== "source" && root?.kind !== "test") return false;
|
||||
if (JVM_BUILD.test(root.detectedFrom ?? "") || JVM_DIR.test(root.path)) return true;
|
||||
return root.detectedFrom === null && inBuildModule(null, rel, modules);
|
||||
}
|
||||
|
||||
/** Output roles are relative to detected JVM modules, never arbitrary package names. */
|
||||
export function outputFolderKind(
|
||||
rel: string,
|
||||
@@ -115,12 +134,8 @@ export function directoryFolderKind(
|
||||
if (role) return ROLE_KIND[role];
|
||||
if (output) return output;
|
||||
if (rel !== null && (containing?.kind === "source" || containing?.kind === "test")) {
|
||||
const inModule = [...(build?.modules.keys() ?? [])].some((dir) =>
|
||||
isAbsolute(dir)
|
||||
? path === dir || path.startsWith(`${dir}/`)
|
||||
: !attachedMember && (!dir || rel.startsWith(`${dir}/`)),
|
||||
);
|
||||
if (inModule || isJvmSourcePackage(rel, roots)) return "package";
|
||||
const modules = build?.modules ?? new Map();
|
||||
if (inBuildModule(path, rel, modules, attachedMember) || isJvmSourcePackage(rel, roots, modules)) return "package";
|
||||
}
|
||||
return basename(path) === ".github" ? "github" : "plain";
|
||||
}
|
||||
|
||||
Reference in new issue
Заблокувати користувача