Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7eed99745a test(plugins): keep the editor panel's problem levels out of the text catalog
The severity map's `hint: "weakWarning"` entry read as UI text to the
text-catalog check (`hint` is a text property), failing it on main since #3885.
A function maps the levels instead.
2026-11-17 12:33:43 +08:00
LU XIANGRUIтаwildcatDownstairs ebc879dc8b feat(plugins): folded ranges and wrapped rows for editor panels (#3890)
An editor panel's page could not tell which lines are folded or how many rows a soft-wrapped line takes, so a minimap drew folded code and drifted from the editor. openidea.editor now has folded() ([{ fromLine, toLine }], nested folds merged), wrapped(fromLine, toLine) (visual rows per line, 0 for folded-away lines, null without soft wrap, at most 2000 lines) and onLayout(fn) with { folded, softWrap }, at most once a frame. Folds come from foldedRanges and rows from the editor's own line blocks.

Closes #3867

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:32:03 +08:00
LU XIANGRUIтаwildcatDownstairs 7096a1c374 feat(plugins): include semantic highlighting in editor panels' highlights() (#3887)
openidea.editor.highlights() returned only the Lezer syntax colours, so a minimap drew semantic tokens (cm-sem-* marks, rainbow identifiers) in the wrong colour. It now layers the editor's semantic marks over the syntax spans the way the editor does, and onHighlights reports the lines whose semantic marks changed (RangeSet.compare on the semantic field, so mapped marks report nothing extra). The page API is unchanged.

Closes #3866

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:42 +08:00
LU XIANGRUIтаwildcatDownstairs a1d4d6fb7f feat(plugins): the marker bar's problems in editor panels (#3885)
An editor panel's page can now read the problems the marker bar shows: openidea.editor.problems() returns [{ line, lastLine, severity }] (0-based lines; error, warning or weakWarning) and onProblems(fn) reports changes at most once a frame. The data is the marker bar's own diagnostics marks field, exported as markerBarProblems(state), so positions follow edits the same way. Covered by editor.read; the minimap fixture draws them.

Closes #3865

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:20 +08:00
Muuтаmuutot 7596e95b76 fix(spell): raw strings keep the letter after a backslash (#3886)
Typo checking treated every backslash in a string literal as an escape and skipped the letter after it, so r"\user" was checked as "ser" and flagged. The syntax layer now marks raw / verbatim strings (Python r/R prefixes with b/f/u combinations, Rust and C++ raw strings, C# verbatim strings, Go backtick strings), and the spelling layer checks them without escape handling.

Co-authored-by: muutot <[email protected]>
2026-11-17 12:30:01 +08:00
Gabriel Gondim cc471029d2 fix(xml): map Doctrine ORM XSD through a LemMinX catalog (#3881)
Doctrine ORM XML mappings that follow Doctrine's docs and point xsi:schemaLocation at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd failed validation (TargetNamespace.1, cvc-elt.1.a): the hosted XSD declares the schema URL as its targetNamespace after an http→https rewrite. The upstream schema (MIT) is bundled and an OASIS catalog, written to a private per-process directory, is prepended to LemMinX's xml.catalogs so the namespace and both system IDs resolve to it.

Closes #3843

Co-authored-by: GGVidal <[email protected]>
2026-11-17 12:28:31 +08:00
LU XIANGRUIтаwildcatDownstairs ee8afe39a2 fix(build): make the injected WAR and resource init scripts work with the configuration cache (#3877)
With org.gradle.configuration-cache=true, Tomcat WAR deployment and Spring Boot resource update failed: the doLast actions of war.init.gradle and resources.init.gradle referred to the Project and other tasks, which the configuration cache cannot serialize. The values they need (the war archive provider or file, processResources' destination, the manifest file) are now resolved at configuration time. The other injected scripts only configure tasks and have no task actions.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:36 +08:00
LU XIANGRUIтаwildcatDownstairs 5f606219b2 fix(run): make the injected Gradle init scripts work on Gradle 4.6–6.3 (#3875)
Run/Debug, tests, bootRun debug, VM options, coverage, resource update and WAR deployment failed on Gradle before 6.4 because the injected init scripts used newer API without a version check: JavaExec.mainClass (6.4+), tasks.register/named/configureEach (4.9+), debugOptions (5.6+), Report.required (6.1+), archiveFile (5.1+), and sourceSets as an extension (4.10+). Each use now falls back to the older API, with Gradle 4.6 as the oldest supported version; newer Gradle keeps the lazy API.

Closes #3864

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:07 +08:00
28 змінених файлів з 1621 додано та 111 видалено

No files matched your search

+22 -6
Переглянути файл
@@ -47,13 +47,20 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
fs::write( fs::write(
&script, &script,
format!( format!(
r#"gradle.projectsEvaluated {{ r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({}) def p = gradle.rootProject.project({})
def resources = p.tasks.named('processResources') def update = {{ t ->
p.tasks.register('openideaUpdateResources') {{ t.dependsOn 'processResources'
dependsOn resources // Resolved here so the action holds no task or project (configuration cache).
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }} def dir = p.tasks.getByName('processResources').destinationDir
def manifest = new File({})
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
}} }}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}} }}
"#, "#,
literal(&p.path), literal(&p.path),
@@ -172,7 +179,16 @@ mod tests {
assert_eq!(gradle.command, "/tools/gradlew"); assert_eq!(gradle.command, "/tools/gradlew");
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources"); assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap(); let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath")); assert!(
script.contains("processResources")
&& script.contains(".destinationDir\n")
&& script.contains("setText(dir.absolutePath")
);
// `register` is Gradle 4.9+ (#3864).
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
assert!(!script.contains("build/resources/main")); // The task owns custom output locations. assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
} }
+7 -3
Переглянути файл
@@ -30,7 +30,8 @@ def processedResources = { Project p, s ->
def describe = { Project p -> def describe = { Project p ->
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)] def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
if (p.gradle.parent != null) m.build = identity(p.rootProject) if (p.gradle.parent != null) m.build = identity(p.rootProject)
def sets = p.extensions.findByName('sourceSets') // Gradle 4.x has it as a convention property, not an extension.
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
if (sets != null) { if (sets != null) {
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites, // Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
// and sets whose folders the `idea` plugin lists as test sources. // and sets whose folders the `idea` plugin lists as test sources.
@@ -51,9 +52,12 @@ def describe = { Project p ->
} }
} }
try { try {
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
def java = p.extensions.findByName('java') def java = p.extensions.findByName('java')
def lv = java?.toolchain?.languageVersion?.getOrNull() def lv = null
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer) try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {} } catch (ignored) {}
println '@openidea-model\t' + JsonOutput.toJson(m) println '@openidea-model\t' + JsonOutput.toJson(m)
} }
+26 -7
Переглянути файл
@@ -172,13 +172,25 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
fs::write( fs::write(
&script, &script,
format!( format!(
r#"gradle.projectsEvaluated {{ r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({}) def p = gradle.rootProject.project({})
def warTask = p.tasks.named('war') def artifact = {{ t ->
p.tasks.register('openideaTomcatArtifact') {{ t.dependsOn 'war'
dependsOn warTask // Resolved here so the action holds no task or project (configuration cache).
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }} def war = p.tasks.getByName('war')
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
def manifest = new File({})
t.doLast {{
def file = archive instanceof File ? archive : archive.get().asFile
manifest.setText(file.absolutePath, 'UTF-8')
}}
}} }}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}} }}
"#, "#,
groovy_literal(path), groovy_literal(path),
@@ -270,7 +282,7 @@ mod tests {
assert_eq!(a.len(), 1); assert_eq!(a.len(), 1);
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap(); let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
assert!(plan.args.contains(&":openideaTomcatArtifact".into())); assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()")); assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
assert!(!crate::gradle::has_war_plugin("// plugins { war }")); assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
} }
@@ -297,7 +309,14 @@ mod tests {
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':')))); assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap(); let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
assert!(script.contains(&format!("rootProject.project('{}')", module))); assert!(script.contains(&format!("rootProject.project('{}')", module)));
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'")); assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
assert!(
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
);
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
} }
} }
} }
+8 -5
Переглянути файл
@@ -167,10 +167,11 @@ const GRADLE: &[&str] = &["gradle", "gradlew"];
/// Gradle's own JVM and the compiler's source encoding are untouched. /// Gradle's own JVM and the compiler's source encoding are untouched.
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8. // Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { allprojects {
tasks.withType(JavaExec).configureEach { each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
defaultCharacterEncoding = 'UTF-8'
}
} }
"; ";
@@ -621,10 +622,12 @@ mod tests {
#[test] #[test]
fn gradle_script_respects_the_builds_own_file_encoding() { fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT; let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}"); assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}"); assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}"); assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}"); assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(s.contains("? tasks.configureEach(action) : tasks.all(action)"), "{s}");
} }
#[test] #[test]
+14 -6
Переглянути файл
@@ -6,11 +6,16 @@ use ide_run::wrap::{self, program_name};
use std::path::Path; use std::path::Path;
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage. const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
allprojects { import org.gradle.util.GradleVersion
plugins.withId('java') { // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
apply plugin: 'jacoco' def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
tasks.withType(Test).configureEach { t -> t.finalizedBy(tasks.named('jacocoTestReport')) } allprojects { p ->
tasks.named('jacocoTestReport') { r -> r.reports { xml.required.set(true) } } p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
def xml = p.tasks.getByName('jacocoTestReport').reports.xml
// `Report.required` is Gradle 6.1+, `enabled` is gone in 8.0.
if (xml.hasProperty('required')) xml.required.set(true) else xml.enabled = true
} }
} }
"#; "#;
@@ -391,7 +396,10 @@ mod tests {
let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path()); let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path());
let (l, report) = launch(&p); let (l, report) = launch(&p);
assert_eq!(l.args[0], "--init-script"); assert_eq!(l.args[0], "--init-script");
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco")); let script = std::fs::read_to_string(&l.args[1]).unwrap();
assert!(script.contains("p.apply plugin: 'jacoco'"), "{script}");
// `Report.required` is Gradle 6.1+, `configureEach` 4.9+ (#3864).
assert!(script.contains("else xml.enabled = true") && script.contains(": tasks.all(action)"), "{script}");
assert!(matches!(report, CoverageReportSpec::Jacoco { .. })); assert!(matches!(report, CoverageReportSpec::Jacoco { .. }));
} }
+1
Переглянути файл
@@ -65,6 +65,7 @@ pub async fn spell_check(
end: r.end, end: r.end,
kind: match r.kind { kind: match r.kind {
SpellingKind::Comment => RegionKind::Comment, SpellingKind::Comment => RegionKind::Comment,
SpellingKind::String if r.raw => RegionKind::RawString,
SpellingKind::String => RegionKind::String, SpellingKind::String => RegionKind::String,
SpellingKind::Name => RegionKind::Name, SpellingKind::Name => RegionKind::Name,
}, },
+34 -3
Переглянути файл
@@ -73,6 +73,33 @@ pub struct SpellingRegion {
pub start: usize, pub start: usize,
pub end: usize, pub end: usize,
pub kind: SpellingKind, pub kind: SpellingKind,
/// A raw / verbatim string: backslashes are literal text, not escapes
/// (`r"\user"`, `r#"…"#`, `` `…` ``, `@"…"`). The spelling layer must not
/// skip the character after a `\` in one of these.
pub raw: bool,
}
/// Whether `node` is a string literal whose backslashes are not escapes.
fn is_raw_string(node: &Node<'_>, text: &str) -> bool {
let kind = node.kind();
// Rust/C++/C# grammars name the node directly.
if kind == "raw_string_literal" || kind == "verbatim_string_literal" || kind.contains("raw_string") {
return true;
}
// Go backtick strings and Python `r`/`fr`/`rb` prefixes: the grammar uses
// the generic `string` node, so inspect the literal's own prefix.
if kind == "string" || kind == "string_literal" {
let literal = &text[node.start_byte()..node.end_byte()];
if literal.starts_with('`') {
return true;
}
let quote = literal.find(['"', '\'']);
let prefix = quote.map_or("", |i| &literal[..i]);
return !prefix.is_empty()
&& prefix.chars().any(|c| c == 'r' || c == 'R')
&& prefix.chars().all(|c| matches!(c, 'r' | 'R' | 'b' | 'B' | 'f' | 'F' | 'u' | 'U'));
}
false
} }
fn is_name_leaf(kind: &str) -> bool { fn is_name_leaf(kind: &str) -> bool {
@@ -101,16 +128,20 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
} }
/// Comments, string literals and declared names, for spell checking. /// Comments, string literals and declared names, for spell checking.
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> { pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> Vec<SpellingRegion> {
let mut out = Vec::new(); let mut out = Vec::new();
let mut cursor = tree.walk(); let mut cursor = tree.walk();
loop { loop {
let node = cursor.node(); let node = cursor.node();
let literal = kind_of(&node); let literal = kind_of(&node);
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind }; let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
match literal { match literal {
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)), Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
Some(LiteralKind::String) => out.push(region(SpellingKind::String)), Some(LiteralKind::String) => {
let mut r = region(SpellingKind::String);
r.raw = is_raw_string(&node, text);
out.push(r);
}
None if node.is_named() None if node.is_named()
&& node.child_count() == 0 && node.child_count() == 0
&& is_name_leaf(node.kind()) && is_name_leaf(node.kind())
+1 -1
Переглянути файл
@@ -294,7 +294,7 @@ impl Syntax {
/// Comments, string literals and declared names (byte ranges, document /// Comments, string literals and declared names (byte ranges, document
/// order) for the Typo inspection; `None` like [`Self::literals`]. /// order) for the Typo inspection; `None` like [`Self::literals`].
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> { pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree))) self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
} }
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first. /// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
+29
Переглянути файл
@@ -1422,6 +1422,35 @@ fn spelling_regions_cover_declared_names_only() {
assert_eq!(names, ["Bird", "fly", "text"]); assert_eq!(names, ["Bird", "fly", "text"]);
} }
#[test]
fn spelling_regions_mark_raw_strings() {
let py = r#"a = r"\user" + R'\mesage' + fr"\wrd" + rb"\foo" + "\user""#;
let found: Vec<(&str, bool)> = syntax()
.spelling_regions(&lang("python"), py)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::String)
.map(|r| (&py[r.start..r.end], r.raw))
.collect();
assert_eq!(
found,
vec![
(r#"r"\user""#, true),
(r"R'\mesage'", true),
(r#"fr"\wrd""#, true),
(r#"rb"\foo""#, true),
(r#""\user""#, false),
]
);
// C# verbatim / Rust raw literals are named by the grammar itself.
let cs = r#"var s = @"C:\mesage";"#;
let raw = syntax().spelling_regions(&lang("csharp"), cs).unwrap().iter().any(|r| r.raw);
assert!(raw, "C# verbatim string should be raw");
let rs = r#"let s = r"\mesage";"#;
let raw = syntax().spelling_regions(&lang("rust"), rs).unwrap().iter().any(|r| r.raw);
assert!(raw, "Rust raw string should be raw");
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Script regions of Vue SFCs and HTML documents // Script regions of Vue SFCs and HTML documents
+5
Переглянути файл
@@ -0,0 +1,5 @@
doctrine-mapping.xsd is from Doctrine ORM (https://github.com/doctrine/orm),
MIT License. Copyright (c) Doctrine Project.
The copy published at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd
is broken (wrong targetNamespace / XMLSchema URI after an http→https rewrite);
this file is the upstream schema with the correct namespace.
+643
Переглянути файл
@@ -0,0 +1,643 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:orm="http://doctrine-project.org/schemas/orm/doctrine-mapping"
elementFormDefault="qualified">
<xs:annotation>
<xs:documentation><![CDATA[
This is the XML Schema for the object/relational
mapping file used by the Doctrine ORM.
]]></xs:documentation>
</xs:annotation>
<xs:element name="doctrine-mapping">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="mapped-superclass" type="orm:mapped-superclass" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="entity" type="orm:entity" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="embeddable" type="orm:embeddable" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:element>
<xs:complexType name="emptyType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="cascade-type">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cascade-all" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-persist" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-merge" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-remove" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-refresh" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-detach" type="orm:emptyType" minOccurs="0"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="lifecycle-callback-type">
<xs:restriction base="xs:token">
<xs:enumeration value="prePersist"/>
<xs:enumeration value="postPersist"/>
<xs:enumeration value="preUpdate"/>
<xs:enumeration value="postUpdate"/>
<xs:enumeration value="preRemove"/>
<xs:enumeration value="postRemove"/>
<xs:enumeration value="postLoad"/>
<xs:enumeration value="preFlush"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cache-usage-type">
<xs:restriction base="xs:token">
<xs:enumeration value="READ_ONLY"/>
<xs:enumeration value="READ_WRITE"/>
<xs:enumeration value="NONSTRICT_READ_WRITE"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="lifecycle-callback">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:lifecycle-callback-type" use="required" />
<xs:attribute name="method" type="xs:NMTOKEN" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="lifecycle-callbacks">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-query">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="query" type="xs:string" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-queries">
<xs:sequence>
<xs:element name="named-query" type="orm:named-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="named-native-query">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="query" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="result-class" type="orm:fqcn" />
<xs:attribute name="result-set-mapping" type="xs:string" />
</xs:complexType>
<xs:complexType name="named-native-queries">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="named-native-query" type="orm:named-native-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="entity-listener">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn"/>
</xs:complexType>
<xs:complexType name="entity-listeners">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-listener" type="orm:entity-listener" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="column-result">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="field-result">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="column" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity-result">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field-result" type="orm:field-result" minOccurs="0" maxOccurs="unbounded" />
</xs:choice>
<xs:attribute name="entity-class" type="orm:fqcn" use="required" />
<xs:attribute name="discriminator-column" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="sql-result-set-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-result" type="orm:entity-result"/>
<xs:element name="column-result" type="orm:column-result"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="sql-result-set-mappings">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="cache">
<xs:attribute name="usage" type="orm:cache-usage-type" />
<xs:attribute name="region" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:element name="indexes" type="orm:indexes" minOccurs="0"/>
<xs:element name="unique-constraints" type="orm:unique-constraints" minOccurs="0"/>
<xs:element name="discriminator-column" type="orm:discriminator-column" minOccurs="0"/>
<xs:element name="discriminator-map" type="orm:discriminator-map" minOccurs="0"/>
<xs:element name="lifecycle-callbacks" type="orm:lifecycle-callbacks" minOccurs="0" maxOccurs="1" />
<xs:element name="entity-listeners" type="orm:entity-listeners" minOccurs="0" maxOccurs="1" />
<xs:element name="named-queries" type="orm:named-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="named-native-queries" type="orm:named-native-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="sql-result-set-mappings" type="orm:sql-result-set-mappings" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="id" type="orm:id" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="field" type="orm:field" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="embedded" type="orm:embedded" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-one" type="orm:one-to-one" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-many" type="orm:one-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-one" type="orm:many-to-one" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-many" type="orm:many-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="association-overrides" type="orm:association-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="attribute-overrides" type="orm:attribute-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="table" type="orm:tablename" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:attribute name="repository-class" type="orm:fqcn"/>
<xs:attribute name="inheritance-type" type="orm:inheritance-type"/>
<xs:attribute name="change-tracking-policy" type="orm:change-tracking-policy" />
<xs:attribute name="read-only" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="tablename" id="tablename">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff.]+" id="tablename.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="option" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="options">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="mapped-superclass" >
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="embeddable">
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="change-tracking-policy">
<xs:restriction base="xs:token">
<xs:enumeration value="DEFERRED_IMPLICIT"/>
<xs:enumeration value="DEFERRED_EXPLICIT"/>
<xs:enumeration value="NOTIFY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="inheritance-type">
<xs:restriction base="xs:token">
<xs:enumeration value="SINGLE_TABLE"/>
<xs:enumeration value="JOINED"/>
<xs:enumeration value="TABLE_PER_CLASS"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generator-strategy">
<xs:restriction base="xs:token">
<xs:enumeration value="NONE"/>
<xs:enumeration value="SEQUENCE"/>
<xs:enumeration value="IDENTITY"/>
<xs:enumeration value="AUTO"/>
<xs:enumeration value="UUID"/>
<xs:enumeration value="CUSTOM" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fk-action">
<xs:restriction base="xs:token">
<xs:enumeration value="CASCADE"/>
<xs:enumeration value="RESTRICT"/>
<xs:enumeration value="SET NULL"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fetch-type">
<xs:restriction base="xs:token">
<xs:enumeration value="EAGER"/>
<xs:enumeration value="LAZY"/>
<xs:enumeration value="EXTRA_LAZY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generated-type">
<xs:restriction base="xs:token">
<xs:enumeration value="NEVER"/>
<xs:enumeration value="INSERT"/>
<xs:enumeration value="ALWAYS"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updatable" type="xs:boolean" default="true" />
<xs:attribute name="generated" type="orm:generated-type" default="NEVER" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="embedded">
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="optional" />
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
</xs:complexType>
<xs:complexType name="discriminator-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="xs:NMTOKEN"/>
<xs:attribute name="field-name" type="xs:NMTOKEN" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraint">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraints">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="unique-constraint" type="orm:unique-constraint" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="index">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:attribute name="flags" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="indexes">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="index" type="orm:index" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="value" type="orm:type" use="required"/>
<xs:attribute name="class" type="orm:fqcn" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-map">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="discriminator-mapping" type="orm:discriminator-mapping" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="strategy" type="orm:generator-strategy" use="optional" default="AUTO" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="id">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="generator" type="orm:generator" minOccurs="0" />
<xs:element name="sequence-generator" type="orm:sequence-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="custom-id-generator" type="orm:custom-id-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="association-key" type="xs:boolean" default="false" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="sequence-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="sequence-name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="allocation-size" type="xs:integer" use="optional" default="1" />
<xs:attribute name="initial-value" type="xs:integer" use="optional" default="1" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="custom-id-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn" use="required" />
</xs:complexType>
<xs:simpleType name="fqcn" id="fqcn">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+" id="fqcn.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="type" id="type">
<xs:restriction base="xs:token">
<xs:pattern value="([a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+)|(\c+)" id="type.class.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="inverse-join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional" />
<xs:attribute name="referenced-column-name" type="xs:NMTOKEN" use="optional" default="id" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="true" />
<xs:attribute name="on-delete" type="orm:fk-action" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-table">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-columns" type="orm:join-columns" />
<xs:element name="inverse-join-columns" type="orm:join-columns" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="order-by-field" type="orm:order-by-field" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="direction" type="orm:order-by-direction" default="ASC" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="order-by-direction">
<xs:restriction base="xs:token">
<xs:enumeration value="ASC"/>
<xs:enumeration value="DESC"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="columntoken" id="columntoken">
<xs:restriction base="xs:token">
<xs:pattern value="[-._:A-Za-z0-9`]+" id="columntoken.pattern"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="many-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" use="required" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="many-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="association-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="association-override" type="orm:association-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="association-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="join-columns" type="orm:join-columns" minOccurs="0" />
<xs:element name="inversed-by" type="orm:inversed-by-override" minOccurs="0" maxOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="fetch" type="orm:fetch-type" use="optional" />
</xs:complexType>
<xs:complexType name="inversed-by-override">
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="attribute-override" type="orm:attribute-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="attribute-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field" type="orm:attribute-override-field" minOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-override-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updateable" type="xs:boolean" default="true" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:schema>
+4
Переглянути файл
@@ -40,6 +40,7 @@ mod uri;
mod virtual_doc; mod virtual_doc;
mod vue_navigation; mod vue_navigation;
mod vue_refs; mod vue_refs;
mod xml_catalog;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES}; pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions}; pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
@@ -3795,6 +3796,9 @@ impl LspManager {
if cfg.name == compose::SERVER { if cfg.name == compose::SERVER {
compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files()); compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files());
} }
if cfg.name == xml_catalog::SERVER {
xml_catalog::configure_lemminx_catalogs(&mut cfg);
}
cfg cfg
} }
+149
Переглянути файл
@@ -0,0 +1,149 @@
//! Bundled XML catalogs for LemMinX so known-broken remote XSDs resolve locally.
//!
//! Doctrine's hosted `doctrine-mapping.xsd` advertises the wrong `targetNamespace`
//! (the schema URL itself) after an http→https rewrite, so any mapping file that
//! points `xsi:schemaLocation` at that URL fails with `TargetNamespace.1` /
//! `cvc-elt.1.a`. An OASIS catalog maps the namespace and those system IDs to the
//! correct upstream schema we ship.
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const SERVER: &str = "lemminx";
const DOCTRINE_XSD: &str = include_str!("../schemas/xml/doctrine-mapping.xsd");
const CATALOG_TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://doctrine-project.org/schemas/orm/doctrine-mapping" uri="doctrine-mapping.xsd"/>
<uri name="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
</catalog>
"#;
/// Writes the bundled catalog (idempotent) and prepends it to LemMinX `xml.catalogs`.
pub fn configure_lemminx_catalogs(cfg: &mut LanguageServerConfig) {
if cfg.name != SERVER {
return;
}
let Some(catalog) = ensure_catalog() else { return };
let catalog = path_for_settings(&catalog);
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
let Some(root) = settings.as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(xml) = root.entry("xml").or_insert_with(|| json!({})).as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(catalogs) = xml.entry("catalogs").or_insert_with(|| json!([])).as_array_mut() else {
cfg.settings = Some(settings);
return;
};
if catalogs.iter().any(|v| v.as_str() == Some(catalog.as_str())) {
cfg.settings = Some(settings);
return;
}
catalogs.insert(0, Value::String(catalog));
cfg.settings = Some(settings);
}
fn ensure_catalog() -> Option<PathBuf> {
// Per-pid directory: shared `/tmp/openidea-xml-catalog` would let another
// local user plant a catalog that remaps arbitrary schema URIs.
let dir = std::env::temp_dir().join(format!("openidea-xml-catalog-{}", std::process::id()));
if let Err(e) = ide_vfs::create_private_dir(&dir) {
tracing::warn!("xml catalog: cannot create {}: {e}", dir.display());
return None;
}
let xsd = dir.join("doctrine-mapping.xsd");
if !write_if_changed(&xsd, DOCTRINE_XSD.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", xsd.display());
return None;
}
let catalog = dir.join("catalog.xml");
if !write_if_changed(&catalog, CATALOG_TEMPLATE.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", catalog.display());
return None;
}
Some(catalog)
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> bool {
if std::fs::read(path).ok().as_deref() == Some(bytes) {
return true;
}
ide_vfs::write_atomic_private(path, bytes).is_ok()
}
fn path_for_settings(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use ide_language::LanguageRegistry;
const DOCTRINE_NS: &str = "http://doctrine-project.org/schemas/orm/doctrine-mapping";
const DOCTRINE_SCHEMA_HTTPS: &str = "https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
const DOCTRINE_SCHEMA_HTTP: &str = "http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
#[test]
fn bundled_xsd_keeps_http_namespace() {
assert!(DOCTRINE_XSD.contains(&format!("targetNamespace=\"{DOCTRINE_NS}\"")));
assert!(!DOCTRINE_XSD.contains("xmlns:xs=\"https://www.w3.org/2001/XMLSchema\""));
assert!(!DOCTRINE_XSD.contains("targetNamespace=\"https://www.doctrine-project.org"));
}
#[test]
fn catalog_maps_namespace_and_system_ids() {
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTP}""#)));
assert_eq!(CATALOG_TEMPLATE.matches(r#"uri="doctrine-mapping.xsd""#).count(), 4);
}
#[test]
fn prepends_catalog_without_dropping_user_entries() {
let reg = LanguageRegistry::load(None).unwrap();
let xml = reg.get(&ide_core::LanguageId::new("xml")).unwrap();
let mut cfg = xml.language_servers[0].clone();
cfg.settings = Some(json!({"xml": {"catalogs": ["/user/catalog.xml"]}}));
configure_lemminx_catalogs(&mut cfg);
let list: Vec<String> = cfg.settings.as_ref().unwrap()["xml"]["catalogs"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
assert_eq!(list.len(), 2);
assert!(list[0].ends_with("catalog.xml"));
assert!(list[0].contains(&format!("openidea-xml-catalog-{}", std::process::id())));
assert_eq!(list[1], "/user/catalog.xml");
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings.as_ref().unwrap()["xml"]["catalogs"].as_array().unwrap().len(), 2);
let catalog = PathBuf::from(&list[0]);
let body = std::fs::read_to_string(&catalog).unwrap();
assert_eq!(body, CATALOG_TEMPLATE);
assert!(body.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
let xsd = catalog.with_file_name("doctrine-mapping.xsd");
assert_eq!(std::fs::read_to_string(xsd).unwrap(), DOCTRINE_XSD);
}
#[test]
fn ignores_other_servers() {
let reg = LanguageRegistry::load(None).unwrap();
let yaml = reg.get(&ide_core::LanguageId::new("yaml")).unwrap();
let mut cfg = yaml.language_servers[0].clone();
let before = cfg.settings.clone();
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings, before);
}
}
+57 -9
Переглянути файл
@@ -23,7 +23,7 @@
<script> <script>
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide, // A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
// in its highlight colour; the visible area as a frame that can be dragged; the wheel // in its highlight colour; the visible area as a frame that can be dragged; the wheel
// scrolls the editor. // scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out.
const editor = window.openidea.editor; const editor = window.openidea.editor;
const canvas = document.getElementById("map"); const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
@@ -33,6 +33,10 @@
let colors = new Map(); let colors = new Map();
let loading = new Set(); let loading = new Set();
let view = null; let view = null;
let problems = [];
let folds = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null; let drag = null;
let queued = false; let queued = false;
@@ -42,17 +46,39 @@
}; };
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || ""; const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
const rowOf = (line) => {
let hidden = 0;
for (const f of folds) {
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
else break;
}
return line - hidden;
};
const lineOfRow = (row) => {
let hidden = 0;
for (const f of folds) {
const r = f.fromLine - hidden;
if (row >= r + 1) hidden += f.toLine - f.fromLine;
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
else break;
}
return row + hidden;
};
function layout() { function layout() {
const H = canvas.clientHeight; const H = canvas.clientHeight;
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 }; if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
const L = Math.max(1, view.lineCount); const L = Math.max(1, rowOf(view.lineCount));
const visible = Math.max(0, view.lastLine - view.firstLine); const firstRow = rowOf(view.firstLine);
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight); const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable)); const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
const mapH = L * LINE; const mapH = L * LINE;
const offset = p * Math.max(0, mapH - H); const offset = p * Math.max(0, mapH - H);
const range = Math.max(1, Math.min(H, mapH) - visible * LINE); const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L }; return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
} }
function redraw() { function redraw() {
@@ -65,7 +91,7 @@
queued = false; queued = false;
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
const W = canvas.clientWidth; const W = canvas.clientWidth;
const { H, offset, top, height } = layout(); const { H, offset, top, height, L } = layout();
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) { if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
canvas.width = Math.round(W * dpr); canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr); canvas.height = Math.round(H * dpr);
@@ -74,11 +100,12 @@
ctx.clearRect(0, 0, W, H); ctx.clearRect(0, 0, W, H);
if (!view) return; if (!view) return;
const first = Math.floor(offset / LINE); const first = Math.floor(offset / LINE);
const last = Math.min(text.length, Math.ceil((offset + H) / LINE)); const last = Math.min(L, Math.ceil((offset + H) / LINE));
const missing = []; const missing = [];
const muted = cssVar("--openidea-fg-muted"); const muted = cssVar("--openidea-fg-muted");
for (let i = first; i < last; i++) { for (let row = first; row < last; row++) {
const y = i * LINE - offset; const i = lineOfRow(row);
const y = row * LINE - offset;
const line = text[i] || ""; const line = text[i] || "";
// Text without a syntax colour: faint, so the coloured spans stand out. // Text without a syntax colour: faint, so the coloured spans stand out.
ctx.globalAlpha = 0.2; ctx.globalAlpha = 0.2;
@@ -95,6 +122,13 @@
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5); ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
} }
} }
// Problems: errors drawn last, on top; weak warnings in the muted colour.
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
const y = Math.floor(rowOf(p.line));
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
}
// The visible area: a light accent tint and a 1px border, stronger while dragged. // The visible area: a light accent tint and a 1px border, stronger while dragged.
const frameH = Math.max(height, 4); const frameH = Math.max(height, 4);
ctx.fillStyle = cssVar("--openidea-accent"); ctx.fillStyle = cssVar("--openidea-accent");
@@ -134,6 +168,9 @@
} }
const doc = await editor.document.get(); const doc = await editor.document.get();
text = doc.text.split("\n"); text = doc.text.split("\n");
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
view = Object.assign(await editor.viewport(), { version: target.version }); view = Object.assign(await editor.viewport(), { version: target.version });
redraw(); redraw();
} }
@@ -151,6 +188,17 @@
for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k); for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k);
redraw(); redraw();
}); });
if (editor.onProblems)
editor.onProblems((p) => {
problems = p;
redraw();
});
// `onLayout` is API 1.10.
if (editor.onLayout)
editor.onLayout((l) => {
folds = l.folded;
redraw();
});
window.openidea.onThemeChange(redraw); window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas); new ResizeObserver(redraw).observe(canvas);
@@ -158,7 +206,7 @@
const scrollToFrameTop = (frameTop) => { const scrollToFrameTop = (frameTop) => {
const { range, visible, L } = layout(); const { range, visible, L } = layout();
const p = Math.min(1, Math.max(0, frameTop / range)); const p = Math.min(1, Math.max(0, frameTop / range));
void editor.scrollTo(p * Math.max(0, L - visible)); void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
}; };
canvas.addEventListener("pointerdown", (e) => { canvas.addEventListener("pointerdown", (e) => {
if (!view) return; if (!view) return;
+10 -4
Переглянути файл
@@ -26,9 +26,13 @@ pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", "); let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!( format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\ "// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \ allprojects {{\n \
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \ each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\ each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
}}\n" }}\n"
) )
} }
@@ -75,8 +79,10 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() { fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"])); let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']"; let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}"); assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}"); assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
} }
#[test] #[test]
+13 -2
Переглянути файл
@@ -24,6 +24,8 @@ pub use words::{MIN_WORD_CHARS, WordSpan, words};
pub enum RegionKind { pub enum RegionKind {
Comment, Comment,
String, String,
/// A raw / verbatim string: `\` is literal text, not an escape (`r"\user"`).
RawString,
/// A declared identifier (`camelCase` / `snake_case` split). /// A declared identifier (`camelCase` / `snake_case` split).
Name, Name,
/// Plain text / Markdown prose. /// Plain text / Markdown prose.
@@ -53,7 +55,7 @@ impl From<RegionKind> for TypoContext {
fn from(kind: RegionKind) -> Self { fn from(kind: RegionKind) -> Self {
match kind { match kind {
RegionKind::Name => Self::Code, RegionKind::Name => Self::Code,
RegionKind::String => Self::Literal, RegionKind::String | RegionKind::RawString => Self::Literal,
RegionKind::Comment => Self::Comment, RegionKind::Comment => Self::Comment,
RegionKind::Prose => Self::Prose, RegionKind::Prose => Self::Prose,
} }
@@ -89,7 +91,7 @@ impl SpellScope {
pub fn includes(&self, kind: RegionKind) -> bool { pub fn includes(&self, kind: RegionKind) -> bool {
match kind { match kind {
RegionKind::Name => self.code, RegionKind::Name => self.code,
RegionKind::String => self.literals, RegionKind::String | RegionKind::RawString => self.literals,
RegionKind::Comment => self.comments, RegionKind::Comment => self.comments,
RegionKind::Prose => true, RegionKind::Prose => true,
} }
@@ -678,6 +680,15 @@ mod tests {
assert_eq!(found, [("mesage", TypoContext::Code)]); assert_eq!(found, [("mesage", TypoContext::Code)]);
} }
#[test]
fn raw_strings_do_not_lose_the_letter_after_a_backslash() {
let s = Speller::default();
let text = r#"r"\user \mesage""#;
let regions = [Region { start: 0, end: text.len(), kind: RegionKind::RawString }];
let typos = s.check(text, &regions, &|| false).unwrap();
assert_eq!(typos.iter().map(|t| t.word.as_str()).collect::<Vec<_>>(), ["mesage"]);
}
#[test] #[test]
fn scope_filters_region_kinds() { fn scope_filters_region_kinds() {
let comments_only = SpellScope { code: false, literals: false, comments: true }; let comments_only = SpellScope { code: false, literals: false, comments: true };
+12 -1
Переглянути файл
@@ -18,7 +18,7 @@ pub struct WordSpan {
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) { pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
let Some(slice) = text.get(start..end) else { return }; let Some(slice) = text.get(start..end) else { return };
let escapes = match kind { let escapes = match kind {
RegionKind::Name => Escapes::None, RegionKind::Name | RegionKind::RawString => Escapes::None,
RegionKind::String => Escapes::Char, RegionKind::String => Escapes::Char,
RegionKind::Comment | RegionKind::Prose => Escapes::Word, RegionKind::Comment | RegionKind::Prose => Escapes::Word,
}; };
@@ -186,6 +186,17 @@ mod tests {
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]); assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
} }
#[test]
fn raw_strings_keep_the_letter_after_a_backslash() {
// `\u` in a normal string is an escape: the letter is consumed and only
// `ser` is prose. In a raw string the backslash is literal, so `user`
// must be checked whole (issue: r"\user" flagged as typo 'ser').
assert_eq!(split(r#""\user""#, RegionKind::String), ["ser"]);
assert_eq!(split(r#""\user""#, RegionKind::RawString), ["user"]);
assert_eq!(split(r"\n\t \wrd", RegionKind::RawString), ["wrd"]);
assert_eq!(split(r"C:\Users\mesage", RegionKind::RawString), ["Users", "mesage"]);
}
#[test] #[test]
fn skips_backslash_commands_in_comments() { fn skips_backslash_commands_in_comments() {
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]); assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
+35 -14
Переглянути файл
@@ -447,6 +447,17 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
required `when`: the command runs on a plain Escape in a focused editor once the required `when`: the command runs on a plain Escape in a focused editor once the
IDE's own Escape handling (popups, completion, rename, selection, extra carets, IDE's own Escape handling (popups, completion, rename, selection, extra carets,
Vim) found nothing to do. Vim) found nothing to do.
- **The marker bar's problems in editor panels.** An editor panel's page reads
the problems its group's marker bar shows with `openidea.editor.problems()`
and hears them change through `onProblems`. See _Editor panels_.
- **Semantic highlighting in editor panels.** `openidea.editor.highlights()`
returns the colours the editor shows, semantic highlighting from the language
server layered over the syntax colours, and `onHighlights` reports the lines
whose colours change when semantic tokens arrive. See _Editor panels_.
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
lines are folded with `openidea.editor.folded()`, how many rows each line takes
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
through `onLayout`. See _Editor panels_.
### API 1.9 ### API 1.9
@@ -1912,22 +1923,32 @@ sit side by side.
The page gets `openidea.editor` (only an editor panel's page has it). Lines are The page gets `openidea.editor` (only an editor panel's page has it). Lines are
0-based, columns UTF-16: 0-based, columns UTF-16:
| `openidea.editor` | What it does | | `openidea.editor` | What it does |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` | | `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none | | `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame | | `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame | | `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging | | `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel | | `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the syntax colour in the current scheme (a CSS colour) | | `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the colour the editor shows in the current scheme (a CSS colour; API 1.10: semantic highlighting included) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed | | `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
Colours come from syntax highlighting only (no semantic highlighting yet); the Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
highlighting over it (a semantic colour wins where both apply). The
panel's other colours are the frame's theme variables (`openidea.theme`, panel's other colours are the frame's theme variables (`openidea.theme`,
`onThemeChange`). Not there yet: the caret and selections, and the marker bar's `onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped` or
problems and changes. `crates/ide-plugin/tests/fixtures/editor-panel` is a `onLayout`: check for them (`if (editor.problems)`) when the page also runs in
minimal minimap (each line 2 px, its frame draggable) to install and try. older IDEs. Outside the visible area the editor estimates wrapped rows from the
line's length until it lays the line out; `onLayout` follows when it does. Not
there yet: the caret and selections, and the marker bar's changes.
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
2 px, its frame draggable, problems marked at its right edge, folded lines left out) to install and try.
### Web frame PTYs (API 1.3) ### Web frame PTYs (API 1.3)
+27 -7
Переглянути файл
@@ -4,7 +4,7 @@
* path through `@codemirror/lint` (wavy underlines, no gutter, no lint * path through `@codemirror/lint` (wavy underlines, no gutter, no lint
* tooltip — `hover.ts` renders diagnostics together with documentation). * tooltip — `hover.ts` renders diagnostics together with documentation).
*/ */
import type { Text } from "@codemirror/state"; import type { EditorState, Text } from "@codemirror/state";
import { EditorSelection, StateEffect, StateField } from "@codemirror/state"; import { EditorSelection, StateEffect, StateField } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint"; import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint";
@@ -165,32 +165,52 @@ const MARK_COLOR: Partial<Record<Severity, string>> = {
info: "var(--info)", info: "var(--info)",
}; };
/** A diagnostic's mark on the overview lane (the marker bar). */
export interface ProblemMark extends ScrollbarMark {
to: number;
severity: Severity;
}
/** Overview-lane (scrollbar) marks for diagnostics, errors on top. */ /** Overview-lane (scrollbar) marks for diagnostics, errors on top. */
export function diagnosticMarks(diags: readonly LintDiagnostic[]): ScrollbarMark[] { export function diagnosticMarks(diags: readonly LintDiagnostic[]): ProblemMark[] {
const out: ScrollbarMark[] = []; const out: ProblemMark[] = [];
for (const d of diags) { for (const d of diags) {
const color = MARK_COLOR[d.severity]; const color = MARK_COLOR[d.severity];
if (!color || d.markClass?.includes("cm-lsp-unnecessary") || d.markClass?.includes("cm-lsp-typo")) continue; if (!color || d.markClass?.includes("cm-lsp-unnecessary") || d.markClass?.includes("cm-lsp-typo")) continue;
out.push({ from: d.from, to: d.to, color, tooltip: d.message, priority: 3 - SEVERITY_RANK[d.severity] }); out.push({
from: d.from,
to: d.to,
color,
tooltip: d.message,
priority: 3 - SEVERITY_RANK[d.severity],
severity: d.severity,
});
} }
return out; return out;
} }
const setMarks = StateEffect.define<readonly ScrollbarMark[]>(); const setMarks = StateEffect.define<readonly ProblemMark[]>();
const marksField = StateField.define<readonly ScrollbarMark[]>({ const marksField = StateField.define<readonly ProblemMark[]>({
create: () => [], create: () => [],
update(marks, tr) { update(marks, tr) {
for (const e of tr.effects) if (e.is(setMarks)) return e.value; for (const e of tr.effects) if (e.is(setMarks)) return e.value;
if (!tr.docChanged || !marks.length) return marks; if (!tr.docChanged || !marks.length) return marks;
return marks.map((m) => { return marks.map((m) => {
const from = tr.changes.mapPos(m.from); const from = tr.changes.mapPos(m.from);
return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to ?? m.from)) }; return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to)) };
}); });
}, },
provide: (f) => scrollbarMarks.from(f), provide: (f) => scrollbarMarks.from(f),
}); });
const NO_MARKS: readonly ProblemMark[] = [];
/** The problems the marker bar shows for `state`'s document, in document order; positions follow edits. */
export function markerBarProblems(state: EditorState): readonly ProblemMark[] {
return state.field(marksField, false) ?? NO_MARKS;
}
const diagnosticsSync = ViewPlugin.fromClass( const diagnosticsSync = ViewPlugin.fromClass(
class { class {
private unsubscribe: () => void; private unsubscribe: () => void;
+6 -1
Переглянути файл
@@ -14,7 +14,7 @@
*/ */
import { syntaxTree } from "@codemirror/language"; import { syntaxTree } from "@codemirror/language";
import type { Tree } from "@lezer/common"; import type { Tree } from "@lezer/common";
import { Prec, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; 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 { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { commands, type SemanticTokens } from "@/platform/ipc"; import { commands, type SemanticTokens } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings"; import { editorPrefs } from "@/platform/editorSettings";
@@ -207,6 +207,11 @@ const semanticField = StateField.define<DecorationSet>({
}, },
}); });
/** The semantic marks the editor shows over the syntax colours (empty without semantic highlighting). */
export function semanticHighlights(state: EditorState): DecorationSet {
return state.field(semanticField, false) ?? Decoration.none;
}
const semanticPlugin = ViewPlugin.fromClass( const semanticPlugin = ViewPlugin.fromClass(
class { class {
private refresh = debounce(() => void this.run(), 600); private refresh = debounce(() => void this.run(), 600);
+291 -3
Переглянути файл
@@ -1,21 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react"; import { render, waitFor } from "@testing-library/react";
import { javascript } from "@codemirror/lang-javascript"; import { javascript } from "@codemirror/lang-javascript";
import { syntaxHighlighting } from "@codemirror/language"; import { codeFolding, foldEffect, syntaxHighlighting, unfoldEffect } from "@codemirror/language";
import { EditorState } from "@codemirror/state"; import { EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view"; import { EditorView } from "@codemirror/view";
import type { PluginInfo } from "@/bindings"; import type { Diagnostic, PluginInfo } from "@/bindings";
import type { TextEditorHandle } from "@/editor/api"; import type { TextEditorHandle } from "@/editor/api";
import { diagnosticsExtension, setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { lspDoc } from "@/editor/lsp/lsp";
import { openideaHighlightStyle } from "@/editor/core/cm/highlight"; import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { setContext } from "@/platform/context"; import { setContext } from "@/platform/context";
import { useEditorGroupPanels } from "@/workbench/contributions"; import { useEditorGroupPanels } from "@/workbench/contributions";
import type { SemanticTokens } from "@/platform/ipc";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend"; import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { usePlugins } from "../store"; import { usePlugins } from "../store";
import { FRAME_TAG, frameDocument } from "../views/frame"; import { FRAME_TAG, frameDocument } from "../views/frame";
import { PanelEditor, editorPanelUpdates, projectEditorPanel } from "../views/editorPanel"; import { PanelEditor, editorPanelUpdates, projectEditorPanel } from "../views/editorPanel";
import { WebView, type FrameEditor, type FrameEditorEvent } from "../views/WebView"; import { WebView, type FrameEditor, type FrameEditorEvent } from "../views/WebView";
// The language server's semantic tokens, for the editor's semantic highlighting.
const lsp = vi.hoisted(() => ({ tokens: { data: [], tokenTypes: [], tokenModifiers: [] } as SemanticTokens }));
const lspSemanticTokens = vi.hoisted(() => async () => ({ status: "ok" as const, data: lsp.tokens }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSemanticTokens } };
});
const { semanticExtension } = await import("@/editor/lsp/semantic");
afterEach(() => { afterEach(() => {
vi.useRealTimers();
setPluginsBackend(null); setPluginsBackend(null);
usePlugins.setState({ plugins: [] }); usePlugins.setState({ plugins: [] });
}); });
@@ -64,9 +77,14 @@ describe("frame bridge: openidea.editor", () => {
scrollTo(line: number): Promise<unknown>; scrollTo(line: number): Promise<unknown>;
scrollBy(pixels: number): Promise<unknown>; scrollBy(pixels: number): Promise<unknown>;
highlights(from: number, to: number): Promise<unknown>; highlights(from: number, to: number): Promise<unknown>;
problems(): Promise<unknown>;
folded(): Promise<unknown>;
wrapped(from: number, to: number): Promise<unknown>;
onTarget(fn: (v: unknown) => void): void; onTarget(fn: (v: unknown) => void): void;
onViewport(fn: (v: unknown) => void): void; onViewport(fn: (v: unknown) => void): void;
onHighlights(fn: (v: unknown) => void): void; onHighlights(fn: (v: unknown) => void): void;
onProblems(fn: (v: unknown) => void): void;
onLayout(fn: (v: unknown) => void): void;
document: unknown; document: unknown;
}; };
expect(editor.document).toBe(api.document); expect(editor.document).toBe(api.document);
@@ -86,19 +104,33 @@ describe("frame bridge: openidea.editor", () => {
expect(sent.at(-1)).toMatchObject({ op: "editor.highlights", args: { fromLine: 0, toLine: 3000 } }); expect(sent.at(-1)).toMatchObject({ op: "editor.highlights", args: { fromLine: 0, toLine: 3000 } });
send({ reply: sent.at(-1)!.call, error: "at most 2000 lines at a time" }); send({ reply: sent.at(-1)!.call, error: "at most 2000 lines at a time" });
await expect(lines).rejects.toThrow("2000"); await expect(lines).rejects.toThrow("2000");
const problems = editor.problems();
expect(sent.at(-1)).toMatchObject({ op: "editor.problems" });
send({ reply: sent.at(-1)!.call, value: [{ line: 2, lastLine: 2, severity: "error" }] });
await expect(problems).resolves.toEqual([{ line: 2, lastLine: 2, severity: "error" }]);
void editor.folded();
expect(sent.at(-1)).toMatchObject({ op: "editor.folded" });
void editor.wrapped(4, 9);
expect(sent.at(-1)).toMatchObject({ op: "editor.wrapped", args: { fromLine: 4, toLine: 9 } });
const events: unknown[] = []; const events: unknown[] = [];
editor.onTarget((v) => events.push(["target", v])); editor.onTarget((v) => events.push(["target", v]));
editor.onViewport((v) => events.push(["viewport", v])); editor.onViewport((v) => events.push(["viewport", v]));
editor.onHighlights((v) => events.push(["highlights", v])); editor.onHighlights((v) => events.push(["highlights", v]));
editor.onProblems((v) => events.push(["problems", v]));
editor.onLayout((v) => events.push(["layout", v]));
send({ editor: "target", value: null }); send({ editor: "target", value: null });
send({ editor: "viewport", value: { firstLine: 1.5 } }); send({ editor: "viewport", value: { firstLine: 1.5 } });
send({ editor: "highlights", value: { fromLine: 0, toLine: 4 } }); send({ editor: "highlights", value: { fromLine: 0, toLine: 4 } });
send({ editor: "problems", value: [] });
send({ editor: "layout", value: { folded: [], softWrap: true } });
send({ editor: "constructor", value: 1 }); send({ editor: "constructor", value: 1 });
expect(events).toEqual([ expect(events).toEqual([
["target", null], ["target", null],
["viewport", { firstLine: 1.5 }], ["viewport", { firstLine: 1.5 }],
["highlights", { fromLine: 0, toLine: 4 }], ["highlights", { fromLine: 0, toLine: 4 }],
["problems", []],
["layout", { folded: [], softWrap: true }],
]); ]);
}); });
@@ -124,6 +156,12 @@ describe("WebView as an editor panel", () => {
calls.push(["highlights", from, to]); calls.push(["highlights", from, to]);
return [[{ from: 0, to: 5, color: "rgb(1, 2, 3)" }]]; return [[{ from: 0, to: 5, color: "rgb(1, 2, 3)" }]];
}, },
problems: () => [{ line: 1, lastLine: 2, severity: "warning" }],
folded: () => [{ fromLine: 0, toLine: 2 }],
wrapped: (from, to) => {
calls.push(["wrapped", from, to]);
return [1, 3];
},
subscribe: (l) => { subscribe: (l) => {
listeners.add(l); listeners.add(l);
return () => void listeners.delete(l); return () => void listeners.delete(l);
@@ -178,6 +216,17 @@ describe("WebView as an editor panel", () => {
// Read-only: the page cannot edit the group's file. // Read-only: the page cannot edit the group's file.
send({ call: 8, op: "document.edit", args: { version: 0, edits: [] } }); send({ call: 8, op: "document.edit", args: { version: 0, edits: [] } });
expect((await reply(8)).error).toBeDefined(); expect((await reply(8)).error).toBeDefined();
send({ call: 9, op: "editor.problems" });
expect((await reply(9)).value).toEqual([{ line: 1, lastLine: 2, severity: "warning" }]);
send({ call: 10, op: "editor.folded" });
expect((await reply(10)).value).toEqual([{ fromLine: 0, toLine: 2 }]);
send({ call: 11, op: "editor.wrapped", args: { fromLine: 1, toLine: 3 } });
expect((await reply(11)).value).toEqual([1, 3]);
send({ call: 12, op: "editor.wrapped", args: { fromLine: 0, toLine: 2001 } });
expect(String((await reply(12)).error)).toContain("2000");
send({ call: 13, op: "editor.wrapped", args: { fromLine: 0.5, toLine: 2 } });
expect((await reply(13)).error).toBeDefined();
expect(calls.at(-1)).toEqual(["wrapped", 1, 3]);
editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } }); editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } });
expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } }); expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } });
@@ -273,6 +322,245 @@ describe("PanelEditor", () => {
}); });
}); });
describe("PanelEditor semantic highlights", () => {
it("layers the semantic colours over the syntax colours and follows the tokens", async () => {
vi.useFakeTimers();
const PATH = "/p/src/semantic.js";
lsp.tokens = { data: [1, 0, 5, 0, 0], tokenTypes: ["property"], tokenModifiers: [] };
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({
doc: "let total = 1;\ntotal;\nend",
extensions: [
lspDoc.of({ doc: 1, path: PATH, language: "javascript", uiMode: null, readOnly: false }),
javascript(),
syntaxHighlighting(openideaHighlightStyle),
semanticExtension(),
EditorView.theme({ ".cm-sem-property": { color: "rgb(1, 2, 3)" } }),
editorPanelUpdates,
],
}),
});
const handle: TextEditorHandle = {
view,
tabId: "t1",
ctx: { doc: 1, path: PATH, language: "javascript", uiMode: "JavaScript", readOnly: false },
};
const panel = new PanelEditor();
const events: FrameEditorEvent[] = [];
panel.subscribe((e) => events.push(e));
panel.bind(handle);
const syntaxOnly = panel.highlights(0, 3);
const semantic = "rgb(1, 2, 3)";
expect(syntaxOnly.flat().map((s) => s.color)).not.toContain(semantic);
// The tokens arrive: line 1's `total` takes the semantic colour; the other lines keep theirs.
events.length = 0;
await vi.advanceTimersByTimeAsync(1000);
expect(view.contentDOM.querySelector(".cm-sem-property")).not.toBeNull();
expect(events).toContainEqual({ editor: "highlights", value: { fromLine: 1, toLine: 2 } });
const lines = panel.highlights(0, 3);
expect(lines[1]).toContainEqual({ from: 0, to: 5, color: semantic });
expect(lines[1]!.filter((s) => s.from < 5)).toHaveLength(1);
expect(lines[0]).toEqual(syntaxOnly[0]);
expect(lines[2]).toEqual(syntaxOnly[2]);
// Refreshed after an edit at the end: the token moved to line 0, whose colours are reported.
lsp.tokens = { data: [0, 4, 5, 0, 0], tokenTypes: ["property"], tokenModifiers: [] };
view.dispatch({ changes: { from: view.state.doc.length, insert: "!" } });
await vi.advanceTimersByTimeAsync(20);
events.length = 0;
await vi.advanceTimersByTimeAsync(1000);
expect(events).toContainEqual({ editor: "highlights", value: { fromLine: 0, toLine: 2 } });
expect(panel.highlights(0, 1)[0]).toContainEqual({ from: 4, to: 9, color: semantic });
expect(panel.highlights(1, 2)).toEqual([syntaxOnly[1]]);
panel.dispose();
view.destroy();
});
});
describe("PanelEditor layout", () => {
it("reports the folded lines and the rows of wrapped lines, and follows them", async () => {
const long = "x".repeat(200);
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({
doc: `function f() {\n a;\n b;\n}\n${long}\nend`,
extensions: [codeFolding(), editorPanelUpdates],
}),
});
const handle: TextEditorHandle = {
view,
tabId: "t1",
ctx: { doc: 1, path: "/p/src/a.js", language: "javascript", uiMode: "JavaScript", readOnly: false },
};
const panel = new PanelEditor();
const events: FrameEditorEvent[] = [];
panel.subscribe((e) => events.push(e));
panel.bind(handle);
await nextFrame();
// Neither: no folds, no rows (switching to a file says so).
expect(panel.folded()).toEqual([]);
expect(panel.wrapped(0, 6)).toBeNull();
expect(events.filter((e) => e.editor === "layout")).toEqual([
{ editor: "layout", value: { folded: [], softWrap: false } },
]);
// Folding lines 1–2 (the `{` line stays, `}` joins it), and a fold inside it.
events.length = 0;
const open = view.state.doc.line(1).to;
const close = view.state.doc.line(4).from;
view.dispatch({
effects: [foldEffect.of({ from: open, to: close }), foldEffect.of({ from: open + 3, to: open + 6 })],
});
await nextFrame();
const folds = [{ fromLine: 0, toLine: 3 }];
expect(panel.folded()).toEqual(folds);
expect(events.filter((e) => e.editor === "layout")).toEqual([
{ editor: "layout", value: { folded: folds, softWrap: false } },
]);
// Soft wrap on: the long line takes several rows, the folded ones none. jsdom lays nothing
// out, so the measured state stands in: wrapping on, the long line's block three rows high.
events.length = 0;
let wrapping = false;
Object.defineProperty(view, "lineWrapping", { get: () => wrapping });
const lineBlockAt = view.lineBlockAt.bind(view);
vi.spyOn(view, "lineBlockAt").mockImplementation((pos) => {
const b = lineBlockAt(pos);
return b.from === view.state.doc.line(5).from
? Object.assign(Object.create(b), { height: 3 * view.defaultLineHeight })
: b;
});
wrapping = true;
view.dispatch({ effects: StateEffect.appendConfig.of(EditorView.lineWrapping) });
await nextFrame();
const rows = panel.wrapped(0, 6)!;
expect(rows).toEqual([1, 0, 0, 0, 3, 1]);
expect(panel.wrapped(4, 99)).toEqual(rows.slice(4));
expect(events.filter((e) => e.editor === "layout")).toEqual([
{ editor: "layout", value: { folded: folds, softWrap: true } },
]);
// The outer fold opened: the lines come back, but for the inner fold's.
events.length = 0;
view.dispatch({ effects: unfoldEffect.of({ from: open, to: close }) });
await nextFrame();
const inner = [{ fromLine: 1, toLine: 2 }];
expect(panel.folded()).toEqual(inner);
expect(panel.wrapped(0, 4)).toEqual([1, 1, 0, 1]);
expect(events.filter((e) => e.editor === "layout")).toEqual([
{ editor: "layout", value: { folded: inner, softWrap: true } },
]);
// Soft wrap off: no rows.
events.length = 0;
wrapping = false;
view.dispatch({ effects: StateEffect.reconfigure.of([codeFolding(), editorPanelUpdates]) });
await nextFrame();
expect(panel.wrapped(0, 4)).toBeNull();
expect(events.filter((e) => e.editor === "layout")).toEqual([
{ editor: "layout", value: { folded: inner, softWrap: false } },
]);
// Selecting alone says nothing.
events.length = 0;
view.dispatch({ selection: { anchor: 2 } });
await nextFrame();
expect(events.filter((e) => e.editor === "layout")).toEqual([]);
panel.dispose();
view.destroy();
});
});
describe("PanelEditor problems", () => {
const PATH = "/p/src/problems.js";
const at = (line: number, col: number, endLine = line, endCol = col + 1) => ({
start: { line, col },
end: { line: endLine, col: endCol },
});
const diag = (range: ReturnType<typeof at>, severity: Diagnostic["severity"], extra: Partial<Diagnostic> = {}) =>
({ range, severity, message: severity, source: null, code: null, ...extra }) as Diagnostic;
it("reports the marker bar's problems by line and follows them", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({
doc: "let a = 1;\nlet b = 2;\nfoo(\n bar);\nend",
extensions: [
lspDoc.of({ doc: 1, path: PATH, language: "javascript", uiMode: null, readOnly: false }),
diagnosticsExtension(),
editorPanelUpdates,
],
}),
});
const handle: TextEditorHandle = {
view,
tabId: "t1",
ctx: { doc: 1, path: PATH, language: "javascript", uiMode: "JavaScript", readOnly: false },
};
const panel = new PanelEditor();
const events: FrameEditorEvent[] = [];
panel.subscribe((e) => events.push(e));
panel.bind(handle);
await nextFrame();
// Switching to a file: its problems (none yet).
expect(events).toContainEqual({ editor: "problems", value: [] });
events.length = 0;
setFileDiagnostics(PATH, "test", [
diag(at(2, 0, 3, 6), "error"),
diag(at(0, 4), "warning"),
diag(at(1, 4), "info"),
// Not on the marker bar: hints, unused code.
diag(at(4, 0), "hint"),
diag(at(0, 0), "warning", { unnecessary: true }),
]);
await Promise.resolve();
await nextFrame();
const shown = [
{ line: 0, lastLine: 0, severity: "warning" },
{ line: 1, lastLine: 1, severity: "weakWarning" },
{ line: 2, lastLine: 3, severity: "error" },
];
expect(panel.problems()).toEqual(shown);
expect(events.filter((e) => e.editor === "problems")).toEqual([{ editor: "problems", value: shown }]);
// An edit above moves them.
events.length = 0;
view.dispatch({ changes: { from: 0, insert: "\n" } });
await nextFrame();
expect(events).toContainEqual({
editor: "problems",
value: shown.map((p) => ({ ...p, line: p.line + 1, lastLine: p.lastLine + 1 })),
});
// Fixed: gone.
events.length = 0;
setFileDiagnostics(PATH, "test", []);
await Promise.resolve();
await nextFrame();
expect(events).toEqual([{ editor: "problems", value: [] }]);
// Scrolling or selecting alone says nothing.
events.length = 0;
view.dispatch({ selection: { anchor: 2 } });
await nextFrame();
expect(events.filter((e) => e.editor === "problems")).toEqual([]);
panel.dispose();
view.destroy();
});
});
describe("editorPanels projection", () => { describe("editorPanels projection", () => {
it("shows the panel only while `editor.read` is granted and `when` holds", () => { it("shows the panel only while `editor.read` is granted and `when` holds", () => {
const plugin = (granted: boolean) => const plugin = (granted: boolean) =>
+36 -3
Переглянути файл
@@ -91,10 +91,34 @@ export interface HighlightSpan {
color: string; color: string;
} }
/** One problem of the marker bar, as `openidea.editor.problems()` returns it: 0-based lines. */
export interface EditorProblem {
line: number;
/** The last line the problem covers (`line` for most). */
lastLine: number;
severity: "error" | "warning" | "weakWarning";
}
/** A fold, as `openidea.editor.folded()` returns it: 0-based lines. */
export interface EditorFold {
/** The line that stays visible, showing the placeholder. */
fromLine: number;
/** The last line the fold hides. */
toLine: number;
}
/** What `openidea.editor.onLayout` hears: the folds, and whether long lines wrap. */
export interface EditorLayout {
folded: EditorFold[];
softWrap: boolean;
}
export type FrameEditorEvent = export type FrameEditorEvent =
| { editor: "target"; value: EditorTarget | null } | { editor: "target"; value: EditorTarget | null }
| { editor: "viewport"; value: EditorViewport } | { editor: "viewport"; value: EditorViewport }
| { editor: "highlights"; value: { fromLine: number; toLine: number } }; | { editor: "highlights"; value: { fromLine: number; toLine: number } }
| { editor: "problems"; value: EditorProblem[] }
| { editor: "layout"; value: EditorLayout };
/** The text editor an editor panel's frame follows (`openidea.editor`). */ /** The text editor an editor panel's frame follows (`openidea.editor`). */
export interface FrameEditor { export interface FrameEditor {
@@ -104,6 +128,10 @@ export interface FrameEditor {
scrollBy(pixels: number): void; scrollBy(pixels: number): void;
/** Lines `fromLine` up to `toLine` (exclusive); throws over {@link MAX_HIGHLIGHT_LINES}. */ /** Lines `fromLine` up to `toLine` (exclusive); throws over {@link MAX_HIGHLIGHT_LINES}. */
highlights(fromLine: number, toLine: number): HighlightSpan[][]; highlights(fromLine: number, toLine: number): HighlightSpan[][];
problems(): EditorProblem[];
folded(): EditorFold[];
/** Visual rows of lines `fromLine` up to `toLine` (0 for lines folds hide), or null without soft wrap. */
wrapped(fromLine: number, toLine: number): number[] | null;
subscribe(listener: (event: FrameEditorEvent) => void): () => void; subscribe(listener: (event: FrameEditorEvent) => void): () => void;
} }
@@ -372,9 +400,14 @@ export function WebView({
case "editor.viewport": case "editor.viewport":
case "editor.scrollTo": case "editor.scrollTo":
case "editor.scrollBy": case "editor.scrollBy":
case "editor.highlights": { case "editor.highlights":
case "editor.problems":
case "editor.folded":
case "editor.wrapped": {
if (!editor) throw new Error("this view is not an editor panel"); if (!editor) throw new Error("this view is not an editor panel");
if (op === "editor.get") return [editor.get()]; if (op === "editor.get") return [editor.get()];
if (op === "editor.problems") return [editor.problems()];
if (op === "editor.folded") return [editor.folded()];
if (op === "editor.viewport") return [editor.viewport()]; if (op === "editor.viewport") return [editor.viewport()];
if (op === "editor.scrollTo") return [editor.scrollTo(finite(args.line, "line"))]; if (op === "editor.scrollTo") return [editor.scrollTo(finite(args.line, "line"))];
if (op === "editor.scrollBy") return [editor.scrollBy(finite(args.pixels, "pixels"))]; if (op === "editor.scrollBy") return [editor.scrollBy(finite(args.pixels, "pixels"))];
@@ -383,7 +416,7 @@ export function WebView({
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < from) if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < from)
throw new Error("lines are 0 ≤ fromLine ≤ toLine, whole numbers"); throw new Error("lines are 0 ≤ fromLine ≤ toLine, whole numbers");
if (to - from > MAX_HIGHLIGHT_LINES) throw new Error(`at most ${MAX_HIGHLIGHT_LINES} lines at a time`); if (to - from > MAX_HIGHLIGHT_LINES) throw new Error(`at most ${MAX_HIGHLIGHT_LINES} lines at a time`);
return [editor.highlights(from, to)]; return [op === "editor.wrapped" ? editor.wrapped(from, to) : editor.highlights(from, to)];
} }
case "saveFile": case "saveFile":
case "openFile": { case "openFile": {
+136 -26
Переглянути файл
@@ -2,15 +2,19 @@
* Plugin editor panels (`[[contributes.editorPanels]]`): a web page at the right edge of every * Plugin editor panels (`[[contributes.editorPanels]]`): a web page at the right edge of every
* editor group, following the group's text editor (a minimap, say). Each group has one frame, * editor group, following the group's text editor (a minimap, say). Each group has one frame,
* kept while the group switches tabs: the page hears `onTarget` instead of reloading. Through * kept while the group switches tabs: the page hears `onTarget` instead of reloading. Through
* `openidea.editor` it reads the file (read-only), the viewport and the syntax colours, and * `openidea.editor` it reads the file (read-only), the viewport, the colours (syntax and semantic), the
* scrolls the editor — straight from the editor, not through the plugin's code, since a minimap * marker bar's problems, the folds and the rows of wrapped lines, and scrolls the editor — straight
* follows every frame of a scroll. * from the editor, not through the plugin's code, since a minimap follows every frame of a scroll.
*/ */
import { highlightingFor, syntaxTree } from "@codemirror/language"; import { foldedRanges, highlightingFor, syntaxTree } from "@codemirror/language";
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view"; import { RangeSet, type Range } from "@codemirror/state";
import { BlockType, Decoration, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { highlightTree } from "@lezer/highlight"; import { highlightTree } from "@lezer/highlight";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo } from "react";
import type { Severity } from "@/bindings";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api"; import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { markerBarProblems } from "@/editor/lsp/diagnostics";
import { semanticHighlights } from "@/editor/lsp/semantic";
import { evaluateWhen, useContextKeys } from "@/platform/context"; import { evaluateWhen, useContextKeys } from "@/platform/context";
import { subscribeTheme } from "@/platform/themeWatch"; import { subscribeTheme } from "@/platform/themeWatch";
import { registerEditorGroupPanel } from "@/workbench/contributions"; import { registerEditorGroupPanel } from "@/workbench/contributions";
@@ -19,6 +23,8 @@ import { basename } from "./customEditor";
import { import {
WebView, WebView,
type DocumentState, type DocumentState,
type EditorFold,
type EditorProblem,
type EditorTarget, type EditorTarget,
type EditorViewport, type EditorViewport,
type FrameDocument, type FrameDocument,
@@ -35,6 +41,17 @@ export interface EditorPanelDecl {
when?: string | null; when?: string | null;
} }
/** The marker bar's levels (IDEA's): `info` is a weak warning; hints have no mark. */
const problemLevel = (severity: Severity): EditorProblem["severity"] =>
severity === "error" || severity === "warning" ? severity : "weakWarning";
const syntaxMarks = new Map<string, Decoration>();
const syntaxMark = (classes: string) => {
let m = syntaxMarks.get(classes);
if (!m) syntaxMarks.set(classes, (m = Decoration.mark({ class: classes })));
return m;
};
/** View updates of the editors that panels follow. */ /** View updates of the editors that panels follow. */
const updateListeners = new Map<EditorView, Set<(u: ViewUpdate) => void>>(); const updateListeners = new Map<EditorView, Set<(u: ViewUpdate) => void>>();
@@ -56,6 +73,15 @@ function lineAtHeight(view: EditorView, height: number): number {
return Math.min(doc.lines, first + frac * span); return Math.min(doc.lines, first + frac * span);
} }
/** What the next frame sends: nothing yet. */
const nothingPending = () => ({
viewport: false,
document: false,
problems: false,
layout: false,
lines: null as [number, number] | null,
});
/** One panel frame's view of its group's text editor. */ /** One panel frame's view of its group's text editor. */
export class PanelEditor implements FrameEditor { export class PanelEditor implements FrameEditor {
private handle: TextEditorHandle | null = null; private handle: TextEditorHandle | null = null;
@@ -67,11 +93,7 @@ export class PanelEditor implements FrameEditor {
/** Highlight classes → their colour in the current scheme. */ /** Highlight classes → their colour in the current scheme. */
private readonly colors = new Map<string, string>(); private readonly colors = new Map<string, string>();
private frame = 0; private frame = 0;
private pending: { viewport: boolean; document: boolean; lines: [number, number] | null } = { private pending = nothingPending();
viewport: false,
document: false,
lines: null,
};
readonly document: FrameDocument = { readonly document: FrameDocument = {
read: () => { read: () => {
@@ -99,6 +121,7 @@ export class PanelEditor implements FrameEditor {
if (handle) { if (handle) {
const { view } = handle; const { view } = handle;
const onScroll = () => this.schedule({ viewport: true }); const onScroll = () => this.schedule({ viewport: true });
let softWrap = view.lineWrapping;
const onUpdate = (u: ViewUpdate) => { const onUpdate = (u: ViewUpdate) => {
const lines = u.state.doc.lines; const lines = u.state.doc.lines;
if (u.docChanged) { if (u.docChanged) {
@@ -117,6 +140,23 @@ export class PanelEditor implements FrameEditor {
} }
} }
if (u.geometryChanged || u.heightChanged || u.viewportChanged) this.schedule({ viewport: true }); if (u.geometryChanged || u.heightChanged || u.viewportChanged) this.schedule({ viewport: true });
if (markerBarProblems(u.startState) !== markerBarProblems(u.state)) this.schedule({ problems: true });
// Wrapped rows follow the line blocks' heights.
const wrap = u.view.lineWrapping;
if (foldedRanges(u.startState) !== foldedRanges(u.state) || wrap !== softWrap || (wrap && u.heightChanged)) {
softWrap = wrap;
this.schedule({ layout: true });
}
const semBefore = semanticHighlights(u.startState);
const semAfter = semanticHighlights(u.state);
if (semBefore !== semAfter) {
// New semantic tokens: the lines whose marks differ (in the new document).
const changed = (from: number, to: number) => {
const doc = u.state.doc;
this.schedule({ lines: [doc.lineAt(from).number - 1, doc.lineAt(Math.max(from, to - 1)).number] });
};
RangeSet.compare([semBefore], [semAfter], u.changes, { compareRange: changed, comparePoint: changed });
}
}; };
view.scrollDOM.addEventListener("scroll", onScroll, { passive: true }); view.scrollDOM.addEventListener("scroll", onScroll, { passive: true });
let set = updateListeners.get(view); let set = updateListeners.get(view);
@@ -127,7 +167,7 @@ export class PanelEditor implements FrameEditor {
set.delete(onUpdate); set.delete(onUpdate);
if (!set.size) updateListeners.delete(view); if (!set.size) updateListeners.delete(view);
}; };
this.schedule({ viewport: true }); this.schedule({ viewport: true, problems: true, layout: true });
} }
this.emit({ editor: "target", value: this.get() }); this.emit({ editor: "target", value: this.get() });
} }
@@ -201,38 +241,98 @@ export class PanelEditor implements FrameEditor {
const out: HighlightSpan[][] = Array.from({ length: to - fromLine }, () => []); const out: HighlightSpan[][] = Array.from({ length: to - fromLine }, () => []);
const start = doc.line(fromLine + 1).from; const start = doc.line(fromLine + 1).from;
const end = doc.line(to).to; const end = doc.line(to).to;
const syntax: Range<Decoration>[] = [];
highlightTree( highlightTree(
syntaxTree(state), syntaxTree(state),
{ style: (tags) => highlightingFor(state, tags) }, { style: (tags) => highlightingFor(state, tags) },
(from, until, classes) => { (from, until, classes) => void syntax.push(syntaxMark(classes).range(from, until)),
const color = this.color(view, classes); start,
end,
);
// As the editor layers them: semantic marks inside the syntax spans, so their colour wins.
RangeSet.spans([semanticHighlights(state), Decoration.set(syntax)], start, end, {
span: (from, until, active) => {
if (!active.length) return;
// `active` runs innermost first.
const color = this.color(view, active.map((d) => (d.spec.class as string | undefined) ?? "").reverse());
if (!color) return; if (!color) return;
// A token can run over several lines (a block comment): one span per line. // A token can run over several lines (a block comment): one span per line.
for (let pos = Math.max(from, start); pos < Math.min(until, end);) { for (let pos = from; pos < until;) {
const line = doc.lineAt(pos); const line = doc.lineAt(pos);
const stop = Math.min(until, end, line.to); const stop = Math.min(until, line.to);
if (stop > pos) out[line.number - 1 - fromLine]!.push({ from: pos - line.from, to: stop - line.from, color }); if (stop > pos) out[line.number - 1 - fromLine]!.push({ from: pos - line.from, to: stop - line.from, color });
pos = line.to + 1; pos = line.to + 1;
} }
}, },
start, point: () => {},
end, });
);
return out; return out;
} }
/** The text colour `classes` give in the editor, as the current scheme resolves it. */ problems(): EditorProblem[] {
private color(view: EditorView, classes: string): string { const view = this.handle?.view;
let color = this.colors.get(classes); if (!view) return [];
const doc = view.state.doc;
return markerBarProblems(view.state).map((m) => ({
line: doc.lineAt(m.from).number - 1,
lastLine: doc.lineAt(Math.max(m.from, m.to - 1)).number - 1,
severity: problemLevel(m.severity),
}));
}
folded(): EditorFold[] {
const view = this.handle?.view;
if (!view) return [];
const doc = view.state.doc;
const out: EditorFold[] = [];
foldedRanges(view.state).between(0, doc.length, (from, to) => {
const fromLine = doc.lineAt(from).number - 1;
const toLine = doc.lineAt(to).number - 1;
const last = out.at(-1);
// Folds inside a fold, or starting on the row it ends on, are part of it.
if (last && fromLine <= last.toLine) last.toLine = Math.max(last.toLine, toLine);
else if (toLine > fromLine) out.push({ fromLine, toLine });
});
return out;
}
wrapped(fromLine: number, toLine: number): number[] | null {
const view = this.handle?.view;
if (!view?.lineWrapping) return null;
const doc = view.state.doc;
const out: number[] = [];
for (let n = fromLine + 1; n <= Math.min(toLine, doc.lines); n++) {
const line = doc.line(n);
// The editor's own line blocks: measured in the viewport, estimated elsewhere.
const block = view.lineBlockAt(line.from);
if (block.from < line.from) {
out.push(0);
continue;
}
// Block widgets (above or below the line) are not rows of its text.
const height = Array.isArray(block.type)
? block.type.reduce((h, b) => (b.type === BlockType.Text ? h + b.height : h), 0)
: block.height;
out.push(Math.max(1, Math.round(height / view.defaultLineHeight)));
}
return out;
}
/** The text colour of spans nested with these classes (outermost first), as the current scheme resolves it. */
private color(view: EditorView, nested: string[]): string {
const key = nested.join("\n");
let color = this.colors.get(key);
if (color === undefined) { if (color === undefined) {
// Outside the content DOM, which the editor observes; inside the editor, for its variables. // Outside the content DOM, which the editor observes; inside the editor, for its variables.
const probe = document.createElement("span"); const probe = document.createElement("span");
probe.className = classes;
probe.style.cssText = "position:absolute;visibility:hidden"; probe.style.cssText = "position:absolute;visibility:hidden";
let inner = probe;
for (const classes of nested)
inner = inner.appendChild(Object.assign(document.createElement("span"), { className: classes }));
view.dom.appendChild(probe); view.dom.appendChild(probe);
color = getComputedStyle(probe).color; color = getComputedStyle(inner).color;
probe.remove(); probe.remove();
this.colors.set(classes, color); this.colors.set(key, color);
} }
return color; return color;
} }
@@ -241,10 +341,18 @@ export class PanelEditor implements FrameEditor {
for (const l of this.listeners) l(e); for (const l of this.listeners) l(e);
} }
private schedule(p: { viewport?: boolean; document?: boolean; lines?: [number, number] }) { private schedule(p: {
viewport?: boolean;
document?: boolean;
problems?: boolean;
layout?: boolean;
lines?: [number, number];
}) {
const q = this.pending; const q = this.pending;
q.viewport ||= !!p.viewport; q.viewport ||= !!p.viewport;
q.document ||= !!p.document; q.document ||= !!p.document;
q.problems ||= !!p.problems;
q.layout ||= !!p.layout;
if (p.lines) q.lines = q.lines ? [Math.min(q.lines[0], p.lines[0]), Math.max(q.lines[1], p.lines[1])] : p.lines; if (p.lines) q.lines = q.lines ? [Math.min(q.lines[0], p.lines[0]), Math.max(q.lines[1], p.lines[1])] : p.lines;
if (!this.frame) this.frame = requestAnimationFrame(() => this.flush()); if (!this.frame) this.frame = requestAnimationFrame(() => this.flush());
} }
@@ -252,7 +360,7 @@ export class PanelEditor implements FrameEditor {
private flush() { private flush() {
this.frame = 0; this.frame = 0;
const q = this.pending; const q = this.pending;
this.pending = { viewport: false, document: false, lines: null }; this.pending = nothingPending();
const view = this.handle?.view; const view = this.handle?.view;
if (!view) return; if (!view) return;
if (q.document && this.documentListeners.size) { if (q.document && this.documentListeners.size) {
@@ -265,6 +373,8 @@ export class PanelEditor implements FrameEditor {
this.emit({ editor: "highlights", value: { fromLine, toLine: Math.min(q.lines[1], lines) } }); this.emit({ editor: "highlights", value: { fromLine, toLine: Math.min(q.lines[1], lines) } });
} }
if (q.viewport) this.emit({ editor: "viewport", value: this.viewport()! }); if (q.viewport) this.emit({ editor: "viewport", value: this.viewport()! });
if (q.problems) this.emit({ editor: "problems", value: this.problems() });
if (q.layout) this.emit({ editor: "layout", value: { folded: this.folded(), softWrap: view.lineWrapping } });
} }
} }
+12 -2
Переглянути файл
@@ -19,7 +19,7 @@
const listeners = []; const listeners = [];
const themeListeners = []; const themeListeners = [];
const documentListeners = []; const documentListeners = [];
const editorListeners = { target: [], viewport: [], highlights: [] }; const editorListeners = { target: [], viewport: [], highlights: [], problems: [], layout: [] };
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1)); const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
const pending = new Map(); const pending = new Map();
const root = document.documentElement; const root = document.documentElement;
@@ -99,7 +99,7 @@
} else if (m.document) { } else if (m.document) {
for (const l of documentListeners) safely(l, m.document); for (const l of documentListeners) safely(l, m.document);
} else if (editorPanel && typeof m.editor === "string") { } else if (editorPanel && typeof m.editor === "string") {
// Only the three lists: not `constructor` and the like. // Only those lists: not `constructor` and the like.
const list = editorListeners[m.editor]; const list = editorListeners[m.editor];
if (Array.isArray(list)) for (const l of list) safely(l, m.value); if (Array.isArray(list)) for (const l of list) safely(l, m.value);
} else if (typeof m.text === "string") { } else if (typeof m.text === "string") {
@@ -149,6 +149,16 @@
highlights: (fromLine, toLine) => call("editor.highlights", { fromLine: Number(fromLine), toLine: Number(toLine) }), highlights: (fromLine, toLine) => call("editor.highlights", { fromLine: Number(fromLine), toLine: Number(toLine) }),
/** Called with `{ fromLine, toLine }` when those lines' colours may have changed. */ /** Called with `{ fromLine, toLine }` when those lines' colours may have changed. */
onHighlights: listen(editorListeners.highlights), onHighlights: listen(editorListeners.highlights),
/** The marker bar's problems: `[{ line, lastLine, severity }]`, severity `error`, `warning` or `weakWarning`. */
problems: () => call("editor.problems"),
/** Called with `problems()` when a problem appears or goes away, or its lines move, at most once a frame. */
onProblems: listen(editorListeners.problems),
/** The folded ranges: `[{ fromLine, toLine }]`, the line that stays visible and the last one hidden. */
folded: () => call("editor.folded"),
/** Visual rows of lines `fromLine` up to `toLine` (exclusive), at most 2000; 0 for folded-away lines. Null without soft wrap. */
wrapped: (fromLine, toLine) => call("editor.wrapped", { fromLine: Number(fromLine), toLine: Number(toLine) }),
/** Called with `{ folded, softWrap }` when folds change, soft wrap turns on or off, or wrapped rows may have changed, at most once a frame. */
onLayout: listen(editorListeners.layout),
}); });
window.openidea = Object.freeze({ window.openidea = Object.freeze({
+5 -2
Переглянути файл
@@ -1,10 +1,13 @@
// OpenIDEA: BootRun is a JavaExec task; give its forked application JVM a dynamic // OpenIDEA: BootRun is a JavaExec task; give its forked application JVM a dynamic
// JDWP port instead of Gradle's fixed 5005. The property is added by jdwpLaunch. // JDWP port instead of Gradle's fixed 5005. The property is added by jdwpLaunch.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
gradle.projectsEvaluated { gradle.projectsEvaluated {
allprojects { allprojects {
tasks.matching { it.name == 'bootRun' }.configureEach { task -> each(tasks.matching { it.name == 'bootRun' }) { task ->
if (System.getProperty('openidea.run.debug') == 'true') { if (System.getProperty('openidea.run.debug') == 'true') {
task.debugOptions.enabled = false task.debug = false
task.doFirst { task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll { task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
+10 -3
Переглянути файл
@@ -1,7 +1,11 @@
// OpenIDEA: runs a main class on its Gradle source set's runtime classpath, like IntelliJ // OpenIDEA: runs a main class on its Gradle source set's runtime classpath, like IntelliJ
// IDEA's "Build and run using: Gradle" (ApplicationTaskInitScript.gradle). Parameters come // IDEA's "Build and run using: Gradle" (ApplicationTaskInitScript.gradle). Parameters come
// as system properties so this file never changes: see `gradleRun.ts`. // as system properties so this file never changes: see `gradleRun.ts`. Works from Gradle 4.6,
// the oldest IDEA supports: `register` is Gradle 4.9+, `JavaExec.mainClass` 6.4+.
import groovy.json.JsonSlurper import groovy.json.JsonSlurper
import org.gradle.util.GradleVersion
def lazyTasks = GradleVersion.current() >= GradleVersion.version('4.9')
def target = System.getProperty('openidea.run.project') def target = System.getProperty('openidea.run.project')
if (target != null) { if (target != null) {
@@ -12,10 +16,11 @@ if (target != null) {
p.plugins.withId('java') { p.plugins.withId('java') {
def json = new JsonSlurper() def json = new JsonSlurper()
def list = { String key -> (List) json.parseText(System.getProperty(key, '[]')) } def list = { String key -> (List) json.parseText(System.getProperty(key, '[]')) }
p.tasks.register('openideaRun', JavaExec) { t -> def configure = { JavaExec t ->
t.description = 'Runs a main class for OpenIDEA.' t.description = 'Runs a main class for OpenIDEA.'
t.classpath = p.sourceSets.getByName(System.getProperty('openidea.run.sourceSet', 'main')).runtimeClasspath t.classpath = p.sourceSets.getByName(System.getProperty('openidea.run.sourceSet', 'main')).runtimeClasspath
t.mainClass.set(System.getProperty('openidea.run.main')) def main = System.getProperty('openidea.run.main')
if (t.hasProperty('mainClass')) t.mainClass.set(main) else t.main = main
t.args(list('openidea.run.args')) t.args(list('openidea.run.args'))
t.jvmArgs(list('openidea.run.jvmArgs')) t.jvmArgs(list('openidea.run.jvmArgs'))
// The IDE attaches to this JVM, not to the Gradle daemon; port 0 prints the one picked. // The IDE attaches to this JVM, not to the Gradle daemon; port 0 prints the one picked.
@@ -31,6 +36,8 @@ if (target != null) {
if (dir) t.workingDir = dir if (dir) t.workingDir = dir
t.standardInput = System.in t.standardInput = System.in
} }
if (lazyTasks) p.tasks.register('openideaRun', JavaExec, configure)
else p.tasks.create('openideaRun', JavaExec, configure)
} }
} }
} }
+21
Переглянути файл
@@ -190,6 +190,27 @@ describe("Build and run using: Gradle", () => {
expect(guard).toContain("list('openidea.run.jvmArgs')"); expect(guard).toContain("list('openidea.run.jvmArgs')");
expect(guard).toContain("StartAttachListener|DisableAttachMechanism"); expect(guard).toContain("StartAttachListener|DisableAttachMechanism");
}); });
// Gradle 4.6 is the oldest IDEA supports: `register`, `named` and `configureEach` are 4.9+,
// `debugOptions` 5.6+, `JavaExec.mainClass` 6.4+. Each use needs a guard on its line (#3864).
it.each([
["gradleRun", RUN_SCRIPT],
["gradleTests", TESTS_SCRIPT],
["gradleBoot", BOOT_SCRIPT],
])("%s guards Gradle API newer than 4.6", (_, script) => {
const unguarded = script
.split("\n")
.filter((l) => !l.trim().startsWith("//"))
.filter((l) => /\.register\(|\.named\(|configureEach|debugOptions|mainClass/.test(l))
.filter((l) => !/GradleVersion|lazyTasks|hasProperty/.test(l));
expect(unguarded).toEqual([]);
});
it("sets the main class with `main` and creates the task eagerly on old Gradle (#3864)", () => {
expect(RUN_SCRIPT).toContain("if (t.hasProperty('mainClass')) t.mainClass.set(main) else t.main = main");
expect(RUN_SCRIPT).toContain("else p.tasks.create('openideaRun', JavaExec, configure)");
expect(RUN_SCRIPT).toContain("import org.gradle.util.GradleVersion");
});
}); });
describe("Gradle test runs", () => { describe("Gradle test runs", () => {
+7 -3
Переглянути файл
@@ -2,6 +2,10 @@
// build's output, for the Run window's test tree: Gradle itself prints only failures (or a // build's output, for the Run window's test tree: Gradle itself prints only failures (or a
// project's own format), and writes its XML reports when a task ends. Test tasks always run, // project's own format), and writes its XML reports when a task ends. Test tasks always run,
// so a rerun never ends UP-TO-DATE without results. // so a rerun never ends UP-TO-DATE without results.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
def tc = { String s -> def tc = { String s ->
s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r') s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r')
@@ -9,7 +13,7 @@ def tc = { String s ->
} }
allprojects { allprojects {
tasks.withType(Test).configureEach { Test task -> each(tasks.withType(Test)) { Test task ->
task.outputs.upToDateWhen { false } task.outputs.upToDateWhen { false }
task.addTestListener(new TestListener() { task.addTestListener(new TestListener() {
void beforeSuite(TestDescriptor suite) {} void beforeSuite(TestDescriptor suite) {}
@@ -48,9 +52,9 @@ allprojects {
// Replace build-configured agents only for this debug launch, after project configuration. // Replace build-configured agents only for this debug launch, after project configuration.
gradle.projectsEvaluated { gradle.projectsEvaluated {
allprojects { allprojects {
tasks.withType(Test).configureEach { Test task -> each(tasks.withType(Test)) { Test task ->
if (System.getProperty('openidea.run.debug') == 'true') { if (System.getProperty('openidea.run.debug') == 'true') {
task.debugOptions.enabled = false task.debug = false
task.doFirst { task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll { task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')