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

...
Автор SHA1 Повідомлення Дата
l0ng-ai d6835c2b2f fix(color-scheme): an unticked Foreground keeps the text visible
Unticking Foreground stored the cleared colour and wrote `transparent` into
the attribute's colour variable, so its tokens became invisible. A cleared
foreground now falls back to the default text colour; cleared backgrounds
and effects stay transparent.

Refs #4059
2026-11-18 08:45:07 +08:00
l0ng-ai 2678698bf9 fix(agents): report a session that fails to load instead of replacing it (#4064)
When session/load failed for a task's saved session, the task silently
started a new session and stored its id over the old one, so the agent lost
the conversation without a word in the chat (OMP fails to load a session
saved with a model it cannot restore). The failure now shows in the chat and
keeps the saved session; sending again starts a new session. An
authentication failure during the load shows the sign-in error instead.

Fixes #4035
2026-11-18 08:43:12 +08:00
l0ng-ai e8d91b4615 docs: drop the memory indicator from the landing page screenshot (#4063) 2026-11-18 08:41:44 +08:00
Ray Liangтаcubelitblade c1f3debbb9 fix(terminal): use fish's hostname variable for OSC 7 (#4050)
The fish prompt hook ran the external hostname command to build the OSC 7
working-directory URL, so fish printed an error at every prompt where that
command is unavailable. It now uses fish's built-in \$hostname variable.

Closes #4046

Co-authored-by: cubelitblade <[email protected]>
2026-11-18 08:37:55 +08:00
l0ng-ai c1782f01eb docs: add a landing page and a plugin marketplace to the documentation site (#4033)
/en and /zh open a landing page: the product in the dark theme, startup and
memory numbers, the main features, featured plugins and the default keymap.
The introduction pages move to /en/introduction and /zh/introduction.

/plugins and /zh/plugins list the marketplace's plugins with search,
category filters, sorting and a details dialog. The list is a snapshot of
plugins-index.json written by `pnpm gen:plugin-catalog`.
2026-11-18 02:03:42 +08:00
Ernstjan FreriksтаEjaYF 9cfe667b6a fix(clipboard): build on Windows again after the command refactor (#4030)
#3598 moved blocking from src-tauri's commands::doc to ide_host::ops::doc,
but the Windows-only import in commands/clipboard.rs still named the old
path, so src-tauri no longer compiled on Windows. It now imports
ide_host::ops::doc::blocking like commands/db.rs and commands/perf.rs.

Co-authored-by: EjaYF <[email protected]>
2026-11-17 23:40:40 +08:00
Ernstjan FreriksтаEjaYF 318f4a2d82 feat(database): export with mysqldump and restore with mysql (#4001)
MySQL and MariaDB data sources, schemas and tables get Import/Export >
Export with 'mysqldump' and Restore with 'mysql'. ide-db builds the arguments
from typed options and runs the tool connected like the data source (TCP,
the driver's SSL flags, the SSH tunnel); the password goes in a user-only
temporary option file passed as --defaults-extra-file and removed after the
run. Restore pipes the dump into mysql's standard input.

Restore dialogs (MySQL and PostgreSQL) now check the target first: the
Database field lists the source's databases and disables Run for a missing
one, and db_dump_info (formerly db_dump_kind) reports whether an SQL dump
creates its database itself. pg_restore gains --create.

Part of #3188

Co-authored-by: EjaYF <[email protected]>
2026-11-17 23:39:50 +08:00
LU XIANGRUIтаwildcatDownstairs 31466f2834 feat(lsp): make type names in other languages' documentation signatures clickable (#4010)
Go signatures already linked their type names (#3959). For other languages
the name is looked up near the documented symbol's declaration and the
language server's definition there is the target; parameters, the symbol's
own name, inferred types and names with several definitions don't link.
Names resolve on hover, so only those that lead somewhere look like links,
and only the signature code blocks are considered (leading blocks, or the
one after the last rule for clangd). Plain names a grammar leaves untagged
get a tok-name span so they can be followed.

Refs #3874

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 23:29:20 +08:00
lleviathe 9f9beaa27c feat(mcp): show the callers and callees of a function with get_call_hierarchy (#4019)
The built-in MCP server had no call hierarchy, so agents fell back to text
search for callers. get_call_hierarchy returns one level of callers (default)
or callees of the function at a position through lsp_call_hierarchy, with
call sites and their line text, paging and scope like find_references; a
position inside a body means the enclosing function. ide-lsp reports the
hierarchy's root and the file of an outgoing call's sites. find_references
now shares the document guard and the cancel/timeout race with it.

Co-authored-by: lleviathe <[email protected]>
2026-11-17 23:27:25 +08:00
xiaowu0203 182285647e fix(editor): make rectangular mouse selection configurable (#4020)
The rectangular drag gestures were hard-coded, and a middle-button press
navigated immediately, which cut off a middle drag. A new keymap action,
Create Rectangular Selection on Mouse Drag (Alt+Left and Middle by default),
now decides the gesture; middle-click navigation fires on release when the
mouse did not move. Linux keeps middle-button paste unless the user binds the
middle button explicitly, and the mouse shortcut recorder accepts modified
middle clicks.

Closes #3713

Co-authored-by: xiaowu0203 <[email protected]>
2026-11-17 23:22:56 +08:00
Yann ba4bf0ce1d fix(agents): show Codex asynchronous questions (#4013)
Codex attaches non-blocking questions to completed agent messages, but the
question metadata was discarded and only the message text was shown. The
Codex shim now emits them as user_question updates (live and from history),
the timeline keeps them as Question entries that survive the turn's end and
restarts, and the existing question card answers them with Codex's stable
question ids: a running turn is steered, an idle task starts a normal turn.
Skipping does not cancel the agent; blocking permission questions keep
priority over asynchronous ones.

Co-authored-by: YannABC <[email protected]>
2026-11-17 23:19:50 +08:00
l0ng-ai 76c75b0f7f fix(plugins): deliver document-changed events to plugins (#4028)
The event queue relativized path events at enqueue time, so the delivery
filter looked up a project-relative document path, found no project and
dropped every document-changed event. Document paths now stay absolute
through filtering and are relativized to the file's own project at hand-off.
The path-events fixture subscribes document-changed to cover the flow.

Fixes #4008
2026-11-17 23:13:54 +08:00
l0ng-ai c8a91e5b0f feat(appearance): Presentation Assistant (#4026)
While on, each action the user runs shows its name and shortcut in a popup, for screencasts and demos. Toggled from View › Appearance › Presentation Assistant; Settings › Appearance › Presentation Assistant sets the popup size, duration, position and whether to also show the other platform's shortcut (macOS ⇄ Windows/Linux). Hidden actions are not shown.

Closes #3949
2026-11-17 23:01:12 +08:00
l0ng-ai a430d4ace7 fix(tools): fail and retry a stalled tool download instead of hanging (#4024)
Tool downloads used curl with only a connect timeout, so a connection that stopped delivering (a stalled proxy or mirror) left Install waiting indefinitely. Requests now fail after 30 s without data (--speed-limit 1 --speed-time 30), which curl's --retry treats as transient and retries.
2026-11-17 22:47:14 +08:00
l0ng-ai 7e5277eaa6 feat(languages): Typst with the tinymist language server (#4023)
Typst (.typ) files get syntax colouring for markup, embedded code and math, a file icon, and the tinymist language server (installable from its GitHub releases) for completion, diagnostics, navigation and the outline.

Closes #3924
2026-11-17 22:44:13 +08:00
l0ng-ai 2278cf6e8f fix(editor): don't indent C++ namespace and extern "C" contents on Enter (#4018)
Enter inside namespace x { … } or extern "C" { … } indented the new line one level, like any brace body. clang-format's built-in styles (LLVM, Google, Chromium, Mozilla, Microsoft, GNU) keep those contents at the level of the braces' line (NamespaceIndentation: None), so the editor now does too; other brace bodies keep their indentation.

Fixes #3993
2026-11-17 22:10:13 +08:00
l0ng-ai d4f6114be1 feat(settings): context menu for the deployment server list (#4017)
Right-clicking a server or server group in Settings › Build, Execution, Deployment › Deployment selects it and offers Add (Server / Server Group), Duplicate and Use as Default for a server, and Remove; the empty part of the list offers Add.

Closes #3910
2026-11-17 22:03:35 +08:00
l0ng-ai ad93e491c9 feat(settings): choose PHP include paths with a folder chooser (#4016)
+ under Settings › Languages & Frameworks › PHP › Include paths opens a folder chooser and adds the picked folder; Edit and double-click still take a typed path, and outside the desktop app + keeps adding a row to type into. Additional stubs are stub names, so that list stays typed.

Closes #3912
2026-11-17 22:00:43 +08:00
l0ng-ai 098e80dbef fix(agents): name the task's agent in the session status line (#4015)
The session status line under the composer lost the agent's icon and name when it was reduced to one quiet line; with several tasks open side by side there was no way to tell which agent answered without opening the picker. It starts with the agent's icon and name again, before the branch.

Fixes #3917
2026-11-17 21:58:00 +08:00
l0ng-ai 6ab7627fc4 feat(vcs): project conventions for Generate Commit Message with Agent (#4014)
Settings › Version Control › Commit gets a Commit Message Generation section with a multi-line field (vcs.commit.agentInstructions, global or per project). Its text is added to the agent's prompt as the conventions to follow, ahead of the style taken from recent commit subjects.

Closes #3934
2026-11-17 21:53:38 +08:00
l0ng-ai 55e778897f feat(vcs): show a stash's changed files and their diff in the Stash tab (#4012)
Stashes in the Commit tool window's Stash tab expand to the files they changed against the commit they were made on; selecting a file previews its diff (with Show Diff Preview on) and double-clicking opens it. Double-clicking a stash expands it instead of applying it; Apply / Pop / Unstash stay on the toolbar and context menu. Stash (IPC) now carries the stash commit and its base.

Closes #3968
2026-11-17 21:45:50 +08:00
l0ng-ai cc6ed6b5fd feat(editor): copy a multi-line selection's path as path:first-last (#4011)
Copy Path with Line Number (and its entry in Copy Path/Reference…) copies path:12-18 when the selection spans several lines, leaving out a last line the selection only reaches the start of; a caret or single-line selection still copies path:12.

Closes #3962
2026-11-17 21:39:11 +08:00
Vadim LazukтаInf1mum 5efd58d3af fix(workbench): move any project tab to a new window from its own arrow (#3991)
The Move Tab to New Window arrow was one bar-level button drawn inside the last tab, above its centre line, and always moved the selected tab. Every project tab now has its own arrow on its right edge, centred and revealed on hover like the close button, and the tab context menu's Move Tab to New Window works on any tab. window_group_detach takes the tab's label and selects it before detaching; without an argument (Find Action) the action still moves the selected tab.

Fixes #3954

Co-authored-by: Inf1mum <[email protected]>
2026-11-17 21:37:59 +08:00
acaoтаamphetamlne d250b351bb fix(index): report accurate scan work counts (#3229)
Index scans log what they actually did as structured fields: files discovered, metadata reused, candidates scheduled, and mutually exclusive extraction outcomes (symbols extracted, hash reused, ignored, oversized, binary, unsupported, read failed, not processed), instead of calling every metadata-stale candidate parsed. Warm-snapshot startup and fallback scans log their phases separately; cancelled scans log no completion summary. Indexing behaviour is unchanged.

Co-authored-by: amphetamlne <[email protected]>
2026-11-17 21:34:47 +08:00
Aditya Aggarwalтаaditya-786 033f049caf feat(spring): navigate from Feign client methods to controller endpoints (#3997)
Feign client methods in Java and Kotlin get a Go to Feign Endpoint gutter arrow and action, and Go to Declaration on a literal mapping path opens the matching controller methods. Matching reuses the Spring route index (HTTP method + literal path, whole {variable} segments); a literal Feign name narrows candidates to the module whose spring.application.name matches, while dynamic or missing identities and explicit url clients keep every method/path candidate in the declaration chooser.

Refs #3882

Co-authored-by: aditya-786 <[email protected]>
2026-11-17 21:30:26 +08:00
lleviathe 74157ffe54 fix(editor): highlight toml keys, dates and booleans like IntelliJ (#3981)
Adds a TOML stream parser so keys are coloured as keys wherever they stand (table headers, dotted keys, inline tables), with numbers, booleans/dates, strings and valid/invalid escapes told apart, in files, lock files and fenced code blocks.

Co-authored-by: lleviathe <[email protected]>
2026-11-17 21:27:09 +08:00
lleviathe 732e92f756 fix(editor): colour .env and properties keys like other key-value files (#3979)
Adds a properties/.env stream language wrapper so keys use the keyword colour, the first separator the operator colour and values the string colour.

Co-authored-by: lleviathe <[email protected]>
2026-11-17 21:23:53 +08:00
QтаNeverKnowsTomorrow a83bad107c fix(plugins): ask before loading a changed Java agent (#4003)
When a plugin's Java agent jar changed, the host already refused to load it until java.agent was granted again, but Settings still showed the permission as granted, so the agent silently disappeared from Run/Debug. PluginInfo now carries the agent's file name, arguments and whether its jar still matches the approved hash; Settings › Plugins warns about a changed jar and offers Approve new jar, which grants the permission again.

Co-authored-by: NeverKnowsTomorrow <[email protected]>
2026-11-17 21:20:40 +08:00
Akbar Husain 39f709def5 fix(run): debug Zig build steps via the executable config (#4002)
Debug on a detected 'zig build run' configuration said it had no debug adapter: build-step configs only run 'zig build <step>'. Steps that run an executable (addRunArtifact in build.zig) now link to that executable's config, and Debug delegates to it — running its before-launch build and keeping the clicked step as the session's origin.

Refs #3260

Co-authored-by: akbar1214 <[email protected]>
2026-11-17 21:17:05 +08:00
pravdomil ea6638b05e fix(editor): keep scroll inertia out of ⌘/Ctrl+wheel font zoom (#3985)
WebViews don't expose macOS momentum phases, so a trackpad scroll still coasting when ⌘ was pressed zoomed the text, and the inertia after a ⌘ swipe kept zooming. Wheel events less than 150 ms apart now count as one gesture: only a gesture that started with ⌘/Ctrl zooms, and once its deltas shrink four events in a row the rest is inertia. All ⌘/Ctrl+wheel font-zoom surfaces use it (editor, terminal, agent chat, Markdown preview, plugin and services log editors).

Co-authored-by: pravdomil <[email protected]>
2026-11-17 21:15:20 +08:00
TarasтаTarasMK a91421c6e0 fix(docker): list containers without asking the daemon for their sizes (#3976)
Containers were listed with --format '{{json .}}', which includes Size, so the daemon computed every container's writable layer and a busy daemon exceeded the 20 s listing timeout ('docker did not respond in time', no Compose groups). The listing now uses a template with only the fields the parser reads.

Fixes #3975

Co-authored-by: TarasMK <[email protected]>
2026-11-17 21:13:09 +08:00
l0ng-ai 973f0a18a8 fix(vue): don't indent code in top-level <script> and <style> blocks (#4009)
The HTML base indented every element's children, so Enter in <script setup> indented the new line. Like WebStorm's Vue code style, only the top-level <template>'s children are indented; code in top-level <script> and <style> blocks starts at the margin.

Fixes #3982
2026-11-17 21:11:13 +08:00
Vadim LazukтаInf1mum fb64f0cd26 fix(vcs): say whether blocked checkout would remove or overwrite the untracked files (#4005)
When git refused a checkout because of untracked files, the notification always said they would be overwritten; git's own reason (removed vs overwritten) is now carried on CheckoutOutcome::UntrackedFiles and the notification uses git's wording for each case.

Fixes #3980

Co-authored-by: Inf1mum <[email protected]>
2026-11-17 21:07:39 +08:00
195 змінених файлів з 11126 додано та 630 видалено

No files matched your search

+1
Переглянути файл
@@ -9,6 +9,7 @@
"dist",
"target",
"src/bindings.ts",
"docs/snippets/plugin-catalog.jsx",
"evals/*/golden",
"src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/jsp/parser*.ts",
+80
Переглянути файл
@@ -0,0 +1,80 @@
//! Codex's asynchronous questions are answered by a user message, not a permission response.
use crate::AgentQuestion;
use ide_core::{IdeError, IdeResult};
use serde_json::json;
use std::collections::BTreeMap;
/// The wire reply and its readable record. Question ids, not wording, associate each answer.
pub(crate) fn reply(questions: &[AgentQuestion], answers: &str) -> IdeResult<(String, String)> {
let answers: BTreeMap<String, Vec<String>> =
serde_json::from_str(answers).map_err(|_| IdeError::invalid("invalid question answers"))?;
if questions.is_empty() || answers.len() != questions.len() {
return Err(IdeError::invalid("answer every question"));
}
let mut replies = Vec::new();
let mut record = Vec::new();
for question in questions {
let key = question.answer_key.as_deref().ok_or_else(|| IdeError::invalid("missing question id"))?;
let values = answers.get(key).ok_or_else(|| IdeError::invalid("missing question answer"))?;
if values.is_empty()
|| (!question.multi_select && values.len() != 1)
|| values.iter().any(|v| v.trim().is_empty())
{
return Err(IdeError::invalid("empty or invalid question answer"));
}
let answer = values.iter().map(|v| v.trim()).collect::<Vec<_>>().join(", ");
let mut title = question.question.clone();
let mut end = title.len().min(512);
while !title.is_char_boundary(end) {
end -= 1;
}
title.truncate(end);
title = title.replace(['\n', '\r'], " ");
replies.push(json!({ "questionItemId": key, "question": title, "answer": answer }));
record.push(format!("{}: {}", question.question, answer));
}
Ok((
format!("<send_user_message_question_reply>\n{}\n</send_user_message_question_reply>", json!(replies)),
record.join("\n"),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn question(key: &str) -> AgentQuestion {
AgentQuestion {
answer_key: Some(key.into()),
header: String::new(),
question: "Which?".into(),
multi_select: false,
options: Vec::new(),
}
}
#[test]
fn identical_wording_keeps_answers_associated_with_ids() {
let (wire, record) =
reply(&[question("first"), question("second")], r#"{"first":[" One "],"second":["Two"]}"#).unwrap();
let body = wire
.strip_prefix("<send_user_message_question_reply>\n")
.unwrap()
.strip_suffix("\n</send_user_message_question_reply>")
.unwrap();
let replies: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(replies[0], json!({"questionItemId":"first","question":"Which?","answer":"One"}));
assert_eq!(replies[1]["answer"], "Two");
assert_eq!(record, "Which?: One\nWhich?: Two");
}
#[test]
fn malformed_missing_and_empty_answers_are_rejected() {
for answers in
["no", "{}", r#"{"other":["One"]}"#, r#"{"first":[]}"#, r#"{"first":[" "]}"#, r#"{"first":["One","Two"]}"#]
{
assert!(reply(&[question("first")], answers).is_err(), "{answers}");
}
}
}
+75 -3
Переглянути файл
@@ -8,6 +8,7 @@
//! next prompt when the agent supports `session/load`.
mod acp;
mod async_questions;
mod catalogs;
mod config;
mod conversation;
@@ -415,11 +416,15 @@ struct Task {
live: Mutex<Option<Live>>,
/// Serializes starting the agent.
connecting: tokio::sync::Mutex<()>,
/// Serializes replies from multiple windows to the same async question.
answering_questions: tokio::sync::Mutex<()>,
/// Unanswered permission requests: where to send the chosen option id.
permissions: Mutex<HashMap<u32, std::sync::mpsc::Sender<Option<String>>>>,
next_permission: AtomicU32,
/// Set while `session/load` replays history we already have.
replaying: AtomicBool,
/// The saved session failed to load and the user was told: the next start opens a new one.
start_fresh: AtomicBool,
/// The current turn is being cancelled to send the first queued message right away.
send_now: AtomicBool,
/// The user stopped the current turn. A stop that reaches the agent before it took the
@@ -1409,6 +1414,53 @@ impl AgentManager {
}
}
/// Replies to a non-blocking question without interrupting the agent's current turn.
pub async fn answer_question(&self, id: &str, question: &str, answer: Option<String>) -> IdeResult<()> {
let task = self.task(id)?;
let _answering = task.answering_questions.lock().await;
let questions = {
let s = task.state.lock();
s.conversation
.main
.entries
.iter()
.find_map(|entry| match entry {
AgentEntry::Question { id, questions, chosen: None, .. } if id == question => {
Some(questions.clone())
}
_ => None,
})
.ok_or_else(|| IdeError::not_found("the question was already answered"))?
};
let chosen = match answer {
None => "Skipped".to_owned(),
Some(answer) => {
let (text, record) = async_questions::reply(&questions, &answer)?;
let prompt = AgentPrompt { text, files: Vec::new(), images: Vec::new() };
if let Err(prompt) = task.steer(prompt).await {
if task.state.lock().busy {
return Err(IdeError::unavailable("the reply could not join the running turn; try again"));
}
self.prompt(id, prompt, false).await?;
}
record
}
};
let changed = {
let mut s = task.state.lock();
s.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
AgentEntry::Question { id, chosen: current, .. } if id == question => {
*current = Some(chosen.clone());
Some((None, index))
}
_ => None,
})
};
task.mark_dirty(changed);
task.persist();
Ok(())
}
/// Stops the agent and moves the task to Archived; its worktree stays.
pub fn archive(&self, id: &str) -> IdeResult<()> {
let task = self.task(id)?;
@@ -1707,9 +1759,11 @@ impl Task {
}),
live: Mutex::new(None),
connecting: tokio::sync::Mutex::new(()),
answering_questions: tokio::sync::Mutex::new(()),
permissions: Mutex::new(HashMap::new()),
next_permission: AtomicU32::new(1),
replaying: AtomicBool::new(false),
start_fresh: AtomicBool::new(false),
send_now: AtomicBool::new(false),
cancel_pending: AtomicBool::new(false),
turn_started: AtomicBool::new(false),
@@ -2318,7 +2372,8 @@ impl Task {
let mut tried_auth = false;
let mut session = None;
if let (Some(id), true) = (saved, can_load) {
let start_fresh = self.start_fresh.load(Ordering::Acquire);
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(&id);
@@ -2327,7 +2382,23 @@ impl Task {
self.replaying.store(false, Ordering::Release);
match loaded {
Ok(v) => session = Some((id, v)),
Err(e) => tracing::info!("agent task {}: session/load failed, starting a new session: {e}", self.id),
// Not silently: a new session would lose the conversation and replace the saved id.
Err(e) => {
tracing::info!("agent task {}: session/load failed: {e}", self.id);
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
self.start_fresh.store(true, Ordering::Release);
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
continue in a new session. The agent won't see the earlier conversation.",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
}
}
let resumed = session.is_some();
@@ -2432,6 +2503,7 @@ impl Task {
s.task.config = options;
s.task.capabilities = capabilities;
s.session_id = Some(session_id.clone());
self.start_fresh.store(false, Ordering::Release);
// The (re)started process runs nothing yet: whatever it reports next is all of it.
s.background_tasks = Vec::new();
s.task.background.clear();
@@ -2655,7 +2727,7 @@ impl Task {
let applied = self.state.lock().conversation.apply(session, update, now_ms());
self.mark_dirty(applied);
// A subagent can start or finish after the turn that started it: saved right away.
if kind == "subagent_update" {
if matches!(kind, "subagent_update" | "user_question") {
self.persist();
}
}
+8
Переглянути файл
@@ -469,6 +469,14 @@ pub enum AgentEntry {
Agent {
text: String,
},
/// A question that can be answered while the agent keeps working, or after the turn ends.
Question {
id: String,
title: String,
questions: Vec<AgentQuestion>,
/// The submitted answers, or `Skipped`; `None` while unanswered.
chosen: Option<String>,
},
Thought {
text: String,
},
+5
Переглянути файл
@@ -1028,6 +1028,11 @@ impl CodexShim {
}
Some(t.chunk(kind, &id, &text))
});
if ty == "agentMessage"
&& let Some(update) = translate::question_update(item)
{
self.emit(thread, update);
}
}
"subAgentActivity" => {
let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default();
+50
Переглянути файл
@@ -473,6 +473,56 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed");
}
#[test]
fn history_preserves_async_questions_with_stable_answer_ids() {
let updates = history(
&json!({"turns": [{"items": [{
"type": "agentMessage", "id": "call-1", "text": "Which?",
"questions": [{"title": "Which?", "options": ["One", "Two"]}, {"title": "Why?"}]
}]}]}),
None,
);
let asked = updates.iter().find(|u| u["sessionUpdate"] == "user_question").expect("question update");
assert_eq!(asked["id"], "call-1");
assert_eq!(asked["questions"][0]["answerKey"], r#"["request_user_input_async","call-1",0]"#);
assert_eq!(asked["questions"][0]["options"][1]["label"], "Two");
assert_eq!(asked["questions"][1]["options"], json!([]));
}
#[tokio::test]
async fn completing_a_streamed_message_still_delivers_its_async_questions() {
let shim = Arc::new(CodexShim {
runtime: tokio::runtime::Handle::current(),
codex: OnceLock::new(),
client: OnceLock::new(),
state: Mutex::default(),
models: tokio::sync::Mutex::new(None),
skills: tokio::sync::Mutex::new(()),
});
shim.state.lock().threads.insert("thread".into(), Thread::default());
let client = Arc::new(Client::default());
let peer = crate::native::serve(shim.clone(), client.clone());
shim.text("thread", &json!({"itemId":"call-1","delta":"Which?"}), "agent_message_chunk", false);
shim.item(
"thread",
&json!({"type":"agentMessage","id":"call-1","text":"Which?",
"questions":[{"title":"Which?","options":["One","Two"]}]}),
true,
);
tokio::time::timeout(Duration::from_secs(2), async {
while client.of("thread").len() < 2 {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
assert_eq!(client.text("thread", "agent_message_chunk"), "Which?");
assert!(client.of("thread").iter().any(|u| u["sessionUpdate"] == "user_question"));
assert!(client.asked.lock().is_empty(), "an asynchronous question must not block on a permission response");
peer.kill();
shim.client.get().unwrap().kill();
}
// ---- Transcripts ---------------------------------------------------------------------
/// The ACP client: records updates and answers permission requests in order.
+31
Переглянути файл
@@ -871,6 +871,7 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
if !text.is_empty() {
out.push(chunk("agent_message_chunk", text));
}
out.extend(question_update(item));
}
Some("reasoning") => {
let text = reasoning_text(item);
@@ -890,6 +891,36 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
out
}
/// Structured async questions accompany a completed message, even when its text streamed already.
pub(super) fn question_update(item: &Value) -> Option<Value> {
let id = item.get("id")?.as_str().filter(|id| !id.is_empty())?;
let questions: Vec<Value> = item
.get("questions")?
.as_array()?
.iter()
.enumerate()
.filter_map(|(index, q)| {
let title = q.get("title")?.as_str().filter(|title| !title.trim().is_empty())?;
let options: Vec<Value> = q
.get("options")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.filter(|label| !label.trim().is_empty())
.map(|label| json!({ "label": label, "description": "" }))
.collect();
Some(json!({ "answerKey": json!(["request_user_input_async", id, index]).to_string(),
"question": title, "header": "", "multiSelect": false, "options": options }))
})
.collect();
if questions.is_empty() {
return None;
}
Some(json!({ "sessionUpdate": "user_question", "id": id,
"title": questions[0]["question"], "questions": questions }))
}
/// A reasoning item's summary (or, without one, its raw text).
pub(super) fn reasoning_text(item: &Value) -> String {
let parts = |k: &str| -> Vec<String> {
+126 -2
Переглянути файл
@@ -39,6 +39,8 @@ struct FakeAgent {
authenticate_method: Option<String>,
authenticated: AtomicBool,
request_error: Option<(i64, String)>,
/// `session/load` fails with this, as OMP does for a session whose model it can't restore.
load_error: Option<(i64, String)>,
auth_methods: Vec<Value>,
/// Hold the late mode reply until the prompt's permission request is already waiting.
hold_late_mode: bool,
@@ -212,6 +214,7 @@ impl Handler for FakeAgent {
let outcome = if text == "too late" { "promptRequired" } else { "injected" };
Ok(json!({"outcome": outcome, "queue": "steering"}))
}
"session/load" if self.load_error.is_some() => Err(self.load_error.clone().unwrap()),
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
@@ -245,6 +248,10 @@ impl Handler for FakeAgent {
}
"session/prompt" => {
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
if text.starts_with("<send_user_message_question_reply>") {
self.say(&session, "answer received");
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "again" {
self.say(&session, "second turn");
return Ok(json!({"stopReason": "end_turn"}));
@@ -866,7 +873,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
["session/load", "authenticate", "authenticate github_oauth", "session/load", "session/prompt"],
);
// If `authenticate` fails during `session/load`, fallback to `session/new` does not try it again.
// If `authenticate` fails during `session/load`, the sign-in error stands: no new session replaces it.
mgr2.shutdown();
let agent3 = Arc::new(FakeAgent {
auth_on_load: true,
@@ -885,7 +892,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
.iter()
.filter(|c| c.starts_with("session/") || c.starts_with("authenticate"))
.collect::<Vec<_>>(),
["session/load", "authenticate", "session/new"],
["session/load", "authenticate"],
);
mgr3.shutdown();
}
@@ -1150,10 +1157,127 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// OMP: "Could not restore model …" for a session saved with a model it can't restore.
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "Could not restore model x".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
let calls = |agent: &FakeAgent| -> Vec<String> {
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
};
assert_eq!(calls(&agent), ["session/load"], "no new session behind the user's back");
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.state.lock().session_id.as_deref(), Some(saved.as_str()));
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|e| matches!(e,
AgentEntry::Error { message } if message.contains("Could not restore model x") && message.contains("Send the message again"))));
// Sending again is the user's choice to continue without the earlier conversation.
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
fn asynchronous_question() -> Value {
json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]})
}
#[tokio::test(flavor = "multi_thread")]
async fn async_question_answers_join_the_turn_and_skipping_does_not_cancel_it() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent { session_steering: true, ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
let handle = mgr.task(&task.id).unwrap();
handle.on_update(Some("s1"), &asynchronous_question());
assert!(mgr.answer_question(&task.id, "call-1", Some("{}".into())).await.is_err());
handle.live.lock().as_mut().unwrap().capabilities.steer = false;
assert!(mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.is_err());
assert!(handle.state.lock().task.queue.is_empty());
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
handle.live.lock().as_mut().unwrap().capabilities.steer = true;
mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.unwrap();
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
assert!(
agent.calls.lock().iter().any(|call| call.starts_with("_session/steering ") && call.contains("questionItemId"))
);
assert!(!agent.calls.lock().iter().any(|call| call == "session/cancel"));
assert!(mgr.answer_question(&task.id, "call-1", None).await.is_err());
let mut question = asynchronous_question();
question["id"] = json!("call-2");
handle.on_update(Some("s1"), &question);
mgr.answer_question(&task.id, "call-2", None).await.unwrap();
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Question { chosen: Some(chosen), .. }) if chosen == "Skipped")
);
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn async_questions_can_be_answered_after_the_turn_ends() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.task(&task.id).unwrap().on_update(Some("s1"), &asynchronous_question());
mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|entry| matches!(entry, AgentEntry::Question { chosen: Some(answer), .. } if answer == "Which?: One"))
);
let entries = mgr.entries(&task.id, None).unwrap();
assert!(
entries.iter().any(|entry| matches!(entry, AgentEntry::User { text, .. } if text.contains("questionItemId")))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn steers_through_session_steering() {
let tmp = tempfile::tempdir().unwrap();
+36
Переглянути файл
@@ -54,6 +54,23 @@ impl Timeline {
let mut out = Applied::default();
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
match kind {
"user_question" => {
let id = str_field(update, "id");
let Ok(questions) = serde_json::from_value::<Vec<crate::model::AgentQuestion>>(
update.get("questions").cloned().unwrap_or(Value::Null),
) else {
return out;
};
if id.is_empty()
|| questions.is_empty()
|| self.entries.iter().any(|e| matches!(e, AgentEntry::Question { id: known, .. } if known == &id))
{
return out;
}
let index =
self.push(AgentEntry::Question { id, title: str_field(update, "title"), questions, chosen: None });
out.changed.push(index);
}
"agent_message_chunk" | "agent_thought_chunk" => {
let Some(text) = content_text(update.get("content")) else { return out };
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
@@ -388,6 +405,25 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn asynchronous_questions_survive_turn_end_restart_and_duplicate_notifications() {
let mut t = Timeline::default();
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
assert_eq!(t.apply(&update).changed, vec![0]);
assert!(t.end_turn(None).is_empty());
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
let saved = serde_json::to_string(&t.entries).unwrap();
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
assert!(t.apply(&update).changed.is_empty());
assert_eq!(t.entries.len(), 1);
if let AgentEntry::Question { chosen, .. } = &mut t.entries[0] {
*chosen = Some("One".into());
}
assert!(t.apply(&update).changed.is_empty());
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+30
Переглянути файл
@@ -783,6 +783,35 @@ pub struct AppearanceSettings {
pub main_toolbar: Option<MainToolbarSettings>,
/// Appearance › Background Image: an image shown through the IDE window.
pub background_image: BackgroundImageSettings,
/// Appearance › Presentation Assistant: the name and shortcut of each action run.
pub presentation_assistant: PresentationAssistantSettings,
}
/// Appearance › Presentation Assistant: shows the name and shortcut of each action the user runs.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct PresentationAssistantSettings {
pub enabled: bool,
/// `small` | `medium` | `large`.
pub size: String,
/// How long each popup stays, in seconds.
pub duration_seconds: u32,
/// `top-left`, `top`, `top-right`, `bottom-left`, `bottom` or `bottom-right` of the window.
pub position: String,
/// Also show the shortcut of the other platform's keymap (macOS ⇄ Windows/Linux).
pub alternate_keymap: bool,
}
impl Default for PresentationAssistantSettings {
fn default() -> Self {
Self {
enabled: false,
size: "medium".into(),
duration_seconds: 4,
position: "bottom".into(),
alternate_keymap: false,
}
}
}
/// Appearance › Background Image. An empty `path` shows no image.
@@ -875,6 +904,7 @@ impl Default for AppearanceSettings {
status_bar_widgets: BTreeMap::new(),
main_toolbar: None,
background_image: BackgroundImageSettings::default(),
presentation_assistant: PresentationAssistantSettings::default(),
}
}
}
+3
Переглянути файл
@@ -135,6 +135,8 @@ pub struct CommitSettings {
/// `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
#[specta(optional)]
pub double_click_opens_diff: Option<bool>,
/// Team conventions for Generate Commit Message with Agent, added to its prompt.
pub agent_instructions: String,
}
impl Default for CommitSettings {
@@ -156,6 +158,7 @@ impl Default for CommitSettings {
wrap_at_margin: false,
disabled_plugin_checks: Vec::new(),
double_click_opens_diff: None,
agent_instructions: String::new(),
}
}
}
+4 -4
Переглянути файл
@@ -812,16 +812,16 @@ impl DbManager {
let password = self.password(&source).await;
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
let prepared = tools::prepare(job, &target, password.as_deref());
tools::run(executable, &prepared.args, &prepared.env, cancel, on_output).await
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
}
/// The command [`DbManager::run_tool`] would run, for the dialogs' preview: the data source's
/// own host and port (not a tunnel's local end), and no password.
pub fn tool_preview(&self, id: &str, executable: &std::path::Path, job: &tools::DbToolJob) -> IdeResult<String> {
let source = self.source(id)?;
let prepared = tools::prepare(job, &source, None);
Ok(tools::command_line(executable, &prepared.args))
let prepared = tools::prepare(job, executable, &source, None)?;
Ok(tools::command_line(executable, &prepared.args, job.input()))
}
/// The PostgreSQL server's `server_version_num` (`150013` for 15.13).
+215 -4
Переглянути файл
@@ -2,6 +2,7 @@
//! The connection arguments come from [`super::connection`]; these are the rest.
use super::DbTool;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
@@ -58,6 +59,8 @@ pub struct DbPgDumpOptions {
pub struct DbPgRestoreOptions {
pub content: DbDumpContent,
pub schemas: Vec<String>,
/// Creates the database the archive names; the target is only connected to.
pub create: bool,
pub clean: bool,
pub if_exists: bool,
pub no_owner: bool,
@@ -75,6 +78,40 @@ pub struct DbPsqlOptions {
pub stop_on_error: bool,
}
/// Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbMysqldumpOptions {
/// Empty: every database.
pub databases: Vec<String>,
/// Only with exactly one database.
pub tables: Vec<String>,
pub add_drop_table: bool,
pub disable_keys: bool,
pub add_locks: bool,
pub add_drop_trigger: bool,
pub no_data: bool,
pub complete_insert: bool,
pub create_options: bool,
pub routines: bool,
pub events: bool,
/// A consistent InnoDB snapshot without locks; needs no RELOAD privilege.
pub single_transaction: bool,
/// Wins over `single_transaction`.
pub lock_all_tables: bool,
/// `None`: the client has no `--masking-policies`.
pub masking_policies: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbMysqlOptions {
/// Empty: the databases the dump names.
pub database: String,
/// Runs the remaining statements after an error.
pub force: bool,
}
/// A run of a client tool: which one, the file it writes or reads, and its options.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "tool", rename_all = "camelCase")]
@@ -92,6 +129,15 @@ pub enum DbToolJob {
file: String,
options: DbPsqlOptions,
},
Mysqldump {
file: String,
options: DbMysqldumpOptions,
},
/// `file` goes to the standard input.
Mysql {
file: String,
options: DbMysqlOptions,
},
}
impl DbToolJob {
@@ -100,15 +146,38 @@ impl DbToolJob {
DbToolJob::PgDump { .. } => DbTool::PgDump,
DbToolJob::PgRestore { .. } => DbTool::PgRestore,
DbToolJob::Psql { .. } => DbTool::Psql,
DbToolJob::Mysqldump { .. } => DbTool::Mysqldump,
DbToolJob::Mysql { .. } => DbTool::Mysql,
}
}
/// The file piped to the tool's standard input.
pub fn input(&self) -> Option<&str> {
match self {
DbToolJob::Mysql { file, .. } if !file.is_empty() => Some(file),
_ => None,
}
}
/// Refuses names that the tool would read as options: `mysqldump` takes databases and tables
/// as plain arguments.
pub fn check(&self) -> IdeResult<()> {
if let DbToolJob::Mysqldump { options, .. } = self
&& let Some(name) = options.databases.iter().chain(&options.tables).find(|n| n.trim().starts_with('-'))
{
return Err(IdeError::invalid(format!("mysqldump cannot dump a database or table named {name}")));
}
Ok(())
}
/// The arguments after the connection ones.
pub fn args(&self) -> Vec<String> {
match self {
DbToolJob::PgDump { file, options } => pg_dump(options, file),
DbToolJob::PgRestore { file, options } => pg_restore(options, file),
DbToolJob::Psql { file, options } => psql(options, file),
DbToolJob::Mysqldump { file, options } => mysqldump(options, file),
DbToolJob::Mysql { options, .. } => mysql(options),
}
}
}
@@ -162,6 +231,7 @@ fn pg_dump(o: &DbPgDumpOptions, file: &str) -> Vec<String> {
fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
let mut args: Vec<String> = content(o.content).into_iter().collect();
args.extend(each(&o.schemas, "schema"));
args.extend(flag(o.create, "--create"));
args.extend(flag(o.clean, "--clean"));
args.extend(flag(o.clean && o.if_exists, "--if-exists"));
args.extend(flag(o.no_owner, "--no-owner"));
@@ -187,8 +257,53 @@ fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
args
}
/// The command as a shell would need it typed: the dialogs' preview.
pub fn command_line(program: &Path, args: &[String]) -> String {
fn names(list: &[String]) -> impl Iterator<Item = String> {
list.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_owned)
}
fn mysqldump(o: &DbMysqldumpOptions, file: &str) -> Vec<String> {
let skip = |on: bool, option: &str| (!on).then(|| format!("--skip-{option}"));
let mut args = vec![format!("--result-file={file}")];
args.extend(skip(o.add_drop_table, "add-drop-table"));
args.extend(skip(o.disable_keys, "disable-keys"));
args.extend(skip(o.add_locks, "add-locks"));
args.extend(skip(o.create_options, "create-options"));
args.extend(flag(o.add_drop_trigger, "--add-drop-trigger"));
args.extend(flag(o.no_data, "--no-data"));
args.extend(flag(o.complete_insert, "--complete-insert"));
args.extend(flag(o.routines, "--routines"));
args.extend(flag(o.events, "--events"));
args.extend(flag(o.lock_all_tables, "--lock-all-tables"));
args.extend(flag(!o.lock_all_tables && o.single_transaction, "--single-transaction"));
// On by default where it exists; reading the policies needs privileges most users lack.
args.extend(flag(o.masking_policies == Some(false), "--skip-masking-policies"));
// Tablespace statements need the PROCESS privilege and rarely matter in a dump.
args.push("--no-tablespaces".into());
args.push("--verbose".into());
let databases: Vec<String> = names(&o.databases).collect();
match databases.as_slice() {
[] => args.push("--all-databases".into()),
[one] => {
args.push(one.clone());
args.extend(names(&o.tables));
}
_ => {
args.push("--databases".into());
args.extend(databases);
}
}
args
}
fn mysql(o: &DbMysqlOptions) -> Vec<String> {
let database = o.database.trim();
let mut args: Vec<String> = (!database.is_empty()).then(|| format!("--database={database}")).into_iter().collect();
args.extend(flag(o.force, "--force"));
args
}
/// The command as a shell would need it typed: the dialogs' preview. `input` is piped in.
pub fn command_line(program: &Path, args: &[String], input: Option<&str>) -> String {
let quote = |s: &str| {
if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "@%+=:,./-_".contains(c)) {
s.to_owned()
@@ -196,11 +311,15 @@ pub fn command_line(program: &Path, args: &[String]) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
};
std::iter::once(program.to_string_lossy().into_owned())
let line = std::iter::once(program.to_string_lossy().into_owned())
.chain(args.iter().cloned())
.map(|a| quote(&a))
.collect::<Vec<_>>()
.join(" ")
.join(" ");
match input {
Some(file) => format!("{line} < {}", quote(file)),
None => line,
}
}
#[cfg(test)]
@@ -228,6 +347,7 @@ mod tests {
DbPgRestoreOptions {
content: DbDumpContent::All,
schemas: vec![],
create: false,
clean: false,
if_exists: false,
no_owner: false,
@@ -308,6 +428,13 @@ mod tests {
);
}
#[test]
fn creates_the_database_of_the_archive_when_asked() {
let options = DbPgRestoreOptions { create: true, ..restore() };
let a = args(DbToolJob::PgRestore { file: "/tmp/shop.dump".into(), options });
assert_eq!(a, ["--create", "--exit-on-error", "--verbose", "/tmp/shop.dump"]);
}
#[test]
fn leaves_out_an_archive_not_chosen_yet() {
let a = args(DbToolJob::PgRestore { file: String::new(), options: restore() });
@@ -328,8 +455,92 @@ mod tests {
let line = command_line(
Path::new("/usr/bin/pg_dump"),
&["--port=5432".into(), "--file=/tmp/my dump.sql".into(), "--table=it's".into()],
None,
);
assert_eq!(line, r#"/usr/bin/pg_dump --port=5432 '--file=/tmp/my dump.sql' '--table=it'\''s'"#);
let line = command_line(Path::new("mysql"), &["--force".into()], Some("/tmp/my dump.sql"));
assert_eq!(line, "mysql --force < '/tmp/my dump.sql'");
}
fn mysqldump_options() -> DbMysqldumpOptions {
DbMysqldumpOptions {
databases: vec!["shop".into()],
tables: vec![],
add_drop_table: true,
disable_keys: true,
add_locks: true,
add_drop_trigger: false,
no_data: false,
complete_insert: false,
create_options: true,
routines: false,
events: false,
single_transaction: true,
lock_all_tables: false,
masking_policies: None,
}
}
#[test]
fn mysqldump_flags_only_what_differs_from_its_defaults() {
let job = DbToolJob::Mysqldump { file: "/tmp/shop.sql".into(), options: mysqldump_options() };
assert_eq!(
args(job),
["--result-file=/tmp/shop.sql", "--single-transaction", "--no-tablespaces", "--verbose", "shop"]
);
let options = DbMysqldumpOptions {
add_drop_table: false,
create_options: false,
routines: true,
lock_all_tables: true,
masking_policies: Some(false),
..mysqldump_options()
};
let a = args(DbToolJob::Mysqldump { file: "/tmp/x.sql".into(), options });
for expected in ["--skip-add-drop-table", "--skip-create-options", "--routines", "--lock-all-tables"] {
assert!(a.contains(&expected.to_owned()), "{expected} missing from {a:?}");
}
assert!(a.contains(&"--skip-masking-policies".to_owned()), "{a:?}");
assert!(!a.contains(&"--single-transaction".to_owned()), "{a:?}");
}
#[test]
fn mysqldump_names_tables_only_of_a_single_database() {
let tables = vec!["orders".to_owned(), "items".to_owned()];
let one = DbMysqldumpOptions { tables: tables.clone(), ..mysqldump_options() };
assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: one }).ends_with(&[
"shop".into(),
"orders".into(),
"items".into()
]));
let two = DbMysqldumpOptions { databases: vec!["a".into(), "b".into()], tables, ..mysqldump_options() };
assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: two }).ends_with(&[
"--databases".into(),
"a".into(),
"b".into()
]));
let all = DbMysqldumpOptions { databases: vec![], ..mysqldump_options() };
assert_eq!(args(DbToolJob::Mysqldump { file: "f".into(), options: all }).last().unwrap(), "--all-databases");
}
#[test]
fn mysqldump_refuses_names_it_would_read_as_options() {
let options = DbMysqldumpOptions { tables: vec!["--result-file=/etc/x".into()], ..mysqldump_options() };
assert!(DbToolJob::Mysqldump { file: "f".into(), options }.check().is_err());
assert!(DbToolJob::Mysqldump { file: "f".into(), options: mysqldump_options() }.check().is_ok());
}
#[test]
fn mysql_reads_the_dump_from_its_standard_input() {
let job = DbToolJob::Mysql {
file: "/tmp/shop.sql".into(),
options: DbMysqlOptions { database: " shop ".into(), force: true },
};
assert_eq!(args(job.clone()), ["--database=shop", "--force"]);
assert_eq!(job.input(), Some("/tmp/shop.sql"));
let none =
DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: String::new(), force: false } };
assert!(args(none.clone()).is_empty() && none.input().is_none());
}
#[test]
+336 -48
Переглянути файл
@@ -1,5 +1,6 @@
//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`): finding installed copies, the
//! arguments and environment that connect them like the data source, and running them.
//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`, `mysqldump`, `mysql`): finding
//! installed copies, the arguments and environment that connect them like the data source, and
//! running them.
mod jobs;
pub use jobs::*;
@@ -20,6 +21,8 @@ pub enum DbTool {
PgDump,
PgRestore,
Psql,
Mysqldump,
Mysql,
}
impl DbTool {
@@ -27,20 +30,25 @@ impl DbTool {
self.programs()[0]
}
/// Executable names.
/// Executable names, MariaDB's own after MySQL's.
pub fn programs(self) -> &'static [&'static str] {
match self {
DbTool::PgDump => &["pg_dump"],
DbTool::PgRestore => &["pg_restore"],
DbTool::Psql => &["psql"],
DbTool::Mysqldump => &["mysqldump", "mariadb-dump"],
DbTool::Mysql => &["mysql", "mariadb"],
}
}
pub fn driver(self) -> DbDriver {
DbDriver::Postgres
match self {
DbTool::PgDump | DbTool::PgRestore | DbTool::Psql => DbDriver::Postgres,
DbTool::Mysqldump | DbTool::Mysql => DbDriver::Mysql,
}
}
/// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`…).
/// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`, `mariadb-dump`…).
/// The data source's password is handed only to such a program.
pub fn is_program(self, path: &Path) -> bool {
let Some(stem) = path.file_stem().and_then(OsStr::to_str) else { return false };
@@ -53,6 +61,12 @@ impl DbTool {
}
}
/// Whether `executable` is MariaDB's client (`mariadb`, `mariadb-dump`), whose SSL options differ
/// from MySQL's.
fn is_mariadb(executable: &Path) -> bool {
executable.file_stem().and_then(OsStr::to_str).is_some_and(|s| s.starts_with("mariadb"))
}
/// An installed copy of a tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbToolInstall")]
@@ -70,28 +84,41 @@ pub struct ToolLine {
pub text: String,
}
/// Directories holding the tools that are often missing from `PATH`, by platform.
fn known_dirs() -> Vec<PathBuf> {
/// Directories holding the tools of `driver` that are often missing from `PATH`, by platform.
fn known_dirs(driver: DbDriver) -> Vec<PathBuf> {
let mysql = driver == DbDriver::Mysql;
let mut dirs = Vec::new();
if cfg!(target_os = "macos") {
for prefix in ["/opt/homebrew", "/usr/local"] {
dirs.push(PathBuf::from(format!("{prefix}/bin")));
let opt = PathBuf::from(format!("{prefix}/opt"));
for keg in ["libpq", "postgresql"] {
let kegs: &[&str] = if mysql { &["mysql-client", "mysql", "mariadb"] } else { &["libpq", "postgresql"] };
for keg in kegs {
dirs.extend(children(&opt, keg).into_iter().map(|d| d.join("bin")));
}
}
dirs.extend(
children(Path::new("/Applications/Postgres.app/Contents/Versions"), "").into_iter().map(|d| d.join("bin")),
);
if mysql {
dirs.push(PathBuf::from("/usr/local/mysql/bin"));
} else {
dirs.extend(
children(Path::new("/Applications/Postgres.app/Contents/Versions"), "")
.into_iter()
.map(|d| d.join("bin")),
);
}
} else if cfg!(windows) {
for var in ["ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = std::env::var_os(var) {
let root = PathBuf::from(base).join("PostgreSQL");
dirs.extend(children(&root, "").into_iter().map(|d| d.join("bin")));
let base = PathBuf::from(base);
// MySQL installs to `MySQL\MySQL Server 8.4`, MariaDB to `MariaDB 11.4`.
let roots: &[(&str, &str)] =
if mysql { &[("MySQL", "MySQL"), ("", "MariaDB")] } else { &[("PostgreSQL", "")] };
for (dir, prefix) in roots {
dirs.extend(children(&base.join(dir), prefix).into_iter().map(|d| d.join("bin")));
}
}
}
} else {
} else if !mysql {
dirs.extend(children(Path::new("/usr/lib/postgresql"), "").into_iter().map(|d| d.join("bin")));
dirs.extend(children(Path::new("/usr"), "pgsql-").into_iter().map(|d| d.join("bin")));
}
@@ -121,7 +148,7 @@ fn version_key(text: &str) -> Vec<u32> {
pub fn find_installs(tool: DbTool) -> Vec<ToolInstall> {
let path = ide_core::process::host_var_os("PATH").unwrap_or_default();
let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
dirs.extend(known_dirs());
dirs.extend(known_dirs(tool.driver()));
let mut seen = Vec::new();
let mut out = Vec::new();
for dir in dirs {
@@ -150,6 +177,29 @@ pub fn version_of(path: &Path) -> IdeResult<String> {
}
}
/// The long options `path --help` lists (`masking-policies` for `--masking-policies`), so a
/// dialog offers only options this copy knows. Blocking.
pub fn options_of(path: &Path) -> IdeResult<Vec<String>> {
let (_, text) = capture(path, "--help")?;
Ok(help_options(&text))
}
fn help_options(help: &str) -> Vec<String> {
let mut out: Vec<String> = help
.lines()
.filter(|l| l.starts_with(' ') && l.trim_start().starts_with('-'))
.filter_map(|l| {
let at = l.find("--")?;
let name: String =
l[at + 2..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
(!name.is_empty()).then_some(name)
})
.collect();
out.sort();
out.dedup();
out
}
/// Runs `path arg` for at most five seconds; whether it succeeded, and its standard output.
fn capture(path: &Path, arg: &str) -> IdeResult<(bool, String)> {
if !path.is_file() {
@@ -189,23 +239,41 @@ pub enum DbDumpKind {
PostgresArchive,
/// Plain SQL from `pg_dump`: `psql`.
PostgresSql,
/// `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools.
/// `mysqldump` / `mariadb-dump`: `mysql`.
MysqlSql,
Unknown,
}
/// Blocking: reads at most the first 4 KiB.
pub fn dump_kind(path: &Path) -> IdeResult<DbDumpKind> {
/// What a restore needs to know about a dump before it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbDumpInfo")]
pub struct DumpInfo {
pub kind: DbDumpKind,
/// An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`,
/// or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them.
pub creates_database: bool,
}
/// Blocking: reads at most the first 64 KiB, where both tools write their `CREATE DATABASE`.
pub fn dump_info(path: &Path) -> IdeResult<DumpInfo> {
use std::io::Read;
if path.is_dir() {
return Ok(if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown });
let kind = if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown };
return Ok(DumpInfo { kind, creates_database: false });
}
let mut head = Vec::with_capacity(4096);
let mut head = Vec::with_capacity(64 * 1024);
std::fs::File::open(path)
.map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))?
.take(4096)
.take(64 * 1024)
.read_to_end(&mut head)?;
Ok(kind_of(&head))
Ok(info_of(&head))
}
fn info_of(head: &[u8]) -> DumpInfo {
let kind = kind_of(head);
let sql = matches!(kind, DbDumpKind::PostgresSql | DbDumpKind::MysqlSql);
let creates_database = sql && String::from_utf8_lossy(head).lines().any(|l| l.starts_with("CREATE DATABASE "));
DumpInfo { kind, creates_database }
}
fn kind_of(head: &[u8]) -> DbDumpKind {
@@ -224,9 +292,12 @@ fn kind_of(head: &[u8]) -> DbDumpKind {
}
}
/// Arguments and environment that connect `tool` to `source` (already resolved, through its
/// tunnel when it has one). The password is left to [`prepare`].
pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(String, String)>) {
/// Arguments and environment that connect `tool` at `executable` to `source` (already resolved,
/// through its tunnel when it has one). The password is left to [`prepare`].
pub fn connection(tool: DbTool, executable: &Path, source: &DataSource) -> (Vec<String>, Vec<(String, String)>) {
if tool.driver() == DbDriver::Mysql {
return (mysql_connection(tool, executable, source), Vec::new());
}
let mut args = Vec::new();
let host = source.host.trim();
if !host.is_empty() {
@@ -271,6 +342,50 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
(args, env)
}
/// The database is the job's: a dump may name several.
fn mysql_connection(tool: DbTool, executable: &Path, source: &DataSource) -> Vec<String> {
let mut args = Vec::new();
let host = source.host.trim();
if !host.is_empty() {
args.push(format!("--host={host}"));
}
args.push(format!("--port={}", source.port.or(source.driver.default_port()).unwrap_or(3306)));
if !source.user.trim().is_empty() {
args.push(format!("--user={}", source.user.trim()));
}
// `localhost` would otherwise mean the Unix socket, not the port or the tunnel.
args.push("--protocol=TCP".into());
if is_mariadb(executable) {
let flags: &[&str] = match source.ssl {
DbSslMode::Disable => &["--skip-ssl"],
DbSslMode::Prefer => &["--skip-ssl-verify-server-cert"],
DbSslMode::Require => &["--ssl", "--skip-ssl-verify-server-cert"],
DbSslMode::VerifyCa | DbSslMode::VerifyFull => &["--ssl", "--ssl-verify-server-cert"],
};
args.extend(flags.iter().map(|f| f.to_string()));
} else {
let mode = match source.ssl {
DbSslMode::Disable => "DISABLED",
DbSslMode::Prefer => "PREFERRED",
DbSslMode::Require => "REQUIRED",
DbSslMode::VerifyCa => "VERIFY_CA",
DbSslMode::VerifyFull => "VERIFY_IDENTITY",
};
args.push(format!("--ssl-mode={mode}"));
}
for (flag, file) in
[("--ssl-ca", &source.ssl_ca_file), ("--ssl-cert", &source.ssl_cert_file), ("--ssl-key", &source.ssl_key_file)]
{
if !file.trim().is_empty() {
args.push(format!("{flag}={}", ide_ssh::expand(file.trim()).to_string_lossy()));
}
}
if tool == DbTool::Mysql && source.read_only {
args.push("--init-command=SET SESSION TRANSACTION READ ONLY".into());
}
args
}
/// `--dbname` reads a connection string or URI as connection parameters: such a database name
/// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials.
fn dbname_arg(name: &str) -> String {
@@ -281,36 +396,88 @@ fn dbname_arg(name: &str) -> String {
}
}
/// How a tool is started: connection arguments, then the job's, and the environment.
/// A MySQL client option file holding the password, readable by the user only; deleted on drop.
struct SecretFile(PathBuf);
impl SecretFile {
fn mysql_password(password: &str) -> IdeResult<Self> {
use std::io::Write;
let path = std::env::temp_dir().join(format!("openidea-mysql-{}.cnf", uuid::Uuid::new_v4()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&path)?;
let secret = SecretFile(path);
let escaped = password.replace('\\', "\\\\").replace('"', "\\\"");
writeln!(file, "[client]\npassword=\"{escaped}\"")?;
Ok(secret)
}
/// `mysqldump` / `mysql` accept it only as their first argument.
fn arg(&self) -> String {
format!("--defaults-extra-file={}", self.0.display())
}
}
impl Drop for SecretFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// How a tool is started: connection arguments, then the job's, the environment, and the file
/// piped to its standard input. Keep it until the tool exits: it owns the password file.
pub struct Prepared {
pub args: Vec<String>,
pub env: Vec<(String, String)>,
pub input: Option<PathBuf>,
_secret: Option<SecretFile>,
}
/// The command for `job` against `source`. The password goes in `PGPASSWORD`, never in the
/// arguments, which other users of the machine can read in the process list.
pub fn prepare(job: &DbToolJob, source: &DataSource, password: Option<&str>) -> Prepared {
let (mut args, mut env) = connection(job.tool(), source);
/// The command for `job` at `executable` against `source`. The password goes in `PGPASSWORD` or
/// a MySQL option file, never in the arguments, which other users of the machine can read in the
/// process list.
pub fn prepare(job: &DbToolJob, executable: &Path, source: &DataSource, password: Option<&str>) -> IdeResult<Prepared> {
job.check()?;
let tool = job.tool();
let (mut args, mut env) = connection(tool, executable, source);
args.extend(job.args());
if let Some(p) = password.filter(|p| !p.is_empty()) {
env.push(("PGPASSWORD".into(), p.to_owned()));
let mut secret = None;
match password.filter(|p| !p.is_empty()) {
Some(p) if tool.driver() == DbDriver::Mysql => {
let file = SecretFile::mysql_password(p)?;
args.insert(0, file.arg());
secret = Some(file);
}
Some(p) => env.push(("PGPASSWORD".into(), p.to_owned())),
None => {}
}
Prepared { args, env }
Ok(Prepared { args, env, input: job.input().map(PathBuf::from), _secret: secret })
}
/// Runs `program` until it exits, passing its output in batches. Returns the exit code
/// (`None`: ended by a signal). Cancelling kills it and everything it started.
/// Runs `program` until it exits, passing its output in batches; `input` is piped to its standard
/// input. Returns the exit code (`None`: ended by a signal). Cancelling kills it and everything it
/// started.
pub async fn run(
program: &Path,
args: &[String],
env: &[(String, String)],
input: Option<&Path>,
cancel: &CancellationToken,
mut on_output: impl FnMut(Vec<ToolLine>),
) -> IdeResult<Option<i32>> {
let stdin = match input {
Some(path) => Stdio::from(
std::fs::File::open(path)
.map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))?,
),
None => Stdio::null(),
};
let mut cmd = tokio::process::Command::new(program);
cmd.args(args)
.envs(env.iter().map(|(k, v)| (k, v)))
.stdin(Stdio::null())
.stdin(stdin)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
@@ -408,7 +575,7 @@ mod tests {
#[test]
fn connects_like_the_data_source_without_prompting() {
let (args, env) = connection(DbTool::PgDump, &pg());
let (args, env) = connection(DbTool::PgDump, Path::new("pg_dump"), &pg());
assert_eq!(args, ["--host=db.example.test", "--port=6543", "--username=app", "--dbname=shop", "--no-password"]);
assert!(env.contains(&("PGSSLMODE".into(), "prefer".into())));
assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS"));
@@ -421,7 +588,8 @@ mod tests {
(r"it's=\x", r"--dbname=dbname='it\'s=\\x'"),
("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"),
] {
let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() });
let (args, _) =
connection(DbTool::PgDump, Path::new("pg_dump"), &DataSource { database: name.into(), ..pg() });
assert!(args.contains(&arg.to_owned()), "{args:?}");
}
}
@@ -429,14 +597,14 @@ mod tests {
#[test]
fn default_port_and_optional_fields() {
let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() };
let (args, _) = connection(DbTool::Psql, &source);
let (args, _) = connection(DbTool::Psql, Path::new("psql"), &source);
assert_eq!(args, ["--host=db.example.test", "--port=5432", "--no-password"]);
}
#[test]
fn read_only_sources_refuse_writes() {
let source = DataSource { read_only: true, ssl: DbSslMode::VerifyFull, ..pg() };
let (_, env) = connection(DbTool::PgRestore, &source);
let (_, env) = connection(DbTool::PgRestore, Path::new("pg_restore"), &source);
assert!(env.contains(&("PGOPTIONS".into(), "-c default_transaction_read_only=on".into())));
assert!(env.contains(&("PGSSLMODE".into(), "verify-full".into())));
}
@@ -451,6 +619,77 @@ mod tests {
}
}
#[test]
fn mysql_tools_accept_mariadb_names_only_for_themselves() {
assert!(DbTool::Mysqldump.is_program(Path::new("/usr/bin/mariadb-dump")));
assert!(DbTool::Mysql.is_program(Path::new("/opt/homebrew/opt/mysql-client/bin/mysql")));
assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mysqldump")));
assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mariadb-dump")));
assert!(!DbTool::Mysqldump.is_program(Path::new("/usr/bin/mysqlpump")));
}
#[test]
fn mysql_connects_over_tcp_with_the_ssl_flags_of_its_client() {
let source = DataSource {
driver: DbDriver::Mysql,
host: "localhost".into(),
port: None,
user: "app".into(),
read_only: true,
..DataSource::default()
};
let (args, env) = connection(DbTool::Mysql, Path::new("/usr/bin/mysql"), &source);
assert_eq!(
args,
[
"--host=localhost",
"--port=3306",
"--user=app",
"--protocol=TCP",
"--ssl-mode=PREFERRED",
"--init-command=SET SESSION TRANSACTION READ ONLY"
]
);
assert!(env.is_empty());
let (args, _) = connection(DbTool::Mysqldump, Path::new("/usr/bin/mariadb-dump"), &source);
assert!(args.contains(&"--skip-ssl-verify-server-cert".to_owned()));
assert!(!args.iter().any(|a| a.starts_with("--ssl-mode") || a.starts_with("--init-command")));
}
#[test]
fn the_password_file_is_private_and_removed() {
let file = SecretFile::mysql_password(r#"p"a\ss"#).unwrap();
let path = file.arg().trim_start_matches("--defaults-extra-file=").to_owned();
let text = std::fs::read_to_string(&path).unwrap();
assert_eq!(text, "[client]\npassword=\"p\\\"a\\\\ss\"\n");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
drop(file);
assert!(!Path::new(&path).exists());
}
#[test]
fn reads_long_options_from_help() {
let help = "Usage: mysqldump [OPTIONS]\n -A, --all-databases Dump all.\n --masking-policies Dump masking\n policies (--not-an-option).\n -y, --no-tablespaces \n -f, --file=FILENAME output file\n";
assert_eq!(help_options(help), ["all-databases", "file", "masking-policies", "no-tablespaces"]);
}
#[cfg(unix)]
#[tokio::test]
async fn pipes_the_input_file() {
let file = std::env::temp_dir().join(format!("openidea-input-{}", uuid::Uuid::new_v4()));
std::fs::write(&file, "from the file\n").unwrap();
let mut lines = Vec::new();
run(Path::new("/bin/cat"), &[], &[], Some(&file), &CancellationToken::new(), |b| lines.extend(b))
.await
.unwrap();
std::fs::remove_file(&file).unwrap();
assert_eq!(lines, [ToolLine { stderr: false, text: "from the file".into() }]);
}
#[test]
fn tells_dumps_apart_by_their_header() {
assert_eq!(kind_of(b"PGDMP\x01\x0f"), DbDumpKind::PostgresArchive);
@@ -461,6 +700,17 @@ mod tests {
assert_eq!(kind_of(b"CREATE TABLE t (id int);\n"), DbDumpKind::Unknown);
}
#[test]
fn sees_a_dump_that_creates_its_own_database() {
let one = b"-- MySQL dump 10.13\n--\n-- Host: localhost Database: shop\nCREATE TABLE `items` (id int);\n";
assert!(!info_of(one).creates_database);
let several = b"-- MySQL dump 10.13\n--\n-- Current Database: `shop`\n--\n\nCREATE DATABASE /*!32312 IF NOT EXISTS*/ `shop`;\nUSE `shop`;\n";
assert!(info_of(several).creates_database);
let pg = b"--\n-- PostgreSQL database dump\n--\nSET client_encoding = 'UTF8';\nCREATE DATABASE shop WITH TEMPLATE = template0;\n\\connect shop\n";
assert_eq!(info_of(pg), DumpInfo { kind: DbDumpKind::PostgresSql, creates_database: true });
assert!(!info_of(b"CREATE DATABASE x;\n").creates_database, "only for a dump the tools wrote");
}
#[test]
fn newer_versions_sort_first() {
assert!(version_key("pg_dump (PostgreSQL) 17.2") > version_key("pg_dump (PostgreSQL) 9.6.24"));
@@ -474,6 +724,7 @@ mod tests {
Path::new("/bin/sh"),
&["-c".into(), "echo out; echo err >&2; exit 3".into()],
&[],
None,
&CancellationToken::new(),
|batch| lines.extend(batch),
)
@@ -493,19 +744,25 @@ mod tests {
tokio::time::sleep(Duration::from_millis(100)).await;
stop.cancel();
});
let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], &cancel, |_| {}).await;
let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], None, &cancel, |_| {}).await;
assert!(result.is_err());
}
/// A stand-in for `tool` that prints each argument on a line, then whether `PGPASSWORD`
/// holds the expected password.
/// A stand-in for `tool` that prints each argument on a line, then whether it got a password
/// from `PGPASSWORD` or a MySQL option file.
#[cfg(unix)]
fn echo_tool(dir: &Path, tool: DbTool) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(tool.program());
std::fs::write(
&path,
"#!/bin/sh\nfor a in \"$@\"; do echo \"arg:$a\"; done\necho \"env:${PGPASSWORD:+set}\"\n",
concat!(
"#!/bin/sh\n",
"for a in \"$@\"; do echo \"arg:$a\"; case \"$a\" in --defaults-extra-file=*)\n",
" grep -q '^password=' \"${a#*=}\" && echo env:set;; esac; done\n",
"[ -n \"$PGPASSWORD\" ] && echo env:set\n",
"exit 0\n",
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
@@ -541,17 +798,48 @@ mod tests {
file: file.clone(),
options: DbPsqlOptions { single_transaction: true, stop_on_error: true },
},
DbToolJob::Mysqldump {
file: file.clone(),
options: DbMysqldumpOptions {
databases: vec!["shop".into()],
tables: vec![],
add_drop_table: true,
disable_keys: true,
add_locks: true,
add_drop_trigger: false,
no_data: false,
complete_insert: false,
create_options: true,
routines: false,
events: false,
single_transaction: true,
lock_all_tables: false,
masking_policies: None,
},
},
DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: "shop".into(), force: false } },
];
for job in jobs {
let mysql = job.tool().driver() == DbDriver::Mysql;
let source = if mysql { DataSource { driver: DbDriver::Mysql, ..pg() } } else { pg() };
let program = echo_tool(&dir, job.tool());
let prepared = prepare(&job, &pg(), Some(SECRET));
let prepared = prepare(&job, &program, &source, Some(SECRET)).unwrap();
assert!(!prepared.args.iter().any(|a| a.contains(SECRET)), "{:?}", prepared.args);
assert!(!mysql || prepared.env.is_empty(), "{:?}", prepared.env);
let mut lines = Vec::new();
run(&program, &prepared.args, &prepared.env, &CancellationToken::new(), |b| lines.extend(b)).await.unwrap();
run(&program, &prepared.args, &prepared.env, None, &CancellationToken::new(), |b| lines.extend(b))
.await
.unwrap();
let text: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
assert!(text.contains(&"arg:--dbname=shop"), "{text:?}");
let database = if mysql { "shop" } else { "--dbname=shop" };
assert!(text.iter().any(|l| l.strip_prefix("arg:").is_some_and(|a| a.ends_with(database))), "{text:?}");
assert!(!text.iter().any(|l| l.contains(SECRET)), "{text:?}");
assert!(text.contains(&"env:set"), "the tool gets the password from PGPASSWORD: {text:?}");
assert!(text.contains(&"env:set"), "the tool gets the password: {text:?}");
if mysql {
let file = prepared.args[0].trim_start_matches("--defaults-extra-file=").to_owned();
drop(prepared);
assert!(!Path::new(&file).exists(), "the password file outlives the run");
}
}
std::fs::remove_dir_all(&dir).unwrap();
}
+67
Переглянути файл
@@ -231,3 +231,70 @@ async fn servers_that_advertise_deprecate_eof_but_send_legacy_eof_packets() -> I
assert_eq!(r.rows, vec![vec![Some("a".into())], vec![Some("b".into())]]);
Ok(())
}
/// `mysqldump` into a file and `mysql` reading it back, with the data source's password.
#[tokio::test]
async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
use ide_db::tools::{DbMysqlOptions, DbMysqldumpOptions, DbTool, DbToolJob, find_installs};
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let (Some(dump), Some(client)) =
(find_installs(DbTool::Mysqldump).into_iter().next(), find_installs(DbTool::Mysql).into_iter().next())
else {
return Ok(());
};
let c = CancellationToken::new();
for stmt in [
"DROP DATABASE IF EXISTS oi_dump_src",
"DROP DATABASE IF EXISTS oi_dump_dst",
"CREATE DATABASE oi_dump_src",
"CREATE DATABASE oi_dump_dst",
"CREATE TABLE oi_dump_src.items (id INT PRIMARY KEY, tag VARCHAR(20))",
"INSERT INTO oi_dump_src.items VALUES (1, 'dumped')",
] {
db.execute("m", stmt, 1, &c).await?;
}
let file = tmp.path().join("src.sql").to_string_lossy().into_owned();
let run = |executable: String, job: DbToolJob| {
let db = &db;
async move {
let mut lines = Vec::new();
let code =
db.run_tool("m", executable.as_ref(), &job, &CancellationToken::new(), |b| lines.extend(b)).await?;
assert_eq!(code, Some(0), "{} failed: {lines:?}", job.tool().program());
IdeResult::Ok(())
}
};
let masking = ide_db::tools::options_of(dump.path.as_ref())?.iter().any(|o| o == "masking-policies");
let options = DbMysqldumpOptions {
databases: vec!["oi_dump_src".into()],
tables: vec![],
add_drop_table: true,
disable_keys: true,
add_locks: true,
add_drop_trigger: false,
no_data: false,
complete_insert: false,
create_options: true,
routines: false,
events: false,
single_transaction: true,
lock_all_tables: false,
masking_policies: masking.then_some(false),
};
run(dump.path.clone(), DbToolJob::Mysqldump { file: file.clone(), options: options.clone() }).await?;
assert!(!ide_db::tools::dump_info(file.as_ref())?.creates_database, "one database: restored into a chosen one");
let both = tmp.path().join("both.sql").to_string_lossy().into_owned();
let two = DbMysqldumpOptions { databases: vec!["oi_dump_src".into(), "oi_dump_dst".into()], ..options };
run(dump.path, DbToolJob::Mysqldump { file: both.clone(), options: two }).await?;
assert!(ide_db::tools::dump_info(both.as_ref())?.creates_database, "several databases: created by the dump");
let restore = DbMysqlOptions { database: "oi_dump_dst".into(), force: false };
run(client.path, DbToolJob::Mysql { file, options: restore }).await?;
let r = db.execute("m", "SELECT tag FROM oi_dump_dst.items", 1, &c).await?;
assert_eq!(r.rows[0][0].as_deref(), Some("dumped"));
for stmt in ["DROP DATABASE oi_dump_src", "DROP DATABASE oi_dump_dst"] {
db.execute("m", stmt, 1, &c).await?;
}
Ok(())
}
+1
Переглянути файл
@@ -282,6 +282,7 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
let restore = DbPgRestoreOptions {
content: DbDumpContent::All,
schemas: vec![],
create: false,
clean: false,
if_exists: false,
no_owner: false,
+1 -1
Переглянути файл
@@ -142,7 +142,7 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
}
const FMT: &str = "{{json .}}";
let (containers, images, volumes, networks) = std::thread::scope(|s| {
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK));
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
+11 -1
Переглянути файл
@@ -226,6 +226,16 @@ fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> +
})
}
/// The `docker ps --format` template: only the fields [`RawContainer`] reads. `{{json .}}`
/// would also include `Size`, which makes the daemon compute every container's writable
/// layer and can take tens of seconds.
pub const PS_FORMAT: &str = concat!(
r#"{"ID":{{json .ID}},"Names":{{json .Names}},"Image":{{json .Image}},"#,
r#""Command":{{json .Command}},"State":{{json .State}},"Status":{{json .Status}},"#,
r#""Ports":{{json .Ports}},"CreatedAt":{{json .CreatedAt}},"Labels":{{json .Labels}},"#,
r#""Mounts":{{json .Mounts}},"Networks":{{json .Networks}}}"#,
);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawContainer {
@@ -247,7 +257,7 @@ fn split_csv(raw: &str) -> Vec<String> {
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `docker ps -a --no-trunc --format '{{json .}}'`.
/// `docker ps -a --no-trunc --format` [`PS_FORMAT`] (or `'{{json .}}'`).
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
.map(|r| {
+23 -2
Переглянути файл
@@ -1,8 +1,8 @@
//! Parsing of recorded `docker … --format '{{json .}}'` output.
use ide_docker::{
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
parse_volumes,
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
parse_networks, parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
@@ -10,6 +10,27 @@ const IMAGES: &str = include_str!("fixtures/images.jsonl");
const VOLUMES: &str = include_str!("fixtures/volumes.jsonl");
const NETWORKS: &str = include_str!("fixtures/networks.jsonl");
/// Fills `{{json .Field}}` placeholders of a `--format` template from a `{{json .}}` line.
fn render(template: &str, line: &str) -> String {
let fields: serde_json::Map<String, serde_json::Value> = serde_json::from_str(line).unwrap();
let mut out = template.to_owned();
while let Some(start) = out.find("{{json .") {
let end = start + out[start..].find("}}").unwrap() + 2;
let key = &out[start + "{{json .".len()..end - 2];
let value = fields.get(key).unwrap_or_else(|| panic!("fixture lacks {key}"));
out.replace_range(start..end, &value.to_string());
}
out
}
#[test]
fn ps_format_carries_everything_the_parser_reads_but_size() {
assert!(!PS_FORMAT.contains("Size"), "Size makes the daemon compute container sizes");
let rendered: Vec<String> = PS.lines().filter(|l| l.starts_with('{')).map(|l| render(PS_FORMAT, l)).collect();
assert_eq!(rendered.len(), 2);
assert_eq!(parse_containers(&rendered.join("\n")), parse_containers(PS));
}
#[test]
fn containers_with_compose_labels() {
let c = parse_containers(PS);
+1
Переглянути файл
@@ -40,6 +40,7 @@ fn tools() -> Vec<tool::Tool> {
tools.push(check::check_files());
tools.push(symbols::get_symbol_info());
tools.push(symbols::find_references());
tools.push(symbols::get_call_hierarchy());
tools.extend(edit::tools());
tools.extend(run::tools());
tools.extend(vcs::tools());
+1 -1
Переглянути файл
@@ -280,7 +280,7 @@ fn context(call: &Call) -> IdeResult<(u32, u32)> {
/// `line`, or when longer than [`MAX_LINE_TEXT`] UTF-16 units, the part from [`SNIPPET_AROUND`]
/// units before 0-based UTF-16 column `start` to as many after `end`, with `…` where it was cut.
fn snippet(line: &str, start: usize, end: usize) -> String {
pub(super) fn snippet(line: &str, start: usize, end: usize) -> String {
let units: usize = line.chars().map(char::len_utf16).sum();
if units <= MAX_LINE_TEXT {
return line.to_owned();
+422 -22
Переглянути файл
@@ -1,10 +1,13 @@
//! Quick Documentation through the project's language services.
use super::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{IdeError, IdeResult, Pos, Range};
use ide_lsp::types::GotoKind;
use ide_core::error::ErrorKind;
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Pos, Range, RequestId, SymbolKind};
use ide_lsp::types::{CallHierarchy, GotoKind, HierarchyDirection, HierarchyItem, ReferencesIncomplete};
use serde::Serialize;
use serde_json::json;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
pub fn get_symbol_info() -> Tool {
Tool::new("get_symbol_info", "Retrieves information about the symbol at the specified position in the specified file.
@@ -212,26 +215,10 @@ pub fn find_references() -> Tool {
let path = call.resolve_readable(&call.str("filePath")?).await?;
let page = super::page::Page::of(&call, REFERENCES_LIMIT)?;
let dir = super::scope::Scope::of(&call)?;
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
let project = call.project.clone();
let (doc, text) = call.host.blocking(move || {
let text = project.text_of(&path)?;
let doc = project.documents.open(&path)?;
Ok((doc.id, text))
}).await?;
struct Close(std::sync::Arc<crate::Project>, ide_core::DocId);
impl Drop for Close { fn drop(&mut self) { self.0.documents.close(self.1); } }
let _close = Close(call.project.clone(), doc);
let pos = mcp_position(&text, line, column)?;
let opened = open_at(&call, path).await?;
let request = super::tool::request_id();
let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, doc, pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {}));
tokio::pin!(work);
let result = tokio::select! {
result = &mut work => result?,
_ = call.cancel.cancelled() => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::cancelled()); }
_ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::unavailable("references timed out; retry when analysis finishes")); }
};
let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, opened.doc, opened.pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {}));
let result = race(&call, request, work, "references timed out; retry when analysis finishes").await?;
let mut value = serde_json::to_value(&result).map_err(|e| IdeError::internal(e.to_string()))?;
// Convert every Location range at this boundary, including declarations.
fn positions(value: &mut serde_json::Value) {
@@ -274,6 +261,266 @@ pub fn find_references() -> Tool {
/// References `find_references` lists by default.
const REFERENCES_LIMIT: usize = 100;
/// A document a tool opened for the language services and the position it asked about;
/// dropping it closes the document.
#[must_use]
struct Opened {
project: Arc<crate::Project>,
doc: DocId,
pos: Pos,
}
impl Drop for Opened {
fn drop(&mut self) {
self.project.documents.close(self.doc);
}
}
/// Opens `path` at the call's 1-based `line` and `column`.
async fn open_at(call: &Call, path: PathBuf) -> IdeResult<Opened> {
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
let project = call.project.clone();
let (doc, text) = call
.host
.blocking(move || {
let text = project.text_of(&path)?;
let doc = project.documents.open(&path)?;
Ok((doc.id, text))
})
.await?;
let mut opened = Opened { project: call.project.clone(), doc, pos: Pos::default() };
opened.pos = mcp_position(&text, line, column)?;
Ok(opened)
}
/// How long a tool waits for a language service request.
const LANGUAGE_SERVICE_TIMEOUT: Duration = Duration::from_secs(60);
/// `work`, the language service `request`, until it ends; when the client cancels or
/// [`LANGUAGE_SERVICE_TIMEOUT`] passes first, the request is cancelled and `work` runs to its end.
async fn race<T>(
call: &Call,
request: RequestId,
work: impl Future<Output = IdeResult<T>>,
timed_out: &'static str,
) -> IdeResult<T> {
tokio::pin!(work);
tokio::select! {
result = &mut work => result,
_ = call.cancel.cancelled() => {
call.host.cancel_request(request);
let _ = work.await;
Err(IdeError::cancelled())
}
_ = tokio::time::sleep(LANGUAGE_SERVICE_TIMEOUT) => {
call.host.cancel_request(request);
let _ = work.await;
Err(IdeError::unavailable(timed_out))
}
}
}
pub fn get_call_hierarchy() -> Tool {
Tool::new(
"get_call_hierarchy",
"Callers (incoming) or callees (outgoing) of the function or method at the position, from \
the language server's call hierarchy. A position inside a function body means that function. \
One level per call: to go deeper, call again with an item's filePath, startLine and startColumn \
(items in libraries show a URI as filePath and cannot be expanded). \
Positions are 1-based UTF-16. `root` is the symbol the hierarchy is for; each item's callSites \
are where the call happens. Reports incomplete results when analysis is still running.",
call_hierarchy,
)
.param(Param::required("filePath", ParamType::String, "Path relative to the project root"))
.param(Param::required("line", ParamType::Integer, "1-based line"))
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
.param(Param::optional("direction", ParamType::String, "incoming (callers, default) or outgoing (callees)"))
.param(super::scope::param())
.param(Param::optional("limit", ParamType::Integer, "Items to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
}
/// Items `get_call_hierarchy` lists by default.
const CALLS_LIMIT: usize = 100;
/// Call sites shown per item; `callSiteCount` gives the total when there are more.
const MAX_CALL_SITES: usize = 20;
const CALLS_TIMED_OUT: &str = "call hierarchy timed out; retry when analysis finishes";
async fn call_hierarchy(call: Call) -> IdeResult<Output> {
let direction = match call.opt_str("direction")?.as_deref() {
None | Some("incoming") => HierarchyDirection::Incoming,
Some("outgoing") => HierarchyDirection::Outgoing,
Some(_) => return Err(IdeError::invalid("direction must be incoming or outgoing")),
};
let page = super::page::Page::of(&call, CALLS_LIMIT)?;
let scope = super::scope::Scope::of(&call)?;
let path = call.resolve_readable(&call.str("filePath")?).await?;
let opened = open_at(&call, path).await?;
let hierarchy_at = |pos| {
let request = super::tool::request_id();
let work = crate::ops::lsp::lsp_call_hierarchy(&call.host, &call.window, request, opened.doc, pos, direction);
race(&call, request, work, CALLS_TIMED_OUT)
};
let mut found = match hierarchy_at(opened.pos).await {
// IDEA: inside a function body the hierarchy is the enclosing function's.
Err(e) if e.kind == ErrorKind::NotFound => {
let outline = tokio::select! {
outline = crate::ops::doc::doc_outline(&call.host, &call.window, opened.doc) => outline?,
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
};
let at = enclosing_callable(&outline, opened.pos).map(|f| f.selection_range.start);
let Some(at) = at.filter(|at| *at != opened.pos) else {
let Pos { line, col } = opened.pos;
return Err(IdeError::not_found(format!("no function or method at {}:{}", line + 1, col + 1)));
};
hierarchy_at(at).await?
}
result => result?,
};
if scope.dir().is_some() {
found.items.retain(|i| i.uri.is_none() && scope.contains(&i.path.0));
}
let incomplete = found.incomplete;
let (mut root, items) = call_items(found, |p| call.display(p));
let mut out = serde_json::Map::new();
let mut items = page.take(items, &mut out);
// One file in memory at a time, as `search::fill_lines` reads them.
let mut places: Vec<&mut Place> = root
.iter_mut()
.chain(&mut items)
.flat_map(|i| std::iter::once(&mut i.at).chain(&mut i.call_sites))
.filter(|place| place.file.is_some())
.collect();
places.sort_by(|a, b| a.file.cmp(&b.file));
for in_file in places.chunk_by_mut(|a, b| a.file == b.file) {
if call.cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Some(path) = in_file[0].file.clone() else { continue };
if let Ok(text) = crate::ops::fs::fs_read_text(&call.host, call.window(), path).await {
fill_line_texts(in_file, &text);
}
}
Output::json(CallHierarchyOutput { root, items, page: out, incomplete })
}
#[derive(Serialize)]
struct CallHierarchyOutput {
#[serde(skip_serializing_if = "Option::is_none")]
root: Option<CallItem>,
items: Vec<CallItem>,
/// `total`, and `more` and `nextOffset` when items follow.
#[serde(flatten)]
page: serde_json::Map<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
incomplete: Option<ReferencesIncomplete>,
}
/// A function or method in the call hierarchy, at its name.
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CallItem {
name: String,
kind: SymbolKind,
#[serde(skip_serializing_if = "Option::is_none")]
detail: Option<String>,
#[serde(flatten)]
at: Place,
#[serde(skip_serializing_if = "Vec::is_empty")]
call_sites: Vec<Place>,
#[serde(skip_serializing_if = "Option::is_none")]
call_site_count: Option<usize>,
}
/// A range as the tools show it: 1-based UTF-16, with the text of its first line.
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Place {
file_path: String,
start_line: u32,
start_column: u32,
end_line: u32,
end_column: u32,
#[serde(skip_serializing_if = "Option::is_none")]
line_text: Option<String>,
/// The file `line_text` is read from; none in a library.
#[serde(skip)]
file: Option<PathBuf>,
}
/// The root and the items of `h`, sorted by file and position, with call sites in source
/// order, at most [`MAX_CALL_SITES`] per item. Library items show their URI.
fn call_items(h: CallHierarchy, display: impl Fn(&Path) -> String) -> (Option<CallItem>, Vec<CallItem>) {
let CallHierarchy { root, items, .. } = h;
// A file path, or the URI of a virtual document, which has no lines to read here.
let target = |path: &Path, uri: Option<&String>| match uri {
Some(uri) => (None, uri.clone()),
None => (Some(path.to_path_buf()), display(path)),
};
let place = |(file, file_path): (Option<PathBuf>, String), r: Range| Place {
file_path,
start_line: r.start.line + 1,
start_column: r.start.col + 1,
end_line: r.end.line + 1,
end_column: r.end.col + 1,
line_text: None,
file,
};
let convert = |i: HierarchyItem| {
let at = target(&i.path.0, i.uri.as_ref());
let sites_in = match &i.from_path {
Some(p) => {
let shown = p.0.to_string_lossy();
target(&p.0, ide_core::is_virtual_uri(&shown).then(|| shown.into_owned()).as_ref())
}
None => at.clone(),
};
let mut sites = i.from_ranges;
sites.sort();
sites.dedup();
let count = sites.len();
CallItem {
call_sites: sites.into_iter().take(MAX_CALL_SITES).map(|r| place(sites_in.clone(), r)).collect(),
call_site_count: (count > MAX_CALL_SITES).then_some(count),
at: place(at, i.selection_range),
name: i.name,
kind: i.kind,
detail: i.detail,
}
};
let mut items: Vec<CallItem> = items.into_iter().map(&convert).collect();
items.sort_by(|a, b| {
(&a.at.file_path, a.at.start_line, a.at.start_column).cmp(&(
&b.at.file_path,
b.at.start_line,
b.at.start_column,
))
});
(root.map(convert), items)
}
/// Fills `lineText` of `places`, which are all in the file whose text is `text`.
fn fill_line_texts(places: &mut [&mut Place], text: &str) {
let lines: Vec<&str> = text.split('\n').collect();
for place in places {
let Some(line) = lines.get(place.start_line as usize - 1) else { continue };
let line = line.strip_suffix('\r').unwrap_or(line);
let start = place.start_column as usize - 1;
let end = if place.end_line == place.start_line { place.end_column as usize - 1 } else { start };
place.line_text = Some(super::search::snippet(line, start, end));
}
}
/// The innermost function, method or constructor of `outline` whose extent holds `pos`,
/// as the IDE's Call Hierarchy finds it.
fn enclosing_callable(outline: &[OutlineItem], pos: Pos) -> Option<&OutlineItem> {
let item = outline.iter().find(|i| i.range.start <= pos && pos <= i.range.end)?;
enclosing_callable(&item.children, pos).or_else(|| {
matches!(item.kind, SymbolKind::Function | SymbolKind::Method | SymbolKind::Constructor).then_some(item)
})
}
fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult<Pos> {
if line < 1 || line > u32::MAX as i64 || column < 1 || column > u32::MAX as i64 {
return Err(IdeError::invalid("line and column must be positive 1-based positions"));
@@ -284,3 +531,156 @@ fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult<Pos> {
}
Ok(Pos::new((line - 1) as u32, (column - 1) as u32))
}
#[cfg(test)]
mod tests {
use super::*;
fn range(line: u32, col: u32, end_line: u32, end_col: u32) -> Range {
Range::new(Pos::new(line, col), Pos::new(end_line, end_col))
}
fn item(name: &str, path: &str, line: u32, from_ranges: Vec<Range>) -> HierarchyItem {
HierarchyItem {
name: name.into(),
kind: SymbolKind::Function,
detail: Some(format!("fn {name}()")),
path: PathBuf::from(path).into(),
uri: None,
range: range(line, 0, line + 2, 1),
selection_range: range(line, 3, line, 3 + name.len() as u32),
from_ranges,
from_path: None,
}
}
fn shown(path: &Path) -> String {
path.strip_prefix("/p").unwrap_or(path).to_string_lossy().into_owned()
}
fn hierarchy(root: HierarchyItem, items: Vec<HierarchyItem>) -> CallHierarchy {
CallHierarchy { root: Some(root), items, incomplete: None }
}
#[test]
fn incoming_call_sites_are_in_the_callers_file_one_based() {
let h = hierarchy(
item("price", "/p/src/lib.rs", 10, Vec::new()),
vec![item("main", "/p/src/main.rs", 2, vec![range(4, 8, 4, 13)])],
);
let (root, items) = call_items(h, shown);
let root = serde_json::to_value(root.unwrap()).unwrap();
assert_eq!(
root,
json!({"name":"price","kind":"function","detail":"fn price()","filePath":"src/lib.rs",
"startLine":11,"startColumn":4,"endLine":11,"endColumn":9})
);
assert_eq!(
serde_json::to_value(&items).unwrap(),
json!([{"name":"main","kind":"function","detail":"fn main()","filePath":"src/main.rs",
"startLine":3,"startColumn":4,"endLine":3,"endColumn":8,
"callSites":[{"filePath":"src/main.rs","startLine":5,"startColumn":9,"endLine":5,"endColumn":14}]}])
);
}
#[test]
fn outgoing_call_sites_are_in_the_file_ide_lsp_names() {
let mut price = item("price", "/p/src/lib.rs", 10, vec![range(4, 8, 4, 13)]);
price.from_path = Some(PathBuf::from("/p/src/main.rs").into());
let (_, items) = call_items(hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![price]), shown);
assert_eq!(items[0].at.file_path, "src/lib.rs");
assert_eq!(items[0].call_sites[0].file_path, "src/main.rs");
assert_eq!(items[0].call_sites[0].file.as_deref(), Some(Path::new("/p/src/main.rs")));
}
#[test]
fn library_items_show_their_uri() {
let mut library = item("len", "/virtual", 0, vec![range(4, 8, 4, 11)]);
library.uri = Some("jar:file:///lib.jar!/Str.class".into());
library.from_path = Some(PathBuf::from("/p/src/main.rs").into());
let mut called_from_library = item("parse", "/p/src/a.rs", 3, vec![range(1, 0, 1, 4)]);
called_from_library.from_path = Some(PathBuf::from("jdt://contents/lib.jar/Caller.class").into());
let h = hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![library, called_from_library]);
let (_, items) = call_items(h, shown);
assert_eq!(items[0].at.file_path, "jar:file:///lib.jar!/Str.class");
assert_eq!(items[0].at.file, None, "no line text for a library item");
assert_eq!(items[0].call_sites[0].file_path, "src/main.rs");
assert_eq!(items[1].call_sites[0].file_path, "jdt://contents/lib.jar/Caller.class");
assert_eq!(items[1].call_sites[0].file, None);
}
#[test]
fn call_items_are_sorted_by_file_and_line() {
let h = hierarchy(
item("price", "/p/src/lib.rs", 10, Vec::new()),
vec![
item("c", "/p/src/main.rs", 9, Vec::new()),
item("b", "/p/src/main.rs", 2, Vec::new()),
item("a", "/p/src/a.rs", 5, Vec::new()),
],
);
let (_, items) = call_items(h, shown);
assert_eq!(items.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
}
#[test]
fn call_sites_are_capped_with_their_count() {
let sites = (0..MAX_CALL_SITES as u32 + 5).map(|l| range(l, 0, l, 1)).collect();
let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]);
let (_, items) = call_items(h, shown);
assert_eq!(items[0].call_sites.len(), MAX_CALL_SITES);
assert_eq!(items[0].call_site_count, Some(MAX_CALL_SITES + 5));
let one = hierarchy(
item("price", "/p/src/lib.rs", 10, Vec::new()),
vec![item("main", "/p/a.rs", 0, vec![range(1, 0, 1, 1)])],
);
assert_eq!(call_items(one, shown).1[0].call_site_count, None);
}
#[test]
fn call_sites_are_in_source_order_without_duplicates() {
let sites = vec![range(5, 0, 5, 1), range(1, 4, 1, 5), range(5, 0, 5, 1), range(1, 2, 1, 3)];
let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]);
let (_, items) = call_items(h, shown);
let at: Vec<_> = items[0].call_sites.iter().map(|s| (s.start_line, s.start_column)).collect();
assert_eq!(at, [(2, 3), (2, 5), (6, 1)]);
assert_eq!(items[0].call_site_count, None);
}
#[test]
fn line_text_is_cut_from_the_line_of_each_place() {
let h = hierarchy(item("price", "/p/src/lib.rs", 3, vec![range(0, 4, 0, 9), range(1, 0, 3, 1)]), Vec::new());
let mut root = call_items(h, shown).0.unwrap();
let mut places: Vec<&mut Place> = std::iter::once(&mut root.at).chain(&mut root.call_sites).collect();
fill_line_texts(&mut places, " price();\r\nfn other() {\n\nfn price() {}");
assert_eq!(root.at.line_text.as_deref(), Some("fn price() {}"));
assert_eq!(root.call_sites[0].line_text.as_deref(), Some(" price();"));
assert_eq!(root.call_sites[1].line_text.as_deref(), Some("fn other() {"), "a range over lines");
}
#[test]
fn enclosing_callable_is_the_innermost_function() {
let outline = |name: &str, kind, range, children| OutlineItem {
name: name.into(),
detail: None,
kind,
range,
selection_range: Range::new(range.start, range.start),
children,
visibility: None,
};
let method = outline(
"total",
SymbolKind::Method,
range(2, 4, 8, 5),
vec![outline("add", SymbolKind::Function, range(3, 8, 5, 9), Vec::new())],
);
let items = vec![outline("Cart", SymbolKind::Struct, range(0, 0, 9, 1), vec![method])];
let name = |pos| enclosing_callable(&items, pos).map(|i| i.name.as_str());
assert_eq!(name(Pos::new(4, 0)), Some("add"));
assert_eq!(name(Pos::new(5, 9)), Some("add"), "the end is inside");
assert_eq!(name(Pos::new(7, 0)), Some("total"));
assert_eq!(name(Pos::new(0, 3)), None, "a struct is not callable");
assert_eq!(name(Pos::new(12, 0)), None);
}
}
+14
Переглянути файл
@@ -268,6 +268,19 @@ pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: Agent
host.project(window)?.agents.prompt(&task, prompt, now).await
}
/// Answers a non-blocking question, without cancelling the current turn.
#[command(trust = trusted)]
pub async fn agent_answer_question(
host: &Host,
window: &str,
task: String,
question: String,
answer: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.answer_question(&task, &question, answer).await
}
/// Drops a queued message and returns it (to edit it).
#[command(trust = always)]
pub fn agent_unqueue(host: &Host, window: &str, task: String, queued: String) -> IdeResult<AgentQueued> {
@@ -1015,6 +1028,7 @@ mod tests {
ide_command::domain!(
agent:
agent_accept_changes,
agent_answer_question,
agent_archive,
agent_base_text,
agent_cancel,
+41 -28
Переглянути файл
@@ -5,7 +5,7 @@ use ide_extension::Capability;
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
use std::{
collections::{BTreeSet, HashMap},
path::Path,
path::{Path, PathBuf},
};
#[derive(Clone, Default)]
@@ -136,32 +136,14 @@ impl PluginHost {
if !path.is_absolute() {
return None;
}
let workspace = workspace.as_ref()?;
let real = ide_plugin::resolve_real(path);
// The file's own project, not the invoking window's: annotations follow
// the file, so a plugin hears about a file another window has open.
let root = match client {
Some(client) => workspace
.project_of(client)
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.or_else(|| {
workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count())
}),
None => workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count()),
}?;
let root = file_project(workspace.as_deref()?, client, path)?;
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
return None;
}
if let WorkbenchEvent::DocumentChanged(change) = event {
if let WorkbenchEvent::DocumentChanged(_) = event {
// Typed text: only for plugins that may read editors, and only for paths they named.
// The path stays absolute until delivery (`relativize_documents`): the batch is
// filtered again then, against the grants and subscriptions of that moment.
let filter = filters.and_then(|filters| filters.get(event.kind().name()))?;
let granted = &plugin.meta.lock().granted;
if !granted.contains(&Capability::ProjectRead)
@@ -170,11 +152,7 @@ impl PluginHost {
{
return None;
}
let real = ide_plugin::resolve_real(path);
let relative = real.strip_prefix(ide_plugin::resolve_real(&root)).ok()?;
let mut change = change.clone();
change.path = relative.to_string_lossy().replace('\\', "/");
return Some(WorkbenchEvent::DocumentChanged(change));
return Some(event.clone());
}
filters
.and_then(|filters| filters.get(event.kind().name()))
@@ -183,6 +161,41 @@ impl PluginHost {
})
.collect()
}
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
pub(super) fn relativize_documents(
shared: &super::api::Shared,
client: Option<&str>,
events: Vec<WorkbenchEvent>,
) -> Vec<WorkbenchEvent> {
let workspace = shared.workspace();
events
.into_iter()
.filter_map(|event| {
let WorkbenchEvent::DocumentChanged(mut change) = event else { return Some(event) };
let path = Path::new(&change.path);
let root = file_project(workspace.as_deref()?, client, path)?;
let relative = ide_plugin::resolve_real(path)
.strip_prefix(ide_plugin::resolve_real(&root))
.ok()?
.to_string_lossy()
.replace('\\', "/");
change.path = relative;
Some(WorkbenchEvent::DocumentChanged(change))
})
.collect()
}
}
/// The open project an absolute `path` belongs to: the invoking window's when the file is in
/// it, else the innermost open project containing it. Annotations follow the file, so a
/// plugin hears about a file another window has open.
fn file_project(workspace: &dyn super::api::PluginWorkspace, client: Option<&str>, path: &Path) -> Option<PathBuf> {
let real = ide_plugin::resolve_real(path);
let contains = |r: &PathBuf| real.starts_with(ide_plugin::resolve_real(r));
client
.and_then(|client| workspace.project_of(client).filter(contains))
.or_else(|| workspace.projects().into_iter().filter(contains).max_by_key(|r| r.components().count()))
}
#[cfg(test)]
+7 -3
Переглянути файл
@@ -33,10 +33,10 @@ struct Decl {
}
#[derive(Clone, Debug)]
struct Agent {
pub(super) struct Agent {
/// The jar, resolved inside the package.
jar: PathBuf,
args: Option<String>,
pub(super) jar: PathBuf,
pub(super) args: Option<String>,
}
/// Agents of enabled plugins.
@@ -47,6 +47,10 @@ pub struct JavaAgents {
}
impl JavaAgents {
pub(super) fn for_plugin(&self, plugin: &str) -> Option<Agent> {
self.items.read().iter().find(|(_, id, _)| id == plugin).map(|(_, _, agent)| agent.clone())
}
fn add(self: &Arc<Self>, plugin: String, agent: Agent) -> Disposable {
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
self.items.write().push((seq, plugin, agent));
+21
Переглянути файл
@@ -2214,6 +2214,7 @@ impl PluginHost {
if events.is_empty() {
return Ok(());
}
let events = Self::relativize_documents(&shared, invocation.client.as_deref(), events);
rt.handle_events(events, invocation)
},
move |result| {
@@ -3087,6 +3088,26 @@ impl PluginHost {
homepage: m.homepage.clone(),
change_notes: m.change_notes.clone(),
icon: p.icon.clone(),
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
let pin = self
.ledger
.lock()
.get(&p.subject())
.filter(|grant| grant.has(&Capability::JavaAgent))
.and_then(|grant| grant.binaries.get(&Capability::JavaAgent.to_string()).cloned());
let approved = pin.as_ref().is_some_and(|pin| {
pin.path == agent.jar && ledger::file_hash(&pin.path).is_ok_and(|hash| hash == pin.hash)
});
PluginJavaAgent {
file_name: agent
.jar
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| agent.jar.display().to_string()),
args: agent.args,
approved,
}
}),
source: p.source,
path: p.dir().to_path_buf().into(),
enabled: !self.state.lock().disabled.contains(&m.id),
+14
Переглянути файл
@@ -55,6 +55,18 @@ impl PluginStatus {
}
}
/// The Java agent a plugin contributes, for Settings › Plugins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginJavaAgent {
/// The jar's file name.
pub file_name: String,
/// The optional argument passed after `=`.
pub args: Option<String>,
/// The jar still has the hash recorded when `java.agent` was granted.
pub approved: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginInfo {
@@ -66,6 +78,8 @@ pub struct PluginInfo {
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
/// The Java agent this plugin declares, and whether it is still approved.
pub java_agent: Option<PluginJavaAgent>,
pub source: PluginSource,
/// Package directory.
pub path: ide_core::IpcPath,
+243
Переглянути файл
@@ -662,6 +662,34 @@ async fn rust_references_and_rename_through_mcp() {
assert!(std::time::Instant::now() < deadline, "language server did not find format_price references");
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
// Its callers, the callees of one of them, and the hierarchy at a call.
let callers = h.json("get_call_hierarchy", args.clone()).await;
assert_eq!(callers["root"]["name"], "format_price", "{callers}");
let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").expect("main calls it");
assert_eq!(main["filePath"], "src/main.rs");
let call = main["callSites"]
.as_array()
.unwrap()
.iter()
.find(|s| s["lineText"].as_str().unwrap().contains("format_price("))
.expect("the call in main");
assert_eq!(call["filePath"], "src/main.rs");
let callees = h
.json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":main["startLine"], "column":main["startColumn"], "direction":"outgoing"}))
.await;
// rust-analyzer leaves out the calls inside macro arguments, such as `format_price` in `println!`.
let parse = callees["items"].as_array().unwrap().iter().find(|i| i["name"] == "parse").expect("main calls parse");
assert_eq!(
(&parse["filePath"], &parse["callSites"][0]["filePath"]),
(&json!("src/parser.rs"), &json!("src/main.rs"))
);
let at_call = h
.json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":call["startLine"], "column":call["startColumn"], "direction":"outgoing"}))
.await;
assert_eq!(
(&at_call["root"]["name"], &at_call["root"]["filePath"]),
(&json!("format_price"), &json!("src/lib.rs"))
);
let result = h.json("rename_refactoring", json!({"pathInProject":"src/lib.rs", "symbolName":"format_price", "newName":"format_amount", "line":line + 1, "column":column})).await;
assert_eq!(result["applied"], true, "{result}");
assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount"));
@@ -979,3 +1007,218 @@ async fn http_list_and_run_require_confirmation() {
assert!(result.get("headers").is_none(), "{result}");
assert!(result.get("request").is_none(), "{result}");
}
#[tokio::test(flavor = "multi_thread")]
async fn call_hierarchy_is_listed_for_untrusted_projects() {
let h = Harness::new();
let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap();
assert!(tools.iter().any(|t| t.name == "get_call_hierarchy"));
}
#[tokio::test(flavor = "multi_thread")]
async fn call_hierarchy_without_a_language_server_says_it_is_unsupported() {
let h = Harness::new();
let error = h.error("get_call_hierarchy", json!({"filePath":"src/a.txt","line":1,"column":1})).await;
assert!(error.contains("call hierarchy"), "{error}");
}
#[tokio::test(flavor = "multi_thread")]
async fn call_hierarchy_rejects_an_unknown_direction() {
let h = Harness::new();
let args = json!({"filePath":"src/a.txt","line":1,"column":1,"direction":"up"});
assert_eq!(h.error("get_call_hierarchy", args).await, "direction must be incoming or outgoing");
}
/// `src/lib.rs`: `price` calls `double`; `src/main.rs`: `main` calls `price` and `show`;
/// `other/c.rs`: `helper` calls `price`; a library class calls it too.
const LIB_RS: &str = "pub fn price(cents: u64) -> u64 {\n double(cents)\n}\nfn double(v: u64) -> u64 { v * 2 }\n";
const MAIN_RS: &str = "fn main() {\n let a = price(1);\n show(a);\n}\nfn show(v: u64) {}\n";
const C_RS: &str = "fn helper() {\n price(2);\n}\n";
const LIBRARY_URI: &str = "jar:file:///lib.jar!/Caller.class";
/// A language server for `rust` that knows the call hierarchy of the files above.
struct CallServer {
root: PathBuf,
}
impl CallServer {
fn uri(&self, path: &str) -> String {
ide_lsp::path_to_uri_string(&self.root.join(path))
}
fn item(&self, name: &str) -> Value {
let r = |l, c, l2, c2| json!({"start":{"line":l,"character":c},"end":{"line":l2,"character":c2}});
let (uri, range, selection) = match name {
"price" => (self.uri("src/lib.rs"), r(0, 0, 2, 1), r(0, 7, 0, 12)),
"double" => (self.uri("src/lib.rs"), r(3, 0, 3, 34), r(3, 3, 3, 9)),
"main" => (self.uri("src/main.rs"), r(0, 0, 3, 1), r(0, 3, 0, 7)),
"show" => (self.uri("src/main.rs"), r(4, 0, 4, 18), r(4, 3, 4, 7)),
"helper" => (self.uri("other/c.rs"), r(0, 0, 2, 1), r(0, 3, 0, 9)),
_ => (LIBRARY_URI.to_owned(), r(0, 0, 9, 1), r(2, 4, 2, 10)),
};
json!({"name":name,"kind":12,"uri":uri,"range":range,"selectionRange":selection})
}
fn call(&self, name: &str, key: &str, sites: &[(u32, u32, u32)]) -> Value {
let sites: Vec<Value> = sites
.iter()
.map(|(l, c, c2)| json!({"start":{"line":l,"character":c},"end":{"line":l,"character":c2}}))
.collect();
json!({key: self.item(name), "fromRanges": sites})
}
/// The item named at `p`: on a declaration's name or on a call.
fn prepare(&self, p: &Value) -> Value {
let uri = p["textDocument"]["uri"].as_str().unwrap();
let (line, col) = (p["position"]["line"].as_u64().unwrap(), p["position"]["character"].as_u64().unwrap());
let on =
|path: &str, l: u64, from: u64, to: u64| uri == self.uri(path) && line == l && (from..=to).contains(&col);
let name = if on("src/lib.rs", 0, 7, 12) || on("src/main.rs", 1, 12, 17) {
"price"
} else if on("src/main.rs", 0, 3, 7) {
"main"
} else {
return Value::Null;
};
json!([self.item(name)])
}
}
impl ide_jsonrpc::Handler for CallServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
let item = p["item"]["name"].as_str().unwrap_or_default();
Ok(match method {
"initialize" => json!({"capabilities": {
"textDocumentSync": {"openClose": true, "change": 1},
"callHierarchyProvider": true,
"documentSymbolProvider": true,
}}),
"textDocument/prepareCallHierarchy" => self.prepare(&p),
"callHierarchy/incomingCalls" if item == "price" => json!([
self.call("main", "from", &[(1, 12, 17)]),
self.call("helper", "from", &[(1, 4, 9)]),
self.call("Caller", "from", &[(2, 8, 13)]),
]),
"callHierarchy/outgoingCalls" if item == "price" => json!([self.call("double", "to", &[(1, 4, 10)])]),
"callHierarchy/outgoingCalls" if item == "main" => {
json!([self.call("show", "to", &[(2, 4, 8)]), self.call("price", "to", &[(1, 12, 17)])])
}
"textDocument/documentSymbol" if p["textDocument"]["uri"] == self.uri("src/main.rs") => {
let symbol = |name| {
let item = self.item(name);
json!({"name":name,"kind":12,"range":item["range"],"selectionRange":item["selectionRange"]})
};
json!([symbol("main"), symbol("show")])
}
"callHierarchy/incomingCalls" | "callHierarchy/outgoingCalls" | "textDocument/documentSymbol" => json!([]),
_ => Value::Null,
})
}
}
/// The harness with the files above and [`CallServer`] serving them.
async fn call_hierarchy_harness() -> (Harness, tokio::task::JoinHandle<()>) {
let h = Harness::new();
h.trust().await;
for (path, text) in [("src/lib.rs", LIB_RS), ("src/main.rs", MAIN_RS), ("other/c.rs", C_RS)] {
std::fs::create_dir_all(h.root.join(path).parent().unwrap()).unwrap();
std::fs::write(h.root.join(path), text).unwrap();
}
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = Arc::new(CallServer { root: h.root.clone() });
let accept = tokio::spawn(async move {
let mut peers = Vec::new();
while let Ok((stream, _)) = listener.accept().await {
let (r, w) = stream.into_split();
peers.push(ide_jsonrpc::Peer::connect(r, w, server.clone()));
}
});
let cfg: ide_language::LanguageServerConfig =
toml::from_str(&format!("name='calls'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'")).unwrap();
h.host.project("main").unwrap().lsp.set_servers_hook(Box::new(move |language, _| {
if language.as_str() == "rust" { vec![cfg.clone()] } else { Vec::new() }
}));
(h, accept)
}
fn names(result: &Value) -> Vec<&str> {
result["items"].as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap()).collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn call_hierarchy_lists_callers_with_their_call_sites() {
let (h, _server) = call_hierarchy_harness().await;
let callers = h.json("get_call_hierarchy", json!({"filePath":"src/lib.rs","line":1,"column":9})).await;
assert_eq!(callers["root"]["name"], "price");
assert_eq!(callers["root"]["filePath"], "src/lib.rs");
assert_eq!(callers["root"]["lineText"], "pub fn price(cents: u64) -> u64 {");
assert_eq!(callers["total"], 3);
let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").unwrap();
assert_eq!(
main,
&json!({"name":"main","kind":"function","filePath":"src/main.rs",
"startLine":1,"startColumn":4,"endLine":1,"endColumn":8,"lineText":"fn main() {",
"callSites":[{"filePath":"src/main.rs","startLine":2,"startColumn":13,"endLine":2,"endColumn":18,
"lineText":" let a = price(1);"}]})
);
// An item's position is a valid input for the next level.
let main_calls = h
.json(
"get_call_hierarchy",
json!({"filePath":"src/main.rs","line":main["startLine"],"column":main["startColumn"],"direction":"outgoing"}),
)
.await;
assert_eq!(names(&main_calls), ["price", "show"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn outgoing_call_sites_are_in_the_file_of_the_root() {
let (h, _server) = call_hierarchy_harness().await;
// On the call `price(1)` in main.rs: the hierarchy of `price`, declared in lib.rs.
let callees = h
.json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":2,"column":14,"direction":"outgoing"}))
.await;
assert_eq!(callees["root"]["filePath"], "src/lib.rs");
assert_eq!(names(&callees), ["double"]);
assert_eq!(
callees["items"][0]["callSites"],
json!([{"filePath":"src/lib.rs","startLine":2,"startColumn":5,"endLine":2,"endColumn":11,"lineText":" double(cents)"}])
);
let from_main = h
.json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":1,"column":4,"direction":"outgoing"}))
.await;
let price = &from_main["items"][0];
assert_eq!((&price["filePath"], &price["callSites"][0]["filePath"]), (&json!("src/lib.rs"), &json!("src/main.rs")));
assert_eq!(price["callSites"][0]["lineText"], " let a = price(1);");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_position_in_a_function_body_means_that_function() {
let (h, _server) = call_hierarchy_harness().await;
let body = json!({"filePath":"src/main.rs","line":2,"column":5,"direction":"outgoing"});
let callees = h.json("get_call_hierarchy", body).await;
assert_eq!(callees["root"]["name"], "main");
assert_eq!(names(&callees), ["price", "show"]);
let outside = h.error("get_call_hierarchy", json!({"filePath":"src/main.rs","line":6,"column":1})).await;
assert_eq!(outside, "no function or method at 6:1");
}
#[tokio::test(flavor = "multi_thread")]
async fn call_hierarchy_pages_are_sorted_and_scoped() {
let (h, _server) = call_hierarchy_harness().await;
let at = |extra: Value| {
let mut args = json!({"filePath":"src/lib.rs","line":1,"column":9});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
args
};
let first = h.json("get_call_hierarchy", at(json!({"limit":2}))).await;
assert_eq!(names(&first), ["Caller", "helper"]);
assert_eq!(first["items"][0]["filePath"], LIBRARY_URI);
assert!(first["items"][0].get("lineText").is_none(), "{first}");
assert_eq!((&first["more"], &first["nextOffset"]), (&json!(true), &json!(2)));
let next = h.json("get_call_hierarchy", at(json!({"limit":2,"offset":2}))).await;
assert_eq!(names(&next), ["main"]);
let scoped = h.json("get_call_hierarchy", at(json!({"scope":"src"}))).await;
assert_eq!(names(&scoped), ["main"]);
assert_eq!(scoped["total"], 1);
assert_eq!(scoped["root"]["name"], "price", "the root is shown whatever the scope");
}
+32
Переглянути файл
@@ -2204,6 +2204,10 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap();
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
assert!(info.contributions.iter().any(|c| c.point == "javaAgents" && c.label == "fixture agent.jar=mode=test"));
let agent = info.java_agent.clone().expect("agent metadata");
assert_eq!(agent.file_name, "fixture agent.jar");
assert_eq!(agent.args.as_deref(), Some("mode=test"));
assert!(!agent.approved);
let source = f.host.java_agents();
let launch = || {
let agents = ide_run::java_agent::approved(&source.agents());
@@ -2217,6 +2221,7 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
// Granted: the installed jar with its arguments, one argument after the VM options.
let info = f.host.set_capability("java-agent", "java.agent", true).unwrap();
assert!(info.capabilities.iter().any(|c| c.id == "java.agent" && c.granted));
assert!(info.java_agent.as_ref().is_some_and(|agent| agent.approved));
let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap();
let option = format!("-javaagent:{}=mode=test", jar.display());
let mut with_agent = plain.clone();
@@ -2228,7 +2233,11 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
let (args, notes) = launch();
assert_eq!(args, plain);
assert!(notes.len() == 1 && notes[0].contains("changed since it was approved"), "{notes:?}");
let changed = f.host.info_of("java-agent").unwrap();
assert!(!changed.java_agent.as_ref().unwrap().approved, "Settings must show the changed jar");
f.host.set_capability("java-agent", "java.agent", false).unwrap();
f.host.set_capability("java-agent", "java.agent", true).unwrap();
assert!(f.host.info_of("java-agent").unwrap().java_agent.as_ref().is_some_and(|a| a.approved));
assert_eq!(launch(), (with_agent.clone(), vec![]));
// Revoked, then the plugin disabled: no agent either way.
@@ -5275,6 +5284,29 @@ fn plugin_readonly_fields_and_table_row_extensions_round_trip() {
}
}
#[test]
fn document_changes_reach_plugins_relative_to_the_project() {
let f = fixture(Limits::default());
f.install(&sample("path-events"));
f.run("test.path-events", "count", None).unwrap();
let deliver = |path: &str| {
let change = ide_plugin::DocumentChanged {
path: to_ipc(&f.project.join(path)),
base_version: 1,
version: 2,
changes: Vec::new(),
};
f.host.post_events(Some("main"), vec![WorkbenchEvent::DocumentChanged(change)]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
assert!(f.host.wait_events(Duration::from_secs(10)));
};
deliver("src/main.rs");
assert_eq!(f.run("test.path-events", "document", None).unwrap(), None, "outside the subscribed paths");
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
deliver("config/app.yaml");
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
}
#[test]
fn path_filtered_events_do_not_wake_idle_plugins_and_recheck_queued_filters() {
let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(100)), ..Limits::default() });
+461 -33
Переглянути файл
@@ -68,7 +68,7 @@ pub(crate) struct Shared {
pub store: Option<Store>,
pub indexing: AtomicBool,
pub cancelled: AtomicBool,
/// Files whose content was (re)read and parsed; observability for tests.
/// Non-cached content reads, including binary/unsupported files; used by tests.
pub parsed: std::sync::atomic::AtomicUsize,
queue: Mutex<Queue>,
wake: Condvar,
@@ -160,14 +160,38 @@ impl Shared {
q.busy = true;
}
if scan {
let startup_started = Instant::now();
// A warm start can trust the snapshot when neither the scope nor any
// directory/file metadata changed. Rebuilding the walk's file list is
// the expensive part; validate the flat manifest first.
if !self.try_fast_start() {
let snapshot_started = Instant::now();
let fast = self.try_fast_start();
let snapshot_elapsed = snapshot_started.elapsed();
if !fast {
let snapshot_guard = SystemTime::now();
let walk_started = Instant::now();
let found = self.walk_roots(None);
let walk_elapsed = walk_started.elapsed();
let hydration_started = Instant::now();
self.load_persisted(&found);
let hydration_elapsed = hydration_started.elapsed();
self.full_scan(Some(found), snapshot_guard);
if !self.is_cancelled() {
tracing::info!(
mode = "fallback",
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
walk_ms = walk_elapsed.as_millis() as u64,
hydration_ms = hydration_elapsed.as_millis() as u64,
elapsed_ms = startup_started.elapsed().as_millis() as u64,
"index startup completed"
);
}
} else if !self.is_cancelled() {
tracing::info!(
mode = "snapshot",
elapsed_ms = startup_started.elapsed().as_millis() as u64,
"index startup completed"
);
}
} else {
self.indexing.store(false, Ordering::SeqCst);
@@ -234,6 +258,7 @@ impl Shared {
return false;
}
let root = filter.root();
let validation_started = Instant::now();
for i in 0..snapshot.dirs_len() {
let rel = snapshot.dir(i);
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
@@ -265,6 +290,7 @@ impl Shared {
return false;
}
}
let validation_elapsed = validation_started.elapsed();
let build_started = Instant::now();
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
(0..snapshot.len())
@@ -302,9 +328,16 @@ impl Shared {
d.load_bulk(entries, dirs);
drop(d);
tracing::info!(
"index snapshot: warm start in {:?} (load {loaded:?}, validate/build {built:?}, insert {:?})",
started.elapsed(),
insert_started.elapsed()
mode = "snapshot",
snapshot_hydrated = snapshot.len(),
discovered = 0usize,
symbol_extractions = 0usize,
load_ms = loaded.as_millis() as u64,
directory_validation_ms = validation_elapsed.as_millis() as u64,
file_validation_build_ms = built.as_millis() as u64,
insert_ms = insert_started.elapsed().as_millis() as u64,
elapsed_ms = started.elapsed().as_millis() as u64,
"index snapshot hydrated"
);
#[cfg(test)]
eprintln!(
@@ -441,7 +474,7 @@ impl Shared {
self.scan(None, found, guard);
}
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) {
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
let started = Instant::now();
self.indexing.store(true, Ordering::SeqCst);
self.emit_state();
@@ -457,10 +490,12 @@ impl Shared {
let filter = self.filter();
let walk_started = Instant::now();
let was_prewalked = prewalked.is_some();
let found = prewalked.unwrap_or_else(|| self.walk_roots(dirs));
let walk = walk_started.elapsed();
if self.is_cancelled() {
return self.end_scan(task);
self.end_scan(task);
return None;
}
let classify_started = Instant::now();
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
@@ -487,6 +522,7 @@ impl Shared {
self.persist(&[], &stale, false);
let total = todo.len();
let update_started = Instant::now();
let mut laps = ChunkLaps::default();
{
// One streaming parallel pass: parse on `INDEX_POOL` without
@@ -546,11 +582,14 @@ impl Shared {
laps.extract = pass_started.elapsed();
}
if self.is_cancelled() {
return self.end_scan(task);
self.end_scan(task);
return None;
}
let durable_started = Instant::now();
self.persist(&[], &[], true);
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
let d = self.data.read();
@@ -563,6 +602,7 @@ impl Shared {
tracing::warn!("index recent snapshot: {e}");
}
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -574,20 +614,47 @@ impl Shared {
cancellable: false,
});
self.emit_state();
if self.is_cancelled() {
return None;
}
laps.outcomes.not_processed += total - laps.outcomes.total();
let counts = ScanCounts {
discovered: found.len(),
metadata_reused: found.len() - total,
scheduled: total,
outcomes: laps.outcomes,
};
let outcomes = &counts.outcomes;
let d = self.data.read();
tracing::info!(
"indexed {} files ({} parsed, {} symbols) in {:?} (walk {:?}, classify {:?}, extract {:?}, insert {:?}, persist {:?}, durable {:?})",
d.file_count,
total,
d.symbol_count,
started.elapsed(),
walk,
classify,
laps.extract,
laps.insert,
laps.persist,
durable
scope = if dirs.is_some() { "subtree" } else { "full" },
files = d.file_count,
symbols = d.symbol_count,
discovered = counts.discovered,
metadata_reused = counts.metadata_reused,
scheduled = counts.scheduled,
hash_reused = outcomes.hash_reused,
symbol_extractions = outcomes.symbol_extractions,
ignored = outcomes.ignored,
oversized = outcomes.oversized,
binary = outcomes.binary,
unsupported = outcomes.unsupported,
read_failed = outcomes.read_failed,
not_processed = outcomes.not_processed,
prewalked = was_prewalked,
walk_ms = walk.as_millis() as u64,
classify_ms = classify.as_millis() as u64,
// Pipeline and update wall times overlap insert/persist; do not sum these fields.
extract_pipeline_ms = laps.extract.as_millis() as u64,
insert_ms = laps.insert.as_millis() as u64,
persist_ms = laps.persist.as_millis() as u64,
durable_ms = durable.as_millis() as u64,
update_ms = update_elapsed.as_millis() as u64,
snapshot_write_ms = snapshot_elapsed.as_millis() as u64,
elapsed_ms = started.elapsed().as_millis() as u64,
"index scan completed"
);
Some(counts)
}
/// Extracts records in parallel, then publishes them to memory and disk.
@@ -599,6 +666,7 @@ impl Shared {
files.par_iter().filter_map(|(f, prev_hash)| self.parse_found(f, *prev_hash, &filter)).collect()
});
laps.extract = started.elapsed();
laps.outcomes.not_processed = files.len() - extracted.len();
if extracted.is_empty() {
return laps;
}
@@ -622,9 +690,9 @@ impl Shared {
let key = filter.store_key(&f.path);
let outcome = match self.extract(f, prev_hash) {
Extracted::Unchanged => ParsedOutcome::Unchanged { mtime: f.mtime, size: f.size, ignored: f.ignored },
Extracted::New(rec) => {
Extracted::New(rec, extraction) => {
let bytes = key.as_ref().and_then(|_| postcard::to_allocvec(&rec).ok());
ParsedOutcome::New { rec, bytes }
ParsedOutcome::New { rec, bytes, extraction }
}
};
Some(ParsedFile { rel, key, outcome, path: f.path.clone() })
@@ -640,7 +708,8 @@ impl Shared {
for out in batch {
let ParsedFile { rel, key, outcome, path } = out;
match outcome {
ParsedOutcome::New { rec, bytes } => {
ParsedOutcome::New { rec, bytes, extraction } => {
laps.outcomes.record(extraction);
if let (Some(key), Some(bytes)) = (key, bytes) {
puts.push((key, bytes));
}
@@ -658,10 +727,13 @@ impl Shared {
d.insert(e, symbols);
}
for r in refreshes {
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored)
&& let Some(key) = r.key
{
refreshed_records.push((key, rec));
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored) {
laps.outcomes.record(Extraction::HashReused);
if let Some(key) = r.key {
refreshed_records.push((key, rec));
}
} else {
laps.outcomes.not_processed += 1;
}
}
}
@@ -726,15 +798,18 @@ impl Shared {
fn extract(&self, f: &Found, prev_hash: Option<[u8; 32]>) -> Extracted {
let mut rec = FileRecord { mtime: f.mtime, size: f.size, ignored: f.ignored, ..Default::default() };
if f.ignored || f.size > MAX_SYMBOL_FILE {
return Extracted::New(rec);
if f.ignored {
return Extracted::New(rec, Extraction::Ignored);
}
if f.size > MAX_SYMBOL_FILE {
return Extracted::New(rec, Extraction::Oversized);
}
let mut bytes = Vec::with_capacity(f.size as usize);
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
Ok(_) => {}
Err(e) => {
tracing::debug!("index: cannot read {}: {e}", f.path.display());
return Extracted::New(rec);
return Extracted::New(rec, Extraction::ReadFailed);
}
}
rec.hash = *blake3::hash(&bytes).as_bytes();
@@ -743,7 +818,7 @@ impl Shared {
}
self.parsed.fetch_add(1, Ordering::Relaxed);
if bytes[..bytes.len().min(8192)].contains(&0) {
return Extracted::New(rec);
return Extracted::New(rec, Extraction::Binary);
}
let text = String::from_utf8_lossy(&bytes);
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
@@ -760,8 +835,9 @@ impl Shared {
bases: t.bases,
})
.collect();
return Extracted::New(rec, Extraction::Symbols);
}
Extracted::New(rec)
Extracted::New(rec, Extraction::Unsupported)
}
fn process(&self, jobs: Vec<Job>) {
@@ -938,7 +1014,7 @@ fn first_line(text: &str) -> &str {
enum Extracted {
/// Content hash matches the indexed version.
Unchanged,
New(FileRecord),
New(FileRecord, Extraction),
}
/// Wall-time laps of one `index_files` chunk, accumulated by the scan.
@@ -947,6 +1023,7 @@ struct ChunkLaps {
extract: Duration,
insert: Duration,
persist: Duration,
outcomes: ExtractionCounts,
}
impl ChunkLaps {
@@ -954,6 +1031,7 @@ impl ChunkLaps {
self.extract += other.extract;
self.insert += other.insert;
self.persist += other.persist;
self.outcomes.add(other.outcomes);
}
}
@@ -967,7 +1045,7 @@ struct MetadataRefresh {
enum ParsedOutcome {
Unchanged { mtime: u64, size: u64, ignored: bool },
New { rec: FileRecord, bytes: Option<Vec<u8>> },
New { rec: FileRecord, bytes: Option<Vec<u8>>, extraction: Extraction },
}
/// One file parsed off the index thread: its outcome ready to publish, with new
@@ -980,6 +1058,356 @@ struct ParsedFile {
path: PathBuf,
}
/// Mutually exclusive outcomes for this batch, not all files in the index. "Symbols"
/// means tags() was called, even when no symbols were found.
#[derive(Clone, Copy)]
enum Extraction {
HashReused,
Symbols,
Ignored,
Oversized,
Binary,
Unsupported,
ReadFailed,
}
#[derive(Default, Debug, PartialEq, Eq)]
struct ExtractionCounts {
hash_reused: usize,
symbol_extractions: usize,
ignored: usize,
oversized: usize,
binary: usize,
unsupported: usize,
read_failed: usize,
/// Cancellation, a changed root configuration, or a concurrently removed entry.
not_processed: usize,
}
impl ExtractionCounts {
fn total(&self) -> usize {
self.hash_reused
+ self.symbol_extractions
+ self.ignored
+ self.oversized
+ self.binary
+ self.unsupported
+ self.read_failed
+ self.not_processed
}
fn record(&mut self, outcome: Extraction) {
*match outcome {
Extraction::HashReused => &mut self.hash_reused,
Extraction::Symbols => &mut self.symbol_extractions,
Extraction::Ignored => &mut self.ignored,
Extraction::Oversized => &mut self.oversized,
Extraction::Binary => &mut self.binary,
Extraction::Unsupported => &mut self.unsupported,
Extraction::ReadFailed => &mut self.read_failed,
} += 1;
}
fn add(&mut self, other: Self) {
self.hash_reused += other.hash_reused;
self.symbol_extractions += other.symbol_extractions;
self.ignored += other.ignored;
self.oversized += other.oversized;
self.binary += other.binary;
self.unsupported += other.unsupported;
self.read_failed += other.read_failed;
self.not_processed += other.not_processed;
}
}
struct ScanCounts {
/// Files yielded by the filtered walker, not every file on disk.
discovered: usize,
/// Metadata matched an in-memory entry (possibly loaded from disk cache).
metadata_reused: usize,
scheduled: usize,
outcomes: ExtractionCounts,
}
#[cfg(test)]
mod metric_tests {
use super::*;
use std::sync::Arc;
fn index_files<'a>(index: &Shared, files: impl Iterator<Item = &'a Found>, force: bool) -> ExtractionCounts {
let files: Vec<_> = files
.map(|f| {
let hash = if force || f.ignored { None } else { index.data.read().get(&f.path).map(|e| e.hash) };
(f.clone(), hash)
})
.collect();
index.index_files(&files).outcomes
}
fn shared(root: &Path) -> Shared {
Shared::new(
PathFilter::new(root, &crate::IndexRoots::from(Vec::new()), &[]),
Arc::new(LanguageRegistry::load(None).unwrap()),
Arc::new(Syntax::new()),
Arc::new(ide_core::NullSink),
None,
)
}
#[test]
fn streaming_scan_counts_full_batch_and_tail() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let shared = shared(&root);
let count = SCAN_BATCH + 3;
for i in 0..count {
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
}
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
assert_eq!(shared.data.read().file_count as usize, count);
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
assert_eq!(hot.outcomes.total(), 0);
}
#[test]
fn removed_entry_is_not_counted_as_hash_reuse() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let shared = shared(&root);
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
let (found, hash) = {
let data = shared.data.read();
let e = data.get(&path).unwrap();
(Found { path: path.clone(), mtime: e.mtime, size: e.size, ignored: e.ignored }, e.hash)
};
let parsed = shared.parse_found(&found, Some(hash), &shared.filter()).unwrap();
shared.data.write().remove(&path).unwrap();
let counts = shared.publish(std::iter::once(parsed)).outcomes;
assert_eq!(counts, ExtractionCounts { not_processed: 1, ..Default::default() });
assert_eq!(shared.data.read().file_count, 0);
}
#[test]
fn scan_distinguishes_cold_metadata_and_hash_reuse() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}\n").unwrap();
let shared = shared(&root);
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
assert_eq!(hot.outcomes, ExtractionCounts::default());
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
let mut rec = {
let data = shared.data.read();
data.record(data.get(&path).unwrap())
};
rec.mtime = rec.mtime.wrapping_add(1);
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
shared.data.write().insert(entry, symbols);
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
assert_eq!(shared.data.read().symbol_count, 1);
}
#[test]
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let shared = shared(&root);
let mut found = Vec::new();
for (name, contents, ignored, size) in [
("source.rs", "fn source() {}", false, 14),
("ignored.rs", "fn hidden() {}", true, 14),
("huge.rs", "", false, MAX_SYMBOL_FILE + 1),
("binary.rs", "\0", false, 1),
("plain.unknown", "plain", false, 5),
("missing.rs", "", false, 0),
] {
let path = root.join(name);
if name != "missing.rs" {
std::fs::write(&path, contents).unwrap();
}
found.push(Found { path, mtime: 0, size, ignored });
}
let counts = index_files(&shared, found.iter(), false);
assert_eq!(
counts,
ExtractionCounts {
symbol_extractions: 1,
ignored: 1,
oversized: 1,
binary: 1,
unsupported: 1,
read_failed: 1,
hash_reused: 0,
not_processed: 0,
}
);
assert_eq!(shared.data.read().file_count as usize, found.len());
assert_eq!(index_files(&shared, found[..1].iter(), false).hash_reused, 1);
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
}
#[test]
fn reopened_cache_counts_metadata_reuse() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let found = index.walk_roots(None);
index.load_persisted(&found);
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
assert_eq!(counts.outcomes, ExtractionCounts::default());
assert_eq!(index.data.read().symbol_count, 1);
}
#[test]
fn warm_snapshot_hydrates_without_symbol_extraction() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert!(index.try_fast_start());
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
assert_eq!(index.data.read().file_count, 1);
assert_eq!(index.data.read().symbol_count, 1);
}
#[test]
fn cancelled_warm_start_does_not_log_completion() {
struct CompletionCounter(Arc<std::sync::atomic::AtomicUsize>);
impl tracing::Subscriber for CompletionCounter {
fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
true
}
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
tracing::span::Id::from_u64(1)
}
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
fn enter(&self, _: &tracing::span::Id) {}
fn exit(&self, _: &tracing::span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
struct Message(bool);
impl tracing::field::Visit for Message {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" && format!("{value:?}").contains("index startup completed") {
self.0 = true;
}
}
}
let mut message = Message(false);
event.record(&mut message);
if message.0 {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
}
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index.scan(None, None, SystemTime::now()).unwrap();
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
index.cancel();
tracing::subscriber::with_default(CompletionCounter(count.clone()), || {
tracing::info!("index startup completed");
assert_eq!(count.swap(0, Ordering::Relaxed), 1);
index.run(true);
});
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
assert_eq!(index.data.read().file_count, 1);
assert_eq!(count.load(Ordering::Relaxed), 0);
}
#[test]
fn files_outside_current_scope_and_cancelled_batches_are_accounted_for() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let index = shared(&root);
// A scan can retain Found values from a root removed by set_scope.
let outside = Found { path: dir.path().join("outside.rs"), mtime: 0, size: 0, ignored: false };
assert_eq!(
index_files(&index, [&outside].into_iter(), false),
ExtractionCounts { not_processed: 1, ..Default::default() }
);
index.cancel();
let inside = Found { path: root.join("inside.rs"), mtime: 0, size: 0, ignored: false };
assert_eq!(
index_files(&index, [&inside].into_iter(), false),
ExtractionCounts { not_processed: 1, ..Default::default() }
);
}
#[test]
fn cancellation_during_final_notifications_suppresses_completion() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::write(root.join("source.rs"), "fn source() {}").unwrap();
let index: Arc<Shared> = Arc::new_cyclic(|weak: &std::sync::Weak<Shared>| {
let mut index = shared(&root);
let weak = weak.clone();
index.sink = Arc::new(move |event| {
if matches!(event, IdeEvent::Task { done: true, .. }) {
weak.upgrade().unwrap().cancel();
}
});
index
});
assert!(index.scan(None, None, SystemTime::now()).is_none());
assert!(index.is_cancelled());
assert!(!index.indexing.load(Ordering::Relaxed));
assert_eq!(index.data.read().file_count, 1);
}
#[test]
fn cancelled_scan_does_not_report_completion() {
let dir = tempfile::tempdir().unwrap();
let shared = shared(dir.path());
shared.cancel();
assert!(shared.scan(None, None, SystemTime::now()).is_none());
assert!(!shared.indexing.load(Ordering::Relaxed));
}
}
#[cfg(test)]
mod tests {
use crate::data::safe_rel;
+2
Переглянути файл
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
("toml", include_str!("../../../languages/toml.toml")),
("typescript", include_str!("../../../languages/typescript.toml")),
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
("typst", include_str!("../../../languages/typst.toml")),
("vue", include_str!("../../../languages/vue.toml")),
("xml", include_str!("../../../languages/xml.toml")),
("yaml", include_str!("../../../languages/yaml.toml")),
@@ -612,6 +613,7 @@ mod tests {
"TTCN",
"TTCN_CFG",
"Turtle",
"Typst",
"Web IDL",
"VB.NET",
"VBScript",
+2
Переглянути файл
@@ -1032,6 +1032,7 @@ pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Ra
path: path.into(),
uri,
from_ranges,
from_path: None,
})
}
@@ -1056,6 +1057,7 @@ pub fn type_item(conv: &Conv, item: &lsp::TypeHierarchyItem) -> Option<Hierarchy
path: path.into(),
uri,
from_ranges: Vec::new(),
from_path: None,
})
}
+7 -3
Переглянути файл
@@ -3241,6 +3241,7 @@ impl LspManager {
.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), Some(cancel), DEFAULT_TIMEOUT)
.await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let root = convert::call_item(&self.conv(t.enc()), &items[0], Vec::new());
let query = || async {
let mut out = Vec::new();
for item in &items {
@@ -3263,7 +3264,10 @@ impl LspManager {
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
out.extend(
convert::call_item(&conv, &c.to, ranges)
.map(|to| HierarchyItem { from_path: Some(src.clone().into()), ..to }),
);
}
}
}
@@ -3293,8 +3297,8 @@ impl LspManager {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
Ok(CallHierarchy { items: out, incomplete })
self.note_virtual(&t.server, out.iter().chain(&root).map(|i| i.uri.as_deref()));
Ok(CallHierarchy { root, items: out, incomplete })
}
/// The type at `pos` as the server's type hierarchy names it (with its `detail`, the
+1
Переглянути файл
@@ -397,6 +397,7 @@ impl LspManager {
range: *r,
selection_range: *selection,
from_ranges: vec![*call],
from_path: None,
}),
}
}
+9
Переглянути файл
@@ -329,6 +329,11 @@ pub struct HierarchyItem {
pub selection_range: Range,
/// Call sites, for call hierarchy.
pub from_ranges: Vec<Range>,
/// The file of `from_ranges` when it is not the item's own: for an outgoing call, the
/// file of the prepared item that makes it (a path, or the URI of a virtual document).
#[serde(default)]
#[specta(optional)]
pub from_path: Option<ide_core::IpcPath>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -575,6 +580,10 @@ pub struct ServerRefactored {
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchy {
/// The symbol the hierarchy is for: the first item the server prepared at the position.
#[serde(default)]
#[specta(optional)]
pub root: Option<HierarchyItem>,
pub items: Vec<HierarchyItem>,
pub incomplete: Option<ReferencesIncomplete>,
}
+21 -6
Переглянути файл
@@ -3934,17 +3934,32 @@ async fn navigation_rename_format_and_decorations() {
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
s.respond("textDocument/prepareCallHierarchy", json!([item]));
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
let calls = h
.mgr
.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default())
.await
.unwrap()
.items;
let hierarchy =
h.mgr.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default()).await.unwrap();
let root = hierarchy.root.expect("the prepared item");
assert_eq!((root.name.as_str(), root.selection_range), ("foo", rng(0, 3, 0, 6)));
assert_eq!(root.path.to_path_buf(), path);
let calls = hierarchy.items;
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].name, "main");
assert_eq!(calls[0].from_ranges, vec![rng(1, 0, 1, 3)]);
assert_eq!(s.requested("callHierarchy/incomingCalls")[0]["item"]["data"], "id");
// Outgoing calls of each prepared item are in that item's file.
let other = path.with_file_name("b.mk");
let second =
json!({ "name": "foo", "kind": 12, "uri": uri_of(&other), "range": r(4,0,4,11), "selectionRange": r(4,3,4,6) });
s.respond("textDocument/prepareCallHierarchy", json!([item, second]));
s.respond("callHierarchy/outgoingCalls", json!([{ "to": { "name": "bar", "kind": 12, "uri": uri, "range": r(2,0,2,6), "selectionRange": r(2,0,2,3) }, "fromRanges": [r(0,8,0,11)] }]));
let callees = h
.mgr
.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Outgoing, Default::default())
.await
.unwrap()
.items;
let from: Vec<_> = callees.iter().map(|c| c.from_path.clone().map(|p| p.into_path_buf())).collect();
assert_eq!(from, [Some(path.clone()), Some(other)]);
// No documentSymbolProvider → None so callers fall back to tree-sitter.
assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None);
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f9c0cb4fca66ede5adcb1951dd05c3938c218224cb61e63a574ba08a93f4a041
872f94f4bbc441457f36ed7b44b3a2fb6b87021f2f0a66104caf5c807b524147
+6 -2
Переглянути файл
@@ -1,13 +1,13 @@
id = "test.path-events"
name = "Path event fixture"
version = "0.1.0"
engines.openidea = "^1.3"
engines.openidea = "^1.6"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
[capabilities]
required = ["storage"]
optional = ["events", "project.read"]
optional = ["events", "project.read", "editor.read"]
[[contributes.providers]]
kinds = ["hover"]
@@ -29,6 +29,10 @@ title = "all"
id = "off"
title = "off"
[[contributes.commands]]
id = "document"
title = "document"
[[contributes.commands]]
id = "count"
title = "count"
+7
Переглянути файл
@@ -11,6 +11,7 @@ impl Plugin for Fixture {
let globs: Vec<_> = glob.lines().collect();
let _ = host::subscribe_paths("file-opened", &globs);
let _ = host::subscribe_paths("file-saved", &["config/*.yaml"]);
let _ = host::subscribe_paths("document-changed", &["config/*.yaml"]);
Ok(())
}
fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
@@ -31,12 +32,18 @@ impl Plugin for Fixture {
Ok(None)
}
"count" => Ok(host::storage::get("count")?),
"document" => Ok(host::storage::get("document")?),
_ => Err(Error::NotFound(id.into())),
}
}
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
let count = host::storage::get("count").ok().flatten().and_then(|n| n.parse::<usize>().ok()).unwrap_or(0);
host::storage::set("count", &(count + events.len()).to_string()).unwrap();
for event in events {
if let Event::DocumentChanged(change) = event {
host::storage::set("document", &change.path).unwrap();
}
}
}
}
impl HoverProvider for Fixture {
+190 -51
Переглянути файл
@@ -13,12 +13,18 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let src = code_only(&src);
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
let roots = test_roots(&src);
let run_exes = run_step_exes(&src);
for step in steps(&src) {
// `install` is what plain `zig build` runs.
if step == "install" || step == "uninstall" {
continue;
}
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
// A build step that runs an executable has no debug adapter of its own; point it at the
// executable config, which builds first and debugs the installed binary under CodeLLDB.
if let Some(exe) = run_exes.iter().find(|(name, _)| name == &step) {
c.extras.params.insert("debugTarget".into(), format!("zig:exe:{}", exe.1));
}
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
c = c.test();
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
@@ -109,52 +115,51 @@ struct Executable {
source: Option<String>,
}
/// `addExecutable(.{ .name = "…", … .root_source_file = <b>.path("…") … })`: the name at the
/// options' top level (an `imports` entry has its own `.name`) and the first root source file.
/// `.name` and `.root_source_file` of an `addExecutable` call body (just after its `(`).
/// The name is read at the options' top level — an `imports` entry has its own `.name`.
fn add_executable_fields(body: &str) -> (Option<String>, Option<String>) {
let (mut depth, mut in_string, mut escaped) = (0usize, false, false);
let (mut name, mut source) = (None, None);
for (i, c) in body.char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'{' | '[' => depth += 1,
'}' | ']' => depth -= 1,
'.' => {
let field = &body[i + 1..];
let value = |key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
if depth == 1 && name.is_none() {
name = value("name").and_then(string_at);
}
if source.is_none()
&& let Some(v) = value("root_source_file")
&& let Some(call) = v.find(".path(")
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
{
source = string_at(&v[call + ".path(".len()..]);
}
}
_ => {}
}
}
(name, source)
}
/// `addExecutable(.{ .name = "…", … })`: the name at the options' top level and the first root source file.
fn executables(src: &str) -> Vec<Executable> {
let mut out: Vec<Executable> = Vec::new();
for (start, _) in src.match_indices("addExecutable(") {
let body = &src[start + "addExecutable(".len()..];
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
let mut name = None;
let mut source = None;
for (i, c) in body.char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'(' | '{' | '[' => depth += 1,
')' | '}' | ']' => {
depth -= 1;
if depth == 0 {
break;
}
}
'.' => {
let field = &body[i + 1..];
let value =
|key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
if depth == 2 && name.is_none() {
name = value("name").and_then(string_at);
}
if source.is_none()
&& let Some(v) = value("root_source_file")
&& let Some(call) = v.find(".path(")
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
{
source = string_at(&v[call + ".path(".len()..]);
}
}
_ => {}
}
}
let body = call_body(src, start + "addExecutable(".len());
let (name, source) = add_executable_fields(body);
if let Some(name) = name
&& !name.is_empty()
&& !out.iter().any(|e| e.name == name)
@@ -165,6 +170,109 @@ fn executables(src: &str) -> Vec<Executable> {
out
}
/// Variables assigned from `addExecutable` calls, mapped to the executable's name.
fn executable_vars(src: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for (start, _) in src.match_indices("addExecutable(") {
let body = call_body(src, start + "addExecutable(".len());
let (Some(name), Some(var)) = (add_executable_fields(body).0, assigned_var(src, start)) else { continue };
if !name.is_empty() && !out.iter().any(|(v, _)| v == var) {
out.push((var.to_owned(), name));
}
}
out
}
/// Variables assigned from `b.addRunArtifact(x)` calls, mapped to `x` (an executable or test).
fn run_artifact_vars(src: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for (start, _) in src.match_indices("addRunArtifact(") {
let body = call_body(src, start + "addRunArtifact(".len());
let arg: String = body.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
if arg.is_empty() {
continue;
}
if let Some(var) = assigned_var(src, start)
&& !out.iter().any(|(v, _)| v == var)
{
out.push((var.to_owned(), arg));
}
}
out
}
/// Step variables assigned from `b.step("name", …)` calls, mapped to the step's name.
fn step_vars(src: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".step(\"") {
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
if let Some(var) = assigned_var(src, i + 1)
&& !out.iter().any(|(v, _)| v == var)
{
out.push((var.to_owned(), name));
}
}
out
}
/// The argument of a `.dependOn(&…)` call: `after` starts just past its `&`. Stopping at the
/// matching `)` keeps a later `addRunArtifact(` in a different step from being mistaken for this
/// step's artifact.
fn depend_arg(after: &str) -> &str {
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
for (i, c) in after.char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'(' | '{' | '[' => depth += 1,
')' | '}' | ']' => {
depth -= 1;
if depth == 0 {
return &after[..i];
}
}
_ => {}
}
}
after
}
/// Steps whose `dependOn` runs an executable: `(step name, executable name)`. Both the inline
/// (`step.dependOn(&b.addRunArtifact(exe).step)`) and the assigned form
/// (`const cmd = b.addRunArtifact(exe); step.dependOn(&cmd.step)`) are handled.
fn run_step_exes(src: &str) -> Vec<(String, String)> {
let exes = executable_vars(src);
let artifacts = run_artifact_vars(src);
let steps = step_vars(src);
let mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".dependOn(&") {
let Some(step_var) = receiver_var(src, i + 1) else { continue };
let Some((_, name)) = steps.iter().find(|(v, _)| v == step_var) else { continue };
let arg = depend_arg(&src[i + ".dependOn(&".len()..]);
let exe_var = if let Some(at) = arg.find("addRunArtifact(") {
let v = &arg[at + "addRunArtifact(".len()..];
v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>()
} else {
let v: String = arg.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
artifacts.iter().find(|(var, _)| var == &v).map(|(_, exe)| exe.clone()).unwrap_or_default()
};
if let Some((_, exe_name)) = exes.iter().find(|(var, _)| var == &exe_var)
&& !out.iter().any(|(n, _)| n == name)
{
out.push((name.clone(), exe_name.clone()));
}
}
out
}
/// The call's argument text: from just after its `(` to the matching `)`.
fn call_body(src: &str, start: usize) -> &str {
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
@@ -255,14 +363,7 @@ fn test_roots(src: &str) -> Vec<(String, String)> {
tests.push((var.to_owned(), root));
}
}
let mut steps: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".step(\"") {
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
// The match includes the dot, so the assignment ends one character earlier.
if let Some(var) = assigned_var(src, i + 1) {
steps.push((var.to_owned(), name));
}
}
let steps = step_vars(src);
let mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".dependOn(&") {
let Some(step) = receiver_var(src, i + 1) else { continue };
@@ -325,6 +426,7 @@ pub fn build(b: *std.Build) void {
}) });
_ = tool;
const run_step = b.step("run", "Run the app");
run_step.dependOn(&b.addRunArtifact(exe).step);
const tests = b.addTest(.{ .root_module = mod });
const test_step = b.step("test", "Run tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
@@ -358,6 +460,11 @@ pub fn build(b: *std.Build) void {
(test.command.as_str(), test.args.as_slice()),
("zig", ["build".to_owned(), "test".to_owned()].as_slice())
);
// The run step has no adapter of its own, but points at the executable config that does.
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
assert_eq!(run.debug_adapter, None);
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
assert!(!out.iter().find(|c| c.id == "zig:docs").unwrap().extras.params.contains_key("debugTarget"));
let app = out.iter().find(|c| c.id == "zig:exe:app").unwrap();
assert_eq!(app.kind, "zig-application");
assert!(app.command.ends_with(if cfg!(windows) { "app.exe" } else { "zig-out/bin/app" }));
@@ -400,4 +507,36 @@ pub fn build(b: *std.Build) void {
]
);
}
const ASSIGNED_RUN: &str = r#"const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ .name = "app", .root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
}) });
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const tests = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/tally.zig"),
}) });
const test_step = b.step("test", "Run tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
}
"#;
#[test]
fn a_run_step_linked_through_an_assigned_command_finds_its_executable() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("build.zig"), ASSIGNED_RUN).unwrap();
let mut out = Vec::new();
detect(dir.path(), &mut out);
// The test step below the run step has its own inline addRunArtifact; it must not be
// mistaken for the run step's executable.
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
let test = out.iter().find(|c| c.id == "zig:test").unwrap();
assert!(!test.extras.params.contains_key("debugTarget"));
}
}
+1 -1
Переглянути файл
@@ -83,7 +83,7 @@ esac
"#;
const FISH_INIT: &str = concat!(
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]133;D;%s\a\e]7;file://%s%s\a' "$status" (hostname) $PWD; end; "#,
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]133;D;%s\a\e]7;file://%s%s\a' "$status" "$hostname" $PWD; end; "#,
r#"function __openidea_preexec --on-event fish_preexec; printf '\e]133;C\a'; end"#,
);
+11
Переглянути файл
@@ -329,6 +329,9 @@ impl Http {
}
own_group(ide_core::process::prepare(&mut cmd));
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
// A connection that stops delivering (a stalled proxy or mirror) fails and is retried
// instead of leaving the request waiting forever.
cmd.args(["--speed-limit", "1", "--speed-time", "30"]);
// System Settings › HTTP Proxy (a manual proxy comes in through `prepare`'s environment).
cmd.args(ide_core::proxy_settings::proxy().curl_args(url));
if self.https_only {
@@ -918,6 +921,14 @@ mod github_auth_tests {
assert_eq!(fs::read_to_string(f.path("headers")).unwrap(), "Authorization: Bearer gho_fake_second\n");
}
#[test]
fn a_stalled_transfer_times_out_instead_of_hanging() {
let f = Fixture::new();
f.get(API).unwrap();
let args = fs::read_to_string(f.path("curl-args")).unwrap();
assert!(args.contains("--speed-limit\n1\n--speed-time\n30\n"), "{args}");
}
#[test]
fn explicit_token_avoids_gh_and_non_github_urls_receive_no_credentials() {
let mut f = Fixture::new();
+22
Переглянути файл
@@ -992,6 +992,28 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/latex-lsp/texlab",
needs: &[],
},
ToolSpec {
name: "tinymist",
display: "Tinymist (Typst)",
kind: LanguageServer,
commands: &["tinymist"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Myriad-Dreamin/tinymist" },
assets: &[
rule(Mac, Arm64, "tinymist-aarch64-apple-darwin.tar.gz"),
rule(Mac, X64, "tinymist-x86_64-apple-darwin.tar.gz"),
rule(Linux, X64, "tinymist-x86_64-unknown-linux-gnu.tar.gz"),
rule(Linux, Arm64, "tinymist-aarch64-unknown-linux-gnu.tar.gz"),
rule(Windows, X64, "tinymist-x86_64-pc-windows-msvc.zip"),
rule(Windows, Arm64, "tinymist-aarch64-pc-windows-msvc.zip"),
],
locate: &["tinymist"],
},
fallback: None,
version: ver("tinymist"),
homepage: "https://myriad-dreamin.github.io/tinymist/",
needs: &[],
},
ToolSpec {
name: "slint-lsp",
display: "Slint LSP",
+2 -2
Переглянути файл
@@ -425,7 +425,7 @@ fn release_install_end_to_end_without_network() {
"curl",
&format!(
r#"out=""; url=""
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout|--speed-limit|--speed-time) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
case "$url" in
https://api.github.com/*) /bin/cat '{json}';;
*) /bin/cp '{archive}' "$out";;
@@ -485,7 +485,7 @@ fn phar_release_installs_with_a_php_launcher() {
"curl",
&format!(
r#"out=""; url=""
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout|--speed-limit|--speed-time) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
case "$url" in
https://api.github.com/*) /bin/cat '{json}';;
*) /bin/cp '{phar}' "$out";;
+8 -1
Переглянути файл
@@ -360,6 +360,10 @@ pub struct Stash {
pub index: u32,
pub message: String,
pub time_ms: f64,
/// The stash commit; its changes are those against `base`.
pub id: String,
/// The commit the stash was made on (the stash commit's first parent).
pub base: Option<String>,
}
/// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits.
@@ -529,9 +533,12 @@ pub enum CheckoutOutcome {
LocalChanges {
files: Vec<String>,
},
/// These untracked files (repository-relative paths) would be overwritten.
/// These untracked files (repository-relative paths) would be overwritten by the
/// checkout; with `removed`, they would be removed by it (tracked here, absent
/// from the target).
UntrackedFiles {
files: Vec<String>,
removed: bool,
},
/// Local branch `local` has commits that remote branch `remote` does not.
LocalBranchAhead {
+9 -1
Переглянути файл
@@ -158,7 +158,15 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult<Vec<Stash>> {
for (index, line) in lines.enumerate() {
let line = line.map_err(gx)?;
let time_ms = line.signature.time.seconds as f64 * 1000.0;
out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms });
let id = line.new_oid.to_owned();
let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string()));
out.push(Stash {
index: index as u32,
message: to_string(line.message.as_ref()),
time_ms,
id: id.to_string(),
base,
});
}
Ok(out)
}
+10 -5
Переглянути файл
@@ -771,9 +771,14 @@ fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "local changes to the following files would be overwritten")
}
/// Untracked files git refuses to overwrite, from its error message.
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "untracked working tree files would be")
/// Untracked files git refuses to lose, from its error message: they would be *removed*
/// by the checkout (tracked here, absent from the target) or *overwritten* by it (present
/// in the target). Returns the files and whether they would be removed.
fn refused_untracked(stderr: &str) -> Option<(Vec<String>, bool)> {
if let Some(files) = listed_files(stderr, "untracked working tree files would be removed") {
return Some((files, true));
}
Some((listed_files(stderr, "untracked working tree files would be")?, false))
}
/// The branch git refused to check out or update because another worktree has it, from
@@ -840,8 +845,8 @@ pub(crate) fn checkout_with(
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
}
if let Some(files) = overwritten_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files });
if let Some((files, removed)) = refused_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
}
let Some(files) = overwritten_files(&stderr) else {
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
+31 -1
Переглянути файл
@@ -849,6 +849,11 @@ fn stash_push_list_apply_pop() {
assert!(stashes[0].message.contains("WIP on main"), "{stashes:?}");
assert!(stashes[1].message.contains("first stash"), "{stashes:?}");
assert!(stashes[0].time_ms > 0.0);
// Each stash lists the files it changed against the commit it was made on.
let head = repo.head().unwrap().1.unwrap();
assert!(stashes.iter().all(|s| s.base.as_deref() == Some(head.as_str())), "{stashes:?}");
let files = repo.commit_files(&stashes[1].id).unwrap();
assert_eq!(files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["s.txt"]);
repo.stash_apply(1, false, false).unwrap();
assert_eq!(fx.read("s.txt"), "change 1\n");
@@ -2074,12 +2079,37 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("other", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()], removed: false });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("dir/new.txt"), "mine\n");
}
}
/// Untracked on disk but tracked on the current branch and gone from the target
/// (as after `git rm --cached`): git refuses to *remove* the file, and the outcome
/// says so (#3980).
#[test]
fn checkout_reports_untracked_files_it_would_remove() {
let fx = Fixture::new();
fx.write("TEST.md", "hi\n");
fx.commit_all("base");
fx.git(&["checkout", "-q", "-b", "feature/x"]);
fx.git(&["rm", "-q", "TEST.md"]);
fx.commit_all("remove TEST.md on feature/x");
fx.git(&["checkout", "-q", "main"]);
fx.git(&["rm", "--cached", "TEST.md"]);
fx.write("TEST.md", "local dirty version\n");
let repo = fx.repo();
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
// The refusal leaves the repository untouched, so both modes see the same state.
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("feature/x", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["TEST.md".into()], removed: true });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("TEST.md"), "local dirty version\n");
}
}
#[test]
fn reword_keeps_local_changes_and_can_be_undone() {
let fx = Fixture::new();
+1
Переглянути файл
@@ -846,6 +846,7 @@ mod tests {
"wrapAtMargin": false,
"disabledPluginChecks": [],
"doubleClickOpensDiff": null,
"agentInstructions": "",
})
);
}
+41 -2
Переглянути файл
@@ -18,6 +18,10 @@
},
"navbar": {
"links": [
{
"label": "Marketplace",
"href": "/plugins"
},
{
"label": "GitHub",
"href": "https://github.com/l0ng-ai/openidea"
@@ -40,7 +44,14 @@
"groups": [
{
"group": "Get started",
"pages": ["en/index", "en/guide/install", "en/guide/quickstart", "en/guide/migrate", "en/roadmap"]
"pages": [
"en/index",
"en/introduction",
"en/guide/install",
"en/guide/quickstart",
"en/guide/migrate",
"en/roadmap"
]
},
{
"group": "Editing",
@@ -234,13 +245,37 @@
},
{
"language": "zh",
"navbar": {
"links": [
{
"label": "插件市场",
"href": "/zh/plugins"
},
{
"label": "GitHub",
"href": "https://github.com/l0ng-ai/openidea"
}
],
"primary": {
"type": "button",
"label": "下载",
"href": "https://github.com/l0ng-ai/openidea/releases/latest"
}
},
"tabs": [
{
"tab": "指南",
"groups": [
{
"group": "开始",
"pages": ["zh/index", "zh/guide/install", "zh/guide/quickstart", "zh/guide/migrate", "zh/roadmap"]
"pages": [
"zh/index",
"zh/introduction",
"zh/guide/install",
"zh/guide/quickstart",
"zh/guide/migrate",
"zh/roadmap"
]
},
{
"group": "编辑",
@@ -434,6 +469,10 @@
}
]
},
"redirects": [
{ "source": "/en/plugins", "destination": "/plugins" },
{ "source": "/zh/home", "destination": "/zh" }
],
"footer": {
"socials": {
"github": "https://github.com/l0ng-ai/openidea",
+8
Переглянути файл
@@ -129,6 +129,14 @@ OpenIDEA indexes Spring Web endpoints (`@RestController` / `@Controller` classes
Plugins can contribute endpoints of other frameworks; they get an **Open in HTTP Client** gutter icon.
### Feign navigation
In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint** gutter arrow or use the same action from the editor menu or Find Action. On a literal mapping path such as `@GetMapping("/users/{id}")`, modifier-click or Go to Declaration also opens matching controller methods. Multiple matches use the existing declaration chooser; method declarations keep their usual Find Usages behavior.
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
## Not supported
- JavaScript response handlers (`> {% ... %}`, `> handler.js`) and pre-request scripts. Handler lines are recognized and skipped.
+14 -13
Переглянути файл
@@ -83,25 +83,26 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i
## Tools
| Area | Tools |
| ------------- | --------------------------------------------------------------------------- |
| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
| Code | `get_symbol_info`, `find_references`, `rename_refactoring`, `reformat_file` |
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
| Git | `get_repositories`, `git_status`, `git_diff` |
| HTTP Client | `http_list_requests`, `http_run_request` |
| Area | Tools |
| ------------- | ------------------------------------------------------------------------------------------------- |
| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
| Code | `get_symbol_info`, `find_references`, `get_call_hierarchy`, `rename_refactoring`, `reformat_file` |
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
| Git | `get_repositories`, `git_status`, `git_diff` |
| HTTP Client | `http_list_requests`, `http_run_request` |
Notes on what they do:
- `read_file` also reads sources of dependencies and files inside jar and zip archives.
- The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false.
- The query tools (the searches, `find_references`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module.
- The query tools (the searches, `find_references`, `get_call_hierarchy`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module.
- `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows.
- `get_call_hierarchy` lists the callers of the function or method at a position, or with `direction` `outgoing` the functions it calls, one level per call. A position inside a function body means that function. To go one level deeper, call it again with an item's `filePath`, `startLine` and `startColumn`. Items in libraries show a URI as `filePath` and cannot be expanded.
- `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis.
- `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed.
- `rename_refactoring` renames through the language server, so references that a text search would miss are updated too. It can preview without writing.
+246 -45
Переглянути файл
@@ -1,58 +1,259 @@
---
title: "Introduction"
description: "OpenIDEA is an open-source IDE with the IntelliJ IDEA way of working, built as a native app with a Rust core."
title: "OpenIDEA"
sidebarTitle: "Home"
description: "The IDE you know, rebuilt in Rust. Open source, native, and fast on macOS, Windows and Linux."
mode: "custom"
---
OpenIDEA brings the IntelliJ IDEA way of working (its keymap, its tool windows, its search-everything habits) to a native desktop app with a Rust core. It runs on macOS, Windows and Linux and is licensed under Apache 2.0.
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
import { FeaturedPlugins } from "/snippets/marketplace.jsx";
If you have used IntelliJ IDEA, PyCharm or another JetBrains IDE, most of what you know carries over: pressing <kbd>Shift</kbd> twice opens Search Everywhere, `⌥↵` / `Alt+Enter` shows context actions, and the default keymap matches IDEA's. Coming from VS Code or Eclipse? Their keymaps are built in too.
export const Kbd = ({ children }) => <span className="oi-kbd">{children}</span>;
## Highlights
<div className="oi-home">
- **One IDE for many languages.** Editor and code insight for 60+ languages, and a one-click install of the language servers a project needs. See [Languages](/en/languages/index).
- **The tools you expect.** Debugger, Git, terminal, database client, HTTP client, test runner, coverage and profiler, each in its own tool window.
- **Search everything.** Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.
- **Refactorings and inspections.** Rename, extract, inline, change signature, safe delete, quick fixes and Inspect Code.
- **Remote development.** Work on a machine over SSH or in a dev container with the `openidea-server` backend.
- **AI agents.** Run coding agents in a tool window, and give them the IDE's own tools through the built-in MCP server.
- **Plugins.** Plugins add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. They run as sandboxed WebAssembly components; themes, icon themes and languages need no code. The plugin API is still a preview.
<section className="oi-hero">
<div className="oi-hero-glow" aria-hidden="true" />
<div className="oi-grid-bg" aria-hidden="true" />
<div className="oi-wrap oi-hero-inner">
<a className="oi-pill" href="https://github.com/l0ng-ai/openidea">
<span className="oi-pill-dot" />
Open source · Apache 2.0
<span className="oi-pill-arrow">→</span>
</a>
<h1 className="oi-title">
The IDE you know,
<br />
<span className="oi-title-accent">rebuilt in Rust.</span>
</h1>
<p className="oi-lead">
Keymap, tool windows and search-everything habits you already have, in a native desktop app that opens in
under a second and idles at a fraction of the memory.
</p>
<div className="oi-actions">
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
Download
</a>
<a className="oi-btn oi-btn-ghost" href="/en/introduction">
Read the docs
</a>
</div>
<p className="oi-platforms">macOS · Windows · Linux</p>
</div>
## Benchmark
<div className="oi-wrap">
<img
className="oi-shot"
src="/images/ide-dark.webp"
alt="OpenIDEA in the dark theme: a Java project with the project tree and the editor"
width="2880"
height="1800"
noZoom
/>
</div>
</section>
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, about 770 files) with warm caches, median of 5 runs:
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-eyebrow">Benchmark</div>
<h2 className="oi-h2">Native speed, measured from the outside.</h2>
<p className="oi-sub">
Opening freqtrade (Python, ~770 files) with warm caches, median of 5 runs, against IntelliJ IDEA 2026.2.3 with
default settings.
</p>
<div className="oi-stats">
<div className="oi-stat">
<div className="oi-stat-num">
0.9<small>s</small>
</div>
<div className="oi-stat-label">Window with the project</div>
<div className="oi-bar">
<span style={{ width: "29%" }} />
</div>
<div className="oi-stat-vs">3.1 s in IntelliJ IDEA</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
1.1<small>s</small>
</div>
<div className="oi-stat-label">Ready, CPU settled</div>
<div className="oi-bar">
<span style={{ width: "8%" }} />
</div>
<div className="oi-stat-vs">13.2 s in IntelliJ IDEA</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
169<small>MB</small>
</div>
<div className="oi-stat-label">Memory, all processes</div>
<div className="oi-bar">
<span style={{ width: "8%" }} />
</div>
<div className="oi-stat-vs">2011 MB in IntelliJ IDEA</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
0.3<small>s</small>
</div>
<div className="oi-stat-label">Quit</div>
<div className="oi-bar">
<span style={{ width: "5%" }} />
</div>
<div className="oi-stat-vs">5.9 s in IntelliJ IDEA</div>
</div>
</div>
<p className="oi-footnote">
Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" isn't the same work on both
sides. Reproduce it with <a href="https://github.com/l0ng-ai/openidea/blob/main/perf/compare">perf/compare</a>.
</p>
</div>
</section>
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------------- | ----------------- | ---------------------- |
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-eyebrow">Everything in one window</div>
<h2 className="oi-h2">A full IDE, not an editor with extensions.</h2>
<div className="oi-features">
<a className="oi-feature" href="/en/languages/index">
<Icon icon="code" size={18} />
<h3>60+ languages</h3>
<p>
Editor and code insight for every language, with one-click install of the language servers a project needs.
</p>
</a>
<a className="oi-feature" href="/en/guide/search">
<Icon icon="magnifying-glass" size={18} />
<h3>Search everything</h3>
<p>Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.</p>
</a>
<a className="oi-feature" href="/en/guide/refactoring">
<Icon icon="wand-magic-sparkles" size={18} />
<h3>Refactor with confidence</h3>
<p>Rename, extract, inline, change signature and safe delete, plus inspections with quick fixes.</p>
</a>
<a className="oi-feature" href="/en/guide/debugging">
<Icon icon="bug" size={18} />
<h3>Run, test, debug</h3>
<p>Debugger, test runner, coverage and profiler, each in its own tool window.</p>
</a>
<a className="oi-feature" href="/en/guide/vcs">
<Icon icon="code-branch" size={18} />
<h3>Git, terminal, database</h3>
<p>Commit, log and branches, a real terminal, a database client and an HTTP client built in.</p>
</a>
<a className="oi-feature" href="/en/guide/remote/ssh">
<Icon icon="server" size={18} />
<h3>Remote development</h3>
<p>
Work on a machine over SSH or in a dev container, backed by <code>openidea-server</code>.
</p>
</a>
<a className="oi-feature" href="/en/guide/agents">
<Icon icon="sparkles" size={18} />
<h3>AI agents</h3>
<p>Run coding agents in a tool window and give them the IDE's own tools through the built-in MCP server.</p>
</a>
<a className="oi-feature" href="/en/plugins/index">
<Icon icon="puzzle-piece" size={18} />
<h3>WebAssembly plugins</h3>
<p>Sandboxed plugins add actions, completion, tool windows and editors. Themes and languages need no code.</p>
</a>
</div>
</div>
</section>
Measured with a release build of OpenIDEA from `main` and IDEA with default settings and plugins, on Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" doesn't mean the same work on both sides. Both are measured from the outside, the same way: see [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) to run the comparison on your own machine and projects.
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-plug-head">
<div>
<div className="oi-eyebrow">Plugin Marketplace</div>
<h2 className="oi-h2">{pluginCatalog.plugins.length} plugins and counting.</h2>
<p className="oi-sub">
Spring, Laravel, Symfony, Kubernetes, AI commit messages, themes and more, from {pluginCatalog.publishers}{" "}
publishers. Every package is signed and runs in a WebAssembly sandbox.
</p>
</div>
<a className="oi-btn oi-btn-ghost" href="/plugins">
Browse the marketplace →
</a>
</div>
<FeaturedPlugins catalog={pluginCatalog} href="/plugins" />
</div>
</section>
## Where to go next
<section className="oi-section">
<div className="oi-wrap oi-split">
<div>
<div className="oi-eyebrow">Muscle memory included</div>
<h2 className="oi-h2">Your shortcuts already work.</h2>
<p className="oi-sub">
The default keymap matches IntelliJ IDEA, and VS Code and Eclipse keymaps are built in. Settings import brings
the rest.
</p>
<a className="oi-link" href="/en/guide/migrate">
Coming from another IDE →
</a>
</div>
<div className="oi-keys">
<div className="oi-key-row">
<span>
<Kbd>⇧</Kbd>
<Kbd>⇧</Kbd>
</span>
Search Everywhere
</div>
<div className="oi-key-row">
<span>
<Kbd>⌥</Kbd>
<Kbd>↵</Kbd>
</span>
Show context actions
</div>
<div className="oi-key-row">
<span>
<Kbd>⌘</Kbd>
<Kbd>⇧</Kbd>
<Kbd>A</Kbd>
</span>
Find Action
</div>
<div className="oi-key-row">
<span>
<Kbd>⇧</Kbd>
<Kbd>F6</Kbd>
</span>
Rename
</div>
<div className="oi-key-row">
<span>
<Kbd>⌃</Kbd>
<Kbd>⇧</Kbd>
<Kbd>D</Kbd>
</span>
Debug
</div>
</div>
</div>
</section>
<CardGroup cols={2}>
<Card title="Install" icon="download" href="/en/guide/install">
Download OpenIDEA for macOS, Windows or Linux.
</Card>
<Card title="Quickstart" icon="rocket" href="/en/guide/quickstart">
Open a project, find your way around, run and debug.
</Card>
<Card title="Coming from another IDE" icon="right-left" href="/en/guide/migrate">
Keymaps, settings import and concepts for IntelliJ IDEA, VS Code and Eclipse users.
</Card>
<Card title="Languages" icon="code" href="/en/languages/index">
What each language supports and what it needs installed.
</Card>
<Card title="Plugins" icon="puzzle-piece" href="/en/plugins/index">
Write themes, languages and WebAssembly plugins.
</Card>
<Card title="Contribute" icon="code-branch" href="/en/contribute/setup">
Build OpenIDEA from source and send a pull request.
</Card>
</CardGroup>
<section className="oi-cta">
<div className="oi-hero-glow oi-cta-glow" aria-hidden="true" />
<div className="oi-wrap oi-cta-inner">
<h2 className="oi-h2">Open a project in under a second.</h2>
<p className="oi-sub">Free and open source, for macOS, Windows and Linux.</p>
<div className="oi-actions">
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
Download
</a>
<a className="oi-btn oi-btn-ghost" href="/en/guide/quickstart">
Quickstart
</a>
</div>
<p className="oi-disclaimer">
OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
</p>
</div>
</section>
<Note>OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</Note>
</div>
+58
Переглянути файл
@@ -0,0 +1,58 @@
---
title: "Introduction"
description: "OpenIDEA is an open-source IDE with the IntelliJ IDEA way of working, built as a native app with a Rust core."
---
OpenIDEA brings the IntelliJ IDEA way of working (its keymap, its tool windows, its search-everything habits) to a native desktop app with a Rust core. It runs on macOS, Windows and Linux and is licensed under Apache 2.0.
If you have used IntelliJ IDEA, PyCharm or another JetBrains IDE, most of what you know carries over: pressing <kbd>Shift</kbd> twice opens Search Everywhere, `⌥↵` / `Alt+Enter` shows context actions, and the default keymap matches IDEA's. Coming from VS Code or Eclipse? Their keymaps are built in too.
## Highlights
- **One IDE for many languages.** Editor and code insight for 60+ languages, and a one-click install of the language servers a project needs. See [Languages](/en/languages/index).
- **The tools you expect.** Debugger, Git, terminal, database client, HTTP client, test runner, coverage and profiler, each in its own tool window.
- **Search everything.** Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.
- **Refactorings and inspections.** Rename, extract, inline, change signature, safe delete, quick fixes and Inspect Code.
- **Remote development.** Work on a machine over SSH or in a dev container with the `openidea-server` backend.
- **AI agents.** Run coding agents in a tool window, and give them the IDE's own tools through the built-in MCP server.
- **Plugins.** Plugins add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. They run as sandboxed WebAssembly components; themes, icon themes and languages need no code. The plugin API is still a preview.
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, about 770 files) with warm caches, median of 5 runs:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------------- | ----------------- | ---------------------- |
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
Measured with a release build of OpenIDEA from `main` and IDEA with default settings and plugins, on Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" doesn't mean the same work on both sides. Both are measured from the outside, the same way: see [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) to run the comparison on your own machine and projects.
## Where to go next
<CardGroup cols={2}>
<Card title="Install" icon="download" href="/en/guide/install">
Download OpenIDEA for macOS, Windows or Linux.
</Card>
<Card title="Quickstart" icon="rocket" href="/en/guide/quickstart">
Open a project, find your way around, run and debug.
</Card>
<Card title="Coming from another IDE" icon="right-left" href="/en/guide/migrate">
Keymaps, settings import and concepts for IntelliJ IDEA, VS Code and Eclipse users.
</Card>
<Card title="Languages" icon="code" href="/en/languages/index">
What each language supports and what it needs installed.
</Card>
<Card title="Plugins" icon="puzzle-piece" href="/en/plugins/index">
Write themes, languages and WebAssembly plugins.
</Card>
<Card title="Contribute" icon="code-branch" href="/en/contribute/setup">
Build OpenIDEA from source and send a pull request.
</Card>
</CardGroup>
<Note>OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</Note>
+1
Переглянути файл
@@ -172,6 +172,7 @@ The table lists every built-in language definition. Server and debugger names in
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
File diff suppressed because it is too large. Load diff
Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 193 KiB

+10
Переглянути файл
@@ -0,0 +1,10 @@
---
title: "Plugin Marketplace"
description: "Browse OpenIDEA plugins: languages, frameworks, linters, themes, AI and tools from the community and the OpenIDEA team."
mode: "custom"
---
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
import { Marketplace } from "/snippets/marketplace.jsx";
<Marketplace catalog={pluginCatalog} lang="en" />
+411
Переглянути файл
@@ -0,0 +1,411 @@
// Pages import the catalog (`/snippets/plugin-catalog.jsx`) and pass it in. Mintlify takes each imported
// export on its own, so every component here is self-contained: no imports, no shared top-level helpers.
export const Marketplace = ({ catalog: pluginCatalog, lang = "en" }) => {
const TEXT = {
en: {
eyebrow: "Plugin Marketplace",
title: "Make OpenIDEA yours.",
lead: "Languages, frameworks, linters, themes and tools, signed by their publishers and installed in one click from",
path: "Settings › Plugins › Marketplace",
leadEnd: ".",
plugins: "plugins",
publishers: "publishers",
downloads: "downloads",
downloadsLabel: "Downloads",
listSep: ", ",
search: "Search plugins",
sort: "Sort",
popular: "Popular",
az: "A–Z",
category: "Category",
official: "Official",
empty: (q) => `No plugins match “${q}”.`,
buildEyebrow: "Build a plugin",
buildTitle: "Ship your plugin to every OpenIDEA user.",
buildLead:
"Plugins are sandboxed WebAssembly components with a typed API. Themes, icon themes and languages need no code at all. Scaffold one in a minute, then list it through the community registry.",
quickstart: "Plugin quickstart",
publish: "Publish to the marketplace",
term1: "# attach the .oiplugin to a release, then open a",
term2: "# pull request in l0ng-ai/openidea-plugins",
note: (d) =>
`Snapshot of the marketplace index from ${d}. The IDE always shows the current list. Community plugins are built and signed by their authors.`,
close: "Close",
version: "Version",
categoriesLabel: "Categories",
pluginId: "Plugin id",
install: (name) => (
<>
<b>Install</b> In OpenIDEA, open <b>Settings › Plugins › Marketplace</b>, search for “{name}” and click{" "}
<b>Install</b>.
</>
),
source: "Source and docs",
categories: {
all: "All",
frameworks: "Frameworks",
languages: "Languages",
tools: "Tools",
linters: "Linters",
vcs: "Version control",
ai: "AI",
themes: "Themes",
"icon-themes": "Icon themes",
other: "Other",
},
},
zh: {
eyebrow: "插件市场",
title: "让 OpenIDEA 成为你的 IDE。",
lead: "语言、框架、代码检查、主题和工具,均由发布者签名,在",
path: "设置 › 插件 › 插件市场",
leadEnd: "中一键安装。",
plugins: "个插件",
publishers: "位发布者",
downloads: "次下载",
downloadsLabel: "下载量",
listSep: "、",
search: "搜索插件",
sort: "排序",
popular: "最热门",
az: "按名称",
category: "分类",
official: "官方",
empty: (q) => `没有与“${q}”匹配的插件。`,
buildEyebrow: "开发插件",
buildTitle: "把你的插件交到每一位 OpenIDEA 用户手中。",
buildLead:
"插件是运行在沙箱中的 WebAssembly 组件,API 有完整类型。主题、图标主题和语言完全不用写代码。一分钟搭好脚手架,再通过社区登记仓库上架。",
quickstart: "插件快速开始",
publish: "发布到插件市场",
term1: "# 把 .oiplugin 附加到 release,然后向",
term2: "# l0ng-ai/openidea-plugins 提交 pull request",
note: (d) => `插件市场索引快照,生成于 ${d}。IDE 中显示的始终是最新列表。社区插件由作者自行构建和签名。`,
close: "关闭",
version: "版本",
categoriesLabel: "分类",
pluginId: "插件 id",
install: (name) => (
<>
<b>安装</b> 在 OpenIDEA 中打开 <b>设置 › 插件 › 插件市场</b>,搜索“
{name}”,点击 <b>安装</b>。
</>
),
source: "源码与文档",
categories: {
all: "全部",
frameworks: "框架",
languages: "语言",
tools: "工具",
linters: "代码检查",
vcs: "版本控制",
ai: "AI",
themes: "主题",
"icon-themes": "图标主题",
other: "其他",
},
},
};
const CATEGORY_IDS = [
"all",
"frameworks",
"languages",
"tools",
"linters",
"vcs",
"ai",
"themes",
"icon-themes",
"other",
];
const formatCount = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : `${n}`);
// Called as a function: snippet components cannot use each other as JSX tags.
const pluginIcon = (plugin, size) =>
plugin.icon ? (
<span className="oi-mk-icon" style={{ width: size, height: size }}>
<img className="oi-mk-icon-light" src={plugin.icon.light} alt="" />
<img className="oi-mk-icon-dark" src={plugin.icon.dark || plugin.icon.light} alt="" />
</span>
) : (
<span className="oi-mk-icon oi-mk-icon-fallback" style={{ width: size, height: size }}>
{plugin.name
.replace(/^[^A-Za-z0-9]+/, "")
.slice(0, 1)
.toUpperCase()}
</span>
);
const t = TEXT[lang] || TEXT.en;
const categoryLabel = (id) => t.categories[id] || id;
const all = pluginCatalog.plugins;
const [query, setQuery] = useState("");
const [category, setCategory] = useState("all");
const [sort, setSort] = useState("popular");
const [open, setOpen] = useState(null);
const counts = {};
for (const p of all) for (const c of p.categories) counts[c] = (counts[c] || 0) + 1;
const totalDownloads = all.reduce((s, p) => s + p.downloads, 0);
const q = query.trim().toLowerCase();
const shown = all
.filter((p) => category === "all" || p.categories.includes(category))
.filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
p.description.toLowerCase().includes(q) ||
p.publisher.toLowerCase().includes(q) ||
p.id.toLowerCase().includes(q),
)
.slice()
.sort((a, b) => (sort === "name" ? a.name.localeCompare(b.name) : b.downloads - a.downloads));
const current = open && all.find((p) => p.id === open);
useEffect(() => {
if (!current) return;
const onKey = (e) => e.key === "Escape" && setOpen(null);
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [current]);
return (
<div className="oi-home oi-mk">
<section className="oi-mk-hero">
<div className="oi-hero-glow" aria-hidden="true" />
<div className="oi-grid-bg" aria-hidden="true" />
<div className="oi-wrap">
<div className="oi-eyebrow">{t.eyebrow}</div>
<h1 className="oi-mk-title">{t.title}</h1>
<p className="oi-sub">
{t.lead} <b>{t.path}</b>
{t.leadEnd}
</p>
<div className="oi-mk-metrics">
<div>
<strong>{all.length}</strong>
<span>{t.plugins}</span>
</div>
<div>
<strong>{pluginCatalog.publishers}</strong>
<span>{t.publishers}</span>
</div>
<div>
<strong>{formatCount(totalDownloads)}</strong>
<span>{t.downloads}</span>
</div>
</div>
</div>
</section>
<div className="oi-wrap">
<div className="oi-mk-toolbar">
<label className="oi-mk-search">
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
<circle cx="7" cy="7" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5" />
<path d="M10.5 10.5 14 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
<input
type="search"
placeholder={t.search}
aria-label={t.search}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</label>
<div className="oi-mk-sort" role="group" aria-label={t.sort}>
<button type="button" className={sort === "popular" ? "is-on" : ""} onClick={() => setSort("popular")}>
{t.popular}
</button>
<button type="button" className={sort === "name" ? "is-on" : ""} onClick={() => setSort("name")}>
{t.az}
</button>
</div>
</div>
<div className="oi-mk-chips" role="group" aria-label={t.category}>
{CATEGORY_IDS.filter((id) => id === "all" || counts[id]).map((id) => (
<button type="button" key={id} className={category === id ? "is-on" : ""} onClick={() => setCategory(id)}>
{categoryLabel(id)}
<em>{id === "all" ? all.length : counts[id]}</em>
</button>
))}
</div>
<div className="oi-mk-grid">
{shown.map((p) => (
<button type="button" key={p.id} className="oi-mk-card" onClick={() => setOpen(p.id)}>
<div className="oi-mk-card-head">
{pluginIcon(p, 44)}
<div className="oi-mk-card-title">
<h3>{p.name}</h3>
<span>
{p.publisher}
{p.official && <b className="oi-mk-badge">{t.official}</b>}
</span>
</div>
</div>
<p>{p.description}</p>
<div className="oi-mk-card-foot">
<span className="oi-mk-tag">{categoryLabel(p.categories[0])}</span>
{p.downloads > 0 && (
<span className="oi-mk-dl">
<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
<path
d="M8 2v8m0 0 3-3m-3 3L5 7M3 13h10"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
{formatCount(p.downloads)}
</span>
)}
<span className="oi-mk-ver">v{p.version}</span>
</div>
</button>
))}
</div>
{shown.length === 0 && <p className="oi-mk-empty">{t.empty(query)}</p>}
<section className="oi-mk-build">
<div>
<div className="oi-eyebrow">{t.buildEyebrow}</div>
<h2 className="oi-h2">{t.buildTitle}</h2>
<p className="oi-sub">{t.buildLead}</p>
<div className="oi-mk-build-actions">
<a className="oi-btn oi-btn-primary" href={`/${lang}/plugins/quickstart`}>
{t.quickstart}
</a>
<a className="oi-btn oi-btn-ghost" href={`/${lang}/plugins/publishing/marketplace`}>
{t.publish}
</a>
</div>
</div>
<div className="oi-mk-term" aria-hidden="true">
<div className="oi-mk-term-bar">
<span />
<span />
<span />
</div>
<div className="oi-mk-term-body">
<div>
<b>$</b> openidea-plugin new hello --id acme.hello
</div>
<div>
<b>$</b> cd hello && cargo test
</div>
<div>
<b>$</b> openidea-plugin build
</div>
<div>
<b>$</b> openidea-plugin pack . --key acme.key --publisher acme
</div>
<div className="dim">{t.term1}</div>
<div className="dim">{t.term2}</div>
</div>
</div>
</section>
<p className="oi-mk-note">{t.note(pluginCatalog.generatedAt)}</p>
</div>
{current && (
<div className="oi-mk-overlay" onClick={() => setOpen(null)}>
<div
className="oi-mk-dialog"
role="dialog"
aria-modal="true"
aria-label={current.name}
onClick={(e) => e.stopPropagation()}
>
<button type="button" className="oi-mk-close" aria-label={t.close} onClick={() => setOpen(null)}>
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</button>
<div className="oi-mk-card-head">
{pluginIcon(current, 64)}
<div className="oi-mk-card-title">
<h3>{current.name}</h3>
<span>
{current.publisher}
{current.official && <b className="oi-mk-badge">{t.official}</b>}
</span>
</div>
</div>
<p className="oi-mk-dialog-desc">{current.description}</p>
<dl className="oi-mk-facts">
<div>
<dt>{t.version}</dt>
<dd>{current.version}</dd>
</div>
<div>
<dt>{t.downloadsLabel}</dt>
<dd>{current.downloads ? current.downloads.toLocaleString(lang === "zh" ? "zh-CN" : "en-US") : "—"}</dd>
</div>
<div>
<dt>{t.categoriesLabel}</dt>
<dd>{current.categories.map(categoryLabel).join(t.listSep)}</dd>
</div>
<div>
<dt>{t.pluginId}</dt>
<dd>
<code>{current.id}</code>
</dd>
</div>
</dl>
<div className="oi-mk-install">{t.install(current.name)}</div>
{current.homepage && (
<a className="oi-btn oi-btn-ghost oi-mk-home" href={current.homepage} target="_blank" rel="noreferrer">
{t.source} ↗
</a>
)}
</div>
</div>
)}
</div>
);
};
export const FeaturedPlugins = ({ catalog: pluginCatalog, href }) => {
const pluginIcon = (plugin, size) =>
plugin.icon ? (
<span className="oi-mk-icon" style={{ width: size, height: size }}>
<img className="oi-mk-icon-light" src={plugin.icon.light} alt="" />
<img className="oi-mk-icon-dark" src={plugin.icon.dark || plugin.icon.light} alt="" />
</span>
) : (
<span className="oi-mk-icon oi-mk-icon-fallback" style={{ width: size, height: size }}>
{plugin.name
.replace(/^[^A-Za-z0-9]+/, "")
.slice(0, 1)
.toUpperCase()}
</span>
);
return (
<div className="oi-plug-grid">
{pluginCatalog.plugins
.filter((p) => p.icon)
.slice(0, 12)
.map((p) => (
<a key={p.id} className="oi-plug" href={href}>
{pluginIcon(p, 36)}
<span className="oi-plug-text">
<b>{p.name}</b>
<em>{p.publisher}</em>
</span>
</a>
))}
</div>
);
};
+2
Переглянути файл
@@ -0,0 +1,2 @@
// Generated by scripts/gen-plugin-catalog.ts. Do not edit.
export const pluginCatalog = {"generatedAt":"2026-11-17","publishers":43,"plugins":[{"id":"aritti.ignore","name":".ignore","version":"0.3.0","description":"Support for ignore files (.gitignore, .dockerignore, .npmignore, .hgignore and 30 more). Reports duplicate, redundant, relative and malformed entries and invalid `syntax:` values, with quick fixes. Completes `syntax:` in .hgignore, opens the file an entry names on Ctrl-click and highlights ignore files the IDE does not recognise. A tool window adds github/gitignore and user templates. The status bar shows Ignored while you edit an ignored file, a notification warns about a Git project without a .gitignore, and any file gets an Add to .gitignore quick fix. Templates from github/gitignore (CC0-1.0).","publisher":"aritti","official":false,"categories":["linters","vcs"],"downloads":1430,"homepage":"https://github.com/arnaud-ritti/openidea-plugins/tree/main/plugins/ignore","icon":{"light":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0Ij48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSIxNCIgZmlsbD0iI0ZGRkZGRiIgc3Ryb2tlPSIjRDBEM0RCIiBzdHJva2Utd2lkdGg9IjIiLz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4LjAwIDguMDApIHNjYWxlKDAuMTQ4NCkiPjxwYXRoIGZpbGw9IiNkZTRjMzYiIGQ9Ik0yNTEuMTcyIDExNi41OTRMMTM5LjQgNC44MjhjLTYuNDMzLTYuNDM3LTE2Ljg3My02LjQzNy0yMy4zMTQgMGwtMjMuMjEgMjMuMjFsMjkuNDQzIDI5LjQ0M2M2Ljg0Mi0yLjMxMiAxNC42ODgtLjc2MSAyMC4xNDIgNC42OTNjNS40OCA1LjQ4OSA3LjAyIDEzLjQwMiA0LjY1MiAyMC4yNjZsMjguMzc1IDI4LjM3NmM2Ljg2NS0yLjM2NSAxNC43ODYtLjgzNSAyMC4yNjkgNC42NTdjNy42NjMgNy42NiA3LjY2MyAyMC4wNzUgMCAyNy43NGMtNy42NjUgNy42NjYtMjAuMDggNy42NjYtMjcuNzQ5IDBjLTUuNzY0LTUuNzctNy4xODgtMTQuMjM1LTQuMjctMjEuMzM2bC0yNi40NjItMjYuNDYybC0uMDAzIDY5LjYzN2ExOS44IDE5LjggMCAwIDEgNS4xODggMy43MWM3LjY2MyA3LjY2IDcuNjYzIDIwLjA3NiAwIDI3Ljc0N2MtNy42NjUgNy42NjItMjAuMDg2IDcuNjYyLTI3Ljc0IDBjLTcuNjYzLTcuNjcxLTcuNjYzLTIwLjA4NiAwLTI3Ljc0NmExOS43IDE5LjcgMCAwIDEgNi40MjEtNC4yODFWOTQuMTk2YTE5LjQgMTkuNCAwIDAgMS02LjQyMS00LjI4MWMtNS44MDYtNS43OTgtNy4yMDItMTQuMzE3LTQuMjI3LTIxLjQ0Nkw4MS40NyAzOS40NDJMNC44MyAxMTYuMDc3Yy02LjQ0IDYuNDQzLTYuNDQgMTYuODg0IDAgMjMuMzIybDExMS43NzQgMTExLjc2OGM2LjQzNSA2LjQzOCAxNi44NzMgNi40MzggMjMuMzE2IDBsMTExLjI1MS0xMTEuMjQ5YzYuNDM4LTYuNDQgNi40MzgtMTYuODg3IDAtMjMuMzI0Ii8+PC9nPjxjaXJjbGUgY3g9IjQ2IiBjeT0iNDYiIHI9IjEzIiBmaWxsPSIjMUYyMDI0IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIvPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM4LjggMzguOCkgc2NhbGUoLjYpIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSI4IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBmaWxsPSJub25lIi8+PHBhdGggZD0iTTYuMyA2LjNsMTEuNCAxMS40IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBmaWxsPSJub25lIi8+PC9nPjwvc3ZnPg=="}},{"id":"aritti.dotenv","name":".env files","version":"0.3.0","description":".env file support: highlighting, inspections with quick fixes and ${VARIABLE} completion. Environment variables in code (getenv, os.environ, process.env, ENV[…], env::var, PHPUnit <env>, …) get completion and go to declaration in .env files, Dockerfiles and docker-compose files. Go to declaration on a key in a .env file lists its usages, and a confirmed source-only action can update current-file interpolation tokens after a key edit.","publisher":"aritti","official":false,"categories":["languages","linters"],"downloads":1267,"homepage":"https://github.com/arnaud-ritti/openidea-plugins","icon":{"light":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0Ij48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSIxNCIgZmlsbD0iI0ZGRkZGRiIgc3Ryb2tlPSIjRDBEM0RCIiBzdHJva2Utd2lkdGg9IjIiLz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSg5LjAwIDkuMDApIHNjYWxlKDEuOTE2NykiPjxwYXRoIGZpbGw9IiMwOTA5MGIiIGQ9Ik0wIDBoMjR2MjRIMHoiLz48cGF0aCBmaWxsPSIjZWNkNTNmIiBkPSJNMjQgMHYyNEgwVjB6TTEwLjkzMyAxNS44OUg2Ljg0djUuNTJoNC4xOTh2LS45M0g3Ljk1NXYtMS41MDNoMi43N3YtLjkzaC0yLjc3di0xLjIyNGgyLjk3OHptMi4xNDYgMGgtMS4wODR2NS41MmgxLjAzNXYtMy42bDIuMjI2IDMuNmgxLjExOHYtNS41MmgtMS4wMzZ2My42ODZ6bTUuMTE3IDBoLTEuMjA4bDEuOTczIDUuNTJoMS4xOWwxLjk3Ni01LjUyaC0xLjE4MmwtMS4zNTIgNC4wODV6TTUuNCAxOS42OEgzLjcydjEuNjhINS40eiIvPjwvZz48L3N2Zz4="}},{"id":"aritti.spring-boot","name":"Spring Boot Tools","version":"0.3.0","description":"Completion and checks for Spring Boot configuration files. Completes keys and values in application*.properties and application*.yml from a bundled Spring Boot fallback snapshot, explicitly selected version-qualified dependency JAR metadata, the project's configuration metadata files and its @ConfigurationProperties classes. Warns about deprecated keys (with a quick fix) and unknown keys in known groups, and checks cron expressions in @Scheduled(cron) and *.cron keys.","publisher":"aritti","official":false,"categories":["frameworks"],"downloads":1198,"homepage":"https://github.com/arnaud-ritti/openidea-plugins","icon":{Line truncated
+8
Переглянути файл
@@ -129,6 +129,14 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
插件可以提供其他框架的端点,这些端点旁会有 **在 HTTP 客户端中打开** 边栏图标。
### Feign 导航
在 Java 或 Kotlin 的 `@FeignClient` 接口中,点击装订线上的 **跳转到 Feign 端点** 箭头,或从编辑器菜单、查找操作中执行同名操作。在 `@GetMapping("/users/{id}")` 等字面量路径上,也可以使用修饰键点击或跳转到声明。有多个候选时会显示已有的声明选择器;方法声明仍保留原来的查找用法行为。
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
## 暂不支持
- JavaScript 响应处理脚本(`> {% ... %}`、`> handler.js`)和请求前脚本。处理脚本行能被识别,但会跳过。
+14 -13
Переглянути файл
@@ -82,25 +82,26 @@ stdio 配置大致如下(路径以你机器上的为准):
## 工具
| 类别 | 工具 |
| ----------- | --------------------------------------------------------------------------- |
| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
| 代码 | `get_symbol_info`、`find_references`、`rename_refactoring`、`reformat_file` |
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
| Git | `get_repositories`、`git_status`、`git_diff` |
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
| 类别 | 工具 |
| ----------- | ------------------------------------------------------------------------------------------------- |
| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
| 代码 | `get_symbol_info`、`find_references`、`get_call_hierarchy`、`rename_refactoring`、`reformat_file` |
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
| Git | `get_repositories`、`git_status`、`git_diff` |
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
几点说明:
- `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。
- `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。
- `get_call_hierarchy` 列出某个位置上函数或方法的调用方,`direction` 为 `outgoing` 时列出它调用的函数,每次一层。位置在函数体内时,指的就是这个函数。要再深入一层,用某一项的 `filePath`、`startLine` 和 `startColumn` 再调用一次。库中的项以 URI 作为 `filePath`,不能继续展开。
- 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。
- 查询类工具(各搜索工具、`find_references`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。
- 查询类工具(各搜索工具、`find_references`、`get_call_hierarchy`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。
- `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。
- `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。
- `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。
+239 -45
Переглянути файл
@@ -1,58 +1,252 @@
---
title: "介绍"
description: "OpenIDEA 是一款开源 IDE,沿用 IntelliJ IDEA 的使用方式,以 Rust 为核心构建成原生应用。"
title: "OpenIDEA"
sidebarTitle: "首页"
description: "熟悉的 IDE,用 Rust 重新打造。开源、原生,在 macOS、Windows 和 Linux 上都很快。"
mode: "custom"
---
OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处搜索的习惯)带到一个以 Rust 为核心的原生桌面应用里。支持 macOS、Windows 和 Linux,采用 Apache 2.0 许可证。
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
import { FeaturedPlugins } from "/snippets/marketplace.jsx";
用过 IntelliJ IDEA、PyCharm 或其他 JetBrains IDE 的话,大部分经验可以直接沿用:连按两下 <kbd>Shift</kbd> 打开随处搜索,`⌥↵` / `Alt+Enter` 显示上下文操作,默认快捷键方案与 IDEA 一致。从 VS Code 或 Eclipse 过来,也有对应的内置快捷键方案。
export const Kbd = ({ children }) => <span className="oi-kbd">{children}</span>;
## 亮点
<div className="oi-home">
- **一个 IDE 覆盖多种语言。** 为 60 多种语言提供编辑和代码洞察,项目需要的语言服务器可一键安装。参见[语言](/zh/languages/index)。
- **常用工具齐全。** 调试器、Git、终端、数据库客户端、HTTP 客户端、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。
- **随处搜索。** 在已建立索引的项目中使用随处搜索、查找操作、转到类 / 文件 / 符号以及在文件中查找。
- **重构与检查。** 重命名、提取、内联、更改签名、安全删除、快速修复和代码检查。
- **远程开发。** 通过 SSH 或在开发容器中工作,后端是 `openidea-server`。
- **AI 智能体。** 在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具提供给它们。
- **插件。** 插件可以添加操作、补全、快速修复、工具窗口、自定义编辑器、主题、文件图标和语言。插件以沙箱化的 WebAssembly 组件运行;主题、图标主题和语言无需编写代码。插件 API 目前仍是预览版。
<section className="oi-hero">
<div className="oi-hero-glow" aria-hidden="true" />
<div className="oi-grid-bg" aria-hidden="true" />
<div className="oi-wrap oi-hero-inner">
<a className="oi-pill" href="https://github.com/l0ng-ai/openidea">
<span className="oi-pill-dot" />
开源 · Apache 2.0
<span className="oi-pill-arrow">→</span>
</a>
<h1 className="oi-title">
熟悉的 IDE,
<br />
<span className="oi-title-accent">用 Rust 重新打造。</span>
</h1>
<p className="oi-lead">
你熟悉的快捷键、工具窗口和随处搜索,装进一个原生桌面应用:不到一秒打开项目,内存只占一小部分。
</p>
<div className="oi-actions">
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
下载
</a>
<a className="oi-btn oi-btn-ghost" href="/zh/introduction">
阅读文档
</a>
</div>
<p className="oi-platforms">macOS · Windows · Linux</p>
</div>
## 性能对比
<div className="oi-wrap">
<img
className="oi-shot"
src="/images/ide-dark.webp"
alt="深色主题下的 OpenIDEA:一个 Java 项目,包含项目树和编辑器"
width="2880"
height="1800"
noZoom
/>
</div>
</section>
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),取 5 次运行的中位数:
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-eyebrow">性能对比</div>
<h2 className="oi-h2">原生的速度,从外部实测。</h2>
<p className="oi-sub">
打开 freqtrade(Python,约 770 个文件),缓存已预热,取 5 次运行的中位数,对比默认设置的 IntelliJ IDEA 2026.2.3。
</p>
<div className="oi-stats">
<div className="oi-stat">
<div className="oi-stat-num">
0.9<small>s</small>
</div>
<div className="oi-stat-label">项目窗口出现</div>
<div className="oi-bar">
<span style={{ width: "29%" }} />
</div>
<div className="oi-stat-vs">IntelliJ IDEA:3.1 s</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
1.1<small>s</small>
</div>
<div className="oi-stat-label">就绪(CPU 平稳)</div>
<div className="oi-bar">
<span style={{ width: "8%" }} />
</div>
<div className="oi-stat-vs">IntelliJ IDEA:13.2 s</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
169<small>MB</small>
</div>
<div className="oi-stat-label">内存(全部进程)</div>
<div className="oi-bar">
<span style={{ width: "8%" }} />
</div>
<div className="oi-stat-vs">IntelliJ IDEA:2011 MB</div>
</div>
<div className="oi-stat">
<div className="oi-stat-num">
0.3<small>s</small>
</div>
<div className="oi-stat-label">退出</div>
<div className="oi-bar">
<span style={{ width: "5%" }} />
</div>
<div className="oi-stat-vs">IntelliJ IDEA:5.9 s</div>
</div>
</div>
<p className="oi-footnote">
Windows 11,32 核 AMD,62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不是同样的工作量。可以用{" "}
<a href="https://github.com/l0ng-ai/openidea/blob/main/perf/compare">perf/compare</a> 在自己的机器上复现。
</p>
</div>
</section>
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------- | -------------- | ---------------------- |
| 显示项目窗口 | **0.9 s** | 3.1 s |
| 就绪(CPU 平稳) | **1.1 s** | 13.2 s |
| 内存(USS,所有进程) | **169 MB** | 2011 MB |
| 就绪前消耗的 CPU 时间 | **2.4 s** | 47.9 s |
| 空闲 CPU | 单核的 **4 %** | 单核的 7 % |
| 退出 | **0.3 s** | 5.9 s |
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-eyebrow">一个窗口,应有尽有</div>
<h2 className="oi-h2">完整的 IDE,而不是装满扩展的编辑器。</h2>
<div className="oi-features">
<a className="oi-feature" href="/zh/languages/index">
<Icon icon="code" size={18} />
<h3>60 多种语言</h3>
<p>每种语言都有编辑和代码洞察,项目需要的语言服务器一键安装。</p>
</a>
<a className="oi-feature" href="/zh/guide/search">
<Icon icon="magnifying-glass" size={18} />
<h3>随处搜索</h3>
<p>随处搜索、查找操作、转到类 / 文件 / 符号,以及在整个已索引项目中查找。</p>
</a>
<a className="oi-feature" href="/zh/guide/refactoring">
<Icon icon="wand-magic-sparkles" size={18} />
<h3>放心重构</h3>
<p>重命名、提取、内联、更改签名和安全删除,还有带快速修复的代码检查。</p>
</a>
<a className="oi-feature" href="/zh/guide/debugging">
<Icon icon="bug" size={18} />
<h3>运行、测试、调试</h3>
<p>调试器、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。</p>
</a>
<a className="oi-feature" href="/zh/guide/vcs">
<Icon icon="code-branch" size={18} />
<h3>Git、终端、数据库</h3>
<p>提交、日志和分支,真正的终端,内置数据库客户端和 HTTP 客户端。</p>
</a>
<a className="oi-feature" href="/zh/guide/remote/ssh">
<Icon icon="server" size={18} />
<h3>远程开发</h3>
<p>
通过 SSH 连到远程机器,或在开发容器中工作,后端是 <code>openidea-server</code>。
</p>
</a>
<a className="oi-feature" href="/zh/guide/agents">
<Icon icon="sparkles" size={18} />
<h3>AI 智能体</h3>
<p>在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具交给它们。</p>
</a>
<a className="oi-feature" href="/zh/plugins/index">
<Icon icon="puzzle-piece" size={18} />
<h3>WebAssembly 插件</h3>
<p>沙箱化的插件可以添加操作、补全、工具窗口和编辑器。主题和语言无需写代码。</p>
</a>
</div>
</div>
</section>
测试使用 `main` 分支的 OpenIDEA release 构建,以及默认设置和插件的 IDEA,环境为 Windows 11、32 核 AMD、62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不代表完成了同样多的工作。两者都以相同方式从外部测量:可以用 [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) 在自己的机器和项目上复现。
<section className="oi-section">
<div className="oi-wrap">
<div className="oi-plug-head">
<div>
<div className="oi-eyebrow">插件市场</div>
<h2 className="oi-h2">{pluginCatalog.plugins.length} 个插件,还在增加。</h2>
<p className="oi-sub">
Spring、Laravel、Symfony、Kubernetes、AI 提交信息、主题等等,来自 {pluginCatalog.publishers}{" "}
位发布者。每个插件包都经过签名,运行在 WebAssembly 沙箱中。
</p>
</div>
<a className="oi-btn oi-btn-ghost" href="/plugins">
浏览插件市场 →
</a>
</div>
<FeaturedPlugins catalog={pluginCatalog} href="/zh/plugins" />
</div>
</section>
## 下一步
<section className="oi-section">
<div className="oi-wrap oi-split">
<div>
<div className="oi-eyebrow">肌肉记忆照样好用</div>
<h2 className="oi-h2">你的快捷键,直接就能用。</h2>
<p className="oi-sub">
默认快捷键方案与 IntelliJ IDEA 一致,也内置了 VS Code 和 Eclipse 方案。其余设置可以直接导入。
</p>
<a className="oi-link" href="/zh/guide/migrate">
从其他 IDE 迁移 →
</a>
</div>
<div className="oi-keys">
<div className="oi-key-row">
<span>
<Kbd>⇧</Kbd>
<Kbd>⇧</Kbd>
</span>
随处搜索
</div>
<div className="oi-key-row">
<span>
<Kbd>⌥</Kbd>
<Kbd>↵</Kbd>
</span>
显示上下文操作
</div>
<div className="oi-key-row">
<span>
<Kbd>⌘</Kbd>
<Kbd>⇧</Kbd>
<Kbd>A</Kbd>
</span>
查找操作
</div>
<div className="oi-key-row">
<span>
<Kbd>⇧</Kbd>
<Kbd>F6</Kbd>
</span>
重命名
</div>
<div className="oi-key-row">
<span>
<Kbd>⌃</Kbd>
<Kbd>⇧</Kbd>
<Kbd>D</Kbd>
</span>
调试
</div>
</div>
</div>
</section>
<CardGroup cols={2}>
<Card title="安装" icon="download" href="/zh/guide/install">
下载 macOS、Windows 或 Linux 版 OpenIDEA。
</Card>
<Card title="快速上手" icon="rocket" href="/zh/guide/quickstart">
打开项目、熟悉界面、运行和调试。
</Card>
<Card title="从其他 IDE 迁移" icon="right-left" href="/zh/guide/migrate">
面向 IntelliJ IDEA、VS Code 和 Eclipse 用户的快捷键、设置导入和概念对照。
</Card>
<Card title="语言" icon="code" href="/zh/languages/index">
各语言支持哪些功能、需要安装什么。
</Card>
<Card title="插件" icon="puzzle-piece" href="/zh/plugins/index">
编写主题、语言和 WebAssembly 插件。
</Card>
<Card title="参与贡献" icon="code-branch" href="/zh/contribute/setup">
从源码构建 OpenIDEA 并提交 Pull Request。
</Card>
</CardGroup>
<section className="oi-cta">
<div className="oi-hero-glow oi-cta-glow" aria-hidden="true" />
<div className="oi-wrap oi-cta-inner">
<h2 className="oi-h2">不到一秒,打开项目。</h2>
<p className="oi-sub">免费开源,支持 macOS、Windows 和 Linux。</p>
<div className="oi-actions">
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
下载
</a>
<a className="oi-btn oi-btn-ghost" href="/zh/guide/quickstart">
快速开始
</a>
</div>
<p className="oi-disclaimer">OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</p>
</div>
</section>
<Note>OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</Note>
</div>
+58
Переглянути файл
@@ -0,0 +1,58 @@
---
title: "介绍"
description: "OpenIDEA 是一款开源 IDE,沿用 IntelliJ IDEA 的使用方式,以 Rust 为核心构建成原生应用。"
---
OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处搜索的习惯)带到一个以 Rust 为核心的原生桌面应用里。支持 macOS、Windows 和 Linux,采用 Apache 2.0 许可证。
用过 IntelliJ IDEA、PyCharm 或其他 JetBrains IDE 的话,大部分经验可以直接沿用:连按两下 <kbd>Shift</kbd> 打开随处搜索,`⌥↵` / `Alt+Enter` 显示上下文操作,默认快捷键方案与 IDEA 一致。从 VS Code 或 Eclipse 过来,也有对应的内置快捷键方案。
## 亮点
- **一个 IDE 覆盖多种语言。** 为 60 多种语言提供编辑和代码洞察,项目需要的语言服务器可一键安装。参见[语言](/zh/languages/index)。
- **常用工具齐全。** 调试器、Git、终端、数据库客户端、HTTP 客户端、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。
- **随处搜索。** 在已建立索引的项目中使用随处搜索、查找操作、转到类 / 文件 / 符号以及在文件中查找。
- **重构与检查。** 重命名、提取、内联、更改签名、安全删除、快速修复和代码检查。
- **远程开发。** 通过 SSH 或在开发容器中工作,后端是 `openidea-server`。
- **AI 智能体。** 在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具提供给它们。
- **插件。** 插件可以添加操作、补全、快速修复、工具窗口、自定义编辑器、主题、文件图标和语言。插件以沙箱化的 WebAssembly 组件运行;主题、图标主题和语言无需编写代码。插件 API 目前仍是预览版。
## 性能对比
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),取 5 次运行的中位数:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------- | -------------- | ---------------------- |
| 显示项目窗口 | **0.9 s** | 3.1 s |
| 就绪(CPU 平稳) | **1.1 s** | 13.2 s |
| 内存(USS,所有进程) | **169 MB** | 2011 MB |
| 就绪前消耗的 CPU 时间 | **2.4 s** | 47.9 s |
| 空闲 CPU | 单核的 **4 %** | 单核的 7 % |
| 退出 | **0.3 s** | 5.9 s |
测试使用 `main` 分支的 OpenIDEA release 构建,以及默认设置和插件的 IDEA,环境为 Windows 11、32 核 AMD、62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不代表完成了同样多的工作。两者都以相同方式从外部测量:可以用 [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) 在自己的机器和项目上复现。
## 下一步
<CardGroup cols={2}>
<Card title="安装" icon="download" href="/zh/guide/install">
下载 macOS、Windows 或 Linux 版 OpenIDEA。
</Card>
<Card title="快速上手" icon="rocket" href="/zh/guide/quickstart">
打开项目、熟悉界面、运行和调试。
</Card>
<Card title="从其他 IDE 迁移" icon="right-left" href="/zh/guide/migrate">
面向 IntelliJ IDEA、VS Code 和 Eclipse 用户的快捷键、设置导入和概念对照。
</Card>
<Card title="语言" icon="code" href="/zh/languages/index">
各语言支持哪些功能、需要安装什么。
</Card>
<Card title="插件" icon="puzzle-piece" href="/zh/plugins/index">
编写主题、语言和 WebAssembly 插件。
</Card>
<Card title="参与贡献" icon="code-branch" href="/zh/contribute/setup">
从源码构建 OpenIDEA 并提交 Pull Request。
</Card>
</CardGroup>
<Note>OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</Note>
+1
Переглянути файл
@@ -167,6 +167,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
+10
Переглянути файл
@@ -0,0 +1,10 @@
---
title: "插件市场"
description: "浏览 OpenIDEA 插件:来自社区和 OpenIDEA 团队的语言、框架、代码检查、主题、AI 和工具插件。"
mode: "custom"
---
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
import { Marketplace } from "/snippets/marketplace.jsx";
<Marketplace catalog={pluginCatalog} lang="zh" />
+85
Переглянути файл
@@ -44,6 +44,91 @@ const questions: AgentQuestion[] = [
},
];
for (const status of ["running", "ready"] as const) {
test(`answers an asynchronous Codex question when ${status}`, async ({ workbench: page }) => {
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
await page.evaluate(
async ({ task, status, key }) => {
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
(await import(ipcPath)).commands.agentAnswerQuestion = async (
id: string,
question: string,
answer: string | null,
) => {
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
const entries = store.useAgents.getState().entries.get(id)!;
store.useAgents.setState({
entries: new Map([
[
id,
entries.map((entry) =>
entry.type === "question" ? { ...entry, chosen: "Read latest content" } : entry,
),
],
]),
});
return { status: "ok", data: null };
};
store.useAgents.setState({
loaded: true,
tasks: new Map([[task.id, { ...task, status }]]),
entries: new Map([
[
task.id,
[
{ type: "agent", text: "I can keep working while you decide." },
{
type: "question",
id: "call-1",
title: "Should Retry read the latest content?",
chosen: null,
questions: [
{
answerKey: key,
header: "",
question: "Should Retry read the latest content?",
multiSelect: false,
options: [
{ label: "Read latest content (Recommended)", description: "", preview: null },
{ label: "Keep the original snapshot", description: "", preview: null },
],
},
],
},
],
],
]),
});
store.openTaskInEditorLocation(task.id);
},
{ task, status, key },
);
const card = page.getByRole("form", { name: "Should Retry read the latest content?" });
await expect(card).toBeVisible();
await card.getByRole("radio", { name: /^Read latest content/ }).check();
if (status === "running") {
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
}, task.id);
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
}
await card.getByRole("button", { name: "Submit", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute(
"data-async-answer",
JSON.stringify({
id: task.id,
question: "call-1",
answer: JSON.stringify({ [key]: ["Read latest content (Recommended)"] }),
}),
);
await expect(card).toHaveCount(0);
});
}
for (const theme of ["dark", "light"] as const) {
for (const width of [760, 1400]) {
for (const count of [1, 3]) {
+113
Переглянути файл
@@ -0,0 +1,113 @@
import { expect, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
workbench: page,
}, testInfo) => {
await stubDesktop(page);
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const { docBackend } = await import(backend);
const files: Map<string, string> = docBackend().files;
const root = "/dev/acme-api";
const client = `package shop;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "users")
interface UserClient {
@GetMapping("/users/{id}")
String find();
}`;
files.set(`${root}/client/src/main/java/UserClient.java`, client);
for (const service of ["users", "admin"]) {
files.set(
`${root}/${service}/src/main/java/UserController.java`,
`package shop;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
class UserController {
@GetMapping("/users/{id}")
String find() { return "${service}"; }
}`,
);
files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`);
}
window.__ipc.handlers.spring_route_sources = () =>
[...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text }));
window.__ipc.handlers.fs_read_text = ({ path }) => {
if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" };
return files.get(String(path));
};
window.__ipc.handlers.fs_read_dir = ({ path }) =>
[
...new Set(
[...files.keys()]
.filter((p) => p.startsWith(`${path}/`))
.map((p) => p.slice(String(path).length + 1).split("/")[0]!),
),
].map((name) => ({
path: `${path}/${name}`,
name,
kind: files.has(`${path}/${name}`) ? "file" : "dir",
size: files.get(`${path}/${name}`)?.length ?? 0,
mtimeMs: 0,
ignored: false,
excluded: false,
hidden: false,
}));
window.__ipc.handlers.lsp_goto = () => [];
await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`);
});
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" });
await page.locator('button[data-icon-source="feign"]').click();
await expect(page.locator(".cm-content").last()).toContainText('return "users"');
await page.screenshot({ path: testInfo.outputPath("feign-target.png"), animations: "disabled" });
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const ipc = "/src/platform/ipc.ts";
const path = "/dev/acme-api/admin/src/main/resources/application.properties";
(await import(backend)).docBackend().files.set(path, "spring.application.name=users\n");
(await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java");
});
await page.locator('button[data-icon-source="feign"]').click();
const chooser = page.getByRole("dialog", { name: "Choose Feign Endpoint" });
await expect(chooser.getByRole("option")).toHaveCount(2);
await page.screenshot({ path: testInfo.outputPath("feign-chooser.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
await page.locator('button[data-icon-source="feign"]').click();
await expect(chooser.getByRole("option")).toHaveCount(2);
await page.evaluate(async () => {
const ipc = "/src/platform/ipc.ts";
(await import(ipc)).emitLocalIdeEvent({
type: "fsChanged",
created: [],
modified: ["/dev/acme-api/admin/src/main/resources/application.properties"],
removed: [],
});
});
await chooser.getByRole("option").filter({ hasText: "admin/" }).click();
await expect(chooser).not.toBeVisible();
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
// The existing declaration navigation handles mapping URLs; method names
// retain the usual declaration-to-usages behavior.
await page.evaluate(async () => {
const api = "/src/editor/api.ts";
const editor = (await import(api)).activeEditor();
const offset = editor.view.state.doc.toString().indexOf("/users/{id}") + 2;
editor.view.dispatch({ selection: { anchor: offset } });
editor.view.focus();
});
await page.keyboard.press("Meta+b");
const declarations = page.getByRole("dialog", { name: "Choose Declaration" });
await expect(declarations.getByRole("option")).toHaveCount(2);
await declarations.getByRole("option").filter({ hasText: "admin/" }).click();
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
});
+41
Переглянути файл
@@ -39,3 +39,44 @@ for (const activation of ["double-click", "Enter"] as const) {
await expect(page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true })).toBeVisible();
});
}
test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({
workbench: page,
}) => {
const title = "Create Rectangular Selection on Mouse Drag";
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill(title);
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: new RegExp(title) });
for (let i = 0; i < 2; i++) {
await row.click({ button: "right" });
await page
.getByRole("menuitem", { name: /^Remove / })
.first()
.click();
}
await expect(row).toBeVisible();
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: `Mouse Shortcut: ${title}`, exact: true });
await recorder.getByRole("textbox", { name: "Mouse shortcut" }).click({ button: "middle", modifiers: ["Alt"] });
await expect(recorder.getByRole("textbox", { name: "Mouse shortcut" })).toContainText("Middle Click");
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
await expect
.poll(() =>
page.evaluate(async () => {
const keymapModule = "/src/platform/keymap.ts";
const { bindingsFor } = await import(/* @vite-ignore */ keymapModule);
return bindingsFor("editor.createRectangularSelectionOnMouseDrag");
}),
)
.toEqual(["Alt+Button2"]);
await page.keyboard.press("Meta+,");
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill(title);
await expect(row).toContainText("Middle Click");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
});
+60
Переглянути файл
@@ -0,0 +1,60 @@
import { expect, openFromTree, test } from "./fixtures";
test("middle and Alt drags create editable rectangles without changing ordinary selection", async ({
workbench: page,
}) => {
await openFromTree(page, "build.gradle.kts");
const text = "alpha = 111;\nbravo = 222;\ncharl = 333;\ndelta = 444;";
const prepare = () =>
page.evaluate(async (text) => {
const controllerModule = "/src/editor/core/controller.ts";
const columnModule = "/src/editor/core/cm/columnMode.ts";
const { editorController } = await import(/* @vite-ignore */ controllerModule);
const { setColumnMode } = await import(/* @vite-ignore */ columnModule);
const view = editorController().activeSlot.view;
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: text },
selection: { anchor: 0 },
effects: setColumnMode.of(false),
});
view.focus();
const a = view.coordsAtPos(0);
const b = view.coordsAtPos(view.state.doc.line(4).from + 5);
return {
from: { x: a.left + 0.5, y: (a.top + a.bottom) / 2 },
to: { x: b.left + 0.5, y: (b.top + b.bottom) / 2 },
};
}, text);
const selection = () =>
page.evaluate(async () => {
const controllerModule = "/src/editor/core/controller.ts";
const columnModule = "/src/editor/core/cm/columnMode.ts";
const { editorController } = await import(/* @vite-ignore */ controllerModule);
const { isColumnMode } = await import(/* @vite-ignore */ columnModule);
const view = editorController().activeSlot.view;
return {
ranges: view.state.selection.ranges.map((r: { from: number; to: number }) => view.state.sliceDoc(r.from, r.to)),
columnMode: isColumnMode(view.state),
text: view.state.doc.toString(),
};
});
for (const button of ["middle", "left"] as const) {
const points = await prepare();
if (button === "left") await page.keyboard.down("Alt");
await page.mouse.move(points.from.x, points.from.y);
await page.mouse.down({ button });
await page.mouse.move(points.to.x, points.to.y, { steps: 5 });
await page.mouse.up({ button });
if (button === "left") await page.keyboard.up("Alt");
await expect.poll(async () => (await selection()).ranges).toEqual(["alpha", "bravo", "charl", "delta"]);
expect((await selection()).columnMode).toBe(false);
}
await page.keyboard.insertText("name");
await expect.poll(async () => (await selection()).text).toBe("name = 111;\nname = 222;\nname = 333;\nname = 444;");
const points = await prepare();
await page.mouse.move(points.from.x, points.from.y);
await page.mouse.down();
await page.mouse.move(points.to.x, points.to.y, { steps: 5 });
await page.mouse.up();
await expect.poll(async () => (await selection()).ranges).toEqual([text.slice(0, text.lastIndexOf("delta") + 5)]);
});
+14
Переглянути файл
@@ -0,0 +1,14 @@
id = "typst"
name = "Typst"
extensions = ["typ"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Typst"
[[language-servers]]
name = "tinymist"
command = "tinymist"
args = ["lsp"]
root-markers = ["typst.toml"]
install-hint = "cargo install --locked --git https://github.com/Myriad-Dreamin/tinymist tinymist-cli (or brew install tinymist)"
+1
Переглянути файл
@@ -25,6 +25,7 @@
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
"theme:import-intellij": "node scripts/theme/import-intellij-theme.ts",
"dev:app": "node scripts/tauri.ts dev --config src-tauri/tauri.dev.conf.json",
"dev:status": "node scripts/dev-status.ts",
+4 -2
Переглянути файл
@@ -2217,8 +2217,10 @@ args = "optional-arguments" # optional
`[capabilities]` (a manifest that lists it is refused). On grant the IDE
records the jar's content hash and checks it again before every launch; a
changed jar is left out, with a line in the console, until the user approves
`java.agent` again in Settings › Plugins, which shows the agent's file name
and arguments next to the permission. Refusing or revoking it keeps the rest
`java.agent` again in Settings › Plugins. Settings shows the agent's file name
and arguments next to the permission, and when the jar no longer matches the
approved hash it shows the reason and an **Approve new jar** action. Refusing
or revoking it keeps the rest
of the plugin working, and the next launch has no agent.
- The IDE adds one `-javaagent:<absolute path>[=<args>]` argument to the Java
command line of **Application**, **Spring Boot** and **JAR Application**
+93
Переглянути файл
@@ -0,0 +1,93 @@
// Writes docs/snippets/plugin-catalog.jsx, the snapshot of the plugin marketplace the
// documentation site shows, from the release's plugins-index.json (or a local file).
//
// node scripts/gen-plugin-catalog.ts [index.json | url]
import { readFileSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
const OFFICIAL_INDEX = "https://github.com/l0ng-ai/openidea/releases/latest/download/plugins-index.json";
const OUT = fileURLToPath(new URL("../docs/snippets/plugin-catalog.jsx", import.meta.url));
interface IndexPlugin {
id: string;
name: string;
version: string;
description: string;
publisher: string;
categories?: string[];
icon?: { light: string | null; dark: string | null } | null;
homepage?: string | null;
downloads?: number | null;
}
interface Index {
publishers: { id: string; name: string }[];
plugins: IndexPlugin[];
}
async function load(source: string): Promise<Index> {
if (/^https?:\/\//.test(source)) {
const res = await fetch(source);
if (!res.ok) throw new Error(`${source}: HTTP ${res.status}`);
return (await res.json()) as Index;
}
return JSON.parse(readFileSync(source, "utf8")) as Index;
}
function compareVersions(a: string, b: string): number {
const pa = a.split(/[.-]/).map(Number);
const pb = b.split(/[.-]/).map(Number);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const d = (pa[i] || 0) - (pb[i] || 0);
if (d) return d;
}
return 0;
}
const svgUri = (svg: string) => `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
function icon(p: IndexPlugin) {
const light = p.icon?.light ?? p.icon?.dark;
const dark = p.icon?.dark ?? p.icon?.light;
if (!light || !dark) return null;
return light === dark ? { light: svgUri(light) } : { light: svgUri(light), dark: svgUri(dark) };
}
const index = await load(process.argv[2] ?? OFFICIAL_INDEX);
const publishers = new Map(index.publishers.map((p) => [p.id, p.name]));
const latest = new Map<string, IndexPlugin>();
for (const plugin of index.plugins) {
const seen = latest.get(plugin.id);
if (!seen || compareVersions(plugin.version, seen.version) > 0) latest.set(plugin.id, plugin);
}
const plugins = [...latest.values()]
// API examples document the plugin API; they are not offered to users here.
.filter((p) => !/\(API Example\)$/.test(p.name))
.map((p) => ({
id: p.id,
name: p.name,
version: p.version,
description: p.description,
publisher: publishers.get(p.publisher) ?? p.publisher,
official: p.publisher === "openidea",
categories: p.categories?.length ? p.categories : ["other"],
downloads: p.downloads ?? 0,
homepage: p.homepage ?? null,
icon: icon(p),
}))
.sort((a, b) => b.downloads - a.downloads || a.name.localeCompare(b.name));
const catalog = {
generatedAt: new Date().toISOString().slice(0, 10),
publishers: new Set(plugins.map((p) => p.publisher)).size,
plugins,
};
writeFileSync(
OUT,
`// Generated by scripts/gen-plugin-catalog.ts. Do not edit.\nexport const pluginCatalog = ${JSON.stringify(catalog)};\n`,
);
console.log(`${OUT}: ${plugins.length} plugins from ${catalog.publishers} publishers`);
+2 -2
Переглянути файл
@@ -1,11 +1,11 @@
//! The OS clipboard's file list, so the project view and Explorer exchange files.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
use crate::commands::doc::blocking;
use ide_command::desktop_command;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use ide_core::IdeError;
use ide_core::IdeResult;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
use ide_host::ops::doc::blocking;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, WebviewWindow};
+14 -5
Переглянути файл
@@ -3,7 +3,7 @@
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{IdeResult, RequestId};
use ide_db::tools::{DbDumpKind, DbTool, DbToolJob, ToolInstall, ToolLine};
use ide_db::tools::{DbTool, DbToolJob, DumpInfo, ToolInstall, ToolLine};
use tauri::ipc::Channel;
use tauri::{State, Window};
@@ -37,12 +37,20 @@ pub async fn db_tool_version(path: std::path::PathBuf) -> IdeResult<String> {
ide_host::ops::doc::blocking(move || ide_db::tools::version_of(&path)).await
}
/// What made the dump at `path` (from its first bytes), so a restore picks the right tool.
/// The long options the executable at `path` lists in its `--help` (`masking-policies`…).
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn db_dump_kind(path: std::path::PathBuf) -> IdeResult<DbDumpKind> {
ide_host::ops::doc::blocking(move || ide_db::tools::dump_kind(&path)).await
pub async fn db_tool_options(path: std::path::PathBuf) -> IdeResult<Vec<String>> {
ide_host::ops::doc::blocking(move || ide_db::tools::options_of(&path)).await
}
/// What made the dump at `path` and whether it creates its own database (from its first bytes).
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn db_dump_info(path: std::path::PathBuf) -> IdeResult<DumpInfo> {
ide_host::ops::doc::blocking(move || ide_db::tools::dump_info(&path)).await
}
/// The command line `db_run_tool` would run, without the password.
@@ -88,11 +96,12 @@ pub async fn db_server_version(window: Window, state: State<'_, AppState>, id: S
}
ide_command::desktop_domain!(
db_dump_kind,
db_dump_info,
db_export_file,
db_run_tool,
db_server_version,
db_tool_installs,
db_tool_options,
db_tool_preview,
db_tool_version,
);
+3 -2
Переглянути файл
@@ -29,8 +29,9 @@ pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_detach(window: WebviewWindow) -> IdeResult<()> {
groups::detach(window.app_handle(), window.label())?;
pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::detach(window.app_handle(), &label)?;
groups::persist(window.app_handle()).await
}
+1
Переглянути файл
@@ -396,6 +396,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("editor.toggleZen", "Enter Distraction Free Mode"),
act("window.toggleFullScreen", "Toggle Full Screen"),
toggle("view.toggleCompactMode", "Compact Mode"),
toggle("view.togglePresentationAssistant", "Presentation Assistant"),
SEP,
act("view.zoomIn", "Zoom In IDE"),
act("view.zoomOut", "Zoom Out IDE"),
+3 -1
Переглянути файл
@@ -1,6 +1,7 @@
# Generated by `pnpm gen:bindings`; do not edit. One line per command:
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.
agent_accept_changes trusted project_host bindings async
agent_answer_question trusted project_host bindings async
agent_archive always project_host bindings sync
agent_base_text trusted project_host bindings async
agent_cancel always project_host bindings sync
@@ -96,7 +97,7 @@ db_database_catalog trusted project_host bin
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
db_disconnect trusted project_host bindings async
db_dump_kind trusted desktop bindings async
db_dump_info trusted desktop bindings async
db_execute trusted project_host bindings async
db_explain trusted project_host bindings async
db_export_file always desktop bindings async
@@ -123,6 +124,7 @@ db_tables trusted project_host bin
db_test trusted project_host bindings async
db_test_tunnel trusted project_host bindings async
db_tool_installs trusted desktop bindings async
db_tool_options trusted desktop bindings async
db_tool_preview trusted desktop bindings sync
db_tool_version trusted desktop bindings async
db_trust_ssh_host trusted project_host bindings async
+112 -9
Переглянути файл
@@ -12,6 +12,8 @@ export const commands = {
* local checkout, uncommitted; files the checkout changed itself are left alone and reported.
*/
agentAcceptChanges: (task: string, paths: string[] | null) => typedError<AgentAcceptOutcome, IdeError>(__TAURI_INVOKE("agent_accept_changes", { task, paths })),
/** Answers a non-blocking question, without cancelling the current turn. */
agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_answer_question", { task, question, answer })),
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
/** Content of `path` when the task started (left side of its diff). */
agentBaseText: (task: string, path: IpcPath) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path })),
@@ -274,8 +276,8 @@ export const commands = {
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
/** What made the dump at `path` (from its first bytes), so a restore picks the right tool. */
dbDumpKind: (path: string) => typedError<DbDumpKind, IdeError>(__TAURI_INVOKE("db_dump_kind", { path })),
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
dbExplain: (request: RequestId, id: string, statement: string, schema: string | null) => typedError<DbPlanNode[], IdeError>(__TAURI_INVOKE("db_explain", { request, id, statement, schema })),
/**
@@ -316,6 +318,8 @@ export const commands = {
dbTestTunnel: (source: DataSource_Deserialize, sshSecret: string | null) => typedError<string, IdeError>(__TAURI_INVOKE("db_test_tunnel", { source, sshSecret })),
/** Installed copies of `tool`, newest first. */
dbToolInstalls: (tool: DbTool) => typedError<DbToolInstall[], IdeError>(__TAURI_INVOKE("db_tool_installs", { tool })),
/** The long options the executable at `path` lists in its `--help` (`masking-policies`…). */
dbToolOptions: (path: string) => typedError<string[], IdeError>(__TAURI_INVOKE("db_tool_options", { path })),
/** The command line `db_run_tool` would run, without the password. */
dbToolPreview: (id: string, executable: string, job: DbToolJob) => typedError<string, IdeError>(__TAURI_INVOKE("db_tool_preview", { id, executable, job })),
/** The version line of the executable at `path`. */
@@ -811,6 +815,11 @@ export const commands = {
selectionRange: Range,
/** Call sites, for call hierarchy. */
fromRanges: Range[],
/**
* The file of `from_ranges` when it is not the item's own: for an outgoing call, the
* file of the prepared item that makes it (a path, or the URI of a virtual document).
*/
fromPath?: IpcPath | null,
} | null, IdeError>(__TAURI_INVOKE("lsp_prepare_type_hierarchy", { doc, pos })),
/**
* References of the symbol at `pos`. `project_wide` also searches project files
@@ -1812,7 +1821,7 @@ export const commands = {
/** Closes several project tabs one by one (each asks about its own unsaved changes), then selects `keep`. */
windowGroupCloseTabs: (keep: string, labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_close_tabs", { keep, labels })),
windowGroupCurrent: () => typedError<WindowTab[], IdeError>(__TAURI_INVOKE("window_group_current")),
windowGroupDetach: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach")),
windowGroupDetach: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach", { label })),
windowGroupMerge: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_merge")),
windowGroupReorder: (labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_reorder", { labels })),
windowGroupRestore: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_restore")),
@@ -2130,7 +2139,11 @@ sentMs?: number | null;
/** When the turn it started ended; `None` while it runs or when it was cut off. */
doneMs?: number | null;
/** Sent into a running turn rather than starting one. */
steered?: boolean } | { type: "agent"; text: string } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
steered?: boolean } | { type: "agent"; text: string } |
/** A question that can be answered while the agent keeps working, or after the turn ends. */
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
/** The submitted answers, or `Skipped`; `None` while unanswered. */
chosen: string | null } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
kind: string; status: AgentToolStatus; locations: IpcPath[];
/** Text the tool reported (command output…), truncated. */
@@ -2812,6 +2825,8 @@ export type AppearanceSettings_Deserialize = {
mainToolbar?: MainToolbarSettings | null,
/** Appearance › Background Image: an image shown through the IDE window. */
backgroundImage?: BackgroundImageSettings,
/** Appearance › Presentation Assistant: the name and shortcut of each action run. */
presentationAssistant?: PresentationAssistantSettings,
};
export type AppearanceSettings_Serialize = {
@@ -2881,6 +2896,8 @@ export type AppearanceSettings_Serialize = {
mainToolbar: MainToolbarSettings | null,
/** Appearance › Background Image: an image shown through the IDE window. */
backgroundImage: BackgroundImageSettings,
/** Appearance › Presentation Assistant: the name and shortcut of each action run. */
presentationAssistant: PresentationAssistantSettings,
};
export type ApplyOutcome = {
@@ -3183,6 +3200,8 @@ export type CMakeSettings_Serialize = {
};
export type CallHierarchy = {
/** The symbol the hierarchy is for: the first item the server prepared at the position. */
root?: HierarchyItem | null,
items: HierarchyItem[],
incomplete: ReferencesIncomplete | null,
};
@@ -3293,8 +3312,12 @@ export type CheckoutOptions = {
export type CheckoutOutcome = { kind: "done" } |
/** These local changes (repository-relative paths) would be overwritten. */
{ kind: "localChanges"; files: string[] } |
/** These untracked files (repository-relative paths) would be overwritten. */
{ kind: "untrackedFiles"; files: string[] } |
/**
* These untracked files (repository-relative paths) would be overwritten by the
* checkout; with `removed`, they would be removed by it (tracked here, absent
* from the target).
*/
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
/** Local branch `local` has commits that remote branch `remote` does not. */
{ kind: "localBranchAhead"; local: string; remote: string } |
/**
@@ -3579,6 +3602,8 @@ export type CommitSettings = {
* `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
*/
doubleClickOpensDiff?: boolean | null,
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
agentInstructions?: string,
};
export type Commit_Deserialize = {
@@ -4164,13 +4189,23 @@ export type DbDumpFormat =
/** A directory of files; the only format `pg_dump` writes in parallel. */
"directory" | "tar";
/** What a restore needs to know about a dump before it runs. */
export type DbDumpInfo = {
kind: DbDumpKind,
/**
* An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`,
* or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them.
*/
createsDatabase: boolean,
};
/** What made a dump, read from its first bytes (a directory: its `toc.dat`). */
export type DbDumpKind =
/** `pg_dump` custom or tar archive, or a directory archive: `pg_restore`. */
"postgresArchive" |
/** Plain SQL from `pg_dump`: `psql`. */
"postgresSql" |
/** `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools. */
/** `mysqldump` / `mariadb-dump`: `mysql`. */
"mysqlSql" | "unknown";
export type DbDumpStatements = "copy" | "inserts" | "columnInserts";
@@ -4214,6 +4249,36 @@ export type DbIntrospection = {
objectFilter?: string,
};
export type DbMysqlOptions = {
/** Empty: the databases the dump names. */
database: string,
/** Runs the remaining statements after an error. */
force: boolean,
};
/** Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off. */
export type DbMysqldumpOptions = {
/** Empty: every database. */
databases: string[],
/** Only with exactly one database. */
tables: string[],
addDropTable: boolean,
disableKeys: boolean,
addLocks: boolean,
addDropTrigger: boolean,
noData: boolean,
completeInsert: boolean,
createOptions: boolean,
routines: boolean,
events: boolean,
/** A consistent InnoDB snapshot without locks; needs no RELOAD privilege. */
singleTransaction: boolean,
/** Wins over `single_transaction`. */
lockAllTables: boolean,
/** `None`: the client has no `--masking-policies`. */
maskingPolicies: boolean | null,
};
/** Schema objects other than tables and columns (Go to DDL, Drop). */
export type DbObjectKind = "function" | "procedure" | "package" | "trigger" | "sequence";
@@ -4260,6 +4325,8 @@ export type DbPgDumpOptions = {
export type DbPgRestoreOptions = {
content: DbDumpContent,
schemas: string[],
/** Creates the database the archive names; the target is only connected to. */
create: boolean,
clean: boolean,
ifExists: boolean,
noOwner: boolean,
@@ -4456,7 +4523,7 @@ export type DbTablePage = {
offset: number | null,
};
export type DbTool = "pgDump" | "pgRestore" | "psql";
export type DbTool = "pgDump" | "pgRestore" | "psql" | "mysqldump" | "mysql";
/** An installed copy of a tool. */
export type DbToolInstall = {
@@ -4468,7 +4535,9 @@ export type DbToolInstall = {
/** A run of a client tool: which one, the file it writes or reads, and its options. */
export type DbToolJob = { tool: "pgDump"; file: string; options: DbPgDumpOptions } |
/** `file`: an archive, or a directory archive. */
{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions };
{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions } | { tool: "mysqldump"; file: string; options: DbMysqldumpOptions } |
/** `file` goes to the standard input. */
{ tool: "mysql"; file: string; options: DbMysqlOptions };
/** A line the tool wrote. */
export type DbToolLine = {
@@ -6410,6 +6479,11 @@ export type HierarchyItem = {
selectionRange: Range,
/** Call sites, for call hierarchy. */
fromRanges: Range[],
/**
* The file of `from_ranges` when it is not the item's own: for an outgoing call, the
* file of the prepared item that makes it (a path, or the URI of a virtual document).
*/
fromPath?: IpcPath | null,
};
export type HierarchyMember = {
@@ -8876,6 +8950,8 @@ export type PluginInfo = {
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
/** The Java agent this plugin declares, and whether it is still approved. */
javaAgent: PluginJavaAgent | null,
source: PluginSource,
/** Package directory. */
path: IpcPath,
@@ -8910,6 +8986,16 @@ export type PluginInfo = {
extensionPoints: ExtensionPointInfo[],
};
/** The Java agent a plugin contributes, for Settings › Plugins. */
export type PluginJavaAgent = {
/** The jar's file name. */
fileName: string,
/** The optional argument passed after `=`. */
args: string | null,
/** The jar still has the hash recorded when `java.agent` was granted. */
approved: boolean,
};
/**
* Commands of this module the remote server answers.
* Versioned plugin visuals, refreshed after the editor synchronizes its buffer.
@@ -9195,6 +9281,19 @@ export type PreparedRequest = {
body: string | null,
};
/** Appearance › Presentation Assistant: shows the name and shortcut of each action the user runs. */
export type PresentationAssistantSettings = {
enabled?: boolean,
/** `small` | `medium` | `large`. */
size?: string,
/** How long each popup stays, in seconds. */
durationSeconds?: number,
/** `top-left`, `top`, `top-right`, `bottom-left`, `bottom` or `bottom-right` of the window. */
position?: string,
/** Also show the shortcut of the other platform's keymap (macOS ⇄ Windows/Linux). */
alternateKeymap?: boolean,
};
export type ProblemSeverity = "info" | "warning" | "error" |
/** The refactoring can't run at all; there is no edit. */
"fatal";
@@ -10781,6 +10880,10 @@ export type Stash = {
index: number,
message: string,
timeMs: number | null,
/** The stash commit; its changes are those against `base`. */
id: string,
/** The commit the stash was made on (the stash commit's first parent). */
base: string | null,
};
/** A plugin's status bar item. */
+27 -12
Переглянути файл
@@ -570,14 +570,24 @@ function copyReference(reference: Promise<string>) {
}
}
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
const path = slot.model.path;
const { doc, selection } = view.state;
const line = doc.lineAt(selection.main.head).number;
/** The selected lines (1-based), leaving out the one a selection ends at the start of. */
function selectedLines(state: EditorState): { first: number; last: number } {
const { doc, selection } = state;
const { from, to } = selection.main;
// The selected lines, leaving out the one a selection ends at the start of.
const first = doc.lineAt(from).number;
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
return { first, last };
}
/** `path:12`, or `path:12-18` for a selection over several lines. */
function pathWithLines(state: EditorState, path: string): string {
const { first, last } = selectedLines(state);
return `${pathToCopy("relative", path)}:${first}${last > first ? `-${last}` : ""}`;
}
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
const path = slot.model.path;
const { first, last } = selectedLines(view.state);
const contributed = menuGroupItems("copyPath", {
paths: [path],
line: first - 1,
@@ -603,7 +613,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
{
id: "editor.copyPathWithLineNumber",
label: "Path with line number",
value: `${pathToCopy("relative", path)}:${line}`,
value: pathWithLines(view.state, path),
},
];
const popup: Extract<LspPopup, { kind: "list" }> = {
@@ -907,6 +917,16 @@ export function registerEditorActions(): () => void {
// The mouse selection style handles the pointer position and dragging.
run: () => {},
},
{
id: "editor.createRectangularSelectionOnMouseDrag",
title: "Create Rectangular Selection on Mouse Drag",
category: "Editor Actions",
when: "textEditorActive",
hidden: true,
keymap: true,
// The mouse selection style owns the drag; invoking the action alone is harmless.
run: () => {},
},
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => cloneCaretAbove(v), { category: "Editor Actions" }),
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => cloneCaretBelow(v), { category: "Editor Actions" }),
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
@@ -1280,12 +1300,7 @@ export function registerEditorActions(): () => void {
when: TEXT_WHEN,
run: ({ arg }) => {
if (typeof arg === "string") copyEditorPath(arg);
else
withView((view, slot) =>
copyEditorPath(
`${pathToCopy("relative", slot.model.path)}:${view.state.doc.lineAt(view.state.selection.main.head).number}`,
),
)();
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
},
},
{
+184 -1
Переглянути файл
@@ -1,8 +1,10 @@
import { EditorState } from "@codemirror/state";
import { LanguageDescription, 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 { findLanguageDescription, loadSupport } from "./languages";
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("distinguishes PHP classes, method declarations and fields for imported schemes", async () => {
@@ -270,6 +272,28 @@ describe("language modes", () => {
}
});
it('keeps C++ namespace and extern "C" contents at the level of their braces', async () => {
const support = await loadSupport(findLanguageDescription("C++", "/p/a.cpp")!);
const doc = [
"namespace foo {",
"class Bar {",
" int x;",
"};",
"namespace inner {",
"void f() {",
" g();",
"}",
"} // namespace inner",
"} // namespace foo",
'extern "C" {',
"int h();",
"}",
].join("\n");
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect([2, 3, 4, 5, 6, 7, 9, 10, 12, 13].map(indent)).toEqual([0, 2, 0, 0, 0, 2, 0, 0, 0, 0]);
});
it("colours `this`, `super` and Rust's `self` as keywords", async () => {
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
@@ -309,4 +333,163 @@ describe("language modes", () => {
expect(support?.language).toBeTruthy();
}
});
const keywordHighlighter = tagHighlighter([{ tag: t.keyword, class: "keyword" }]);
function keywords(language: Language, source: string) {
const found: string[] = [];
highlightTree(language.parser.parse(source), keywordHighlighter, (from, to) => found.push(source.slice(from, to)));
return found;
}
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
for (const path of ["/p/Cargo.toml", "/p/uv.lock"]) {
const support = await loadSupport(findLanguageDescription("TOML", path)!);
expect(keywords(support!.language, '[package]\nname = "x"'), path).toEqual(["package", "name"]);
}
const fenced = fencedCodeMode("toml")!;
expect(fenced.name).toBe("TOML");
const language =
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
expect(keywords(language, 'name = "x"')).toEqual(["name"]);
});
const propertiesHighlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.operator, class: "operator" },
{ tag: t.string, class: "string" },
{ tag: t.comment, class: "comment" },
{ tag: t.heading, class: "heading" },
]);
function highlightProperties(language: Language, source: string) {
const found: Array<[string, string]> = [];
highlightTree(language.parser.parse(source), propertiesHighlighter, (from, to, style) =>
found.push([source.slice(from, to), style]),
);
return found;
}
it("colours properties and .env keys as keywords, the first separator as an operator and the whole value as a string", async () => {
const support = await loadSupport(findLanguageDescription("Properties files", "/p/.env")!);
const source = [
"APP_NAME=core-user",
"DATABASE_URL=postgres://u:p@h:5432/db",
"APP_KEY=base64:abc==",
"key = value",
"key: value",
"export A=b",
"# c",
"[section]",
"a=b\\",
" c",
"=x",
// A blank line ends a continued value.
"d=e\\",
"",
"f=g",
].join("\n");
expect(highlightProperties(support!.language, source)).toEqual([
["APP_NAME", "keyword"],
["=", "operator"],
["core-user", "string"],
["DATABASE_URL", "keyword"],
["=", "operator"],
["postgres://u:p@h:5432/db", "string"],
["APP_KEY", "keyword"],
["=", "operator"],
["base64:abc==", "string"],
["key ", "keyword"],
["=", "operator"],
[" value", "string"],
["key", "keyword"],
[":", "operator"],
[" value", "string"],
["export A", "keyword"],
["=", "operator"],
["b", "string"],
["# c", "comment"],
["[section]", "heading"],
["a", "keyword"],
["=", "operator"],
["b\\", "string"],
[" c", "string"],
["=", "operator"],
["x", "string"],
["d", "keyword"],
["=", "operator"],
["e\\", "string"],
["f", "keyword"],
["=", "operator"],
["g", "string"],
]);
});
it("colours properties keys in ```ini and ```properties code blocks", async () => {
for (const info of ["ini", "properties"]) {
const fenced = fencedCodeMode(info)!;
expect(fenced.name, info).toBe("Properties files");
const language =
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
expect(highlightProperties(language, "a=b"), info).toEqual([
["a", "keyword"],
["=", "operator"],
["b", "string"],
]);
}
});
it("colours Typst markup, embedded code and math", async () => {
const support = await loadSupport(findLanguageDescription("Typst", "/p/notes.typ")!);
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.comment, class: "comment" },
{ tag: t.heading, class: "heading" },
{ tag: t.strong, class: "strong" },
{ tag: t.emphasis, class: "emphasis" },
{ tag: t.string, class: "string" },
{ tag: t.number, class: "number" },
{ tag: t.function(t.variableName), class: "function" },
{ tag: t.labelName, class: "label" },
{ tag: t.monospace, class: "raw" },
{ tag: t.atom, class: "atom" },
]);
const source = [
"#set page(width: 10cm)",
"// note",
"= Intro <intro>",
"Some *bold* and _it_ in snake_case, `raw` and $x^2$ see @intro.",
"#let total = 1 + 2",
"#if true [yes]",
"```rust",
"let x = 1;",
"```",
].join("\n");
const found: string[] = [];
highlightTree(support!.language.parser.parse(source), highlighter, (from, to, cls) =>
found.push(`${source.slice(from, to)}:${cls}`),
);
expect(found).toEqual(
expect.arrayContaining([
"#set:keyword",
"page:function",
"10cm:number",
"// note:comment",
"= Intro :heading",
"<intro>:label",
"*bold*:strong",
"_it_:emphasis",
"`raw`:raw",
"$:keyword",
"@intro:label",
"#let:keyword",
"1:number",
"#if:keyword",
"true:atom",
"```rust:raw",
"let x = 1;:raw",
]),
);
expect(found.filter((f) => f.endsWith(":emphasis"))).toEqual(["_it_:emphasis"]);
expect(found).not.toContain("yes:keyword");
});
});
+34 -3
Переглянути файл
@@ -11,6 +11,8 @@ import {
LanguageDescription,
LanguageSupport,
StreamLanguage,
delimitedIndent,
indentNodeProp,
indentService,
language as languageFacet,
type StreamParser,
@@ -112,6 +114,11 @@ const OWN_MODES = [
extensions: ["rst"],
load: () => import("./restructuredtext").then((m) => new LanguageSupport(m.restructuredtextLanguage)),
}),
LanguageDescription.of({
name: "Typst",
extensions: ["typ"],
load: async () => new LanguageSupport(StreamLanguage.define((await import("./typst")).typstParser)),
}),
LanguageDescription.of({
name: "Gherkin",
extensions: ["feature"],
@@ -195,6 +202,14 @@ const OWN_MODES = [
);
},
}),
LanguageDescription.of({
name: "TOML",
load: async () => new LanguageSupport(StreamLanguage.define((await import("./toml")).tomlParser)),
}),
LanguageDescription.of({
name: "Properties files",
load: async () => new LanguageSupport((await import("./properties")).propertiesLanguage),
}),
LanguageDescription.of({
name: "Markdown",
extensions: ["md", "markdown", "mkd"],
@@ -413,12 +428,28 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
YAML: { "Key/Literal Key/QuotedLiteral": t.keyword },
};
const bracedIndent = delimitedIndent({ closing: "}" });
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
"C++": [
indentNodeProp.add({
// The stock rule for every `{ … }` body, except the bodies of these two.
CompoundStatement: (cx) =>
cx.node.parent?.name === "NamespaceDefinition" || cx.node.parent?.name === "LinkageSpecification"
? cx.baseIndent
: bracedIndent(cx),
}),
],
};
function patchSupport(desc: LanguageDescription, support: LanguageSupport): LanguageSupport {
const extra = EXTRA_TAGS[desc.name];
const props = [...(extra ? [styleTags(extra)] : []), ...(EXTRA_PROPS[desc.name] ?? [])];
const language =
extra && support.language instanceof LRLanguage
? support.language.configure({ props: [styleTags(extra)] })
: support.language;
props.length && support.language instanceof LRLanguage ? support.language.configure({ props }) : support.language;
const result = new LanguageSupport(language, [
support.support,
docCommentTags(desc.name),
+49
Переглянути файл
@@ -82,3 +82,52 @@ describe("caret mouse bindings", () => {
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
});
});
describe("rectangular mouse bindings", () => {
const id = "editor.createRectangularSelectionOnMouseDrag";
it.each(Object.keys(PRESETS))("%s exposes both default gestures", (preset) => {
useKeymap.setState({ preset });
expect(PRESETS[preset]![id]).toEqual(["Alt+Button1", "Button2"]);
expect(styles(event())[1]).not.toBeNull();
expect(styles(event({ button: 1, altKey: false }))[1]).not.toBeNull();
});
it("uses the full rebound stroke immediately instead of the old defaults", () => {
useKeymap.setState({ overrides: { [id]: ["ctrl+alt+shift+button1"] } });
expect(styles(event())[1]).toBeNull();
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
expect(styles(event({ ctrlKey: true, shiftKey: true }))[1]).not.toBeNull();
expect(styles(event({ ctrlKey: true, shiftKey: true, metaKey: true }))[1]).toBeNull();
});
it("honours removal and restoration without changing the column mode", () => {
useKeymap.setState({ overrides: { [id]: [] } });
expect(styles(event())[1]).toBeNull();
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
useKeymap.setState({ overrides: {} });
expect(styles(event())[1]).not.toBeNull();
});
it("keeps Linux middle paste by default but accepts an explicit middle binding", () => {
usePlatform.setState({ os: "linux" });
expect(styles(event())[1]).not.toBeNull();
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
useKeymap.setState({ overrides: { [id]: ["Button2"] } });
expect(styles(event({ button: 1, altKey: false }))[1]).not.toBeNull();
expect(styles(event())[1]).toBeNull();
});
it("leaves a shared stroke to the add-caret gesture", () => {
useKeymap.setState({ overrides: { [id]: ["Alt+Shift+Button1"] } });
const [caret, rectangle] = styles(event({ shiftKey: true }));
expect(caret).not.toBeNull();
expect(rectangle).toBeNull();
});
it("does not claim right or side buttons", () => {
useKeymap.setState({ overrides: { [id]: ["Alt+Button3", "Alt+Button4"] } });
expect(styles(event({ button: 2 }))[1]).toBeNull();
expect(styles(event({ button: 3 }))[1]).toBeNull();
});
});
+11 -7
Переглянути файл
@@ -1,8 +1,7 @@
/** Mouse caret gestures follow the keymap; Alt and middle-button drags select columns. */
/** Mouse caret and rectangular selection gestures follow the keymap. */
import { EditorSelection, type Extension } from "@codemirror/state";
import { EditorView, type MouseSelectionStyle } from "@codemirror/view";
import { bindingsFor, mouseStrokeOf, normalizeBinding } from "@/platform/keymap";
import { usePlatform } from "@/platform/platformInfo";
import { blockMouseSelection } from "./columnMode";
/** The selection after a caret click / drag from `anchor` to `head` on top of `start`. */
@@ -25,6 +24,15 @@ export function isAddCaretGesture(event: MouseEvent): boolean {
);
}
export function isRectangularSelectionGesture(event: MouseEvent): boolean {
if ((event.button !== 0 && event.button !== 1) || isAddCaretGesture(event)) return false;
const stroke = mouseStrokeOf(event);
return (
stroke !== null &&
bindingsFor("editor.createRectangularSelectionOnMouseDrag").some((binding) => normalizeBinding(binding) === stroke)
);
}
const addCaretStyle = EditorView.mouseSelectionStyle.of((view, event): MouseSelectionStyle | null => {
if (!isAddCaretGesture(event)) return null;
let start = view.state.selection;
@@ -44,9 +52,5 @@ export const multiCaretMouse: Extension = [
addCaretStyle,
// CodeMirror's default (⌘click) would clash with ⌘click navigation.
EditorView.clickAddsSelectionRange.of(() => false),
blockMouseSelection((e) => {
if (isAddCaretGesture(e) || e.shiftKey || e.metaKey || e.ctrlKey) return false;
if (e.button === 0) return e.altKey;
return e.button === 1 && !e.altKey && usePlatform.getState().os !== "linux";
}),
blockMouseSelection(isRectangularSelectionGesture),
];
+4 -2
Переглянути файл
@@ -57,6 +57,7 @@ import { stringClipboard } from "./stringClipboard";
import { filterCopiedText } from "./clipboard";
import { LINE_INSET } from "./lineInset";
import { codeLensPositions } from "./codeLens";
import { wheelZoomStep } from "@/platform/wheelZoom";
// --- soft wraps ---------------------------------------------------------------
@@ -452,9 +453,10 @@ export function resetConfiguredEditorsFontZoom(origin: EditorView): void {
/** Exported for tests: the ⌘/Ctrl+wheel handler of the prefs compartment. */
export const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
if (!e.metaKey && !e.ctrlKey) return false;
const step = wheelZoomStep(e);
if (step === null) return false;
e.preventDefault();
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
if (step) stepConfiguredEditorsFontZoom(view, step);
return true;
},
});
+38
Переглянути файл
@@ -0,0 +1,38 @@
/**
* `.properties`, `.ini`, `.env` and Godot resources, coloured like IntelliJ's Properties and
* DotEnv highlighters: the key is KEYWORD, the first `=` or `:` is OPERATION_SIGN and the rest
* of the line (with its continuation lines) is STRING. The legacy mode finds the parts; its
* own `def` and `quote` styles would read as a variable and plain text.
*/
import { StreamLanguage, type StreamParser } from "@codemirror/language";
import { properties } from "@codemirror/legacy-modes/mode/properties";
/** The legacy state with the one field read here, plus the line's separator. */
interface State {
nextMultiline: boolean;
separated: boolean;
}
const parser: StreamParser<State> = {
name: properties.name,
startState: (indentUnit) => ({ ...(properties.startState!(indentUnit) as State), separated: false }),
// CodeMirror skips `token` on empty lines; a blank line ends a continued value.
blankLine(state) {
state.nextMultiline = false;
},
token(stream, state) {
if (stream.sol() && !state.nextMultiline) state.separated = false;
const style = properties.token(stream, state);
if (style === "def") return "keyword";
if (style === "quote") return "string";
// The legacy mode returns null only for `=` and `:`.
if (style === null) {
if (state.separated) return "string";
state.separated = true;
return "operator";
}
return style;
},
};
export const propertiesLanguage = StreamLanguage.define(parser);
+337
Переглянути файл
@@ -0,0 +1,337 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { StreamLanguage } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { tomlParser } from "./toml";
const language = StreamLanguage.define(tomlParser);
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.string, class: "string" },
{ tag: t.number, class: "number" },
{ tag: t.standard(t.variableName), class: "builtin" },
{ tag: t.comment, class: "comment" },
{ tag: t.escape, class: "escape" },
{ tag: t.invalid, class: "invalid" },
]);
function highlighted(source: string) {
const found: Array<[string, string]> = [];
highlightTree(language.parser.parse(source), highlighter, (from, to, style) =>
found.push([source.slice(from, to), style]),
);
return found;
}
describe("TOML highlighting", () => {
// IntelliJ's colour settings demo (plugins/toml highlighterDemoText.toml). Its two escape lines
// tag only the escapes; the keys and string bodies around them get KEY and STRING there too.
it("colours IntelliJ's TOML demo like IntelliJ", () => {
const demo = [
"# This is a TOML document.",
"",
'title = "TOML Example"',
'description = """',
" Multiline",
" description",
'"""',
"date = 2019-11-04T07:32:00-08:00",
"",
"[database]",
'server = "192.168.1.1"',
"ports = [ 8001, 8001, 8002 ]",
'"connection_max" = 5000',
"enabled = true",
"",
"[servers]",
"alpha = { ip = '10.0.0.1', dc = \"eqdc10\" }",
"beta = { ip = '10.0.0.2', dc = \"eqdc10\" }",
"",
"[clients]",
'data = [ ["gamma", "delta"], [1.0, 2.0] ]',
"",
"hosts = [",
' "alpha",',
' "omega",',
"]",
"",
'valid-escapes = """\\tline \\"1\\"',
" line\\u00202",
" line 3\\U0000002E",
'"""',
'invalid-escapes = "\\a \\u20 \\U0020"',
].join("\n");
expect(highlighted(demo)).toEqual([
["# This is a TOML document.", "comment"],
["title", "keyword"],
['"TOML Example"', "string"],
["description", "keyword"],
['"""', "string"],
[" Multiline", "string"],
[" description", "string"],
['"""', "string"],
["date", "keyword"],
["2019-11-04T07:32:00-08:00", "builtin"],
["database", "keyword"],
["server", "keyword"],
['"192.168.1.1"', "string"],
["ports", "keyword"],
["8001", "number"],
["8001", "number"],
["8002", "number"],
['"connection_max"', "string"],
["5000", "number"],
["enabled", "keyword"],
["true", "builtin"],
["servers", "keyword"],
["alpha", "keyword"],
["ip", "keyword"],
["'10.0.0.1'", "string"],
["dc", "keyword"],
['"eqdc10"', "string"],
["beta", "keyword"],
["ip", "keyword"],
["'10.0.0.2'", "string"],
["dc", "keyword"],
['"eqdc10"', "string"],
["clients", "keyword"],
["data", "keyword"],
['"gamma"', "string"],
['"delta"', "string"],
["1.0", "number"],
["2.0", "number"],
["hosts", "keyword"],
['"alpha"', "string"],
['"omega"', "string"],
["valid-escapes", "keyword"],
['"""', "string"],
["\\t", "escape"],
["line ", "string"],
['\\"', "escape"],
["1", "string"],
['\\"', "escape"],
[" line", "string"],
["\\u0020", "escape"],
["2", "string"],
[" line 3", "string"],
["\\U0000002E", "escape"],
['"""', "string"],
["invalid-escapes", "keyword"],
['"', "string"],
["\\a", "invalid"],
[" ", "string"],
["\\u", "invalid"],
["20 ", "string"],
["\\U", "invalid"],
['0020"', "string"],
]);
});
// IntelliJ's TomlHighlightingAnnotatorTest: numbers, dates and booleans can be keys too.
it("colours numbers and dates as values and bare keys of any shape as keys", () => {
expect(
highlighted(
[
'k1= "foo"',
'k2."k3".k4 = "bar"',
'123 = "baz"',
'2019-11-08 = "qqq"',
"true = 1",
"k5 = { k6 = 123, k7 = 2019-11-08 }",
"[foo.bar]",
].join("\n"),
),
).toEqual([
["k1", "keyword"],
['"foo"', "string"],
["k2", "keyword"],
['"k3"', "string"],
["k4", "keyword"],
['"bar"', "string"],
["123", "keyword"],
['"baz"', "string"],
["2019-11-08", "keyword"],
['"qqq"', "string"],
["true", "keyword"],
["1", "number"],
["k5", "keyword"],
["k6", "keyword"],
["123", "number"],
["k7", "keyword"],
["2019-11-08", "builtin"],
["foo", "keyword"],
["bar", "keyword"],
]);
});
it.each([
["t = 07:32:00", [["07:32:00", "builtin"]]],
// A time needs seconds: this is two numbers around a stray colon, as in IntelliJ's lexer.
[
"t = 07:32",
[
["07", "number"],
["32", "number"],
],
],
[
"d = 2019-11-08 # c",
[
["2019-11-08", "builtin"],
["# c", "comment"],
],
],
["d = 1979-05-27 07:32:00Z", [["1979-05-27 07:32:00Z", "builtin"]]],
["d = 1979-05-27T00:32:00.999999+07:00", [["1979-05-27T00:32:00.999999+07:00", "builtin"]]],
["n = +inf", [["+inf", "number"]]],
["n = 1_000", [["1_000", "number"]]],
["n = 6.626e-34", [["6.626e-34", "number"]]],
["n = 0xdead_beef", [["0xdead_beef", "number"]]],
["n = 0o755", [["0o755", "number"]]],
["n = 0b1101", [["0b1101", "number"]]],
// Not a number (a hex digit has to follow `0x`) or not a boolean: a bare key to IntelliJ's lexer.
["n = 0x_1", [["0x_1", "keyword"]]],
["b = trueish", [["trueish", "keyword"]]],
["s = 'C:\\Users\\nodejs'", [["'C:\\Users\\nodejs'", "string"]]],
['s = """"q""""', [['""""q""""', "string"]]],
["s = ''''q''''", [["''''q''''", "string"]]],
[
's = "\\uD800"',
[
['"', "string"],
["\\uD800", "invalid"],
['"', "string"],
],
],
[
's = "\\U0010FFFF\\U00110000"',
[
['"', "string"],
["\\U0010FFFF", "escape"],
["\\U00110000", "invalid"],
['"', "string"],
],
],
[
's = "\\e"',
[
['"', "string"],
["\\e", "invalid"],
['"', "string"],
],
],
[
's = "\\\\"',
[
['"', "string"],
["\\\\", "escape"],
['"', "string"],
],
],
// A line-ending backslash trims the line break in a multi-line basic string only.
[
's = """a \\\n b"""',
[
['"""a ', "string"],
["\\", "escape"],
[' b"""', "string"],
],
],
// Whitespace may follow that backslash.
[
's = """a \\ \t\n b"""',
[
['"""a ', "string"],
["\\ \t", "escape"],
[' b"""', "string"],
],
],
[
's = "a \\\nb = 1',
[
['"a ', "string"],
["\\", "invalid"],
["b", "keyword"],
["1", "number"],
],
],
[
"k = 'a'.b",
[
["'a'", "string"],
["b", "keyword"],
],
],
[" [dependencies]", [["dependencies", "keyword"]]],
["[[bin]]", [["bin", "keyword"]]],
[
'[ "a b" . c ]',
[
['"a b"', "string"],
["c", "keyword"],
],
],
["x = [{}, 1]", [["1", "number"]]],
[
"x = [{ a = 1 }, { b = [2, { c = 3 }] }]",
[
["a", "keyword"],
["1", "number"],
["b", "keyword"],
["2", "number"],
["c", "keyword"],
["3", "number"],
],
],
[
'features = [\n "derive", # serde\n 1,\n]\nb = true',
[
['"derive"', "string"],
["# serde", "comment"],
["1", "number"],
["b", "keyword"],
["true", "builtin"],
],
],
// A nested array at column 0 is no table header.
[
"x = [\n[1],\n[true]\n]\ny = 2",
[
["1", "number"],
["true", "builtin"],
["y", "keyword"],
["2", "number"],
],
],
// An unclosed array while typing: the next key line starts over.
[
'deps = [\n[package]\nname = "x"',
[
["package", "keyword"],
["name", "keyword"],
['"x"', "string"],
],
],
[
'deps = [\nname = "x"',
[
["name", "keyword"],
['"x"', "string"],
],
],
// An unclosed single-line string ends with its line.
[
's = "abc\nk = 1',
[
['"abc', "string"],
["k", "keyword"],
["1", "number"],
],
],
] as Array<[string, Array<[string, string]>]>)("colours %j", (source, values) => {
const found = highlighted(source);
const key = source.match(/^[A-Za-z0-9_-]+(?= ?=)/)?.[0];
expect(found).toEqual(key ? [[key, "keyword"], ...values] : values);
});
});
+160
Переглянути файл
@@ -0,0 +1,160 @@
/**
* TOML coloured like IntelliJ's TOML plugin (TomlHighlighter, TomlHighlightingAnnotator): a bare
* key is KEYWORD wherever it stands (headers, dotted keys, inline tables), even when it reads as
* a number, date or boolean; booleans and dates are PREDEFINED_SYMBOL; escapes in basic strings
* are valid or invalid as in TomlEscapeLexer. `=`, brackets, `,` and `.` stay plain. Values
* follow the TOML 1.0 lexer (TomlLexer.flex), so a time needs its seconds.
*/
import type { StreamParser, StringStream } from "@codemirror/language";
type Delimiter = '"' | "'" | '"""' | "'''";
export interface TomlState {
/** The string being read; a multi-line one carries over to the next lines. */
string: Delimiter | null;
/** Open arrays and inline tables, innermost last. */
stack: Array<"array" | "inline">;
position: "key" | "value";
}
const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
const DOTTED_KEY = String.raw`${KEY_PART}(?:\s*\.\s*${KEY_PART})*`;
/** A key/value line ends a container left open by a typo; no valid array or inline table holds one. */
const NEW_ENTRY = new RegExp(String.raw`^\s*${DOTTED_KEY}\s*=`);
const BARE_KEY = /^[A-Za-z0-9_-]+/;
const DATE_TIME =
/^(?:\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?)?|\d{2}:\d{2}:\d{2}(?:\.\d+)?)(?:[Zz]|[+-]\d{2}:\d{2})?/;
const BOOLEAN = /^(?:true|false)/;
const DEC_INT = String.raw`[-+]?(?:0|[1-9](?:_?\d)*)`;
const DIGITS = String.raw`\d(?:_?\d)*`;
const NUMBERS = [
new RegExp(String.raw`^${DEC_INT}(?:[eE][-+]?${DIGITS}|\.${DIGITS}(?:[eE][-+]?${DIGITS})?)`),
/^[-+]?(?:inf|nan)/,
/^0x[0-9a-fA-F](?:_?[0-9a-fA-F])*/,
/^0o[0-7](?:_?[0-7])*/,
/^0b[01](?:_?[01])*/,
new RegExp(`^${DEC_INT}`),
// Leading zeros: a key in IntelliJ's lexer, a number where a value stands.
/^-?\d+/,
];
function matchLength(stream: StringStream, pattern: RegExp): number {
const match = stream.match(pattern, false) as RegExpMatchArray | null;
return match ? match[0].length : 0;
}
/**
* Numbers, dates and booleans by the longest match, as JFlex picks. A longer bare word is a
* bare key to IntelliJ's lexer, which colours it as one wherever it stands.
*/
function scalar(stream: StringStream): string | null {
const word = matchLength(stream, BARE_KEY);
const date = matchLength(stream, DATE_TIME);
const bool = matchLength(stream, BOOLEAN);
const number = Math.max(...NUMBERS.map((pattern) => matchLength(stream, pattern)));
const longest = Math.max(date, bool, number);
if (longest === 0 || longest < word) {
if (!word) {
stream.next();
return null;
}
stream.pos += word;
return "keyword";
}
stream.pos += longest;
return number === longest ? "number" : "builtin";
}
function isScalarValue(value: number): boolean {
return value <= 0xd7ff || (value >= 0xe000 && value <= 0x10ffff);
}
function escape(stream: StringStream, multiline: boolean): string {
stream.next();
// A line-ending backslash, whitespace after it allowed, trims the line break of a multi-line string.
if (multiline && stream.match(/^[ \t]*$/)) return "escape";
const ch = stream.next();
if (ch === undefined) return "invalid";
if (ch === "u" || ch === "U") {
const hex = stream.match(ch === "u" ? /^[0-9a-fA-F]{4}/ : /^[0-9a-fA-F]{8}/) as RegExpMatchArray | null;
return hex && isScalarValue(parseInt(hex[0], 16)) ? "escape" : "invalid";
}
return 'btnfr"\\'.includes(ch) ? "escape" : "invalid";
}
function stringBody(stream: StringStream, state: TomlState): string {
const delimiter = state.string!;
const quote = delimiter.charAt(0);
const basic = quote === '"';
if (basic && stream.peek() === "\\") return escape(stream, delimiter === '"""');
while (!stream.eol()) {
if (basic && stream.peek() === "\\") return "string";
if (stream.match(delimiter)) {
// A multi-line string may end in up to two quotes of its own right before the closing three.
if (delimiter.length === 3) for (let i = 0; i < 2 && stream.eat(quote); i++);
state.string = null;
return "string";
}
stream.next();
}
if (delimiter.length === 1) state.string = null;
return "string";
}
function openString(stream: StringStream, state: TomlState): boolean {
const quote = stream.match(/^(?:"""|'''|"|')/) as RegExpMatchArray | null;
if (quote) state.string = quote[0] as Delimiter;
return quote !== null;
}
export const tomlParser: StreamParser<TomlState> = {
name: "toml",
startState: () => ({ string: null, stack: [], position: "key" }),
token(stream, state) {
if (stream.sol()) {
if (state.string === '"' || state.string === "'") state.string = null;
if (!state.string && (!state.stack.length || NEW_ENTRY.test(stream.string))) {
state.stack = [];
state.position = "key";
}
}
if (state.string) return stringBody(stream, state);
if (stream.eatSpace()) return null;
if (stream.peek() === "#") {
stream.skipToEnd();
return "comment";
}
if (openString(stream, state)) return "string";
const top = state.stack[state.stack.length - 1];
if (state.position === "key") {
if (stream.match(BARE_KEY)) return "keyword";
const ch = stream.next();
if (ch === "=") state.position = "value";
else if (ch === "}" && top === "inline") {
state.stack.pop();
state.position = "value";
}
return null;
}
const ch = stream.peek();
if (ch === "[" || ch === "{") {
stream.next();
state.stack.push(ch === "[" ? "array" : "inline");
if (ch === "{") state.position = "key";
return null;
}
if (ch === "]" || ch === "}") {
stream.next();
if (top === (ch === "]" ? "array" : "inline")) state.stack.pop();
return null;
}
if (ch === ",") {
stream.next();
if (top === "inline") state.position = "key";
return null;
}
return scalar(stream);
},
languageData: { commentTokens: { line: "#" } },
};
+321
Переглянути файл
@@ -0,0 +1,321 @@
/**
* Typst markup, code and math as Typst's own lexer splits them (typst-syntax `lexer.rs`): markup
* with `#` embedding a code expression, `[...]` content blocks and `$...$` math nesting in code
* and back. A `#keyword` statement lasts to the end of its line unless a bracket keeps it open.
*/
import type { StreamParser, StringStream } from "@codemirror/language";
type Frame =
/** Markup inside `[...]`; the document itself is the markup below every frame. */
| { kind: "content" }
/** Code in `(...)` or `{...}`, closed by `close`. */
| { kind: "code"; close: ")" | "}" }
/** A `#let` / `#set` / `#show` … statement, ending with its line. */
| { kind: "statement" }
/** An embedded `#name`: calls, content arguments and field accesses may follow it directly. */
| { kind: "expr" }
| { kind: "math" };
export interface TypstState {
stack: Frame[];
strong: boolean;
emph: boolean;
heading: boolean;
/** Nesting depth of an open block comment. */
comment: number;
/** The backtick fence of an open raw block. */
raw: string | null;
}
const KEYWORDS = new Set([
"let",
"set",
"show",
"context",
"if",
"else",
"for",
"in",
"while",
"break",
"continue",
"return",
"import",
"include",
"as",
"and",
"or",
"not",
]);
const ATOMS = new Set(["none", "auto", "true", "false"]);
const IDENT = /^[\p{L}_][\p{L}\p{N}_-]*/u;
const NUMBER = /^(?:0x[0-9a-fA-F]+|0o[0-7]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?(?:pt|mm|cm|in|em|fr|deg|rad|%)?)/;
const LABEL = /^<[\p{L}\p{N}_\-.:]+>/u;
const REF = /^@[\p{L}\p{N}_\-.:]*[\p{L}\p{N}_]/u;
const URL = /^https?:\/\/[^\s<>[\](){}"]*[^\s<>[\](){}".,;:!?'"]/;
const MARKUP_TEXT = /^[^\\#$*_`<@/[\]\nhH-]+/;
const top = (state: TypstState): Frame | undefined => state.stack[state.stack.length - 1];
function blockComment(stream: StringStream, state: TypstState): string {
while (!stream.eol()) {
if (stream.match("/*")) state.comment++;
else if (stream.match("*/")) {
if (--state.comment === 0) break;
} else stream.next();
}
return "comment";
}
function comment(stream: StringStream, state: TypstState): string | null {
if (stream.match("//")) {
stream.skipToEnd();
return "comment";
}
if (stream.match("/*")) {
state.comment = 1;
return blockComment(stream, state);
}
return null;
}
function string(stream: StringStream): string {
stream.next();
let escaped = false;
for (let ch = stream.next(); ch !== undefined; ch = stream.next()) {
if (ch === '"' && !escaped) break;
escaped = !escaped && ch === "\\";
}
return "string";
}
function raw(stream: StringStream, state: TypstState): string {
const fence = (stream.match(/^`+/) as RegExpMatchArray)[0];
if (fence.length === 2) return "monospace";
if (fence.length >= 3) {
state.raw = fence;
if (!stream.match(/^[\p{L}\p{N}_-]+/u)) return rawBody(stream, state);
return "monospace";
}
while (!stream.eol()) if (stream.next() === "`") break;
return "monospace";
}
function rawBody(stream: StringStream, state: TypstState): string {
const fence = state.raw!;
while (!stream.eol()) {
if (stream.match(fence)) {
state.raw = null;
break;
}
stream.next();
}
return "monospace";
}
/** `#` followed by a keyword, a name, or a bracketed expression. */
function embed(stream: StringStream, state: TypstState): string {
stream.next();
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word && KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
state.stack.push({ kind: "statement" });
return "keyword";
}
if (word) {
state.stack.push({ kind: "expr" });
return name(stream);
}
const ch = stream.peek();
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "keyword";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "keyword";
}
if (ch === '"') return string(stream);
return "keyword";
}
/** An identifier: a function when a call or content block follows, a value otherwise. */
function name(stream: StringStream): string {
const word = (stream.match(IDENT) as RegExpMatchArray)[0];
if (ATOMS.has(word)) return "atom";
const next = stream.peek();
return next === "(" || next === "[" ? "variableName.function" : "variableName";
}
function code(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === '"') return string(stream);
if (ch === "$") {
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
}
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
const frame = top(state);
if (ch === ")" || ch === "}") {
stream.next();
if (frame?.kind === "code" && frame.close === ch) state.stack.pop();
return "bracket";
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(NUMBER)) return "number";
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word) {
if (KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
return "keyword";
}
return name(stream);
}
if (stream.match(/^(?:=>|==|!=|<=|>=|\+=|-=|\*=|\/=|\.\.|[-+*/=<>.:,;!])/)) return "operator";
stream.next();
return null;
}
/** What may directly follow an embedded name: `(args)`, `[content]` or `.field`. */
function exprTail(stream: StringStream, state: TypstState): string | null | undefined {
const ch = stream.peek();
if (ch === "(") {
stream.next();
state.stack.push({ kind: "code", close: ")" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
if (ch === "." && stream.match(/^\.(?=[\p{L}_])/u, false)) {
stream.next();
return name(stream);
}
state.stack.pop();
return undefined;
}
function math(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === "$") {
stream.next();
state.stack.pop();
return "keyword";
}
if (ch === "#") return embed(stream, state);
if (ch === "\\") {
stream.next();
stream.next();
return "escape";
}
if (ch === '"') return string(stream);
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
if (stream.match(/^[\p{L}][\p{L}.]+/u)) return "variableName";
if (stream.match(/^[\^_/&=<>+\-*|!']/)) return "operator";
stream.next();
return null;
}
function markup(stream: StringStream, state: TypstState): string | null {
const inline = (style: string | null): string | null => {
const extra = [state.heading && "heading", state.strong && "strong", state.emph && "emphasis"].filter(Boolean);
return [...new Set([style, ...extra].filter(Boolean))].join(" ") || null;
};
if (stream.sol()) {
state.heading = false;
if (stream.match(/^\s*=+(?=\s|$)/)) {
state.heading = true;
return "heading";
}
if (stream.match(/^\s*(?:[-+]|\d+\.)(?=\s|$)/) || stream.match(/^\s*\/(?=\s)/)) return "list";
}
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
switch (ch) {
case "#":
return embed(stream, state);
case "$":
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
case "`":
return raw(stream, state);
case "\\":
stream.next();
if (!stream.match(/^u\{[0-9a-fA-F]+\}/)) stream.next();
return "escape";
case "]":
stream.next();
if (top(state)?.kind === "content") state.stack.pop();
return "bracket";
case "*":
case "_": {
// Inside a word, `*` and `_` are text (`snake_case`, `2*3`).
const before = stream.string.charAt(stream.pos - 1);
const after = stream.string.charAt(stream.pos + 1);
stream.next();
if (/[\p{L}\p{N}]/u.test(before) && /[\p{L}\p{N}]/u.test(after)) return inline(null);
if (ch === "*") state.strong = !state.strong;
else state.emph = !state.emph;
return inline(ch === "*" ? "strong" : "emphasis");
}
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(REF)) return "labelName";
if (stream.match(URL)) return "url";
if (stream.match(/^\/ (?=[^:]*:)/) || stream.match(/^-{2,3}|^~/)) return inline(null);
if (!stream.match(MARKUP_TEXT)) stream.next();
return inline(null);
}
export const typstParser: StreamParser<TypstState> = {
name: "typst",
startState: () => ({ stack: [], strong: false, emph: false, heading: false, comment: 0, raw: null }),
copyState: (state) => ({ ...state, stack: state.stack.slice() }),
blankLine(state) {
state.strong = state.emph = false;
},
token(stream, state) {
if (state.comment) return blockComment(stream, state);
if (state.raw) return rawBody(stream, state);
let style: string | null | undefined;
do {
const frame = top(state);
if (frame?.kind === "expr") style = exprTail(stream, state);
else if (frame?.kind === "code" || frame?.kind === "statement") style = code(stream, state);
else if (frame?.kind === "math") style = math(stream, state);
else style = markup(stream, state);
} while (style === undefined);
// A statement ends with its line once its brackets are closed.
if (stream.eol()) {
while (top(state)?.kind === "expr") state.stack.pop();
if (top(state)?.kind === "statement") state.stack.pop();
}
return style;
},
languageData: {
commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
closeBrackets: { brackets: ["(", "[", "{", '"', "$"] },
},
};
+29
Переглянути файл
@@ -1,4 +1,6 @@
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { findLanguageDescription, loadSupport } from "./languages";
describe("vue language mode", () => {
@@ -23,4 +25,31 @@ describe("vue language mode", () => {
expect(tree).toContain("Declaration");
expect(tree).not.toContain("SassVariableName");
});
it("indents the top-level <template>'s children only, not <script setup> or <style> code", async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const doc = [
"<template>",
"<div>",
"</div>",
"</template>",
'<script setup lang="ts">',
"const a = 1",
"function f() {",
"return a",
"}",
"</script>",
"<style>",
".a { color: red; }",
"</style>",
].join("\n");
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect(indent(2)).toBe(2);
expect(indent(6)).toBe(0);
expect(indent(7)).toBe(0);
expect(indent(8)).toBe(2);
expect(indent(10)).toBe(0);
expect(indent(12)).toBe(0);
});
});
+28 -14
Переглянути файл
@@ -4,24 +4,38 @@
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
* colours.
*/
import { LanguageSupport } from "@codemirror/language";
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
/**
* WebStorm's Vue code style indents the children of the top-level `<template>` only: code in
* `<script setup>` or `<style>` starts at the margin, as `npm create vue` writes it.
*/
function elementIndent(context: TreeIndentContext): number | null {
const after = /^(\s*)(<\/)?/.exec(context.textAfter)!;
const node = context.node;
if (node.to <= context.pos + after[0].length) return context.continue();
const tag = node.firstChild?.getChild("TagName");
const flat =
node.parent?.name === "Document" && !!tag && context.state.sliceDoc(tag.from, tag.to).toLowerCase() !== "template";
return context.lineIndent(node.from) + (after[2] || flat ? 0 : context.unit);
}
export function vueLanguage(): LanguageSupport {
return vue({
base: html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
],
}),
const base = html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
],
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
return vue({ base: new LanguageSupport(language, base.support) });
}
+12
Переглянути файл
@@ -154,6 +154,18 @@ describe("editor Copy Path/Reference chooser", () => {
expect(writeText).toHaveBeenCalledExactlyOnceWith(path);
});
it("copies a selection over several lines as path:first-last", async () => {
const view = ctrl.activeSlot!.view!;
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
await executeAction("editor.copyPathReference");
const item = popup().items.find((item) => item.id === "editor.copyPathWithLineNumber")!;
expect(item.preview).toBe("src/A.java:1-2");
// A selection that ends at the start of a line leaves that line out.
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
await executeAction("editor.copyPathWithLineNumber");
await vi.waitFor(() => expect(writeText).toHaveBeenLastCalledWith("src/A.java:1"));
});
it("uses path:line off a symbol and ignores stale reference resolution", async () => {
ctrl.activeSlot!.view!.dispatch({ selection: { anchor: documentText.length - 1 } });
await executeAction("editor.copyPathReference");
+12
Переглянути файл
@@ -4,6 +4,7 @@ import { EditorView } from "@codemirror/view";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { useProject } from "@/platform/project";
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
const zoomOf = (view: EditorView) => view.state.field(fontZoom, false);
@@ -19,6 +20,7 @@ describe("editor font zoom (active editor by default, all editors when configure
return view;
};
beforeEach(() => {
resetWheelZoomGesture();
resetAllEditorsFontZoom();
useProject.setState({ settings: null });
});
@@ -45,6 +47,16 @@ describe("editor font zoom (active editor by default, all editors when configure
expect(zoomOf(second)).toBe(-1);
});
it("doesn't zoom from the inertia of a scroll when ⌘/Ctrl is pressed during it", () => {
const view = makeView();
const plain = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -40 });
view.contentDOM.dispatchEvent(plain);
const coasting = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -20 });
view.contentDOM.dispatchEvent(coasting);
expect(coasting.defaultPrevented).toBe(false);
expect(zoomOf(view)).toBe(0);
});
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
const first = makeView();
+6 -3
Переглянути файл
@@ -290,11 +290,14 @@
.docBody {
padding: 10px 14px;
}
/* Go signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts). */
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName) {
/* Signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts); other
languages' names look like links once they are found to lead somewhere. */
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName),
.docBody :global(.cm-lsp-markdown [data-doc-ref]) {
cursor: pointer;
}
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover) {
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover),
.docBody :global(.cm-lsp-markdown [data-doc-ref]:hover) {
text-decoration: underline;
}
.defPopup {
+72
Переглянути файл
@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from "vitest";
import type { Location, Pos } from "@/bindings";
const at = (path: string, line: number, col = 0): Location => ({
path,
range: { start: { line, col }, end: { line, col } },
});
const LIB = "/w/src/lib.rs";
const files: Record<string, string[]> = {
[LIB]: [
"use crate::model::Item;",
"",
"/// Takes the items.",
"pub fn take(items: Vec<Item>,",
" on: Clock) -> Inventory { // an Order list",
" Order::all(items)",
"}",
],
"/w/src/c.ts": ["/** Note: Item is re-read. */", "export function f(x: Item): void {}"],
};
// What the server answers per `path:line:col`.
const defs: Record<string, Location[]> = {
[`${LIB}:3:7`]: [at(LIB, 3, 7)], // take
[`${LIB}:3:12`]: [at(LIB, 3, 12)], // items: the parameter
[`${LIB}:3:19`]: [at("/rust/library/alloc/src/vec/mod.rs", 396, 11)], // Vec
[`${LIB}:3:23`]: [at("/w/src/model.rs", 4, 11)], // Item
[`${LIB}:4:8`]: [at("/w/src/clock.rs", 1, 11), at("/w/src/clock2.rs", 1, 11)], // Clock: two places
[`${LIB}:4:18`]: [at("/w/src/inventory.rs", 2, 11)], // Inventory
[`${LIB}:5:4`]: [at("/w/src/order.rs", 2, 11)], // Order, in the body
"/w/src/c.ts:1:21": [at("/w/src/item.ts", 0, 17)], // Item; the comment's has no definition
};
let file = "";
vi.mock("../files", () => ({
readFileLines: async (p: string) => files[p] ?? null,
withDocument: async <T>(p: string, fn: (doc: number) => Promise<T>) => ((file = p), fn(1)),
}));
vi.mock("../lsp", () => ({ lspRequest: <T>(run: () => Promise<T>) => run() }));
vi.mock("@/platform/ipc", () => ({
commands: { lspGoto: async (_doc: number, pos: Pos) => defs[`${file}:${pos.line}:${pos.col}`] ?? [] },
}));
const { signatureNameTarget } = await import("./signature");
describe("names in a signature", () => {
it.each([
["a type from another file", "Item", { path: "/w/src/model.rs", line: 4, col: 11 }],
["a library type", "Vec", { path: "/rust/library/alloc/src/vec/mod.rs", line: 396, col: 11 }],
["a wrapped parameter's type", "Inventory", { path: "/w/src/inventory.rs", line: 2, col: 11 }],
["a parameter", "items", null],
["the symbol itself", "take", null],
["defined in two places", "Clock", null],
["inferred: not in the source", "Option", null],
["not a name", "a.b", null],
])("%s", async (_, name, want) => {
expect(await signatureNameTarget(at(LIB, 3, 7), name, 1)).toEqual(want);
});
it("asks only near the declaration", async () => {
expect(await signatureNameTarget(at(LIB, 3, 7), "Order", 1)).toEqual({ path: "/w/src/order.rs", line: 2, col: 11 });
expect(await signatureNameTarget(at(LIB, 0, 0), "Order", -9)).toBeNull();
});
it("skips an occurrence the server has no definition for (a comment)", async () => {
expect(await signatureNameTarget(at("/w/src/c.ts", 0), "Item", 1)).toEqual({
path: "/w/src/item.ts",
line: 0,
col: 17,
});
});
});
+40
Переглянути файл
@@ -0,0 +1,40 @@
/**
* Names in a signature, for languages without their own rule (Go has `go.ts`): the name is
* looked up in the documented symbol's declaration, in its source, and the language server's
* definition of it there is the target. A name the source doesn't spell (an inferred type)
* or one declared by the declaration itself (a parameter, a type parameter, the symbol's own
* name) leads nowhere; so does a definition the server finds in several places.
*/
import { commands, type Location } from "@/platform/ipc";
import { readFileLines, withDocument } from "../files";
import { lspRequest } from "../lsp";
import { unique, type DocTarget } from "./symbols";
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
/** Lines the declaration may take in its source beyond the signature's own (wrapped parameters, attributes). */
const SLACK = 10;
/** Where `name`, written in the signature (`lines` long) of the symbol declared at `decl`, is declared. */
export async function signatureNameTarget(decl: Location, name: string, lines: number): Promise<DocTarget | null> {
if (!NAME.test(name)) return null;
const text = await readFileLines(decl.path).catch(() => null);
if (!text) return null;
const first = decl.range.start.line;
const last = Math.min(text.length, first + lines + SLACK);
// A preceding non-name character, not a lookbehind: WebKit before 16.4 can't parse one.
const word = new RegExp(`(^|[^\\p{L}\\p{N}_$])${name.replace(/\$/g, "\\$")}(?![\\p{L}\\p{N}_$])`, "gu");
const inside = (l: Location) => l.path === decl.path && l.range.start.line >= first && l.range.start.line < last;
return withDocument(decl.path, async (doc) => {
for (let line = first; line < last; line++) {
for (const m of text[line]!.matchAll(word)) {
const locs = await lspRequest(() =>
commands.lspGoto(doc, { line, col: m.index + m[1]!.length }, "definition"),
).catch(() => []);
// Nothing here: a comment or a string; the next occurrence may be the name itself.
if (!locs.length) continue;
return locs.some(inside) ? null : unique(locs.map((location) => ({ location })));
}
}
return null;
});
}
+2 -2
Переглянути файл
@@ -1,5 +1,5 @@
/** `workspace/symbol` lookups shared by the per-language documentation link rules. */
import { call, commands, nextRequestId, type WorkspaceSymbol } from "@/platform/ipc";
import { call, commands, nextRequestId, type Location, type WorkspaceSymbol } from "@/platform/ipc";
export interface DocTarget {
path: string;
@@ -12,7 +12,7 @@ export async function symbols(query: string): Promise<WorkspaceSymbol[]> {
}
/** The one place `hits` name (the same place listed twice counts once); null when none or several. */
export function unique(hits: WorkspaceSymbol[]): DocTarget | null {
export function unique(hits: { location: Location }[]): DocTarget | null {
const places = new Map(
hits.map((s) => {
const { path, range } = s.location;
+49
Переглянути файл
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
const signatureNameTarget = vi.fn(async (_decl: unknown, name: string, _lines: number) =>
name === "Item" ? { path: "/w/src/model.rs", line: 4, col: 11 } : null,
);
vi.mock("./docLinks/signature", () => ({ signatureNameTarget }));
const { linkSignatureTypes } = await import("./docs");
describe("signature names", () => {
it("resolve in the signature blocks only, and look like links once they lead somewhere", async () => {
const dom = document.createElement("div");
// rust-analyzer: module path, signature, rule, docs with an example.
dom.innerHTML =
'<pre><code class="language-rust">inventory</code></pre>' +
'<pre><code class="language-rust">pub fn take(<span class="tok-variableName tok-definition">items</span>: ' +
'<span class="tok-typeName">Vec</span>&lt;<span class="tok-typeName">Item</span>&gt;)</code></pre>' +
'<hr><p>Takes them.</p><pre><code class="language-rust"><span class="tok-typeName">Item</span></code></pre>';
const decl = { path: "/w/src/lib.rs", range: { start: { line: 3, col: 7 }, end: { line: 3, col: 11 } } };
linkSignatureTypes(dom, "window", {
markup: { kind: "markdown", value: "" },
language: null,
source: async () => decl,
});
const [items, vec, item, example] = [...dom.querySelectorAll("span")];
for (const el of [items!, vec!, item!, example!]) fireEvent.mouseOver(el);
await vi.waitFor(() => expect(item!.hasAttribute("data-doc-ref")).toBe(true));
expect(vec!.hasAttribute("data-doc-ref")).toBe(false);
expect(signatureNameTarget.mock.calls.map((c) => c[1])).toEqual(["Vec", "Item"]);
expect(signatureNameTarget).toHaveBeenCalledWith(decl, "Item", 1);
});
it("include the block closing the documentation after a rule (clangd)", async () => {
signatureNameTarget.mockClear();
const dom = document.createElement("div");
dom.innerHTML =
"<h3>function take</h3><hr><p>Takes them.</p><hr>" +
'<pre><code class="language-cpp">void take(<span class="tok-typeName">Item</span> i)</code></pre>';
const decl = { path: "/w/take.cpp", range: { start: { line: 1, col: 5 }, end: { line: 1, col: 9 } } };
linkSignatureTypes(dom, "window", {
markup: { kind: "markdown", value: "" },
language: null,
source: async () => decl,
});
fireEvent.mouseOver(dom.querySelector("span")!);
await vi.waitFor(() => expect(dom.querySelector("[data-doc-ref]")?.textContent).toBe("Item"));
});
});
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more