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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 4e9dc45d68 fix(fonts): keep Latin text monospaced when the chosen font isn't installed
With a fallback font set and a primary family that isn't installed, every
glyph came from the fallback. A CJK fallback such as PingFang SC has
proportional Latin letters, and the terminal sized its cells for the widest
of them, so text came out spread apart. Once the native font catalog shows
the family is missing, the bundled JetBrains Mono now stands in for it ahead
of the fallback, which still covers the glyphs it lacks. Applies to every
monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:24:48 +08:00
l0ng-ai cc9279a6d6 fix(editor): indent Slint element blocks by their braces (#7012)
Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch.

Fixes #6976
2026-11-30 18:22:26 +08:00
l0ng-ai 1cfbb24b31 fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011)
The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView.

Fixes #6978
2026-11-30 18:18:33 +08:00
l0ng-ai a8a0cdb315 fix(plugins): load precompiled plugin components in the signed macOS app (#7010)
compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code.

Refs #6954
2026-11-30 18:16:20 +08:00
l0ng-ai 8ab776ada6 fix(keymap): import an Emacs-based IDEA keymap on top of $default, not macOS (#7008)
presetOf picked the macOS preset for any parent whose name contains "mac", including "Emacs", so a keymap derived from IDEA's Emacs keymap was imported as based on macOS. The match is now on the word (Mac OS X, macOS), and Emacs and its copies map to the $default preset they inherit in IDEA.

Refs #6896
2026-11-30 18:14:01 +08:00
LU XIANGRUIтаwildcatDownstairs 88b463d888 fix(debugger): let a tsx program behind a remote root run under Attach to Node.js (#6926)
On a loopback address js-debug makes the program require its child-process bootloader by a local path; behind a remote root (published container port, SSH tunnel) that path is missing, tsx's esbuild worker exits and the program waits for it forever. Attach to Node.js with a remote root, and Node.js debugging on SSH/Docker/Compose run targets, now pass autoAttachChildProcesses: false.

Closes #6925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:42 +08:00
LU XIANGRUIтаwildcatDownstairs ac88059d0f fix(plugins): index the first 20,000 files of a large project instead of none (#6958)
Plugin navigation discovery refused the whole project above 20,000 matching files, counted out-of-scope and git-ignored files toward the cap, and showed the raw error text half translated. Discovery now keeps the first 20,000 in-scope, non-ignored files, reports total/truncated, and shows one warning naming the project and the counts.

Fixes #6940

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:27 +08:00
Waiting-Night a09c9aa9ad fix(java): navigate inherited method references to their declarations (#6953)
JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 18:06:54 +08:00
LU XIANGRUIтаwildcatDownstairs 7fef1e10a8 fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936)
The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing.

Fixes #6930

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:03:40 +08:00
l0ng-ai 1748c98ac8 test(agents): type the store import of the long agent form e2e (#7004)
The e2e from #7003 imported the store by a literal /src path, which pnpm typecheck rejects (TS2307); it now imports through a variable typed as the store module.
2026-11-30 17:59:41 +08:00
42 змінених файлів з 878 додано та 43 видалено

No files matched your search

+32 -3
Переглянути файл
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
let cancel = cancel.clone();
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
plugin_call(move || {
let offered = plugins.offers_inline_completion(&d.language);
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
})
.await
}
_ => None,
};
host.end_request(request);
inline_items(result, plugin)
}
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
/// for the document, "no server supports inline completion" is not returned:
/// the editor would stop asking while typing for 30 s, and a plugin that had
/// nothing this time (cancelled by the next keystroke) may have some next time.
fn inline_items(
servers: IdeResult<Vec<InlineCompletionItem>>,
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
) -> IdeResult<Vec<InlineCompletionItem>> {
match plugin {
Some((_, s)) => Ok(vec![InlineCompletionItem {
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
insert_text: s.insert_text,
range: s.replace,
filter_text: None,
command: None,
server: PLUGIN_SERVER,
}]),
None => result,
Some((true, None)) => provider_server(servers),
_ => servers,
}
}
@@ -2429,6 +2445,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
// No plugin for this language: the servers' answer as it is.
assert!(inline_items(none(), Some((false, None))).is_err());
assert!(inline_items(none(), None).is_err());
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
}
#[test]
fn a_completion_word_is_its_line_and_what_precedes_it() {
use super::*;
+44 -6
Переглянути файл
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
pub paths: Vec<ide_core::IpcPath>,
pub indexing: bool,
pub extensions: Vec<String>,
/// In-scope files matching `extensions`; `paths` holds the first
/// `MAX_NAVIGATION_FILES` of them.
pub total: u32,
pub truncated: bool,
}
/// Discovery offers at most this many files; larger projects get navigation
/// on the first ones instead of none.
const MAX_NAVIGATION_FILES: usize = 20_000;
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
let total = files.len();
files.truncate(limit);
(files, total)
}
#[command(trust = trusted)]
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
blocking(move || {
let extensions = plugins.navigation_extensions(&project.root);
if extensions.is_empty() {
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
return Ok(NavigationFiles {
paths: vec![],
indexing: false,
extensions: vec![],
total: 0,
truncated: false,
});
}
let indexing = project.index.status().indexing;
let files = project.index.files_with_extensions(&extensions, 20_001);
if files.len() > 20_000 {
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
}
let files = project.index.files_with_extensions(&extensions, usize::MAX);
// A project window group's members are project scope: their files are
// in the group's index (the group root holds none of them).
let members = crate::project::workspace_member_roots(&project.root);
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
Ok(NavigationFiles {
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
truncated: total > files.len(),
total: u32::try_from(total).unwrap_or(u32::MAX),
paths: files.into_iter().map(Into::into).collect(),
indexing,
extensions,
})
@@ -210,3 +232,19 @@ ide_command::domain!(
plugin_navigation_invalidate,
plugin_navigation_markers,
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
// Out-of-scope files neither take a slot nor count toward the total.
assert_eq!(total, 4);
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
assert_eq!((kept.len(), total), (3, 3));
}
}
+5
Переглянути файл
@@ -653,6 +653,11 @@ impl PluginHost {
.collect()
}
/// Whether a usable plugin offers ghost text for `language`.
pub fn offers_inline_completion(&self, language: &str) -> bool {
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
}
/// Ghost text from the first plugin that has some. Not bound by the
/// edit-path soft deadline (it may need the network) but by `cancel`:
/// the editor cancels a request as soon as the user types on.
+32
Переглянути файл
@@ -3027,6 +3027,38 @@ fn official_ai_completion_cancels_superseded_requests() {
assert!(times[9] < Duration::from_millis(500), "{times:?}");
}
/// Installed with the optional network permission refused (it is not ticked by
/// default), a suggestion request says so in the window instead of failing silently.
#[test]
fn official_ai_completion_explains_a_refused_network_permission() {
let f = fixture(Limits::default());
f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap();
let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO);
f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap();
f.take_events();
let doc = ide_plugin::ProviderDocument {
path: f.project.join("src/a.rs"),
language: "rust".into(),
version: 1,
text: "let x = ".into(),
};
for _ in 0..2 {
assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none());
}
assert!(seen.lock().is_empty(), "denied before connecting");
let notices: Vec<String> = f
.take_events()
.into_iter()
.filter_map(|(_, e)| match e {
PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body),
_ => None,
})
.collect();
assert_eq!(notices.len(), 1, "once: {notices:?}");
assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}");
assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash");
}
/// Checkstyle: a save runs the approved `checkstyle` and publishes
/// diagnostics; quick fixes come through the code-action provider; saving
/// again cancels the check still running.
+3 -1
Переглянути файл
@@ -258,7 +258,8 @@ impl ProjectIndex {
}
/// Bounded file inventory for background plugin indexers; honors the same
/// project/exclude scope as search and never walks the filesystem.
/// project/exclude scope as search, leaves VCS-ignored files out and never
/// walks the filesystem.
pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec<PathBuf> {
self.shared
.data
@@ -266,6 +267,7 @@ impl ProjectIndex {
.files
.iter()
.flatten()
.filter(|f| !f.ignored)
.filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)))
.take(limit)
.map(|f| f.path.clone())
+5 -1
Переглянути файл
@@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
}
#[test]
fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() {
fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() {
let java = "package demo; interface UserMapper { void find(); }";
let f = Fixture::new(&[
("src/UserMapper.java", java),
("src/mapper.xml", "<mapper/>"),
("target/Generated.java", "class Generated {}"),
("other.txt", "ignored"),
(".gitignore", "gen/\n"),
("gen/Ignored.java", "class Ignored {}"),
]);
let index = f.open();
// Go to File lists the git-ignored file; plugin navigation leaves it out.
assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]);
let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100);
assert_eq!(paths.len(), 2);
assert!(paths.iter().all(|p| p.starts_with(f.root.join("src"))));
+16 -1
Переглянути файл
@@ -9,7 +9,8 @@ use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::{ErrorData, ErrorKind};
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos};
use lsp_types as lsp;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use specta::Type;
@@ -20,6 +21,7 @@ use std::time::{Duration, Instant};
pub(crate) const SERVER: &str = "jdtls";
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition";
pub(crate) mod configuration;
pub(crate) mod exception_breakpoints;
@@ -771,6 +773,19 @@ impl LspManager {
}
}
/// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`.
/// JDT's selection-based definition can return the functional interface method when the
/// referenced method is inherited; the extension resolves the AST binding instead.
pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult<Vec<Location>> {
let uri = crate::path_to_uri_string(path);
let value = self
.jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)])
.await?;
let locations: Vec<lsp::Location> = serde_json::from_value(value).unwrap_or_default();
let conv = self.conv(crate::text::Encoding::Utf16);
Ok(locations.iter().filter_map(|location| conv.location(location)).collect())
}
/// The jdtls instance serving `path` (a module directory or source file),
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
+74 -1
Переглянути файл
@@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
}
}
/// Whether the caret is on the method name of a Java method reference (`Type::method`).
/// A method reference can name a functional interface's method through JDT's selection-based
/// definition when the referenced method is inherited, so ask the AST binding command instead.
fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
let line = text.line(pos.line as usize);
let mut utf16 = 0u32;
let mut at = line.len();
for (i, c) in line.char_indices() {
if utf16 >= pos.col {
at = i;
break;
}
utf16 += c.len_utf16() as u32;
}
let before = line[..at].trim_end();
let Some(colon) = before.rfind("::") else { return false };
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
match e {
RpcError::Cancelled => IdeError::cancelled(),
@@ -1793,7 +1812,31 @@ impl LspManager {
}
let (method, cap, feature) = goto_method(kind);
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
self.goto_in(&snap, &targets, method, pos, None, None).await
let result = self.goto_in(&snap, &targets, method, pos, None, None).await;
// JDT's selection-based definition can name the functional interface method for an
// inherited method reference. Ask the Java binding command when that is what came back,
// when the caret is on a method reference, or when the server found no target at all.
let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos);
if kind == GotoKind::Definition
&& snap.language.as_str() == "java"
&& (method_reference
|| result.as_ref().is_ok_and(|locs| {
locs.is_empty()
|| locs.iter().any(|l| {
let path = l.path.to_string_lossy().replace('\\', "/");
let uri = l.uri.as_deref().unwrap_or_default();
path.contains("java/util/function")
|| path.contains("java.util.function")
|| uri.contains("java/util/function")
|| uri.contains("java.util.function")
})
}))
&& let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await
&& !found.is_empty()
{
return Ok(found);
}
result
}
/// Go to Implementation, with the implementations found first passed to `partial` while
@@ -4677,6 +4720,36 @@ mod code_action_tests {
}
}
#[cfg(test)]
mod java_method_reference_tests {
use super::java_method_reference_at;
use crate::text::DocText;
use ide_core::Pos;
#[test]
fn finds_the_method_name_of_a_method_reference() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32;
assert!(java_method_reference_at(&text, Pos::new(0, col)));
}
#[test]
fn allows_whitespace_around_the_method_reference_operator() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);");
let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32;
assert!(java_method_reference_at(&text, Pos::new(0, col)));
}
#[test]
fn ignores_regular_calls_and_the_referenced_type() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32;
assert!(!java_method_reference_at(&text, Pos::new(0, type_col)));
let call = DocText::new("wrapper.set(getUpdateTime(), now);");
assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32)));
}
}
#[cfg(test)]
mod did_change_content_tests {
use super::*;
+25 -2
Переглянути файл
@@ -613,11 +613,14 @@ impl PluginEngine {
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
if file.is_file() {
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
// memory executable"), so the cache never hit and every activation compiled again.
if let Ok(precompiled) = std::fs::read(&file) {
// SAFETY: the cache directory belongs to the IDE (inside its plugins
// directory) and is written only by `store_precompiled` below from
// components this engine compiled; a corrupt file fails validation.
match unsafe { Component::deserialize_file(&self.engine, &file) } {
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
Ok(component) => return Ok(component),
Err(e) => {
tracing::info!("discarding precompiled {}: {e}", file.display());
@@ -3035,6 +3038,26 @@ impl Runtime {
mod tests {
use super::*;
/// The second compile of the same component loads the cached one instead of compiling and
/// writing it again (a failed load deletes and rewrites the file).
#[test]
fn a_precompiled_component_is_loaded_from_the_cache() {
let engine = PluginEngine::new().unwrap();
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
let cache = tempfile::tempdir().unwrap();
engine.compile_cached(&wasm, cache.path()).unwrap();
let cached = || {
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
assert_eq!(entries.len(), 1, "{entries:?}");
let file = entries[0].clone();
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
};
let before = cached();
std::thread::sleep(std::time::Duration::from_millis(20));
engine.compile_cached(&wasm, cache.path()).unwrap();
assert_eq!(cached(), before, "loaded, not compiled and stored again");
}
#[test]
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
let fields = [
+1 -1
Переглянути файл
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.19.0",
"1.20.1",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+2 -1
Переглянути файл
@@ -254,7 +254,8 @@ test("a long agent form scrolls above the composer instead of being cut off", as
}));
await page.evaluate(
async ({ task, fields }) => {
const store = await import("/src/features/agents/store.ts");
const storePath = "/src/features/agents/store.ts";
const store: typeof AgentStore = await import(storePath);
store.useAgents.setState({
loaded: true,
tasks: new Map([[task.id, task]]),
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.19.0
Bundle-Version: 1.20.1
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+10 -1
Переглянути файл
@@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
`access` is read/write/readWrite/unknown. Missing access metadata is unknown;
old servers and ordinary LSP locations remain visible under either filter.
`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name
of a `Type::method` or `expr::method` reference through its AST binding and returns the
declaring method's location. This keeps inherited methods on their parent declaration
where JDT's selection-based definition may return the functional interface method.
An absent or failing extension command uses standard LSP references, without access
classification or toolbar controls. This includes errors during scope widening.
The Rust bridge logs the failure once per project session. Cancelled requests and
@@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.20.1.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception
breakpoint intention; its reproducible SHA-256 is
`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`.
Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method
references from their AST binding instead of JDT's selection result. Lombok-generated accessors
without a source range fall back to their field or declaring type; its reproducible SHA-256 is
`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
@@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat
python3 java/java-usages/tests/hierarchy.py /path/to/jdtls
python3 java/java-usages/tests/implementations.py /path/to/jdtls
python3 java/java-usages/tests/exception-type.py /path/to/jdtls
python3 java/java-usages/tests/method-reference.py /path/to/jdtls
```
The harnesses select the JDT LS configuration for the current platform. The first
Бінарний файл не відображається.
+3
Переглянути файл
@@ -27,6 +27,9 @@
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
<command id="openidea.java.implementationLocations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.navigation.MethodReferenceDefinitionCommand">
<command id="openidea.java.methodReferenceDefinition"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
+131
Переглянути файл
@@ -0,0 +1,131 @@
package ai.openidea.navigation;
import ai.openidea.Documents;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ExpressionMethodReference;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodReference;
import org.eclipse.jdt.core.dom.NodeFinder;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SuperMethodReference;
import org.eclipse.jdt.core.dom.TypeMethodReference;
import org.eclipse.jdt.core.manipulation.CoreASTProvider;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
import org.eclipse.lsp4j.Location;
/**
* Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration
* of the referenced method. JDT's selection-based definition request can return the
* functional interface method ({@code Function.apply}) when the method is inherited;
* bindings retain the actual method identity instead.
*/
public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
Documents.awaitChanges(monitor);
String uri = (String) arguments.get(0);
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
if (root == null || !root.exists()) return List.of();
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
if (ast == null) return List.of();
int offset = JsonRpcHelpers.toOffset(root, line, column);
if (offset < 0) return List.of();
MethodReference reference = enclosingReference(ast, offset);
if (reference == null) return List.of();
SimpleName name = methodName(reference);
if (name == null) return List.of();
int start = name.getStartPosition();
if (offset < start || offset > start + name.getLength()) return List.of();
IMethodBinding binding = reference.resolveMethodBinding();
if (binding == null) return List.of();
IMethodBinding declaration = binding.getMethodDeclaration();
if (declaration == null) return List.of();
Location location = locationOf(declaration);
return location == null ? List.of() : List.of(location);
}
/**
* The declaration's source location. Lombok-generated accessors have a binding and a Java
* element but no source range; then the field the accessor reads (or the declaring type)
* is the closest source declaration. Without this fallback the standard definition request
* stays at the functional interface method.
*/
private static Location locationOf(IMethodBinding declaration) throws Exception {
var element = declaration.getJavaElement();
Location location = element == null ? null : JDTUtils.toLocation(element);
if (location != null) return location;
if (element instanceof IMember member && member.getClassFile() != null)
return JDTUtils.toLocation(member.getClassFile());
ITypeBinding owner = declaration.getDeclaringClass();
if (owner == null) return null;
var ownerElement = owner.getJavaElement();
if (!(ownerElement instanceof IType type) || !type.exists()) return null;
for (IMethod method : type.getMethods()) {
if (!method.getElementName().equals(declaration.getName())) continue;
if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue;
location = JDTUtils.toLocation(method);
if (location != null) return location;
}
String fieldName = propertyName(declaration.getName());
if (fieldName != null) {
IField field = type.getField(fieldName);
if (field.exists()) {
location = JDTUtils.toLocation(field);
if (location != null) return location;
}
}
return JDTUtils.toLocation(type);
}
/** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */
private static String propertyName(String methodName) {
String rest;
if (methodName.startsWith("get") || methodName.startsWith("set")) {
rest = methodName.substring(3);
} else if (methodName.startsWith("is")) {
rest = methodName.substring(2);
} else {
return null;
}
if (rest.isEmpty()) return null;
if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) {
return rest;
}
return Character.toLowerCase(rest.charAt(0)) + rest.substring(1);
}
private static MethodReference enclosingReference(CompilationUnit ast, int offset) {
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
for (ASTNode node = leaf; node != null; node = node.getParent()) {
if (node instanceof MethodReference reference) return reference;
}
return null;
}
private static SimpleName methodName(MethodReference reference) {
return switch (reference) {
case TypeMethodReference type -> type.getName();
case ExpressionMethodReference expression -> expression.getName();
case SuperMethodReference superReference -> superReference.getName();
default -> null;
};
}
}
+167
Переглянути файл
@@ -0,0 +1,167 @@
"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
Each case puts the caret on a method reference's name and checks that
`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited
method on its parent, not the functional interface method), and nothing elsewhere.
"""
import json
import pathlib
import platform
import queue
import subprocess
import sys
import tempfile
import threading
import time
home = pathlib.Path(sys.argv[1]).resolve()
bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-'))
config = work / 'config'
config.mkdir()
system, machine = platform.system(), platform.machine().lower()
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file())
(config / 'config.ini').write_bytes(config_source.read_bytes())
project = work / 'project'
(project / 'src/app').mkdir(parents=True)
(project / '.project').write_text('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
sources = {
'Parent.java': '''package app;
public class Parent {
public String getGoodsSpace() {
return "space";
}
public static String describe(Object o) {
return String.valueOf(o);
}
}
''',
'Child.java': '''package app;
public class Child extends Parent {
public int own() {
return 1;
}
}
''',
'Main.java': '''package app;
import java.util.List;
import java.util.function.Function;
public class Main {
void run(List<Child> children) {
Function<Child, String> inherited = Child::getGoodsSpace;
Function<Child, Integer> own = Child::own;
Function<Object, String> statics = Child::describe;
children.forEach(System.out::println);
String plain = new Child().getGoodsSpace();
}
}
''',
}
for name, text in sources.items():
(project / 'src/app' / name).write_text(text)
uri = lambda name: (project / 'src/app' / name).as_uri()
log = (work / 'stderr.log').open('w')
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
messages = queue.Queue()
lock = threading.Lock()
def send(message):
data = json.dumps(message).encode()
with lock:
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
proc.stdin.flush()
def read():
while True:
headers = {}
while True:
line = proc.stdout.readline()
if not line:
return
if line == b'\r\n':
break
k, v = line.decode().split(':', 1)
headers[k.lower()] = v.strip()
message = json.loads(proc.stdout.read(int(headers['content-length'])))
if 'method' in message and 'id' in message:
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
else:
messages.put(message)
threading.Thread(target=read, daemon=True).start()
seq = 0
def request(method, params):
global seq
seq += 1
send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params})
deadline = time.monotonic() + 180
while time.monotonic() < deadline:
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
if msg.get('id') == seq:
if 'error' in msg:
raise RuntimeError(msg['error'])
return msg.get('result')
raise TimeoutError(method)
def where(loc):
return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line'])
def line_of(file, needle):
return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t)
CASES = [
('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]),
('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]),
('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]),
('Child::getGoodsSpace', 'Child', 2, []),
('new Child().getGoodsSpace', 'getGoodsSpace', 2, []),
]
try:
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
commands = init['capabilities']['executeCommandProvider']['commands']
assert 'openidea.java.methodReferenceDefinition' in commands, commands
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
for name, text in sources.items():
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}})
request('java/buildWorkspace', True)
failed = []
lines = sources['Main.java'].splitlines()
for line_needle, needle, at, expected in CASES:
line = next(i for i, t in enumerate(lines) if line_needle in t)
column = lines[line].index(needle, lines[line].index(line_needle)) + at
got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]})
got = [where(l) for l in got or []]
ok = got == expected
if not ok:
failed.append((line_needle, needle))
print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got)
# The functional interface's method is what the standard request answers for the inherited case.
line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t)
std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}})
print('standard definition:', std)
assert not failed, failed
print('method-reference: all cases passed')
finally:
proc.terminate()
proc.wait(timeout=20)
print('Evidence:', work, file=sys.stderr)
+1 -1
Переглянути файл
@@ -105,7 +105,7 @@ dependencies = [
[[package]]
name = "openidea-plugin-openidea-ai-completion"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"openidea-plugin",
"serde_json",
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "openidea-plugin-openidea-ai-completion"
version = "0.1.0"
version = "0.1.1"
edition = "2024"
publish = false
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fbaa75cf43cf1188b6b5f7621a94739a0f91ba4c8bd13b94fe78a2e8aa17bcc9
385b624ee9593d759a2ce22d4427edc0f06954d0e98f458a77d780e5a3dbe92a
+7 -2
Переглянути файл
@@ -1,10 +1,10 @@
id = "openidea.ai-completion"
name = "AI Completion"
version = "0.1.0"
version = "0.1.1"
description = "Inline code suggestions (ghost text) from a local model (Ollama) or OpenAI, as you type."
authors = ["OpenIDEA contributors"]
license = "Apache-2.0"
change-notes = "0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
change-notes = "0.1.1 — say why no suggestions appear (network access, missing model, Ollama not running) and choose the model with AI Completion: Set Model. 0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
categories = ["ai"]
engines.openidea = "^1.0"
wasm = "dist/plugin.wasm"
@@ -43,3 +43,8 @@ category = "AI Completion"
id = "set-endpoint"
title = "AI Completion: Set Endpoint URL"
category = "AI Completion"
[[contributes.commands]]
id = "set-model"
title = "AI Completion: Set Model"
category = "AI Completion"
+114 -6
Переглянути файл
@@ -22,6 +22,8 @@ const SUFFIX_CHARS: usize = 1000;
pub struct AiCompletion {
/// Why the last request failed, so it is logged once rather than per keystroke.
last_error: Option<String>,
/// The last failure shown to the user, so a notice is not repeated.
last_notice: Option<String>,
}
struct Config {
@@ -48,6 +50,34 @@ fn config() -> Config {
Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") }
}
/// What to tell the user about a failed request: why, and what to do.
pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result<String, Error>) -> String {
match failure {
Err(Error::Denied(_)) => format!(
"AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion."
),
Ok(text) if !openai && text.starts_with("HTTP 404") => format!(
"The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model."
),
Err(Error::Failed(e)) if e.contains("timed out") => format!(
"{endpoint} took too long to answer; the model may still be loading, or be too large for this machine."
),
Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"),
Ok(text) => format!("{endpoint} answered {text}"),
Err(e) => format!("Could not reach {endpoint}: {e}"),
}
}
/// The command's argument, or what the user types (pre-filled with `current`);
/// `None` when dismissed.
fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result<Option<String>, Error> {
let value = match arg {
Some(a) => Some(a.to_owned()),
None => host::input(prompt, Some(current))?,
};
Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()))
}
/// The last `max` characters of `s` (on a char boundary).
fn tail(s: &str, max: usize) -> &str {
match s.char_indices().rev().nth(max.saturating_sub(1)) {
@@ -112,14 +142,21 @@ impl Providers for AiCompletion {
// Superseded by the next keystroke: nothing to report.
Err(Error::Cancelled) => None,
other => {
let msg = match other {
Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)),
let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200)));
let msg = match &failure {
Ok(m) => m.clone(),
Err(e) => e.to_string(),
};
if self.last_error.as_ref() != Some(&msg) {
host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint));
self.last_error = Some(msg);
}
// Otherwise a failure only shows in the IDE log, where nobody looks.
let notice = advice(&c.endpoint, &c.model, c.openai, &failure);
if self.last_notice.as_ref() != Some(&notice) {
host::notify(NotificationLevel::Warning, "AI Completion", &notice);
self.last_notice = Some(notice);
}
None
}
}
@@ -144,11 +181,23 @@ impl Plugin for AiCompletion {
}
}
"set-endpoint" => {
let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://"));
let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?;
storage::set("endpoint", url)?;
let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)?
else {
return Ok(None);
};
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("give the endpoint URL, e.g. http://localhost:11434".into());
}
storage::set("endpoint", &url)?;
format!("Using {url}.")
}
"set-model" => {
let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else {
return Ok(None);
};
storage::set("model", &model)?;
format!("Using the model {model}.")
}
"toggle" => {
let enabled = !config().enabled;
storage::set("enabled", if enabled { "true" } else { "false" })?;
@@ -156,6 +205,8 @@ impl Plugin for AiCompletion {
}
_ => return Err(Error::NotFound(format!("command {id}"))),
};
// A new setting may fix (or change) the failure: tell again.
self.last_notice = None;
host::notify(NotificationLevel::Info, "AI Completion", &msg);
Ok(Some(msg))
}
@@ -228,7 +279,7 @@ mod tests {
}
#[test]
fn quiet_when_cancelled_denied_or_mid_word() {
fn quiet_when_cancelled_or_mid_word() {
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied");
@@ -243,4 +294,61 @@ mod tests {
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
assert_eq!(host2.requests().len(), 1, "disabled: no request");
}
#[test]
fn tells_the_user_why_once_and_what_to_do() {
// Installed without the optional network permission (the default for it).
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none());
let notes = host.notifications();
assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}");
assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body);
// A model that is not pulled: Ollama answers 404.
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse {
status: 404,
headers: vec![],
body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"#
.to_vec(),
})
});
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
let body = &host.notifications()[0].body;
assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}");
// Ollama not running.
host.on_fetch(|_| Err(Error::Failed("connection refused".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[1].body.contains("Is it running?"));
host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[2].body.contains("took too long"));
}
#[test]
fn set_model_takes_an_argument_or_asks() {
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
});
let mut p = AiCompletion::default();
p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap();
assert_eq!(config().model, "qwen2.5-coder:7b");
// From the command palette: no argument, so it asks.
host.answer_next_prompt(Some(&["codellama:7b-code"]));
p.run_command("set-model", &host.invocation(), None).unwrap();
p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap();
let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap();
assert_eq!(body["model"], "codellama:7b-code");
// Dismissed: nothing changes.
assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None);
assert_eq!(config().model, "codellama:7b-code");
host.answer_next_prompt(Some(&["http://127.0.0.1:11434"]));
p.run_command("set-endpoint", &host.invocation(), None).unwrap();
assert_eq!(config().endpoint, "http://127.0.0.1:11434");
}
}
+6
Переглянути файл
@@ -11748,6 +11748,12 @@ export type NavigationFiles = {
paths: IpcPath[],
indexing: boolean,
extensions: string[],
/**
* In-scope files matching `extensions`; `paths` holds the first
* `MAX_NAVIGATION_FILES` of them.
*/
total: number,
truncated: boolean,
};
export type NavigationResult = {
+42 -2
Переглянути файл
@@ -1,12 +1,12 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
import { LanguageDescription, type Language } from "@codemirror/language";
import { LanguageDescription, indentUnit, type Language } from "@codemirror/language";
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { logWarning } from "./highlight";
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => {
@@ -765,3 +765,43 @@ describe("language modes", () => {
expect(found).not.toContain("yes:keyword");
});
});
describe("Slint indentation", () => {
it("indents element blocks by their braces under the C highlighting mode", async () => {
const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!);
const slint = commentTokens({
id: "slint",
name: "Slint",
extensions: ["slint"],
uiMode: "C",
lineComment: "//",
blockComment: ["/*", "*/"],
indent: { tabSize: 4, insertSpaces: true },
});
const enter = (doc: string, at = doc.length) => {
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.cursor(at),
extensions: [support!, slint, indentUnit.of(" ")],
}),
parent: document.body,
});
insertNewlineAndIndent(view);
const out = view.state.doc.toString();
view.destroy();
return out;
};
const app = "export component App inherits Window {";
expect(enter(app)).toBe(`${app}\n `);
expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`);
expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `);
// After a child element closes, the next line stays at the child's level.
expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe(
`${app}\n Text {\n text: "hi";\n }\n `,
);
expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe(
`${app}\n Text {\n }\n Rectangle {\n `,
);
});
});
+8 -1
Переглянути файл
@@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([
"gitattributes",
]);
/**
* Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's
* element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after
* one lands at the wrong column. These use the brace-based fallback indentation instead.
*/
const BRACE_INDENT_OVER_MODE = new Set(["slint"]);
function opensBlock(code: string, language: string | undefined): boolean {
if (!code) return false;
if (/[{([]$/.test(code)) return true;
@@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string
*/
export function fallbackIndent(language?: string): Extension {
return indentService.of((cx, pos) => {
if (cx.state.facet(languageFacet)) return undefined;
if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined;
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
const stripComment = (text: string) => indentationCode(text, lineComment);
+4
Переглянути файл
@@ -245,7 +245,11 @@ describe("remote attach requests", () => {
port: 9229,
localRoot: "/p",
remoteRoot: "/usr/src/app",
autoAttachChildProcesses: false,
});
// Without a remote root the program may be local, and its child processes are followed.
const local = JSON.parse(remoteAttachConfig(configOf(nodeRemoteType), "/p")!.extraJson!);
expect(local).not.toHaveProperty("autoAttachChildProcesses");
});
it("Attach to Node.js reconnects automatically only when the option is on", () => {
+5 -1
Переглянути файл
@@ -502,7 +502,11 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
type: "pwa-node",
address: host,
port: portOf(p, 9229),
...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}),
// On a loopback address (a published container port, an SSH tunnel) js-debug makes the
// program require its child-process bootloader by a path on this machine. Behind a
// remote root that path is missing: tsx's esbuild worker dies of it and the program
// waits for that worker forever.
...(map ? { localRoot: map.local, remoteRoot: map.remote, autoAttachChildProcesses: false } : {}),
skipFiles: skip ? ["<node_internals>/**", "**/node_modules/**"] : [],
...(p.restart === "true" ? { restart: true } : {}),
});
+28 -1
Переглянути файл
@@ -5,7 +5,8 @@ import { useProject } from "@/platform/project";
import { usePlugins } from "./store";
import { useEditorRegistry } from "@/editor/api";
import { lspDoc } from "@/editor/lsp/lsp";
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
import { notifications, provideNotificationService, synchronizeDocumentIndexes } from "@/workbench/contributions";
import { setLocale, txTemplate, useI18n } from "@/platform/i18n";
const mocks = vi.hoisted(() => ({
files: vi.fn(),
@@ -215,3 +216,29 @@ it("keeps unrelated language-server queries available when plugin discovery fail
await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true);
expect(mocks.index).not.toHaveBeenCalled();
});
it("indexes the first files of a large project and says how many it covers, in one sentence", async () => {
mocks.files.mockResolvedValue({
status: "ok",
data: { paths: ["/project/A.java"], indexing: false, extensions: ["java"], total: 28684, truncated: true },
});
useProject.setState({ project: { root: "/project", name: "big-demo", trusted: true } as never });
const notify = vi.fn();
const previous = notifications();
const locale = useI18n.getState().locale;
provideNotificationService({ notify } as never);
try {
await setLocale("zh");
off = startPluginNavigation();
await vi.advanceTimersByTimeAsync(250);
expect(mocks.index.mock.calls[0]?.[0]).toEqual(["/project/A.java"]);
expect(notify).toHaveBeenCalledTimes(1);
const body = notify.mock.calls[0]![0].body;
expect(body).toBe("插件导航仅覆盖 big-demo 中 28,684 个文件里的 1 个;可排除文件夹以缩小范围");
// The balloon and the OS toast look the text up again: it stays whole.
expect(txTemplate(body)).toBe(body);
} finally {
provideNotificationService(previous);
await setLocale(locale);
}
});
+15
Переглянути файл
@@ -47,6 +47,19 @@ export function startPluginNavigation(): () => void {
body: String(error),
});
}
let reportedTruncated = false;
function reportTruncated(count: number, total: number) {
if (reportedTruncated) return;
reportedTruncated = true;
const project = useProject.getState().project;
const name = project?.displayName || project?.name || "";
notifications().notify({
group: "plugins",
level: "warning",
title: "Plugin navigation indexing incomplete",
body: tx`Plugin navigation covers ${count.toLocaleString()} of ${total.toLocaleString()} files in ${name}; exclude folders to narrow it`,
});
}
let fileExtensions = new Set<string>();
const extensions = () => fileExtensions;
const eligible = (path: string) => extensions().has(path.split(".").pop() ?? "");
@@ -142,6 +155,7 @@ export function startPluginNavigation(): () => void {
inventory.paths.forEach((p) => known.add(p));
queue(fresh);
queue([...views.values()], true);
if (inventory.truncated) reportTruncated(inventory.paths.length, inventory.total);
} catch (error) {
discovered = false;
discoveryFailed = true;
@@ -165,6 +179,7 @@ export function startPluginNavigation(): () => void {
discoveryFailed = false;
discovery = null;
reportedError = false;
reportedTruncated = false;
notify();
if (ready())
void call(commands.pluginNavigationInvalidate(null))
+2 -2
Переглянути файл
@@ -100,9 +100,9 @@ export function ProjectHeaderActions() {
{!alwaysSelect && (
<IconButton
icon="locate"
action="navigate.selectInProjectView"
action="project.selectOpenedFile"
title="Select Opened File"
shortcut={shortcutLabel("navigate.selectInProjectView")}
shortcut={shortcutLabel("project.selectOpenedFile")}
size="small"
/>
)}
+10
Переглянути файл
@@ -254,6 +254,16 @@ export function registerProjectActions(): () => void {
keywords: ["locate", "reveal", "scroll from source", "select opened file"],
run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null),
},
{
// IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button.
id: "project.selectOpenedFile",
title: "Select Opened File",
category: "Project View",
icon: "locate",
when: OPEN,
keywords: ["locate", "reveal", "scroll from source", "select in project view"],
run: () => void selectInProjectView(null),
},
{
id: "project.reveal",
title: "Reveal in Project View",
+12
Переглянути файл
@@ -152,6 +152,18 @@ describe("Select In (⌥F1)", () => {
expect(useContextMenuStore.getState().menu).toBeNull();
});
it("Select Opened File is a Project View action of its own, as in IDEA's keymap", async () => {
const { IDEA_ACTIONS } = await import("@/platform/ideaActions");
disposers.push(registerProjectActions(), () => setContext("projectOpen", false));
setContext("projectOpen", true);
expect(getAction("project.selectOpenedFile")).toMatchObject({
title: "Select Opened File",
category: "Project View",
});
expect(IDEA_ACTIONS.SelectOpenedFileInProjectView).toBe("project.selectOpenedFile");
expect(IDEA_ACTIONS.SelectInProjectView).toBe("navigate.selectInProjectView");
});
it("expands an in-project folder when expand is true and reveals out-of-project folders in the file manager", async () => {
const { useProjectTree } = await import("./store");
const prev = useProjectTree.getState();
+23
Переглянути файл
@@ -101,6 +101,29 @@ describe("resolveMonoFont", () => {
});
});
describe("a chosen family that isn't installed", () => {
afterEach(() => {
vi.resetModules();
});
it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => {
const fonts = await import("./fonts");
// Before the native catalog loads nothing is known to be missing.
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`);
fonts.noteInstalledFonts(["PingFang SC", "Menlo"]);
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(
`"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`,
);
// Installed, bundled and generic families keep the fallback right after them; so does no fallback.
expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe(
`"Inter", "Inter Variable", "PingFang SC", ${BASE}`,
);
expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`);
});
});
describe("discovered Nerd Font fallbacks (#3723)", () => {
afterEach(() => {
vi.resetModules();
+20 -2
Переглянути файл
@@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise<void> {
* face is named alone unless the native catalog lists an installed JetBrains Mono.
*/
let monoInstalled: boolean | null = null;
/** Lower-cased installed family names from the native catalog, once it has loaded. */
let installedFamilies: ReadonlySet<string> | null = null;
const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true;
const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace';
/** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */
export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void {
monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase());
installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase()));
monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase());
installMonoStack(root);
}
@@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base =
const name = familyName(family ?? "");
const fb = familyName(fallback);
const head = familyFaces(name || BUNDLED_MONO_FAMILY);
return [...head, ...(fb ? familyFaces(fb) : []), base].join(", ");
// A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face
// whose Latin letters are proportional: a grid measures its cells by the widest of them and
// the text comes out spread apart. The bundled face stands in for the missing one, and the
// fallback still covers what that lacks.
const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : [];
return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", ");
}
const GENERIC_FAMILIES =
/^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i;
/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */
function familyMissing(name: string): boolean {
if (!installedFamilies) return false;
const key = name.toLowerCase();
return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name);
}
/** Tools › Terminal › Font, shared by the terminal and the Run console. */
+2
Переглянути файл
@@ -6,6 +6,8 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
GotoDeclaration: "navigate.declaration",
GotoImplementation: "navigate.implementation",
GotoTypeDeclaration: "navigate.typeDeclaration",
SelectInProjectView: "navigate.selectInProjectView",
SelectOpenedFileInProjectView: "project.selectOpenedFile",
GotoSuperMethod: "navigate.superMethod",
GotoTest: "navigate.gotoTest",
GotoRelated: "navigate.relatedSymbol",
+16
Переглянути файл
@@ -49,6 +49,22 @@ describe("IntelliJ IDEA keymap import", () => {
expect(k.overrides).toEqual({});
});
it("bases a keymap derived from Emacs on $default, not macOS", () => {
for (const parent of ["Emacs", "Emacs copy"]) {
const k = parseIdeaKeymap(`<keymap name="E" parent="${parent}"></keymap>`);
expect(k.parent).toBe("intellij-windows");
}
for (const [parent, preset] of [
["Mac OS X", "intellij-macos"],
["macOS System Shortcuts", "intellij-macos"],
["Eclipse (Mac OS X)", "eclipse-macos"],
["VSCode (macOS)", "vscode-macos"],
["Default for KDE", "intellij-windows"],
]) {
expect(parseIdeaKeymap(`<keymap name="K" parent="${parent}"></keymap>`).parent).toBe(preset);
}
});
it("maps Duplicate Entire Lines, which has no shortcut in the presets", () => {
const k = parseIdeaKeymap(
`<keymap name="M" parent="Mac OS X 10.5+"><action id="EditorDuplicateLines"><keyboard-shortcut first-keystroke="shift meta D"/></action></keymap>`,
+4 -2
Переглянути файл
@@ -31,11 +31,13 @@ export interface ImportedIdeaKeymap {
/** IDEA's bundled keymap names (`<keymap name=…>`) → our presets. */
function presetOf(parent: string | null): string {
const p = parent ?? "";
const mac = /mac/i.test(p);
// "Mac OS X 10.5+", "Eclipse (Mac OS X)", "VSCode (macOS)"; not the "mac" inside "Emacs".
const mac = /\bmac(?: ?os)?\b/i.test(p);
if (/^eclipse/i.test(p)) return mac ? "eclipse-macos" : "eclipse-windows";
if (/^vs ?code/i.test(p)) return mac ? "vscode-macos" : "vscode-windows";
if (mac) return "intellij-macos";
if (p === "$default" || /^default for/i.test(p)) return "intellij-windows";
// IDEA's Emacs keymap (and copies of it) inherits $default.
if (p === "$default" || /^default for/i.test(p) || /^emacs\b/i.test(p)) return "intellij-windows";
return defaultPreset();
}
+1
Переглянути файл
@@ -531,6 +531,7 @@ export const intellijMacos: Record<string, string[]> = {
"db.showDiagram": ["Meta+Alt+Shift+U"],
"db.showDiagramPopup": ["Meta+Alt+U"],
"db.selectOpened": [],
"project.selectOpenedFile": [],
"db.expandAll": [],
"db.collapseAll": [],
// Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there.
+1
Переглянути файл
@@ -529,6 +529,7 @@ export const intellijWindows: Record<string, string[]> = {
"db.showDiagram": ["Ctrl+Alt+Shift+U"],
"db.showDiagramPopup": ["Ctrl+Alt+U"],
"db.selectOpened": [],
"project.selectOpenedFile": [],
"db.expandAll": [],
"db.collapseAll": [],
// Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there.
+2 -1
Переглянути файл
@@ -4810,5 +4810,6 @@
"{count} files aren't in the Xcode project": "{count} files aren't in the Xcode project",
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
"Open in Xcode": "Open in Xcode"
"Open in Xcode": "Open in Xcode",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
}
+2 -1
Переглянути файл
@@ -11463,5 +11463,6 @@
"{count} files aren't in the Xcode project": "{count} 个文件不在 Xcode 项目中",
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
"Open in Xcode": "在 Xcode 中打开"
"Open in Xcode": "在 Xcode 中打开",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
}