feat(plugins): add syntax-aware editor decoration providers (#7579)

Adds an optional syntax-decorations-provider export on plugin API 1.20: a plugin paints foreground colours on ranges of an open text editor from a bounded slice of the editor's own syntax tree (no second parser). A mark is a theme token (rainbow-1 … rainbow-5, mapped onto --syn-rainbow-*) or its own dark and light colours (#rrggbb / #rrggbbaa, the set-styled format; SyntaxMark::colored in the SDK). The host validates the snapshot, drops marks with unknown tokens or invalid colours, debounces and cancels superseded requests, and the editor stylesheet picks the dark or light colour, so a theme change does not ask the plugin again. Sticky Scroll lines keep the marks.

Co-authored-by: fsk <[email protected]>
Цей коміт міститься в:
Furkan Şahin Kulaksız authored and GitHub committed 2026-12-03 03:52:27 +08:00
1 джерело 55274d2dd1
коміт 5ae211ecd6
141 files changed
+2820 -92

No files matched your search

+70 -2
Переглянути файл
@@ -7,8 +7,8 @@ use super::{
use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{IdeResult, RequestId};
use ide_plugin::Invocation;
use ide_core::{DocId, IdeError, IdeResult, Range, RequestId};
use ide_plugin::{Invocation, ProviderDocument, SyntaxDecorationBatch, SyntaxNodeSnapshot};
use ide_workspace::settings::SettingsScope;
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -236,6 +236,72 @@ pub fn plugin_decoration_sets(plugins: &Arc<PluginHost>) -> BTreeMap<String, Vec
plugins.decoration_sets()
}
/// Languages that have a syntax-decoration provider. Does not load plugin code.
#[command(trust = trusted)]
pub fn plugin_syntax_decoration_languages(plugins: &Arc<PluginHost>) -> Vec<String> {
plugins.syntax_decoration_languages()
}
/// Foreground marks for one open document. An unknown document, a document the
/// window does not have, or an invalid snapshot answers with no marks.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn plugin_syntax_decorations(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
request: RequestId,
doc: DocId,
ranges: Vec<Range>,
nodes: Vec<SyntaxNodeSnapshot>,
epoch: u64,
) -> IdeResult<SyntaxDecorationBatch> {
let Ok(project) = host.project(window) else {
return Ok(SyntaxDecorationBatch { version: 0, epoch, stale: false, marks: Vec::new() });
};
let plugins = plugins.clone();
let documents = project.documents.clone();
let cancel = host.begin_project_request(window, request);
let work_cancel = cancel.clone();
let result = blocking(move || {
if work_cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(snap) = documents.snapshot(doc) else { return Ok(None) };
let version = u64::from(snap.version);
// `large` is the code insight limit stamped when the document was opened.
if snap.large {
return Ok(Some((version, Vec::new())));
}
let document = ProviderDocument { path: snap.path.0, language: snap.language.0, version, text: snap.text };
let marks = plugins.provide_syntax_decorations(&document, &ranges, &nodes, &work_cancel);
Ok(Some((version, marks)))
})
.await;
host.end_request(request);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Some((version, marks)) = result? else {
return Ok(SyntaxDecorationBatch { version: 0, epoch, stale: false, marks: Vec::new() });
};
let current = host
.project(window)
.ok()
.filter(|current| Arc::ptr_eq(current, &project))
.and_then(|project| project.documents.version(doc).ok())
.map(u64::from);
if current != Some(version) {
return Ok(SyntaxDecorationBatch {
version: current.unwrap_or(version),
epoch,
stale: true,
marks: Vec::new(),
});
}
Ok(SyntaxDecorationBatch { version, epoch, stale: false, marks })
}
/// Every plugin's console highlight rules (later changes arrive as `consoleRulesChanged`).
#[command(trust = trusted)]
pub fn plugin_console_rules(plugins: &Arc<PluginHost>) -> BTreeMap<String, Vec<ide_plugin::ConsoleRule>> {
@@ -373,6 +439,8 @@ ide_command::domain!(
plugin_set_active_file,
plugin_set_ui_locale,
plugin_status_items,
plugin_syntax_decoration_languages,
plugin_syntax_decorations,
plugin_terminal_session_close,
plugin_terminal_session_spawn,
);
+129 -28
Переглянути файл
@@ -19,7 +19,9 @@
//! description = "Create one at https://example.com/keys"
//! ```
use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id};
use ide_extension::{
Capability, Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id,
};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -56,6 +58,7 @@ pub enum ProviderKind {
GutterActions,
HoverActions,
Injections,
SyntaxDecorations,
}
#[derive(Clone, Debug, Deserialize)]
@@ -105,6 +108,22 @@ impl Providers {
self.matching::<Vec<_>>(kind, language).into_iter().map(|(plugin, _)| plugin).collect()
}
/// Languages declared for `kind`, including `"*"` when a plugin asks for every language.
pub fn languages(&self, kind: ProviderKind) -> Vec<String> {
let mut out = Vec::new();
for (_, _, kinds, languages) in self.items.read().iter() {
if !kinds.contains(&kind) {
continue;
}
for language in languages {
if !out.contains(language) {
out.push(language.clone());
}
}
}
out
}
/// One coherent declaration snapshot, preserving the first match per plugin.
fn matching<T: FromIterator<(String, u64)>>(&self, kind: ProviderKind, language: &str) -> T {
let items = self.items.read();
@@ -190,6 +209,12 @@ impl ExtensionPoint for ProvidersPoint {
if d.kinds.contains(&ProviderKind::InlayHints) {
pkg.manifest.needs_api("contributes.providers: inlay-hints", 3)?;
}
if d.kinds.contains(&ProviderKind::SyntaxDecorations) {
pkg.manifest.needs_api("contributes.providers: syntax-decorations", 20)?;
if !pkg.manifest.capabilities.all().any(|cap| *cap == Capability::EditorRead) {
return Err("contributes.providers: syntax-decorations needs the `editor.read` capability".into());
}
}
if d.kinds.iter().any(|k| {
matches!(
k,
@@ -390,6 +415,40 @@ impl PluginHost {
.collect()
}
fn edit_calls_cancellable<R: Send + 'static>(
&self,
plugins: impl IntoIterator<Item = Arc<LoadedPlugin>>,
cancel: &CancellationToken,
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
) -> Vec<(Arc<LoadedPlugin>, R)> {
std::thread::scope(|scope| {
let calls: Vec<_> = plugins
.into_iter()
.map(|plugin| {
let f = f.clone();
scope.spawn(move || {
if cancel.is_cancelled() {
return None;
}
let (actor, activated) = self.ensure_active(&plugin, None).ok()?;
if activated {
self.changed();
}
let started = Instant::now();
let hard = self.limits.edit_hard;
let result =
actor.call_edit_cancellable(cancel, CANCEL_GRACE, self.limits.edit_soft, move |rt| {
f(rt, hard)
});
let items = self.finish_provider_call(&plugin, &actor, started, result)?;
(!cancel.is_cancelled()).then_some((plugin, items))
})
})
.collect();
calls.into_iter().filter_map(|call| call.join().ok().flatten()).collect()
})
}
pub(super) fn finish_provider_call<R>(
&self,
plugin: &Arc<LoadedPlugin>,
@@ -601,33 +660,19 @@ impl PluginHost {
doc: &ProviderDocument,
cancel: &CancellationToken,
) -> Vec<(String, Vec<ide_core::Diagnostic>)> {
std::thread::scope(|scope| {
let calls: Vec<_> = self
.provider_plugins(ProviderKind::Diagnostics, &doc.language)
.into_iter()
.filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project)
.map(|p| {
scope.spawn(move || {
if cancel.is_cancelled() {
return None;
}
let (actor, activated) = self.ensure_active(&p, None).ok()?;
if activated {
self.changed();
}
let (d, timeout) = (doc.clone(), self.limits.edit_hard);
let started = Instant::now();
let result =
actor.call_edit_cancellable(cancel, CANCEL_GRACE, self.limits.edit_soft, move |rt| {
rt.provide_diagnostics(&d, timeout)
});
let items = self.finish_provider_call(&p, &actor, started, result)?;
(!cancel.is_cancelled()).then(|| (p.id().to_owned(), items))
})
})
.collect();
calls.into_iter().filter_map(|call| call.join().ok().flatten()).collect()
})
let mut plugins = self
.provider_plugins(ProviderKind::Diagnostics, &doc.language)
.into_iter()
.filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project)
.peekable();
if plugins.peek().is_none() {
return Vec::new();
}
let doc = Arc::new(doc.clone());
self.edit_calls_cancellable(plugins, cancel, move |rt, timeout| rt.provide_diagnostics(&doc, timeout))
.into_iter()
.map(|(plugin, items)| (plugin.id().to_owned(), items))
.collect()
}
pub fn provide_hover(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec<PluginHover> {
@@ -653,6 +698,62 @@ impl PluginHost {
.collect()
}
/// Theme-token marks for one open document. Plugins that do not declare the
/// language are not called. An invalid snapshot calls none of them.
pub fn provide_syntax_decorations(
&self,
doc: &ProviderDocument,
ranges: &[ide_core::Range],
nodes: &[ide_plugin::SyntaxNodeSnapshot],
cancel: &CancellationToken,
) -> Vec<ide_plugin::SyntaxDecoration> {
if ranges.is_empty() || nodes.is_empty() || cancel.is_cancelled() {
return Vec::new();
}
let plugins: Vec<_> = self
.syntax_decoration_plugins(&doc.language)
.filter(|p| p.dev_root.as_ref().is_none_or(|root| doc.path.starts_with(root)))
.collect();
if plugins.is_empty() || ide_plugin::validate_syntax_snapshot(&doc.text, ranges, nodes).is_err() {
return Vec::new();
}
let owned_ranges = Arc::<[_]>::from(ranges);
let owned_nodes = Arc::<[_]>::from(nodes);
let d = Arc::new(doc.clone());
self.edit_calls_cancellable(plugins, cancel, move |rt, timeout| {
rt.provide_syntax_decorations(&d, &owned_ranges, &owned_nodes, timeout)
})
.into_iter()
.flat_map(|(plugin, marks)| {
let id = plugin.id().to_owned();
ide_plugin::filter_syntax_marks(&doc.text, ranges, marks).into_iter().map(move |mark| {
ide_plugin::SyntaxDecoration {
plugin: id.clone(),
range: mark.range,
token: mark.token,
foreground: mark.foreground,
}
})
})
.take(ide_plugin::MAX_SYNTAX_MARKS)
.collect()
}
fn syntax_decoration_plugins(&self, language: &str) -> impl Iterator<Item = Arc<LoadedPlugin>> {
self.provider_plugins(ProviderKind::SyntaxDecorations, language)
.into_iter()
.filter(|plugin| plugin.meta.lock().granted.contains(&Capability::EditorRead))
}
/// Languages with a `syntax-decorations` provider, without loading any plugin.
pub fn syntax_decoration_languages(&self) -> Vec<String> {
self.providers
.languages(ProviderKind::SyntaxDecorations)
.into_iter()
.filter(|language| self.syntax_decoration_plugins(language).next().is_some())
.collect()
}
/// Whether a usable plugin offers ghost text for `language`.
pub fn offers_inline_completion(&self, language: &str) -> bool {
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
+357
Переглянути файл
@@ -0,0 +1,357 @@
mod common;
use ide_core::{CancellationToken, Pos, Range, RequestId};
use ide_host::plugins::{Consent, PluginHost};
use ide_host::{Host, plugins::commands::plugin_syntax_decorations};
use ide_plugin::{Limits, ProviderDocument, SyntaxNodeSnapshot};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
fn fixture_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/syntax-decorations")
}
fn host(dir: &Path) -> PluginHost {
let limits = ide_plugin::Limits {
edit_soft: Duration::from_secs(5),
edit_hard: Duration::from_secs(10),
..ide_plugin::Limits::default()
};
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
}
fn doc(dir: &Path, language: &str, version: u64) -> ProviderDocument {
ProviderDocument { path: dir.join("a.js"), language: language.into(), version, text: "const value = 1;\n".into() }
}
fn node(name: &str, parent: Option<u32>) -> SyntaxNodeSnapshot {
SyntaxNodeSnapshot { name: name.into(), range: Range::new(Pos::new(0, 6), Pos::new(0, 11)), parent }
}
fn pair() -> Vec<SyntaxNodeSnapshot> {
vec![node("Script", None), node("VariableName", Some(0))]
}
fn asked() -> Range {
Range::new(Pos::new(0, 0), Pos::new(0, 16))
}
#[test]
fn a_parented_node_is_marked_with_the_theme_token() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
let marks = host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 4),
&[asked()],
&pair(),
&CancellationToken::new(),
);
assert_eq!(marks.len(), 1);
assert_eq!(marks[0].plugin, "test.syntax-decorations");
assert_eq!(marks[0].token, "rainbow-1");
assert_eq!(marks[0].range, Range::new(Pos::new(0, 6), Pos::new(0, 11)));
}
#[test]
fn colour_marks_are_normalised_and_invalid_ones_dropped() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
let marks = host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 7),
&[asked()],
&pair(),
&CancellationToken::new(),
);
assert_eq!(marks.len(), 1, "{marks:?}");
assert_eq!(
marks[0].foreground,
Some(ide_plugin::SyntaxForeground { dark: "#80cbc4".into(), light: "#23766f".into() })
);
}
#[test]
fn a_zero_version_and_another_language_produce_nothing() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
assert!(
host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 0),
&[asked()],
&pair(),
&CancellationToken::new()
)
.is_empty()
);
assert!(
host.provide_syntax_decorations(&doc(tmp.path(), "yaml", 4), &[asked()], &pair(), &CancellationToken::new())
.is_empty()
);
}
#[test]
fn an_invalid_snapshot_does_not_call_the_plugin() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
let marks = host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 4),
&[asked()],
&[node("A", Some(9))],
&CancellationToken::new(),
);
assert!(marks.is_empty());
}
#[test]
fn declining_editor_read_disables_the_provider() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
let pkg = tmp.path().join("optional");
std::fs::create_dir_all(pkg.join("dist")).unwrap();
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
std::fs::write(pkg.join("plugin.toml"), manifest.replace("required =", "optional =")).unwrap();
host.install_from_dir(&pkg, &Consent::default()).unwrap();
assert!(host.syntax_decoration_languages().is_empty());
assert!(
host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 4),
&[asked()],
&pair(),
&CancellationToken::new(),
)
.is_empty()
);
}
#[test]
fn uninstalling_the_plugin_drops_its_marks() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
assert_eq!(
host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 4),
&[asked()],
&pair(),
&CancellationToken::new()
)
.len(),
1
);
host.uninstall("test.syntax-decorations").unwrap();
assert!(
host.provide_syntax_decorations(
&doc(tmp.path(), "javascript", 4),
&[asked()],
&pair(),
&CancellationToken::new()
)
.is_empty()
);
}
#[test]
fn the_kind_needs_plugin_api_1_20() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
let pkg = tmp.path().join("old");
std::fs::create_dir_all(pkg.join("dist")).unwrap();
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.20\"", "\"^1.0\"")).unwrap();
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.20"), "{}", err.message);
}
fn misbehave_wasm() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm")
}
/// The shared misbehave component, declared here as a syntax-decoration provider.
/// Its own manifest stays on `^1.0` and does not advertise this kind.
fn misbehave_provider(dir: &Path) -> PathBuf {
let pkg = dir.join("misbehave-syntax");
std::fs::create_dir_all(pkg.join("dist")).unwrap();
std::fs::copy(misbehave_wasm(), pkg.join("dist/plugin.wasm")).unwrap();
std::fs::write(
pkg.join("plugin.toml"),
"\
id = \"misbehave\"
name = \"Misbehave\"
version = \"0.0.2\"
engines.openidea = \"^1.20\"
wasm = \"dist/plugin.wasm\"
[capabilities]
required = [\"editor.read\"]
[[contributes.providers]]
kinds = [\"syntax-decorations\"]
languages = [\"javascript\"]
",
)
.unwrap();
pkg
}
fn tight(dir: &Path) -> PluginHost {
let limits = Limits {
edit_soft: Duration::from_millis(50),
edit_hard: Duration::from_millis(400),
fuel: u64::MAX,
restart_backoff: Duration::ZERO,
..Limits::default()
};
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
}
/// The first name is how misbehave fails. The second node is what the fixture marks.
fn signal(name: &str) -> Vec<SyntaxNodeSnapshot> {
vec![
SyntaxNodeSnapshot { name: name.into(), range: Range::new(Pos::new(0, 0), Pos::new(0, 5)), parent: None },
node("VariableName", Some(0)),
]
}
fn install_pair(host: &PluginHost, dir: &Path) {
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
host.install_from_dir(&misbehave_provider(dir), &Consent::all()).unwrap();
}
fn ready(host: &PluginHost, dir: &Path) {
let document = doc(dir, "javascript", 4);
let mut ok = false;
for _ in 0..30 {
let marks = host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new());
let fixture = marks.iter().any(|m| m.plugin == "test.syntax-decorations");
let mis = host.info_of("misbehave").is_ok_and(|info| info.stats.activations >= 1);
if fixture && mis {
ok = true;
break;
}
std::thread::sleep(Duration::from_millis(40));
}
assert!(ok, "plugins did not finish activating");
}
fn keeps_the_other(marks: &[ide_plugin::SyntaxDecoration]) {
assert!(marks.iter().any(|m| m.plugin == "test.syntax-decorations" && m.token == "rainbow-1"), "{marks:?}");
assert!(marks.iter().all(|m| m.plugin != "misbehave"), "{marks:?}");
}
#[test]
fn a_trapped_plugin_drops_its_marks_and_leaves_the_other() {
let tmp = tempfile::tempdir().unwrap();
let host = tight(tmp.path());
install_pair(&host, tmp.path());
ready(&host, tmp.path());
let document = doc(tmp.path(), "javascript", 4);
keeps_the_other(&host.provide_syntax_decorations(
&document,
&[asked()],
&signal("panic"),
&CancellationToken::new(),
));
assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1);
}
#[test]
fn a_slow_plugin_is_dropped_and_the_other_answers() {
let tmp = tempfile::tempdir().unwrap();
let host = tight(tmp.path());
install_pair(&host, tmp.path());
ready(&host, tmp.path());
let document = doc(tmp.path(), "javascript", 4);
keeps_the_other(&host.provide_syntax_decorations(
&document,
&[asked()],
&signal("sleep:150"),
&CancellationToken::new(),
));
let info = host.info_of("misbehave").unwrap();
assert!(info.stats.slow_calls >= 1, "{:?}", info.stats);
assert_eq!(info.stats.crashes, 0, "{:?}", info.stats);
assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1);
}
#[test]
fn uninstalling_a_spinning_plugin_keeps_the_other_answering() {
let tmp = tempfile::tempdir().unwrap();
let host = Arc::new(tight(tmp.path()));
install_pair(&host, tmp.path());
ready(&host, tmp.path());
let document = doc(tmp.path(), "javascript", 4);
let running = {
let host = host.clone();
let document = document.clone();
std::thread::spawn(move || {
host.provide_syntax_decorations(&document, &[asked()], &signal("spin"), &CancellationToken::new())
})
};
std::thread::sleep(Duration::from_millis(20));
host.uninstall("misbehave").unwrap();
keeps_the_other(&running.join().unwrap());
assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1);
}
fn bump(project: &ide_host::Project, doc: ide_core::DocId) -> u32 {
project
.documents
.apply_edits(
doc,
&[ide_core::TextEdit { range: Range::new(Pos::new(0, 16), Pos::new(0, 16)), new_text: " ".into() }],
)
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_code_insight_limit_gates_the_provider_without_a_fixed_character_ceiling() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let file = root.join("a.js");
std::fs::write(&file, "const value = 1;\n").unwrap();
let plugins =
Arc::new(PluginHost::new(root.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap());
plugins.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
let open_host = Host::new(common::host_config(&root.join("open")));
open_host.set_project_trust(&root, true, false).await.unwrap();
let open = open_host.open_project("main", &root).unwrap();
let small = open.documents.open(&file).unwrap();
assert!(!small.large);
assert!(bump(&open, small.id) >= 1);
let allowed =
plugin_syntax_decorations(&open_host, &plugins, "main", RequestId(1), small.id, vec![asked()], pair(), 2)
.await
.unwrap();
assert_eq!(allowed.marks.len(), 1, "{allowed:?}");
assert_eq!(allowed.marks[0].token, "rainbow-1");
let cancelled = RequestId(2);
open_host.cancel_request(cancelled);
let error = plugin_syntax_decorations(&open_host, &plugins, "main", cancelled, small.id, vec![asked()], pair(), 3)
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
let limited_host = Host::new(common::host_config(&root.join("limited")));
limited_host.set_project_trust(&root, true, false).await.unwrap();
let limited = limited_host.open_project("main", &root).unwrap();
let defaults = ide_workspace::FileDefaults { max_code_insight_bytes: 1, ..Default::default() };
limited.documents.set_file_defaults(defaults);
let large = limited.documents.open(&file).unwrap();
assert!(large.large, "a one-byte insight limit marks the file without allocating a huge buffer");
assert!(bump(&limited, large.id) >= 1, "the gate is only visible once the fixture would have answered");
let blocked =
plugin_syntax_decorations(&limited_host, &plugins, "main", RequestId(1), large.id, vec![asked()], pair(), 1)
.await
.unwrap();
assert!(blocked.marks.is_empty(), "{blocked:?}");
assert!(!blocked.stale);
assert!(blocked.version >= 1, "{blocked:?}");
}
+6
Переглянути файл
@@ -31,6 +31,12 @@ pub use wasmtime::component::Component;
mod execution;
pub use execution::*;
mod syntax_decorations;
pub use syntax_decorations::{
MAX_SYNTAX_MARKS, MAX_SYNTAX_NAME, MAX_SYNTAX_NODES, MAX_SYNTAX_RANGES, SYNTAX_TOKENS, SyntaxSnapshotError,
filter_syntax_marks, syntax_foreground, syntax_token_allowed, validate_syntax_snapshot,
};
pub use ide_core::remote_settings::PluginRunTarget;
pub mod language_features;
+49 -1
Переглянути файл
@@ -26,7 +26,8 @@ use crate::wit_host::run_target_validation_bindings::exports::openidea::plugin::
use crate::wit_host::search_bindings::exports::openidea::plugin::search_provider as wit_search;
use crate::wit_host::{
bindings, commit_checks_bindings, details_bindings, endpoints_bindings, file_actions_bindings, hover_bindings,
indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings, views_bindings,
indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings,
syntax_decoration_bindings, views_bindings,
};
use ide_core::CancellationToken;
use ide_core::ipc_path::to_ipc;
@@ -60,6 +61,7 @@ use inlay_bindings::exports::openidea::plugin::inlay_hints_provider as wit_inlay
use providers_bindings::exports::openidea::plugin::providers as wit_prov;
use semantic_bindings::exports::openidea::plugin::semantic_tokens_provider as wit_sem;
use syntax_bindings::exports::openidea::plugin::syntax_provider as wit_syntax;
use syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider as wit_syn;
use views_bindings::exports::openidea::plugin::view_provider as wit_view;
use views_bindings::openidea::plugin::view_types as wit_vt;
@@ -973,6 +975,7 @@ struct Exports {
hover: Option<wit_hover::Guest>,
commit_checks: Option<wit_cc::Guest>,
inlay: Option<wit_inlay::Guest>,
syntax_decorations: Option<wit_syn::Guest>,
endpoints: Option<wit_endpoints::Guest>,
search: Option<wit_search::Guest>,
hover_actions: Option<wit_hia::Guest>,
@@ -1135,6 +1138,7 @@ impl Runtime {
let hover_indices = wit_hover::GuestIndices::new(&pre).ok();
let commit_check_indices = wit_cc::GuestIndices::new(&pre).ok();
let inlay_indices = wit_inlay::GuestIndices::new(&pre).ok();
let syntax_decoration_indices = wit_syn::GuestIndices::new(&pre).ok();
let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok();
let search_indices = wit_search::GuestIndices::new(&pre).ok();
let hover_actions_indices = wit_hia::GuestIndices::new(&pre).ok();
@@ -1211,6 +1215,10 @@ impl Runtime {
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
None => None,
};
let syntax_decorations = match syntax_decoration_indices {
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
None => None,
};
let search = search_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let hover_actions =
hover_actions_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
@@ -1239,6 +1247,7 @@ impl Runtime {
hover,
commit_checks,
inlay,
syntax_decorations,
endpoints,
search,
hover_actions,
@@ -1882,6 +1891,45 @@ impl Runtime {
.collect())
}
pub fn provide_syntax_decorations(
&mut self,
doc: &ProviderDocument,
ranges: &[ide_core::Range],
nodes: &[crate::SyntaxNodeSnapshot],
timeout: Duration,
) -> Result<Vec<crate::PluginSyntaxMark>, CallError> {
if self.exports.syntax_decorations.is_none() {
return Err(CallError::missing_export("syntax-decorations-provider"));
}
let request = wit_syn::DecorationRequest {
document: wit_syn::Document {
path: to_ipc(&doc.path),
language: doc.language.clone(),
version: doc.version,
},
ranges: ranges.iter().copied().map(range_to_wit).collect(),
nodes: nodes
.iter()
.map(|n| wit_syn::SyntaxNode { name: n.name.clone(), range: range_to_wit(n.range), parent: n.parent })
.collect(),
};
let marks = self.call(Invocation::default(), timeout, |e, store| {
e.syntax_decorations.as_ref().expect("checked").call_syntax_decorations(store, &request)
})?;
Ok(marks
.into_iter()
.filter_map(|m| {
let foreground = match &m.foreground {
Some(f) => Some(crate::syntax_foreground(&f.dark, &f.light)?),
None if crate::syntax_token_allowed(&m.token) => None,
None => return None,
};
Some(crate::PluginSyntaxMark { range: range_from_wit(m.range), token: m.token, foreground })
})
.take(MAX_PROVIDER_ITEMS)
.collect())
}
pub fn activate(&mut self) -> Result<(), CallError> {
let data = self.store.data();
let ctx = wit_types::Context {
+228
Переглянути файл
@@ -0,0 +1,228 @@
//! Bounds for the syntax-decoration provider. The editor builds the snapshot
//! from the syntax tree it already has; this module only checks that the
//! snapshot and the marks stay inside the document.
use crate::{PluginSyntaxMark, SyntaxForeground, SyntaxNodeSnapshot};
use ide_core::{Pos, Range};
/// Nodes included in one request, including ancestors of the requested ranges.
pub const MAX_SYNTAX_NODES: usize = 8_192;
/// Visible ranges plus sticky header lines.
pub const MAX_SYNTAX_RANGES: usize = 32;
pub const MAX_SYNTAX_NAME: usize = 128;
/// Same cap as the other editor providers.
pub const MAX_SYNTAX_MARKS: usize = 10_000;
/// Theme tokens the host maps onto `--syn-rainbow-1` … `--syn-rainbow-5`.
pub const SYNTAX_TOKENS: [&str; 5] = ["rainbow-1", "rainbow-2", "rainbow-3", "rainbow-4", "rainbow-5"];
/// A mark colour as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case.
fn mark_color(color: &str) -> Option<String> {
let hex = color.strip_prefix('#')?;
((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| format!("#{}", hex.to_ascii_lowercase()))
}
/// The foreground a plugin gave, normalised; `None` when either colour is invalid.
pub fn syntax_foreground(dark: &str, light: &str) -> Option<SyntaxForeground> {
Some(SyntaxForeground { dark: mark_color(dark)?, light: mark_color(light)? })
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SyntaxSnapshotError {
TooManyRanges,
TooManyNodes,
BadName,
BadParent,
BadRange,
}
struct Lines {
lens: Vec<u32>,
}
impl Lines {
fn new(text: &str) -> Self {
let mut lens = Vec::new();
for line in text.split('\n') {
let line = line.strip_suffix('\r').unwrap_or(line);
lens.push(u32::try_from(line.encode_utf16().count()).unwrap_or(u32::MAX));
}
if lens.is_empty() {
lens.push(0);
}
Self { lens }
}
fn contains(&self, range: Range) -> bool {
let ok = |p: Pos| (p.line as usize) < self.lens.len() && p.col <= self.lens[p.line as usize];
ok(range.start) && ok(range.end) && range.start <= range.end
}
}
fn overlaps(a: Range, b: Range) -> bool {
a.start < b.end && b.start < a.end
}
fn parents_ok(nodes: &[SyntaxNodeSnapshot]) -> bool {
let mut visiting = vec![false; nodes.len()];
let mut checked = vec![false; nodes.len()];
let mut path = Vec::new();
for i in 0..nodes.len() {
let mut next = Some(i);
while let Some(index) = next {
if index >= nodes.len() || visiting[index] {
return false;
}
if checked[index] {
break;
}
visiting[index] = true;
path.push(index);
next = nodes[index].parent.map(|parent| parent as usize);
}
for index in path.drain(..) {
visiting[index] = false;
checked[index] = true;
}
}
true
}
/// Reject a snapshot the editor should not have sent. An empty range list is
/// valid and means there is nothing to ask.
pub fn validate_syntax_snapshot(
text: &str,
ranges: &[Range],
nodes: &[SyntaxNodeSnapshot],
) -> Result<(), SyntaxSnapshotError> {
if ranges.len() > MAX_SYNTAX_RANGES {
return Err(SyntaxSnapshotError::TooManyRanges);
}
if nodes.len() > MAX_SYNTAX_NODES {
return Err(SyntaxSnapshotError::TooManyNodes);
}
let lines = Lines::new(text);
if ranges.iter().any(|r| !lines.contains(*r)) || nodes.iter().any(|n| !lines.contains(n.range)) {
return Err(SyntaxSnapshotError::BadRange);
}
if nodes.iter().any(|n| n.name.is_empty() || n.name.len() > MAX_SYNTAX_NAME) {
return Err(SyntaxSnapshotError::BadName);
}
if !parents_ok(nodes) {
return Err(SyntaxSnapshotError::BadParent);
}
Ok(())
}
pub fn syntax_token_allowed(token: &str) -> bool {
SYNTAX_TOKENS.contains(&token)
}
/// Keep marks the plugin may paint: checked colours or an allowlisted token, a range inside the
/// document, and an overlap with a range the host asked about.
pub fn filter_syntax_marks(text: &str, ranges: &[Range], marks: Vec<PluginSyntaxMark>) -> Vec<PluginSyntaxMark> {
let lines = Lines::new(text);
marks
.into_iter()
.filter(|m| {
(m.foreground.is_some() || syntax_token_allowed(&m.token))
&& m.range.start < m.range.end
&& lines.contains(m.range)
&& ranges.iter().any(|r| overlaps(m.range, *r))
})
.take(MAX_SYNTAX_MARKS)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn range(line: u32, col: u32, end_col: u32) -> Range {
Range::new(Pos::new(line, col), Pos::new(line, end_col))
}
fn node(name: &str, parent: Option<u32>) -> SyntaxNodeSnapshot {
SyntaxNodeSnapshot { name: name.into(), range: range(0, 0, 1), parent }
}
#[test]
fn a_parent_outside_the_range_is_accepted() {
let nodes = vec![node("Document", None), node("Key", Some(0))];
assert_eq!(validate_syntax_snapshot("ab\n", &[range(0, 0, 1)], &nodes), Ok(()));
}
#[test]
fn utf16_columns_follow_the_line() {
let text = "a😀b\n";
let ok = range(0, 0, 4);
let past = range(0, 0, 5);
assert!(validate_syntax_snapshot(text, &[ok], &[]).is_ok());
assert_eq!(validate_syntax_snapshot(text, &[past], &[]), Err(SyntaxSnapshotError::BadRange));
}
#[test]
fn an_empty_document_has_one_empty_line() {
assert!(validate_syntax_snapshot("", &[range(0, 0, 0)], &[]).is_ok());
assert_eq!(validate_syntax_snapshot("", &[range(1, 0, 0)], &[]), Err(SyntaxSnapshotError::BadRange));
}
#[test]
fn a_bad_parent_rejects_the_snapshot() {
let nodes = vec![node("A", Some(1)), node("B", Some(0))];
assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &nodes), Err(SyntaxSnapshotError::BadParent));
let itself = vec![node("A", Some(0))];
assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &itself), Err(SyntaxSnapshotError::BadParent));
let missing = vec![node("A", Some(3))];
assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &missing), Err(SyntaxSnapshotError::BadParent));
}
#[test]
fn the_node_cap_is_enforced() {
let nodes = vec![node("A", None); MAX_SYNTAX_NODES + 1];
assert_eq!(validate_syntax_snapshot("a", &[range(0, 0, 1)], &nodes), Err(SyntaxSnapshotError::TooManyNodes));
}
#[test]
fn marks_outside_the_request_or_the_token_list_are_dropped() {
let asked = range(0, 0, 2);
let marks = vec![
PluginSyntaxMark { range: asked, token: "rainbow-2".into(), foreground: None },
PluginSyntaxMark { range: asked, token: "red".into(), foreground: None },
PluginSyntaxMark { range: range(0, 4, 5), token: "rainbow-1".into(), foreground: None },
PluginSyntaxMark {
range: Range::new(Pos::new(0, 8), Pos::new(0, 1)),
token: "rainbow-1".into(),
foreground: None,
},
PluginSyntaxMark {
range: Range::new(Pos::new(9, 0), Pos::new(9, 1)),
token: "rainbow-1".into(),
foreground: None,
},
];
let kept = filter_syntax_marks("hello", &[asked], marks);
assert_eq!(kept, vec![PluginSyntaxMark { range: asked, token: "rainbow-2".into(), foreground: None }]);
}
#[test]
fn foreground_colours_are_normalised_and_css_is_rejected() {
assert_eq!(
syntax_foreground("#80CBC4", "#23766fcc"),
Some(SyntaxForeground { dark: "#80cbc4".into(), light: "#23766fcc".into() })
);
for bad in ["80CBC4", "#80CBC", "#80CBC4;color:red", "url(x)", "var(--syn-rainbow-1)", "red", ""] {
assert_eq!(syntax_foreground(bad, "#23766f"), None, "{bad}");
assert_eq!(syntax_foreground("#23766f", bad), None, "{bad}");
}
let asked = range(0, 0, 2);
let colored = syntax_foreground("#80cbc4", "#23766f");
let marks = vec![
PluginSyntaxMark { range: asked, token: String::new(), foreground: colored.clone() },
PluginSyntaxMark { range: asked, token: String::new(), foreground: None },
];
let kept = filter_syntax_marks("hello", &[asked], marks);
assert_eq!(kept, vec![PluginSyntaxMark { range: asked, token: String::new(), foreground: colored }]);
}
}
+48
Переглянути файл
@@ -817,6 +817,54 @@ pub struct PluginInlayHint {
pub padding_right: bool,
}
/// One node of an editor syntax snapshot (`syntax-decorations-provider`).
/// `parent` indexes this same list.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxNodeSnapshot {
pub name: String,
pub range: ide_core::Range,
pub parent: Option<u32>,
}
/// A theme-token mark returned by one plugin. `plugin` is assigned by the host.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxDecoration {
pub plugin: String,
pub range: ide_core::Range,
pub token: String,
/// Checked colours, `#rrggbb` / `#rrggbbaa` in lower case; painted instead of `token`.
pub foreground: Option<SyntaxForeground>,
}
/// A mark's own foreground for dark and for light themes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxForeground {
pub dark: String,
pub light: String,
}
/// A mark before the host has attached the plugin that produced it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginSyntaxMark {
pub range: ide_core::Range,
pub token: String,
pub foreground: Option<SyntaxForeground>,
}
/// Answer of `plugin_syntax_decorations`. `stale` means the document changed
/// while the plugins were running; `marks` is then empty.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxDecorationBatch {
pub version: u64,
pub epoch: u64,
pub stale: bool,
pub marks: Vec<SyntaxDecoration>,
}
// ---- declarative views (wit/views.wit) ---------------------------------------
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+7
Переглянути файл
@@ -2682,6 +2682,13 @@ pub(crate) mod inlay_bindings {
});
}
pub(crate) mod syntax_decoration_bindings {
wasmtime::component::bindgen!({
world: "syntax-decorations", path: "../../wit",
with: { "openidea:plugin/types": super::bindings::openidea::plugin::types },
});
}
pub(crate) mod endpoints_bindings {
wasmtime::component::bindgen!({
world: "endpoints", path: "../../wit",
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
daf3ed46b1e98c6b416c0092a10a02579d2cf97959cedd03df1851a5e76d675d
fbb81178d7ee654ba2ba009253643bb3e13865c6f41b946ad39508145c481df0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b54f16ce7e7caf877ea464b50014117fc10f30b761236e5ddcb19ad07254ea13
3a246151d713185ea416f72e1c4dacb6d46b0c68a48b878f131c517051e5823d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
56e088be4df2db66a03060d388890ff9b68c354e36851ad46665b26bd27ea817
c71fba2e8fc92e0c30b88b79e91a62e829d0e4651a4cee43fb91af6388f27688
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
eefdb2d5e0b1fcf96d3ba03e5494513577f43f877d675873d4b922ee71bd3cc5
c38fe66dd5601e29539cc002ea15ec9a33f70d0df129b6d3d2cb0da95358d632
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
00c70c0584a32dacdaee29379b805815d17e6d9cb209e1c21d72fbfc18020498
c3fb87d8e3782fbe37dbdae67fefbaca9e11e97b9b34d92cc575e8f6dfcbe566
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e08f776a59706399eca922a324f21835208740a16c2e87911f0c338dd8e25cb2
40f458ad646b1ecb4f68dcd190fcb6b979a07bbffcb63a136ba66eaa8bb90522
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
43bc34ad3aafd1d2869cf8f745dbaa0e8fce05ae6e39bf91ab39660cbcfc4740
f72b332f4288f992ba0ad4d7732f2c52e9eb168222cd0b405afcc593946890d1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b4d92a22c5ebadc47284a22be1de2beec6deeffcc2f60c55173b924322588844
74c63125ea431acea5f43e49c490c8810af342f476cffbe29f5fe567db4dbc30
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
452aed5f05ac3cc3d299afd74427fd58c5934dec6ca5a239e2a1e347ba036044
e09c6b3e642f2bae0c86551a89c89a73f41d366d47f4b29768e21eaa879d9260
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2abcea42de506e9e28a0970ba2a8615c7cc88d769cb5fa47fe3bb57e03af5258
a77a9acf6b4003c24d2ef55f63d33f488eb7ae1205fb143b3fc57d723cec55bc
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
60e1a1925b3d83ea34be69727b9e8804ba3a1db767b7a06f87bcad6ab326a604
82fdbc642d28863ca61f602b7df5c25b5553e70c9d90280d96b5ee71e9447400
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
92d626a131d5b8b82781a3cb7d87a293ddb0e5e81450bef17dc505c12f2a4f57
eb250aaf92ff5f7efca010dfc9a2d3aee62b698390330bbbc75a2f10b9328989
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
86ec4a4ebc1d770b0e6973d9169544111fce24485f3eed8b7040d7dce8280dcd
24ffd29881199bb7eede7084a4a11d14e70ee78e53261e2bd33d173112c98fd3
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
254dddbf9c67f00451fc173602532e2e4fe92a6fd8d3d91824c950a403c7583c
740183f685319af40013c81a26da70df23e9a9fbe9293c24605c55b1cf6a9f55
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
49e66ff2b91e070477c272ac1c5c60367148b274d75bb7d92efca0b1d5092f6a
ba325d0dab1366018feef26a7bd5a8f2002f946972e725c1df10f2ffb7a0ab8e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cfb61fe65b344d86bf71a821c1216963d9ab7789206a292450b1d66222d6cbc5
3b1f0a3a43f0e0a6f17dd0d648ce69cf0619f052a981958656b1065c4923b4ec
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
706e69379855967f598abbcc3bcc955cb5581ca4b009d5220f4785ccb05dda0f
d9e930f460de8bb20f5b228e5e15191b0a27c1247d564e5595b976f5453050ea
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
118c6f4870e99d57acfc9fbb265031a3a7d1dfc03b4408be8c8b5eade33e4f38
fd510b30360542de87a80052f373ad9b98faa68bc8c267bf1845d44d21e0fde7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
19b04c02c5230c0700bdc8fe8a3cae266422aa23e8d7e932b7dafd546e41846d
c646af70d26715a3c231c80e16d93e40b8a2570516322c364924854be08af1d7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
14e46bbf68efaacaff75627814be666dcf00460656ba7e66b7fb088317ce6c79
1f64dbc8b9f1d623080eda6b19fccc161f35c9801e5c1689abb2a8e993f4856e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
55afdbdb4db919c59a38b14eb6483c911934d64d433ef19106098bfde4830a91
71826d403bdaf5fee4390c0eb7a9fed7ee6804742b4c23ea8607e4897d6f5cce
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
99099a7f01295188bade661777d926fd12ba434ec4ff36035ee1b13523d63ae8
418b35d6a7e98fe80d9594af073b409cf400ab8b65a7d2f42b524edceb284de4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ff6ecc3baa94d7cd4447f3d9f2a3f819ee44dac3564fdfba3a5f88a0637c0af0
185a50ea6cd0564cb73ee66cd700b0dc052a1eab0c4418bfc515de83c7f88c55
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
45990bb70318e04cb69c8ffa5c980b85e65bd860559b10507061762f8ecb38b3
9024a4e059a4a5b5fa0c92bd235671914db911971f66d1189c34845c08c905e0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cb21ced740ff159017a96075e41b31782c062db10596e4286327fb4d002b6ebf
20f7450b91e444e74354bf87c1e7fdddaccdd500e6a2c315d622bcff45086066
+26
Переглянути файл
@@ -8,6 +8,7 @@ wit_bindgen::generate!({
include openidea:plugin/plugin-syntax@1.20.0;
export openidea:plugin/providers@1.20.0;
export openidea:plugin/file-actions@1.20.0;
export openidea:plugin/syntax-decorations-provider@1.20.0;
}
",
path: "../../../../../wit",
@@ -512,4 +513,29 @@ impl exports::openidea::plugin::file_actions::Guest for Misbehave {
}
}
/// The first node's name selects the failure: `panic`, `spin`, or `sleep:<ms>`.
/// A normal name returns no marks, so a well behaved plugin beside this one
/// still supplies its own.
impl exports::openidea::plugin::syntax_decorations_provider::Guest for Misbehave {
fn syntax_decorations(
request: exports::openidea::plugin::syntax_decorations_provider::DecorationRequest,
) -> Vec<exports::openidea::plugin::syntax_decorations_provider::SyntaxMark> {
if let Some(name) = request.nodes.first().map(|node| node.name.as_str()) {
if name == "panic" {
panic!("boom");
} else if name == "spin" {
loop {
std::hint::black_box(0);
}
} else if let Some(ms) = name.strip_prefix("sleep:").and_then(|n| n.parse::<u64>().ok()) {
let until = std::time::Instant::now() + std::time::Duration::from_millis(ms);
while std::time::Instant::now() < until {
std::hint::black_box(0);
}
}
}
Vec::new()
}
}
export!(Misbehave);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9bdc92f81b7985bec88bd2b3929771df22f1d31945e575a3a71ca705aad4d1dc
800d5114110774f24ddd30cf4b4b14a802dc9f41cdc5e8834a4a429adc186ed3
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3cbfd56bef0062d1fb25854efe256c34c7de23ddf1ae4611e05119410a487f4b
aab5a3b60e1f0dfc3474994f8d61b571b1a15b5070ee753d75234fac300843bc
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
87c9742d4700629243bbfd544d227c64bbb478a0607bd21b1a16072eb50b6b8e
3e6345dee4360f925168f1a9dca30e9464054937252aa075368d5b3fed237c62
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8bdf895f76e7615b03cd8d2e50ee8272e9598a6f21426a4ec86e124fbaf86741
97d5c95eff3e2d5837f7ff07f7f4c82dfbbdec3522b8294d0a865e70ae020d14
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
63cc4ad099d6c383b78e46dddc5b578c899cfc42e4b9dc5726704f1d6c8da83a
fd34c1b1d1a131122822a102d9168b1c700b5f26c1a336a2bda0ae07b1d83314
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
213bdb00682f6e573f54ad07698e5090f9bc1ccd3ebfc9cf7f703b2fdce9f30a
20d01f5aa6f3519f40138a674500d5485a87bd2ba83e91b584e7e7592801fe86
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1facc9f2d4e26f87e8a80719b560b61d7e6a3c953753cfe20bc2eba9b31934d1
da1cabc8d502e54bc4dbcaa92a8b8d570d696b842dba174f3e0011db896d9083
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7fbe4b0ac9d49efd8300867d9b447bced49a7f3d9ab7bcebd74b11c7c8ff546f
911a05d11ca6e419fd7adee7a21fa76cb669a2d32242c281f59eb6366a55810d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2c4cc949885b3d1d0f4a9dbc44c239d55ed4e43f71c8b09a8da3e9f31a439841
039e8c3424f0417b1cd8cd46b2d2e2938971304983b61e9bc5e8ce4955ab96cd
+336
Переглянути файл
@@ -0,0 +1,336 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "macro-string"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "openidea-plugin"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"wit-bindgen",
]
[[package]]
name = "openidea-test-syntax-decorations"
version = "0.1.0"
dependencies = [
"openidea-plugin",
]
[[package]]
name = "prettyplease"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "wasm-encoder"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
dependencies = [
"bitflags",
"hashbrown",
"indexmap",
"semver",
]
[[package]]
name = "wit-bindgen"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
dependencies = [
"bitflags",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
dependencies = [
"anyhow",
"macro-string",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
dependencies = [
"anyhow",
"hashbrown",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-ident",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+20
Переглянути файл
@@ -0,0 +1,20 @@
[package]
name = "openidea-test-syntax-decorations"
version = "0.1.0"
edition = "2024"
publish = false
[workspace]
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
[profile.release]
opt-level = "s"
lto = true
strip = true
codegen-units = 1
panic = "abort"
+5
Переглянути файл
@@ -0,0 +1,5 @@
# Syntax decorations fixture
Proves the `syntax-decorations` provider. It is not a highlighter: the first
syntax node that has a parent is marked `rainbow-1`, and a document version of
0 returns nothing.
Бінарний файл не відображається.
+1
Переглянути файл
@@ -0,0 +1 @@
7bc77abc900cd575e24e2fda4a27aac752b82df45811671aeaef3736dafa2808
+12
Переглянути файл
@@ -0,0 +1,12 @@
id = "test.syntax-decorations"
name = "Syntax decorations fixture"
version = "0.1.0"
engines.openidea = "^1.20"
wasm = "dist/plugin.wasm"
[capabilities]
required = ["editor.read"]
[[contributes.providers]]
kinds = ["syntax-decorations"]
languages = ["javascript"]
+36
Переглянути файл
@@ -0,0 +1,36 @@
use openidea_plugin::syntax_decorations::{SyntaxDecorationRequest, SyntaxDecorations, SyntaxMark};
use openidea_plugin::{Error, Invocation, Plugin, register_plugin};
#[derive(Default)]
struct Fixture;
impl Plugin for Fixture {
fn run_command(&mut self, id: &str, _: &Invocation, _: Option<&str>) -> Result<Option<String>, Error> {
Err(Error::NotFound(id.into()))
}
}
impl SyntaxDecorations for Fixture {
fn syntax_decorations(&mut self, request: &SyntaxDecorationRequest) -> Vec<SyntaxMark> {
if request.document.version == 0 {
return Vec::new();
}
// Version 7 asks for colour marks: one valid, one the host must drop.
if request.document.version == 7 {
let Some(node) = request.nodes.iter().find(|node| node.parent.is_some()) else { return Vec::new() };
return vec![
SyntaxMark::colored(node.range, "#80CBC4", "#23766f"),
SyntaxMark::colored(node.range, "#80CBC4;color:red", "#23766f"),
];
}
request
.nodes
.iter()
.find(|node| node.parent.is_some())
.map(|node| SyntaxMark::new(node.range, "rainbow-1"))
.into_iter()
.collect()
}
}
register_plugin!(Fixture, syntax_decorations);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
23c9187f4deb89351de32a52e8f08b4933d2bbe72fcf3c9a7c9b29ae20bbdb44
d1f97800b9aad4b6c27d2a2e1e47dfa1ca70741b9a4163940d36547a2a2d5af1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e7159f2069bbfbdb68b8770040772949013b733e16513d57333664d6a945a326
671ed8fe2f6a922fd92ee3ca2a6c2e47ffcf0985fb9e4f96c5ec7712d3c728e6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
29f64f3236c46cd1b0e7915736fdb41f3826161c4d950aac7ed7b6b0767786be
5cd36ce9a7e01aafadd4b14fab1367664a7a5ffa0f7332d8b3b22770bb381422
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
072c75538a1e36064fafd69f66e7d40024b4f5909f3d6acf8191071dbe195c92
da9ee39b1b46ab778b0bf6b5d3719d5d0ef5500778be75ff54ca276b31310ac2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ecc4f6f73209bd2d4d10353ed73a3a8629381cf6c8901673ae8ce19541136b96
f81c21c6cfe046bf2149f53bee39aeb45b320593996e163f4e5ea3acfebdfa78
+1 -1
Переглянути файл
@@ -34,7 +34,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette |
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself |
| 1.19.0 | In development on `main` | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view |
| 1.20.0 | In development | Database table context menus and read-only table schema inspection (`database.schema`). |
| 1.20.0 | In development | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. |
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
+1 -1
Переглянути файл
@@ -31,7 +31,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.20 的各个版本,
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 |
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 |
| 1.19.0 | `main` 上开发中 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 |
| 1.20.0 | `main` 上开发中 | Database table context menus and read-only table schema inspection (`database.schema`). |
| 1.20.0 | `main` 上开发中 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 |
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
+120 -2
Переглянути файл
@@ -33,10 +33,10 @@ plugins/
├─ regex-tester/ # html view talking to its code, settings, the editor's selection
└─ license-header/ # file-opened events, quick fix, project scan in a task
sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host)
crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints, decorations
crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints, decorations, syntax-decorations
```
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.19.0`, world
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.20.0`, world
`plugin`).
## 1. Quick start
@@ -1313,6 +1313,13 @@ cancellable, bounded by the I/O timeout and limited to 4096 entries per collecti
See the [database guide](../docs/en/plugins/guides/database.mdx) for a complete manifest
and Rust example; generating files additionally requires `project.write`.
### Syntax decorations (API 1.20)
With `engines.openidea = "^1.20"`, a plugin can paint foreground marks from the
editor's own syntax tree. Declare `syntax-decorations` and register
`register_plugin!(MyPlugin, syntax_decorations)`. The host asks; the plugin does
not parse. See [Syntax decorations](#syntax-decorations).
### Database sources (API 1.4)
Declare `database.sources` (medium risk). All five calls require it and a
@@ -1919,6 +1926,117 @@ shows it. The host asks the language server and the plugins together, under
the edit-path budget, and shows both; the editor asks again after edits and
scrolling. Labels are cut at 256 bytes and tooltips at 1 KiB.
#### Syntax decorations
The `syntax-decorations` kind (API 1.20) paints a foreground colour on ranges of
an open editor. It is how a plugin can colour syntax — for example keys at
different depths — using the colours of the active theme. Register with
`register_plugin!(MyPlugin, syntax_decorations)` and implement
`openidea_plugin::syntax_decorations::SyntaxDecorations`:
```rust
impl SyntaxDecorations for MyPlugin {
fn syntax_decorations(&mut self, request: &SyntaxDecorationRequest) -> Vec<SyntaxMark> {
let Some(node) = request.nodes.iter().find(|n| n.parent.is_some()) else {
return vec![];
};
vec![SyntaxMark::new(node.range, "rainbow-1")]
}
}
```
```toml
[capabilities]
required = ["editor.read"]
[[contributes.providers]]
kinds = ["syntax-decorations"]
languages = ["yaml"]
```
The [syntax decorations test plugin](../crates/ide-plugin/tests/fixtures/syntax-decorations)
demonstrates the provider on JavaScript.
The host sends one `SyntaxDecorationRequest` for the ranges it is painting
and a bounded syntax snapshot of at most 8192 nodes. Visible ranges are added
first. Sticky header lines, which can sit outside the viewport, are added
after them and only while the request still has room. A request holds at most
32 ranges. When the visible ranges already fill that budget, a sticky header
is left out and keeps the syntax highlighter's colour.
Each node has the parser's `name`, a UTF-16 `range`, and `parent` as an index
into that same list, or none. Index 0 is a real node. The list is ordered by
position, so a parent index may be greater than the child's index. The
snapshot contains the nodes that overlap the requested ranges and the
ancestors needed to reach them, until the node budget runs out. It can be a
partial tree: the editor does not parse the rest of the file for the plugin,
and the host does not run a second parser. `parent` is none when that ancestor
was not included. None does not mean the node is the root of the real tree;
truncation can drop an ancestor and keep the child. Node names belong to the
editor's parser. They are not a vocabulary shared by every language, and a
plugin must not treat a name as stable across parsers.
`document.version` is the host buffer version when the call starts. A result
whose document changed before the call finished is discarded. The editor also
discards a result when the viewport, the syntax tree or the document moved
while the plugin was running, and it does not ask again for a selection change
alone. Edits, scrolling, folding, syntax updates, enabling the plugin and
plugin setting changes ask again. A theme change does not. Rainbow tokens
are theme variables, and a mark's own colours already cover both kinds of theme.
A mark is either a token or its own colours. The tokens `rainbow-1`,
`rainbow-2`, `rainbow-3`, `rainbow-4` and `rainbow-5` map onto the existing
`--syn-rainbow-1` … `--syn-rainbow-5` colours of the light and dark themes. For
colours outside that palette, set `foreground` (`SyntaxMark::colored` in the
Rust SDK): `#rrggbb` or `#rrggbbaa` for dark themes and for light themes, the
same colour format as `decorations.set-styled`. The host drops a mark with an
unknown token or an invalid colour; a plugin cannot send CSS, HTML, a script, a
class name or a theme variable. The mark changes the foreground only; font weight
and style stay as they are. The editor stylesheet, not the plugin, picks the dark
or light colour when the theme changes. The mark is drawn inside the syntax highlighter's span, so it overrides that
span's foreground colour. Existing
`decorations.set` and `decorations.set-styled` sets are unchanged and stay on
their own layer. Where a syntax-decoration mark covers the same characters,
its foreground is the inner one, so it wins over a `set-styled` colour; a
background or underline from `set-styled` still shows.
The host sends a snapshot only to plugins with an `editor.read` grant that
declared the document's language. The document must be open in the calling window. A
project plugin still only receives documents inside the project where it was
granted. The plugin cannot ask for a different document. Ranges outside the
document or outside the requested ranges, a parent index that does not point
at a node in the list, and more than 10,000 marks are dropped. One plugin's
marks never replace another's. When several plugins mark the same range, declaration
order is kept and the earlier plugin's mark is the inner span, so its colour
is the one that shows. Ranges that only partly overlap are split where they
meet. Each plugin keeps the characters only it covers, and the shared
characters are nested. Plugin id does not decide that case.
The editor waits 50 ms and syncs pending edits before sending one request
for the latest snapshot. A new refresh or a closed editor cancels a pending
or in-flight request. Calls use the editor-provider deadline (normally 50 ms
soft / 500 ms hard) and the same fuel and memory limits as other providers.
The editor discards answers superseded by a document, viewport, syntax tree
or provider change. Disabling or uninstalling a plugin
stops its actor, which drops a call that actor was still running; other
plugins' answers in the same request are kept. A timeout, a trap or an invalid
answer contributes no marks. Disabling, uninstalling or unloading the plugin
removes its marks. An answer already in flight is not applied after the plugin
set changes. Closing the editor drops the marks with the editor, and a
response that arrives after the editor is gone is ignored. An idle reclaimed
instance is asked again on the next refresh; its previous marks stay until
that answer arrives. A document the editor opened as past the code insight
file size limit is not sent. That limit is the user's Editor setting (1–50
MiB, 5 MiB by default), decided when the document was opened. There is no
separate fixed character ceiling.
The provider runs in the text editor. The diff viewer and notebook cells do
not ask it.
Plugins built for an older API keep working. `set`, `set-markdown` and
`set-styled` are unchanged. A component that does not export
`syntax-decorations-provider` is not called.
#### Additional language features (API 1.4)
Declare the following kinds under `[[contributes.providers]]`, with
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4b1f2303c8b795c11e9c6c57d980005e28b0bdf53a98999175db0d573b38554f
55181617e0c0df5d3d454bf9cc95323f406ef247df09b43a25e06fd539393754
Бінарний файл не відображається.
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more