diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index fbfceea4b9..b249c34539 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -629,6 +629,8 @@ impl Default for FileSettings { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct LanguagesSettings { + /// Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. + pub plugin_formatters: BTreeMap, pub python: PythonSettings, pub node: NodeSettings, pub php: PhpSettings, @@ -646,6 +648,7 @@ pub struct LanguagesSettings { impl Default for LanguagesSettings { fn default() -> Self { Self { + plugin_formatters: BTreeMap::new(), python: PythonSettings::default(), node: NodeSettings::default(), php: PhpSettings::default(), diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index fea37d0533..ad3416ac5d 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -130,6 +130,38 @@ pub async fn format( let snap = project.documents.snapshot(doc)?; let settings = project.settings.effective(); let language = project.languages.get(&snap.language); + if options.tool.is_none() + && let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty()) + { + if options.on_save && !settings.editor.format_on_save { + return Ok(Vec::new()); + } + if snap.read_only { + return Err(IdeError::invalid("The file is read-only")); + } + let plugins = crate::plugins::editor_plugin_host() + .ok_or_else(|| IdeError::not_found("The selected plugin formatter is unavailable"))?; + let d = ide_plugin::ProviderDocument { + path: snap.path.0, + language: snap.language.0, + version: u64::from(snap.version), + text: snap.text, + }; + let id = id.clone(); + return tokio::task::spawn_blocking(move || { + plugins.language_format( + &id, + &d, + range, + ide_plugin::language_features::FormatOptions { + tab_size: options.tab_size, + insert_spaces: options.insert_spaces, + }, + ) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))?; + } // A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files. if options.tool.is_none() && snap.path.extension().is_some_and(|e| e == "php") diff --git a/crates/ide-host/src/ops/doc/commands.rs b/crates/ide-host/src/ops/doc/commands.rs index ddb9c8a6f2..ad10190362 100644 --- a/crates/ide-host/src/ops/doc/commands.rs +++ b/crates/ide-host/src/ops/doc/commands.rs @@ -52,6 +52,20 @@ pub fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_ending: L pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult> { let project = host.project(window)?; let lsp = project.lsp.document_symbols(doc).await.ok().flatten(); + let lsp = if lsp.as_ref().is_none_or(|v| v.is_empty()) { + if let Some((plugins, d)) = + crate::ops::lsp::plugin_providers(host, window, doc, crate::plugins::ProviderKind::DocumentSymbols) + { + let items = + crate::ops::lsp::plugin_call(move || plugins.language_document_symbols(&d)).await.unwrap_or_default(); + if items.is_empty() { lsp } else { Some(crate::plugins::language_features::outline(items)) } + } else { + lsp + } + } else { + lsp + }; + let lsp = lsp.filter(|v| !v.is_empty()); blocking(move || { let snap = match project.documents.text_snapshot(doc) { Ok(snap) => snap, @@ -80,7 +94,27 @@ pub async fn doc_folding(host: &Host, window: &str, doc: DocId) -> IdeResult ide_language::FoldKind::Comment, + "imports" => ide_language::FoldKind::Imports, + _ => ide_language::FoldKind::Region, + }, + })); + folds.sort_by_key(|f| (f.start_line, f.end_line)); + folds.dedup_by_key(|f| (f.start_line, f.end_line)); + } + Ok(folds) }) .await } @@ -105,6 +139,21 @@ pub async fn doc_selection_ranges(host: &Host, window: &str, doc: DocId, offset: let project = host.project(window)?; blocking(move || { let snap = project.documents.text_snapshot(doc)?; + if !snap.large + && let Some(plugins) = crate::plugins::editor_providers_for(crate::plugins::ProviderKind::SelectionRanges) + { + let at = ide_text::Document::new(&snap.text).offset_to_pos(offset); + let d = ide_plugin::ProviderDocument { + path: project.documents.identity(doc)?.0, + language: snap.language.0.clone(), + version: u64::from(snap.version), + text: snap.text.clone(), + }; + let ranges = plugins.language_selection_ranges(&d, at); + if !ranges.is_empty() { + return Ok(ranges); + } + } let language = if snap.large { ide_core::LanguageId::plain_text() } else { snap.language }; Ok(project.syntax.selection_ranges(doc, &language, snap.version, &snap.text, offset)) }) diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index 5ed1de2703..1e368cd4ac 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -56,7 +56,7 @@ pub async fn lsp_completion( } /// The plugin host and the document, when some plugin provides `kind`. -fn plugin_providers( +pub(crate) fn plugin_providers( host: &Host, window: &str, doc: DocId, @@ -74,10 +74,48 @@ fn plugin_providers( } /// Plugin calls block (the plugin's actor thread does the work). -async fn plugin_call(f: impl FnOnce() -> T + Send + 'static) -> Option { +pub(crate) async fn plugin_call(f: impl FnOnce() -> T + Send + 'static) -> Option { tokio::task::spawn_blocking(f).await.ok() } +fn provider_server(server: IdeResult) -> IdeResult { + match server { + Ok(v) => Ok(v), + Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable) => Ok(T::default()), + Err(e) => Err(e), + } +} + +fn merge_language_locations(mut server: Vec, plugin: Vec) -> Vec { + let mut seen: std::collections::HashSet<_> = server.iter().cloned().collect(); + for l in plugin { + let loc = Location::file(l.path, l.range); + if seen.insert(loc.clone()) { + server.push(loc); + } + } + server +} +fn merge_language_highlights( + mut server: Vec, + plugin: Vec, +) -> Vec { + let mut seen: std::collections::HashSet<_> = server.iter().map(|h| h.range).collect(); + for h in plugin { + if seen.insert(h.range) { + server.push(Highlight { + range: h.range, + kind: match h.kind.as_str() { + "read" => HighlightKind::Read, + "write" => HighlightKind::Write, + _ => HighlightKind::Text, + }, + }); + } + } + server +} + /// Items from plugins carry no server: commands don't apply, and a code /// action is resolved by the plugin named in its `data` ([`PluginActionRef`]). const PLUGIN_SERVER: ServerId = ServerId(0); @@ -222,7 +260,21 @@ pub async fn lsp_hover( } pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult> { - host.project(window)?.lsp.signature_help(doc, pos).await + let server = host.project(window)?.lsp.signature_help(doc, pos).await; + if matches!(&server,Ok(Some(h)) if !h.signatures.is_empty()) { + return server; + } + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::SignatureHelp) else { + return server; + }; + let help = plugin_call(move || plugins.language_signature_help(&d, pos)).await.flatten(); + match help { + Some(h) => { + let _ = provider_server(server)?; + Ok(Some(crate::plugins::language_features::signature_help(h))) + } + None => server, + } } pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult> { @@ -238,6 +290,23 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got } } let result = host.project(window)?.lsp.goto(doc, pos, kind).await; + if matches!(kind, GotoKind::Implementation | GotoKind::TypeDefinition) { + let k = + if kind == GotoKind::Implementation { ProviderKind::Implementation } else { ProviderKind::TypeDefinition }; + let Some((plugins, d)) = plugin_providers(host, window, doc, k) else { + return result; + }; + let locations = plugin_call(move || { + if kind == GotoKind::Implementation { + plugins.language_implementation(&d, pos) + } else { + plugins.language_type_definition(&d, pos) + } + }) + .await + .unwrap_or_default(); + return Ok(merge_language_locations(provider_server(result)?, locations)); + } if kind != GotoKind::Definition { return result; } @@ -358,6 +427,20 @@ pub async fn lsp_implementations( let cancel = host.begin_request(request); let result = lsp.implementations(doc, &positions, cancel).await; host.end_request(request); + if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) { + let count = positions.len(); + let found = plugin_call(move || { + positions.into_iter().map(|pos| plugins.language_implementation(&d, pos)).collect::>() + }) + .await + .unwrap_or_default(); + let mut out = provider_server(result)?; + out.resize_with(count, Vec::new); + for (items, found) in out.iter_mut().zip(found) { + *items = merge_language_locations(std::mem::take(items), found); + } + return Ok(out); + } result } @@ -380,6 +463,10 @@ pub async fn lsp_goto_implementation( }) .await; host.end_request(request); + if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) { + let found = plugin_call(move || plugins.language_implementation(&d, pos)).await.unwrap_or_default(); + return Ok(merge_language_locations(provider_server(result)?, found)); + } result } @@ -555,7 +642,12 @@ fn merge_indexed_references(mut server: References, symbol: &crate::plugins::nav } pub async fn lsp_document_highlights(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult> { - host.project(window)?.lsp.document_highlights(doc, pos).await + let server = host.project(window)?.lsp.document_highlights(doc, pos).await; + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::DocumentHighlights) else { + return server; + }; + let items = plugin_call(move || plugins.language_document_highlights(&d, pos)).await.unwrap_or_default(); + Ok(merge_language_highlights(provider_server(server)?, items)) } pub async fn lsp_workspace_symbols( @@ -597,7 +689,7 @@ pub async fn lsp_code_actions( let actions = if plugin_actions.is_empty() { result? } else { - let mut out = result.unwrap_or_default(); + let mut out = provider_server(result)?; out.extend(plugin_actions); out }; @@ -1105,12 +1197,52 @@ pub async fn lsp_semantic_tokens(host: &Host, window: &str, doc: DocId) -> IdeRe } pub async fn lsp_code_lens(host: &Host, window: &str, doc: DocId) -> IdeResult> { - host.project(window)?.lsp.code_lens(doc).await + let server = host.project(window)?.lsp.code_lens(doc).await; + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::CodeLenses) else { + return server; + }; + let items = plugin_call(move || plugins.language_code_lenses(&d)).await.unwrap_or_default(); + let mut out = provider_server(server)?; + out.extend(items.into_iter().map(|(plugin, i)| CodeLens { + range: i.range, + command: Some(Command { + title: i.title, + command: format!("openidea.plugin-language:{plugin}:{}", i.command), + arguments: vec![serde_json::json!(serde_json::to_string(&i.argument).unwrap_or_default())], + }), + })); + Ok(out) } /// Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeResult> { - host.project(window)?.lsp.document_links(doc).await + let server = host.project(window)?.lsp.document_links(doc).await; + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::DocumentLinks) else { + return server; + }; + let root = host.project(window)?.root.clone(); + let items = plugin_call(move || plugins.language_document_links(&d)).await.unwrap_or_default(); + let mut out = provider_server(server)?; + out.extend(items.into_iter().filter_map(|i| { + let url = i.target.starts_with("https://") || i.target.starts_with("http://"); + if !url && ide_core::is_virtual_uri(&i.target) { + return None; + } + Some(DocumentLink { + range: i.range, + path: (!url).then(|| { + { + let path = std::path::PathBuf::from(&i.target); + if path.is_absolute() { path } else { root.join(path) } + } + .into() + }), + url: url.then_some(i.target), + fragment: None, + tooltip: None, + }) + })); + Ok(out) } pub async fn lsp_call_hierarchy( @@ -1200,6 +1332,34 @@ pub async fn redo_workspace_edit(host: &Host, window: &str, id: u32) -> IdeResul /// Runs a server command (`workspace/executeCommand`), e.g. a completion item's /// follow-up command. Edits the server requests arrive via `workspace/applyEdit`. pub async fn lsp_execute_command(host: &Host, window: &str, doc: DocId, command: Command) -> IdeResult<()> { + if let Some(rest) = command.command.strip_prefix("openidea.plugin-language:") { + let (plugin, command_id) = + rest.split_once(':').ok_or_else(|| ide_core::IdeError::invalid("Invalid plugin command"))?; + let plugins = crate::plugins::editor_plugin_host() + .ok_or_else(|| ide_core::IdeError::not_found("Plugin host unavailable"))?; + let argument = command + .arguments + .first() + .and_then(|a| a.as_str()) + .and_then(|s| serde_json::from_str::>(s).ok()) + .flatten(); + let project = host.project(window)?; + let snap = project.documents.snapshot(doc)?; + let invocation = ide_plugin::Invocation { + client: Some(window.into()), + workspace_root: Some(project.root.clone()), + editor: Some(ide_plugin::EditorContext { + path: snap.path.0.clone(), + language: snap.language.0, + selections: vec![], + }), + selected_paths: vec![snap.path.0], + ..Default::default() + }; + let (plugin, command_id) = (plugin.to_owned(), command_id.to_owned()); + return blocking(move || plugins.run_language_command(&plugin, &command_id, argument.as_deref(), invocation)) + .await; + } host.project(window)?.lsp.execute_command(doc, command).await } @@ -1262,7 +1422,74 @@ pub async fn lsp_execute_code_action( } /// Commands of this module the remote server answers. +/// Versioned plugin visuals, refreshed after the editor synchronizes its buffer. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginLanguageVisuals { + pub version: u64, + pub injections: Vec, + pub colors: Vec<(String, ide_plugin::language_features::ColorInfo)>, + pub gutter_actions: Vec<(String, ide_plugin::language_features::GutterAction)>, +} +pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> IdeResult { + let snap = host.project(window)?.documents.snapshot(doc)?; + blocking(move || { + let d = ProviderDocument { + path: snap.path.0, + language: snap.language.0, + version: u64::from(snap.version), + text: snap.text, + }; + let mut out = + PluginLanguageVisuals { version: d.version, injections: vec![], colors: vec![], gutter_actions: vec![] }; + if d.text.len() <= crate::plugins::navigation::MAX_DOCUMENT_BYTES + && let Some(plugins) = crate::plugins::editor_plugin_host() + { + out.injections = plugins.provide_injections(&d); + out.colors = plugins.language_colors(&d); + out.gutter_actions = plugins.language_gutter_actions(&d); + } + Ok(out) + }) + .await +} +pub async fn plugin_color_presentations( + host: &Host, + window: &str, + doc: DocId, + plugin: String, + color: ide_plugin::language_features::ColorInfo, +) -> IdeResult> { + let snap = host.project(window)?.documents.snapshot(doc)?; + blocking(move || { + let d = ProviderDocument { + path: snap.path.0, + language: snap.language.0, + version: u64::from(snap.version), + text: snap.text, + }; + if !crate::plugins::language_features::valid_range(&d, color.range) { + return Err(ide_core::IdeError::invalid("Invalid color range")); + } + Ok(crate::plugins::editor_plugin_host() + .map(|p| p.language_color_presentations(&plugin, &d, color)) + .unwrap_or_default()) + }) + .await +} +pub fn plugin_formatters() -> Vec { + crate::plugins::editor_plugin_host().map(|p| p.formatter_choices()).unwrap_or_default() +} + pub(crate) fn register(d: &mut Dispatcher) { + d.add( + "plugin_language_visuals", + |c| async move { plugin_language_visuals(&c.host, &c.window, c.arg("doc")?).await }, + ); + d.add("plugin_color_presentations", |c| async move { + plugin_color_presentations(&c.host, &c.window, c.arg("doc")?, c.arg("plugin")?, c.arg("color")?).await + }); + d.add("plugin_formatters", |_c| async move { Ok(plugin_formatters()) }); d.add("lsp_completion", |c| async move { lsp_completion(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, c.arg("trigger")?).await }); @@ -1408,6 +1635,32 @@ pub(crate) fn register(d: &mut Dispatcher) { #[cfg(test)] mod tests { + #[test] + fn language_features_merge_without_overwriting_lsp_ranges_or_masking_errors() { + use super::*; + let range = Range::new(Pos::default(), Pos::new(0, 1)); + let existing = Location::file("/p/a".into(), range); + let merged = merge_language_locations( + vec![existing.clone()], + vec![ + ide_plugin::Location { path: "/p/a".into(), range }, + ide_plugin::Location { path: "/p/b".into(), range }, + ], + ); + assert_eq!(merged.len(), 2); + assert_eq!(merged[0], existing); + let merged = merge_language_highlights( + vec![Highlight { range, kind: HighlightKind::Read }], + vec![ide_plugin::language_features::Highlight { range, kind: "write".into() }], + ); + assert_eq!(merged.len(), 1); + assert_eq!(merged[0].kind, HighlightKind::Read); + assert!( + provider_server::>(Err(ide_core::IdeError::unavailable("no server"))).unwrap().is_empty() + ); + assert!(provider_server::>(Err(ide_core::IdeError::cancelled())).is_err()); + } + use super::*; #[test] diff --git a/crates/ide-host/src/plugins/diagnostics.rs b/crates/ide-host/src/plugins/diagnostics.rs index 14470f56a6..86e44ccd88 100644 --- a/crates/ide-host/src/plugins/diagnostics.rs +++ b/crates/ide-host/src/plugins/diagnostics.rs @@ -79,7 +79,9 @@ impl Diagnostics { doc.cancel.cancel(); doc.cancel = CancellationToken::new(); let Some(host) = editor_plugin_host() else { return }; - if host.providers.plugins_for(ProviderKind::Diagnostics, &doc.snapshot.language).is_empty() { + if host.providers.plugins_for(ProviderKind::Diagnostics, &doc.snapshot.language).is_empty() + && !host.providers.any(ProviderKind::Injections) + { return; } // Register only once per project incarnation; no project is retained by the host. @@ -113,6 +115,7 @@ impl Diagnostics { snapshot.text = current.text; drop(documents); + let injections = host.providers.injection_generations(&snapshot.language); let generations = host.providers.diagnostic_generations(&snapshot.language); let results = if snapshot.text.len() <= super::navigation::MAX_DOCUMENT_BYTES { host.provide_project_diagnostics(Some(&root), &snapshot, &cancel) @@ -124,6 +127,11 @@ impl Diagnostics { if state.closed || cancel.is_cancelled() { return; } + if injections != host.providers.injection_generations(&snapshot.language) + || injections.keys().any(|id| lifecycle_generations.get(id) != state.generations.get(id)) + { + return; + } let matching: HashSet<_> = host .diagnostic_plugins(Some(&root), &snapshot.language) .into_iter() @@ -224,6 +232,13 @@ pub(super) type ProjectState = (Weak>, SharedSink); impl PluginHost { pub(super) fn clear_provider_diagnostics(&self, plugin: &str) { // Clone before taking a project's state lock (edits register in the other order). + let injector = self.get(plugin).is_ok_and(|p| { + p.manifest().declarations("providers").iter().any(|d| { + d.get("kinds") + .and_then(|v| v.as_array()) + .is_some_and(|v| v.iter().any(|k| k.as_str() == Some("injections"))) + }) + }); let projects = self.diagnostic_projects.lock().clone(); for (state, sink) in projects { if let Some(state) = state.upgrade() { @@ -231,7 +246,15 @@ impl PluginHost { // A completed answer can still be waiting for another provider. *state.generations.entry(plugin.to_owned()).or_default() += 1; for doc in state.documents.values_mut() { - if doc.sources.remove(plugin) { + if injector { + for source in doc.sources.drain() { + sink.emit(IdeEvent::Diagnostics { + path: doc.snapshot.path.clone().into(), + source: format!("plugin-provider:{source}"), + items: vec![], + }); + } + } else if doc.sources.remove(plugin) { sink.emit(IdeEvent::Diagnostics { path: doc.snapshot.path.clone().into(), source: format!("plugin-provider:{plugin}"), diff --git a/crates/ide-host/src/plugins/injections.rs b/crates/ide-host/src/plugins/injections.rs new file mode 100644 index 0000000000..79e1328454 --- /dev/null +++ b/crates/ide-host/src/plugins/injections.rs @@ -0,0 +1,126 @@ +//! Embedded plugin-provider documents preserve the host's UTF-16 coordinates. +use super::{PluginHost, ProviderKind}; +use ide_core::{Pos, Range}; +use ide_plugin::{ProviderDocument, language_features::Injection}; +use std::sync::Arc; + +/// Allowed output ranges for one virtual document; the host document is unrestricted. +pub(super) struct Bounds(Option>); +impl Bounds { + pub fn unrestricted() -> Self { + Self(None) + } + pub fn contains(&self, range: Range) -> bool { + self.0.as_ref().is_none_or(|rs| rs.iter().any(|r| r.start <= range.start && range.end <= r.end)) + } + pub fn lines(&self, start: u32, end: u32) -> bool { + self.0.as_ref().is_none_or(|rs| rs.iter().any(|r| r.start.line <= start && end <= r.end.line)) + } +} + +impl PluginHost { + pub fn provide_injections(&self, doc: &ProviderDocument) -> Vec { + if !self.providers.any(ProviderKind::Injections) { + return vec![]; + } + if doc.text.len() > super::navigation::MAX_DOCUMENT_BYTES { + return Vec::new(); + } + let text = ide_text::Document::new(&doc.text); + let d = Arc::new(doc.clone()); + let mut items: Vec<_> = self + .document_calls(ProviderKind::Injections, doc, move |rt, t| rt.provide_injections(&d, t)) + .into_iter() + .flat_map(|(_, v)| v) + .filter(|i| { + !i.range.is_empty() + && super::language_features::valid_range_in(&text, i.range) + && i.language != doc.language + && !i.language.is_empty() + && i.language.len() <= 64 + && i.language.chars().all(|c| c.is_ascii_alphanumeric() || "-_.+#".contains(c)) + }) + .collect(); + items.sort_by_key(|i| i.range); + let mut end = Pos::default(); + items.retain(|i| { + if i.range.start < end { + return false; + } + end = i.range.end; + true + }); + items.truncate(1000); + items + } + + pub(super) fn feature_documents(&self, doc: &ProviderDocument, at: Option) -> Vec<(ProviderDocument, Bounds)> { + let injections = self.provide_injections(doc); + let mut languages = Vec::new(); + for i in &injections { + if at.is_some_and(|p| p < i.range.start || p >= i.range.end) || languages.contains(&i.language) { + continue; + } + languages.push(i.language.clone()); + if languages.len() == 32 { + break; + } + } + let mut docs = Vec::new(); + for language in languages { + let ranges = injections.iter().filter(|i| i.language == language).map(|i| i.range).collect(); + let text = virtual_text(doc, &injections, &language); + docs.push((ProviderDocument { language, text, ..doc.clone() }, Bounds(Some(ranges)))); + } + docs.push((doc.clone(), Bounds(None))); + docs + } +} + +pub(crate) fn virtual_text(doc: &ProviderDocument, ranges: &[Injection], language: &str) -> String { + let ranges: Vec<_> = ranges.iter().filter(|i| i.language == language).map(|i| i.range).collect(); + let mut index = 0; + let mut at = Pos::default(); + let mut text = String::with_capacity(doc.text.len()); + for c in doc.text.chars() { + while index < ranges.len() && ranges[index].end <= at { + index += 1; + } + let inside = ranges.get(index).is_some_and(|r| r.start <= at && at < r.end); + if inside || c == '\n' || c == '\r' { + text.push(c); + } else { + for _ in 0..c.len_utf16() { + text.push(' '); + } + } + if c == '\n' { + at.line += 1; + at.col = 0; + } else { + at.col += c.len_utf16() as u32; + } + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn virtual_documents_preserve_utf16_columns_and_newlines() { + let d = ProviderDocument { + path: "/p/a".into(), + language: "host".into(), + version: 7, + text: "😀 sql\n outside\n sql".into(), + }; + let ranges = vec![ + Injection { range: Range::new(Pos::new(0, 3), Pos::new(0, 6)), language: "sql".into() }, + Injection { range: Range::new(Pos::new(2, 1), Pos::new(2, 4)), language: "sql".into() }, + ]; + let text = virtual_text(&d, &ranges, "sql"); + assert_eq!(text, " sql\n \n sql"); + assert_eq!(text.encode_utf16().count(), d.text.encode_utf16().count()); + } +} diff --git a/crates/ide-host/src/plugins/language_features.rs b/crates/ide-host/src/plugins/language_features.rs new file mode 100644 index 0000000000..b7852690ad --- /dev/null +++ b/crates/ide-host/src/plugins/language_features.rs @@ -0,0 +1,462 @@ +//! API 1.4 language features. Results are bounded and checked against the snapshot. +use super::{PluginHost, ProviderKind}; +use ide_core::{IdeResult, Pos, Range}; +use ide_plugin::{ProviderDocument, language_features::*}; +use std::sync::Arc; + +pub(crate) fn valid_range(doc: &ProviderDocument, range: Range) -> bool { + valid_range_in(&ide_text::Document::new(&doc.text), range) +} +pub(super) fn valid_range_in(text: &ide_text::Document, range: Range) -> bool { + if range.start > range.end { + return false; + } + [range.start, range.end].iter().all(|p| text.offset_to_pos(text.pos_to_offset(*p)) == *p) +} + +impl PluginHost { + pub fn language_format( + &self, + id: &str, + doc: &ProviderDocument, + range: Option, + options: FormatOptions, + ) -> IdeResult> { + let candidates = if let Some(r) = range { + self.feature_documents(doc, Some(r.start)) + } else { + vec![(doc.clone(), super::injections::Bounds::unrestricted())] + }; + let (target, bounds) = candidates + .into_iter() + .find(|(d, b)| { + range.is_none_or(|r| b.contains(r)) + && self + .provider_plugins(ProviderKind::Formatting, &d.language) + .iter() + .any(|p| p.id() == id && p.dev_root.as_ref().is_none_or(|r| d.path.starts_with(r))) + }) + .ok_or_else(|| ide_core::IdeError::not_found("The selected plugin formatter is unavailable"))?; + let text = ide_text::Document::new(&target.text); + let d = Arc::new(target); + let edits = self.code_call(id, ide_plugin::Invocation::default(), "formatting", move |rt, _| { + rt.language_format(&d, range, options.clone(), std::time::Duration::from_secs(5)) + })?; + if edits.iter().any(|e| !valid_range_in(&text, e.range) || !bounds.contains(e.range)) { + return Err(ide_core::IdeError::invalid("Plugin formatter returned an invalid range")); + } + let mut ranges: Vec<_> = edits.iter().map(|e| e.range).collect(); + ranges.sort(); + if ranges.windows(2).any(|p| p[0].end > p[1].start) { + return Err(ide_core::IdeError::invalid("Plugin formatter returned overlapping edits")); + } + Ok(edits) + } + pub fn language_signature_help(&self, doc: &ProviderDocument, at: Pos) -> Option { + for (d, _bounds) in self.feature_documents(doc, Some(at)) { + let snapshot = d.clone(); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::SignatureHelp, &snapshot, move |rt, t| { + rt.language_signature_help(&d, at, t) + }); + for (_, v) in results { + if let Some(v) = v.filter(|h| !h.signatures.is_empty()) { + return Some(v); + } + } + } + None + } + pub fn language_document_highlights(&self, doc: &ProviderDocument, at: Pos) -> Vec { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, Some(at)) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::DocumentHighlights, &snapshot, move |rt, t| { + rt.language_document_highlights(&d, at, t) + }); + for (p, items) in results { + for i in items { + let _ = &p; + if valid_range_in(&text, i.range) && bounds.contains(i.range) { + out.push(i); + } + } + } + } + out + } + pub fn language_document_links(&self, doc: &ProviderDocument) -> Vec { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = self + .document_calls(ProviderKind::DocumentLinks, &snapshot, move |rt, t| rt.language_document_links(&d, t)); + for (p, items) in results { + for i in items { + let _ = &p; + if valid_range_in(&text, i.range) && bounds.contains(i.range) { + out.push(i); + } + } + } + } + out + } + pub fn language_code_lenses(&self, doc: &ProviderDocument) -> Vec<(String, CodeLens)> { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = + self.document_calls(ProviderKind::CodeLenses, &snapshot, move |rt, t| rt.language_code_lenses(&d, t)); + for (p, items) in results { + let commands: std::collections::HashSet<_> = + self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect(); + for i in items { + if valid_range_in(&text, i.range) && bounds.contains(i.range) && commands.contains(&i.command) { + out.push((p.id().to_owned(), i)); + } + } + } + } + out + } + pub fn language_selection_ranges(&self, doc: &ProviderDocument, at: Pos) -> Vec { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, Some(at)) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::SelectionRanges, &snapshot, move |rt, t| { + rt.language_selection_ranges(&d, at, t) + }); + for (p, items) in results { + for i in items { + let _ = &p; + if valid_range_in(&text, i) && i.start <= at && at <= i.end && bounds.contains(i) { + out.push(i); + } + } + } + } + out.sort_by(|a, b| b.start.cmp(&a.start).then(a.end.cmp(&b.end))); + out.dedup(); + let mut end = None; + out.retain(|r| { + let ok = end.is_none_or(|prev: Range| r.start <= prev.start && prev.end <= r.end); + if ok { + end = Some(*r); + } + ok + }); + out + } + pub fn language_folding(&self, doc: &ProviderDocument) -> Vec { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let lines = d.text.split('\n').count() as u32; + let snapshot = d.clone(); + let d = Arc::new(d); + let results = + self.document_calls(ProviderKind::Folding, &snapshot, move |rt, t| rt.language_folding(&d, t)); + for (p, items) in results { + for i in items { + let _ = &p; + if i.start_line < i.end_line && i.end_line < lines && bounds.lines(i.start_line, i.end_line) { + out.push(i); + } + } + } + } + out + } + pub fn language_colors(&self, doc: &ProviderDocument) -> Vec<(String, ColorInfo)> { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::Colors, &snapshot, move |rt, t| rt.language_colors(&d, t)); + for (p, items) in results { + for i in items { + if valid_range_in(&text, i.range) + && bounds.contains(i.range) + && [i.red, i.green, i.blue, i.alpha].iter().all(|c| c.is_finite() && (0.0..=1.0).contains(c)) + { + out.push((p.id().to_owned(), i)); + } + } + } + } + out + } + pub fn language_color_presentations(&self, id: &str, doc: &ProviderDocument, color: ColorInfo) -> Vec { + for (d, bounds) in self.feature_documents(doc, Some(color.range.start)) { + if !bounds.contains(color.range) + || !self.provider_plugins(ProviderKind::Colors, &d.language).iter().any(|p| p.id() == id) + { + continue; + } + let snapshot = d.clone(); + let d = Arc::new(d); + let color = color.clone(); + let result = self.document_calls_for(ProviderKind::Colors, &snapshot, Some(id), move |rt, t| { + rt.language_color_presentations(&d, color.clone(), t) + }); + if let Some((_, items)) = result.into_iter().find(|(p, _)| p.id() == id) { + return items.into_iter().take(100).collect(); + } + } + Vec::new() + } + pub fn language_document_symbols(&self, doc: &ProviderDocument) -> Vec { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let snapshot = d.clone(); + let text = ide_text::Document::new(&snapshot.text); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::DocumentSymbols, &snapshot, move |rt, t| { + rt.language_document_symbols(&d, t) + }); + for (_, items) in results { + let mut remap = std::collections::HashMap::new(); + for (index, mut i) in items.into_iter().enumerate() { + if !valid_range_in(&text, i.range) + || !valid_range_in(&text, i.selection_range) + || i.selection_range.start < i.range.start + || i.selection_range.end > i.range.end + || !bounds.contains(i.range) + { + continue; + } + i.parent = i.parent.and_then(|p| remap.get(&(p as usize)).copied()); + remap.insert(index, out.len() as u32); + out.push(i); + } + } + } + out + } + pub fn language_implementation(&self, doc: &ProviderDocument, at: Pos) -> Vec { + let mut out = Vec::new(); + for (d, _bounds) in self.feature_documents(doc, Some(at)) { + let snapshot = d.clone(); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::Implementation, &snapshot, move |rt, t| { + rt.language_implementation(&d, at, t) + }); + for (p, items) in results { + for i in items { + let _ = &p; + out.push(i); + } + } + } + out + } + pub fn language_type_definition(&self, doc: &ProviderDocument, at: Pos) -> Vec { + let mut out = Vec::new(); + for (d, _bounds) in self.feature_documents(doc, Some(at)) { + let snapshot = d.clone(); + let d = Arc::new(d); + let results = self.document_calls(ProviderKind::TypeDefinition, &snapshot, move |rt, t| { + rt.language_type_definition(&d, at, t) + }); + for (p, items) in results { + for i in items { + let _ = &p; + out.push(i); + } + } + } + out + } + pub fn language_gutter_actions(&self, doc: &ProviderDocument) -> Vec<(String, GutterAction)> { + let mut out = Vec::new(); + for (d, bounds) in self.feature_documents(doc, None) { + let lines = d.text.split('\n').count() as u32; + let snapshot = d.clone(); + let d = Arc::new(d); + let results = self + .document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| rt.language_gutter_actions(&d, t)); + for (p, items) in results { + let commands: std::collections::HashSet<_> = + self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect(); + for i in items { + if i.line < lines && bounds.lines(i.line, i.line) && commands.contains(&i.command) { + out.push((p.id().to_owned(), i)); + } + } + } + } + out + } +} + +impl PluginHost { + pub(crate) fn run_language_command( + &self, + plugin: &str, + command: &str, + argument: Option<&str>, + invocation: ide_plugin::Invocation, + ) -> IdeResult<()> { + if !self.ui.items(super::COMMANDS, Some(plugin)).iter().any(|c| c.key == command) { + return Err(ide_core::IdeError::not_found("The plugin did not declare this command")); + } + self.run_command(plugin, command, argument, invocation).map(|_| ()) + } +} + +pub(crate) fn signature_help(h: SignatureHelp) -> ide_lsp::types::SignatureHelp { + let signatures: Vec<_> = h + .signatures + .into_iter() + .take(100) + .map(|s| { + let len = s.label.encode_utf16().count() as u32; + let parameters = s + .parameters + .into_iter() + .take(100) + .map(|p| match p.label { + ParameterLabel::Offsets((a, b)) => (a.min(len), b.max(a).min(len)), + ParameterLabel::Text(t) => s + .label + .find(&t) + .map(|a| { + let start = s.label[..a].encode_utf16().count() as u32; + (start, start + t.encode_utf16().count() as u32) + }) + .unwrap_or((0, 0)), + }) + .collect(); + ide_lsp::types::Signature { + label: s.label, + documentation: s.documentation.map(|value| ide_lsp::types::Markup { kind: "markdown".into(), value }), + parameters, + } + }) + .collect(); + let active_signature = h.active_signature.min(signatures.len().saturating_sub(1) as u32); + let active_parameter = + h.active_parameter + .min(signatures.get(active_signature as usize).map(|s| s.parameters.len().saturating_sub(1)).unwrap_or(0) + as u32); + ide_lsp::types::SignatureHelp { signatures, active_signature, active_parameter } +} + +pub(crate) fn outline(items: Vec) -> Vec { + // A parent must precede its child, ruling out cycles and unbounded recursion. + let mut depths = vec![0usize; items.len()]; + let mut parents = vec![None; items.len()]; + for (idx, item) in items.iter().enumerate() { + if let Some(parent) = item.parent.map(|p| p as usize).filter(|p| { + *p < idx + && depths[*p] < 63 + && items[*p].range.start <= item.range.start + && item.range.end <= items[*p].range.end + }) { + parents[idx] = Some(parent); + depths[idx] = depths[parent] + 1; + } + } + let mut nodes: Vec<_> = items + .into_iter() + .map(|i| { + Some(ide_core::OutlineItem { + name: i.name, + detail: Some(i.detail).filter(|s| !s.is_empty()), + kind: serde_json::from_value(serde_json::Value::String(symbol_kind_name(&i.kind))) + .unwrap_or(ide_core::SymbolKind::Unknown), + range: i.range, + selection_range: i.selection_range, + children: vec![], + visibility: None, + }) + }) + .collect(); + let mut roots = Vec::new(); + for idx in (0..nodes.len()).rev() { + let mut node = nodes[idx].take().expect("once"); + node.children.reverse(); + if let Some(parent) = parents[idx] { + nodes[parent].as_mut().expect("parent precedes child").children.push(node); + } else { + roots.push(node); + } + } + roots.reverse(); + roots +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct FormatterChoice { + pub id: String, + pub name: String, + pub languages: Vec, +} +impl PluginHost { + pub fn formatter_choices(&self) -> Vec { + let mut out = std::collections::BTreeMap::::new(); + for (id, languages) in self.providers.formatter_declarations() { + let Ok(p) = self.get(&id) else { + continue; + }; + if !matches!(p.meta.lock().status, super::PluginStatus::Active | super::PluginStatus::Inactive) { + continue; + } + out.entry(id.clone()) + .or_insert_with(|| FormatterChoice { id, name: p.pkg.manifest.name.clone(), languages: vec![] }) + .languages + .extend(languages); + } + out.into_values() + .map(|mut c| { + c.languages.sort(); + c.languages.dedup(); + c + }) + .collect() + } +} + +fn symbol_kind_name(kind: &str) -> String { + let mut parts = kind.split('-'); + let mut out = parts.next().unwrap_or_default().to_owned(); + for part in parts { + let mut chars = part.chars(); + if let Some(c) = chars.next() { + out.extend(c.to_uppercase()); + out.extend(chars); + } + } + out +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn outline_uses_parent_order_containment_and_string_kinds() { + let range = Range::new(Pos::new(0, 0), Pos::new(0, 10)); + let item = |name: &str, parent| DocumentSymbol { + name: name.into(), + detail: String::new(), + kind: "enum-member".into(), + range, + selection_range: range, + parent, + }; + let out = + outline(vec![item("root", None), item("child", Some(0)), item("future", Some(3)), item("other", Some(2))]); + assert_eq!(out[0].children[0].kind, ide_core::SymbolKind::EnumMember); + assert_eq!(out[1].name, "future"); + assert_eq!(out[1].children[0].name, "other"); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 4cb624f26e..46b4693f71 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -29,10 +29,12 @@ mod icon_patterns; mod icon_settings; mod icons; pub mod index_ops; +pub(crate) mod injections; mod inlay_hints; mod install; pub mod intellij; mod ipc; +pub mod language_features; mod market; pub mod navigation; mod points; @@ -42,6 +44,7 @@ pub mod remote_host; mod run_detectors; pub mod run_targets; mod semantic_tokens; +mod snippets; mod theme; mod types; pub mod ui_points; diff --git a/crates/ide-host/src/plugins/points.rs b/crates/ide-host/src/plugins/points.rs index 9e1031d2d9..65c7fc2c35 100644 --- a/crates/ide-host/src/plugins/points.rs +++ b/crates/ide-host/src/plugins/points.rs @@ -20,15 +20,23 @@ pub struct CommandDecl { pub id: String, pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option, /// Enablement, evaluated by the client against context keys (`editorLang == rust`). #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option, } -fn command(_pkg: &Package, decl: toml::Value) -> Result { +fn command(pkg: &Package, decl: toml::Value) -> Result { let c: CommandDecl = decode(COMMANDS, decl)?; validate_item_id(&c.id, "command id")?; + if let Some(icon) = &c.icon { + pkg.manifest.needs_api("contributes.commands.icon", 4)?; + if icon.is_empty() || icon.len() > 256 { + return Err("command icon: expected 1–256 bytes".into()); + } + } if c.title.trim().is_empty() { return Err(format!("command {:?} has an empty title", c.id)); } @@ -40,7 +48,14 @@ fn command(_pkg: &Package, decl: toml::Value) -> Result { } let c = CommandDecl { category: c.category.filter(|x| !x.trim().is_empty()), ..c }; let json = serde_json::to_value(&c).map_err(|e| e.to_string())?; - Ok(UiDecl::new(c.id.clone(), c.title, json)) + let mut out = UiDecl::new(c.id.clone(), c.title, json); + if let Some(icon) = c.icon.filter(|s| s.ends_with(".svg")) { + let path = std::path::PathBuf::from(icon); + let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?; + out.files.push(path); + out.assets.push((format!("commandIcon/{}", c.id), svg)); + } + Ok(out) } /// Registers every first-party extension point. @@ -65,6 +80,7 @@ pub fn register_builtin_points( ui.clone(), super::execution::configurations_declaration, )))?; + registry.register(Arc::new(UiPoint::new("snippets", ui.clone(), super::snippets::declaration)))?; use super::ui_points as p; registry.register(Arc::new(UiPoint::new(p::MENUS, ui.clone(), p::menu)))?; registry.register(Arc::new(UiPoint::new(p::KEYMAPS, ui.clone(), p::keymap)))?; diff --git a/crates/ide-host/src/plugins/providers.rs b/crates/ide-host/src/plugins/providers.rs index ad1d590f9b..10a8ebf274 100644 --- a/crates/ide-host/src/plugins/providers.rs +++ b/crates/ide-host/src/plugins/providers.rs @@ -42,6 +42,19 @@ pub enum ProviderKind { Hover, InlayHints, Diagnostics, + Formatting, + SignatureHelp, + DocumentHighlights, + DocumentLinks, + CodeLenses, + SelectionRanges, + Folding, + Colors, + DocumentSymbols, + Implementation, + TypeDefinition, + GutterActions, + Injections, } #[derive(Clone, Debug, Deserialize)] @@ -94,9 +107,30 @@ impl Providers { } pub(super) fn diagnostic_generations(&self, language: &str) -> HashMap { - self.matching(ProviderKind::Diagnostics, language) + if self.any(ProviderKind::Injections) { + let mut out = HashMap::new(); + for (seq, plugin, kinds, _) in self.items.read().iter() { + if kinds.contains(&ProviderKind::Diagnostics) { + out.entry(plugin.clone()).or_insert(*seq); + } + } + out + } else { + self.matching(ProviderKind::Diagnostics, language) + } } + pub(super) fn injection_generations(&self, language: &str) -> HashMap { + self.matching(ProviderKind::Injections, language) + } + pub(super) fn formatter_declarations(&self) -> Vec<(String, Vec)> { + self.items + .read() + .iter() + .filter(|(_, _, k, _)| k.contains(&ProviderKind::Formatting)) + .map(|(_, p, _, l)| (p.clone(), l.clone())) + .collect() + } /// Whether any plugin provides `kind` (for any language). pub fn any(&self, kind: ProviderKind) -> bool { self.items.read().iter().any(|(_, _, kinds, _)| kinds.contains(&kind)) @@ -142,6 +176,26 @@ impl ExtensionPoint for ProvidersPoint { if d.kinds.contains(&ProviderKind::InlayHints) { pkg.manifest.needs_api("contributes.providers: inlay-hints", 3)?; } + if d.kinds.iter().any(|k| { + matches!( + k, + ProviderKind::Formatting + | ProviderKind::SignatureHelp + | ProviderKind::DocumentHighlights + | ProviderKind::DocumentLinks + | ProviderKind::CodeLenses + | ProviderKind::SelectionRanges + | ProviderKind::Folding + | ProviderKind::Colors + | ProviderKind::DocumentSymbols + | ProviderKind::Implementation + | ProviderKind::TypeDefinition + | ProviderKind::GutterActions + | ProviderKind::Injections + ) + }) { + pkg.manifest.needs_api("contributes.providers: language features and injections", 4)?; + } for l in &d.languages { if l != "*" && (l.is_empty() @@ -211,7 +265,7 @@ pub fn set_editor_providers(host: Option<&Arc>) { /// The plugin host whose providers take part, when any declares `kind`. pub(crate) fn editor_providers(kind: ProviderKind) -> Option> { let host = editor_plugin_host()?; - host.providers.any(kind).then_some(host) + (host.providers.any(kind) || host.providers.any(ProviderKind::Injections)).then_some(host) } pub(crate) fn editor_plugin_host() -> Option> { @@ -236,15 +290,46 @@ impl PluginHost { /// declares `kind` for `language`, in plugin order, leaving out those that /// failed or were late. Each plugin runs on its own thread, so the calls /// run at the same time: the wait is the slowest plugin's, not the sum. - fn edit_calls( + pub(super) fn edit_calls( &self, kind: ProviderKind, language: &str, f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> Vec<(Arc, R)> { + self.edit_calls_plugins(self.provider_plugins(kind, language), f) + } + + pub(super) fn document_calls( + &self, + kind: ProviderKind, + doc: &ProviderDocument, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> Vec<(Arc, R)> { + self.document_calls_for(kind, doc, None, f) + } + pub(super) fn document_calls_for( + &self, + kind: ProviderKind, + doc: &ProviderDocument, + owner: Option<&str>, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> Vec<(Arc, R)> { + let plugins = self + .provider_plugins(kind, &doc.language) + .into_iter() + .filter(|p| { + p.dev_root.as_ref().is_none_or(|r| doc.path.starts_with(r)) && owner.is_none_or(|id| p.id() == id) + }) + .collect(); + self.edit_calls_plugins(plugins, f) + } + fn edit_calls_plugins( + &self, + plugins: Vec>, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, ) -> Vec<(Arc, R)> { let (soft, hard) = (self.limits.edit_soft, self.limits.edit_hard); - let queued: Vec<_> = self - .provider_plugins(kind, language) + let queued: Vec<_> = plugins .into_iter() .filter_map(|plugin| { let (actor, activated) = self.ensure_active(&plugin, None).ok()?; @@ -303,13 +388,24 @@ impl PluginHost { at: ide_core::Pos, trigger: Option<&str>, ) -> Vec<(String, CompletionItem)> { - let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned)); - self.edit_calls(ProviderKind::Completion, &doc.language, move |rt, timeout| { - rt.provide_completion(&d, at, t.as_deref(), timeout) - }) - .into_iter() - .flat_map(|(p, items)| items.into_iter().map(move |i| (p.id().to_owned(), i))) - .collect() + self.feature_documents(doc, Some(at)) + .into_iter() + .flat_map(|(doc, bounds)| { + let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned)); + self.document_calls(ProviderKind::Completion, &doc, move |rt, timeout| { + rt.provide_completion(&d, at, t.as_deref(), timeout) + }) + .into_iter() + .flat_map(|(p, items)| items.into_iter().map(move |i| (p.id().to_owned(), i))) + .filter_map(move |(p, mut i)| { + if i.replace.is_some_and(|r| !bounds.contains(r)) { + return None; + } + i.additional_edits.retain(|e| bounds.contains(e.range)); + Some((p, i)) + }) + }) + .collect() } pub fn provide_code_actions( @@ -391,10 +487,20 @@ impl PluginHost { project: Option<&std::path::Path>, language: &str, ) -> Vec> { - self.provider_plugins(ProviderKind::Diagnostics, language) - .into_iter() - .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) - .collect() + let plugins = if self.providers.any(ProviderKind::Injections) { + self.providers + .diagnostic_generations(language) + .keys() + .filter_map(|id| self.get(id).ok()) + .filter(|p| { + let m = p.meta.lock(); + matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty() + }) + .collect() + } else { + self.provider_plugins(ProviderKind::Diagnostics, language) + }; + plugins.into_iter().filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project).collect() } pub(super) fn provide_project_diagnostics( @@ -402,11 +508,35 @@ impl PluginHost { project: Option<&std::path::Path>, doc: &ProviderDocument, cancel: &CancellationToken, + ) -> Vec<(String, Vec)> { + let mut out = std::collections::BTreeMap::>::new(); + for (d, bounds) in self.feature_documents(doc, None) { + if cancel.is_cancelled() { + break; + } + for (id, items) in self.provide_document_diagnostics(project, &d, cancel) { + out.entry(id).or_default().extend(items.into_iter().filter(|i| bounds.contains(i.range))); + } + } + out.into_iter() + .map(|(id, mut items)| { + items.truncate(5000); + (id, items) + }) + .collect() + } + + fn provide_document_diagnostics( + &self, + project: Option<&std::path::Path>, + doc: &ProviderDocument, + cancel: &CancellationToken, ) -> Vec<(String, Vec)> { std::thread::scope(|scope| { let calls: Vec<_> = self - .diagnostic_plugins(project, &doc.language) + .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() { @@ -432,10 +562,15 @@ impl PluginHost { } pub fn provide_hover(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec { - let d = Arc::new(doc.clone()); - self.edit_calls(ProviderKind::Hover, &doc.language, move |rt, timeout| rt.provide_hover(&d, at, timeout)) + self.feature_documents(doc, Some(at)) .into_iter() - .filter_map(|(_, hover)| hover) + .flat_map(|(doc, bounds)| { + let d = Arc::new(doc.clone()); + self.document_calls(ProviderKind::Hover, &doc, move |rt, timeout| rt.provide_hover(&d, at, timeout)) + .into_iter() + .filter_map(|(_, h)| h) + .filter(move |h| h.range.is_none_or(|r| bounds.contains(r))) + }) .collect() } diff --git a/crates/ide-host/src/plugins/snippets.rs b/crates/ide-host/src/plugins/snippets.rs new file mode 100644 index 0000000000..dac8228fb2 --- /dev/null +++ b/crates/ide-host/src/plugins/snippets.rs @@ -0,0 +1,106 @@ +//! Named JSON snippets, retained as read-only UI declarations. +use ide_extension::{Package, UiDecl, decode}; +use serde::Deserialize; +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + language: String, + path: std::path::PathBuf, +} +#[derive(Deserialize)] +#[serde(untagged)] +enum Lines { + One(String), + Many(Vec), +} +impl Lines { + fn values(self) -> Vec { + match self { + Self::One(s) => vec![s], + Self::Many(v) => v, + } + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Snippet { + prefix: Lines, + body: Lines, + description: Option, +} + +pub(super) fn declaration(pkg: &Package, decl: toml::Value) -> Result { + pkg.manifest.needs_api("contributes.snippets", 4)?; + let d: Decl = decode("snippets", decl)?; + if d.language.is_empty() + || d.language.len() > 64 + || !d.language.chars().all(|c| c.is_ascii_alphanumeric() || "-_.+#".contains(c)) + { + return Err("snippets: invalid language id".into()); + } + let text = pkg.read_text(&d.path)?; + if text.len() > 1024 * 1024 { + return Err("snippets: file exceeds 1 MiB".into()); + } + let snippets: std::collections::BTreeMap = + serde_json::from_str(&text).map_err(|e| format!("snippets: {e}"))?; + if snippets.len() > 1000 { + return Err("snippets: at most 1000 entries per file".into()); + } + let mut entries = vec![]; + for (name, s) in snippets { + let prefixes = s.prefix.values(); + let body = s.body.values().join("\n"); + if name.is_empty() + || name.len() > 256 + || prefixes.is_empty() + || prefixes.len() > 32 + || prefixes.iter().any(|p| p.is_empty() || p.len() > 256) + || body.len() > 65536 + || s.description.as_ref().is_some_and(|s| s.len() > 4096) + { + return Err(format!("snippets: invalid entry {name:?}")); + } + entries.push(serde_json::json!({"name":name,"prefixes":prefixes,"body":body,"description":s.description.unwrap_or_default()})); + } + let key = d.path.to_string_lossy().into_owned(); + let mut out = UiDecl::new( + key.clone(), + d.language.clone(), + serde_json::json!({"source":key,"language":d.language,"entries":entries}), + ); + out.files.push(d.path); + Ok(out) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn validates_every_snippet_at_install_and_requires_api4() { + let dir = tempfile::tempdir().unwrap(); + let manifest = |api| { + ide_extension::Manifest::parse(&format!( + "id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'" + )) + .unwrap() + }; + let decl: toml::Value = toml::from_str("language='sql'\npath='snippets.json'").unwrap(); + std::fs::write( + dir.path().join("snippets.json"), + r#"{"Select":{"prefix":["sel","select"],"body":["SELECT ${1:column}","FROM $1$0"],"description":"Query"}}"#, + ) + .unwrap(); + let pkg = Package::new(manifest("^1.4"), dir.path().into()); + let out = declaration(&pkg, decl.clone()).unwrap(); + assert_eq!(out.json["entries"][0]["body"], "SELECT ${1:column}\nFROM $1$0"); + assert!(declaration(&Package::new(manifest("^1.3"), dir.path().into()), decl.clone()).is_err()); + for text in [ + r#"{"x":{"prefix":[],"body":"x"}}"#, + r#"{"x":{"prefix":"x","body":42}}"#, + r#"{"x":{"prefix":"x","body":"x","extra":1}}"#, + ] { + std::fs::write(dir.path().join("snippets.json"), text).unwrap(); + assert!(declaration(&pkg, decl.clone()).is_err()); + } + } +} diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index 9a1edc4e07..b8ca5f94f9 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -76,8 +76,18 @@ pub const COMMIT_CHECKS: &str = "commitChecks"; const VIEW_ITEM_MENU: &str = "viewItem.context"; /// The toolbar above the commit message (Commit tool window and dialog). const COMMIT_MESSAGE_MENU: &str = "commit.message"; -const MENU_IDS: [&str; 6] = - ["editor.context", "projectView.context", "editorTab.context", "tools", VIEW_ITEM_MENU, COMMIT_MESSAGE_MENU]; +const MENU_IDS: [&str; 10] = [ + "editor.context", + "projectView.context", + "editorTab.context", + "tools", + VIEW_ITEM_MENU, + COMMIT_MESSAGE_MENU, + "editor.title", + "mainToolbar", + "problems.context", + "searchResults.context", +]; const MAX_TITLE: usize = 256; const MAX_SETTINGS: usize = 200; const MAX_PATTERNS: usize = 16; @@ -135,6 +145,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result { return Err(format!("contributes.menus: unknown menu {:?} (one of {})", d.menu, MENU_IDS.join(", "))); } declared_command(pkg, MENUS, &d.command)?; + if ["editor.title", "mainToolbar", "problems.context", "searchResults.context"].contains(&d.menu.as_str()) { + pkg.manifest.needs_api("contributes.menus: language workbench menus", 4)?; + } if d.menu == COMMIT_MESSAGE_MENU { pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?; } @@ -965,6 +978,20 @@ pub(super) fn locales(pkg: &Package, _decl: toml::Value) -> Result std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/language-features") +} +fn plugins(base: &Path) -> Arc { + let p = Arc::new( + PluginHost::new( + base.join("plugins"), + Arc::new(|_: Option<&str>, _| {}), + Limits { edit_soft: Duration::from_secs(3), edit_hard: Duration::from_secs(5), ..Default::default() }, + ) + .unwrap(), + ); + p.install_from_dir(&fixture(), &Consent::all()).unwrap(); + p +} +#[test] +fn injections_route_only_declared_embedded_providers_and_filter_diagnostics() { + let tmp = tempfile::tempdir().unwrap(); + let p = plugins(tmp.path()); + let doc = ProviderDocument { + path: tmp.path().join("a.txt"), + language: "text".into(), + version: 9, + text: "xx[[sql]]zz".into(), + }; + assert_eq!(p.provide_injections(&doc).len(), 1); + let items = p.provide_completion(&doc, Pos::new(0, 5), None); + assert_eq!(items.len(), 1); + assert_eq!(items[0].1.label, "sql: sql "); + assert!(p.provide_completion(&doc, Pos::new(0, 1), None).is_empty()); + assert_eq!(p.provide_hover(&doc, Pos::new(0, 5))[0].markdown, "sql: sql "); + let diagnostics = p.provide_diagnostics(&doc, &CancellationToken::new()); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].1.len(), 1); + assert_eq!(diagnostics[0].1[0].range, Range::new(Pos::new(0, 4), Pos::new(0, 7))); + assert!(p.language_signature_help(&ProviderDocument { language: "rust".into(), ..doc }, Pos::default()).is_none()); +} +#[test] +fn every_new_kind_requires_api4_at_install() { + let tmp = tempfile::tempdir().unwrap(); + let p = plugins(tmp.path()); + let package = tmp.path().join("old"); + std::fs::create_dir_all(package.join("dist")).unwrap(); + std::fs::copy(fixture().join("dist/plugin.wasm"), package.join("dist/plugin.wasm")).unwrap(); + let header = "id='old'\nname='Old'\nversion='1.0.0'\nengines.openidea='^1.3'\nwasm='dist/plugin.wasm'\n"; + for kind in [ + "formatting", + "signature-help", + "document-highlights", + "document-links", + "code-lenses", + "selection-ranges", + "folding", + "colors", + "document-symbols", + "implementation", + "type-definition", + "gutter-actions", + "injections", + ] { + std::fs::write( + package.join("plugin.toml"), + format!("{header}\n[[contributes.providers]]\nkinds=['{kind}']\nlanguages=['text']"), + ) + .unwrap(); + assert!(p.install_from_dir(&package, &Consent::all()).is_err(), "{kind}"); + } +} +#[tokio::test(flavor = "multi_thread")] +async fn editor_ops_merge_the_fixture_format_selection_and_execute_owned_commands() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().canonicalize().unwrap().join("project"); + std::fs::create_dir(&root).unwrap(); + let host = Arc::new(Host::new(HostConfig { + config_dir: tmp.path().join("config"), + data_dir: tmp.path().join("data"), + local_data_dir: tmp.path().join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + host.open_project("main", &root).unwrap(); + let p = plugins(tmp.path()); + p.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); + set_editor_providers(Some(&p)); + let path = root.join("a.txt"); + std::fs::write(&path, "value\nnext\nend").unwrap(); + let doc = ops::doc::open(&host, "main", path.clone()).await.unwrap(); + assert_eq!( + ops::lsp::lsp_signature_help(&host, "main", doc.id, Pos::default()).await.unwrap().unwrap().signatures[0] + .parameters, + vec![(6, 11)] + ); + assert_eq!(ops::lsp::lsp_document_highlights(&host, "main", doc.id, Pos::default()).await.unwrap().len(), 1); + let links = ops::lsp::lsp_document_links(&host, "main", doc.id).await.unwrap(); + assert_eq!(links.len(), 2); + assert_eq!(links[0].path.as_ref().unwrap().0, root.join("next.txt")); + let lenses = ops::lsp::lsp_code_lens(&host, "main", doc.id).await.unwrap(); + assert_eq!(lenses.len(), 1, "undeclared command was dropped"); + ops::lsp::lsp_execute_command(&host, "main", doc.id, lenses[0].command.clone().unwrap()).await.unwrap(); + assert_eq!(p.run_command(ID, "state", None, Invocation::default()).unwrap().as_deref(), Some("lens")); + let outline = ops::doc::doc_outline(&host, "main", doc.id).await.unwrap(); + assert_eq!(outline[0].name, "Outer"); + assert_eq!(outline[0].children[0].name, "Inner"); + assert_eq!(ops::doc::doc_folding(&host, "main", doc.id).await.unwrap()[0].end_line, 2); + assert_eq!(ops::doc::doc_selection_ranges(&host, "main", doc.id, 0).await.unwrap().len(), 2); + for kind in [ide_lsp::types::GotoKind::Implementation, ide_lsp::types::GotoKind::TypeDefinition] { + assert_eq!(ops::lsp::lsp_goto(&host, "main", doc.id, Pos::default(), kind).await.unwrap().len(), 1); + } + assert_eq!( + ops::lsp::lsp_goto_implementation( + &host, + "main", + RequestId(1), + doc.id, + Pos::default(), + ide_host::ops::Channel::new(|_| {}) + ) + .await + .unwrap() + .len(), + 1 + ); + let visuals = ops::lsp::plugin_language_visuals(&host, "main", doc.id).await.unwrap(); + assert_eq!(visuals.colors.len(), 1); + assert_eq!(visuals.gutter_actions.len(), 1); + assert_eq!( + ops::lsp::plugin_color_presentations(&host, "main", doc.id, ID.into(), visuals.colors[0].1.clone()) + .await + .unwrap(), + ["red-plaintext", "#ff0000"] + ); + let project = host.project("main").unwrap(); + project + .settings + .set( + ide_workspace::settings::SettingsScope::Project, + "languages.pluginFormatters", + serde_json::json!({doc.language.as_str():ID}), + ) + .unwrap(); + let options = ide_lsp::types::FormatOptions { tab_size: 2, insert_spaces: true, on_save: false, tool: None }; + let formatted = + ops::lsp::lsp_format(&host, "main", doc.id, Some(Range::new(Pos::default(), Pos::new(0, 5))), options) + .await + .unwrap(); + assert_eq!(formatted[0].new_text, "formatted"); + // The same editor ops are exposed by the server dispatcher, with no desktop provider call. + let dispatcher = ide_host::rpc::Dispatcher::standard(); + assert!(dispatcher.commands().contains(&"plugin_language_visuals")); + + let base = tmp.path().join("server"); + let peer_slot = Arc::new(std::sync::OnceLock::new()); + let remote = ide_host::plugins::remote_host::RemotePlugins::start(&base, &host, peer_slot.clone()).unwrap(); + let mut dispatcher = ide_host::rpc::Dispatcher::standard(); + remote.register(&mut dispatcher); + let (client_io, server_io) = tokio::io::duplex(1 << 20); + let (sr, sw) = tokio::io::split(server_io); + tokio::spawn(ide_host::rpc::serve(host.clone(), dispatcher, peer_slot, sr, sw)); + struct Client; + impl ide_jsonrpc::Handler for Client { + fn on_notification(&self, _: &str, _: serde_json::Value) {} + fn on_request(&self, method: &str, _: serde_json::Value) -> Result { + Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned())) + } + } + let (cr, cw) = tokio::io::split(client_io); + let peer = ide_jsonrpc::Peer::connect(cr, cw, Arc::new(Client)); + let _: serde_json::Value = + peer.request("initialize", serde_json::json!({"version":ide_host::rpc::PROTOCOL_VERSION}), None).await.unwrap(); + async fn invoke(peer: &ide_jsonrpc::Peer, cmd: &str, args: serde_json::Value) -> serde_json::Value { + peer.request( + "invoke", + serde_json::to_value(ide_host::rpc::Invoke { window: "main".into(), cmd: cmd.into(), args }).unwrap(), + None, + ) + .await + .unwrap() + } + invoke(&peer, "project_trust_set", serde_json::json!({"path":root,"trusted":true,"folder":false})).await; + let files = serde_json::json!({ID:p.remote_package_files(ID).unwrap()}); + let synced = invoke( + &peer, + ide_host::plugins::remote_host::SYNC_PACKAGES, + serde_json::json!({"packages":p.remote_packages(),"files":files}), + ) + .await; + assert_eq!(synced["failed"], serde_json::json!([]), "{synced}"); + let listed = invoke(&peer, "plugin_formatters", serde_json::json!({})).await; + assert_eq!(listed[0]["id"], ID); + let visual = invoke(&peer, "plugin_language_visuals", serde_json::json!({"doc":doc.id})).await; + assert_eq!(visual["gutterActions"].as_array().unwrap().len(), 1); + set_editor_providers(Some(&p)); + p.set_enabled(ID, false).unwrap(); + assert!(ops::lsp::plugin_formatters().is_empty()); + set_editor_providers(None); +} + +#[test] +fn formatting_uses_the_command_budget_while_editor_calls_can_expire() { + let tmp = tempfile::tempdir().unwrap(); + let p = PluginHost::new( + tmp.path().join("plugins"), + Arc::new(|_: Option<&str>, _| {}), + Limits { edit_soft: Duration::ZERO, ..Default::default() }, + ) + .unwrap(); + p.install_from_dir(&fixture(), &Consent::all()).unwrap(); + let doc = + ProviderDocument { path: tmp.path().join("a.txt"), language: "text".into(), version: 1, text: "value".into() }; + assert_eq!( + p.language_format( + ID, + &doc, + None, + ide_plugin::language_features::FormatOptions { tab_size: 4, insert_spaces: true } + ) + .unwrap()[0] + .new_text, + "formatted" + ); + assert!(p.language_signature_help(&doc, Pos::default()).is_none()); + assert!(p.info_of(ID).unwrap().stats.slow_calls > 0); +} diff --git a/crates/ide-plugin/src/language_features.rs b/crates/ide-plugin/src/language_features.rs new file mode 100644 index 0000000000..7530054d8a --- /dev/null +++ b/crates/ide-plugin/src/language_features.rs @@ -0,0 +1,109 @@ +//! Optional API 1.4 language features and embedded language ranges. +use ide_core::Range; +use serde::{Deserialize, Serialize}; +use specta::Type; +/// A parameter label, as text or UTF-16 offsets within the signature. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +pub enum ParameterLabel { + Text(String), + Offsets((u32, u32)), +} +/// FormatOptions data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct FormatOptions { + pub tab_size: u32, + pub insert_spaces: bool, +} +/// Parameter data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Parameter { + pub label: ParameterLabel, + pub documentation: Option, +} +/// Signature data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Signature { + pub label: String, + pub documentation: Option, + pub parameters: Vec, +} +/// SignatureHelp data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelp { + pub signatures: Vec, + pub active_signature: u32, + pub active_parameter: u32, +} +/// Highlight data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Highlight { + pub range: Range, + pub kind: String, +} +/// DocumentLink data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DocumentLink { + pub range: Range, + pub target: String, +} +/// CodeLens data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CodeLens { + pub range: Range, + pub title: String, + pub command: String, + pub argument: Option, +} +/// FoldRange data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct FoldRange { + pub start_line: u32, + pub end_line: u32, + pub kind: String, +} +/// ColorInfo data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ColorInfo { + pub range: Range, + pub red: f32, + pub green: f32, + pub blue: f32, + pub alpha: f32, +} +/// DocumentSymbol data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DocumentSymbol { + pub name: String, + pub detail: String, + pub kind: String, + pub range: Range, + pub selection_range: Range, + pub parent: Option, +} +/// GutterAction data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GutterAction { + pub line: u32, + pub icon: Option, + pub tooltip: String, + pub command: String, + pub argument: Option, +} +/// Injection data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Injection { + pub range: Range, + pub language: String, +} diff --git a/crates/ide-plugin/src/lib.rs b/crates/ide-plugin/src/lib.rs index 72775c5943..6a000bfda9 100644 --- a/crates/ide-plugin/src/lib.rs +++ b/crates/ide-plugin/src/lib.rs @@ -28,3 +28,5 @@ mod execution; pub use execution::*; pub use ide_core::remote_settings::PluginRunTarget; + +pub mod language_features; diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 5c662c14ab..09ff2f0bb5 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -16,6 +16,8 @@ use crate::types::{ FieldValue, ServiceLog, ServiceLogToggle, ServicePane, ServiceTab, TableSort, View, ViewBody, ViewButton, ViewEvent, ViewField, ViewListItem, ViewTable, ViewTreeItem, Viewport, }; +use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj; +use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf; 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, @@ -872,6 +874,8 @@ pub struct Runtime { /// What the component exports: the `plugin` world, plus optional interfaces. struct Exports { + language_features: Option, + injections: Option, plugin: bindings::Plugin, syntax: Option, providers: Option, @@ -1006,10 +1010,14 @@ impl Runtime { let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok(); let configs_indices = wit_configs::GuestIndices::new(&pre).ok(); let tests_indices = wit_tests::GuestIndices::new(&pre).ok(); + let lf_indices = wit_lf::GuestIndices::new(&pre).ok(); + let inj_indices = wit_inj::GuestIndices::new(&pre).ok(); let instance = pre.instantiate(&mut store).map_err(api_hint)?; let run_configurations = configs_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; let test_results = tests_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; + let language_features = lf_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; + let injections = inj_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; let plugin = plugin_indices.load(&mut store, &instance).map_err(api_hint)?; let syntax = match syntax_indices { Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), @@ -1062,6 +1070,8 @@ impl Runtime { Ok(Self { store, exports: Exports { + language_features, + injections, plugin, syntax, providers, @@ -2165,6 +2175,334 @@ fn test_event_from_wit(event: wit_tests::TestEvent) -> crate::PluginTestEvent { } } +fn parameter_from(v: wit_lf::Parameter) -> crate::language_features::Parameter { + crate::language_features::Parameter { + label: parameter_label_from(v.label), + documentation: v.documentation.map(|v| crate::runtime::clip(v, 65536)), + } +} +fn signature_from(v: wit_lf::Signature) -> crate::language_features::Signature { + crate::language_features::Signature { + label: crate::runtime::clip(v.label, 65536), + documentation: v.documentation.map(|v| crate::runtime::clip(v, 65536)), + parameters: v.parameters.into_iter().take(10000).map(parameter_from).collect(), + } +} +fn signature_help_from(v: wit_lf::SignatureHelpResult) -> crate::language_features::SignatureHelp { + crate::language_features::SignatureHelp { + signatures: v.signatures.into_iter().take(10000).map(signature_from).collect(), + active_signature: v.active_signature, + active_parameter: v.active_parameter, + } +} +fn highlight_from(v: wit_lf::Highlight) -> crate::language_features::Highlight { + crate::language_features::Highlight { range: range_from_wit(v.range), kind: crate::runtime::clip(v.kind, 65536) } +} +fn document_link_from(v: wit_lf::DocumentLink) -> crate::language_features::DocumentLink { + crate::language_features::DocumentLink { + range: range_from_wit(v.range), + target: crate::runtime::clip(v.target, 65536), + } +} +fn code_lens_from(v: wit_lf::CodeLens) -> crate::language_features::CodeLens { + crate::language_features::CodeLens { + range: range_from_wit(v.range), + title: crate::runtime::clip(v.title, 65536), + command: crate::runtime::clip(v.command, 65536), + argument: v.argument.map(|v| crate::runtime::clip(v, 65536)), + } +} +fn fold_range_from(v: wit_lf::FoldRange) -> crate::language_features::FoldRange { + crate::language_features::FoldRange { + start_line: v.start_line, + end_line: v.end_line, + kind: crate::runtime::clip(v.kind, 65536), + } +} +fn color_info_from(v: wit_lf::ColorInfo) -> crate::language_features::ColorInfo { + crate::language_features::ColorInfo { + range: range_from_wit(v.range), + red: v.red, + green: v.green, + blue: v.blue, + alpha: v.alpha, + } +} +fn document_symbol_from(v: wit_lf::DocumentSymbol) -> crate::language_features::DocumentSymbol { + crate::language_features::DocumentSymbol { + name: crate::runtime::clip(v.name, 65536), + detail: crate::runtime::clip(v.detail, 65536), + kind: crate::runtime::clip(v.kind, 65536), + range: range_from_wit(v.range), + selection_range: range_from_wit(v.selection_range), + parent: v.parent, + } +} +fn gutter_action_from(v: wit_lf::GutterAction) -> crate::language_features::GutterAction { + crate::language_features::GutterAction { + line: v.line, + icon: v.icon.map(|v| crate::runtime::clip(v, 65536)), + tooltip: crate::runtime::clip(v.tooltip, 65536), + command: crate::runtime::clip(v.command, 65536), + argument: v.argument.map(|v| crate::runtime::clip(v, 65536)), + } +} +fn parameter_label_from(v: wit_lf::ParameterLabel) -> crate::language_features::ParameterLabel { + use crate::language_features::ParameterLabel as P; + match v { + wit_lf::ParameterLabel::Text(t) => P::Text(clip(t, 4096)), + wit_lf::ParameterLabel::Offsets(t) => P::Offsets(t), + } +} +impl Runtime { + fn language_feature_call( + &mut self, + timeout: Duration, + f: impl FnOnce(&wit_lf::Guest, &mut Store) -> wasmtime::Result, + ) -> Result { + if self.exports.language_features.is_none() { + return Err(CallError::missing_export("language-features")); + } + self.call(Invocation::default(), timeout, |e, s| f(e.language_features.as_ref().expect("checked"), s)) + } + pub fn language_format( + &mut self, + doc: &ProviderDocument, + range: Option, + options: crate::language_features::FormatOptions, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| { + p.call_format( + s, + &d, + range.map(range_to_wit), + wit_lf::FormatOptions { tab_size: options.tab_size, insert_spaces: options.insert_spaces }, + ) + })?; + let result = result.map_err(|e| CallError::Guest(e.into()))?; + Ok(result.into_iter().take(10000).map(edit_from_wit).collect()) + } + pub fn language_signature_help( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_signature_help(s, &d, pos_to_wit(at)))?; + Ok(result.map(signature_help_from)) + } + pub fn language_document_highlights( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_document_highlights(s, &d, pos_to_wit(at)))?; + Ok(result.into_iter().take(10000).map(highlight_from).collect()) + } + pub fn language_document_links( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_document_links(s, &d))?; + Ok(result.into_iter().take(10000).map(document_link_from).collect()) + } + pub fn language_code_lenses( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_code_lenses(s, &d))?; + Ok(result.into_iter().take(10000).map(code_lens_from).collect()) + } + pub fn language_selection_ranges( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_selection_ranges(s, &d, pos_to_wit(at)))?; + Ok(result.into_iter().take(10000).map(range_from_wit).collect()) + } + pub fn language_folding( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_folding(s, &d))?; + Ok(result.into_iter().take(10000).map(fold_range_from).collect()) + } + pub fn language_colors( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_colors(s, &d))?; + Ok(result.into_iter().take(10000).map(color_info_from).collect()) + } + pub fn language_color_presentations( + &mut self, + doc: &ProviderDocument, + color: crate::language_features::ColorInfo, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| { + p.call_color_presentations( + s, + &d, + wit_lf::ColorInfo { + range: range_to_wit(color.range), + red: color.red, + green: color.green, + blue: color.blue, + alpha: color.alpha, + }, + ) + })?; + Ok(result.into_iter().take(10000).map(|v| crate::runtime::clip(v, 65536)).collect()) + } + pub fn language_document_symbols( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_document_symbols(s, &d))?; + Ok(result.into_iter().take(10000).map(document_symbol_from).collect()) + } + pub fn language_implementation( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_implementation(s, &d, pos_to_wit(at)))?; + Ok(result.into_iter().take(10000).map(location_from_wit).collect()) + } + pub fn language_type_definition( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_type_definition(s, &d, pos_to_wit(at)))?; + Ok(result.into_iter().take(10000).map(location_from_wit).collect()) + } + pub fn language_gutter_actions( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = wit_lf::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.language_feature_call(timeout, |p, s| p.call_gutter_actions(s, &d))?; + Ok(result.into_iter().take(10000).map(gutter_action_from).collect()) + } + pub fn provide_injections( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + if self.exports.injections.is_none() { + return Err(CallError::missing_export("injections")); + } + let d = wit_inj::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + text: doc.text.clone(), + }; + let result = self.call(Invocation::default(), timeout, |e, s| { + e.injections.as_ref().expect("checked").call_injections(s, &d) + })?; + Ok(result + .into_iter() + .take(10000) + .map(|i| crate::language_features::Injection { + range: range_from_wit(i.range), + language: clip(i.language, 64), + }) + .collect()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index 55b0aadeae..595b0a9968 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -2165,3 +2165,14 @@ impl bindings::openidea::plugin::decorations::Host for StoreData { Ok(self.host.file_decorations(None, &set_id, None).map_err(to_wit)) } } + +pub(crate) mod language_features_bindings { + wasmtime::component::bindgen!({ world: "editor-language-features", path: "../../wit", + with: { "openidea:plugin/types": super::bindings::openidea::plugin::types }, + }); +} +pub(crate) mod injections_bindings { + wasmtime::component::bindgen!({ world: "language-injections", path: "../../wit", + with: { "openidea:plugin/types": super::bindings::openidea::plugin::types }, + }); +} diff --git a/crates/ide-plugin/tests/api_compat.rs b/crates/ide-plugin/tests/api_compat.rs index 602dc883c5..6e9778a633 100644 --- a/crates/ide-plugin/tests/api_compat.rs +++ b/crates/ide-plugin/tests/api_compat.rs @@ -32,6 +32,7 @@ fn components() -> Vec { repo().join("crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm"), repo().join("crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm"), repo().join("crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm"), + repo().join("crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm"), repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"), ]; let official = repo().join("plugins/official"); diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index 70fcc60020..8621743822 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 302531a0c3..90e12dde88 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -aca0cf50e9b7e9f66d62705ba040c7caee745f0cf97fe492cb39af86971aed22 +bac658dc0f223ec8b0be5087cc8d1f66f317d7ae6b5e5511a5f9496a6acaa308 diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 30033e2995..1a2cda115b 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 52bd8acdee..9650a44b06 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -f3d07c243ae6e279f49cb4e1bd9fa67117ad4f7ebfb4c22dcfe1510701b56a71 +ac2f9291842359e5cfc280d5e0e55073f79ad2a69511df7c1f89a1ef7b907a55 diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index a7eee1e1d2..29ab44a19a 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index f08e5e4c0e..8d218bf7c9 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -6134e5ad5b174fe75ee6ddba9604a30d5d30bd675ffabbaea1ad78831a21609a +3535be047d3ef3bb2778c6fd3343401b6c9e641640dea7b3fe515a13fe3ac70f diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 10a2228c9d..2aafe9e74a 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index d644317c03..072eeb354d 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -9f9b56b7044adac003648ca18d34ceffb58505918f550cf8ad187ac14a8845d7 +f5345d17fe4255962ac70fa7bc0dd02a4f1cd74b2c6b323d700f0ff42d9f5ef8 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index cd12556872..eb98af730d 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index 3ab2e473d0..280f67f6df 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -ed71c7f1ad8420439f58426f898b41d982ae97653916b1c56590705320dc66b1 +aff88e85279461e7c05f7930f6f6f48d93b34c88a36a7f14b618c22c426df472 diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index 38e6e6081b..a2cac70dba 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index 991637c08a..495638cfec 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -fc3b498f6f82197db683cd2aa9500593f883f962492ca11f0a6940233ad6c7f0 +45fa9a4b902e98881d1bde723af6229b5b4854fffe419f2916181bef98a8395c diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index 3a1f090dcb..60d93ee912 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 22ec5194a7..b1459cdf7c 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -131d45a3c7ef42f063e1100ab7f9d4e1e7b7fcf2095f27377f95eb59387756ee +b88de6312230de83beeb20565866c4954f3c6dbeb063e801a3ea2d3134da3b81 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index 5fe12a3952..3d657db662 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index cfee5f2236..7769208931 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -ea0612a1a1248e5410de7e55ff2dad7c4c1973cff690ce0e7f151e5d9395b209 +dceaa88fd5c0029e28779ff6e30e2fa1c4303561ae4d439d5676f0e5c001a90d diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index a881f8a7d3..693717a6ed 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index 7be43c7596..1ddf161b34 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -99cbcce92580b3b292bb92ab34468a156554b1afa53df66320a85df92b37f936 +6ff365ce704f2ba58a167410d2a0a8195de4ee63f0e755e8a92618b4596e3d1a diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index 7a7d3bb56b..7985ac24c8 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index b3695a5547..6d38df072f 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -e7209fe969f00bb2ffb135e401aede7fa40a5b59ca865cc2c0f499d935b8d944 +d519439e8d19999ebe14aae544d9073c8dd9ac2418774a0de5cb1560dcbf6c29 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index a9a8203044..476c2ab97c 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index a5608e6bd7..d14bbb828b 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -da1d956ebc383809fd44dd40fa37d9107bf71e2cf2328dcb4a9f4be9203fdff1 +c470e2b88f279c0d1ac79b3a5c4421b878f6a7090f19bea0c0061f1b85db89a2 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index 0dec53401f..65b277bfb0 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index 4ddef10cc0..5ffac7fc9b 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -9367abca6a02ab0867707450b0dad9a810b586ca14593f8b4ceecbdef67763cd +7089d560996621a7c86188a72867a0086ef45e8f1eeb7d53bca8ecdcdf948899 diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index dbb3305b1b..32e72dc104 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index 22c5bb0a21..a40d4b832d 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -9d6498184eff25bfa053c5ab81f22ffc2ec817e83b26ce8496ab25e7f75c4811 +d3b94ce5415175d252408987bf20ca0be8f4252f7227cef9319c8939bd252505 diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 51464f0b03..fc517c6c5e 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 1c95460155..fa0ecf604b 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -caad529a0659e7b48763026f49025c29d78d1bc12702e4fed307d1f94d76556f +1573c9d8ac88413d1a88887040bce9b042a8b979dfbc1c4f8b1f0e1bea4db0f7 diff --git a/crates/ide-plugin/tests/fixtures/language-features/Cargo.lock b/crates/ide-plugin/tests/fixtures/language-features/Cargo.lock new file mode 100644 index 0000000000..fdd99c28db --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/Cargo.lock @@ -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.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +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.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[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-language-features" +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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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" diff --git a/crates/ide-plugin/tests/fixtures/language-features/Cargo.toml b/crates/ide-plugin/tests/fixtures/language-features/Cargo.toml new file mode 100644 index 0000000000..2d5067628a --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "openidea-test-language-features" +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" diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm new file mode 100644 index 0000000000..1865ce24b1 Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources new file mode 100644 index 0000000000..b2712ee9ac --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources @@ -0,0 +1 @@ +88fc4df46bfca5f1f4c285d55991ebd590a4de0e54e0db8b74760d3aa029a643 diff --git a/crates/ide-plugin/tests/fixtures/language-features/plugin.toml b/crates/ide-plugin/tests/fixtures/language-features/plugin.toml new file mode 100644 index 0000000000..0b77ae880e --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/plugin.toml @@ -0,0 +1,31 @@ +id = "test.language-features" +name = "Language features fixture" +version = "0.1.0" +engines.openidea = "^1.4" +wasm = "dist/plugin.wasm" + +[[contributes.providers]] +kinds = ["formatting", "signature-help", "document-highlights", "document-links", "code-lenses", "selection-ranges", "folding", "colors", "document-symbols", "implementation", "type-definition", "gutter-actions", "injections"] +languages = ["plaintext", "text", "sql"] + +[[contributes.providers]] +kinds = ["completion", "hover", "diagnostics"] +languages = ["sql"] + +[[contributes.commands]] +id = "run" +title = "Run fixture" +icon = "run" + +[[contributes.commands]] +id = "state" +title = "Fixture state" + +[[contributes.snippets]] +language = "sql" +path = "snippets.json" + +[[contributes.menus]] +menu = "editor.title" +command = "run" +when = "editorLangId == sql" diff --git a/crates/ide-plugin/tests/fixtures/language-features/snippets.json b/crates/ide-plugin/tests/fixtures/language-features/snippets.json new file mode 100644 index 0000000000..f19ee3f95e --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/snippets.json @@ -0,0 +1 @@ +{"Select":{"prefix":["sel","select"],"body":["SELECT ${1:column}","FROM ${2:table}$0"],"description":"Select rows"}} diff --git a/crates/ide-plugin/tests/fixtures/language-features/src/lib.rs b/crates/ide-plugin/tests/fixtures/language-features/src/lib.rs new file mode 100644 index 0000000000..db7190a637 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/language-features/src/lib.rs @@ -0,0 +1,144 @@ +use openidea_plugin::language_features::*; +use openidea_plugin::{ + Diagnostic, Error, Invocation, Location, Plugin, Position, Range, Severity, TextEdit, register_plugin, text, +}; +#[derive(Default)] +struct Fixture { + last: Option, +} +fn range(a: u32, b: u32) -> Range { + Range { start: Position { line: 0, character: a }, end: Position { line: 0, character: b } } +} +impl Plugin for Fixture { + fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result, Error> { + match id { + "run" => { + self.last = arg.map(str::to_owned); + Ok(self.last.clone()) + } + "state" => Ok(self.last.clone()), + _ => Err(Error::NotFound(id.into())), + } + } +} +impl LanguageFeatures for Fixture { + fn format(&mut self, d: &Document, r: Option, _: FormatOptions) -> Result, Error> { + Ok(vec![TextEdit { + range: r.unwrap_or(Range { start: Position::default(), end: text::position(&d.text, d.text.len()) }), + text: "formatted".into(), + }]) + } + fn signature_help(&mut self, _: &Document, _: Position) -> Option { + Some(SignatureHelp { + signatures: vec![Signature { + label: "query(value)".into(), + documentation: Some("Query".into()), + parameters: vec![Parameter { label: ParameterLabel::Text("value".into()), documentation: None }], + }], + active_signature: 0, + active_parameter: 0, + }) + } + fn document_highlights(&mut self, _: &Document, _: Position) -> Vec { + vec![Highlight { range: range(0, 1), kind: "read".into() }] + } + fn document_links(&mut self, _: &Document) -> Vec { + vec![ + DocumentLink { range: range(0, 1), target: "next.txt".into() }, + DocumentLink { range: range(1, 2), target: "https://example.com".into() }, + ] + } + fn code_lenses(&mut self, _: &Document) -> Vec { + vec![ + CodeLens { range: range(0, 1), title: "Run".into(), command: "run".into(), argument: Some("lens".into()) }, + CodeLens { range: range(0, 1), title: "Foreign".into(), command: "foreign".into(), argument: None }, + ] + } + fn selection_ranges(&mut self, _: &Document, _: Position) -> Vec { + vec![range(0, 1), range(0, 5)] + } + fn folding(&mut self, _: &Document) -> Vec { + vec![FoldRange { start_line: 0, end_line: 2, kind: "region".into() }] + } + fn colors(&mut self, _: &Document) -> Vec { + vec![ColorInfo { range: range(0, 1), red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0 }] + } + fn color_presentations(&mut self, d: &Document, _: ColorInfo) -> Vec { + vec![format!("red-{}", d.language), "#ff0000".into()] + } + fn document_symbols(&mut self, _: &Document) -> Vec { + vec![ + DocumentSymbol { + name: "Outer".into(), + detail: "module".into(), + kind: "module".into(), + range: range(0, 5), + selection_range: range(0, 1), + parent: None, + }, + DocumentSymbol { + name: "Inner".into(), + detail: "value".into(), + kind: "variable".into(), + range: range(1, 2), + selection_range: range(1, 2), + parent: Some(0), + }, + ] + } + fn implementation(&mut self, d: &Document, _: Position) -> Vec { + vec![Location { path: d.path.clone(), range: range(1, 2) }] + } + fn type_definition(&mut self, d: &Document, _: Position) -> Vec { + vec![Location { path: d.path.clone(), range: range(2, 3) }] + } + fn gutter_actions(&mut self, _: &Document) -> Vec { + vec![GutterAction { + line: 0, + icon: Some("run".into()), + tooltip: "Run fixture".into(), + command: "run".into(), + argument: Some("gutter".into()), + }] + } +} +impl Injections for Fixture { + fn injections(&mut self, d: &Document) -> Vec { + if d.language == "sql" { + return vec![]; + } + let Some(start) = d.text.find("[[") else { return vec![] }; + let Some(end) = d.text[start + 2..].find("]]") else { return vec![] }; + vec![Injection { + range: Range { start: text::position(&d.text, start + 2), end: text::position(&d.text, start + 2 + end) }, + language: "sql".into(), + }] + } +} +impl openidea_plugin::providers::Providers for Fixture { + fn completion( + &mut self, + d: &Document, + _: Position, + _: Option<&str>, + ) -> Vec { + vec![openidea_plugin::providers::CompletionItem::new( + &format!("{}:{}", d.language, d.text), + openidea_plugin::providers::CompletionKind::Text, + )] + } +} +impl openidea_plugin::hover::HoverProvider for Fixture { + fn hover(&mut self, d: &Document, _: Position) -> Option { + Some(openidea_plugin::hover::Hover::new(format!("{}:{}", d.language, d.text))) + } +} +impl openidea_plugin::diagnostics::DiagnosticsProvider for Fixture { + fn diagnostics(&mut self, d: &Document) -> Vec { + vec![ + Diagnostic::new(range(0, 1), Severity::Warning, "outside"), + Diagnostic::new(range(4, 7), Severity::Warning, format!("{}:{}", d.language, d.text)), + ] + } +} +register_plugin!(Fixture, language_features, injections, providers, hover, diagnostics); diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index d668c0bbe7..3874ce679b 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -867d6182eefeb902cfc500c3f7e9eaaf0e58483acfcc3dcac28c3f032d2a7628 +60835e4d3aeee32df911ed43632fadcdbaae1917df08d36a979168c90290cb76 diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index 18aa9eef76..ed5f70ad8a 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index ce11f4669c..bdb04911b3 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -663c709e7b9da5a97851383f2b47c41eda745b870dc4c770dca0fe092afad4e9 +b5f12f107c7e7f75f22598a954cb4b92b328f23b59b62e50c354d0228c789984 diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 25ac8761d3..16d67f4fbe 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index 9ffd134428..f539a2ed3e 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -18e0bfeacbd6d5b2cb4ec86ff42d0daf7d679134b2be70136abc24b6572b514b +25a64b4b79a0b5af11659ead762b5dc7de9d374fc6df5a30245145da0d622b04 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index 760839aab2..43967f4e3d 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index f029b8e663..aa052be49d 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -413693a2fbb1ad85f5443040bb15e6535572d2aac00cb9f6626dc059ac08137a +c79667d4db55a7f96f0830e256691cc8b19338298a7b1409a1d3974b602b964c diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index 985a7211e3..2789a7f4ae 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index b847bdfd68..5058f689e0 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -46541cd8169abd46eea69185feb2a5c00d6315f9ba22ff15bb357cf058ca0e68 +5372b855970ac2a6c06d5d7943c3cd5c4dca3805c9874b9544f514855cc44c6a diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 6427a09a60..f4f0ebdd03 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index fb39b6fcaa..21c604d9d8 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -a44ecdc63945e57ad99cd1a285b3b5cd7f82b6825dc110273fc9ddff943c9527 +0b8f91288cf06e428a630ecdac9c52189438b5de1944da10bd60e06b62a0cc4f diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index 252818a63b..22aab52381 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index bdf2e5c2c3..60c57d6c8c 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -c0d21fff65bd68e7cb827bdd3436961e5082d2eaa611022ce6ca9fb486e29e3e +126c5356e7c88b8ec7f0e551b91b88042e8ac49f72c498c42d0fbe8ad8255155 diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index 8de9fc9faf..2563e88ef2 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index 331e896b7b..9c7ddc07d7 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -14d881cbad963cc24abf17d9eaddbaa61fa15fa363ddb6951df0439e3341760f +30ebea1d057d45756fe422f3ee112961a6e10627f857a478a427f39c3d6f002c diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index 2841a1d8b6..5bafc38ab3 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 513c081e92..61c9a64b38 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -850f96f66fe3d2872c797dda2100358e0e92ecc7661e447ecb7d71e525ae7958 +288907e6ab2a97d96b7171396d3728c6f682477c35f1d16fb48d83314641337a diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index ecee4deb29..14ac0b08a4 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index 5a0d685aef..490e9d0ee3 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -a56c82dce6035ee8ae2367bc188c05e2d7ad5520ba6c1fb9bf58586b92f5326a +445b3207138eadaf2badab5ab6e78c0f2ca8f62db7537d7e4e8a97bbdac08c7a diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index 3f91cb8e7d..7e64834da0 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index 044802bcea..03efe6d2f4 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -8b1377bb6901a5b8595a5818d997cd8fd7d4287269c54c138032f7de6b44b219 +30a4ad100823e74b7b202acd421220620370a1f33fe185113b7152028301c7af diff --git a/plugins/README.md b/plugins/README.md index 4b98c6d182..add364a704 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -145,6 +145,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `languages` | `path` (`languages/.toml` format, see §6) | no | | `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | | `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | +| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | | `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | | `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | | `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`), `view?`, `command`, `when?` | no | @@ -706,8 +707,7 @@ The referenced icon path is package-relative, up to 256 bytes; both SVGs use the references are rejected during installation. Missing or unknown icons retain the navigation glyph. A marker's optional target still navigates on click. For several cross-file targets, publish document-index mappings; the existing -chooser lists every matching definition. Command clicks are deferred; use a -code action on the same line. +chooser lists every matching definition. Command clicks are available through the API 1.4 `gutter-actions` kind. Document-indexer markers (`Edges.markers`) use a declared icon when their key starts with one of its `markers` prefixes; the longest matching prefix wins, @@ -880,6 +880,124 @@ 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. +#### Additional language features (API 1.4) + +Declare the following kinds under `[[contributes.providers]]`, with +`engines.openidea = "^1.4"`, implement `language_features::LanguageFeatures`, +and register `register_plugin!(MyPlugin, language_features)`: + +| Kind | SDK method | Host policy | +| --------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `formatting` | `format(doc, range, options)` | Settings › Languages & Frameworks › Plugin Formatters selects a plugin per language; it takes precedence over automatic formatters. Explicit external-formatter actions still select that tool. Format Document, Selection and format-on-save share this choice. Uses the 5-second command budget. | +| `signature-help` | `signature_help(doc, at)` | Used when LSP returns no signatures. Parameter labels accept literal text or UTF-16 offsets within the signature label. | +| `document-highlights` | `document_highlights(doc, at)` | Appended to LSP highlights; the LSP wins duplicate ranges. Kinds are `text`, `read`, `write`. | +| `document-links` | `document_links(doc)` | Appended to LSP links, in the same Ctrl/⌘-click UI. Targets are absolute paths, paths relative to the project root, or HTTP(S) URLs. Other URI schemes are ignored. | +| `code-lenses` | `code_lenses(doc)` | Rendered beside LSP and built-in code-vision lenses. Clicks invoke only the returning plugin's declared command. | +| `selection-ranges` | `selection_ranges(doc, at)` | Extend Selection prefers valid plugin ranges, innermost to outermost, then falls back to tree-sitter. | +| `folding` | `folding(doc)` | Merged with tree-sitter folds, deduplicated by start/end lines. Applies to any declared language; `syntax-provider.folding` remains available for a plugin's own languages. | +| `colors` | `colors(doc)`, `color_presentations(doc, color)` | Color Preview shows swatches and the native picker. A presentation replaces the original range; multiple presentations open a chooser. Channels are finite floats in 0–1. | +| `document-symbols` | `document_symbols(doc)` | Structure and breadcrumbs use these only when LSP returns no document symbols (including an empty list); otherwise LSP symbols win. Tree-sitter is the final fallback. | +| `implementation` | `implementation(doc, at)` | Merged with LSP Go to Implementation, deduplicated by location. | +| `type-definition` | `type_definition(doc, at)` | Merged with LSP Go to Type Declaration, deduplicated by location. | +| `gutter-actions` | `gutter_actions(doc)` | Buttons beside line markers. Clicks invoke only the returning plugin's declared command, with its optional string argument and the editor window/project context. Icons accept the same names, aliases and declared marker SVG paths as line markers. | + +The optional WIT interface is `language-features`, in worlds +`plugin-language-features` / `editor-language-features`. Its own `document` +record contains path, language, version and unsaved text. All functions are +present in the interface from its first release, but the host calls only +kinds declared by the plugin. No additional capability is required for the +supplied document; host imports retain their normal permission checks. +Except formatting, these calls use the editor-provider soft/hard budgets. +Missing/unavailable LSP services permit plugin results; other LSP errors +remain errors. + +`document-symbol.parent` is an index in the returned flat list. A parent +must precede its children and contain their ranges; invalid parents become +roots, and outline depth is bounded to 64. Symbol/fold/highlight kinds are +strings so later host versions can recognize new ones. Unknown kinds use +neutral UI defaults. Invalid document ranges are dropped. Each list is +limited to 10,000 items; signature help retains at most 100 signatures and +100 parameters each, presentations at most 100 strings. Text is bounded to +64 KiB per string. Format edits must be valid and non-overlapping. +Disabling a selected formatter reports it as unavailable rather than silently +formatting with another provider. Format-on-save uses the editor's existing +Format on save setting. Native tests can obtain the current unsaved snapshot +with `MockHost::provider_document()` and call the traits directly. + +#### Embedded languages (API 1.4) + +Implement `language_features::Injections`, declare `kinds = ["injections"]` +for the host language, and register `register_plugin!(MyPlugin, injections)`. +The optional `injections` interface has worlds `plugin-injections` / +`language-injections` and returns `{range, language}` entries. Ranges use +host-document UTF-16 coordinates. The editor refreshes them after edits +(300 ms debounce) and highlights each slice using the embedded language's +CodeMirror parser and current color scheme, over the host tokens. + +Completion, hover, diagnostics and additional language features use embedded +languages' **plugin** providers. A virtual document keeps the original path, +version and newlines, replaces text outside all ranges of that language with +spaces, and changes the language id. One space is emitted per UTF-16 unit, +so emoji outside a range do not shift its positions. Point requests ask the +embedded language at the caret before the host language. Document features +filter results to their injected ranges, and diagnostics outside those +ranges are dropped. Completion replacement/additional edits are confined to +the embedded ranges. Ranges are half-open; the end belongs to the host. + +At most 1,000 non-overlapping injection ranges and 32 embedded languages +are routed per document. Earlier ranges in document order win overlaps. +Documents over 2 MiB are excluded. Invalid ranges, self-injections and invalid +language ids are ignored. Injections are not applied recursively. The same +server-side plugin host handles remote editing. **Embedded LSP forwarding is +future host-side work**, not part of 1.4, and needs no WIT change. + +### Snippets (API 1.4) + +Contribution-only or code plugins can package read-only live templates: + +```toml +[[contributes.snippets]] +language = "sql" +path = "snippets/sql.json" +``` + +```json +{ + "Select rows": { + "prefix": ["sel", "select"], + "body": ["SELECT ${1:column}", "FROM ${2:table}$0"], + "description": "Select rows from a table" + } +} +``` + +`prefix` and `body` each accept a string or an array of strings (body lines +join with newlines). Numbered `$1`, `${1:default}` and final `$0` placeholders +use the existing linked live-template fields, in numeric tab order; `\$` +escapes a literal dollar. They appear in completion, Tab expansion and +Settings › Editor › Live Templates, grouped by the plugin name and read-only. +Disabling or removing the plugin removes them. Plugin locales translate +`description`; prefixes and bodies remain code. Installation and +`openidea-plugin check` validate every entry and package path. Limits: 1 MiB +per file, 1,000 named entries, 32 prefixes per entry, 64 KiB per body, 4 KiB +per description. No additional permission or runtime export is needed. + +### Additional menu locations (API 1.4) + +`[[contributes.menus]]` also accepts `editor.title` (the editor tab bar's +actions area), `mainToolbar`, `problems.context` and `searchResults.context`. +The existing `when` clauses apply alongside command enablement. Toolbar +icons use the command's optional API-1.4 `icon`, then the plugin manifest +icon. A command icon may be a built-in icon name or a package SVG path, +validated and bundled at installation. Context menus also support the +existing submenu grouping. + +Commands receive the usual invoking window/project/editor context. For a +problem or search match, `selected-paths` contains its file and the command's +string argument is JSON `{ "path": "…", "line": 0, "column": 0 }`; lines +and columns are zero-based and columns are UTF-16 units. Editor-title and +main-toolbar actions use the focused editor context. + ### Network and secrets `host::fetch` requires `net:` for HTTPS and loopback HTTP. API 1.4 adds diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 3d2ad3c4d0..2f3eac3d2d 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index ab03df14cc..c2fab7e894 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -ff03abdb82800057592e18466292e642ad18f644eab5855993cd67e00850698b +0201ab7c30a7c1df472294507667291d65539d8e8f59083d545f13b929c038f4 diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index a70548890b..f975c8da7f 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index e146254c53..89c1507912 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -6429c38a0dbc856e4b992e4ec80148e75b54a87730c8e1b137169d259f3d6d54 +1be593e19df6e3fb756e9225cd381a237ba0240ffe6ae10493b45cd436c83b9c diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index 0e02d04254..ffb919de4c 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index c6718c0740..7ad6aaf2f9 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -41c3f77d244a40c27a52cd66b1514dea9be0cb6cde85515d72f67cd1b8dabab1 +fd11a873196f91f2bdb27c88bad17c4fce09cad12f08470272becc48268f84ee diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 810facdfc7..ccb8847138 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 907425febe..05e06145d1 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -14f8678dd23d0dd9d6e25b4af27a6d964010eebd5715c6ea8fe49aff91811dbe +70f1044637a86d74c9fb7bd6b7ececb282ea0afcb861083d2eb29fbb9681938c diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index 1351dffe4c..f8ee80f4b5 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index 287dcd0868..5bd62dc252 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -765857e31af345347bda02016f4162e90cd5e3f4fc4d19957d867ea1a0d88b02 +c1d3ec3909a228a721d346d93b53a4662037f7a74ab90c5cf66f2aad34348c0e diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 204ed76f16..9769c4603b 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 6f07058ed3..7905dae6fd 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -f1b38b7bde8db372ef45077db017d2612712bc4ff1d3946136e3b3bc2c197a75 +f0208a96f5cc0fa4057848cb58985d5c595e80cf60c518d4605e6f888bed9bd2 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index feb5b6737d..e653987e7b 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index efb053ad1e..3afab27d93 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -661638c93c0e695bf61b647289cf5f242c5d057fa1ebc176768166053254d364 +0ecac73373cc505a45e52ac50a2cc986445d1f6097df9d85063983aa2ceff78d diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index 21dcd79c08..a363e57fca 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index 9cfc339a16..04f2de4f90 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -ccbfb3bd2f763aaca519947d7205236108201919effd848f7963c850337f0773 +c96b240e9cbdaa11cb052b0fce6baf555dd0be850c270a70db247835a99f4298 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index 8302226294..ddb825bf71 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index 1b465d476b..cb40cd541b 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -d83934c41880875ac20ffa119dba61d9fc04339653df1cbcc2da9f6465360dcf +aba9d413070c12c9eca73163f0de251df23bf6f64ca2e9a373976f688690ec53 diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index fb2578db88..d8dacea0d4 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index fe25189dfb..06fc380a45 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -1f423f8744f7470b43b364ed3b42b283039a3700fa908b7052d163afe9fdb427 +aac77d04d0578745fe0a3a59babefa425b7e759581bde2bd3394aafec9a85c11 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 31d7725f7d..cd997fb58d 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index 7d6641b282..b0505a9c2b 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -4f70b1ec6d7ba5e67d5d49607ba30185cd7c0842b229a732ad6f17bf32ebb24c +57ba1252a0d2dcf1fe1ccf676cd056ed7ac85a3281fbfd5aa726732357ae6bb4 diff --git a/sdk/rust/openidea-plugin/src/language_features.rs b/sdk/rust/openidea-plugin/src/language_features.rs new file mode 100644 index 0000000000..d2fe68e3d9 --- /dev/null +++ b/sdk/rust/openidea-plugin/src/language_features.rs @@ -0,0 +1,347 @@ +//! Optional API 1.4 language features and embedded language ranges. +pub use crate::providers::Document; +use crate::{Error, Location, Position, Range, TextEdit}; +/// A parameter label, as text or UTF-16 offsets within the signature. +#[derive(Clone, Debug, PartialEq)] +pub enum ParameterLabel { + Text(String), + Offsets((u32, u32)), +} +/// FormatOptions data. +#[derive(Clone, Debug, PartialEq)] +pub struct FormatOptions { + pub tab_size: u32, + pub insert_spaces: bool, +} +/// Parameter data. +#[derive(Clone, Debug, PartialEq)] +pub struct Parameter { + pub label: ParameterLabel, + pub documentation: Option, +} +/// Signature data. +#[derive(Clone, Debug, PartialEq)] +pub struct Signature { + pub label: String, + pub documentation: Option, + pub parameters: Vec, +} +/// SignatureHelp data. +#[derive(Clone, Debug, PartialEq)] +pub struct SignatureHelp { + pub signatures: Vec, + pub active_signature: u32, + pub active_parameter: u32, +} +/// Highlight data. +#[derive(Clone, Debug, PartialEq)] +pub struct Highlight { + pub range: Range, + pub kind: String, +} +/// DocumentLink data. +#[derive(Clone, Debug, PartialEq)] +pub struct DocumentLink { + pub range: Range, + pub target: String, +} +/// CodeLens data. +#[derive(Clone, Debug, PartialEq)] +pub struct CodeLens { + pub range: Range, + pub title: String, + pub command: String, + pub argument: Option, +} +/// FoldRange data. +#[derive(Clone, Debug, PartialEq)] +pub struct FoldRange { + pub start_line: u32, + pub end_line: u32, + pub kind: String, +} +/// ColorInfo data. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorInfo { + pub range: Range, + pub red: f32, + pub green: f32, + pub blue: f32, + pub alpha: f32, +} +/// DocumentSymbol data. +#[derive(Clone, Debug, PartialEq)] +pub struct DocumentSymbol { + pub name: String, + pub detail: String, + pub kind: String, + pub range: Range, + pub selection_range: Range, + pub parent: Option, +} +/// GutterAction data. +#[derive(Clone, Debug, PartialEq)] +pub struct GutterAction { + pub line: u32, + pub icon: Option, + pub tooltip: String, + pub command: String, + pub argument: Option, +} +/// Injection data. +#[derive(Clone, Debug, PartialEq)] +pub struct Injection { + pub range: Range, + pub language: String, +} +/// Implement only the kinds declared under contributes.providers. +pub trait LanguageFeatures { + fn format( + &mut self, + _doc: &Document, + _range: Option, + _options: FormatOptions, + ) -> Result, Error> { + Ok(Vec::new()) + } + fn signature_help(&mut self, _doc: &Document, _at: Position) -> Option { + None + } + fn document_highlights(&mut self, _doc: &Document, _at: Position) -> Vec { + Vec::new() + } + fn document_links(&mut self, _doc: &Document) -> Vec { + Vec::new() + } + fn code_lenses(&mut self, _doc: &Document) -> Vec { + Vec::new() + } + fn selection_ranges(&mut self, _doc: &Document, _at: Position) -> Vec { + Vec::new() + } + fn folding(&mut self, _doc: &Document) -> Vec { + Vec::new() + } + fn colors(&mut self, _doc: &Document) -> Vec { + Vec::new() + } + fn color_presentations(&mut self, _doc: &Document, _color: ColorInfo) -> Vec { + Vec::new() + } + fn document_symbols(&mut self, _doc: &Document) -> Vec { + Vec::new() + } + fn implementation(&mut self, _doc: &Document, _at: Position) -> Vec { + Vec::new() + } + fn type_definition(&mut self, _doc: &Document, _at: Position) -> Vec { + Vec::new() + } + fn gutter_actions(&mut self, _doc: &Document) -> Vec { + Vec::new() + } +} +/// Identifies embedded ranges in a host document. +pub trait Injections { + fn injections(&mut self, doc: &Document) -> Vec; +} + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod wasm { + use super::*; + use crate::bindings::openidea::plugin::types as b; + use crate::injections_bindings::exports::openidea::plugin::injections as wi; + use crate::language_features_bindings::exports::openidea::plugin::language_features as w; + fn format_options_from(v: w::FormatOptions) -> FormatOptions { + FormatOptions { tab_size: v.tab_size, insert_spaces: v.insert_spaces } + } + fn parameter_to(v: Parameter) -> w::Parameter { + w::Parameter { label: parameter_label_to(v.label), documentation: v.documentation } + } + fn signature_to(v: Signature) -> w::Signature { + w::Signature { + label: v.label, + documentation: v.documentation, + parameters: v.parameters.into_iter().map(parameter_to).collect(), + } + } + fn signature_help_to(v: SignatureHelp) -> w::SignatureHelpResult { + w::SignatureHelpResult { + signatures: v.signatures.into_iter().map(signature_to).collect(), + active_signature: v.active_signature, + active_parameter: v.active_parameter, + } + } + fn highlight_to(v: Highlight) -> w::Highlight { + w::Highlight { range: crate::host::__range_to(v.range), kind: v.kind } + } + fn document_link_to(v: DocumentLink) -> w::DocumentLink { + w::DocumentLink { range: crate::host::__range_to(v.range), target: v.target } + } + fn code_lens_to(v: CodeLens) -> w::CodeLens { + w::CodeLens { + range: crate::host::__range_to(v.range), + title: v.title, + command: v.command, + argument: v.argument, + } + } + fn fold_range_to(v: FoldRange) -> w::FoldRange { + w::FoldRange { start_line: v.start_line, end_line: v.end_line, kind: v.kind } + } + fn color_info_to(v: ColorInfo) -> w::ColorInfo { + w::ColorInfo { + range: crate::host::__range_to(v.range), + red: v.red, + green: v.green, + blue: v.blue, + alpha: v.alpha, + } + } + fn color_info_from(v: w::ColorInfo) -> ColorInfo { + ColorInfo { + range: crate::host::__range_from(v.range), + red: v.red, + green: v.green, + blue: v.blue, + alpha: v.alpha, + } + } + fn document_symbol_to(v: DocumentSymbol) -> w::DocumentSymbol { + w::DocumentSymbol { + name: v.name, + detail: v.detail, + kind: v.kind, + range: crate::host::__range_to(v.range), + selection_range: crate::host::__range_to(v.selection_range), + parent: v.parent, + } + } + fn gutter_action_to(v: GutterAction) -> w::GutterAction { + w::GutterAction { line: v.line, icon: v.icon, tooltip: v.tooltip, command: v.command, argument: v.argument } + } + fn parameter_label_to(v: ParameterLabel) -> w::ParameterLabel { + match v { + ParameterLabel::Text(t) => w::ParameterLabel::Text(t), + ParameterLabel::Offsets(t) => w::ParameterLabel::Offsets(t), + } + } + pub fn format( + d: w::Document, + range: Option, + options: w::FormatOptions, + ) -> Result, b::Error> { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| { + p.format(&doc, range.map(|v| crate::host::__range_from(v)), format_options_from(options)) + }); + result + .map(|result| { + result + .into_iter() + .map(|v| b::TextEdit { range: crate::host::__range_to(v.range), text: v.text }) + .collect() + }) + .map_err(|e| match e { + Error::Denied(s) => b::Error::Denied(s), + Error::Stale => b::Error::Stale, + Error::NotFound(s) => b::Error::NotFound(s), + Error::Invalid(s) => b::Error::Invalid(s), + Error::Cancelled => b::Error::Cancelled, + Error::Failed(s) => b::Error::Failed(s), + }) + } + pub fn signature_help( + d: w::Document, + at: b::Position, + ) -> Option { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = + crate::__rt::with::(|p| p.signature_help(&doc, Position { line: at.line, character: at.character })); + result.map(signature_help_to) + } + pub fn document_highlights( + d: w::Document, + at: b::Position, + ) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| { + p.document_highlights(&doc, Position { line: at.line, character: at.character }) + }); + result.into_iter().map(highlight_to).collect() + } + pub fn document_links(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.document_links(&doc)); + result.into_iter().map(document_link_to).collect() + } + pub fn code_lenses(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.code_lenses(&doc)); + result.into_iter().map(code_lens_to).collect() + } + pub fn selection_ranges( + d: w::Document, + at: b::Position, + ) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| { + p.selection_ranges(&doc, Position { line: at.line, character: at.character }) + }); + result.into_iter().map(|v| crate::host::__range_to(v)).collect() + } + pub fn folding(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.folding(&doc)); + result.into_iter().map(fold_range_to).collect() + } + pub fn colors(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.colors(&doc)); + result.into_iter().map(color_info_to).collect() + } + pub fn color_presentations( + d: w::Document, + color: w::ColorInfo, + ) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.color_presentations(&doc, color_info_from(color))); + result.into_iter().collect() + } + pub fn document_symbols(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.document_symbols(&doc)); + result.into_iter().map(document_symbol_to).collect() + } + pub fn implementation( + d: w::Document, + at: b::Position, + ) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = + crate::__rt::with::(|p| p.implementation(&doc, Position { line: at.line, character: at.character })); + result.into_iter().map(|v| b::Location { path: v.path, range: crate::host::__range_to(v.range) }).collect() + } + pub fn type_definition( + d: w::Document, + at: b::Position, + ) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = + crate::__rt::with::(|p| p.type_definition(&doc, Position { line: at.line, character: at.character })); + result.into_iter().map(|v| b::Location { path: v.path, range: crate::host::__range_to(v.range) }).collect() + } + pub fn gutter_actions(d: w::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + let result = crate::__rt::with::(|p| p.gutter_actions(&doc)); + result.into_iter().map(gutter_action_to).collect() + } + pub fn injections(d: wi::Document) -> Vec { + let doc = Document { path: d.path, language: d.language, version: d.version, text: d.text }; + crate::__rt::with::(|p| p.injections(&doc)) + .into_iter() + .map(|i| wi::Injection { range: crate::host::__range_to(i.range), language: i.language }) + .collect() + } +} diff --git a/sdk/rust/openidea-plugin/src/lib.rs b/sdk/rust/openidea-plugin/src/lib.rs index 8d337bdcec..39b3fd5fbf 100644 --- a/sdk/rust/openidea-plugin/src/lib.rs +++ b/sdk/rust/openidea-plugin/src/lib.rs @@ -286,6 +286,8 @@ macro_rules! register_plugin { #[doc(hidden)] #[macro_export] macro_rules! __optional_exports { + (injections, $plugin:ty, $component:ident) => { $crate::__injections_exports!($plugin, $component); }; + (language_features, $plugin:ty, $component:ident) => { $crate::__language_features_exports!($plugin, $component); }; (run_configurations, $plugin:ty, $component:ident) => { $crate::__run_configurations_exports!($plugin, $component); }; (test_results, $plugin:ty, $component:ident) => { $crate::__test_results_exports!($plugin, $component); }; @@ -656,7 +658,7 @@ pub mod __rt { static INSTANCE: RefCell>> = const { RefCell::new(None) }; } - fn with(f: impl FnOnce(&mut T) -> R) -> R { + pub(crate) fn with(f: impl FnOnce(&mut T) -> R) -> R { INSTANCE.with(|cell| { let mut slot = cell.borrow_mut(); let plugin = slot.get_or_insert_with(|| Box::new(T::default())); @@ -1313,3 +1315,62 @@ macro_rules! __test_results_exports { $crate::test_results_bindings::__export_tests_world!($component with_types_in $crate::test_results_bindings); }; } + +pub mod language_features; + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod language_features_bindings { + wit_bindgen::generate!({world: "editor-language-features", path: "wit", pub_export_macro: true, + export_macro_name: "__export_language_features_world", default_bindings_module: "openidea_plugin::language_features_bindings", + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, + }); +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __language_features_exports { + ($plugin:ty, $component:ident) => { + impl $crate::language_features_bindings::exports::openidea::plugin::language_features::Guest for $component { +fn format(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, range: Option<$crate::bindings::openidea::plugin::types::Range>, options: $crate::language_features_bindings::exports::openidea::plugin::language_features::FormatOptions) -> Result, $crate::bindings::openidea::plugin::types::Error> { $crate::language_features::wasm::format::<$plugin>(doc, range, options) } +fn signature_help(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, at: $crate::bindings::openidea::plugin::types::Position) -> Option<$crate::language_features_bindings::exports::openidea::plugin::language_features::SignatureHelpResult> { $crate::language_features::wasm::signature_help::<$plugin>(doc, at) } +fn document_highlights(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, at: $crate::bindings::openidea::plugin::types::Position) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::Highlight> { $crate::language_features::wasm::document_highlights::<$plugin>(doc, at) } +fn document_links(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::DocumentLink> { $crate::language_features::wasm::document_links::<$plugin>(doc) } +fn code_lenses(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::CodeLens> { $crate::language_features::wasm::code_lenses::<$plugin>(doc) } +fn selection_ranges(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, at: $crate::bindings::openidea::plugin::types::Position) -> Vec<$crate::bindings::openidea::plugin::types::Range> { $crate::language_features::wasm::selection_ranges::<$plugin>(doc, at) } +fn folding(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::FoldRange> { $crate::language_features::wasm::folding::<$plugin>(doc) } +fn colors(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::ColorInfo> { $crate::language_features::wasm::colors::<$plugin>(doc) } +fn color_presentations(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, color: $crate::language_features_bindings::exports::openidea::plugin::language_features::ColorInfo) -> Vec { $crate::language_features::wasm::color_presentations::<$plugin>(doc, color) } +fn document_symbols(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::DocumentSymbol> { $crate::language_features::wasm::document_symbols::<$plugin>(doc) } +fn implementation(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, at: $crate::bindings::openidea::plugin::types::Position) -> Vec<$crate::bindings::openidea::plugin::types::Location> { $crate::language_features::wasm::implementation::<$plugin>(doc, at) } +fn type_definition(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document, at: $crate::bindings::openidea::plugin::types::Position) -> Vec<$crate::bindings::openidea::plugin::types::Location> { $crate::language_features::wasm::type_definition::<$plugin>(doc, at) } +fn gutter_actions(doc: $crate::language_features_bindings::exports::openidea::plugin::language_features::Document) -> Vec<$crate::language_features_bindings::exports::openidea::plugin::language_features::GutterAction> { $crate::language_features::wasm::gutter_actions::<$plugin>(doc) } + } + $crate::language_features_bindings::__export_language_features_world!($component with_types_in $crate::language_features_bindings); + }; +} + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod injections_bindings { + wit_bindgen::generate!({world: "language-injections", path: "wit", pub_export_macro: true, + export_macro_name: "__export_injections_world", default_bindings_module: "openidea_plugin::injections_bindings", + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, + }); +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __injections_exports { + ($plugin:ty, $component:ident) => { + impl $crate::injections_bindings::exports::openidea::plugin::injections::Guest for $component { +fn injections(doc: $crate::injections_bindings::exports::openidea::plugin::injections::Document) -> Vec<$crate::injections_bindings::exports::openidea::plugin::injections::Injection> { $crate::language_features::wasm::injections::<$plugin>(doc) } + } + $crate::injections_bindings::__export_injections_world!($component with_types_in $crate::injections_bindings); + }; +} + +/// Embedded-language range providers (API 1.4). +pub mod injections { + pub use crate::language_features::{Document, Injection, Injections}; +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index edd5126ca5..ab7d64f9d7 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -440,6 +440,16 @@ impl MockHost { self.state.borrow().diagnostics.clone() } + /// Snapshot supplied to optional language-feature and injection traits in native tests. + pub fn provider_document(&self) -> Option { + self.state.borrow().editor.as_ref().map(|e| crate::providers::Document { + path: e.path.clone(), + language: e.language.clone(), + version: e.version, + text: e.text.clone(), + }) + } + /// Runs a diagnostics provider against the current mock editor snapshot. /// This explicit call replaces the real host's debounce; it needs no capability. pub fn refresh_diagnostics(&self, provider: &mut impl crate::diagnostics::DiagnosticsProvider) { diff --git a/sdk/rust/openidea-plugin/tests/api14_stage4.rs b/sdk/rust/openidea-plugin/tests/api14_stage4.rs new file mode 100644 index 0000000000..418e2972fb --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api14_stage4.rs @@ -0,0 +1,39 @@ +use openidea_plugin::{Position, Range, language_features::*, mock::MockHost}; +struct Features; +impl LanguageFeatures for Features { + fn signature_help(&mut self, d: &Document, _: Position) -> Option { + Some(SignatureHelp { + signatures: vec![Signature { + label: d.text.clone(), + documentation: None, + parameters: vec![Parameter { + label: ParameterLabel::Offsets((0, 2)), + documentation: Some(d.language.clone()), + }], + }], + active_signature: 0, + active_parameter: 0, + }) + } +} +impl Injections for Features { + fn injections(&mut self, _: &Document) -> Vec { + vec![Injection { + range: Range { start: Position::default(), end: Position { line: 0, character: 2 } }, + language: "sql".into(), + }] + } +} +#[test] +fn optional_traits_use_the_unsaved_mock_snapshot_without_extra_capabilities() { + let host = MockHost::install().with_capabilities(&[]); + host.open_editor("/project/a.txt", "text", "😀", &[]); + host.type_in_editor(" SELECT"); + let doc = host.provider_document().unwrap(); + assert_eq!(doc.version, 2); + let mut provider = Features; + assert_eq!(provider.signature_help(&doc, Position::default()).unwrap().signatures[0].label, "😀 SELECT"); + assert_eq!(provider.injections(&doc)[0].range.end.character, 2); + assert!(provider.document_links(&doc).is_empty()); + assert!(provider.format(&doc, None, FormatOptions { tab_size: 4, insert_spaces: true }).unwrap().is_empty()); +} diff --git a/sdk/rust/openidea-plugin/wit/injections.wit b/sdk/rust/openidea-plugin/wit/injections.wit new file mode 100644 index 0000000000..5f9d7c2eb8 --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/injections.wit @@ -0,0 +1,12 @@ +package openidea:plugin@1.4.0; + +/// Embedded languages. This host routes plugin providers, not embedded LSP servers. +interface injections { + /// A versioned document snapshot. Coordinates are zero-based UTF-16. + record document { path: string, language: string, version: u64, text: string } + /// A host-document range containing the named language. + record injection { range: range, language: string } + use types.{range}; + /// Embedded ranges, refreshed after edits under the editor-provider budget. + injections: func(doc: document) -> list; +} diff --git a/sdk/rust/openidea-plugin/wit/language-features.wit b/sdk/rust/openidea-plugin/wit/language-features.wit new file mode 100644 index 0000000000..c47c4b621d --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/language-features.wit @@ -0,0 +1,114 @@ +package openidea:plugin@1.4.0; + +/// Additional language features, called only for declared API 1.4 provider kinds. +/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds. +interface language-features { + use types.{error, position, range, text-edit, location}; + /// A versioned document snapshot. Coordinates are zero-based UTF-16. + record document { + path: string, + language: string, + version: u64, + text: string, + } + /// A parameter label, either literal text or UTF-16 offsets within the signature label. + variant parameter-label { text(string), offsets(tuple) } + /// Indentation options selected by the editor. + record format-options { + tab-size: u32, + insert-spaces: bool, + } + /// One parameter, with optional Markdown documentation. + record parameter { + label: parameter-label, + documentation: option, + } + /// One callable signature; documentation is Markdown. + record signature { + label: string, + documentation: option, + parameters: list, + } + /// Callable signatures and zero-based active signature/parameter indices. + record signature-help-result { + signatures: list, + active-signature: u32, + active-parameter: u32, + } + /// An occurrence of the symbol. Kind: text, read or write; unknown is text. + record highlight { + range: range, + kind: string, + } + /// An absolute path, project-relative path or HTTP(S) URL to follow on click. + record document-link { + range: range, + target: string, + } + /// An inline action. Command must be this plugin's declared command id. + record code-lens { + range: range, + title: string, + command: string, + argument: option, + } + /// A multi-line fold. Kinds: region, comment or imports; unknown is region. + record fold-range { + start-line: u32, + end-line: u32, + kind: string, + } + /// A color literal. All channels are finite floats in the inclusive range 0–1. + record color-info { + range: range, + red: f32, + green: f32, + blue: f32, + alpha: f32, + } + /// An outline node. Parent indexes this list, precedes the child and contains it. + /// Kinds are LSP-style names (e.g. class, method, enum-member); unknown is neutral. + record document-symbol { + name: string, + detail: string, + kind: string, + range: range, + selection-range: range, + parent: option, + } + /// A line action for this plugin's own declared command. Icons follow line-marker + /// aliases, registered icon names or declared manifest marker SVG paths. + record gutter-action { + line: u32, + icon: option, + tooltip: string, + command: string, + argument: option, + } + /// Format the whole document or the selected range. + format: func(doc: document, range: option, options: format-options) -> result, error>; + /// Signature help when the language server has no signatures. + signature-help: func(doc: document, at: position) -> option; + /// Occurrences at the caret, appended to language-server highlights. + document-highlights: func(doc: document, at: position) -> list; + /// Navigable ranges, appended to language-server document links. + document-links: func(doc: document) -> list; + /// Clicks run only this plugin's declared commands. + code-lenses: func(doc: document) -> list; + /// Nested ranges, innermost to outermost. + selection-ranges: func(doc: document, at: position) -> list; + /// Folds to merge with tree-sitter, for any declared language. + folding: func(doc: document) -> list; + /// Color literals to show in the existing color-preview gutter and picker. + colors: func(doc: document) -> list; + /// Replacement strings for the selected color range. + color-presentations: func(doc: document, color: color-info) -> list; + /// Used only when no LSP document symbols are available. + document-symbols: func(doc: document) -> list; + /// Implementation locations, merged with language-server results. + implementation: func(doc: document, at: position) -> list; + /// Type-declaration locations, merged with language-server results. + type-definition: func(doc: document, at: position) -> list; + /// Clicks run only this plugin's declared commands. + gutter-actions: func(doc: document) -> list; +} diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index ffe202a3f1..7f55e7ce70 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -184,3 +184,12 @@ world configurations-provider { export run-configurations; } world plugin-test-results { include plugin; export test-results; } /// Export-only test parser world, composed with plugin by SDK macros. world test-results-provider { export test-results; } + +/// A plugin with additional API 1.4 language features. +world plugin-language-features { include plugin; export language-features; } +/// Export-only language features, composed with the base plugin world. +world editor-language-features { export language-features; } +/// A plugin that identifies embedded language ranges. +world plugin-injections { include plugin; export injections; } +/// Export-only injections, composed with the base plugin world. +world language-injections { export injections; } diff --git a/src-tauri/src/commands/lsp.rs b/src-tauri/src/commands/lsp.rs index 14a51a69fc..baf2cdc6f7 100644 --- a/src-tauri/src/commands/lsp.rs +++ b/src-tauri/src/commands/lsp.rs @@ -460,3 +460,29 @@ pub async fn lsp_execute_code_action( ) -> IdeResult> { ide_host::ops::lsp::lsp_execute_code_action(&state.host, window.label(), request, doc, action, answers).await } + +#[tauri::command] +#[specta::specta] +pub async fn plugin_language_visuals( + window: Window, + state: State<'_, AppState>, + doc: DocId, +) -> IdeResult { + ide_host::ops::lsp::plugin_language_visuals(&state.host, window.label(), doc).await +} +#[tauri::command] +#[specta::specta] +pub async fn plugin_color_presentations( + window: Window, + state: State<'_, AppState>, + doc: DocId, + plugin: String, + color: ide_plugin::language_features::ColorInfo, +) -> IdeResult> { + ide_host::ops::lsp::plugin_color_presentations(&state.host, window.label(), doc, plugin, color).await +} +#[tauri::command] +#[specta::specta] +pub fn plugin_formatters() -> IdeResult> { + Ok(ide_host::ops::lsp::plugin_formatters()) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 0a6be2d74c..bcfc8a1e4a 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -224,6 +224,9 @@ pub fn builder() -> tauri_specta::Builder { search::replace_in_files, search::replace_preview, search::search_validate, + lsp::plugin_language_visuals, + lsp::plugin_color_presentations, + lsp::plugin_formatters, lsp::lsp_completion, lsp::lsp_inline_completion, lsp::lsp_resolve_completion, diff --git a/src/bindings.ts b/src/bindings.ts index 1aff1f41e6..813d89fcdf 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -407,6 +407,9 @@ export const commands = { replacePreview: (query: SearchQuery, replacement: string, preserveCase: boolean, path: string, only: Pos[] | null) => typedError(__TAURI_INVOKE("replace_preview", { query, replacement, preserveCase, path, only })), /** Validates a query (e.g. regex syntax) while the user types. */ searchValidate: (query: SearchQuery) => typedError(__TAURI_INVOKE("search_validate", { query })), + pluginLanguageVisuals: (doc: DocId) => typedError(__TAURI_INVOKE("plugin_language_visuals", { doc })), + pluginColorPresentations: (doc: DocId, plugin: string, color: ColorInfo) => typedError(__TAURI_INVOKE("plugin_color_presentations", { doc, plugin, color })), + pluginFormatters: () => typedError(__TAURI_INVOKE("plugin_formatters")), lspCompletion: (request: RequestId, doc: DocId, pos: Pos, trigger: string | null) => typedError(__TAURI_INVOKE("lsp_completion", { request, doc, pos, trigger })), /** Inline (ghost text) suggestions at `pos`; `automatic` when triggered by typing. */ lspInlineCompletion: (request: RequestId, doc: DocId, pos: Pos, automatic: boolean) => typedError(__TAURI_INVOKE("lsp_inline_completion", { request, doc, pos, automatic })), @@ -2449,6 +2452,15 @@ export type CodeStyleSettings_Serialize = { formatterTagsRegexp: boolean, }; +/** ColorInfo data. */ +export type ColorInfo = { + range: Range, + red: number | null, + green: number | null, + blue: number | null, + alpha: number | null, +}; + export type Command = { title: string, command: string, @@ -4228,6 +4240,12 @@ export type FormatOptions = { tool?: ExternalFormatter | null, }; +export type FormatterChoice = { + id: string, + name: string, + languages: string[], +}; + /** A port of the remote host reachable on this machine at `localhost:local_port`. */ export type ForwardedPort = { remotePort: number, @@ -4501,6 +4519,15 @@ export type GradleTask = { description: string | null, }; +/** GutterAction data. */ +export type GutterAction = { + line: number, + icon: string | null, + tooltip: string, + command: string, + argument: string | null, +}; + /** HEAD before and after a history rewrite, for its Undo. */ export type HeadChange = { before: string, @@ -4847,6 +4874,12 @@ export type IndexedMarker = { icon: string | null, }; +/** Injection data. */ +export type Injection = { + range: Range, + language: string, +}; + export type InlayHint = { position: Pos, label: string, @@ -5342,6 +5375,8 @@ export type LanguageServerSettings_Serialize = { }; export type LanguagesSettings = { + /** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */ + pluginFormatters?: { [key in string]: string }, python?: PythonSettings, node?: NodeSettings, php?: PhpSettings, @@ -6462,6 +6497,17 @@ export type PluginInfo = { previousVersion: string | null, }; +/** + * Commands of this module the remote server answers. + * Versioned plugin visuals, refreshed after the editor synchronizes its buffer. + */ +export type PluginLanguageVisuals = { + version: number, + injections: Injection[], + colors: ([string, ColorInfo])[], + gutterActions: ([string, GutterAction])[], +}; + export type PluginLocation = { path: string, range: Range, diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 13e22533df..cbf6f73543 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -1,3 +1,4 @@ +import { ContributedToolbar } from "@/workbench/ContributedToolbar"; import { useFilePresentationIcons } from "@/platform/filePresentation"; /** * The editor area: split layout of panes, each with IDEA-style tabs (preview @@ -474,6 +475,7 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) { const moreRef = useRef(null); return (
+ {LayoutActions && } }>(); +export function pluginVisuals(view: EditorView, ctx: EditorDocContext): Promise { + const text = view.state.doc; + const epoch = navigationEpoch(); + const cached = pending.get(text); + if (cached?.epoch === epoch && cached.doc === ctx.doc) return cached.value; + const value = whenSynced(view).then(() => call(commands.pluginLanguageVisuals(ctx.doc))); + pending.set(text, { epoch, doc: ctx.doc, value }); + return value; +} diff --git a/src/editor/lsp/serverCodeLens.test.ts b/src/editor/lsp/serverCodeLens.test.ts new file mode 100644 index 0000000000..7d554e6b56 --- /dev/null +++ b/src/editor/lsp/serverCodeLens.test.ts @@ -0,0 +1,40 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { codeLenses } from "@/editor/api"; +const ipc = vi.hoisted(() => ({ + lspCodeLens: vi.fn(), + lspExecuteCommand: vi.fn(async () => ({ status: "ok", data: null })), +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: { ...(await original()).commands, ...ipc }, +})); +const { serverCodeLenses } = await import("./serverCodeLens"); +const views: EditorView[] = []; +afterEach(() => { + views.splice(0).forEach((v) => v.destroy()); + vi.useRealTimers(); + vi.clearAllMocks(); +}); +it("renders LSP and plugin lens commands in the shared facet and invokes their commands", async () => { + vi.useFakeTimers(); + const command = { title: "Run fixture", command: "openidea.plugin-language:p:run", arguments: ['"lens"'] }; + ipc.lspCodeLens.mockResolvedValue({ + status: "ok", + data: [{ range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } }, command }], + }); + const view = new EditorView({ + state: EditorState.create({ + doc: "x", + extensions: serverCodeLenses({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }), + }), + parent: document.body, + }); + views.push(view); + await vi.advanceTimersByTimeAsync(400); + const lenses = view.state.facet(codeLenses); + expect(lenses.map((l) => l.title)).toEqual(["Run fixture"]); + lenses[0]!.run!(view, new MouseEvent("click")); + expect(ipc.lspExecuteCommand).toHaveBeenCalledWith(1, command); +}); diff --git a/src/editor/lsp/serverCodeLens.ts b/src/editor/lsp/serverCodeLens.ts new file mode 100644 index 0000000000..c7ed3d7c74 --- /dev/null +++ b/src/editor/lsp/serverCodeLens.ts @@ -0,0 +1,81 @@ +/** Language-server and plugin lenses in the shared editor code-vision renderer. */ +import { StateEffect, StateField, type Extension } from "@codemirror/state"; +import { ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { codeLenses, whenSynced, type CodeLens, type EditorDocContext } from "@/editor/api"; +import { call, commands } from "@/platform/ipc"; +import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; +import { posToOffset } from "./positions"; +import { onLspRefresh, onServerSettled } from "./availability"; +const set = StateEffect.define(); +const field = StateField.define({ + create: () => [], + update(value, tr) { + for (const e of tr.effects) if (e.is(set)) return e.value; + return tr.docChanged ? [] : value; + }, + provide: (f) => codeLenses.from(f), +}); +export function serverCodeLenses(ctx: EditorDocContext): Extension { + if (ctx.doc < 0) return []; + return [ + field, + ViewPlugin.define( + (view) => + new (class { + timer: ReturnType | undefined; + generation = 0; + off: () => void; + constructor() { + const offs = [ + onNavigationProvidersChanged(() => this.schedule()), + onLspRefresh("codeLens", () => this.schedule()), + onServerSettled(() => this.schedule()), + ]; + this.off = () => offs.forEach((f) => f()); + this.schedule(); + } + schedule() { + this.generation++; + clearTimeout(this.timer); + this.timer = setTimeout(() => void this.run(), 400); + } + update(u: ViewUpdate) { + if (u.docChanged) this.schedule(); + } + async run() { + const gen = this.generation; + const text = view.state.doc; + try { + await whenSynced(view); + const result = await call(commands.lspCodeLens(ctx.doc)); + if (gen !== this.generation || text !== view.state.doc || !view.dom.isConnected) return; + view.dispatch({ + effects: set.of( + result.flatMap((l) => + l.command + ? [ + { + pos: posToOffset(text, l.range.start), + title: l.command.title, + run: () => { + void call(commands.lspExecuteCommand(ctx.doc, l.command!)).catch(console.warn); + }, + }, + ] + : [], + ), + ), + }); + } catch { + if (gen === this.generation && view.dom.isConnected) view.dispatch({ effects: set.of([]) }); + } + } + destroy() { + this.generation++; + clearTimeout(this.timer); + this.off(); + } + })(), + ), + ]; +} diff --git a/src/features/code-insight/ProblemsView.tsx b/src/features/code-insight/ProblemsView.tsx index abcde0838a..924368e143 100644 --- a/src/features/code-insight/ProblemsView.tsx +++ b/src/features/code-insight/ProblemsView.tsx @@ -1,3 +1,4 @@ +import { menuGroupItems } from "@/workbench/contributions"; /** Problems tool window: "File" (current editor) and "Project Errors" tabs. */ import { useCallback, useMemo, useRef, useState, type KeyboardEvent } from "react"; import { create } from "zustand"; @@ -387,6 +388,7 @@ export function ProblemsView() { run: () => copy(n), }, ...inspectionMenu(n.kind === "diag" ? diagInspection(map, n.path, n.d) : null), + ...menuGroupItems("problems", { paths: [t.path], line: t.d.range.start.line, column: t.d.range.start.col }), ]); }} activateExpandable={false} diff --git a/src/features/color-preview/index.ts b/src/features/color-preview/index.ts index 834401bd30..5528249675 100644 --- a/src/features/color-preview/index.ts +++ b/src/features/color-preview/index.ts @@ -1,7 +1,12 @@ /** Color swatches in the editor gutter for color literals (Settings › Editor › General › Gutter Icons). */ import { registerEditorContribution } from "@/editor/api"; +import { pluginColorPreview } from "./pluginColors"; import { colorPreviewGutter } from "./gutter"; export function activate(): () => void { - return registerEditorContribution({ id: "colorPreview.gutter", order: 59, extensions: colorPreviewGutter }); + return registerEditorContribution({ + id: "colorPreview.gutter", + order: 59, + extensions: (ctx) => [colorPreviewGutter(ctx), pluginColorPreview(ctx)], + }); } diff --git a/src/features/color-preview/pluginColors.test.ts b/src/features/color-preview/pluginColors.test.ts new file mode 100644 index 0000000000..ce093d3528 --- /dev/null +++ b/src/features/color-preview/pluginColors.test.ts @@ -0,0 +1,55 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +const ipc = vi.hoisted(() => ({ + pluginLanguageVisuals: vi.fn(), + pluginColorPresentations: vi.fn(async () => ({ status: "ok", data: ["red"] })), +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: ipc, +})); +const { pluginColorPreview } = await import("./pluginColors"); +const views: EditorView[] = []; +afterEach(() => { + views.splice(0).forEach((v) => v.destroy()); + vi.useRealTimers(); + vi.clearAllMocks(); + document.querySelectorAll('input[type="color"]').forEach((n) => n.remove()); +}); +it("uses plugin presentations to replace precisely the reported range", async () => { + vi.useFakeTimers(); + Object.defineProperty(HTMLInputElement.prototype, "showPicker", { value: vi.fn(), configurable: true }); + ipc.pluginLanguageVisuals.mockResolvedValue({ + status: "ok", + data: { + version: 1, + injections: [], + gutterActions: [], + colors: [ + ["p", { range: { start: { line: 0, col: 1 }, end: { line: 0, col: 2 } }, red: 1, green: 0, blue: 0, alpha: 1 }], + ], + }, + }); + const view = new EditorView({ + state: EditorState.create({ + doc: "xyz", + extensions: pluginColorPreview({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }), + }), + parent: document.body, + }); + views.push(view); + await vi.advanceTimersByTimeAsync(300); + const swatch = view.dom.querySelector("button")!; + swatch.click(); + const picker = document.querySelector('input[type="color"]')!; + picker.value = "#00ff00"; + picker.dispatchEvent(new Event("change")); + await vi.advanceTimersByTimeAsync(0); + expect(view.state.doc.toString()).toBe("xredz"); + expect(ipc.pluginColorPresentations).toHaveBeenCalledWith( + 1, + "p", + expect.objectContaining({ red: 0, green: 1, blue: 0, alpha: 1 }), + ); +}); diff --git a/src/features/color-preview/pluginColors.ts b/src/features/color-preview/pluginColors.ts new file mode 100644 index 0000000000..afc1f4dcc3 --- /dev/null +++ b/src/features/color-preview/pluginColors.ts @@ -0,0 +1,153 @@ +/** Plugin colors use the same native picker and provider-supplied replacement strings. */ +import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state"; +import { GutterMarker, ViewPlugin, gutter, type EditorView, type ViewUpdate } from "@codemirror/view"; +import { type EditorDocContext } from "@/editor/api"; +import { rangeToOffsets } from "@/editor/lsp/positions"; +import { pluginVisuals } from "@/editor/lsp/pluginVisuals"; +import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; +import { call, commands, type ColorInfo } from "@/platform/ipc"; +import { showContextMenu } from "@/ui"; +import styles from "./ColorPreview.module.css"; +const setColors = StateEffect.define<[string, ColorInfo][]>(); +const colors = StateField.define<[string, ColorInfo][]>({ + create: () => [], + update(v, tr) { + for (const e of tr.effects) if (e.is(setColors)) return e.value; + return tr.docChanged ? [] : v; + }, +}); +class Swatch extends GutterMarker { + constructor( + readonly plugin: string, + readonly color: ColorInfo, + readonly view: EditorView, + readonly ctx: EditorDocContext, + ) { + super(); + } + override eq(other: GutterMarker) { + return ( + other instanceof Swatch && + this.plugin === other.plugin && + JSON.stringify(this.color) === JSON.stringify(other.color) + ); + } + override toDOM() { + const el = document.createElement("button"); + el.type = "button"; + el.className = styles.swatch!; + el.title = `rgba(${this.color.red}, ${this.color.green}, ${this.color.blue}, ${this.color.alpha})`; + el.setAttribute("aria-label", el.title); + const fill = document.createElement("span"); + fill.style.background = `rgba(${(this.color.red ?? 0) * 255}, ${(this.color.green ?? 0) * 255}, ${(this.color.blue ?? 0) * 255}, ${this.color.alpha})`; + el.append(fill); + el.onclick = () => { + if (this.view.state.readOnly) return; + const rect = el.getBoundingClientRect(); + pick(this.view, this.ctx, this.plugin, this.color, rect.left, rect.bottom + 2); + }; + return el; + } +} +function pick(view: EditorView, ctx: EditorDocContext, plugin: string, color: ColorInfo, x: number, y: number) { + const text = view.state.doc; + const { from, to } = rangeToOffsets(text, color.range); + const input = document.createElement("input"); + input.type = "color"; + input.className = styles.picker!; + input.style.left = `${x}px`; + input.style.top = `${y}px`; + input.value = + "#" + + [color.red, color.green, color.blue] + .map((c) => + Math.round((c ?? 0) * 255) + .toString(16) + .padStart(2, "0"), + ) + .join(""); + document.body.append(input); + input.onchange = () => { + input.remove(); + const hex = input.value; + const chosen = { + ...color, + red: parseInt(hex.slice(1, 3), 16) / 255, + green: parseInt(hex.slice(3, 5), 16) / 255, + blue: parseInt(hex.slice(5, 7), 16) / 255, + }; + void call(commands.pluginColorPresentations(ctx.doc, plugin, chosen)) + .then((list) => { + const apply = (insert: string) => { + if (view.state.doc === text && !view.state.readOnly) + view.dispatch({ changes: { from, to, insert }, userEvent: "input.color" }); + }; + if (view.state.doc !== text) return; + if (list.length === 1) apply(list[0]!); + else if (list.length) + showContextMenu( + { x, y }, + list.map((label) => ({ label, verbatim: true, run: () => apply(label) })), + ); + }) + .catch(console.warn); + }; + input.oncancel = () => input.remove(); + try { + input.showPicker(); + } catch { + input.click(); + } +} +export function pluginColorPreview(ctx: EditorDocContext): Extension { + if (ctx.doc < 0) return []; + return [ + colors, + gutter({ + class: `${styles.gutter} cm-plugin-color-preview`, + markers: (view) => + RangeSet.of( + view.state + .field(colors) + .map(([p, c]) => new Swatch(p, c, view, ctx).range(view.state.doc.line(c.range.start.line + 1).from)), + true, + ), + }), + ViewPlugin.define( + (view) => + new (class { + timer: ReturnType | undefined; + generation = 0; + off: () => void; + constructor() { + this.off = onNavigationProvidersChanged(() => this.schedule()); + this.schedule(); + } + schedule() { + this.generation++; + clearTimeout(this.timer); + this.timer = setTimeout(() => void this.run(), 300); + } + update(u: ViewUpdate) { + if (u.docChanged) this.schedule(); + } + async run() { + const gen = this.generation; + const text = view.state.doc; + try { + const r = await pluginVisuals(view, ctx); + if (gen === this.generation && view.state.doc === text && view.dom.isConnected) + view.dispatch({ effects: setColors.of(r.colors) }); + } catch { + if (gen === this.generation && view.dom.isConnected) view.dispatch({ effects: setColors.of([]) }); + } + } + destroy() { + this.generation++; + clearTimeout(this.timer); + this.off(); + } + })(), + ), + ]; +} diff --git a/src/features/plugins/__tests__/views.test.tsx b/src/features/plugins/__tests__/views.test.tsx index 8f008fe1b2..c4d78af608 100644 --- a/src/features/plugins/__tests__/views.test.tsx +++ b/src/features/plugins/__tests__/views.test.tsx @@ -713,3 +713,32 @@ describe("API 1.3 read-only values and table rows", () => { }, ); }); + +it("carries zero-based problem and search coordinates as JSON and selected paths", () => { + const off = registerAction({ id: "plugin.p.check", title: "Inspect", run: () => {} }); + const plugin = { id: "p", name: "P", status: "active", enabled: true } as unknown as Parameters< + typeof syncUiContributions + >[1][number]; + syncUiContributions( + ["problems.context", "searchResults.context"].map((menu) => ({ + pluginId: "p", + point: "menus", + key: menu, + decl: { menu, command: "check" }, + })), + [plugin], + ); + for (const menu of ["problems", "searchResults"] as const) { + const item = pluginMenuItems(menu, ["/p/a.sql"], { line: 3, column: 5 })[0]!; + expect(item).toMatchObject({ + kind: "action", + action: "plugin.p.check", + arg: { path: "/p/a.sql", paths: ["/p/a.sql"], line: 3, column: 5 }, + }); + expect(commandArgs("arg" in item ? item.arg : null)).toEqual([ + '{"path":"/p/a.sql","line":3,"column":5}', + ["/p/a.sql"], + ]); + } + off(); +}); diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index df6138bb9f..2f06e61ebe 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -1,3 +1,4 @@ +import { pluginLanguageVisuals } from "./languageVisuals"; /** * Plugins: Settings › Plugins (installed list, enable/disable, install from * disk with a permission page, uninstall, theme selection) and the runtime @@ -159,6 +160,7 @@ export function activate(): () => void { startViewUi((input) => void editorService().openInput(input)), startWorkspaceContains(), // Gutter icons from plugins' `line-markers` providers (next to the LSP ones). + registerEditorContribution({ id: "plugins.languageFeatures", order: 58, extensions: pluginLanguageVisuals }), registerEditorContribution({ id: "plugins.lineMarkers", order: 57, extensions: pluginLineMarkerGutter }), // Dev plugins (`/.openidea/plugins`) depend on the open project. useProject.subscribe((s, prev) => { diff --git a/src/features/plugins/languageVisuals.test.ts b/src/features/plugins/languageVisuals.test.ts new file mode 100644 index 0000000000..5186d73492 --- /dev/null +++ b/src/features/plugins/languageVisuals.test.ts @@ -0,0 +1,72 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { syntaxHighlighting, defaultHighlightStyle } from "@codemirror/language"; +const ipc = vi.hoisted(() => ({ + pluginLanguageVisuals: vi.fn(), + lspExecuteCommand: vi.fn(async () => ({ status: "ok", data: null })), +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: ipc, +})); +const { injectedHighlights, pluginLanguageVisuals } = await import("./languageVisuals"); +const ctx = { doc: 7, path: "/p/a.txt", language: "text", uiMode: null, readOnly: false }; +const views: EditorView[] = []; +afterEach(() => { + views.splice(0).forEach((v) => v.destroy()); + vi.useRealTimers(); + vi.clearAllMocks(); +}); +it("highlights only the embedded slice with its own parser and the editor theme", async () => { + const state = EditorState.create({ + doc: "host SELECT a FROM t host", + extensions: [syntaxHighlighting(defaultHighlightStyle)], + }); + const deco = await injectedHighlights(state, [ + { range: { start: { line: 0, col: 5 }, end: { line: 0, col: 20 } }, language: "sql" }, + ]); + expect(deco.size).toBeGreaterThan(0); + const cursor = deco.iter(); + while (cursor.value) { + expect(cursor.from).toBeGreaterThanOrEqual(5); + expect(cursor.to).toBeLessThanOrEqual(20); + expect(cursor.value.spec.class).toMatch(/\S/); + cursor.next(); + } +}); +it("renders owned gutter commands and drops answers to superseded buffers", async () => { + vi.useFakeTimers(); + let answer!: (v: unknown) => void; + ipc.pluginLanguageVisuals.mockImplementationOnce( + () => + new Promise((r) => { + answer = r; + }), + ); + const visual = { + version: 2, + injections: [], + colors: [], + gutterActions: [["test", { line: 0, icon: "run", tooltip: "Run test", command: "run", argument: "value" }]], + }; + ipc.pluginLanguageVisuals.mockResolvedValue({ status: "ok", data: visual }); + const view = new EditorView({ + state: EditorState.create({ doc: "before", extensions: pluginLanguageVisuals(ctx) }), + parent: document.body, + }); + views.push(view); + await vi.advanceTimersByTimeAsync(300); + view.dispatch({ changes: { from: 0, to: 6, insert: "after" } }); + answer({ status: "ok", data: visual }); + await vi.advanceTimersByTimeAsync(0); + expect(view.dom.querySelector(".cm-plugin-gutter-action")).toBeNull(); + await vi.advanceTimersByTimeAsync(300); + const button = view.dom.querySelector(".cm-plugin-gutter-action")!; + expect(button.getAttribute("aria-label")).toBe("Run test"); + button.click(); + expect(ipc.lspExecuteCommand).toHaveBeenCalledWith( + 7, + expect.objectContaining({ command: "openidea.plugin-language:test:run", arguments: ['"value"'] }), + ); +}); diff --git a/src/features/plugins/languageVisuals.ts b/src/features/plugins/languageVisuals.ts new file mode 100644 index 0000000000..d144409323 --- /dev/null +++ b/src/features/plugins/languageVisuals.ts @@ -0,0 +1,190 @@ +/** Embedded highlighting and command gutter actions share the editor-provider refresh. */ +import { + Compartment, + Prec, + RangeSet, + StateEffect, + StateField, + type Extension, + type EditorState, +} from "@codemirror/state"; +import { + Decoration, + EditorView, + GutterMarker, + ViewPlugin, + gutter, + type DecorationSet, + type ViewUpdate, +} from "@codemirror/view"; +import { highlightingFor } from "@codemirror/language"; +import { highlightTree } from "@lezer/highlight"; +import { type EditorDocContext } from "@/editor/api"; +import { rangeToOffsets } from "@/editor/lsp/positions"; +import { pluginVisuals } from "@/editor/lsp/pluginVisuals"; +import { findLanguageDescription, languageInfo, loadSupport } from "@/editor/core/cm/languages"; +import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; +import { call, commands, type GutterAction, type Injection } from "@/platform/ipc"; +import { gutterIconMarkup } from "@/ui/icons"; +import { resolveMarkerIcon, onMarkerIconsChanged } from "./markerIcons"; +import { markerIcon } from "./lineMarkerGutter"; +import styles from "@/editor/navigation/LineMarkers.module.css"; + +export async function injectedHighlights(state: EditorState, injections: readonly Injection[]): Promise { + const ranges = await Promise.all( + injections.map(async (i) => { + const { from, to } = rangeToOffsets(state.doc, i.range); + if (from >= to) return []; + const desc = findLanguageDescription(languageInfo(i.language)?.uiMode ?? i.language, ""); + const support = desc ? await loadSupport(desc) : null; + if (!support) return []; + const marks = [] as ReturnType[]; + highlightTree( + support.language.parser.parse(state.sliceDoc(from, to)), + { style: (tags) => highlightingFor(state, tags) }, + (a, b, cls) => marks.push(Decoration.mark({ class: cls }).range(from + a, from + b)), + ); + return marks; + }), + ); + return Decoration.set(ranges.flat(), true); +} +const setHighlight = StateEffect.define(); +const highlights = StateField.define({ + create: () => Decoration.none, + update(value, tr) { + for (const e of tr.effects) if (e.is(setHighlight)) return e.value; + return tr.docChanged ? Decoration.none : value; + }, + provide: (f) => Prec.high(EditorView.decorations.from(f)), +}); +class ActionMarker extends GutterMarker { + constructor( + readonly plugin: string, + readonly action: GutterAction, + readonly ctx: EditorDocContext, + ) { + super(); + } + override eq(other: GutterMarker) { + return ( + other instanceof ActionMarker && + other.plugin === this.plugin && + JSON.stringify(other.action) === JSON.stringify(this.action) + ); + } + override toDOM() { + const el = document.createElement("button"); + el.type = "button"; + el.className = `${styles.marker} cm-plugin-gutter-action`; + el.title = this.action.tooltip; + el.setAttribute("aria-label", this.action.tooltip); + el.innerHTML = gutterIconMarkup(markerIcon(this.action.icon)) ?? ""; + el.onclick = (e) => { + e.preventDefault(); + e.stopPropagation(); + void call( + commands.lspExecuteCommand(this.ctx.doc, { + title: this.action.tooltip, + command: `openidea.plugin-language:${this.plugin}:${this.action.command}`, + arguments: [JSON.stringify(this.action.argument)], + }), + ).catch(console.warn); + }; + return el; + } +} +const setActions = StateEffect.define<{ pos: number; marker: ActionMarker }[]>(); +const actions = StateField.define<{ pos: number; marker: ActionMarker }[]>({ + create: () => [], + update(v, tr) { + for (const e of tr.effects) if (e.is(setActions)) return e.value; + return tr.docChanged ? [] : v; + }, +}); +const column = gutter({ + class: `${styles.gutter} cm-plugin-gutter-actions`, + markers: (view) => + RangeSet.of( + view.state.field(actions).map((a) => a.marker.range(a.pos)), + true, + ), +}); +export function pluginLanguageVisuals(ctx: EditorDocContext): Extension { + if (ctx.doc < 0) return []; + const compartment = new Compartment(); + return [ + highlights, + actions, + compartment.of([]), + ViewPlugin.define( + (view) => + new (class { + timer: ReturnType | undefined; + generation = 0; + shown = false; + off: () => void; + constructor() { + const a = onNavigationProvidersChanged(() => this.schedule(true)); + const b = onMarkerIconsChanged(() => this.schedule()); + this.off = () => { + a(); + b(); + }; + this.schedule(); + } + schedule(clear = false) { + this.generation++; + clearTimeout(this.timer); + if (clear) + queueMicrotask(() => { + if (view.dom.isConnected) + view.dispatch({ + effects: [setHighlight.of(Decoration.none), setActions.of([]), compartment.reconfigure([])], + }); + this.shown = false; + }); + this.timer = setTimeout(() => void this.run(), 300); + } + update(u: ViewUpdate) { + if (u.docChanged) this.schedule(); + } + async run() { + const generation = this.generation; + const text = view.state.doc; + try { + const result = await pluginVisuals(view, ctx); + const deco = await injectedHighlights(view.state, result.injections); + const placed = await Promise.all( + result.gutterActions + .filter(([, a]) => a.line < text.lines) + .map(async ([plugin, a]) => ({ + pos: text.line(a.line + 1).from, + marker: new ActionMarker(plugin, { ...a, icon: await resolveMarkerIcon(plugin, a.icon) }, ctx), + })), + ); + if (generation !== this.generation || view.state.doc !== text || !view.dom.isConnected) return; + this.shown = !!placed.length; + view.dispatch({ + effects: [ + setHighlight.of(deco), + setActions.of(placed), + compartment.reconfigure(this.shown ? column : []), + ], + }); + } catch { + if (generation === this.generation && view.dom.isConnected) + view.dispatch({ + effects: [setHighlight.of(Decoration.none), setActions.of([]), compartment.reconfigure([])], + }); + } + } + destroy() { + this.generation++; + clearTimeout(this.timer); + this.off(); + } + })(), + ), + ]; +} diff --git a/src/features/plugins/pluginText.ts b/src/features/plugins/pluginText.ts index 8f9b1291c1..ce28f0d64d 100644 --- a/src/features/plugins/pluginText.ts +++ b/src/features/plugins/pluginText.ts @@ -82,6 +82,7 @@ const TEXT_KEYS: Record = { statusBar: ["text", "tooltip"], settings: ["title"], fileTemplates: ["name"], + snippets: [], iconThemes: ["label"], themes: ["name"], secrets: ["label", "description"], @@ -91,6 +92,7 @@ function localizeDecl(decl: unknown, keys: readonly string[], t: PluginTranslate if (!decl || typeof decl !== "object") return decl; const out: Record = { ...(decl as Record) }; for (const key of keys) if (typeof out[key] === "string") out[key] = t(out[key]); + if (Array.isArray(out.entries)) out.entries = out.entries.map((s) => localizeDecl(s, ["description"], t)); if (Array.isArray(out.properties)) out.properties = out.properties.map((p) => localizeDecl(p, ["title", "description", "group"], t)); if (Array.isArray(out.pages)) out.pages = out.pages.map((p) => localizeDecl(p, ["title"], t)); diff --git a/src/features/plugins/points.tsx b/src/features/plugins/points.tsx index 3e3f5cc2fa..e5b2f34efd 100644 --- a/src/features/plugins/points.tsx +++ b/src/features/plugins/points.tsx @@ -5,6 +5,7 @@ */ import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions"; import type { PluginInfo, ThemeDef } from "@/bindings"; +import { pluginIconName } from "./pluginIcon"; import { registerAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { addContributedTheme, pluginThemeRef } from "@/platform/themes"; @@ -22,8 +23,15 @@ import styles from "./PluginsPage.module.css"; /** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */ export function commandArgs(arg: unknown): [string | null, string[]] { if (typeof arg === "string") return [arg, []]; - const { path, paths } = (arg ?? {}) as { path?: unknown; paths?: unknown }; + const { path, paths, line, column } = (arg ?? {}) as { + path?: unknown; + paths?: unknown; + line?: unknown; + column?: unknown; + }; if (typeof path !== "string" || !Array.isArray(paths)) return [null, []]; + if (typeof line === "number" && typeof column === "number") + return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")]; return [path, paths.filter((p): p is string => typeof p === "string")]; } @@ -32,6 +40,7 @@ export const pluginActionId = (pluginId: string, commandId: string) => `plugin.$ interface CommandDecl { id: string; title: string; + icon?: string | null; category?: string | null; when?: string | null; } @@ -184,21 +193,43 @@ export function defineBuiltinUiPoints(): () => void { defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }), defineUiPoint("commands", { title: "Commands", - project: ({ pluginId, decl }, { plugin }) => - registerAction({ + project: ({ pluginId, decl }, { plugin }) => { + let disposed = false; + const action = { id: pluginActionId(pluginId, decl.id), title: decl.title, category: decl.category ?? plugin.name, - icon: "package", + icon: + decl.icon && !decl.icon.endsWith(".svg") + ? decl.icon + : plugin.icon + ? pluginIconName(pluginId, plugin.icon) + : "package", when: decl.when ?? undefined, verbatim: true, keywords: ["plugin", plugin.name, pluginId], description: tx`From plugin ${plugin.name}`, - run: async ({ arg }) => { + run: async ({ arg }: { arg?: unknown }) => { const [path, paths] = commandArgs(arg); await runPluginCommand(pluginId, decl.id, path, paths); }, - }), + }; + let off = registerAction(action); + if (decl.icon?.endsWith(".svg")) + void pluginsBackend() + .assets(pluginId, `commandIcon/${decl.id}`) + .then((assets) => { + const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1]; + if (!svg || disposed) return; + off(); + off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) }); + }) + .catch(console.warn); + return () => { + disposed = true; + off(); + }; + }, Details: CommandsDetails, }), // Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one. diff --git a/src/features/plugins/uiPoints.tsx b/src/features/plugins/uiPoints.tsx index 9e1f1a8cd8..614161e527 100644 --- a/src/features/plugins/uiPoints.tsx +++ b/src/features/plugins/uiPoints.tsx @@ -22,6 +22,7 @@ import { isMacHost, registerExtensionBindings } from "@/platform/keymap"; import { addFileIconProvider, fileIconName, registerExternalIcons, type MenuItem } from "@/ui"; import { addContributedFileTemplate } from "@/workbench/contributions"; import { + addContributedSnippets, registerEditorKind, registerFileEditorProvider, registerCommitCheckProvider, @@ -70,6 +71,10 @@ import { projectSettings, type SettingsDecl } from "./settings"; interface MenuDecl { menu: + | "editor.title" + | "mainToolbar" + | "problems.context" + | "searchResults.context" | "editor.context" | "projectView.context" | "editorTab.context" @@ -87,6 +92,8 @@ interface MenuDecl { const CONTEXT_MENUS: Record = { "editor.context": "editor", + "problems.context": "problems", + "searchResults.context": "searchResults", "projectView.context": "projectView", "editorTab.context": "editorTab", }; @@ -127,7 +134,11 @@ function flattenSingleGroups(items: MenuItem[]): MenuItem[] { } /** Plugin items of a context menu: their command's action with the menu's file as argument. */ -export function pluginMenuItems(menu: ContextMenuId, paths: readonly string[]): MenuItem[] { +export function pluginMenuItems( + menu: ContextMenuId, + paths: readonly string[], + position?: { line: number; column: number }, +): MenuItem[] { const out: MenuItem[] = []; const groups = new Map(); for (const { pluginId, decl } of contextItems.values()) { @@ -138,7 +149,7 @@ export function pluginMenuItems(menu: ContextMenuId, paths: readonly string[]): addGrouped(out, groups, pluginId, decl.submenu, { kind: "action", action, - arg: menu === "editor" ? undefined : { path: paths[0], paths: [...paths] }, + arg: menu === "editor" ? undefined : { path: paths[0], paths: [...paths], ...(position ?? {}) }, }); } return flattenSingleGroups(out); @@ -165,14 +176,14 @@ function projectMenu(pluginId: string, decl: MenuDecl, plugin: PluginInfo): () = const title = decl.commandTitle ?? getAction(action)?.title ?? `${plugin.name}: ${decl.command}`; return registerMenuSlotItem("pluginTools", { action, label: title, verbatim: true }); } - if (decl.menu === "commit.message") { + if (decl.menu === "commit.message" || decl.menu === "editor.title" || decl.menu === "mainToolbar") { const action = pluginActionId(pluginId, decl.command); const label = getAction(action)?.title ?? `${plugin.name}: ${decl.command}`; - return registerMenuSlotItem("commitMessage", { + return registerMenuSlotItem(decl.menu === "commit.message" ? "commitMessage" : decl.menu, { action, label, verbatim: true, - icon: pluginIconName(pluginId, plugin.icon), + icon: getAction(action)?.icon ?? pluginIconName(pluginId, plugin.icon), when: decl.when ?? null, }); } @@ -487,6 +498,24 @@ export function defineViewUiPoints(): () => void { title: "Commit Checks", project: ({ pluginId, decl }) => projectCommitCheck(pluginId, decl), }), + defineUiPoint<{ + source: string; + language: string; + entries: { name: string; prefixes: string[]; body: string; description: string }[]; + }>("snippets", { + title: "Snippets", + project: ({ pluginId, decl }, { plugin }) => + addContributedSnippets( + decl.entries.map((s, i) => ({ + id: `plugin-snippet:${pluginId}:${decl.source}:${i}`, + pluginName: plugin.name, + language: decl.language, + prefixes: s.prefixes, + body: s.body, + description: s.description, + })), + ), + }), defineUiPoint("fileTemplates", { title: "File Templates", project: ({ pluginId, decl }) => @@ -539,12 +568,16 @@ export function startViewUi(openInput: (input: ReturnType { - const items = pluginMenuItems(menu, ctx.paths); + const items = pluginMenuItems( + menu, + ctx.paths, + ctx.line === undefined ? undefined : { line: ctx.line, column: ctx.column ?? 0 }, + ); const path = ctx.paths[0]; - if (menu !== "editor" && path && !ctx.dirs?.[0]) { + if ((menu === "projectView" || menu === "editorTab") && path && !ctx.dirs?.[0]) { const editors = [...openWith.values()].filter((e) => e.matches(path)); if (editors.length) items.push({ diff --git a/src/features/search/find/FindToolWindow.tsx b/src/features/search/find/FindToolWindow.tsx index 90066080e5..cfd11a4053 100644 --- a/src/features/search/find/FindToolWindow.tsx +++ b/src/features/search/find/FindToolWindow.tsx @@ -1,3 +1,4 @@ +import { menuGroupItems } from "@/workbench/contributions"; import { useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { create } from "zustand"; @@ -459,6 +460,9 @@ function FindTabView({ tab }: { tab: FindTab }) { const groups = [...sel].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : [])); const excludedAll = groups.length > 0 && groups.every((g) => groupState(g, marks) === "excluded"); showContextMenu(e, [ + ...(_n?.kind === "match" + ? menuGroupItems("searchResults", { paths: [_n.path], line: _n.line, column: _n.col }) + : []), { id: "exclude", label: excludedAll ? "Include" : "Exclude", diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index 4c1623e800..221727ea16 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -18,6 +18,9 @@ import { validateSettings } from "../model/schema"; describe("languages settings", () => { it("defaults and normalises malformed values", () => { expect(validateLanguages(undefined)).toEqual(DEFAULT_LANGUAGES); + expect(validateLanguages({ pluginFormatters: { sql: "example.formatter", text: 42 } }).pluginFormatters).toEqual({ + sql: "example.formatter", + }); const v = validateLanguages({ python: { interpreter: " /usr/bin/python3 ", activateVirtualenv: "yes" }, node: { packageManager: "pip" }, @@ -303,6 +306,7 @@ describe("language pages", () => { "Ruby", "Rust", "TypeScript", + "Plugin Formatters", ]); }); diff --git a/src/features/settings/languages/PluginFormattersPage.tsx b/src/features/settings/languages/PluginFormattersPage.tsx new file mode 100644 index 0000000000..d257779d38 --- /dev/null +++ b/src/features/settings/languages/PluginFormattersPage.tsx @@ -0,0 +1,56 @@ +import { useEffect, useState } from "react"; +import { call, commands, type FormatterChoice } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { Row, Section, Select, Toggle } from "../components/Form"; +import { useSetting } from "../components/context"; +export function PluginFormattersPage() { + const [known, setKnown] = useState([]); + const [choices, setChoices] = useState([]); + const [selected, setSelected] = useSetting>("languages.pluginFormatters"); + const [save, setSave] = useSetting("editor.formatOnSave"); + useEffect(() => { + let active = true; + void call(commands.pluginFormatters()) + .then((v) => { + if (active) setChoices(v); + }) + .catch(() => {}); + return () => { + active = false; + }; + }, []); + useEffect(() => { + void commands + .languages() + .then((list) => setKnown(list.map((l) => l.id))) + .catch(() => {}); + }, []); + const languages = [ + ...new Set([...known, ...Object.keys(selected ?? {}), ...choices.flatMap((c) => c.languages)]), + ].filter( + (l) => l !== "*" && (selected?.[l] || choices.some((c) => c.languages.includes(l) || c.languages.includes("*"))), + ); + return ( +
+ {languages.map((language) => ( + +