дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 20:46:22 +02:00
Порівняти коміти
17
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
60c6f49701 | ||
|
|
66c36a7361 | ||
|
|
8daeb21005 | ||
|
|
44b2d11b2d | ||
|
|
f8b3ef6840 | ||
|
|
55836e1b49 | ||
|
|
a94b4bff42 | ||
|
|
3193fd583f | ||
|
|
995ea886ab | ||
|
|
630d436e18 | ||
|
|
a61a89fe86 | ||
|
|
50212e7397 | ||
|
|
08fd134bdb | ||
|
|
ecb3134460 | ||
|
|
5b63a2b95c | ||
|
|
ac426c8881 | ||
|
|
eef24ea785 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Repository-wide oxfmt formatting (#135)
|
||||
55836e1b4961c9d87df8503ec374e624c81d6bf6
|
||||
@@ -81,6 +81,7 @@ jobs:
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
- run: pnpm format:check
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
|
||||
|
||||
+18
-1
@@ -5,5 +5,22 @@
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all",
|
||||
"sortPackageJson": false,
|
||||
"ignorePatterns": ["dist", "target", "src/bindings.ts", "pnpm-lock.yaml", "**/*.toml"]
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"target",
|
||||
"src/bindings.ts",
|
||||
"docs/plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"crates/**/tests/fixtures"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.md"],
|
||||
"options": {
|
||||
"embeddedLanguageFormatting": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Створено
+33
-33
@@ -3974,7 +3974,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -3992,7 +3992,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4006,7 +4006,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4021,11 +4021,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4038,7 +4038,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4052,7 +4052,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4069,7 +4069,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4088,7 +4088,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4102,7 +4102,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4116,7 +4116,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4157,7 +4157,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4175,7 +4175,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4197,7 +4197,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4213,7 +4213,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4267,7 +4267,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4290,7 +4290,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4308,7 +4308,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4321,7 +4321,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4338,7 +4338,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4358,7 +4358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4377,7 +4377,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4397,7 +4397,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4410,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4429,7 +4429,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4457,7 +4457,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4469,7 +4469,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4489,7 +4489,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4506,7 +4506,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4527,7 +4527,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4543,7 +4543,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5968,7 +5968,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.21"
|
||||
version = "0.1.22"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+8
-8
@@ -30,14 +30,14 @@ for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~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 |
|
||||
| | 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 |
|
||||
|
||||
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
|
||||
Windows 11, 32-core AMD, 62 GB RAM.
|
||||
|
||||
@@ -116,7 +116,7 @@ Apache License
|
||||
|
||||
Version 2.0, January 2004
|
||||
|
||||
http://www.apache.org/licenses/
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
@@ -251,7 +251,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
```
|
||||
|
||||
|
||||
## Chinese UI terminology from Visual Studio Code
|
||||
|
||||
Some Simplified Chinese terms in `src/platform/locales/text/zh.json` follow the
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! A task's conversation and those of its subagents.
|
||||
//!
|
||||
//! An agent that supports ACP subagent sessions runs each subagent (Claude Code's Agent
|
||||
//! tool, Codex's spawned agents) as a child session: `subagent_update` on the parent
|
||||
//! announces it and reports its state, its own updates carry its session id, and
|
||||
//! `session_message`s carry what it was asked and what it answered. The parent's
|
||||
//! timeline shows a card per subagent; each subagent keeps its own timeline.
|
||||
|
||||
use crate::model::AgentEntry;
|
||||
use crate::timeline::{Timeline, blocks_text, content_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
|
||||
pub(crate) type Session = Option<String>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Conversation {
|
||||
pub main: Timeline,
|
||||
/// In the order they started.
|
||||
subagents: Vec<Subagent>,
|
||||
}
|
||||
|
||||
struct Subagent {
|
||||
id: String,
|
||||
/// The session that started it.
|
||||
parent: Session,
|
||||
timeline: Timeline,
|
||||
}
|
||||
|
||||
/// A subagent's conversation, as saved with its task.
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct SavedSubagent {
|
||||
pub id: String,
|
||||
pub parent: Option<String>,
|
||||
pub entries: Vec<AgentEntry>,
|
||||
}
|
||||
|
||||
impl Conversation {
|
||||
pub fn restore(main: Vec<AgentEntry>, subagents: Vec<SavedSubagent>) -> Self {
|
||||
Self {
|
||||
main: Timeline::from_entries(main),
|
||||
subagents: subagents
|
||||
.into_iter()
|
||||
.map(|s| Subagent { id: s.id, parent: s.parent, timeline: Timeline::from_entries(s.entries) })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn saved_subagents(&self) -> Vec<SavedSubagent> {
|
||||
self.subagents
|
||||
.iter()
|
||||
.map(|s| SavedSubagent { id: s.id.clone(), parent: s.parent.clone(), entries: s.timeline.entries.clone() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn timeline(&self, session: &Session) -> Option<&Timeline> {
|
||||
match session {
|
||||
None => Some(&self.main),
|
||||
Some(id) => self.subagents.iter().find(|s| &s.id == id).map(|s| &s.timeline),
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline_mut(&mut self, session: &Session) -> Option<&mut Timeline> {
|
||||
match session {
|
||||
None => Some(&mut self.main),
|
||||
Some(id) => self.subagents.iter_mut().find(|s| &s.id == id).map(|s| &mut s.timeline),
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_of(&self, id: &str) -> Option<&Session> {
|
||||
self.subagents.iter().find(|s| s.id == id).map(|s| &s.parent)
|
||||
}
|
||||
|
||||
/// The session an update for session id `session` belongs to: a known subagent's, else the task's.
|
||||
pub fn owner(&self, session: Option<&str>) -> Session {
|
||||
session.filter(|s| self.parent_of(s).is_some()).map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The parent's title (or description) for subagent `id`.
|
||||
pub fn label(&self, id: &str) -> Option<String> {
|
||||
let parent = self.parent_of(id)?;
|
||||
self.timeline(parent)?.entries.iter().find_map(|e| match e {
|
||||
AgentEntry::Subagent { id: card, title, description, .. } if card == id => {
|
||||
title.clone().or_else(|| description.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies one `session/update` of session id `session` (the task's own when unknown);
|
||||
/// returns the entries it added or changed.
|
||||
pub fn apply(&mut self, session: Option<&str>, update: &Value, now: f64) -> Vec<(Session, usize)> {
|
||||
let owner = self.owner(session);
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
match kind {
|
||||
"subagent_update" => {
|
||||
let Some(id) = update.get("sessionId").and_then(Value::as_str) else { return out };
|
||||
if self.parent_of(id).is_none() {
|
||||
self.subagents.push(Subagent { id: id.to_owned(), parent: owner, timeline: Timeline::default() });
|
||||
}
|
||||
let parent = self.parent_of(id).cloned().flatten();
|
||||
let Some(timeline) = self.timeline_mut(&parent) else { return out };
|
||||
let (index, stopped) = timeline.subagent(id, update, now);
|
||||
out.push((parent, index));
|
||||
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
|
||||
let id = Some(id.to_owned());
|
||||
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
}
|
||||
"session_message" | "session_message_chunk" => {
|
||||
let append = kind == "session_message_chunk";
|
||||
let text = if append {
|
||||
content_text(update.get("content")).unwrap_or_default()
|
||||
} else {
|
||||
blocks_text(update.get("content"))
|
||||
};
|
||||
let field = |k: &str| update.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
let (sender, recipient) = (field("senderSessionId"), field("recipientSessionId"));
|
||||
let ours =
|
||||
|s: &Option<String>| s.as_deref().filter(|s| self.parent_of(s) == Some(&owner)).map(str::to_owned);
|
||||
// Between this session and a subagent of it: the subagent's task or answer, on its card.
|
||||
let card = ours(&recipient).map(|c| (c, false)).or_else(|| ours(&sender).map(|c| (c, true)));
|
||||
let Some(timeline) = self.timeline_mut(&owner) else { return out };
|
||||
let index = match card {
|
||||
Some((child, reply)) => timeline.card_message(&child, reply, &text, append),
|
||||
None => {
|
||||
let id = field("messageId").unwrap_or_default();
|
||||
Some(timeline.message(&id, sender != owner, &text, append))
|
||||
}
|
||||
};
|
||||
out.extend(index.map(|i| (owner, i)));
|
||||
}
|
||||
_ => {
|
||||
let Some(timeline) = self.timeline_mut(&owner) else { return out };
|
||||
out.extend(timeline.apply(update).changed.into_iter().map(|i| (owner.clone(), i)));
|
||||
if let Some(id) = owner.as_deref()
|
||||
&& matches!(kind, "tool_call" | "tool_call_update")
|
||||
{
|
||||
out.extend(self.refresh_card(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Updates subagent `id`'s card from its timeline.
|
||||
fn refresh_card(&mut self, id: &str) -> Option<(Session, usize)> {
|
||||
let parent = self.parent_of(id)?.clone();
|
||||
let child = self.subagents.iter().position(|s| s.id == id)?;
|
||||
let timeline = std::mem::take(&mut self.subagents[child].timeline);
|
||||
let changed = self.timeline_mut(&parent).and_then(|p| p.card_activity(id, &timeline));
|
||||
self.subagents[child].timeline = timeline;
|
||||
changed.map(|i| (parent, i))
|
||||
}
|
||||
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
|
||||
}
|
||||
|
||||
/// Settles everything left open once the agent is gone, subagents included.
|
||||
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
|
||||
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
|
||||
for s in &mut self.subagents {
|
||||
let id = Some(s.id.clone());
|
||||
let mut changed = s.timeline.end_turn(None);
|
||||
changed.extend(s.timeline.stop_subagents(now));
|
||||
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{AgentSubagentStatus, AgentToolStatus};
|
||||
use serde_json::json;
|
||||
|
||||
fn card(c: &Conversation, session: &Session, index: usize) -> AgentEntry {
|
||||
c.timeline(session).unwrap().entries[index].clone()
|
||||
}
|
||||
|
||||
/// Claude Code's Agent tool, as `claude-agent-acp` reports it to a client with subagent sessions.
|
||||
#[test]
|
||||
fn a_subagent_gets_a_card_in_its_parent_and_its_own_timeline() {
|
||||
let mut c = Conversation::default();
|
||||
let sub = Some("child".to_owned());
|
||||
let announce = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "title": "Explore",
|
||||
"description": "Find the parser", "capabilities": {"cancel": {}}, "state": {"state": "running"}});
|
||||
assert_eq!(c.apply(Some("root"), &announce, 10.0), vec![(None, 0)]);
|
||||
// The launch prompt: the parent's outgoing view, then the child's incoming one.
|
||||
let prompt = json!({"sessionUpdate": "session_message", "messageId": "toolu_1",
|
||||
"senderSessionId": "root", "recipientSessionId": "child",
|
||||
"content": [{"type": "text", "text": "Look for it"}]});
|
||||
assert_eq!(c.apply(Some("root"), &prompt, 11.0), vec![(None, 0)]);
|
||||
assert_eq!(c.apply(Some("child"), &prompt, 11.0), vec![(sub.clone(), 0)]);
|
||||
assert_eq!(card(&c, &sub, 0), AgentEntry::Message { incoming: true, text: "Look for it".into() });
|
||||
|
||||
// The child's own work stays out of the parent's timeline; its card follows it.
|
||||
c.apply(
|
||||
Some("child"),
|
||||
&json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "hm"}}),
|
||||
12.0,
|
||||
);
|
||||
let changed = c.apply(
|
||||
Some("child"),
|
||||
&json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read lib.rs", "kind": "read", "status": "in_progress"}),
|
||||
12.0,
|
||||
);
|
||||
assert_eq!(changed, vec![(sub.clone(), 2), (None, 0)]);
|
||||
assert_eq!(c.main.entries.len(), 1);
|
||||
// Settings of the child session don't touch the task.
|
||||
assert_eq!(c.owner(Some("child")), sub);
|
||||
assert_eq!(c.owner(Some("root")), None);
|
||||
|
||||
let done = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "state": {"state": "idle", "stopReason": "end_turn"}});
|
||||
let changed = c.apply(Some("root"), &done, 20.0);
|
||||
// Its tool calls left open are settled when it stops.
|
||||
assert_eq!(changed, vec![(None, 0), (sub.clone(), 2)]);
|
||||
let reply = json!({"sessionUpdate": "session_message", "messageId": "toolu_1:reply", "senderSessionId": "child",
|
||||
"recipientSessionId": "root", "content": [{"type": "text", "text": "In "}, {"type": "text", "text": "parser.rs"}]});
|
||||
c.apply(Some("root"), &reply, 20.0);
|
||||
assert_eq!(
|
||||
c.main.entries[0],
|
||||
AgentEntry::Subagent {
|
||||
id: "child".into(),
|
||||
title: Some("Explore".into()),
|
||||
description: Some("Find the parser".into()),
|
||||
status: AgentSubagentStatus::Done,
|
||||
error: None,
|
||||
prompt: Some("Look for it".into()),
|
||||
reply: Some("In \nparser.rs".into()),
|
||||
tools: 1,
|
||||
activity: Some("Read lib.rs".into()),
|
||||
started_ms: 10.0,
|
||||
ended_ms: Some(20.0),
|
||||
cancellable: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(c.label("child").as_deref(), Some("Explore"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_subagents_and_failures() {
|
||||
let mut c = Conversation::default();
|
||||
c.apply(
|
||||
None,
|
||||
&json!({"sessionUpdate": "subagent_update", "sessionId": "a", "state": {"state": "running"}}),
|
||||
1.0,
|
||||
);
|
||||
c.apply(
|
||||
Some("a"),
|
||||
&json!({"sessionUpdate": "subagent_update", "sessionId": "b", "description": "deeper"}),
|
||||
2.0,
|
||||
);
|
||||
let a = Some("a".to_owned());
|
||||
assert!(matches!(card(&c, &a, 0), AgentEntry::Subagent { ref id, .. } if id == "b"));
|
||||
let failed = json!({"sessionUpdate": "subagent_update", "sessionId": "b",
|
||||
"state": {"state": "idle", "stopReason": "error", "error": {"code": -32603, "message": "boom"}}});
|
||||
assert_eq!(c.apply(Some("a"), &failed, 3.0), vec![(a.clone(), 0)]);
|
||||
assert!(matches!(card(&c, &a, 0),
|
||||
AgentEntry::Subagent { status: AgentSubagentStatus::Failed, error: Some(ref e), ended_ms: Some(3.0), .. } if e == "boom"));
|
||||
|
||||
// Saved and restored, then the agent is gone: what still works is stopped.
|
||||
let mut c = Conversation::restore(c.main.entries.clone(), c.saved_subagents());
|
||||
c.apply(
|
||||
Some("a"),
|
||||
&json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Run", "status": "in_progress"}),
|
||||
4.0,
|
||||
);
|
||||
let settled = c.settle(9.0);
|
||||
assert_eq!(settled, vec![(None, 0), (a.clone(), 1)]);
|
||||
assert!(matches!(c.main.entries[0], AgentEntry::Subagent { status: AgentSubagentStatus::Cancelled, .. }));
|
||||
assert!(matches!(card(&c, &a, 1), AgentEntry::Tool { status: AgentToolStatus::Failed, .. }));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
//! next prompt when the agent supports `session/load`.
|
||||
|
||||
mod config;
|
||||
mod conversation;
|
||||
mod model;
|
||||
mod provider;
|
||||
mod skills;
|
||||
@@ -16,17 +17,17 @@ mod worktree;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
use timeline::Timeline;
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
@@ -39,6 +40,9 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// can trail its `session/prompt` response by this much.
|
||||
const TURN_GRACE: Duration = Duration::from_millis(100);
|
||||
const STDERR_LINES: usize = 20;
|
||||
/// Updates of a session's state rather than its conversation.
|
||||
const SESSION_STATE: [&str; 5] =
|
||||
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
|
||||
@@ -152,13 +156,19 @@ struct TaskFile {
|
||||
/// Settings the user chose, re-applied to every new or reloaded session.
|
||||
#[serde(default)]
|
||||
wanted: Vec<AgentConfigChoice>,
|
||||
/// In the project's own checkout: files already changed when the task started.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
before: BTreeMap<String, worktree::Stamp>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
task: AgentTask,
|
||||
session_id: Option<String>,
|
||||
timeline: Timeline,
|
||||
conversation: Conversation,
|
||||
wanted: Vec<AgentConfigChoice>,
|
||||
before: Arc<BTreeMap<String, worktree::Stamp>>,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
}
|
||||
@@ -188,7 +198,7 @@ struct Task {
|
||||
replaying: AtomicBool,
|
||||
/// The current turn is being cancelled to send the first queued message right away.
|
||||
send_now: AtomicBool,
|
||||
dirty: Mutex<BTreeSet<usize>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
flush_scheduled: AtomicBool,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// Set by `delete`; held while saving.
|
||||
@@ -231,11 +241,9 @@ impl AgentManager {
|
||||
// The agent process did not survive the restart: whatever was in flight is over.
|
||||
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
let mut timeline = Timeline::from_entries(std::mem::take(&mut f.entries));
|
||||
timeline.end_turn(None);
|
||||
f.entries = timeline.entries;
|
||||
}
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
}
|
||||
Err(e) => tracing::warn!("skipping agent task {}: {e}", path.display()),
|
||||
@@ -297,8 +305,12 @@ impl AgentManager {
|
||||
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
|
||||
}
|
||||
|
||||
pub fn entries(&self, id: &str) -> IdeResult<Vec<AgentEntry>> {
|
||||
Ok(self.task(id)?.state.lock().timeline.entries.clone())
|
||||
/// The entries of the task's conversation, or of its subagent `subagent`'s.
|
||||
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
let task = self.task(id)?;
|
||||
let s = task.state.lock();
|
||||
let timeline = s.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
|
||||
Ok(timeline.entries.clone())
|
||||
}
|
||||
|
||||
/// Creates the task (and its worktree) and sends `req.prompt` as its first message.
|
||||
@@ -310,18 +322,20 @@ impl AgentManager {
|
||||
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the task first"))?;
|
||||
let title = title_of(&prompt);
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let (cwd, branch, base, base_commit) = match req.isolation {
|
||||
let (cwd, branch, base, base_commit, before) = match req.isolation {
|
||||
Isolation::Worktree => {
|
||||
let dir = self.shared.paths.worktrees_dir.clone();
|
||||
let (t, b) = (title.clone(), req.base.clone());
|
||||
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
|
||||
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit))
|
||||
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
|
||||
}
|
||||
Isolation::Local => {
|
||||
let r = root.clone();
|
||||
let head = blocking(move || worktree::head_of(&r)).await.ok();
|
||||
let (head, before) =
|
||||
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
|
||||
.await?;
|
||||
let (base, commit) = head.unzip();
|
||||
(root, None, base, commit)
|
||||
(root, None, base, commit, before)
|
||||
}
|
||||
};
|
||||
// Until the session reports its own, show what the agent offered last time with the choices applied.
|
||||
@@ -351,7 +365,14 @@ impl AgentManager {
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
};
|
||||
let file = TaskFile { task: task.clone(), session_id: None, entries: Vec::new(), wanted: req.config };
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
wanted: req.config,
|
||||
before,
|
||||
subagents: Vec::new(),
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
handle.state.lock().busy = true;
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
@@ -481,9 +502,17 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// Stops the current turn (`session/cancel`); pending permission requests are cancelled.
|
||||
/// Queued messages stay queued.
|
||||
pub fn cancel(&self, id: &str) -> IdeResult<()> {
|
||||
self.task(id)?.cancel();
|
||||
/// Queued messages stay queued. With `subagent`, stops only that subagent's work.
|
||||
pub fn cancel(&self, id: &str, subagent: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
match subagent {
|
||||
None => task.cancel(),
|
||||
Some(sub) => {
|
||||
if let Some(live) = task.live.lock().clone() {
|
||||
let _ = live.peer.notify("session/cancel", json!({ "sessionId": sub }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -529,8 +558,10 @@ impl AgentManager {
|
||||
|
||||
/// Files the task changed since it started.
|
||||
pub async fn changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, base) = self.task(id)?.cwd_and_base();
|
||||
blocking(move || worktree::changes(&cwd, &base)).await
|
||||
let task = self.task(id)?;
|
||||
let (cwd, base) = task.cwd_and_base();
|
||||
let before = task.state.lock().before.clone();
|
||||
blocking(move || Ok(worktree::without_untouched(worktree::changes(&cwd, &base)?, &before))).await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) when the task started.
|
||||
@@ -543,6 +574,8 @@ impl AgentManager {
|
||||
pub fn shutdown(&self) {
|
||||
for task in self.tasks.read().values() {
|
||||
task.kill();
|
||||
// What arrived after the last save (a subagent's late updates).
|
||||
task.persist();
|
||||
}
|
||||
*self.shared.sink.write() = None;
|
||||
}
|
||||
@@ -551,15 +584,16 @@ impl AgentManager {
|
||||
impl Task {
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let task = file.task;
|
||||
let timeline = Timeline::from_entries(file.entries);
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
Arc::new(Self {
|
||||
id: task.id.clone(),
|
||||
shared,
|
||||
state: Mutex::new(TaskState {
|
||||
task,
|
||||
session_id: file.session_id,
|
||||
timeline,
|
||||
conversation,
|
||||
wanted: file.wanted,
|
||||
before: Arc::new(file.before),
|
||||
busy: false,
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
@@ -614,8 +648,10 @@ impl Task {
|
||||
serde_json::to_vec(&TaskFile {
|
||||
task: s.task.clone(),
|
||||
session_id: s.session_id.clone(),
|
||||
entries: s.timeline.entries.clone(),
|
||||
entries: s.conversation.main.entries.clone(),
|
||||
wanted: s.wanted.clone(),
|
||||
before: (*s.before).clone(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
})
|
||||
};
|
||||
let path = self.shared.paths.store_dir.join(format!("{}.json", self.id));
|
||||
@@ -624,7 +660,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = usize>) {
|
||||
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = (Session, usize)>) {
|
||||
self.dirty.lock().extend(indices);
|
||||
if !self.flush_scheduled.swap(true, Ordering::AcqRel) {
|
||||
let task = self.clone();
|
||||
@@ -642,9 +678,9 @@ impl Task {
|
||||
let s = self.state.lock();
|
||||
indices
|
||||
.into_iter()
|
||||
.filter_map(|i| {
|
||||
let entry = s.timeline.entries.get(i)?.clone();
|
||||
Some(AgentEvent::Entry { task: self.id.clone(), index: i as u32, entry })
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?.clone();
|
||||
Some(AgentEvent::Entry { task: self.id.clone(), subagent, index: i as u32, entry })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -654,8 +690,8 @@ impl Task {
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().timeline.push(entry);
|
||||
self.mark_dirty([i]);
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
i
|
||||
}
|
||||
|
||||
@@ -665,7 +701,7 @@ impl Task {
|
||||
loop {
|
||||
let result = self.turn(&prompt).await;
|
||||
tokio::time::sleep(TURN_GRACE).await;
|
||||
let changed = self.state.lock().timeline.end_turn(Some(now_ms()));
|
||||
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
let send_now = self.send_now.swap(false, Ordering::AcqRel);
|
||||
let next = {
|
||||
@@ -779,7 +815,12 @@ impl Task {
|
||||
"initialize",
|
||||
json!({
|
||||
"protocolVersion": 1,
|
||||
"clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false },
|
||||
"clientCapabilities": {
|
||||
"fs": { "readTextFile": false, "writeTextFile": false },
|
||||
"terminal": false,
|
||||
// Subagents as sessions of their own (ACP subagents RFD).
|
||||
"subagents": {},
|
||||
},
|
||||
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
|
||||
}),
|
||||
None,
|
||||
@@ -880,8 +921,16 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn on_update(self: &Arc<Self>, update: &Value) {
|
||||
/// Applies a `session/update` of session `session` (the task's, or one of its subagents').
|
||||
fn on_update(self: &Arc<Self>, session: Option<&str>, update: &Value) {
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
// A subagent's title, settings and usage are its own, not the task's.
|
||||
if self.state.lock().conversation.owner(session).is_some() {
|
||||
if !SESSION_STATE.contains(&kind) && !self.replaying.load(Ordering::Acquire) {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
@@ -936,8 +985,16 @@ impl Task {
|
||||
if self.replaying.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let applied = self.state.lock().timeline.apply(update);
|
||||
self.mark_dirty(applied.changed);
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
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" {
|
||||
self.persist();
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the calling (blocking-pool) thread until the user answers.
|
||||
@@ -949,6 +1006,12 @@ impl Task {
|
||||
.filter(|t| !t.is_empty())
|
||||
.unwrap_or("The agent asks for permission")
|
||||
.to_owned();
|
||||
// A subagent's request is answered in the task's conversation, named after the subagent.
|
||||
let session = params.get("sessionId").and_then(Value::as_str);
|
||||
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
|
||||
Some(label) => format!("{label}: {title}"),
|
||||
None => title,
|
||||
};
|
||||
let options: Vec<AgentPermissionOption> = params
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
@@ -976,11 +1039,11 @@ impl Task {
|
||||
.map_or_else(|| "Cancelled".to_owned(), |o| o.name.clone());
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.timeline.entries.get_mut(entry) {
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
|
||||
*chosen = Some(name);
|
||||
}
|
||||
}
|
||||
self.mark_dirty([entry]);
|
||||
self.mark_dirty([(None, entry)]);
|
||||
let still_asking = !self.permissions.lock().is_empty();
|
||||
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
@@ -1022,7 +1085,7 @@ impl Handler for Client {
|
||||
if method == "session/update"
|
||||
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
|
||||
{
|
||||
task.on_update(update);
|
||||
task.on_update(params.get("sessionId").and_then(Value::as_str), update);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -166,6 +166,18 @@ pub struct AgentToolDiff {
|
||||
pub removed: u32,
|
||||
}
|
||||
|
||||
/// What a subagent is doing, as its parent reports it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSubagentStatus {
|
||||
Running,
|
||||
/// One of its requests (a permission) waits for an answer.
|
||||
NeedsInput,
|
||||
Done,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlanItem {
|
||||
@@ -218,6 +230,33 @@ pub enum AgentEntry {
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
},
|
||||
/// A subagent the agent started: its own session, whose entries are listed separately.
|
||||
Subagent {
|
||||
/// The subagent's session id.
|
||||
id: String,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
status: AgentSubagentStatus,
|
||||
error: Option<String>,
|
||||
/// What it was asked to do, last.
|
||||
prompt: Option<String>,
|
||||
/// Its answer.
|
||||
reply: Option<String>,
|
||||
/// Tool calls it made.
|
||||
tools: u32,
|
||||
/// Title of its latest tool call.
|
||||
activity: Option<String>,
|
||||
started_ms: f64,
|
||||
/// When it last stopped working; `None` while it works.
|
||||
ended_ms: Option<f64>,
|
||||
/// Whether it can be stopped on its own.
|
||||
cancellable: bool,
|
||||
},
|
||||
/// A message between sessions in a subagent's conversation: its task (`incoming`) or its report.
|
||||
Message {
|
||||
incoming: bool,
|
||||
text: String,
|
||||
},
|
||||
Permission {
|
||||
id: u32,
|
||||
title: String,
|
||||
@@ -279,9 +318,10 @@ pub enum AgentEvent {
|
||||
Removed {
|
||||
id: String,
|
||||
},
|
||||
/// Entry `index` of `task` was added or replaced.
|
||||
/// Entry `index` of `task` (of its subagent `subagent`) was added or replaced.
|
||||
Entry {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
entry: AgentEntry,
|
||||
},
|
||||
|
||||
@@ -25,6 +25,44 @@ impl FakeAgent {
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
/// Runs a subagent in session `c1`, as an agent with ACP subagent sessions reports it.
|
||||
fn delegate(&self, root: &str) {
|
||||
let sub = |state: Value| json!({"sessionUpdate": "subagent_update", "sessionId": "c1", "state": state});
|
||||
let mut announce = sub(json!({"state": "running"}));
|
||||
announce["title"] = json!("Explore");
|
||||
self.update(root, announce);
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "session_message", "messageId": "m1", "senderSessionId": root,
|
||||
"recipientSessionId": "c1", "content": [{"type": "text", "text": "Find the lexer"}]}),
|
||||
);
|
||||
self.update("c1", json!({"sessionUpdate": "usage_update", "used": 900, "size": 1000}));
|
||||
self.update(
|
||||
"c1",
|
||||
json!({"sessionUpdate": "tool_call", "toolCallId": "c1-t1", "title": "Read lexer.rs",
|
||||
"kind": "read", "status": "completed"}),
|
||||
);
|
||||
let peer = self.peer.get().unwrap().clone();
|
||||
let _: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t2", "title": "Run ls"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
self.say("c1", "It is in lexer.rs");
|
||||
self.update(root, sub(json!({"state": "idle", "stopReason": "end_turn"})));
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "session_message", "messageId": "m2", "senderSessionId": "c1",
|
||||
"recipientSessionId": root, "content": [{"type": "text", "text": "lexer.rs"}]}),
|
||||
);
|
||||
self.say(root, "Found it");
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for FakeAgent {
|
||||
fn on_notification(&self, method: &str, _: Value) {
|
||||
self.calls.lock().push(method.to_owned());
|
||||
@@ -34,7 +72,12 @@ impl Handler for FakeAgent {
|
||||
self.calls.lock().push(method.to_owned());
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
"initialize" => Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}})),
|
||||
"initialize" => {
|
||||
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
|
||||
self.calls.lock().push("subagents".into());
|
||||
}
|
||||
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}}))
|
||||
}
|
||||
"session/new" => Ok(json!({"sessionId": "s1",
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
|
||||
@@ -53,6 +96,10 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "second turn");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
@@ -194,7 +241,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
let permission = mgr
|
||||
.entries(&task.id)
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
@@ -205,7 +252,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr.entries(&task.id).unwrap();
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let kinds: Vec<String> = entries
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
@@ -261,13 +308,13 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
mgr.shutdown();
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
assert_eq!(mgr2.entries(&task.id).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
|
||||
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr2.entries(&task.id).unwrap();
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert_eq!(entries.len(), 7);
|
||||
assert_eq!(entries[6], AgentEntry::Agent { text: "second turn".into() });
|
||||
assert!(agent2.calls.lock().contains(&"session/load".to_owned()));
|
||||
@@ -303,14 +350,14 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
|
||||
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
|
||||
for _ in 0..500 {
|
||||
if mgr.entries(&task.id).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
|
||||
if mgr.entries(&task.id, None).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let users: Vec<String> = mgr
|
||||
.entries(&task.id)
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
@@ -326,7 +373,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
agent.calls.lock().retain(|c| c != "session/cancel");
|
||||
mgr.prompt(&task.id, text("later"), false).await.unwrap();
|
||||
mgr.cancel(&task.id).unwrap();
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
|
||||
assert_eq!(queued.len(), 1);
|
||||
@@ -334,6 +381,68 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn subagents_get_their_own_conversation() {
|
||||
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("delegate"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The subagent's permission request is answered in the task's conversation.
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let (id, title) = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, title, .. } => Some((id, title)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(title, "Explore: Run ls");
|
||||
mgr.respond(&task.id, id, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "subagents"));
|
||||
|
||||
let check = |mgr: &AgentManager| {
|
||||
let main = mgr.entries(&task.id, None).unwrap();
|
||||
let card = main.iter().find(|e| matches!(e, AgentEntry::Subagent { .. })).unwrap();
|
||||
let AgentEntry::Subagent { title, status, prompt, reply, tools, activity, .. } = card else { unreachable!() };
|
||||
assert_eq!(title.as_deref(), Some("Explore"));
|
||||
assert_eq!(*status, AgentSubagentStatus::Done);
|
||||
assert_eq!((prompt.as_deref(), reply.as_deref()), (Some("Find the lexer"), Some("lexer.rs")));
|
||||
assert_eq!((*tools, activity.as_deref()), (1, Some("Read lexer.rs")));
|
||||
assert!(main.contains(&AgentEntry::Agent { text: "Found it".into() }));
|
||||
assert!(!main.iter().any(|e| matches!(e, AgentEntry::Tool { .. })));
|
||||
let sub = mgr.entries(&task.id, Some("c1".into())).unwrap();
|
||||
assert!(matches!(&sub[0], AgentEntry::Tool { title, .. } if title == "Read lexer.rs"));
|
||||
assert_eq!(sub[1], AgentEntry::Agent { text: "It is in lexer.rs".into() });
|
||||
};
|
||||
// Updates can trail the end of the turn.
|
||||
for _ in 0..500 {
|
||||
if mgr.entries(&task.id, None).unwrap().contains(&AgentEntry::Agent { text: "Found it".into() }) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
check(&mgr);
|
||||
// The subagent's context use is not the task's.
|
||||
assert_ne!(mgr.task(&task.id).unwrap().state.lock().task.usage.as_ref().map(|u| u.used), Some(900));
|
||||
assert!(mgr.entries(&task.id, Some("nope".into())).is_err());
|
||||
|
||||
// Saved with the task.
|
||||
mgr.shutdown();
|
||||
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompts_become_acp_content_blocks() {
|
||||
let p = AgentPrompt {
|
||||
@@ -381,15 +490,15 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&task.id).unwrap();
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id).unwrap();
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")));
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "chose none".into() }));
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.model.as_deref(), Some("big"), "the agent's default");
|
||||
|
||||
mgr.delete(&task.id, false).await.unwrap();
|
||||
assert!(mgr.entries(&task.id).is_err());
|
||||
assert!(mgr.entries(&task.id, None).is_err());
|
||||
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
|
||||
assert!(
|
||||
mgr.create(NewAgentTask {
|
||||
@@ -452,7 +561,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
let status = mgr.task(&task.id).unwrap().state.lock().task.status;
|
||||
match status {
|
||||
AgentStatus::NeedsInput => {
|
||||
let pending = mgr.entries(&task.id).unwrap().into_iter().rev().find_map(|e| match e {
|
||||
let pending = mgr.entries(&task.id, None).unwrap().into_iter().rev().find_map(|e| match e {
|
||||
AgentEntry::Permission { id, options, chosen: None, .. } => Some((id, options)),
|
||||
_ => None,
|
||||
});
|
||||
@@ -467,7 +576,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
for e in mgr.entries(&task.id).unwrap() {
|
||||
for e in mgr.entries(&task.id, None).unwrap() {
|
||||
eprintln!("{e:?}");
|
||||
}
|
||||
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -13,6 +13,10 @@ pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
tools: HashMap<String, usize>,
|
||||
plan: Option<usize>,
|
||||
/// Subagent cards, by the subagent's session id.
|
||||
cards: HashMap<String, usize>,
|
||||
/// Session messages, by message id.
|
||||
messages: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
/// What a `session/update` changed in the timeline.
|
||||
@@ -31,6 +35,9 @@ impl Timeline {
|
||||
t.tools.insert(id.clone(), i);
|
||||
}
|
||||
AgentEntry::Plan { .. } => t.plan = Some(i),
|
||||
AgentEntry::Subagent { id, .. } => {
|
||||
t.cards.insert(id.clone(), i);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -166,6 +173,119 @@ impl Timeline {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
|
||||
/// card's index and whether the subagent just stopped working.
|
||||
pub fn subagent(&mut self, id: &str, update: &Value, now: f64) -> (usize, bool) {
|
||||
let index = match self.cards.get(id) {
|
||||
Some(&i) => i,
|
||||
None => {
|
||||
let i = self.push(AgentEntry::Subagent {
|
||||
id: id.to_owned(),
|
||||
title: None,
|
||||
description: None,
|
||||
status: AgentSubagentStatus::Running,
|
||||
error: None,
|
||||
prompt: None,
|
||||
reply: None,
|
||||
tools: 0,
|
||||
activity: None,
|
||||
started_ms: now,
|
||||
ended_ms: None,
|
||||
cancellable: false,
|
||||
});
|
||||
self.cards.insert(id.to_owned(), i);
|
||||
i
|
||||
}
|
||||
};
|
||||
let AgentEntry::Subagent { title, description, status, error, ended_ms, cancellable, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return (index, false);
|
||||
};
|
||||
// Patch semantics: an omitted field is unchanged, `null` clears it.
|
||||
if let Some(v) = update.get("title") {
|
||||
*title = v.as_str().map(str::to_owned);
|
||||
}
|
||||
if let Some(v) = update.get("description") {
|
||||
*description = v.as_str().map(str::to_owned);
|
||||
}
|
||||
if let Some(v) = update.get("capabilities") {
|
||||
*cancellable = v.get("cancel").is_some_and(Value::is_object);
|
||||
}
|
||||
let mut stopped = false;
|
||||
if let Some((next, message)) = update.get("state").and_then(subagent_status) {
|
||||
let working = matches!(next, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput);
|
||||
stopped = !working && ended_ms.is_none();
|
||||
*ended_ms = if working { None } else { ended_ms.or(Some(now)) };
|
||||
*status = next;
|
||||
*error = message;
|
||||
}
|
||||
(index, stopped)
|
||||
}
|
||||
|
||||
/// Sets (or with `append`, extends) what subagent `id` was asked or answered, on its card.
|
||||
pub fn card_message(&mut self, id: &str, reply: bool, text: &str, append: bool) -> Option<usize> {
|
||||
let &index = self.cards.get(id)?;
|
||||
let AgentEntry::Subagent { prompt, reply: answer, .. } = &mut self.entries[index] else { return None };
|
||||
let field = if reply { answer } else { prompt };
|
||||
match field {
|
||||
Some(t) if append => t.push_str(text),
|
||||
_ => *field = Some(text.to_owned()),
|
||||
}
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Adds, replaces or (with `append`) extends session message `id`.
|
||||
pub fn message(&mut self, id: &str, incoming: bool, text: &str, append: bool) -> usize {
|
||||
if let Some(&i) = self.messages.get(id)
|
||||
&& let AgentEntry::Message { text: t, .. } = &mut self.entries[i]
|
||||
{
|
||||
if append {
|
||||
t.push_str(text);
|
||||
} else {
|
||||
*t = text.to_owned();
|
||||
}
|
||||
return i;
|
||||
}
|
||||
let i = self.push(AgentEntry::Message { incoming, text: text.to_owned() });
|
||||
self.messages.insert(id.to_owned(), i);
|
||||
i
|
||||
}
|
||||
|
||||
/// Updates subagent `id`'s card with what its own timeline `of` shows: how many tool
|
||||
/// calls it made and its latest one. Returns the card's index when it changed.
|
||||
pub fn card_activity(&mut self, id: &str, of: &Timeline) -> Option<usize> {
|
||||
let &index = self.cards.get(id)?;
|
||||
let AgentEntry::Subagent { tools, activity, .. } = &mut self.entries[index] else { return None };
|
||||
let calls = of.entries.iter().filter_map(|e| match e {
|
||||
AgentEntry::Tool { title, kind, .. } => Some(if title.is_empty() { kind } else { title }),
|
||||
_ => None,
|
||||
});
|
||||
let count = calls.clone().count() as u32;
|
||||
let latest = calls.clone().next_back().cloned();
|
||||
if *tools == count && *activity == latest {
|
||||
return None;
|
||||
}
|
||||
*tools = count;
|
||||
*activity = latest;
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Marks the subagents still working as stopped (their agent is gone).
|
||||
pub fn stop_subagents(&mut self, now: f64) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
for (i, e) in self.entries.iter_mut().enumerate() {
|
||||
if let AgentEntry::Subagent { status, ended_ms, .. } = e
|
||||
&& matches!(status, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput)
|
||||
{
|
||||
*status = AgentSubagentStatus::Cancelled;
|
||||
*ended_ms = Some(now);
|
||||
changed.push(i);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Settles what an ended turn left open: running tools and pending permissions,
|
||||
/// and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
|
||||
@@ -198,7 +318,30 @@ fn str_field(v: &Value, key: &str) -> String {
|
||||
v.get(key).and_then(Value::as_str).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
fn content_text(content: Option<&Value>) -> Option<String> {
|
||||
/// The status a subagent `state` reports, with its error message; `None` for an unknown state.
|
||||
fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>)> {
|
||||
Some(match state.get("state")?.as_str()? {
|
||||
"running" => (AgentSubagentStatus::Running, None),
|
||||
"requires_action" => (AgentSubagentStatus::NeedsInput, None),
|
||||
"idle" => match state.get("stopReason").and_then(Value::as_str) {
|
||||
Some("cancelled") => (AgentSubagentStatus::Cancelled, None),
|
||||
Some("error") => (
|
||||
AgentSubagentStatus::Failed,
|
||||
state.pointer("/error/message").and_then(Value::as_str).map(str::to_owned),
|
||||
),
|
||||
_ => (AgentSubagentStatus::Done, None),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
blocks.iter().filter_map(|b| content_text(Some(b))).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
pub(crate) fn content_text(content: Option<&Value>) -> Option<String> {
|
||||
let c = content?;
|
||||
match c.get("type").and_then(Value::as_str) {
|
||||
Some("text") => c.get("text").and_then(Value::as_str).map(str::to_owned),
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
use crate::model::AgentChange;
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_vcs::{ChangeKind, Repo};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
pub(crate) struct Created {
|
||||
pub path: PathBuf,
|
||||
@@ -74,6 +76,25 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Size and modification time of a file, `None` once it is gone.
|
||||
pub(crate) type Stamp = Option<(u64, u128)>;
|
||||
|
||||
fn stamp(path: &Path) -> Stamp {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_nanos();
|
||||
Some((meta.len(), modified))
|
||||
}
|
||||
|
||||
/// The files already changed in `cwd` against `HEAD`, stamped so later edits to them show.
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
Ok(changes(cwd, "HEAD")?.into_iter().map(|c| (c.rel_path, stamp(&c.path))).collect())
|
||||
}
|
||||
|
||||
/// Drops the changes that were there before the task and haven't been touched since.
|
||||
pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> {
|
||||
changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
repo_at(cwd)?.file_at(path, Some(rev))
|
||||
}
|
||||
@@ -148,6 +169,17 @@ mod tests {
|
||||
let base_text = file_at(&created.path, &created.path.join("a.txt"), &created.base_commit).unwrap();
|
||||
assert_eq!(base_text.as_deref(), Some("one\ntwo\n"));
|
||||
|
||||
// Changes already in the checkout drop out until they are edited again.
|
||||
let before = snapshot(&created.path).unwrap();
|
||||
std::fs::write(created.path.join("b.txt"), "b\n").unwrap();
|
||||
let rels = |c: Vec<AgentChange>| c.into_iter().map(|c| c.rel_path).collect::<Vec<_>>();
|
||||
let after = changes(&created.path, "HEAD").unwrap();
|
||||
assert_eq!(rels(without_untouched(after, &before)), ["b.txt"]);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(created.path.join("new.txt"), "x\ny\nz\n").unwrap();
|
||||
let after = changes(&created.path, "HEAD").unwrap();
|
||||
assert_eq!(rels(without_untouched(after, &before)), ["b.txt", "new.txt"]);
|
||||
|
||||
// A second task with the same title gets its own worktree.
|
||||
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
|
||||
remove(&repo, &created.path).unwrap();
|
||||
|
||||
@@ -67,6 +67,11 @@ pub enum IdeEvent {
|
||||
status: ServerStatus,
|
||||
message: Option<String>,
|
||||
},
|
||||
/// A stopped language server left the project's list (disabled in settings, or a
|
||||
/// fallback that a preferred server took over from again).
|
||||
LanguageServerRemoved {
|
||||
server: ServerId,
|
||||
},
|
||||
/// A language server asked clients to re-request one kind of data for its
|
||||
/// open documents (`workspace/inlayHint/refresh`, …), e.g. after indexing.
|
||||
LspRefresh {
|
||||
|
||||
@@ -17,6 +17,7 @@ pub struct VcsSettings {
|
||||
pub git: GitSettings,
|
||||
pub commit: CommitSettings,
|
||||
pub confirmation: VcsConfirmationSettings,
|
||||
pub shelf: ShelfSettings,
|
||||
/// Issue Navigation: commit-message patterns turned into links.
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
}
|
||||
@@ -31,6 +32,7 @@ impl Default for VcsSettings {
|
||||
git: GitSettings::default(),
|
||||
commit: CommitSettings::default(),
|
||||
confirmation: VcsConfirmationSettings::default(),
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -53,6 +55,17 @@ pub struct GitSettings {
|
||||
pub protected_branches: String,
|
||||
/// Initial state of Commit Options › Sign-off Commit.
|
||||
pub sign_off: bool,
|
||||
/// Ask before committing files larger than `large_file_mb`.
|
||||
pub warn_large_files: bool,
|
||||
pub large_file_mb: u32,
|
||||
/// Ask before committing names that are invalid on Windows or differ only in case.
|
||||
pub warn_bad_file_names: bool,
|
||||
/// Commit and Push opens the Push dialog; otherwise it pushes right away.
|
||||
pub show_push_dialog: bool,
|
||||
/// With `show_push_dialog`: only for commits to protected branches.
|
||||
pub push_dialog_only_protected: bool,
|
||||
/// Stashes and shelves share one tab.
|
||||
pub combine_stash_and_shelf: bool,
|
||||
}
|
||||
|
||||
impl Default for GitSettings {
|
||||
@@ -66,6 +79,12 @@ impl Default for GitSettings {
|
||||
incoming_check: "auto".into(),
|
||||
protected_branches: "master; main".into(),
|
||||
sign_off: false,
|
||||
warn_large_files: true,
|
||||
large_file_mb: 50,
|
||||
warn_bad_file_names: true,
|
||||
show_push_dialog: true,
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,6 +93,11 @@ impl Default for GitSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CommitSettings {
|
||||
/// Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
pub check_todo: bool,
|
||||
pub reformat: bool,
|
||||
@@ -91,6 +115,8 @@ pub struct CommitSettings {
|
||||
impl Default for CommitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
non_modal: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
check_todo: true,
|
||||
reformat: false,
|
||||
@@ -107,20 +133,40 @@ impl Default for CommitSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Version Control › Confirmation. Values: `ask` | `silently` | `never`.
|
||||
/// Version Control › Confirmation.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct VcsConfirmationSettings {
|
||||
/// `ask` | `silently` | `never`.
|
||||
pub on_create: String,
|
||||
pub on_delete: String,
|
||||
/// Update Project opens its options dialog first.
|
||||
pub show_update_options: bool,
|
||||
pub confirm_drop_commits: bool,
|
||||
/// After a patch is saved: `ask` | `no` | `reveal` (show it in the file manager).
|
||||
pub on_patch_created: String,
|
||||
}
|
||||
|
||||
impl Default for VcsConfirmationSettings {
|
||||
fn default() -> Self {
|
||||
Self { on_create: "ask".into(), on_delete: "ask".into() }
|
||||
Self {
|
||||
on_create: "ask".into(),
|
||||
on_delete: "ask".into(),
|
||||
show_update_options: true,
|
||||
confirm_drop_commits: true,
|
||||
on_patch_created: "ask".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Version Control › Shelf.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ShelfSettings {
|
||||
/// Initial state of Unshelve's "Remove successfully applied files from the shelf".
|
||||
pub remove_applied: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct IssueLink {
|
||||
|
||||
@@ -28,8 +28,9 @@ pub async fn commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
pub fn entries(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task)
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
}
|
||||
|
||||
pub async fn create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
@@ -56,8 +57,9 @@ pub async fn set_config(host: &Host, window: &str, task: String, option: String,
|
||||
host.project(window)?.agents.set_config(&task, &option, value).await
|
||||
}
|
||||
|
||||
pub fn cancel(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.cancel(&task)
|
||||
/// Stops the task's current turn, or with `subagent` only that subagent's work.
|
||||
pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: None` cancels it.
|
||||
@@ -87,7 +89,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
|
||||
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
|
||||
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
|
||||
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
|
||||
d.add("agent_prompt", |c| async move {
|
||||
prompt(&c.host, &c.window, c.arg("task")?, c.arg("prompt")?, c.arg("now")?).await
|
||||
@@ -100,7 +102,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_set_config", |c| async move {
|
||||
set_config(&c.host, &c.window, c.arg("task")?, c.arg("option")?, c.arg("value")?).await
|
||||
});
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
|
||||
@@ -518,12 +518,14 @@ mod tests {
|
||||
#[test]
|
||||
fn alternative_servers_are_fallbacks() {
|
||||
let reg = reg();
|
||||
for (lang, servers) in
|
||||
[("python", ["basedpyright", "pyright"]), ("typescript", ["vtsls", "typescript-language-server"])]
|
||||
{
|
||||
for (lang, servers) in [
|
||||
("python", vec!["basedpyright", "pyright", "ty"]),
|
||||
("typescript", vec!["vtsls", "typescript-language-server"]),
|
||||
] {
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
let got: Vec<(&str, bool)> = cfg.language_servers.iter().map(|s| (s.name.as_str(), s.fallback)).collect();
|
||||
assert_eq!(got, [(servers[0], false), (servers[1], true)]);
|
||||
let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1931,7 +1931,7 @@ impl LspManager {
|
||||
tracing::info!("{}: shadowed by an enabled server, stopping", s.name);
|
||||
self.stop_instance(s, true).await;
|
||||
}
|
||||
self.servers.lock().retain(|s| !detached.iter().any(|d| d.id == s.id));
|
||||
self.forget(&detached);
|
||||
}
|
||||
|
||||
/// Stops and forgets the servers that none of their languages uses any more.
|
||||
@@ -1949,10 +1949,18 @@ impl LspManager {
|
||||
self.stop_instance(s, true).await;
|
||||
}
|
||||
let gone = |s: &Arc<Server>| unlisted.iter().any(|u| u.id == s.id);
|
||||
self.servers.lock().retain(|s| !gone(s));
|
||||
for d in self.docs.lock().values_mut() {
|
||||
d.servers.retain(|a| !gone(&a.server));
|
||||
}
|
||||
self.forget(&unlisted);
|
||||
}
|
||||
|
||||
/// Drops stopped servers from the list and tells the UI they are gone.
|
||||
fn forget(&self, gone: &[Arc<Server>]) {
|
||||
self.servers.lock().retain(|s| !gone.iter().any(|g| g.id == s.id));
|
||||
for s in gone {
|
||||
self.sink.emit(ide_core::IdeEvent::LanguageServerRemoved { server: s.id });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_apply_edit_hook(&self, hook: Box<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Protocol tests against in-memory mock language servers.
|
||||
|
||||
use ide_core::event::ServerStatus;
|
||||
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, Severity, WorkspaceEdit};
|
||||
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, ServerId, Severity, WorkspaceEdit};
|
||||
use ide_jsonrpc::{Handler, NoopHandler, Peer};
|
||||
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::types::*;
|
||||
@@ -9,7 +9,7 @@ use ide_lsp::{LaunchError, Launcher, LspManager};
|
||||
use ide_text::AppliedChange;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -275,6 +275,22 @@ impl Harness {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether every instance of `name` was reported as removed from the server list.
|
||||
fn removed(&self, name: &str) -> bool {
|
||||
let events = self.events.lock();
|
||||
let ids: HashSet<ServerId> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::LanguageServer { server, name: n, .. } if n == name => Some(*server),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
!ids.is_empty()
|
||||
&& ids.iter().all(|id| {
|
||||
events.iter().any(|e| matches!(e, IdeEvent::LanguageServerRemoved { server } if server == id))
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_status(&self, name: &str, status: ServerStatus) {
|
||||
eventually(|| self.statuses(name).last() == Some(&status)).await;
|
||||
}
|
||||
@@ -847,6 +863,8 @@ async fn settings_changes_reach_servers_without_restarts() {
|
||||
h.mgr.reconfigure().await;
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["mock"]);
|
||||
assert_eq!(h.statuses("extra").last(), Some(&ServerStatus::Stopped));
|
||||
assert!(h.removed("extra"));
|
||||
assert!(!h.removed("mock"));
|
||||
disabled.lock().clear();
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("extra", ServerStatus::Ready).await;
|
||||
@@ -899,6 +917,7 @@ async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
|
||||
assert!(h.removed("main"));
|
||||
|
||||
// Enabled again: the fallback closes the document and stops.
|
||||
disabled.lock().clear();
|
||||
@@ -907,6 +926,7 @@ async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
|
||||
eventually(|| h.launcher.state("main").docs.lock().contains_key(&uri)).await;
|
||||
assert!(!h.launcher.state("alt").notified("textDocument/didClose").is_empty());
|
||||
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
|
||||
assert!(h.removed("alt"));
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["main"]);
|
||||
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
|
||||
assert_eq!(h.launcher.state("alt").requested("textDocument/hover").len(), 0);
|
||||
|
||||
@@ -105,6 +105,44 @@ fn main() {
|
||||
}
|
||||
";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires ty on PATH"]
|
||||
async fn ty_python_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let path = root.join("example.py");
|
||||
let source = "def greet(name: str) -> str:\n return name\n\nresult = greet('Ada')\nbad: int = 'wrong'\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
|
||||
python.language_servers.retain(|server| server.name == "ty");
|
||||
assert_eq!(python.language_servers.len(), 1);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
|
||||
retry("ty ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "ty");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("ty failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
let defs = retry("ty definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, Pos::new(3, 10), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs[0].path, path);
|
||||
assert_eq!(defs[0].range.start.line, 0);
|
||||
retry("ty diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().any(
|
||||
|event| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "ty" && !items.is_empty()),
|
||||
);
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires rust-analyzer"]
|
||||
async fn rust_analyzer_end_to_end() {
|
||||
|
||||
@@ -134,7 +134,7 @@ pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
const PYTHON_SERVERS: [&str; 5] = ["basedpyright", "pyright", "pylsp", "jedi-language-server", "ruff"];
|
||||
const PYTHON_SERVERS: [&str; 6] = ["basedpyright", "pyright", "ty", "pylsp", "jedi-language-server", "ruff"];
|
||||
|
||||
fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Shell integration (Settings › Tools › Terminal › Shell integration): the
|
||||
//! shell reports its working directory (OSC 7) at every prompt, so links and
|
||||
//! new splits resolve against the directory the user `cd`-ed into.
|
||||
//! new splits resolve against the directory the user `cd`-ed into, and marks
|
||||
//! where a command starts and ends (OSC 133 C / D), so the tab shows the
|
||||
//! running program's title only while one runs.
|
||||
//!
|
||||
//! zsh starts with `ZDOTDIR` pointing at generated startup files that source
|
||||
//! the user's own ones first; bash gets an `--init-file` that replays the
|
||||
@@ -29,8 +31,11 @@ ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
[[ -f $ZDOTDIR/.zshrc ]] && . $ZDOTDIR/.zshrc
|
||||
OPENIDEA_USER_ZDOTDIR=$ZDOTDIR
|
||||
ZDOTDIR=$_openidea_dir
|
||||
_openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
|
||||
autoload -Uz add-zsh-hook 2>/dev/null && add-zsh-hook precmd _openidea_osc7
|
||||
_openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
|
||||
_openidea_preexec() { printf '\e]133;C\a' }
|
||||
# First, so the command counts as finished before other hooks set the prompt's title.
|
||||
precmd_functions=(_openidea_osc7 ${precmd_functions:#_openidea_osc7})
|
||||
preexec_functions+=(_openidea_preexec)
|
||||
if [[ ! -o login ]]; then
|
||||
ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
|
||||
@@ -54,15 +59,22 @@ if [ "${OPENIDEA_LOGIN:-}" = 1 ]; then
|
||||
else
|
||||
[ -f ~/.bashrc ] && . ~/.bashrc
|
||||
fi
|
||||
__openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
|
||||
__openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
|
||||
case ";${PROMPT_COMMAND:-};" in
|
||||
*";__openidea_osc7;"*) ;;
|
||||
*) PROMPT_COMMAND="__openidea_osc7${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
|
||||
esac
|
||||
# PS0 (bash 4.4+) prints before each command runs.
|
||||
case "${PS0:-}" in
|
||||
*'133;C'*) ;;
|
||||
*) PS0="${PS0:-}\e]133;C\a" ;;
|
||||
esac
|
||||
"#;
|
||||
|
||||
const FISH_INIT: &str =
|
||||
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]7;file://%s%s\a' (hostname) $PWD; end"#;
|
||||
const FISH_INIT: &str = concat!(
|
||||
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]133;D\a\e]7;file://%s%s\a' (hostname) $PWD; end; "#,
|
||||
r#"function __openidea_preexec --on-event fish_preexec; printf '\e]133;C\a'; end"#,
|
||||
);
|
||||
|
||||
/// Directory holding the generated startup files (written on demand).
|
||||
fn scripts_dir() -> PathBuf {
|
||||
|
||||
@@ -167,6 +167,16 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://docs.basedpyright.com",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "ty",
|
||||
display: "ty (Python)",
|
||||
kind: LanguageServer,
|
||||
commands: &["ty"],
|
||||
method: Method::PipVenv { package: "ty" },
|
||||
version: ver("ty"),
|
||||
homepage: "https://docs.astral.sh/ty/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-language-server",
|
||||
display: "Bash Language Server",
|
||||
|
||||
@@ -67,6 +67,11 @@ fn everything_missing_on_an_empty_system() {
|
||||
let vtsls = find(&list, "vtsls");
|
||||
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
|
||||
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
|
||||
let ty = find(&list, "ty");
|
||||
assert_eq!(ty.status, ToolStatus::Missing);
|
||||
assert_eq!(ty.command, "ty");
|
||||
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
|
||||
assert!(ty.languages.iter().any(|language| language == "Python"));
|
||||
// Servers without an installer are listed with their manual hint.
|
||||
let hls = find(&list, "haskell-language-server");
|
||||
assert_eq!(hls.install_method, None);
|
||||
|
||||
@@ -295,7 +295,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
203 themeable tokens: 113 in the UI theme file, 90 in the editor colour scheme file.
|
||||
219 themeable tokens: 113 in the UI theme file, 106 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
@@ -480,6 +480,27 @@ a token.
|
||||
| `--ansi-bright-cyan` | `#00e5e5` | `#1b9ea3` |
|
||||
| `--ansi-bright-white` | `#ffffff` | `#5f6269` |
|
||||
|
||||
### Terminal ANSI palette (editor scheme)
|
||||
|
||||
| Token | Islands Dark | Islands Light |
|
||||
|---|---|---|
|
||||
| `--terminal-ansi-black` | `#000000` | `#000000` |
|
||||
| `--terminal-ansi-red` | `#f27481` | `#c93645` |
|
||||
| `--terminal-ansi-green` | `#6bcc62` | `#357d1f` |
|
||||
| `--terminal-ansi-yellow` | `#e0ce70` | `#b2a400` |
|
||||
| `--terminal-ansi-blue` | `#5594fa` | `#225cd6` |
|
||||
| `--terminal-ansi-magenta` | `#c092fa` | `#6e32e5` |
|
||||
| `--terminal-ansi-cyan` | `#47ccbd` | `#007a80` |
|
||||
| `--terminal-ansi-white` | `#ced0d6` | `#bec0c5` |
|
||||
| `--terminal-ansi-bright-black` | `#4e5157` | `#6c707e` |
|
||||
| `--terminal-ansi-bright-red` | `#ff6b7a` | `#ff5462` |
|
||||
| `--terminal-ansi-bright-green` | `#67ff59` | `#3dcc3d` |
|
||||
| `--terminal-ansi-bright-yellow` | `#ffec1a` | `#d4bb00` |
|
||||
| `--terminal-ansi-bright-blue` | `#3399ff` | `#009dff` |
|
||||
| `--terminal-ansi-bright-magenta` | `#d970ff` | `#d659ff` |
|
||||
| `--terminal-ansi-bright-cyan` | `#40ffe9` | `#31c4b3` |
|
||||
| `--terminal-ansi-bright-white` | `#ffffff` | `#d2d4d9` |
|
||||
|
||||
### Shadows and window controls (UI theme)
|
||||
|
||||
| Token | Islands Dark | Islands Light |
|
||||
|
||||
@@ -87,12 +87,12 @@ terminal is a real xterm renderer, without a native PTY or shell. These images
|
||||
cover the shell, sidebar, editor, gutter, find matches, terminal, Settings,
|
||||
focused controls, disabled settings and the selected theme popup.
|
||||
|
||||
| Theme | Workbench, editor and terminal | Settings and theme popup |
|
||||
|---|---|---|
|
||||
| Theme | Workbench, editor and terminal | Settings and theme popup |
|
||||
| --------------- | -------------------------------------------------------- | ---------------------------------------------------- |
|
||||
| Solarized Light | [Screenshot](media/themes/solarized-light-workbench.png) | [Screenshot](media/themes/solarized-light-popup.png) |
|
||||
| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
|
||||
| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
|
||||
| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
|
||||
| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
|
||||
| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
|
||||
| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
|
||||
|
||||
The browser regression also checks refresh / startup cache restoration,
|
||||
selection visibility, same-kind switches, the quick menu, existing themes,
|
||||
|
||||
+11
-2
@@ -11,11 +11,20 @@
|
||||
<div id="root"></div>
|
||||
<div id="splash" class="splash" data-tauri-drag-region>
|
||||
<svg class="splash-logo" viewBox="22 24 56 56" aria-hidden="true">
|
||||
<rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" /><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" /><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" /><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" /><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" /><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" /><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
|
||||
<rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" />
|
||||
<rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" />
|
||||
<circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" />
|
||||
<rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" />
|
||||
<rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" />
|
||||
<rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" />
|
||||
<circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
|
||||
</svg>
|
||||
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
|
||||
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
|
||||
<path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z"
|
||||
/>
|
||||
</svg>
|
||||
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
|
||||
</div>
|
||||
|
||||
@@ -32,6 +32,14 @@ args = ["--stdio"]
|
||||
root-markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"]
|
||||
install-hint = "npm i -g pyright (or: pip install pyright)"
|
||||
|
||||
[[language-servers]]
|
||||
name = "ty"
|
||||
fallback = true
|
||||
command = "ty"
|
||||
args = ["server"]
|
||||
root-markers = ["ty.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
|
||||
install-hint = "uv tool install ty (or: pip install ty)"
|
||||
|
||||
[debugger]
|
||||
adapter = "debugpy"
|
||||
command = "python3"
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.21",
|
||||
"version": "0.1.22",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -14,6 +14,7 @@
|
||||
"test:watch": "vitest",
|
||||
"lint": "oxlint",
|
||||
"format": "oxfmt",
|
||||
"format:check": "oxfmt --check",
|
||||
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit",
|
||||
"gen:bindings": "cargo test -p openidea --test export_bindings",
|
||||
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
|
||||
|
||||
@@ -13,15 +13,15 @@ python perf/compare/bench.py ~/src/spring-petclinic --runs 5 --wipe-caches # c
|
||||
Each run launches the app on the project, waits until it is ready, idles,
|
||||
closes it, and records:
|
||||
|
||||
| Metric | How |
|
||||
|---|---|
|
||||
| `window_s` | first visible window whose title matches `window_title` (the project name) |
|
||||
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
|
||||
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
|
||||
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
|
||||
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
|
||||
| `exit_s` | until every process has exited |
|
||||
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
|
||||
| Metric | How |
|
||||
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| `window_s` | first visible window whose title matches `window_title` (the project name) |
|
||||
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
|
||||
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
|
||||
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
|
||||
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
|
||||
| `exit_s` | until every process has exited |
|
||||
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
|
||||
|
||||
Apps run interleaved, rotating the order, after `--warmup` discarded runs.
|
||||
Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
|
||||
@@ -31,8 +31,8 @@ Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
|
||||
|
||||
- Release builds only; a running instance of the same executable (a
|
||||
`pnpm tauri dev` build too) would take over the launch, so the script refuses.
|
||||
- IDEA: open the project once by hand and trust it; turn off *Reopen projects
|
||||
on startup* and *Confirm before exiting*; note the version, `-Xmx` and whether
|
||||
- IDEA: open the project once by hand and trust it; turn off _Reopen projects
|
||||
on startup_ and _Confirm before exiting_; note the version, `-Xmx` and whether
|
||||
Shared Indexes were on.
|
||||
- Same machine, power plan and plugged in; exclude the project and caches from
|
||||
antivirus scanning, or neither.
|
||||
|
||||
+29
-29
@@ -48,11 +48,11 @@ All paths are relative to the package directory and may not leave it.
|
||||
|
||||
### Permissions
|
||||
|
||||
| Permission | Unlocks |
|
||||
|----------------|-------------------------------------------------|
|
||||
| Permission | Unlocks |
|
||||
| -------------- | ------------------------------------------------- |
|
||||
| `project-read` | `workspace-root`, `read-file` (project root only) |
|
||||
| `editor-read` | `active-file` |
|
||||
| `editor-write` | `insert-text`, `replace-selection` |
|
||||
| `editor-read` | `active-file` |
|
||||
| `editor-write` | `insert-text`, `replace-selection` |
|
||||
|
||||
`log`, `register-command`, `show-notification`, `register-language` and
|
||||
`register-theme` are always available. Calling a gated function without its
|
||||
@@ -133,22 +133,22 @@ Any language with component-model tooling works (e.g. `componentize-py`,
|
||||
|
||||
### Host functions
|
||||
|
||||
| Function | Notes |
|
||||
|---|---|
|
||||
| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
|
||||
| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
|
||||
| `show-notification(level, title, body)` | Balloon in the invoking window. |
|
||||
| `workspace-root()` | Root of the project the command runs in. |
|
||||
| `active-file()` | Absolute path of the focused editor's file. |
|
||||
| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
|
||||
| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
|
||||
| `replace-selection(text)` | Replaces every selection and selects the new text. |
|
||||
| `register-language(toml)` | Same format as `languages/<id>.toml`. |
|
||||
| `register-theme(json)` | See *Themes* below. |
|
||||
| Function | Notes |
|
||||
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
|
||||
| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
|
||||
| `show-notification(level, title, body)` | Balloon in the invoking window. |
|
||||
| `workspace-root()` | Root of the project the command runs in. |
|
||||
| `active-file()` | Absolute path of the focused editor's file. |
|
||||
| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
|
||||
| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
|
||||
| `replace-selection(text)` | Replaces every selection and selects the new text. |
|
||||
| `register-language(toml)` | Same format as `languages/<id>.toml`. |
|
||||
| `register-theme(json)` | See _Themes_ below. |
|
||||
|
||||
`run-command` receives an optional string argument: `executeAction("plugin.hello.insert-date", "arg")`
|
||||
from another feature, or nothing when run from Search Everywhere / a shortcut.
|
||||
Returning `Err(msg)` shows *"<title> failed: msg"*; the plugin keeps running.
|
||||
Returning `Err(msg)` shows _"<title> failed: msg"_; the plugin keeps running.
|
||||
|
||||
### Sandbox and limits
|
||||
|
||||
@@ -156,13 +156,13 @@ Each plugin gets its own wasmtime `Store`: no preopened directories, no
|
||||
environment, no network, no inherited stdio — only clocks and randomness from
|
||||
WASI, plus the host functions above. Every call into the plugin is bounded:
|
||||
|
||||
* **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
|
||||
* **time:** 5 s wall clock per call (epoch interruption);
|
||||
* **memory:** 256 MiB of linear memory.
|
||||
- **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
|
||||
- **time:** 5 s wall clock per call (epoch interruption);
|
||||
- **memory:** 256 MiB of linear memory.
|
||||
|
||||
A panic, trap, permission violation or exceeded limit stops the plugin and
|
||||
marks it *Failed* for the session (with the reason in Settings › Plugins);
|
||||
toggling it off and on, or *Reload*, starts a fresh instance. The IDE itself is
|
||||
marks it _Failed_ for the session (with the reason in Settings › Plugins);
|
||||
toggling it off and on, or _Reload_, starts a fresh instance. The IDE itself is
|
||||
never affected.
|
||||
|
||||
## 3. Themes
|
||||
@@ -181,7 +181,7 @@ Tokens are the CSS variables of `src/styles/tokens.css` (`--bg-*`, `--fg-*`,
|
||||
keep the values of the built-in base named by `kind`. Values must be plain CSS
|
||||
values (no `url()`, `;`, braces); `//` and `/* */` comments are allowed. A
|
||||
manifest theme entry may add `editor-scheme = "themes/x.scheme.json"` (editor
|
||||
colours, merged over the theme). Pick a theme in Settings › Plugins › *Apply*.
|
||||
colours, merged over the theme). Pick a theme in Settings › Plugins › _Apply_.
|
||||
|
||||
Start from [`templates/theme-plugin`](../templates/theme-plugin); the full guide,
|
||||
token reference and IntelliJ / VS Code porting tables are in
|
||||
@@ -196,14 +196,14 @@ token reference and IntelliJ / VS Code porting tables are in
|
||||
|
||||
## 5. Installing and developing
|
||||
|
||||
* **Install:** Settings › Plugins › *Install Plugin from Disk…* (or the action
|
||||
*Install Plugin from Disk…*) and pick the package folder. The manifest and the
|
||||
- **Install:** Settings › Plugins › _Install Plugin from Disk…_ (or the action
|
||||
_Install Plugin from Disk…_) and pick the package folder. The manifest and the
|
||||
files it references are copied to `<app-data>/plugins/<id>/`.
|
||||
* **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
|
||||
It loads when the project is opened, is listed with a *dev* tag, and *Reload*
|
||||
(or the *Reload Plugins* action) picks up a rebuilt `plugin.wasm` without
|
||||
- **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
|
||||
It loads when the project is opened, is listed with a _dev_ tag, and _Reload_
|
||||
(or the _Reload Plugins_ action) picks up a rebuilt `plugin.wasm` without
|
||||
restarting the IDE.
|
||||
* Commands appear in Search Everywhere › Actions under their category, and can
|
||||
- Commands appear in Search Everywhere › Actions under their category, and can
|
||||
be bound in Settings › Keymap like any other action.
|
||||
|
||||
## 6. Testing
|
||||
|
||||
+51
-12
@@ -4,8 +4,13 @@
|
||||
Until tokens load, the colours are the last theme's --bg-frame / --fg-muted that boot.js
|
||||
restored as --boot-*, else these built-in ones; the bar keeps the last --accent throughout. */
|
||||
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
|
||||
body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
|
||||
:root[data-theme="dark"] :is(body, .splash) { background: var(--bg-frame, var(--boot-frame, #26282c)); }
|
||||
body,
|
||||
.splash {
|
||||
background: var(--bg-frame, var(--boot-frame, #e9eaee));
|
||||
}
|
||||
:root[data-theme="dark"] :is(body, .splash) {
|
||||
background: var(--bg-frame, var(--boot-frame, #26282c));
|
||||
}
|
||||
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) {
|
||||
background: var(--bg-frame, var(--boot-frame, #1a1b1e));
|
||||
}
|
||||
@@ -27,12 +32,29 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
|
||||
animation: splash-in 240ms ease-out 120ms both;
|
||||
transition: opacity 160ms ease-out;
|
||||
}
|
||||
.splash.splash-out { opacity: 0; pointer-events: none; }
|
||||
:root[data-theme^="dark"] .splash { color: var(--fg-muted, var(--boot-fg, #8c8f95)); }
|
||||
.splash-logo { width: 56px; height: 56px; }
|
||||
.splash.splash-out {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
:root[data-theme^="dark"] .splash {
|
||||
color: var(--fg-muted, var(--boot-fg, #8c8f95));
|
||||
}
|
||||
.splash-logo {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
}
|
||||
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
|
||||
.splash-wordmark { width: 73.2px; height: 18.15px; }
|
||||
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
|
||||
.splash-wordmark {
|
||||
width: 73.2px;
|
||||
height: 18.15px;
|
||||
}
|
||||
.splash-bar {
|
||||
width: 120px;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
overflow: hidden;
|
||||
background: rgb(127 127 127 / 0.18);
|
||||
}
|
||||
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out.
|
||||
The remembered accent comes first: tokens.css brings the theme's default --accent before
|
||||
settings restore a custom one, which would flash the default mid-load. */
|
||||
@@ -44,11 +66,28 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
|
||||
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
|
||||
}
|
||||
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
|
||||
:root[data-window="settings"] .splash { animation-delay: 400ms; }
|
||||
:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
|
||||
@keyframes splash-in { from { opacity: 0; } }
|
||||
@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
|
||||
:root[data-window="settings"] .splash {
|
||||
animation-delay: 400ms;
|
||||
}
|
||||
:root[data-window="settings"] .splash > :not(.splash-bar) {
|
||||
display: none;
|
||||
}
|
||||
@keyframes splash-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@keyframes splash-fill {
|
||||
from {
|
||||
transform: scaleX(0.04);
|
||||
}
|
||||
to {
|
||||
transform: scaleX(0.92);
|
||||
}
|
||||
}
|
||||
/* The fill stays: it grows in place, which reduced motion allows. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.splash { animation: none; }
|
||||
.splash {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export interface TokenGroup {
|
||||
}
|
||||
|
||||
/** tokens.css sections that IntelliJ keeps in an editor scheme (`.icls`). */
|
||||
export const SCHEME_GROUPS = ["syntax", "editor", "ANSI palette"];
|
||||
export const SCHEME_GROUPS = ["syntax", "editor", "ANSI palette", "terminal ANSI palette"];
|
||||
|
||||
const LIGHT_SELECTOR = ':root[data-theme="light"]';
|
||||
|
||||
|
||||
@@ -2,11 +2,7 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": [
|
||||
"main",
|
||||
"project-*",
|
||||
"settings-*"
|
||||
],
|
||||
"windows": ["main", "project-*", "settings-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
|
||||
@@ -2,12 +2,6 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "e2e-bridge",
|
||||
"description": "Debug-only automation bridge",
|
||||
"windows": [
|
||||
"main",
|
||||
"project-*",
|
||||
"settings-*"
|
||||
],
|
||||
"permissions": [
|
||||
"mcp-bridge:default"
|
||||
]
|
||||
}
|
||||
"windows": ["main", "project-*", "settings-*"],
|
||||
"permissions": ["mcp-bridge:default"]
|
||||
}
|
||||
@@ -46,10 +46,16 @@ pub async fn agent_commands(
|
||||
agent::commands(&state.host, window.label(), provider, task).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn agent_entries(window: Window, state: State<'_, AppState>, task: String) -> IdeResult<Vec<AgentEntry>> {
|
||||
agent::entries(&state.host, window.label(), task)
|
||||
pub fn agent_entries(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
agent::entries(&state.host, window.label(), task, subagent)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -108,10 +114,16 @@ pub async fn agent_set_config(
|
||||
agent::set_config(&state.host, window.label(), task, option, value).await
|
||||
}
|
||||
|
||||
/// Stops the task's current turn, or with `subagent` only that subagent's work.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn agent_cancel(window: Window, state: State<'_, AppState>, task: String) -> IdeResult<()> {
|
||||
agent::cancel(&state.host, window.label(), task)
|
||||
pub fn agent_cancel(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
agent::cancel(&state.host, window.label(), task, subagent)
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: null` cancels it.
|
||||
|
||||
+100
-16
@@ -568,8 +568,14 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.pull", "Pull…"),
|
||||
act("vcs.fetch", "Fetch"),
|
||||
SEP,
|
||||
// Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress.
|
||||
act("vcs.merge", "Merge…"),
|
||||
act("vcs.merge.abort", "Abort Merge"),
|
||||
act("vcs.rebase", "Rebase…"),
|
||||
act("vcs.rebase.abort", "Abort Rebase"),
|
||||
act("vcs.rebase.continue", "Continue Rebase"),
|
||||
act("vcs.rebase.skip", "Skip Commit"),
|
||||
act("vcs.resolveConflicts", "Resolve Conflicts…"),
|
||||
SEP,
|
||||
act("vcs.branches", "Branches…"),
|
||||
act("vcs.newBranch", "New Branch…"),
|
||||
@@ -579,17 +585,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.newWorktree", "New Worktree…"),
|
||||
act("vcs.worktrees", "Worktrees…"),
|
||||
SEP,
|
||||
act("vcs.showDiff", "Show Diff"),
|
||||
act("vcs.rollback", "Rollback…"),
|
||||
act("vcs.annotate", "Annotate with Git Blame"),
|
||||
act("vcs.showLog", "Show Git Log"),
|
||||
act("vcs.localHistory", "Local History"),
|
||||
act("localHistory.putLabel", "Put Label…"),
|
||||
SEP,
|
||||
act("vcs.stash", "Stash Changes…"),
|
||||
act("vcs.unstash", "Unstash Changes…"),
|
||||
act("vcs.shelve", "Shelve Changes…"),
|
||||
act("vcs.showShelf", "Show Shelf"),
|
||||
sub(
|
||||
"gitPatch",
|
||||
"Patch",
|
||||
@@ -599,12 +595,32 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.applyPatchFromClipboard", "Apply Patch from Clipboard…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("vcs.resolveConflicts", "Resolve Conflicts…"),
|
||||
act("vcs.rebase.continue", "Continue Rebase"),
|
||||
act("vcs.rebase.abort", "Abort Rebase"),
|
||||
act("vcs.rebase.skip", "Skip Commit"),
|
||||
act("vcs.merge.abort", "Abort Merge"),
|
||||
sub(
|
||||
"gitUncommittedChanges",
|
||||
"Uncommitted Changes",
|
||||
vec![
|
||||
act("vcs.shelve", "Shelve Changes…"),
|
||||
act("vcs.showShelf", "Show Shelf"),
|
||||
act("vcs.stash", "Stash Changes…"),
|
||||
act("vcs.unstash", "Unstash Changes…"),
|
||||
act("vcs.rollback", "Rollback…"),
|
||||
],
|
||||
),
|
||||
sub(
|
||||
"gitCurrentFile",
|
||||
"Current File",
|
||||
vec![
|
||||
act("vcs.addToVcs", "Add to VCS"),
|
||||
SEP,
|
||||
act("vcs.annotate", "Annotate with Git Blame"),
|
||||
act("vcs.showDiff", "Show Diff"),
|
||||
act("vcs.compareWithBranch", "Compare with Branch or Revision…"),
|
||||
act("vcs.showHistory", "Show History"),
|
||||
SEP,
|
||||
act("vcs.localHistory", "Local History"),
|
||||
act("localHistory.putLabel", "Put Label…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
sub(
|
||||
"gitHub",
|
||||
@@ -620,6 +636,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.clone", "Clone…"),
|
||||
SEP,
|
||||
act("vcs.operations", "VCS Operations Popup…"),
|
||||
SEP,
|
||||
act("vcs.revert.continue", "Continue Revert"),
|
||||
act("vcs.revert.abort", "Abort Revert"),
|
||||
act("vcs.cherryPick.continue", "Continue Cherry-Pick"),
|
||||
act("vcs.cherryPick.abort", "Abort Cherry-Pick"),
|
||||
],
|
||||
));
|
||||
|
||||
@@ -1436,6 +1457,69 @@ mod tests {
|
||||
assert!(item_enabled("submenu:refactor", &disabled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_menu_follows_idea_order() {
|
||||
let spec = spec(Os::Mac);
|
||||
let Some(Entry::Submenu { children, .. }) = spec.iter().find(|e| matches!(e, Entry::Submenu { id: "git", .. }))
|
||||
else {
|
||||
panic!("Git menu missing");
|
||||
};
|
||||
let top: Vec<&str> = children
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
Entry::Action { id, .. } | Entry::Submenu { id, .. } => *id,
|
||||
Entry::Separator => "|",
|
||||
_ => "?",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
top,
|
||||
[
|
||||
"vcs.commit",
|
||||
"vcs.push",
|
||||
"vcs.update",
|
||||
"vcs.pull",
|
||||
"vcs.fetch",
|
||||
"|",
|
||||
"vcs.merge",
|
||||
"vcs.merge.abort",
|
||||
"vcs.rebase",
|
||||
"vcs.rebase.abort",
|
||||
"vcs.rebase.continue",
|
||||
"vcs.rebase.skip",
|
||||
"vcs.resolveConflicts",
|
||||
"|",
|
||||
"vcs.branches",
|
||||
"vcs.newBranch",
|
||||
"vcs.newTag",
|
||||
"vcs.resetHead",
|
||||
"|",
|
||||
"vcs.newWorktree",
|
||||
"vcs.worktrees",
|
||||
"|",
|
||||
"vcs.showLog",
|
||||
"gitPatch",
|
||||
"gitUncommittedChanges",
|
||||
"gitCurrentFile",
|
||||
"|",
|
||||
"gitHub",
|
||||
"vcs.manageRemotes",
|
||||
"vcs.clone",
|
||||
"|",
|
||||
"vcs.operations",
|
||||
"|",
|
||||
"vcs.revert.continue",
|
||||
"vcs.revert.abort",
|
||||
"vcs.cherryPick.continue",
|
||||
"vcs.cherryPick.abort",
|
||||
]
|
||||
);
|
||||
let ids = action_ids(children);
|
||||
for moved in ["vcs.showDiff", "vcs.rollback", "vcs.annotate", "vcs.localHistory", "localHistory.putLabel"] {
|
||||
assert!(ids.contains(&moved), "{moved} missing from the Git menu");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idea_menu_items_are_present() {
|
||||
for os in ALL_OS {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.21",
|
||||
"version": "0.1.22",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
@@ -37,13 +37,7 @@
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/[email protected]",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.icns", "icons/icon.ico"],
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "Copyright © 2026 OpenIDEA contributors",
|
||||
"license": "Apache-2.0",
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
"app": {
|
||||
"withGlobalTauri": true
|
||||
}
|
||||
}
|
||||
}
|
||||
+67
-6
@@ -61,7 +61,8 @@ export const commands = {
|
||||
* before a task exists (skills and custom commands on disk included).
|
||||
*/
|
||||
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
|
||||
agentEntries: (task: string) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task })),
|
||||
/** Entries of `task`'s conversation, or of its subagent `subagent`'s. */
|
||||
agentEntries: (task: string, subagent: string | null) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task, subagent })),
|
||||
agentCreate: (request: NewAgentTask) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create", { request })),
|
||||
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
|
||||
agentPrompt: (task: string, prompt: AgentPrompt, now: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_prompt", { task, prompt, now })),
|
||||
@@ -71,7 +72,8 @@ export const commands = {
|
||||
agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })),
|
||||
/** Changes a session setting (model, mode, thinking effort…). */
|
||||
agentSetConfig: (task: string, option: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_config", { task, option, value })),
|
||||
agentCancel: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_cancel", { task })),
|
||||
/** Stops the task's current turn, or with `subagent` only that subagent's work. */
|
||||
agentCancel: (task: string, subagent: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_cancel", { task, subagent })),
|
||||
/** Answers a permission request; `option: null` cancels it. */
|
||||
agentRespond: (task: string, permission: number, option: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_respond", { task, permission, option })),
|
||||
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
|
||||
@@ -1001,7 +1003,25 @@ doneMs?: number | null } | { type: "agent"; text: string } | { type: "thought";
|
||||
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
|
||||
kind: string; status: AgentToolStatus; locations: IpcPath[];
|
||||
/** Text the tool reported (command output…), truncated. */
|
||||
output: string | null; diffs: AgentToolDiff[] } | { type: "plan"; items: AgentPlanItem[] } | { type: "permission"; id: number; title: string; options: AgentPermissionOption[];
|
||||
output: string | null; diffs: AgentToolDiff[] } | { type: "plan"; items: AgentPlanItem[] } |
|
||||
/** A subagent the agent started: its own session, whose entries are listed separately. */
|
||||
{ type: "subagent";
|
||||
/** The subagent's session id. */
|
||||
id: string; title: string | null; description: string | null; status: AgentSubagentStatus; error: string | null;
|
||||
/** What it was asked to do, last. */
|
||||
prompt: string | null;
|
||||
/** Its answer. */
|
||||
reply: string | null;
|
||||
/** Tool calls it made. */
|
||||
tools: number;
|
||||
/** Title of its latest tool call. */
|
||||
activity: string | null; startedMs: number | null;
|
||||
/** When it last stopped working; `None` while it works. */
|
||||
endedMs: number | null;
|
||||
/** Whether it can be stopped on its own. */
|
||||
cancellable: boolean } |
|
||||
/** A message between sessions in a subagent's conversation: its task (`incoming`) or its report. */
|
||||
{ type: "message"; incoming: boolean; text: string } | { type: "permission"; id: number; title: string; options: AgentPermissionOption[];
|
||||
/** Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled". */
|
||||
chosen: string | null } | { type: "error"; message: string };
|
||||
|
||||
@@ -1009,8 +1029,8 @@ chosen: string | null } | { type: "error"; message: string };
|
||||
export type AgentEvent =
|
||||
/** A task was created or its metadata changed. */
|
||||
{ type: "task"; task: AgentTask } | { type: "removed"; id: string } |
|
||||
/** Entry `index` of `task` was added or replaced. */
|
||||
{ type: "entry"; task: string; index: number; entry: AgentEntry };
|
||||
/** Entry `index` of `task` (of its subagent `subagent`) was added or replaced. */
|
||||
{ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry };
|
||||
|
||||
export type AgentImage = {
|
||||
mimeType: string,
|
||||
@@ -1065,6 +1085,11 @@ export type AgentStatus =
|
||||
/** The turn ended; the result can be reviewed or the conversation continued. */
|
||||
"ready" | "failed" | "archived";
|
||||
|
||||
/** What a subagent is doing, as its parent reports it. */
|
||||
export type AgentSubagentStatus = "running" |
|
||||
/** One of its requests (a permission) waits for an answer. */
|
||||
"needsInput" | "done" | "cancelled" | "failed";
|
||||
|
||||
export type AgentTask = {
|
||||
id: string,
|
||||
title: string,
|
||||
@@ -1616,6 +1641,13 @@ export type CommitOptions = {
|
||||
|
||||
/** Version Control › Commit: commit checks and commit-message inspections. */
|
||||
export type CommitSettings = {
|
||||
/**
|
||||
* Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
* window and a Commit dialog.
|
||||
*/
|
||||
nonModal?: boolean,
|
||||
/** Start with an empty message instead of the last one / the changelist's. */
|
||||
clearInitialMessage?: boolean,
|
||||
analyzeCode?: boolean,
|
||||
checkTodo?: boolean,
|
||||
reformat?: boolean,
|
||||
@@ -2889,6 +2921,17 @@ export type GitSettings = {
|
||||
protectedBranches?: string,
|
||||
/** Initial state of Commit Options › Sign-off Commit. */
|
||||
signOff?: boolean,
|
||||
/** Ask before committing files larger than `large_file_mb`. */
|
||||
warnLargeFiles?: boolean,
|
||||
largeFileMb?: number,
|
||||
/** Ask before committing names that are invalid on Windows or differ only in case. */
|
||||
warnBadFileNames?: boolean,
|
||||
/** Commit and Push opens the Push dialog; otherwise it pushes right away. */
|
||||
showPushDialog?: boolean,
|
||||
/** With `show_push_dialog`: only for commits to protected branches. */
|
||||
pushDialogOnlyProtected?: boolean,
|
||||
/** Stashes and shelves share one tab. */
|
||||
combineStashAndShelf?: boolean,
|
||||
};
|
||||
|
||||
export type GoSettings = {
|
||||
@@ -3088,6 +3131,11 @@ export type IdeEvent =
|
||||
{ type: "indexState"; indexing: boolean; files: number; symbols: number } |
|
||||
/** Git status / branch information should be refreshed. */
|
||||
{ type: "vcsChanged"; root: IpcPath } | { type: "languageServer"; server: ServerId; name: string; status: ServerStatus; message: string | null } |
|
||||
/**
|
||||
* A stopped language server left the project's list (disabled in settings, or a
|
||||
* fallback that a preferred server took over from again).
|
||||
*/
|
||||
{ type: "languageServerRemoved"; server: ServerId } |
|
||||
/**
|
||||
* A language server asked clients to re-request one kind of data for its
|
||||
* open documents (`workspace/inlayHint/refresh`, …), e.g. after indexing.
|
||||
@@ -5007,6 +5055,12 @@ export type Settings_Serialize = {
|
||||
|
||||
export type Severity = "error" | "warning" | "info" | "hint";
|
||||
|
||||
/** Version Control › Shelf. */
|
||||
export type ShelfSettings = {
|
||||
/** Initial state of Unshelve's "Remove successfully applied files from the shelf". */
|
||||
removeApplied?: boolean,
|
||||
};
|
||||
|
||||
/** A change list on the shelf. */
|
||||
export type ShelvedChangeList = {
|
||||
/** Folder name under the shelf directory. */
|
||||
@@ -5579,10 +5633,16 @@ export type Variable = {
|
||||
evaluateName: string | null,
|
||||
};
|
||||
|
||||
/** Version Control › Confirmation. Values: `ask` | `silently` | `never`. */
|
||||
/** Version Control › Confirmation. */
|
||||
export type VcsConfirmationSettings = {
|
||||
/** `ask` | `silently` | `never`. */
|
||||
onCreate?: string,
|
||||
onDelete?: string,
|
||||
/** Update Project opens its options dialog first. */
|
||||
showUpdateOptions?: boolean,
|
||||
confirmDropCommits?: boolean,
|
||||
/** After a patch is saved: `ask` | `no` | `reveal` (show it in the file manager). */
|
||||
onPatchCreated?: string,
|
||||
};
|
||||
|
||||
/** A repository of the project (IDEA's VCS root). */
|
||||
@@ -5607,6 +5667,7 @@ export type VcsSettings = {
|
||||
git?: GitSettings,
|
||||
commit?: CommitSettings,
|
||||
confirmation?: VcsConfirmationSettings,
|
||||
shelf?: ShelfSettings,
|
||||
/** Issue Navigation: commit-message patterns turned into links. */
|
||||
issueNavigation?: IssueLink[],
|
||||
};
|
||||
|
||||
@@ -17,7 +17,15 @@
|
||||
* - Right-hand overview marks: `scrollbarMarks`; save hooks:
|
||||
* `registerSaveParticipant`; Back/Forward history: `getNavigationHistory`.
|
||||
*/
|
||||
import { Annotation, Compartment, Facet, type EditorState, type Extension, type RangeSet, type Transaction } from "@codemirror/state";
|
||||
import {
|
||||
Annotation,
|
||||
Compartment,
|
||||
Facet,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
type RangeSet,
|
||||
type Transaction,
|
||||
} from "@codemirror/state";
|
||||
import { GutterMarker, ViewPlugin, type EditorView } from "@codemirror/view";
|
||||
import type { LanguageDescription } from "@codemirror/language";
|
||||
import { create } from "zustand";
|
||||
@@ -252,7 +260,12 @@ export class LaneMarker extends GutterMarker {
|
||||
super();
|
||||
}
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof LaneMarker && other.color === this.color && other.kind === this.kind && other.title === this.title;
|
||||
return (
|
||||
other instanceof LaneMarker &&
|
||||
other.color === this.color &&
|
||||
other.kind === this.kind &&
|
||||
other.title === this.title
|
||||
);
|
||||
}
|
||||
override toDOM(): Node {
|
||||
const el = document.createElement("div");
|
||||
@@ -283,7 +296,10 @@ export type ContributedFormatter = (
|
||||
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
|
||||
export type ContributedDefinition = (view: EditorView, pos: number) => boolean;
|
||||
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
|
||||
export type ContributedHover = (state: EditorState, pos: number) => { from: number; to: number; markdown: string } | null;
|
||||
export type ContributedHover = (
|
||||
state: EditorState,
|
||||
pos: number,
|
||||
) => { from: number; to: number; markdown: string } | null;
|
||||
|
||||
export function contributedAt<T>(state: EditorState, key: string, pos: number): T | undefined {
|
||||
return state.languageDataAt<T>(key, pos)[0];
|
||||
|
||||
@@ -23,12 +23,32 @@ import {
|
||||
toggleCase,
|
||||
unselectOccurrence,
|
||||
} from "./cm/editing";
|
||||
import { emptyStack, extendSelection, shrinkSelection, type SelectionStack, type SimpleRange } from "./model/selectionStack";
|
||||
import {
|
||||
emptyStack,
|
||||
extendSelection,
|
||||
shrinkSelection,
|
||||
type SelectionStack,
|
||||
type SimpleRange,
|
||||
} from "./model/selectionStack";
|
||||
import type { EditorSlot } from "./model/slot";
|
||||
import { findAgain, openFindBar } from "./view/FindBar";
|
||||
import { collapseAll, collapseRecursively, expandAll, expandRecursively, foldAtCaret, foldSelection, unfoldAtCaret } from "./cm/folding";
|
||||
import {
|
||||
collapseAll,
|
||||
collapseRecursively,
|
||||
expandAll,
|
||||
expandRecursively,
|
||||
foldAtCaret,
|
||||
foldSelection,
|
||||
unfoldAtCaret,
|
||||
} from "./cm/folding";
|
||||
import { reverseLines, sortLines } from "./cm/lines";
|
||||
import { cursorCodeBlockEnd, cursorCodeBlockStart, cursorMatchBrace, scrollToCenter, splitLine } from "./cm/caretCommands";
|
||||
import {
|
||||
cursorCodeBlockEnd,
|
||||
cursorCodeBlockStart,
|
||||
cursorMatchBrace,
|
||||
scrollToCenter,
|
||||
splitLine,
|
||||
} from "./cm/caretCommands";
|
||||
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
|
||||
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
|
||||
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
|
||||
@@ -86,19 +106,32 @@ export function syntaxCandidates(state: EditorState, sel: SimpleRange): SimpleRa
|
||||
const word = state.wordAt(sel.from);
|
||||
if (word) out.push({ from: word.from, to: word.to });
|
||||
const tree = syntaxTree(state);
|
||||
for (let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(sel.from, 1); node; node = node.parent) {
|
||||
for (
|
||||
let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(sel.from, 1);
|
||||
node;
|
||||
node = node.parent
|
||||
) {
|
||||
out.push({ from: node.from, to: node.to });
|
||||
const text = state.sliceDoc(node.from, Math.min(node.to, node.from + 1)) + state.sliceDoc(Math.max(node.from, node.to - 1), node.to);
|
||||
const text =
|
||||
state.sliceDoc(node.from, Math.min(node.to, node.from + 1)) +
|
||||
state.sliceDoc(Math.max(node.from, node.to - 1), node.to);
|
||||
if (/^[([{"'`][)\]}"'`]$/.test(text) && node.to - node.from > 2) out.push({ from: node.from + 1, to: node.to - 1 });
|
||||
}
|
||||
const line = state.doc.lineAt(sel.from);
|
||||
const endLine = state.doc.lineAt(sel.to);
|
||||
const indent = /^\s*/.exec(line.text)![0].length;
|
||||
out.push({ from: line.from + indent, to: endLine.to }, { from: line.from, to: endLine.to }, { from: 0, to: state.doc.length });
|
||||
out.push(
|
||||
{ from: line.from + indent, to: endLine.to },
|
||||
{ from: line.from, to: endLine.to },
|
||||
{ from: 0, to: state.doc.length },
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
function rangesFromBackend(state: EditorState, ranges: Array<{ start: { line: number; col: number }; end: { line: number; col: number } }>): SimpleRange[] {
|
||||
function rangesFromBackend(
|
||||
state: EditorState,
|
||||
ranges: Array<{ start: { line: number; col: number }; end: { line: number; col: number } }>,
|
||||
): SimpleRange[] {
|
||||
const off = (p: { line: number; col: number }) => {
|
||||
if (p.line + 1 > state.doc.lines) return state.doc.length;
|
||||
const l = state.doc.line(p.line + 1);
|
||||
@@ -120,8 +153,14 @@ export interface BackendChain {
|
||||
* unchanged and the selection still covers its position: every node around
|
||||
* the selection is around that position too. Repeated ⌥↑ then needs no IPC.
|
||||
*/
|
||||
export function reusableChain(chain: BackendChain | undefined, counter: number, current: SimpleRange): SimpleRange[] | null {
|
||||
return chain && chain.counter === counter && chain.pos >= current.from && chain.pos <= current.to ? chain.ranges : null;
|
||||
export function reusableChain(
|
||||
chain: BackendChain | undefined,
|
||||
counter: number,
|
||||
current: SimpleRange,
|
||||
): SimpleRange[] | null {
|
||||
return chain && chain.counter === counter && chain.pos >= current.from && chain.pos <= current.to
|
||||
? chain.ranges
|
||||
: null;
|
||||
}
|
||||
|
||||
const chains = new WeakMap<EditorSlot, BackendChain>();
|
||||
@@ -156,10 +195,17 @@ async function extend(slot: EditorSlot) {
|
||||
const results = currents.map((c, i) =>
|
||||
extendSelection(prev[i] ?? emptyStack(), c, [...candidates[i]!, ...syntaxCandidates(v.state, c)]),
|
||||
);
|
||||
stacks.set(slot, results.map((r) => r.state));
|
||||
stacks.set(
|
||||
slot,
|
||||
results.map((r) => r.state),
|
||||
);
|
||||
if (!results.some((r) => r.next)) return;
|
||||
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : before.ranges[i]!));
|
||||
v.dispatch({ selection: EditorSelection.create(ranges, before.mainIndex), scrollIntoView: true, userEvent: "select.extend" });
|
||||
v.dispatch({
|
||||
selection: EditorSelection.create(ranges, before.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select.extend",
|
||||
});
|
||||
}
|
||||
|
||||
/** Extend / shrink run in order: a quick ⌥↑⌥↑ extends twice although extending waits for the backend. */
|
||||
@@ -177,10 +223,17 @@ function shrink(slot: EditorSlot) {
|
||||
const sel = view.state.selection;
|
||||
const prev = stacks.get(slot) ?? [];
|
||||
const results = sel.ranges.map((r, i) => shrinkSelection(prev[i] ?? emptyStack(), { from: r.from, to: r.to }));
|
||||
stacks.set(slot, results.map((r) => r.state));
|
||||
stacks.set(
|
||||
slot,
|
||||
results.map((r) => r.state),
|
||||
);
|
||||
if (!results.some((r) => r.next)) return;
|
||||
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : sel.ranges[i]!));
|
||||
view.dispatch({ selection: EditorSelection.create(ranges, sel.mainIndex), scrollIntoView: true, userEvent: "select.shrink" });
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, sel.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select.shrink",
|
||||
});
|
||||
}
|
||||
|
||||
// --- structural editing without a Lezer tree ------------------------------------------
|
||||
@@ -231,7 +284,8 @@ function moveStatement(view: EditorView, slot: EditorSlot, up: boolean) {
|
||||
const v = slot.view;
|
||||
if (!v) return;
|
||||
const language = slot.model.getMeta().language;
|
||||
if ((await hasStructure(language)) && (await moveStatementStructural(v, up, queriesFor(slot.model))) !== "fallback") return;
|
||||
if ((await hasStructure(language)) && (await moveStatementStructural(v, up, queriesFor(slot.model))) !== "fallback")
|
||||
return;
|
||||
if (slot.view === v) (up ? moveLineUp : moveLineDown)(v);
|
||||
});
|
||||
}
|
||||
@@ -246,11 +300,16 @@ function completeCurrentStatement(view: EditorView, slot: EditorSlot) {
|
||||
if (completionStatus(view.state) === "active") acceptCompletion(view);
|
||||
const language = slot.model.getMeta().language;
|
||||
const sel = view.state.selection;
|
||||
if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1) return completeStatement(language)(view);
|
||||
if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1)
|
||||
return completeStatement(language)(view);
|
||||
void queueEdit(slot, async () => {
|
||||
const v = slot.view;
|
||||
if (!v || v.state.readOnly) return;
|
||||
if ((await hasStructure(language)) && (await completeStatementStructural(v, language, queriesFor(slot.model))) !== "fallback") return;
|
||||
if (
|
||||
(await hasStructure(language)) &&
|
||||
(await completeStatementStructural(v, language, queriesFor(slot.model))) !== "fallback"
|
||||
)
|
||||
return;
|
||||
if (slot.view === v) completeStatement(language)(v);
|
||||
});
|
||||
}
|
||||
@@ -299,7 +358,8 @@ function copyReference(view: EditorView, slot: EditorSlot) {
|
||||
|
||||
/** ⌃G; when nothing more is found, a hint first and the search from the top on the next press (IDEA). */
|
||||
function addNextOccurrence(view: EditorView) {
|
||||
if (nextOccurrence(view) === "notFound") void executeAction("editor.showHint", { text: "Not found, press again to search from the top" });
|
||||
if (nextOccurrence(view) === "notFound")
|
||||
void executeAction("editor.showHint", { text: "Not found, press again to search from the top" });
|
||||
}
|
||||
|
||||
/** Settings › Editor › Color Scheme switches that are also toggle actions. */
|
||||
@@ -309,7 +369,11 @@ export async function toggleSchemeSwitch(key: SchemeSwitch, on = !editorPrefs()[
|
||||
try {
|
||||
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(on))) });
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: "Cannot change the setting", body: e instanceof Error ? e.message : String(e) });
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot change the setting",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,7 +390,12 @@ const schemeSwitch = (id: string, title: string, key: SchemeSwitch, keywords: st
|
||||
|
||||
export function registerEditorActions(): () => void {
|
||||
const ctrl = editorController();
|
||||
const text = (id: string, title: string, run: (view: EditorView, slot: EditorSlot) => unknown, extra: Partial<Action> = {}): Action => ({
|
||||
const text = (
|
||||
id: string,
|
||||
title: string,
|
||||
run: (view: EditorView, slot: EditorSlot) => unknown,
|
||||
extra: Partial<Action> = {},
|
||||
): Action => ({
|
||||
id,
|
||||
title,
|
||||
category: "Code",
|
||||
@@ -358,22 +427,34 @@ export function registerEditorActions(): () => void {
|
||||
text("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
|
||||
text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)),
|
||||
text("code.moveStatementDown", "Move Statement Down", (v, slot) => moveStatement(v, slot, false)),
|
||||
text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), { category: "Edit" }),
|
||||
text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), { category: "Edit" }),
|
||||
text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.fold", "Collapse", (v) => foldAtCaret(v), { category: "Folding", keywords: ["fold"] }),
|
||||
text("code.unfold", "Expand", (v) => unfoldAtCaret(v), { category: "Folding", keywords: ["unfold"] }),
|
||||
text("code.foldToggle", "Toggle Fold", (v) => toggleFold(v), { category: "Folding" }),
|
||||
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => expandWord(v, slot, "backward"), {
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
}),
|
||||
text("code.cyclicExpandWordBackward", "Cyclic Expand Word (Backward)", (v, slot) => expandWord(v, slot, "forward"), {
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
}),
|
||||
text(
|
||||
"code.cyclicExpandWordBackward",
|
||||
"Cyclic Expand Word (Backward)",
|
||||
(v, slot) => expandWord(v, slot, "forward"),
|
||||
{
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
},
|
||||
),
|
||||
text("editor.copyReference", "Copy Reference", (v, slot) => copyReference(v, slot), {
|
||||
category: "Edit",
|
||||
keywords: ["fully qualified name", "fqn", "copy path"],
|
||||
}),
|
||||
text("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), { category: "Edit", icon: "paste" }),
|
||||
text("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), {
|
||||
category: "Edit",
|
||||
icon: "paste",
|
||||
}),
|
||||
{
|
||||
id: "editor.toggleSoftWrap",
|
||||
title: "Soft-Wrap",
|
||||
@@ -386,17 +467,29 @@ export function registerEditorActions(): () => void {
|
||||
},
|
||||
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
|
||||
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
|
||||
text("code.collapseRecursively", "Collapse Recursively", (v) => collapseRecursively(v), { category: "Folding", keywords: ["fold"] }),
|
||||
text("code.expandRecursively", "Expand Recursively", (v) => expandRecursively(v), { category: "Folding", keywords: ["unfold"] }),
|
||||
text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addNextOccurrence(v), { category: "Edit" }),
|
||||
text("code.collapseRecursively", "Collapse Recursively", (v) => collapseRecursively(v), {
|
||||
category: "Folding",
|
||||
keywords: ["fold"],
|
||||
}),
|
||||
text("code.expandRecursively", "Expand Recursively", (v) => expandRecursively(v), {
|
||||
category: "Folding",
|
||||
keywords: ["unfold"],
|
||||
}),
|
||||
text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addNextOccurrence(v), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.selectAllOccurrences", "Select All Occurrences", (v) => selectAllOccurrences(v), { category: "Edit" }),
|
||||
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
|
||||
text("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
|
||||
text("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
|
||||
text("code.splitLine", "Split Line", (v) => splitLine(v)),
|
||||
text("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
|
||||
text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), { category: "Editor Actions" }),
|
||||
text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), { category: "Editor Actions" }),
|
||||
text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => addCursorAbove(v), { category: "Editor Actions" }),
|
||||
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => addCursorBelow(v), { category: "Editor Actions" }),
|
||||
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
|
||||
@@ -414,12 +507,19 @@ export function registerEditorActions(): () => void {
|
||||
}),
|
||||
text("code.joinLines", "Join Lines", (v) => joinLines(v)),
|
||||
text("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
|
||||
text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), { category: "Edit" }),
|
||||
text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.unselectOccurrence", "Unselect Occurrence", (v) => unselectOccurrence(v), { category: "Edit" }),
|
||||
text("code.pasteFromHistory", "Paste from History…", (v) => pasteFromHistory(v), { category: "Edit", keywords: ["clipboard", "paste multiple"] }),
|
||||
text("code.pasteFromHistory", "Paste from History…", (v) => pasteFromHistory(v), {
|
||||
category: "Edit",
|
||||
keywords: ["clipboard", "paste multiple"],
|
||||
}),
|
||||
text("code.sortLines", "Sort Lines", (v) => sortLines(v), { category: "Edit" }),
|
||||
text("code.reverseLines", "Reverse Lines", (v) => reverseLines(v), { category: "Edit" }),
|
||||
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), { keywords: ["unwrap", "remove if"] }),
|
||||
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
|
||||
keywords: ["unwrap", "remove if"],
|
||||
}),
|
||||
text("code.foldSelection", "Fold Selection / Remove Region", (v) => foldSelection(v), { category: "Folding" }),
|
||||
{
|
||||
id: "editor.toggleColumnSelection",
|
||||
@@ -441,7 +541,12 @@ export function registerEditorActions(): () => void {
|
||||
when: "projectOpen",
|
||||
keywords: ["synchronize", "refresh", "revert"],
|
||||
run: ({ arg }) => {
|
||||
const paths = typeof arg === "string" ? [arg] : Array.isArray(arg) ? arg.filter((p): p is string => typeof p === "string") : [];
|
||||
const paths =
|
||||
typeof arg === "string"
|
||||
? [arg]
|
||||
: Array.isArray(arg)
|
||||
? arg.filter((p): p is string => typeof p === "string")
|
||||
: [];
|
||||
const active = ctrl.activePath();
|
||||
return ctrl.reloadFromDisk(paths.length ? paths : active ? [active] : []);
|
||||
},
|
||||
@@ -622,7 +727,13 @@ export function registerEditorActions(): () => void {
|
||||
run: () => ctrl.reopenClosed(),
|
||||
},
|
||||
{ id: "editor.nextTab", title: "Select Next Tab", category: "Window", when: TABS_WHEN, run: () => ctrl.cycle(1) },
|
||||
{ id: "editor.prevTab", title: "Select Previous Tab", category: "Window", when: TABS_WHEN, run: () => ctrl.cycle(-1) },
|
||||
{
|
||||
id: "editor.prevTab",
|
||||
title: "Select Previous Tab",
|
||||
category: "Window",
|
||||
when: TABS_WHEN,
|
||||
run: () => ctrl.cycle(-1),
|
||||
},
|
||||
{
|
||||
id: "editor.splitRight",
|
||||
title: "Split Right",
|
||||
|
||||
@@ -93,23 +93,131 @@ interface MemDoc {
|
||||
}
|
||||
|
||||
const EXT_LANG: Record<string, string> = {
|
||||
ts: "typescript", tsx: "typescriptreact", js: "javascript", jsx: "javascriptreact", rs: "rust", kt: "kotlin",
|
||||
kts: "kotlin", java: "java", py: "python", go: "go", json: "json", md: "markdown", css: "css", html: "html",
|
||||
yml: "yaml", yaml: "yaml", toml: "toml", c: "c", cpp: "cpp", h: "c", sh: "shellscript", sql: "sql", xml: "xml",
|
||||
ts: "typescript",
|
||||
tsx: "typescriptreact",
|
||||
js: "javascript",
|
||||
jsx: "javascriptreact",
|
||||
rs: "rust",
|
||||
kt: "kotlin",
|
||||
kts: "kotlin",
|
||||
java: "java",
|
||||
py: "python",
|
||||
go: "go",
|
||||
json: "json",
|
||||
md: "markdown",
|
||||
css: "css",
|
||||
html: "html",
|
||||
yml: "yaml",
|
||||
yaml: "yaml",
|
||||
toml: "toml",
|
||||
c: "c",
|
||||
cpp: "cpp",
|
||||
h: "c",
|
||||
sh: "shellscript",
|
||||
sql: "sql",
|
||||
xml: "xml",
|
||||
};
|
||||
|
||||
const MEM_LANGUAGES: LanguageInfo[] = [
|
||||
{ id: "typescript", name: "TypeScript", extensions: ["ts"], uiMode: "TypeScript", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
|
||||
{ id: "typescriptreact", name: "TypeScript JSX", extensions: ["tsx"], uiMode: "TSX", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
|
||||
{ id: "javascript", name: "JavaScript", extensions: ["js"], uiMode: "JavaScript", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
|
||||
{ id: "rust", name: "Rust", extensions: ["rs"], uiMode: "Rust", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
|
||||
{ id: "kotlin", name: "Kotlin", extensions: ["kt", "kts"], uiMode: "Kotlin", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
|
||||
{ id: "java", name: "Java", extensions: ["java"], uiMode: "Java", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
|
||||
{ id: "python", name: "Python", extensions: ["py"], uiMode: "Python", lineComment: "#", blockComment: null, indent: null },
|
||||
{ id: "json", name: "JSON", extensions: ["json"], uiMode: "JSON", lineComment: null, blockComment: null, indent: { tabSize: 2, insertSpaces: true } },
|
||||
{ id: "markdown", name: "Markdown", extensions: ["md"], uiMode: "Markdown", lineComment: null, blockComment: ["<!--", "-->"], indent: null },
|
||||
{ id: "yaml", name: "YAML", extensions: ["yml", "yaml"], uiMode: "YAML", lineComment: "#", blockComment: null, indent: { tabSize: 2, insertSpaces: true } },
|
||||
{ id: "plaintext", name: "Plain Text", extensions: ["txt"], uiMode: null, lineComment: null, blockComment: null, indent: null },
|
||||
{
|
||||
id: "typescript",
|
||||
name: "TypeScript",
|
||||
extensions: ["ts"],
|
||||
uiMode: "TypeScript",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: { tabSize: 2, insertSpaces: true },
|
||||
},
|
||||
{
|
||||
id: "typescriptreact",
|
||||
name: "TypeScript JSX",
|
||||
extensions: ["tsx"],
|
||||
uiMode: "TSX",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: { tabSize: 2, insertSpaces: true },
|
||||
},
|
||||
{
|
||||
id: "javascript",
|
||||
name: "JavaScript",
|
||||
extensions: ["js"],
|
||||
uiMode: "JavaScript",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: { tabSize: 2, insertSpaces: true },
|
||||
},
|
||||
{
|
||||
id: "rust",
|
||||
name: "Rust",
|
||||
extensions: ["rs"],
|
||||
uiMode: "Rust",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "kotlin",
|
||||
name: "Kotlin",
|
||||
extensions: ["kt", "kts"],
|
||||
uiMode: "Kotlin",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "java",
|
||||
name: "Java",
|
||||
extensions: ["java"],
|
||||
uiMode: "Java",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "python",
|
||||
name: "Python",
|
||||
extensions: ["py"],
|
||||
uiMode: "Python",
|
||||
lineComment: "#",
|
||||
blockComment: null,
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "json",
|
||||
name: "JSON",
|
||||
extensions: ["json"],
|
||||
uiMode: "JSON",
|
||||
lineComment: null,
|
||||
blockComment: null,
|
||||
indent: { tabSize: 2, insertSpaces: true },
|
||||
},
|
||||
{
|
||||
id: "markdown",
|
||||
name: "Markdown",
|
||||
extensions: ["md"],
|
||||
uiMode: "Markdown",
|
||||
lineComment: null,
|
||||
blockComment: ["<!--", "-->"],
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "yaml",
|
||||
name: "YAML",
|
||||
extensions: ["yml", "yaml"],
|
||||
uiMode: "YAML",
|
||||
lineComment: "#",
|
||||
blockComment: null,
|
||||
indent: { tabSize: 2, insertSpaces: true },
|
||||
},
|
||||
{
|
||||
id: "plaintext",
|
||||
name: "Plain Text",
|
||||
extensions: ["txt"],
|
||||
uiMode: null,
|
||||
lineComment: null,
|
||||
blockComment: null,
|
||||
indent: null,
|
||||
},
|
||||
];
|
||||
|
||||
const SAMPLE_KOTLIN = `package com.acme.orders
|
||||
@@ -314,7 +422,10 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
async outline(doc) {
|
||||
// Brace-based outline good enough for the dev shell.
|
||||
const d = get(doc);
|
||||
const posAt = ((index) => (_text: string, offset: number) => index(offset))(lineIndex(d.text));
|
||||
const posAt = (
|
||||
(index) => (_text: string, offset: number) =>
|
||||
index(offset)
|
||||
)(lineIndex(d.text));
|
||||
const items: OutlineItem[] = [];
|
||||
const re = /\b(class|fun|function|fn|interface|object)\s+([A-Za-z_]\w*)/g;
|
||||
for (let m = re.exec(d.text); m; m = re.exec(d.text)) {
|
||||
@@ -342,7 +453,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
};
|
||||
const parent = items.findLast(
|
||||
(p) =>
|
||||
(p.range.start.line < start.line || (p.range.start.line === start.line && p.range.start.col <= start.col)) &&
|
||||
(p.range.start.line < start.line ||
|
||||
(p.range.start.line === start.line && p.range.start.col <= start.col)) &&
|
||||
(p.range.end.line > start.line || (p.range.end.line === start.line && p.range.end.col >= start.col)),
|
||||
);
|
||||
if (parent) parent.children.push(item);
|
||||
|
||||
@@ -28,9 +28,21 @@ describe("clipboard history (Paste from History)", () => {
|
||||
it("copies the selections, or whole caret lines without a selection", () => {
|
||||
const doc = "one\ntwo\nthree";
|
||||
const ext = EditorState.allowMultipleSelections.of(true);
|
||||
const sel = EditorState.create({ doc, extensions: ext, selection: EditorSelection.create([EditorSelection.range(0, 3), EditorSelection.range(8, 13)]) });
|
||||
const sel = EditorState.create({
|
||||
doc,
|
||||
extensions: ext,
|
||||
selection: EditorSelection.create([EditorSelection.range(0, 3), EditorSelection.range(8, 13)]),
|
||||
});
|
||||
expect(copiedText(sel)).toBe("one\nthree");
|
||||
const carets = EditorState.create({ doc, extensions: ext, selection: EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(2), EditorSelection.cursor(5)]) });
|
||||
const carets = EditorState.create({
|
||||
doc,
|
||||
extensions: ext,
|
||||
selection: EditorSelection.create([
|
||||
EditorSelection.cursor(1),
|
||||
EditorSelection.cursor(2),
|
||||
EditorSelection.cursor(5),
|
||||
]),
|
||||
});
|
||||
expect(copiedText(carets)).toBe("one\ntwo\n");
|
||||
});
|
||||
|
||||
|
||||
@@ -28,7 +28,11 @@ export function clearClipboardHistory() {
|
||||
/** What CodeMirror copies: the selections, or the caret lines when nothing is selected. */
|
||||
export function copiedText(state: EditorState): string {
|
||||
const ranges = state.selection.ranges;
|
||||
if (ranges.some((r) => !r.empty)) return ranges.filter((r) => !r.empty).map((r) => state.sliceDoc(r.from, r.to)).join(state.lineBreak);
|
||||
if (ranges.some((r) => !r.empty))
|
||||
return ranges
|
||||
.filter((r) => !r.empty)
|
||||
.map((r) => state.sliceDoc(r.from, r.to))
|
||||
.join(state.lineBreak);
|
||||
const lines: string[] = [];
|
||||
let last = -1;
|
||||
for (const r of ranges) {
|
||||
|
||||
@@ -14,7 +14,12 @@ afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
const braceIndent = indentService.of((cx, pos) => {
|
||||
const line = cx.lineAt(pos, -1);
|
||||
const base = /^ */.exec(line.text)![0].length;
|
||||
return line.text.slice(0, pos - line.from).trimEnd().endsWith("{") ? base + 2 : base;
|
||||
return line.text
|
||||
.slice(0, pos - line.from)
|
||||
.trimEnd()
|
||||
.endsWith("{")
|
||||
? base + 2
|
||||
: base;
|
||||
});
|
||||
|
||||
/** `|` marks carets. */
|
||||
@@ -96,7 +101,8 @@ describe("code block navigation", () => {
|
||||
describe("editor base keymap", () => {
|
||||
it("drops CodeMirror defaults that IDEA uses for other actions", () => {
|
||||
const runs = editorBaseKeymap.map((b) => b.run);
|
||||
for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove]) expect(runs).not.toContain(cmd);
|
||||
for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove])
|
||||
expect(runs).not.toContain(cmd);
|
||||
expect(editorBaseKeymap.some((b) => b.key === "Mod-Enter" || b.key === "Ctrl-m")).toBe(false);
|
||||
expect(editorBaseKeymap.some((b) => b.win === "Ctrl-Shift-z")).toBe(true);
|
||||
});
|
||||
|
||||
@@ -125,6 +125,10 @@ export const cursorMatchBrace: Command = (view) => {
|
||||
return EditorSelection.cursor(target);
|
||||
});
|
||||
if (!moved) return false;
|
||||
view.dispatch({ selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "select.navigate" });
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select.navigate",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
@@ -6,7 +6,9 @@ const doc = (text: string) => EditorState.create({ doc: text });
|
||||
|
||||
describe("code lens layout", () => {
|
||||
it("places lenses above attributes, annotations and doc comments", () => {
|
||||
const s = doc("mod a {\n /// Docs\n #[test]\n #[ignore]\n fn t() {}\n}\n@Test\nvoid x() {}\n/**\n * doc\n */\nfunction f() {}");
|
||||
const s = doc(
|
||||
"mod a {\n /// Docs\n #[test]\n #[ignore]\n fn t() {}\n}\n@Test\nvoid x() {}\n/**\n * doc\n */\nfunction f() {}",
|
||||
);
|
||||
expect(s.doc.lineAt(declarationStart(s, 5)).number).toBe(2);
|
||||
expect(s.doc.lineAt(declarationStart(s, 8)).number).toBe(7);
|
||||
expect(s.doc.lineAt(declarationStart(s, 12)).number).toBe(9);
|
||||
|
||||
@@ -7,7 +7,10 @@ import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemir
|
||||
import { codeLenses, type CodeLens } from "@/editor/api";
|
||||
|
||||
/** Groups lenses by line start, ordered by line then `order`. Exported for tests. */
|
||||
export function groupLenses(state: EditorState, lenses: readonly CodeLens[]): Array<{ lineFrom: number; lenses: CodeLens[] }> {
|
||||
export function groupLenses(
|
||||
state: EditorState,
|
||||
lenses: readonly CodeLens[],
|
||||
): Array<{ lineFrom: number; lenses: CodeLens[] }> {
|
||||
const byLine = new Map<number, CodeLens[]>();
|
||||
const len = state.doc.length;
|
||||
for (const l of lenses) {
|
||||
@@ -68,7 +71,11 @@ class LensWidget extends WidgetType {
|
||||
}
|
||||
|
||||
private get key(): string {
|
||||
return this.indent + "\u0000" + this.lenses.map((l) => `${l.icon ?? ""}|${l.title}|${l.tooltip ?? ""}|${l.run ? 1 : 0}`).join("\u0001");
|
||||
return (
|
||||
this.indent +
|
||||
"\u0000" +
|
||||
this.lenses.map((l) => `${l.icon ?? ""}|${l.title}|${l.tooltip ?? ""}|${l.run ? 1 : 0}`).join("\u0001")
|
||||
);
|
||||
}
|
||||
|
||||
override eq(other: LensWidget): boolean {
|
||||
@@ -184,7 +191,4 @@ const lensTheme = EditorView.theme({
|
||||
});
|
||||
|
||||
/** Base extension (always installed): no cost until a provider contributes lenses. */
|
||||
export const codeLensExtension: Extension = [
|
||||
EditorView.decorations.compute([codeLenses], buildDecorations),
|
||||
lensTheme,
|
||||
];
|
||||
export const codeLensExtension: Extension = [EditorView.decorations.compute([codeLenses], buildDecorations), lensTheme];
|
||||
@@ -12,7 +12,11 @@ afterEach(() => {
|
||||
|
||||
function make(doc: string, at: number) {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ doc, selection: { anchor: at }, extensions: [columnModeExtension, EditorState.allowMultipleSelections.of(true)] }),
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: { anchor: at },
|
||||
extensions: [columnModeExtension, EditorState.allowMultipleSelections.of(true)],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
return view;
|
||||
|
||||
@@ -2,7 +2,16 @@
|
||||
* Edit › Column Selection Mode (⇧⌘8): while on, a plain mouse drag and
|
||||
* ⇧+arrows make rectangular (block) selections, one range per line.
|
||||
*/
|
||||
import { EditorSelection, Prec, StateEffect, StateField, countColumn, findColumn, type EditorState, type Extension } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
countColumn,
|
||||
findColumn,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
} from "@codemirror/state";
|
||||
import { EditorView, keymap, rectangularSelection } from "@codemirror/view";
|
||||
|
||||
/** A block between two visual columns (tabs expanded) of two lines. */
|
||||
@@ -79,7 +88,12 @@ export function extendBlock(view: EditorView, dLine: number, dCol: number): bool
|
||||
const a = state.doc.lineAt(main.anchor);
|
||||
const h = state.doc.lineAt(main.head);
|
||||
const col = (text: string, offset: number) => countColumn(text, state.tabSize, offset);
|
||||
b = { anchorLine: a.number, anchorCol: col(a.text, main.anchor - a.from), headLine: h.number, headCol: col(h.text, main.head - h.from) };
|
||||
b = {
|
||||
anchorLine: a.number,
|
||||
anchorCol: col(a.text, main.anchor - a.from),
|
||||
headLine: h.number,
|
||||
headCol: col(h.text, main.head - h.from),
|
||||
};
|
||||
}
|
||||
const headLine = Math.max(1, Math.min(state.doc.lines, b.headLine + dLine));
|
||||
const next = { ...b, headLine, headCol: stepColumn(state.doc.line(b.headLine).text, b.headCol, dCol, state.tabSize) };
|
||||
@@ -113,5 +127,7 @@ export const columnModeExtension: Extension = [
|
||||
{ key: "Shift-ArrowRight", run: (v) => extendBlock(v, 0, 1) },
|
||||
]),
|
||||
),
|
||||
EditorView.editorAttributes.compute([columnModeField], (s): Record<string, string> => (isColumnMode(s) ? { class: "cm-openidea-columnMode" } : {})),
|
||||
EditorView.editorAttributes.compute([columnModeField], (s): Record<string, string> =>
|
||||
isColumnMode(s) ? { class: "cm-openidea-columnMode" } : {},
|
||||
),
|
||||
];
|
||||
@@ -1,7 +1,14 @@
|
||||
/**
|
||||
* Comment with Line Comment and Enter inside a line comment, as in IDEA.
|
||||
*/
|
||||
import { EditorSelection, Facet, countColumn, type ChangeSpec, type EditorState, type SelectionRange } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
Facet,
|
||||
countColumn,
|
||||
type ChangeSpec,
|
||||
type EditorState,
|
||||
type SelectionRange,
|
||||
} from "@codemirror/state";
|
||||
import type { Command, EditorView } from "@codemirror/view";
|
||||
import { indentString, syntaxTree } from "@codemirror/language";
|
||||
import { toggleComment } from "@codemirror/commands";
|
||||
@@ -57,12 +64,16 @@ export const commentLine: Command = (view) => {
|
||||
if (!block) blocks.push(target);
|
||||
target.ranges.push(i);
|
||||
target.endLine = Math.max(target.endLine, endLine);
|
||||
const wholeLines = r.empty || (r.from === doc.lineAt(r.from).from && r.to === doc.lineAt(r.to).from && r.to > r.from);
|
||||
const wholeLines =
|
||||
r.empty || (r.from === doc.lineAt(r.from).from && r.to === doc.lineAt(r.to).from && r.to > r.from);
|
||||
const emptyLine = !doc.lineAt(r.from).text.trim();
|
||||
target.caretUpdate = r.empty && emptyLine && !repeated ? "commentStart" : r.empty ? "down" : wholeLines ? "restoreSelection" : null;
|
||||
target.caretUpdate =
|
||||
r.empty && emptyLine && !repeated ? "commentStart" : r.empty ? "down" : wholeLines ? "restoreSelection" : null;
|
||||
}
|
||||
|
||||
const tokens = blocks.map((b) => lineToken(state, doc.line(b.startLine).from + leadingWs(doc.line(b.startLine).text)));
|
||||
const tokens = blocks.map((b) =>
|
||||
lineToken(state, doc.line(b.startLine).from + leadingWs(doc.line(b.startLine).text)),
|
||||
);
|
||||
// Languages without line comments (CSS, HTML…): block comments.
|
||||
if (tokens.some((t) => !t)) return toggleComment(view);
|
||||
|
||||
|
||||
@@ -16,7 +16,11 @@ function mount(s: EditorSettings | undefined) {
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: "fn main() {}\n",
|
||||
extensions: [lineNumbersExtension(s), distractionFreeExtension(s), prefsFor({ settings: s, path: "/p/a.rs", info: undefined, readOnly: false })],
|
||||
extensions: [
|
||||
lineNumbersExtension(s),
|
||||
distractionFreeExtension(s),
|
||||
prefsFor({ settings: s, path: "/p/a.rs", info: undefined, readOnly: false }),
|
||||
],
|
||||
}),
|
||||
});
|
||||
return { view, dispose: () => (view.destroy(), parent.remove()) };
|
||||
|
||||
@@ -54,7 +54,9 @@ function show(view: EditorView): string {
|
||||
const { doc, selection } = view.state;
|
||||
let out = doc.toString();
|
||||
for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
|
||||
out = r.empty ? out.slice(0, r.head) + "|" + out.slice(r.head) : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
|
||||
out = r.empty
|
||||
? out.slice(0, r.head) + "|" + out.slice(r.head)
|
||||
: out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -98,8 +100,21 @@ describe("join lines", () => {
|
||||
});
|
||||
|
||||
it("merges consecutive line comments and keeps brackets tight", () => {
|
||||
expect((() => { const v = make("// one|\n// two"); joinLines(v); return v.state.doc.toString(); })()).toBe("// one two");
|
||||
expect((() => { const v = make("f(|\n x\n)"); joinLines(v); joinLines(v); return v.state.doc.toString(); })()).toBe("f(x)");
|
||||
expect(
|
||||
(() => {
|
||||
const v = make("// one|\n// two");
|
||||
joinLines(v);
|
||||
return v.state.doc.toString();
|
||||
})(),
|
||||
).toBe("// one two");
|
||||
expect(
|
||||
(() => {
|
||||
const v = make("f(|\n x\n)");
|
||||
joinLines(v);
|
||||
joinLines(v);
|
||||
return v.state.doc.toString();
|
||||
})(),
|
||||
).toBe("f(x)");
|
||||
});
|
||||
|
||||
it("does nothing on the last line", () => {
|
||||
@@ -163,7 +178,10 @@ describe("multiple carets", () => {
|
||||
expect(toggleCaret(start, 3, 3).ranges.map((r) => r.head)).toEqual([1, 3, 5]);
|
||||
expect(toggleCaret(start, 5, 5).ranges.map((r) => r.head)).toEqual([1]);
|
||||
expect(toggleCaret(EditorSelection.single(2), 2, 2).ranges.map((r) => r.head)).toEqual([2]);
|
||||
expect(toggleCaret(EditorSelection.single(0), 2, 4).ranges.map((r) => [r.from, r.to])).toEqual([[0, 0], [2, 4]]);
|
||||
expect(toggleCaret(EditorSelection.single(0), 2, 4).ranges.map((r) => [r.from, r.to])).toEqual([
|
||||
[0, 0],
|
||||
[2, 4],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,14 @@ import {
|
||||
type TransactionSpec,
|
||||
} from "@codemirror/state";
|
||||
import { EditorView, type Command } from "@codemirror/view";
|
||||
import { foldedRanges, forceParsing, syntaxTree, getIndentUnit, indentString, getIndentation } from "@codemirror/language";
|
||||
import {
|
||||
foldedRanges,
|
||||
forceParsing,
|
||||
syntaxTree,
|
||||
getIndentUnit,
|
||||
indentString,
|
||||
getIndentation,
|
||||
} from "@codemirror/language";
|
||||
import {
|
||||
copyLineDown,
|
||||
deleteLine as deleteDocLine,
|
||||
@@ -69,7 +76,9 @@ function deleteHump(forward: boolean, camel = true): Command {
|
||||
const to = Math.max(target, r.head);
|
||||
return { changes: { from, to }, range: EditorSelection.cursor(from) };
|
||||
});
|
||||
view.dispatch(view.state.update(tr, { scrollIntoView: true, userEvent: forward ? "delete.forward" : "delete.backward" }));
|
||||
view.dispatch(
|
||||
view.state.update(tr, { scrollIntoView: true, userEvent: forward ? "delete.forward" : "delete.backward" }),
|
||||
);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -89,7 +98,7 @@ export function visualLineSpan(state: EditorState, from: number, to: number): {
|
||||
let a = state.doc.lineAt(from).from;
|
||||
let b = state.doc.lineAt(to).to;
|
||||
const folded = foldedRanges(state);
|
||||
for (let changed = true; changed; ) {
|
||||
for (let changed = true; changed;) {
|
||||
changed = false;
|
||||
folded.between(a, b, (f, t) => {
|
||||
const na = Math.min(a, state.doc.lineAt(f).from);
|
||||
@@ -127,12 +136,19 @@ export const duplicateLineOrSelection: Command = (view) => {
|
||||
const spans = foldedLineSpans(state);
|
||||
if (!spans) return copyLineDown(view);
|
||||
// On a folded region's line the whole folded block is duplicated.
|
||||
const changes = state.changes(spans.map((s) => ({ from: s.to, insert: state.lineBreak + state.sliceDoc(s.from, s.to) })));
|
||||
const changes = state.changes(
|
||||
spans.map((s) => ({ from: s.to, insert: state.lineBreak + state.sliceDoc(s.from, s.to) })),
|
||||
);
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
const s = spans.find((sp) => sp.from <= r.head && r.head <= sp.to)!;
|
||||
return EditorSelection.cursor(changes.mapPos(r.head, -1) + s.to - s.from + state.lineBreak.length);
|
||||
});
|
||||
view.dispatch({ changes, selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "input.duplicate" });
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "input.duplicate",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
const tr = state.changeByRange((r) => {
|
||||
@@ -169,7 +185,12 @@ export const deleteLine: Command = (view) => {
|
||||
const line = doc.lineAt(changes.mapPos(r.head, -1));
|
||||
return EditorSelection.cursor(line.from + Math.min(col, line.length));
|
||||
});
|
||||
view.dispatch({ changes, selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "delete.line" });
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "delete.line",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -194,7 +215,8 @@ export const occurrenceSearch = StateField.define<OccurrenceSearch | null>({
|
||||
});
|
||||
|
||||
const IDENT = /[\p{L}\p{N}_$]/u;
|
||||
const identAt = (state: EditorState, pos: number) => pos >= 0 && pos < state.doc.length && IDENT.test(state.sliceDoc(pos, pos + 1));
|
||||
const identAt = (state: EditorState, pos: number) =>
|
||||
pos >= 0 && pos < state.doc.length && IDENT.test(state.sliceDoc(pos, pos + 1));
|
||||
|
||||
/** The identifier at or right before `pos`. */
|
||||
export function identifierAt(state: EditorState, pos: number): { from: number; to: number } | null {
|
||||
@@ -221,7 +243,9 @@ function* matches(state: EditorState, text: string, from: number, wholeWords: bo
|
||||
|
||||
/** A selection of `m` with the head on the same side as in `like`. */
|
||||
const rangeLike = (like: SelectionRange, m: { from: number; to: number }) =>
|
||||
like.head === like.from && like.from !== like.to ? EditorSelection.range(m.to, m.from) : EditorSelection.range(m.from, m.to);
|
||||
like.head === like.from && like.from !== like.to
|
||||
? EditorSelection.range(m.to, m.from)
|
||||
: EditorSelection.range(m.from, m.to);
|
||||
|
||||
/**
|
||||
* ⌃G: Add Selection for Next Occurrence. From a bare caret it selects the
|
||||
@@ -323,13 +347,15 @@ function statementStartingAt(state: EditorState, lineNo: number): Node | null {
|
||||
}
|
||||
|
||||
/** Lines a moved statement stops at: blank lines, statement starts and closing braces of blocks. */
|
||||
const isStopLine = (state: EditorState, lineNo: number) => firstToken(state, lineNo) === null || !!statementStartingAt(state, lineNo);
|
||||
const isStopLine = (state: EditorState, lineNo: number) =>
|
||||
firstToken(state, lineNo) === null || !!statementStartingAt(state, lineNo);
|
||||
|
||||
/** The statement containing the first token of the caret line. */
|
||||
function statementAround(state: EditorState, pos: number): Node | null {
|
||||
const start = firstToken(state, state.doc.lineAt(pos).number);
|
||||
if (start === null) return null;
|
||||
for (let n: Node | null = syntaxTree(state).resolveInner(start, 1); n && n.parent; n = n.parent) if (isContainer(n.parent)) return n;
|
||||
for (let n: Node | null = syntaxTree(state).resolveInner(start, 1); n && n.parent; n = n.parent)
|
||||
if (isContainer(n.parent)) return n;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -460,7 +486,7 @@ function shiftToIndentation(state: EditorState, from: number, to: number) {
|
||||
const delta = proper - countColumn(/^\s*/.exec(first.text)![0], state.tabSize);
|
||||
if (!delta) return null;
|
||||
const changes: ChangeSpec[] = [];
|
||||
for (let pos = from; pos <= to; ) {
|
||||
for (let pos = from; pos <= to;) {
|
||||
const line = state.doc.lineAt(pos);
|
||||
pos = line.to + 1;
|
||||
const ws = /^\s*/.exec(line.text)![0];
|
||||
@@ -494,18 +520,53 @@ export const moveStatementDown = moveStatement(false);
|
||||
// --- complete statement -------------------------------------------------------
|
||||
|
||||
export const SEMICOLON_LANGS = new Set([
|
||||
"java", "c", "cpp", "csharp", "javascript", "javascriptreact", "typescript", "typescriptreact", "rust", "php",
|
||||
"dart", "objective-c", "objective-cpp", "groovy", "zig",
|
||||
"java",
|
||||
"c",
|
||||
"cpp",
|
||||
"csharp",
|
||||
"javascript",
|
||||
"javascriptreact",
|
||||
"typescript",
|
||||
"typescriptreact",
|
||||
"rust",
|
||||
"php",
|
||||
"dart",
|
||||
"objective-c",
|
||||
"objective-cpp",
|
||||
"groovy",
|
||||
"zig",
|
||||
]);
|
||||
/** Blocks close with a keyword (`end`) or by indentation: never complete them with braces. */
|
||||
export const KEYWORD_BLOCK_LANGS = new Set([
|
||||
"python", "ruby", "lua", "elixir", "haskell", "shellscript", "julia", "erlang", "fsharp", "ocaml", "ocaml.interface",
|
||||
"yaml", "markdown", "plaintext", "makefile", "cmake", "toml", "ini", "properties", "sql", "r", "perl", "powershell",
|
||||
"python",
|
||||
"ruby",
|
||||
"lua",
|
||||
"elixir",
|
||||
"haskell",
|
||||
"shellscript",
|
||||
"julia",
|
||||
"erlang",
|
||||
"fsharp",
|
||||
"ocaml",
|
||||
"ocaml.interface",
|
||||
"yaml",
|
||||
"markdown",
|
||||
"plaintext",
|
||||
"makefile",
|
||||
"cmake",
|
||||
"toml",
|
||||
"ini",
|
||||
"properties",
|
||||
"sql",
|
||||
"r",
|
||||
"perl",
|
||||
"powershell",
|
||||
]);
|
||||
/** A line opening an indented body in `end` / layout languages (Ruby, Lua, Elixir, Haskell…). */
|
||||
const KEYWORD_HEAD =
|
||||
/\b(do(\s*\|[^|]*\|)?|then|where|of)$|^\s*(def|defp|defmodule|class|module|function|local function|if|unless|elsif|elseif|else|while|until|for|case|begin)\b/;
|
||||
const BLOCK_HEAD = /^\s*(if|else|for|while|do|switch|try|catch|finally|fn|fun|func|function|class|struct|enum|impl|trait|interface|object|match|when|loop|unsafe|mod|namespace)\b/;
|
||||
const BLOCK_HEAD =
|
||||
/^\s*(if|else|for|while|do|switch|try|catch|finally|fn|fun|func|function|class|struct|enum|impl|trait|interface|object|match|when|loop|unsafe|mod|namespace)\b/;
|
||||
|
||||
/** Offset in `text` where a trailing line comment starts (outside string literals), else `text.length`. */
|
||||
export function codeEnd(text: string, lineComment: string | undefined): number {
|
||||
@@ -548,7 +609,11 @@ export function completeStatementSpec(state: EditorState, language: string): Tra
|
||||
const from = line.from + text.length;
|
||||
return {
|
||||
// A trailing comment moves to the end of the header line.
|
||||
changes: { from, to: line.from + full.length, insert: insert.slice(0, 2) + full.slice(text.length) + insert.slice(2) },
|
||||
changes: {
|
||||
from,
|
||||
to: line.from + full.length,
|
||||
insert: insert.slice(0, 2) + full.slice(text.length) + insert.slice(2),
|
||||
},
|
||||
selection: { anchor: from + 2 + full.length - text.length + br.length + baseIndent.length + unit.length },
|
||||
scrollIntoView: true,
|
||||
userEvent: "input.complete",
|
||||
@@ -556,9 +621,13 @@ export function completeStatementSpec(state: EditorState, language: string): Tra
|
||||
}
|
||||
let insert = "";
|
||||
if (SEMICOLON_LANGS.has(language) && !comment && text.trim() && !/[;{},:]$/.test(text)) insert = ";";
|
||||
if (language === "python" && BLOCK_HEAD.test(text.replace(/^\s*(def|elif)\b/, "if")) && !text.endsWith(":")) insert = ":";
|
||||
if (language === "python" && BLOCK_HEAD.test(text.replace(/^\s*(def|elif)\b/, "if")) && !text.endsWith(":"))
|
||||
insert = ":";
|
||||
const opensBlock =
|
||||
text.endsWith("{") || insert === ":" || text.endsWith(":") || (KEYWORD_BLOCK_LANGS.has(language) && KEYWORD_HEAD.test(text) && !/^\s*module\b.*\bwhere$/.test(text));
|
||||
text.endsWith("{") ||
|
||||
insert === ":" ||
|
||||
text.endsWith(":") ||
|
||||
(KEYWORD_BLOCK_LANGS.has(language) && KEYWORD_HEAD.test(text) && !/^\s*module\b.*\bwhere$/.test(text));
|
||||
const nextIndent = baseIndent + (opensBlock ? unit : "");
|
||||
const indentHere = getIndentation(state, line.to);
|
||||
const newline = br + (indentHere !== null && !opensBlock ? indentString(state, indentHere) : nextIndent);
|
||||
@@ -615,7 +684,10 @@ function newLineCommand(before: boolean): Command {
|
||||
const computed = syntaxTree(state).length ? getIndentation(state, line.from) : null;
|
||||
let indent = computed !== null ? indentString(state, computed) : own;
|
||||
if (/^\s*[)\]}]/.test(line.text) && indent.length <= own.length) indent = own + unit;
|
||||
return { changes: { from: line.from, insert: indent + state.lineBreak }, range: EditorSelection.cursor(line.from + indent.length) };
|
||||
return {
|
||||
changes: { from: line.from, insert: indent + state.lineBreak },
|
||||
range: EditorSelection.cursor(line.from + indent.length),
|
||||
};
|
||||
});
|
||||
view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input" }));
|
||||
return true;
|
||||
@@ -665,13 +737,22 @@ export const joinLines: Command = (view) => {
|
||||
// Drop the comment marker of a joined line comment (`// a` + `// b` → `// a b`).
|
||||
const comment = /^(\/\/+|#+|--)\s?/.exec(nextText);
|
||||
const curTrim = cur.text.slice(0, cur.length - trail);
|
||||
const skip = comment && new RegExp(`(^|\\s)${comment[1]!.replace(/[-/#]/g, "\\$&")}`).test(curTrim) ? comment[0].length : 0;
|
||||
const sep = !curTrim.length || !nextText.length || /[([{]$/.test(curTrim) || /^[)\]}.,;]/.test(nextText.slice(skip)) ? "" : " ";
|
||||
const skip =
|
||||
comment && new RegExp(`(^|\\s)${comment[1]!.replace(/[-/#]/g, "\\$&")}`).test(curTrim) ? comment[0].length : 0;
|
||||
const sep =
|
||||
!curTrim.length || !nextText.length || /[([{]$/.test(curTrim) || /^[)\]}.,;]/.test(nextText.slice(skip))
|
||||
? ""
|
||||
: " ";
|
||||
changes.push({ from: cur.to - trail, to: next.from + lead + skip, insert: sep });
|
||||
if (n === first.number) caret = cur.to - trail;
|
||||
}
|
||||
const set = state.changes(changes);
|
||||
return { changes: set, range: r.empty ? EditorSelection.cursor(set.mapPos(caret, -1)) : EditorSelection.range(set.mapPos(r.from, 1), set.mapPos(r.to, -1)) };
|
||||
return {
|
||||
changes: set,
|
||||
range: r.empty
|
||||
? EditorSelection.cursor(set.mapPos(caret, -1))
|
||||
: EditorSelection.range(set.mapPos(r.from, 1), set.mapPos(r.to, -1)),
|
||||
};
|
||||
});
|
||||
view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input.join" }));
|
||||
return true;
|
||||
@@ -713,7 +794,9 @@ export const toggleCase: Command = (view) => {
|
||||
const t = targets[state.selection.ranges.indexOf(r)];
|
||||
if (!t) return { range: r };
|
||||
const insert = caseOf(state, t.from, t.to, lower);
|
||||
const range = r.empty ? EditorSelection.range(t.from, t.from + insert.length) : EditorSelection.range(r.anchor, r.head);
|
||||
const range = r.empty
|
||||
? EditorSelection.range(t.from, t.from + insert.length)
|
||||
: EditorSelection.range(r.anchor, r.head);
|
||||
return { changes: { from: t.from, to: t.to, insert }, range };
|
||||
});
|
||||
view.dispatch(state.update(tr, { userEvent: "input.case" }));
|
||||
@@ -735,7 +818,11 @@ export const addCaretsToLineEnds: Command = (view) => {
|
||||
for (let n = first; n <= last; n++) ranges.push(EditorSelection.cursor(state.doc.line(n).to));
|
||||
}
|
||||
if (ranges.length === state.selection.ranges.length && state.selection.ranges.every((r) => r.empty)) return false;
|
||||
view.dispatch({ selection: EditorSelection.create(ranges, ranges.length - 1), scrollIntoView: true, userEvent: "select" });
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, ranges.length - 1),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -759,6 +846,11 @@ export const unselectOccurrence: Command = (view) => {
|
||||
main = i;
|
||||
break;
|
||||
}
|
||||
view.dispatch({ selection: EditorSelection.create(ranges, main), effects, scrollIntoView: true, userEvent: "select" });
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, main),
|
||||
effects,
|
||||
scrollIntoView: true,
|
||||
userEvent: "select",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
@@ -26,7 +26,10 @@ const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
|
||||
function make(doc: string, o: Partial<FindOptions>, scope?: { from: number; to: number }) {
|
||||
const view = new EditorView({ state: EditorState.create({ doc, extensions: [findExtension()] }), parent: document.body });
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [findExtension()] }),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
const q = makeQuery({ search: "", caseSensitive: false, wholeWord: false, regexp: false, replace: "", ...o });
|
||||
view.dispatch({ effects: [setSearchQuery.of(q), ...(scope ? [setFindScope.of(scope)] : [])] });
|
||||
|
||||
@@ -7,7 +7,15 @@
|
||||
* string literals) and excluded matches filter matches through the query's
|
||||
* `test`, so CodeMirror's own commands honour them too.
|
||||
*/
|
||||
import { EditorSelection, Prec, StateEffect, StateField, type ChangeDesc, type EditorState, type Extension } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
type ChangeDesc,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
} from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
SearchQuery,
|
||||
@@ -52,7 +60,10 @@ export const findScope = StateField.define<FindScope | null>({
|
||||
return v && tr.docChanged ? mapScope(v, tr.changes) : v;
|
||||
},
|
||||
// Lowest precedence: the scope's mark wraps the match marks, which stay visible inside it.
|
||||
provide: (f) => Prec.lowest(EditorView.decorations.from(f, (s) => (s ? Decoration.set([scopeDeco.range(s.from, s.to)]) : Decoration.none))),
|
||||
provide: (f) =>
|
||||
Prec.lowest(
|
||||
EditorView.decorations.from(f, (s) => (s ? Decoration.set([scopeDeco.range(s.from, s.to)]) : Decoration.none)),
|
||||
),
|
||||
});
|
||||
|
||||
/** IDEA's Exclude: matches skipped by Next / Previous and Replace All until the query changes. */
|
||||
@@ -234,7 +245,10 @@ export function regexValid(source: string): boolean {
|
||||
export const MAX_COUNT = 9_999;
|
||||
|
||||
/** Counts matches (capped) and the 1-based index of the selected one. */
|
||||
export function countMatches(state: EditorState, budgetMs = 30): { total: number; current: number; capped: boolean; starts: number[] } {
|
||||
export function countMatches(
|
||||
state: EditorState,
|
||||
budgetMs = 30,
|
||||
): { total: number; current: number; capped: boolean; starts: number[] } {
|
||||
const query = getSearchQuery(state);
|
||||
if (!query.valid) return { total: 0, current: 0, capped: false, starts: [] };
|
||||
const main = state.selection.main;
|
||||
@@ -270,7 +284,8 @@ function matchesIn(state: EditorState, limit = Infinity): Match[] {
|
||||
const scope = scopeOf(state);
|
||||
const out: Match[] = [];
|
||||
const cursor = query.getCursor(state, scope.from, scope.to);
|
||||
for (let r = cursor.next(); !r.done && out.length < limit; r = cursor.next()) if (r.value.to > r.value.from) out.push(r.value as Match);
|
||||
for (let r = cursor.next(); !r.done && out.length < limit; r = cursor.next())
|
||||
if (r.value.to > r.value.from) out.push(r.value as Match);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -293,7 +308,9 @@ function step(view: EditorView, forward: boolean): boolean {
|
||||
const ms = matchesIn(view.state);
|
||||
if (!ms.length) return false;
|
||||
const { from, to } = view.state.selection.main;
|
||||
const m = forward ? (ms.find((x) => x.from >= to && !(x.from === from && x.to === to)) ?? ms[0]!) : ([...ms].reverse().find((x) => x.to <= from) ?? ms[ms.length - 1]!);
|
||||
const m = forward
|
||||
? (ms.find((x) => x.from >= to && !(x.from === from && x.to === to)) ?? ms[0]!)
|
||||
: ([...ms].reverse().find((x) => x.to <= from) ?? ms[ms.length - 1]!);
|
||||
selectMatch(view, m);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,15 @@
|
||||
*/
|
||||
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Line } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { codeFolding, foldEffect, foldGutter, foldService, foldable, foldedRanges, unfoldEffect } from "@codemirror/language";
|
||||
import {
|
||||
codeFolding,
|
||||
foldEffect,
|
||||
foldGutter,
|
||||
foldService,
|
||||
foldable,
|
||||
foldedRanges,
|
||||
unfoldEffect,
|
||||
} from "@codemirror/language";
|
||||
import type { FoldRange } from "@/platform/ipc";
|
||||
|
||||
export interface BackendFold {
|
||||
@@ -182,7 +190,8 @@ export function foldSelection(view: EditorView): boolean {
|
||||
const sel = view.state.selection;
|
||||
const folded = effects.filter((e) => e.is(foldEffect)).map((e) => e.value as { from: number; to: number });
|
||||
// The caret lands after the new fold, like IDEA.
|
||||
const after = sel.ranges.some((r) => !r.empty) && folded.length ? { anchor: folded[folded.length - 1]!.to } : undefined;
|
||||
const after =
|
||||
sel.ranges.some((r) => !r.empty) && folded.length ? { anchor: folded[folded.length - 1]!.to } : undefined;
|
||||
view.dispatch({ effects, selection: after });
|
||||
return true;
|
||||
}
|
||||
@@ -196,9 +205,13 @@ function isFolded(state: EditorState, r: { from: number; to: number }): boolean
|
||||
}
|
||||
|
||||
/** Every foldable region (nested ones included) of the lines in `[from, to]`, kept within `[from, to]`. */
|
||||
export function foldableRegions(state: EditorState, from = 0, to = state.doc.length): Array<{ from: number; to: number }> {
|
||||
export function foldableRegions(
|
||||
state: EditorState,
|
||||
from = 0,
|
||||
to = state.doc.length,
|
||||
): Array<{ from: number; to: number }> {
|
||||
const out: Array<{ from: number; to: number }> = [];
|
||||
for (let pos = state.doc.lineAt(from).from; pos <= to; ) {
|
||||
for (let pos = state.doc.lineAt(from).from; pos <= to;) {
|
||||
const line = state.doc.lineAt(pos);
|
||||
const r = foldable(state, line.from, line.to);
|
||||
if (r && r.from >= from && r.to <= to) out.push(r);
|
||||
@@ -268,9 +281,15 @@ function dispatchEffects(view: EditorView, effects: StateEffect<unknown>[]): boo
|
||||
export const collapseAll = (view: EditorView) => dispatchEffects(view, collapseAllEffects(view.state));
|
||||
export const expandAll = (view: EditorView) => dispatchEffects(view, expandAllEffects(view.state));
|
||||
export const collapseRecursively = (view: EditorView) =>
|
||||
dispatchEffects(view, view.state.selection.ranges.flatMap((r) => collapseRecursivelyEffects(view.state, r.head)));
|
||||
dispatchEffects(
|
||||
view,
|
||||
view.state.selection.ranges.flatMap((r) => collapseRecursivelyEffects(view.state, r.head)),
|
||||
);
|
||||
export const expandRecursively = (view: EditorView) =>
|
||||
dispatchEffects(view, view.state.selection.ranges.flatMap((r) => expandRecursivelyEffects(view.state, r.head)));
|
||||
dispatchEffects(
|
||||
view,
|
||||
view.state.selection.ranges.flatMap((r) => expandRecursivelyEffects(view.state, r.head)),
|
||||
);
|
||||
|
||||
function chevron(open: boolean): HTMLElement {
|
||||
const span = document.createElement("span");
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
import { HighlightStyle, type TagStyle } from "@codemirror/language";
|
||||
import { tags as t, type Tag } from "@lezer/highlight";
|
||||
|
||||
function token(tag: Tag | Tag[], name: string, defaults: { italic?: string; bold?: string; effect?: string } = {}): TagStyle {
|
||||
function token(
|
||||
tag: Tag | Tag[],
|
||||
name: string,
|
||||
defaults: { italic?: string; bold?: string; effect?: string } = {},
|
||||
): TagStyle {
|
||||
return {
|
||||
tag,
|
||||
color: `var(--syn-${name})`,
|
||||
@@ -21,7 +25,20 @@ export const openideaHighlightStyle = HighlightStyle.define([
|
||||
// Markdown tags whole links / quotes; listed first so marks, URL and title inside keep their own colours.
|
||||
token(t.link, "link", { effect: "underline" }),
|
||||
token(t.quote, "string"),
|
||||
token([t.keyword, t.controlKeyword, t.moduleKeyword, t.operatorKeyword, t.definitionKeyword, t.modifier, t.null, t.bool, t.unit], "keyword"),
|
||||
token(
|
||||
[
|
||||
t.keyword,
|
||||
t.controlKeyword,
|
||||
t.moduleKeyword,
|
||||
t.operatorKeyword,
|
||||
t.definitionKeyword,
|
||||
t.modifier,
|
||||
t.null,
|
||||
t.bool,
|
||||
t.unit,
|
||||
],
|
||||
"keyword",
|
||||
),
|
||||
token(t.self, "self"),
|
||||
token([t.string, t.special(t.string), t.character, t.attributeValue], "string"),
|
||||
token(t.docString, "docstring", { italic: "italic" }),
|
||||
@@ -31,7 +48,14 @@ export const openideaHighlightStyle = HighlightStyle.define([
|
||||
token([t.typeName, t.className, t.namespace, t.definition(t.typeName)], "type"),
|
||||
token([t.standard(t.typeName), t.standard(t.variableName), t.standard(t.function(t.variableName))], "builtin"),
|
||||
token([t.function(t.variableName), t.function(t.propertyName)], "function-call"),
|
||||
token([t.function(t.definition(t.variableName)), t.definition(t.function(t.variableName)), t.function(t.definition(t.propertyName))], "function"),
|
||||
token(
|
||||
[
|
||||
t.function(t.definition(t.variableName)),
|
||||
t.definition(t.function(t.variableName)),
|
||||
t.function(t.definition(t.propertyName)),
|
||||
],
|
||||
"function",
|
||||
),
|
||||
token([t.comment, t.lineComment, t.blockComment], "comment", { italic: "var(--syn-comment-style)" }),
|
||||
token(t.docComment, "doc-comment", { italic: "italic" }),
|
||||
token([t.meta, t.annotation, t.macroName], "decorator"),
|
||||
|
||||
@@ -13,7 +13,10 @@ function guideDeco(levels: number, step: number) {
|
||||
let d = cache.get(key);
|
||||
if (!d) {
|
||||
d = Decoration.line({
|
||||
attributes: { class: "cm-openidea-guides", style: `--openidea-guide-levels: ${levels}; --openidea-guide-step: ${step}` },
|
||||
attributes: {
|
||||
class: "cm-openidea-guides",
|
||||
style: `--openidea-guide-levels: ${levels}; --openidea-guide-step: ${step}`,
|
||||
},
|
||||
});
|
||||
cache.set(key, d);
|
||||
}
|
||||
|
||||
@@ -97,7 +97,11 @@ class OverviewLane {
|
||||
rows.set(key, { top: prev?.top ?? top, height: Math.max(height, prev?.height ?? 0), mark: m });
|
||||
}
|
||||
const caret = pos(view.lineBlockAt(view.state.selection.main.head).top);
|
||||
return { rows: [...rows.values()].sort((x, y) => (x.mark.priority ?? 0) - (y.mark.priority ?? 0)), caret, unit };
|
||||
return {
|
||||
rows: [...rows.values()].sort((x, y) => (x.mark.priority ?? 0) - (y.mark.priority ?? 0)),
|
||||
caret,
|
||||
unit,
|
||||
};
|
||||
},
|
||||
write: ({ rows, caret, unit }) => {
|
||||
const key =
|
||||
@@ -107,7 +111,10 @@ class OverviewLane {
|
||||
const frag = document.createDocumentFragment();
|
||||
for (const r of rows) {
|
||||
const el = document.createElement("div");
|
||||
el.className = r.mark.kind === "thin" ? "cm-openidea-overviewMark cm-openidea-overviewMark-thin" : "cm-openidea-overviewMark";
|
||||
el.className =
|
||||
r.mark.kind === "thin"
|
||||
? "cm-openidea-overviewMark cm-openidea-overviewMark-thin"
|
||||
: "cm-openidea-overviewMark";
|
||||
el.style.top = `${r.top}${unit}`;
|
||||
el.style.height = `${r.height}${unit}`;
|
||||
el.style.background = r.mark.color;
|
||||
|
||||
@@ -61,18 +61,23 @@ export function findLanguageDescription(uiMode: string | null, path: string): La
|
||||
const loose = LanguageDescription.matchLanguageName(languageData, uiMode, false);
|
||||
if (loose) return loose;
|
||||
}
|
||||
return uiMode === null && infos ? null : LanguageDescription.matchFilename(languageData, path.slice(path.lastIndexOf("/") + 1));
|
||||
return uiMode === null && infos
|
||||
? null
|
||||
: LanguageDescription.matchFilename(languageData, path.slice(path.lastIndexOf("/") + 1));
|
||||
}
|
||||
|
||||
/** Loads (once) the CodeMirror language for `desc`. */
|
||||
export function loadSupport(desc: LanguageDescription): Promise<LanguageSupport | null> {
|
||||
let p = supports.get(desc.name);
|
||||
if (!p) {
|
||||
p = desc.load().then((support) => patchSupport(desc, support)).catch((e) => {
|
||||
console.warn(`failed to load language ${desc.name}`, e);
|
||||
supports.delete(desc.name);
|
||||
return null;
|
||||
});
|
||||
p = desc
|
||||
.load()
|
||||
.then((support) => patchSupport(desc, support))
|
||||
.catch((e) => {
|
||||
console.warn(`failed to load language ${desc.name}`, e);
|
||||
supports.delete(desc.name);
|
||||
return null;
|
||||
});
|
||||
supports.set(desc.name, p);
|
||||
}
|
||||
return p;
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
/** Edit › Sort Lines / Reverse Lines: the selected lines, or the whole file without a selection. */
|
||||
import { EditorSelection, type ChangeSpec, type EditorState, type Transaction, type TransactionSpec } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
type ChangeSpec,
|
||||
type EditorState,
|
||||
type Transaction,
|
||||
type TransactionSpec,
|
||||
} from "@codemirror/state";
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: false, sensitivity: "variant" });
|
||||
|
||||
@@ -24,7 +30,11 @@ function blocks(state: EditorState): Array<{ from: number; to: number }> {
|
||||
return out;
|
||||
}
|
||||
|
||||
function rewrite(state: EditorState, transform: (lines: string[]) => string[], userEvent: string): TransactionSpec | null {
|
||||
function rewrite(
|
||||
state: EditorState,
|
||||
transform: (lines: string[]) => string[],
|
||||
userEvent: string,
|
||||
): TransactionSpec | null {
|
||||
const changes: ChangeSpec[] = [];
|
||||
for (const b of blocks(state)) {
|
||||
const text = state.sliceDoc(b.from, b.to);
|
||||
@@ -39,7 +49,10 @@ function rewrite(state: EditorState, transform: (lines: string[]) => string[], u
|
||||
return {
|
||||
changes: set,
|
||||
selection: hadSelection
|
||||
? EditorSelection.create(state.selection.ranges.map((r) => EditorSelection.range(set.mapPos(r.anchor, -1), set.mapPos(r.head, 1))), state.selection.mainIndex)
|
||||
? EditorSelection.create(
|
||||
state.selection.ranges.map((r) => EditorSelection.range(set.mapPos(r.anchor, -1), set.mapPos(r.head, 1))),
|
||||
state.selection.mainIndex,
|
||||
)
|
||||
: undefined,
|
||||
scrollIntoView: true,
|
||||
userEvent,
|
||||
|
||||
@@ -25,10 +25,18 @@ describe("editor settings behaviour", () => {
|
||||
expect(detectIndent("a\n\tb\n\t\tc\n")).toEqual({ insertSpaces: false });
|
||||
expect(detectIndent("plain\ntext\n")).toBeNull();
|
||||
const info = { id: "python", indent: { tabSize: 4, insertSpaces: true } } as Parameters<typeof effectiveIndent>[1];
|
||||
const settings = { codeStyle: { languages: { python: { useTab: true, tabSize: 8 } }, detectIndents: true, editorconfig: false } } as unknown as EditorSettings;
|
||||
const settings = {
|
||||
codeStyle: { languages: { python: { useTab: true, tabSize: 8 } }, detectIndents: true, editorconfig: false },
|
||||
} as unknown as EditorSettings;
|
||||
expect(effectiveIndent(settings, info)).toEqual({ tabSize: 8, insertSpaces: false });
|
||||
expect(effectiveIndent(settings, info, { indentSize: 2, indentStyle: "space" } as never)).toEqual({ tabSize: 8, insertSpaces: false });
|
||||
expect(effectiveIndent(settings, info, null, { insertSpaces: true, size: 2 })).toEqual({ tabSize: 2, insertSpaces: true });
|
||||
expect(effectiveIndent(settings, info, { indentSize: 2, indentStyle: "space" } as never)).toEqual({
|
||||
tabSize: 8,
|
||||
insertSpaces: false,
|
||||
});
|
||||
expect(effectiveIndent(settings, info, null, { insertSpaces: true, size: 2 })).toEqual({
|
||||
tabSize: 2,
|
||||
insertSpaces: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("removes trailing blank lines and strips all lines on request", () => {
|
||||
|
||||
@@ -3,7 +3,17 @@
|
||||
* Keys, Code Editing, Code Style). Everything here is rebuilt into the
|
||||
* `prefs` compartment when settings change.
|
||||
*/
|
||||
import { EditorSelection, EditorState, Prec, RangeSetBuilder, StateEffect, StateField, type Extension, type Transaction, type TransactionSpec } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
EditorState,
|
||||
Prec,
|
||||
RangeSetBuilder,
|
||||
StateEffect,
|
||||
StateField,
|
||||
type Extension,
|
||||
type Transaction,
|
||||
type TransactionSpec,
|
||||
} from "@codemirror/state";
|
||||
import {
|
||||
Decoration,
|
||||
EditorView,
|
||||
@@ -47,7 +57,13 @@ export function matchesFilePatterns(patterns: string, path: string): boolean {
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean)
|
||||
.some((p) => {
|
||||
const re = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
|
||||
const re = new RegExp(
|
||||
`^${p
|
||||
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
||||
.replace(/\*/g, ".*")
|
||||
.replace(/\?/g, ".")}$`,
|
||||
"i",
|
||||
);
|
||||
return re.test(name);
|
||||
});
|
||||
}
|
||||
@@ -80,7 +96,7 @@ const wrapIndent = ViewPlugin.fromClass(
|
||||
const b = new RangeSetBuilder<Decoration>();
|
||||
const tab = view.state.tabSize;
|
||||
for (const { from, to } of view.visibleRanges) {
|
||||
for (let pos = from; pos <= to; ) {
|
||||
for (let pos = from; pos <= to;) {
|
||||
const line = view.state.doc.lineAt(pos);
|
||||
let cols = 0;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
@@ -193,7 +209,13 @@ function leadingColumns(text: string, tabSize: number): number {
|
||||
}
|
||||
|
||||
/** Reformat on paste › Indent Block: re-indents a pasted block to the caret's indentation. */
|
||||
export function indentPastedText(text: string, targetCol: number, unit: string, tabSize: number, unitCols = tabSize): string {
|
||||
export function indentPastedText(
|
||||
text: string,
|
||||
targetCol: number,
|
||||
unit: string,
|
||||
tabSize: number,
|
||||
unitCols = tabSize,
|
||||
): string {
|
||||
const lines = text.split("\n");
|
||||
if (lines.length < 2) return text;
|
||||
const rest = lines.slice(1).filter((l) => l.trim());
|
||||
@@ -205,7 +227,8 @@ export function indentPastedText(text: string, targetCol: number, unit: string,
|
||||
// A block opener copied from mid-line ("if x:", "fn f() {") sat one level above its body.
|
||||
if (!firstIndented && base > 0 && /[:{([]\s*$/.test(lines[0]!)) base = Math.max(0, base - unitCols);
|
||||
const delta = targetCol - base;
|
||||
const pad = (n: number) => (unit === "\t" ? "\t".repeat(Math.floor(n / tabSize)) + " ".repeat(n % tabSize) : " ".repeat(n));
|
||||
const pad = (n: number) =>
|
||||
unit === "\t" ? "\t".repeat(Math.floor(n / tabSize)) + " ".repeat(n % tabSize) : " ".repeat(n);
|
||||
return lines
|
||||
.map((l, i) => {
|
||||
if (i === 0) return l.trimStart();
|
||||
@@ -394,7 +417,11 @@ const OPENERS: Record<string, true> = { "(": true, "[": true, "{": true, '"': tr
|
||||
/** Typing a bracket / quote over a selection replaces it instead of wrapping it. */
|
||||
const noSurround = EditorView.inputHandler.of((view, from, to, text) => {
|
||||
if (!OPENERS[text] || from === to || view.state.selection.ranges.length !== 1) return false;
|
||||
view.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + 1), userEvent: "input.type" });
|
||||
view.dispatch({
|
||||
changes: { from, to, insert: text },
|
||||
selection: EditorSelection.cursor(from + 1),
|
||||
userEvent: "input.type",
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -441,17 +468,27 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
if ((o.wrapOverride ?? softWrapActive(o.softWrap, prefs, o.path)) && g.softWrapIndent) out.push(wrapIndent);
|
||||
if (o.showWhitespace) {
|
||||
const a = prefs.appearance;
|
||||
out.push(whitespaceMarks({ leading: a.whitespaceLeading, inner: a.whitespaceInner, trailing: a.whitespaceTrailing }));
|
||||
out.push(
|
||||
whitespaceMarks({ leading: a.whitespaceLeading, inner: a.whitespaceInner, trailing: a.whitespaceTrailing }),
|
||||
);
|
||||
}
|
||||
if (prefs.appearance.hardWrapGuides && !o.distractionFree) out.push(marginGuides([o.hardWrapAt, ...prefs.codeStyle.visualGuides]));
|
||||
if (prefs.appearance.methodSeparators) out.push(EditorView.editorAttributes.of({ class: "cm-openidea-methodSeparators" }));
|
||||
const hidden = GUTTER_ICON_GROUPS.filter((grp) => !prefs.showGutterIcons || prefs.gutterIconsDisabled.includes(grp.id));
|
||||
if (hidden.length) out.push(EditorView.editorAttributes.of({ class: hidden.map((grp) => `cm-openidea-hideGutter-${grp.id}`).join(" ") }));
|
||||
if (prefs.appearance.hardWrapGuides && !o.distractionFree)
|
||||
out.push(marginGuides([o.hardWrapAt, ...prefs.codeStyle.visualGuides]));
|
||||
if (prefs.appearance.methodSeparators)
|
||||
out.push(EditorView.editorAttributes.of({ class: "cm-openidea-methodSeparators" }));
|
||||
const hidden = GUTTER_ICON_GROUPS.filter(
|
||||
(grp) => !prefs.showGutterIcons || prefs.gutterIconsDisabled.includes(grp.id),
|
||||
);
|
||||
if (hidden.length)
|
||||
out.push(
|
||||
EditorView.editorAttributes.of({ class: hidden.map((grp) => `cm-openidea-hideGutter-${grp.id}`).join(" ") }),
|
||||
);
|
||||
if (g.wheelZoom) out.push(wheelZoom);
|
||||
if (!g.dragAndDrop) out.push(noTextDrag);
|
||||
if (g.caretScroll === "center") out.push(centerCaret);
|
||||
if (g.richTextCopy) out.push(richCopy);
|
||||
if (!o.readOnly && (k.reformatOnPaste === "indentBlock" || k.reformatOnPaste === "indentEachLine")) out.push(pasteReindentFilter(k.reformatOnPaste));
|
||||
if (!o.readOnly && (k.reformatOnPaste === "indentBlock" || k.reformatOnPaste === "indentEachLine"))
|
||||
out.push(pasteReindentFilter(k.reformatOnPaste));
|
||||
|
||||
// Pairing: closeBrackets() reads the brackets list from language data; ours comes first.
|
||||
const brackets = [...(k.pairBrackets ? ["(", "[", "{"] : []), ...(k.pairQuotes ? ["'", '"'] : [])];
|
||||
@@ -469,7 +506,11 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
{ key: "Alt-Delete", run: deleteHumpForward },
|
||||
);
|
||||
// Delete to Word Start: the whitespace before the caret and the word before it.
|
||||
keys.push({ key: "Mod-Backspace", mac: "Alt-Backspace", run: k.camelHumps ? deleteHumpBackward : deleteWordBackward });
|
||||
keys.push({
|
||||
key: "Mod-Backspace",
|
||||
mac: "Alt-Backspace",
|
||||
run: k.camelHumps ? deleteHumpBackward : deleteWordBackward,
|
||||
});
|
||||
if (!k.smartHome)
|
||||
keys.push(
|
||||
{ key: "Home", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { selectableText } from "@/ui";
|
||||
import { previewExtensions } from "./preview";
|
||||
|
||||
describe("previewExtensions", () => {
|
||||
it("keeps the read-only preview selectable and focusable", async () => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "let a = 1;", extensions: await previewExtensions("/p/a.txt", undefined) }),
|
||||
});
|
||||
expect(view.state.readOnly).toBe(true);
|
||||
expect(view.contentDOM.getAttribute("contenteditable")).toBe("false");
|
||||
expect(view.contentDOM.getAttribute("tabindex")).toBe("0");
|
||||
expect(view.contentDOM.classList.contains(selectableText)).toBe(true);
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { openideaTheme } from "./theme";
|
||||
import { findLanguageDescription, loadSupport, loadedSupport, uiModeForPath } from "./languages";
|
||||
import { fontExtension } from "./setup";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { selectableText } from "@/ui";
|
||||
|
||||
export async function previewExtensions(path: string, settings: EditorSettings | undefined): Promise<Extension> {
|
||||
const open = editorsFor(path)[0]?.ctx;
|
||||
@@ -26,7 +27,8 @@ export async function previewExtensions(path: string, settings: EditorSettings |
|
||||
syntaxHighlighting(openideaHighlightStyle),
|
||||
EditorState.readOnly.of(true),
|
||||
EditorView.editable.of(false),
|
||||
EditorView.contentAttributes.of({ "aria-label": tx`Preview of ${path}` }),
|
||||
// Not editable, so selection and Copy need the text opted back in and a tab stop.
|
||||
EditorView.contentAttributes.of({ "aria-label": tx`Preview of ${path}`, class: selectableText, tabindex: "0" }),
|
||||
support ?? [],
|
||||
];
|
||||
}
|
||||
@@ -107,7 +107,8 @@ export function detectIndent(text: string): { insertSpaces: boolean; size?: numb
|
||||
if (n < 2 || (tabs === 0 && spaces === 0)) return null;
|
||||
if (tabs > spaces) return { insertSpaces: false };
|
||||
let best: number | undefined;
|
||||
for (const [d, c] of deltas) if (best === undefined || c > deltas.get(best)! || (c === deltas.get(best)! && d < best)) best = d;
|
||||
for (const [d, c] of deltas)
|
||||
if (best === undefined || c > deltas.get(best)! || (c === deltas.get(best)! && d < best)) best = d;
|
||||
return { insertSpaces: true, size: best };
|
||||
}
|
||||
|
||||
@@ -166,8 +167,16 @@ export function fontExtension(settings: EditorSettings | undefined): Extension {
|
||||
if ((family && family !== BUNDLED_MONO_FAMILY) || fallback) {
|
||||
vars.push(`--openidea-editor-font: ${monoFontFamily(family, fallback, "var(--font-mono)")}`);
|
||||
}
|
||||
if (settings?.fontSize) vars.push(`--openidea-editor-font-size: ${settings.fontSize}px`, `--openidea-editor-base-size: ${settings.fontSize}px`);
|
||||
if (settings?.lineHeight) vars.push(`--openidea-editor-line-height: ${settings.lineHeight}px`, `--openidea-editor-base-line: ${settings.lineHeight}px`);
|
||||
if (settings?.fontSize)
|
||||
vars.push(
|
||||
`--openidea-editor-font-size: ${settings.fontSize}px`,
|
||||
`--openidea-editor-base-size: ${settings.fontSize}px`,
|
||||
);
|
||||
if (settings?.lineHeight)
|
||||
vars.push(
|
||||
`--openidea-editor-line-height: ${settings.lineHeight}px`,
|
||||
`--openidea-editor-base-line: ${settings.lineHeight}px`,
|
||||
);
|
||||
const attrs: Record<string, string> = {};
|
||||
if (vars.length) attrs.style = vars.join("; ");
|
||||
if (prefs.ligatures) attrs.class = "cm-openidea-ligatures";
|
||||
@@ -179,12 +188,18 @@ export function readOnlyExtension(readOnly: boolean): Extension {
|
||||
}
|
||||
|
||||
/** Soft wraps per settings (file patterns), unless toggled for the file (`override`). */
|
||||
export function wrapExtension(settings: EditorSettings | undefined, path: string, override?: boolean | null): Extension {
|
||||
export function wrapExtension(
|
||||
settings: EditorSettings | undefined,
|
||||
path: string,
|
||||
override?: boolean | null,
|
||||
): Extension {
|
||||
return (override ?? softWrapActive(settings?.softWrap, prefsOf(settings), path)) ? EditorView.lineWrapping : [];
|
||||
}
|
||||
|
||||
export function stickyExtension(settings: EditorSettings | undefined): Extension {
|
||||
return settings?.stickyScroll === false || isDistractionFree() ? [] : [stickyScroll, stickyMaxLines.of(prefsOf(settings).codeEditing.stickyLinesMax)];
|
||||
return settings?.stickyScroll === false || isDistractionFree()
|
||||
? []
|
||||
: [stickyScroll, stickyMaxLines.of(prefsOf(settings).codeEditing.stickyLinesMax)];
|
||||
}
|
||||
|
||||
const matchingBracket = Decoration.mark({ class: "cm-matchingBracket" });
|
||||
@@ -219,10 +234,16 @@ export function lineNumbersExtension(settings: EditorSettings | undefined): Exte
|
||||
* Distraction Free Mode: no gutter, text column centred at the configured
|
||||
* width (see `cm-openidea-distractionFree` in theme.ts).
|
||||
*/
|
||||
export function distractionFreeExtension(settings: EditorSettings | undefined, active = isDistractionFree()): Extension {
|
||||
export function distractionFreeExtension(
|
||||
settings: EditorSettings | undefined,
|
||||
active = isDistractionFree(),
|
||||
): Extension {
|
||||
if (!active) return [];
|
||||
const columns = distractionFreeWidth(prefsOf(settings).appearance.distractionFreeWidth);
|
||||
return EditorView.editorAttributes.of({ class: "cm-openidea-distractionFree", style: `--openidea-df-columns: ${columns}` });
|
||||
return EditorView.editorAttributes.of({
|
||||
class: "cm-openidea-distractionFree",
|
||||
style: `--openidea-df-columns: ${columns}`,
|
||||
});
|
||||
}
|
||||
|
||||
export function foldingFor(settings: EditorSettings | undefined): Extension {
|
||||
@@ -310,7 +331,12 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
findExtension(),
|
||||
overviewLane,
|
||||
codeLensExtension,
|
||||
EditorView.contentAttributes.of({ spellcheck: "false", autocorrect: "off", autocapitalize: "off", "aria-label": tx`Editor for ${o.ctx.path}` }),
|
||||
EditorView.contentAttributes.of({
|
||||
spellcheck: "false",
|
||||
autocorrect: "off",
|
||||
autocapitalize: "off",
|
||||
"aria-label": tx`Editor for ${o.ctx.path}`,
|
||||
}),
|
||||
tabKeymap,
|
||||
keymap.of([...closeBracketsKeymap, ...editorBaseKeymap, indentWithTab]),
|
||||
compartments.language.of(o.language ?? []),
|
||||
@@ -320,7 +346,15 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
compartments.wrap.of(wrapExtension(o.settings, o.ctx.path, o.wrapOverride)),
|
||||
compartments.sticky.of(stickyExtension(o.settings)),
|
||||
compartments.heavy.of(heavyExtension(o.docLength, o.settings)),
|
||||
compartments.prefs.of(prefsFor({ settings: o.settings, path: o.ctx.path, info: o.info, readOnly: o.ctx.readOnly, wrapOverride: o.wrapOverride })),
|
||||
compartments.prefs.of(
|
||||
prefsFor({
|
||||
settings: o.settings,
|
||||
path: o.ctx.path,
|
||||
info: o.info,
|
||||
readOnly: o.ctx.readOnly,
|
||||
wrapOverride: o.wrapOverride,
|
||||
}),
|
||||
),
|
||||
compartments.contributions.of(contributionExtensions(o.ctx)),
|
||||
compartments.distractionFree.of(distractionFreeExtension(o.settings)),
|
||||
o.extra ?? [],
|
||||
|
||||
@@ -3,7 +3,14 @@ import { EditorSelection, EditorState, type Extension } from "@codemirror/state"
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { indentService, indentUnit } from "@codemirror/language";
|
||||
import { closeBrackets, insertBracket } from "@codemirror/autocomplete";
|
||||
import { autoIndentBackspace, insertTab, smartBackspace, smartBackspaceApplies, tabOutOfScope, tabOutScopes } from "./smartKeys";
|
||||
import {
|
||||
autoIndentBackspace,
|
||||
insertTab,
|
||||
smartBackspace,
|
||||
smartBackspaceApplies,
|
||||
tabOutOfScope,
|
||||
tabOutScopes,
|
||||
} from "./smartKeys";
|
||||
|
||||
/** One unit (2) deeper after a (non-blank) line ending in `{`, one less on a line starting with `}`. */
|
||||
const braces = indentService.of((cx, pos) => {
|
||||
@@ -35,7 +42,12 @@ function make(text: string, extensions: Extension = [], unit = " ") {
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: EditorSelection.create(ranges.length ? ranges : [EditorSelection.cursor(0)]),
|
||||
extensions: [EditorState.allowMultipleSelections.of(true), EditorState.tabSize.of(4), indentUnit.of(unit), extensions],
|
||||
extensions: [
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
EditorState.tabSize.of(4),
|
||||
indentUnit.of(unit),
|
||||
extensions,
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
@@ -47,7 +59,9 @@ function show(view: EditorView): string {
|
||||
const { doc, selection } = view.state;
|
||||
let out = doc.toString();
|
||||
for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
|
||||
out = r.empty ? out.slice(0, r.head) + "|" + out.slice(r.head) : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
|
||||
out = r.empty
|
||||
? out.slice(0, r.head) + "|" + out.slice(r.head)
|
||||
: out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
* IDEA-style Tab, smart Backspace and Tab out of auto-inserted brackets and
|
||||
* quotes.
|
||||
*/
|
||||
import { EditorSelection, StateEffect, countColumn, StateField, type EditorState, type Extension, type Transaction } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
StateEffect,
|
||||
countColumn,
|
||||
StateField,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
type Transaction,
|
||||
} from "@codemirror/state";
|
||||
import { EditorView, keymap, type Command } from "@codemirror/view";
|
||||
import { getIndentUnit, getIndentation, indentString, indentUnit, syntaxTree } from "@codemirror/language";
|
||||
import { indentMore } from "@codemirror/commands";
|
||||
@@ -45,7 +53,10 @@ export function smartBackspaceApplies(mode: string, language: string | undefined
|
||||
}
|
||||
|
||||
/** The change one Backspace makes at `pos` in "To proper indent position" mode, or null to delete normally. */
|
||||
export function autoIndentBackspace(state: EditorState, pos: number): { from: number; to: number; insert: string } | null {
|
||||
export function autoIndentBackspace(
|
||||
state: EditorState,
|
||||
pos: number,
|
||||
): { from: number; to: number; insert: string } | null {
|
||||
const doc = state.doc;
|
||||
const line = doc.lineAt(pos);
|
||||
if (/[^ \t]/.test(doc.sliceString(line.from, pos))) return null;
|
||||
@@ -128,7 +139,8 @@ function insertedPairs(tr: Transaction): Scope[] {
|
||||
export const tabOutOfScope: Command = (view) => {
|
||||
const { state } = view;
|
||||
const scopes = state.field(tabOutScopes, false);
|
||||
if (!scopes?.length || state.selection.ranges.some((r) => !r.empty || !scopes.some((s) => s.to === r.head))) return false;
|
||||
if (!scopes?.length || state.selection.ranges.some((r) => !r.empty || !scopes.some((s) => s.to === r.head)))
|
||||
return false;
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
state.selection.ranges.map((r) => EditorSelection.cursor(Math.min(r.head + 1, state.doc.length))),
|
||||
@@ -148,7 +160,11 @@ export const tabOut: Extension = tabOutScopes;
|
||||
/** `quote` at `pos` closes the string literal the caret is in (typed or not, the pair's end). */
|
||||
export function closesStringAt(state: EditorState, pos: number, quote: string): boolean {
|
||||
if (state.sliceDoc(pos, pos + 1) !== quote) return false;
|
||||
for (let n: ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]> | null = syntaxTree(state).resolveInner(pos, 1); n; n = n.parent) {
|
||||
for (
|
||||
let n: ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]> | null = syntaxTree(state).resolveInner(pos, 1);
|
||||
n;
|
||||
n = n.parent
|
||||
) {
|
||||
if (n.to > pos + 1) break;
|
||||
if (n.to === pos + 1 && n.from < pos && /String|Char|Template|Rune/.test(n.type.name)) return true;
|
||||
}
|
||||
|
||||
@@ -225,7 +225,9 @@ class StickyScroll {
|
||||
if (!row?.dataset.line) return;
|
||||
e.preventDefault();
|
||||
// The line number of a sticky line is not a link (IDEA).
|
||||
const inner = (e.target as HTMLElement).closest(".cm-openidea-stickyText")?.querySelector<HTMLElement>(".cm-openidea-stickyInner");
|
||||
const inner = (e.target as HTMLElement)
|
||||
.closest(".cm-openidea-stickyText")
|
||||
?.querySelector<HTMLElement>(".cm-openidea-stickyInner");
|
||||
if (!inner) return;
|
||||
const state = this.view.state;
|
||||
const line = state.doc.line(Math.min(Number(row.dataset.line), state.doc.lines));
|
||||
@@ -234,7 +236,10 @@ class StickyScroll {
|
||||
// The line takes the place of its sticky row, so the text stays under the pointer.
|
||||
this.view.dispatch({
|
||||
selection: EditorSelection.cursor(line.from + Math.min(offset, line.length)),
|
||||
effects: EditorView.scrollIntoView(line.from, { y: "start", yMargin: Math.max(0, rowIndex) * this.view.defaultLineHeight }),
|
||||
effects: EditorView.scrollIntoView(line.from, {
|
||||
y: "start",
|
||||
yMargin: Math.max(0, rowIndex) * this.view.defaultLineHeight,
|
||||
}),
|
||||
userEvent: "select.sticky",
|
||||
});
|
||||
this.view.focus();
|
||||
|
||||
@@ -15,12 +15,18 @@ function marks(state: EditorState) {
|
||||
|
||||
describe("syntaxHighlightField", () => {
|
||||
const create = () =>
|
||||
EditorState.create({ doc: "def hi, do: :ok", extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField] });
|
||||
EditorState.create({
|
||||
doc: "def hi, do: :ok",
|
||||
extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField],
|
||||
});
|
||||
|
||||
it("styles backend ranges with the active highlight style and maps them through edits", () => {
|
||||
let state = create();
|
||||
state = state.update({
|
||||
effects: setSyntaxHighlights.of({ kinds: ["keyword", "atom", "functionCall"], data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0] }),
|
||||
effects: setSyntaxHighlights.of({
|
||||
kinds: ["keyword", "atom", "functionCall"],
|
||||
data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0],
|
||||
}),
|
||||
}).state;
|
||||
const keyword = highlightingFor(state, [t.keyword]);
|
||||
const atom = highlightingFor(state, [t.atom]);
|
||||
|
||||
@@ -18,7 +18,8 @@ export const openideaTheme = EditorView.theme({
|
||||
"--editor-gutter-border": "var(--border-gutter, var(--border))",
|
||||
"--editor-caret-row": "var(--bg-current-line)",
|
||||
"--editor-selection": "var(--bg-editor-selection, color-mix(in srgb, var(--accent) 24%, transparent))",
|
||||
"--editor-selection-inactive": "var(--bg-editor-selection-inactive, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
"--editor-selection-inactive":
|
||||
"var(--bg-editor-selection-inactive, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
"--editor-indent-guide": "var(--border-indent-guide, var(--border))",
|
||||
"--editor-search": "var(--bg-search-match, color-mix(in srgb, var(--warning) 30%, transparent))",
|
||||
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
|
||||
@@ -52,18 +53,24 @@ export const openideaTheme = EditorView.theme({
|
||||
marginLeft: "0",
|
||||
background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 55%, transparent)",
|
||||
},
|
||||
"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": { fontVariantLigatures: "normal" },
|
||||
"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {
|
||||
fontVariantLigatures: "normal",
|
||||
},
|
||||
"&.cm-openidea-methodSeparators .cm-openidea-methodSeparator": {
|
||||
boxShadow: "inset 0 1px 0 var(--border-method-separator, var(--border))",
|
||||
},
|
||||
"&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks": { display: "none" },
|
||||
"&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks": {
|
||||
display: "none",
|
||||
},
|
||||
// Inheritance markers share one gutter: each group hides its own icons.
|
||||
"&.cm-openidea-hideGutter-inheritors :is(.cm-openidea-lineMarker-implemented, .cm-openidea-lineMarker-overridden), &.cm-openidea-hideGutter-supers :is(.cm-openidea-lineMarker-implementing, .cm-openidea-lineMarker-overriding)":
|
||||
{ display: "none" },
|
||||
// Distraction Free Mode: no gutter; the text column (n chars + line padding) is centred.
|
||||
"&.cm-openidea-distractionFree": { "--openidea-df-width": "calc(var(--openidea-df-columns, 80) * 1ch + 22px)" },
|
||||
"&.cm-openidea-distractionFree .cm-gutters": { display: "none" },
|
||||
"&.cm-openidea-distractionFree .cm-content": { marginInlineStart: "max(0px, calc((100% - var(--openidea-df-width)) / 2))" },
|
||||
"&.cm-openidea-distractionFree .cm-content": {
|
||||
marginInlineStart: "max(0px, calc((100% - var(--openidea-df-width)) / 2))",
|
||||
},
|
||||
"&.cm-openidea-distractionFree .cm-content.cm-lineWrapping": { maxWidth: "var(--openidea-df-width)" },
|
||||
".cm-fat-cursor": { background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 45%, transparent)" },
|
||||
".cm-selectionBackground": { background: "var(--editor-selection-inactive)" },
|
||||
@@ -71,7 +78,9 @@ export const openideaTheme = EditorView.theme({
|
||||
background: "var(--editor-selection)",
|
||||
},
|
||||
".cm-activeLine": { backgroundColor: "var(--editor-caret-row)" },
|
||||
".cm-selectionMatch": { backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))" },
|
||||
".cm-selectionMatch": {
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
|
||||
},
|
||||
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
|
||||
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
|
||||
backgroundColor: "var(--editor-brace)",
|
||||
@@ -214,7 +223,10 @@ export const openideaTheme = EditorView.theme({
|
||||
borderRadius: "var(--radius-popup)",
|
||||
boxShadow: "var(--shadow-popup)",
|
||||
},
|
||||
".cm-tooltip .cm-tooltip-arrow:before": { borderTopColor: "var(--border-popup)", borderBottomColor: "var(--border-popup)" },
|
||||
".cm-tooltip .cm-tooltip-arrow:before": {
|
||||
borderTopColor: "var(--border-popup)",
|
||||
borderBottomColor: "var(--border-popup)",
|
||||
},
|
||||
".cm-tooltip .cm-tooltip-arrow:after": { borderTopColor: "var(--bg-popup)", borderBottomColor: "var(--bg-popup)" },
|
||||
".cm-panels": { backgroundColor: "var(--bg-elev)", color: "var(--fg)" },
|
||||
".cm-panels.cm-panels-top": { borderBottom: "1px solid var(--border)" },
|
||||
|
||||
@@ -31,7 +31,11 @@ describe("unwrapOptions (Unwrap/Remove)", () => {
|
||||
|
||||
it("keeps the else branch the caret is in", () => {
|
||||
const src = "if (a) {\n x();\n} else {\n y();\n}";
|
||||
const chain = [node(src, "expression_statement", "y();"), node(src, "block", "{\n y();\n}", "alternative"), node(src, "if_statement", src)];
|
||||
const chain = [
|
||||
node(src, "expression_statement", "y();"),
|
||||
node(src, "block", "{\n y();\n}", "alternative"),
|
||||
node(src, "if_statement", src),
|
||||
];
|
||||
const [o] = unwrapOptions(Text.of(src.split("\n")), chain);
|
||||
expect(o!.label).toBe("Unwrap 'else'");
|
||||
expect(apply(src, o!)).toBe("y();");
|
||||
@@ -81,7 +85,11 @@ describe("unwrapOptions (Unwrap/Remove)", () => {
|
||||
expect(apply(src, opts[0]!)).toBe("if (a) {\n p();\n} else {\n q();\n}");
|
||||
expect(apply(src, opts[1]!)).toBe("if (b) {\n q();\n}");
|
||||
|
||||
const cond = [node(src, "identifier", "b"), node(src, "parenthesized_expression", "(b)", "condition"), node(src, "if_statement", inner, "alternative")];
|
||||
const cond = [
|
||||
node(src, "identifier", "b"),
|
||||
node(src, "parenthesized_expression", "(b)", "condition"),
|
||||
node(src, "if_statement", inner, "alternative"),
|
||||
];
|
||||
expect(unwrapOptions(Text.of(src.split("\n")), cond)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -60,11 +60,28 @@ const CLAUSES: Record<string, string> = {
|
||||
};
|
||||
|
||||
/** The child on the caret's path must be a body, not the condition / header. */
|
||||
const HEADER_FIELDS = new Set(["condition", "left", "right", "value", "pattern", "initializer", "update", "resources", "parameters", "type", "name"]);
|
||||
const HEADER_FIELDS = new Set([
|
||||
"condition",
|
||||
"left",
|
||||
"right",
|
||||
"value",
|
||||
"pattern",
|
||||
"initializer",
|
||||
"update",
|
||||
"resources",
|
||||
"parameters",
|
||||
"type",
|
||||
"name",
|
||||
]);
|
||||
|
||||
function isBody(n: ChainNode): boolean {
|
||||
if (n.field && HEADER_FIELDS.has(n.field)) return false;
|
||||
return /block|body|statement|compound|suite/.test(n.kind) || n.field === "consequence" || n.field === "alternative" || n.field === "body";
|
||||
return (
|
||||
/block|body|statement|compound|suite/.test(n.kind) ||
|
||||
n.field === "consequence" ||
|
||||
n.field === "alternative" ||
|
||||
n.field === "body"
|
||||
);
|
||||
}
|
||||
|
||||
const leading = (s: string) => /^[ \t]*/.exec(s)![0];
|
||||
@@ -80,7 +97,10 @@ function bodyLines(doc: Text, body: ChainNode, base: string): string[] {
|
||||
}
|
||||
const first = doc.lineAt(from);
|
||||
if (!doc.sliceString(first.from, from).trim()) from = first.from;
|
||||
const lines = doc.sliceString(from, to).split("\n").map((l) => l.trimEnd());
|
||||
const lines = doc
|
||||
.sliceString(from, to)
|
||||
.split("\n")
|
||||
.map((l) => l.trimEnd());
|
||||
while (lines.length && !lines[0]!.trim()) lines.shift();
|
||||
while (lines.length && !lines[lines.length - 1]!.trim()) lines.pop();
|
||||
const indents = lines.filter((l) => l.trim()).map((l) => leading(l).length);
|
||||
@@ -89,13 +109,17 @@ function bodyLines(doc: Text, body: ChainNode, base: string): string[] {
|
||||
}
|
||||
|
||||
function keyword(doc: Text, n: ChainNode): string {
|
||||
return /^[A-Za-z_]+/.exec(doc.sliceString(n.from, Math.min(n.to, n.from + 20)))?.[0] ?? n.kind.replace(/_(statement|expression|block)$/, "");
|
||||
return (
|
||||
/^[A-Za-z_]+/.exec(doc.sliceString(n.from, Math.min(n.to, n.from + 20)))?.[0] ??
|
||||
n.kind.replace(/_(statement|expression|block)$/, "")
|
||||
);
|
||||
}
|
||||
|
||||
function replacement(doc: Text, target: ChainNode, body: ChainNode): { from: number; to: number; insert: string } {
|
||||
const startLine = doc.lineAt(target.from);
|
||||
const endLine = doc.lineAt(target.to);
|
||||
const wholeLines = !doc.sliceString(startLine.from, target.from).trim() && !doc.sliceString(target.to, endLine.to).trim();
|
||||
const wholeLines =
|
||||
!doc.sliceString(startLine.from, target.from).trim() && !doc.sliceString(target.to, endLine.to).trim();
|
||||
if (wholeLines) {
|
||||
const lines = bodyLines(doc, body, leading(startLine.text));
|
||||
// An empty body removes the statement's lines altogether.
|
||||
@@ -134,7 +158,11 @@ export function unwrapOptions(doc: Text, chain: readonly ChainNode[]): UnwrapOpt
|
||||
const key = `${target.from}:${target.to}:${label}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({ label: tx`Unwrap '${label}'`, target: { from: target.from, to: target.to }, ...replacement(doc, target, child) });
|
||||
out.push({
|
||||
label: tx`Unwrap '${label}'`,
|
||||
target: { from: target.from, to: target.to },
|
||||
...replacement(doc, target, child),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -78,8 +78,19 @@ describe("EditorController", () => {
|
||||
});
|
||||
|
||||
it("builds IDEA's editor tab menu", async () => {
|
||||
useProject.setState({ project: { name: "p", root: "/p", isGit: true, settings: {} } as never, settings: {} as never });
|
||||
const ids = ["navigate.selectIn", "project.revealInFinder", "vcs.localHistory", "vcs.commit", "project.copyAbsolutePath", "project.rename", "file.settings"];
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
const ids = [
|
||||
"navigate.selectIn",
|
||||
"project.revealInFinder",
|
||||
"vcs.localHistory",
|
||||
"vcs.commit",
|
||||
"project.copyAbsolutePath",
|
||||
"project.rename",
|
||||
"file.settings",
|
||||
];
|
||||
const dispose = registerActions(ids.map((id) => ({ id, title: id, run: () => undefined })));
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "" }));
|
||||
ctrl.start();
|
||||
|
||||
@@ -335,7 +335,10 @@ export class EditorController implements SlotHost {
|
||||
files[path] = slot.viewState();
|
||||
}
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
storeSession(root, serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable));
|
||||
storeSession(
|
||||
root,
|
||||
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable),
|
||||
);
|
||||
}
|
||||
|
||||
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
|
||||
@@ -912,7 +915,11 @@ export class EditorController implements SlotHost {
|
||||
const encoding = await this.manager.backend.setEncoding(meta.doc, meta.encoding, true);
|
||||
model.setMeta({ encoding });
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: "Cannot reload from disk", body: e instanceof Error ? e.message : String(e) });
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot reload from disk",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1074,7 +1081,8 @@ export class EditorController implements SlotHost {
|
||||
closePath(path: string) {
|
||||
this.apply((s) => {
|
||||
const keys = new Set<string>();
|
||||
for (const pane of Object.values(s.panes)) for (const t of pane.tabs) if (t.input.path === path) keys.add(t.input.key);
|
||||
for (const pane of Object.values(s.panes))
|
||||
for (const t of pane.tabs) if (t.input.path === path) keys.add(t.input.key);
|
||||
let next = s;
|
||||
for (const key of keys) next = closeKey(next, key);
|
||||
return next;
|
||||
@@ -1085,6 +1093,20 @@ export class EditorController implements SlotHost {
|
||||
this.apply((s) => closeKey(s, key));
|
||||
}
|
||||
|
||||
activeInput(): EditorInput | null {
|
||||
return this.activeTabOf()?.input ?? null;
|
||||
}
|
||||
|
||||
onActiveInputChange(fn: (input: EditorInput | null) => void): () => void {
|
||||
let prev = this.activeInput()?.key;
|
||||
return useTabs.subscribe(() => {
|
||||
const input = this.activeInput();
|
||||
if (input?.key === prev) return;
|
||||
prev = input?.key;
|
||||
fn(input);
|
||||
});
|
||||
}
|
||||
|
||||
activePath(): string | null {
|
||||
return this.activeSlot?.model.path ?? this.activeTabOf()?.input.path ?? null;
|
||||
}
|
||||
@@ -1164,7 +1186,14 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "action", action: "project.copyAbsolutePath", arg: path, label: "Absolute Path" },
|
||||
{ kind: "action", action: "project.copyFileName", arg: path, label: "File Name" },
|
||||
...(inProject
|
||||
? ([{ kind: "action", action: "project.copyRelativePath", arg: path, label: "Path From Content Root" }] as MenuItem[])
|
||||
? ([
|
||||
{
|
||||
kind: "action",
|
||||
action: "project.copyRelativePath",
|
||||
arg: path,
|
||||
label: "Path From Content Root",
|
||||
},
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
],
|
||||
},
|
||||
|
||||
@@ -34,7 +34,12 @@ export function pasteFromHistory(view: EditorView) {
|
||||
id: `${i}`,
|
||||
label,
|
||||
detail,
|
||||
preview: text.split(/\r\n?|\n/).slice(1, 4).join(" ⏎ ").trim() || undefined,
|
||||
preview:
|
||||
text
|
||||
.split(/\r\n?|\n/)
|
||||
.slice(1, 4)
|
||||
.join(" ⏎ ")
|
||||
.trim() || undefined,
|
||||
run: () => {
|
||||
recordClipboard(text);
|
||||
void navigator.clipboard?.writeText(text).catch(() => {});
|
||||
|
||||
@@ -43,6 +43,8 @@ export function activate(): void | (() => void) {
|
||||
focus: () => ctrl.focus(),
|
||||
openPaths: () => ctrl.openPaths(),
|
||||
openTabs: () => ctrl.openTabs(),
|
||||
activeInput: () => ctrl.activeInput(),
|
||||
onActiveInputChange: (fn) => ctrl.onActiveInputChange(fn),
|
||||
closePath: (path) => ctrl.closePath(path),
|
||||
closeInput: (key) => ctrl.closeInput(key),
|
||||
reformat: async (path) => {
|
||||
|
||||
@@ -22,10 +22,8 @@ function setup(files: Record<string, string>, settings = {}) {
|
||||
_resetLanguages();
|
||||
const backend: MemoryBackend = createMemoryBackend(files);
|
||||
const scheduled: Array<() => void> = [];
|
||||
const manager = new DocumentManager(
|
||||
backend,
|
||||
{ settings: () => settings, notify: vi.fn() },
|
||||
(fn) => scheduled.push(fn),
|
||||
const manager = new DocumentManager(backend, { settings: () => settings, notify: vi.fn() }, (fn) =>
|
||||
scheduled.push(fn),
|
||||
);
|
||||
manager.start();
|
||||
const frame = async () => {
|
||||
@@ -108,7 +106,10 @@ describe("save cleanup", () => {
|
||||
it("keeps the caret line and untouched lines", () => {
|
||||
const state = EditorState.create({ doc: "a \nb \nc " });
|
||||
const m = new ModifiedRanges();
|
||||
m.ranges = [[0, 3], [8, 11]];
|
||||
m.ranges = [
|
||||
[0, 3],
|
||||
[8, 11],
|
||||
];
|
||||
const changes = saveCleanupChanges(state, m, { trim: true, finalNewline: true, protectLines: new Set([3]) });
|
||||
expect(changes).toEqual([
|
||||
{ from: 1, to: 3 },
|
||||
|
||||
@@ -7,7 +7,16 @@ import { EditorView } from "@codemirror/view";
|
||||
import type { LanguageDescription, LanguageSupport } from "@codemirror/language";
|
||||
import { create } from "zustand";
|
||||
import type { EditorConfigProps } from "@/bindings";
|
||||
import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings, SyntaxHighlights } from "@/platform/ipc";
|
||||
import type {
|
||||
DocId,
|
||||
DocumentInfo,
|
||||
EditorSettings,
|
||||
FileSettings,
|
||||
LineEnding,
|
||||
OutlineItem,
|
||||
Settings,
|
||||
SyntaxHighlights,
|
||||
} from "@/platform/ipc";
|
||||
import {
|
||||
_emitEditorEvent,
|
||||
_saveParticipants,
|
||||
@@ -20,7 +29,14 @@ import {
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import { findLanguageDescription, languageInfo, loadLanguageInfos, loadSupport, loadedSupport, commentTokens } from "../cm/languages";
|
||||
import {
|
||||
findLanguageDescription,
|
||||
languageInfo,
|
||||
loadLanguageInfos,
|
||||
loadSupport,
|
||||
loadedSupport,
|
||||
commentTokens,
|
||||
} from "../cm/languages";
|
||||
import { foldEffect } from "@codemirror/language";
|
||||
import { backendFolds, setBackendFolds } from "../cm/folding";
|
||||
import { setSyntaxHighlights } from "../cm/syntaxHighlight";
|
||||
@@ -137,7 +153,13 @@ export function methodLines(items: readonly OutlineItem[]): number[] {
|
||||
export function saveCleanupChanges(
|
||||
state: EditorState,
|
||||
modified: ModifiedRanges,
|
||||
opts: { trim: boolean; finalNewline: boolean; protectLines: Set<number>; allLines?: boolean; trailingBlankLines?: boolean },
|
||||
opts: {
|
||||
trim: boolean;
|
||||
finalNewline: boolean;
|
||||
protectLines: Set<number>;
|
||||
allLines?: boolean;
|
||||
trailingBlankLines?: boolean;
|
||||
},
|
||||
): Array<{ from: number; to: number; insert?: string }> {
|
||||
const changes: Array<{ from: number; to: number; insert?: string }> = [];
|
||||
const doc = state.doc;
|
||||
@@ -274,7 +296,8 @@ export class DocModel {
|
||||
|
||||
addSlot(slot: EditorSlot) {
|
||||
this.slots.add(slot);
|
||||
if (this.highlights?.counter === this.changeCounter) slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
|
||||
if (this.highlights?.counter === this.changeCounter)
|
||||
slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
|
||||
}
|
||||
|
||||
removeSlot(slot: EditorSlot) {
|
||||
@@ -320,7 +343,8 @@ export class DocModel {
|
||||
this.modified.map(cs);
|
||||
this.changeCounter++;
|
||||
const primary = this.primarySlot();
|
||||
for (const s of this.slots) s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(s === primary)]);
|
||||
for (const s of this.slots)
|
||||
s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(s === primary)]);
|
||||
// Without a tab, the first attached view keeps backend edits (Replace in Files…) undoable.
|
||||
let first = !primary;
|
||||
for (const a of this.attachments) {
|
||||
@@ -405,7 +429,13 @@ export class DocModel {
|
||||
compartments.heavy.reconfigure(heavyExtension(this.sync.localText.length, editor)),
|
||||
compartments.distractionFree.reconfigure(distractionFreeExtension(editor)),
|
||||
compartments.prefs.reconfigure(
|
||||
prefsFor({ settings: editor, path: this.path, info: this.info, readOnly: this.meta.readOnly, wrapOverride: this.softWrapOverride }),
|
||||
prefsFor({
|
||||
settings: editor,
|
||||
path: this.path,
|
||||
info: this.info,
|
||||
readOnly: this.meta.readOnly,
|
||||
wrapOverride: this.softWrapOverride,
|
||||
}),
|
||||
),
|
||||
];
|
||||
// LSP contributions read completion / hover timings when they are built.
|
||||
@@ -422,12 +452,25 @@ export class DocModel {
|
||||
setReadOnly(readOnly: boolean) {
|
||||
if (readOnly === this.meta.readOnly) return;
|
||||
const banner = this.meta.banner;
|
||||
this.setMeta({ readOnly, banner: readOnly ? (banner ?? (this.virtual ? null : "readOnly")) : banner === "readOnly" || banner === "library" ? null : banner });
|
||||
this.setMeta({
|
||||
readOnly,
|
||||
banner: readOnly
|
||||
? (banner ?? (this.virtual ? null : "readOnly"))
|
||||
: banner === "readOnly" || banner === "library"
|
||||
? null
|
||||
: banner,
|
||||
});
|
||||
for (const s of this.slots) {
|
||||
s.reconfigure([
|
||||
compartments.readOnly.reconfigure(readOnlyExtension(readOnly)),
|
||||
compartments.prefs.reconfigure(
|
||||
prefsFor({ settings: this.settings(), path: this.path, info: this.info, readOnly, wrapOverride: this.softWrapOverride }),
|
||||
prefsFor({
|
||||
settings: this.settings(),
|
||||
path: this.path,
|
||||
info: this.info,
|
||||
readOnly,
|
||||
wrapOverride: this.softWrapOverride,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
s.syncContributions(true);
|
||||
|
||||
@@ -18,7 +18,8 @@ export class EditHistory {
|
||||
|
||||
record(loc: Place) {
|
||||
const last = this.entries[this.entries.length - 1];
|
||||
if (last && last.path === loc.path && Math.abs(last.line - loc.line) <= MERGE_LINES) this.entries[this.entries.length - 1] = { ...loc };
|
||||
if (last && last.path === loc.path && Math.abs(last.line - loc.line) <= MERGE_LINES)
|
||||
this.entries[this.entries.length - 1] = { ...loc };
|
||||
else {
|
||||
this.entries = this.entries.filter((e) => e.path !== loc.path || Math.abs(e.line - loc.line) > MERGE_LINES);
|
||||
this.entries.push({ ...loc });
|
||||
|
||||
@@ -17,8 +17,8 @@ export const NAVIGATE_EVENT = "select.navigate";
|
||||
|
||||
/** Caret moves that count as navigation: mouse clicks, find, reveals, stripe / sticky-line clicks, navigate commands. */
|
||||
export function isNavigation(tr: Transaction): boolean {
|
||||
return ["select.pointer", "select.reveal", "select.search", "select.overview", "select.sticky", NAVIGATE_EVENT].some((e) =>
|
||||
tr.isUserEvent(e),
|
||||
return ["select.pointer", "select.reveal", "select.search", "select.overview", "select.sticky", NAVIGATE_EVENT].some(
|
||||
(e) => tr.isUserEvent(e),
|
||||
);
|
||||
}
|
||||
const MAX_ENTRIES = 100;
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { initialTabsState, moveTabToNewSplit, openTab, paneIds, splitAtEdge, splitPane, togglePin, type TabsState } from "./tabs";
|
||||
import {
|
||||
initialTabsState,
|
||||
moveTabToNewSplit,
|
||||
openTab,
|
||||
paneIds,
|
||||
splitAtEdge,
|
||||
splitPane,
|
||||
togglePin,
|
||||
type TabsState,
|
||||
} from "./tabs";
|
||||
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
|
||||
|
||||
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
|
||||
@@ -19,7 +28,10 @@ describe("editor session", () => {
|
||||
const first = s.activePane;
|
||||
s = splitPane(s, first, "column").state;
|
||||
s = open(s, "/p/d.ts");
|
||||
const session = serializeSession(s, { "/p/a.ts": { anchor: 3, head: 5, topLine: 10 }, "/p/zzz.ts": { anchor: 0, head: 0 } })!;
|
||||
const session = serializeSession(s, {
|
||||
"/p/a.ts": { anchor: 3, head: 5, topLine: 10 },
|
||||
"/p/zzz.ts": { anchor: 0, head: 0 },
|
||||
})!;
|
||||
expect(session.layout.kind).toBe("split");
|
||||
expect(session.activePane).toBe(1);
|
||||
expect(Object.keys(session.files)).toEqual(["/p/a.ts"]);
|
||||
@@ -50,7 +62,10 @@ describe("editor session", () => {
|
||||
expect(session.layout).toMatchObject({ kind: "pane", active: 1 });
|
||||
const r = restoreTabsState(parseSession(JSON.parse(JSON.stringify(session)))!, fileKey);
|
||||
const pane = r.panes[paneIds(r)[0]!]!;
|
||||
expect(pane.tabs.map((t) => t.input)).toEqual([file("/p/a.ts"), { kind: "agent-session", key: "agent:1", data: { task: "1" } }]);
|
||||
expect(pane.tabs.map((t) => t.input)).toEqual([
|
||||
file("/p/a.ts"),
|
||||
{ kind: "agent-session", key: "agent:1", data: { task: "1" } },
|
||||
]);
|
||||
expect(pane.active).toBe(pane.tabs[1]!.id);
|
||||
// Only restorable tabs: still a session. Junk inputs (file kind, no key) are dropped.
|
||||
const empty = initialTabsState();
|
||||
@@ -59,7 +74,11 @@ describe("editor session", () => {
|
||||
expect(serializeSession(only, {})).toBeNull();
|
||||
const junk = parseSession({
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ input: { kind: "file", key: "k" } }, { input: { kind: "x" } }, { input: { kind: "x", key: "y" } }], active: 0 },
|
||||
layout: {
|
||||
kind: "pane",
|
||||
tabs: [{ input: { kind: "file", key: "k" } }, { input: { kind: "x" } }, { input: { kind: "x", key: "y" } }],
|
||||
active: 0,
|
||||
},
|
||||
})!;
|
||||
expect(junk.layout).toEqual({ kind: "pane", tabs: [{ input: { kind: "x", key: "y" } }], active: 0 });
|
||||
});
|
||||
@@ -71,7 +90,11 @@ describe("editor session", () => {
|
||||
const ok = parseSession({
|
||||
version: 1,
|
||||
activePane: 7,
|
||||
layout: { kind: "split", dir: "row", children: [{ kind: "pane", tabs: [{ path: "/x" }], active: 9 }, { kind: "bogus" }] },
|
||||
layout: {
|
||||
kind: "split",
|
||||
dir: "row",
|
||||
children: [{ kind: "pane", tabs: [{ path: "/x" }], active: 9 }, { kind: "bogus" }],
|
||||
},
|
||||
files: { "/x": { anchor: 1, head: -1 } },
|
||||
})!;
|
||||
expect(ok.layout).toEqual({ kind: "pane", tabs: [{ path: "/x" }], active: 0 });
|
||||
@@ -109,7 +132,13 @@ describe("moveTabToNewSplit", () => {
|
||||
const split = splitPane(s, first, "row");
|
||||
s = open(split.state, "/b");
|
||||
const bTab = s.panes[split.paneId]!.tabs.find((t) => t.input.path === "/b")!;
|
||||
s = { ...s, panes: { ...s.panes, [split.paneId]: { ...s.panes[split.paneId]!, tabs: [bTab], active: bTab.id, mru: [bTab.id] } } };
|
||||
s = {
|
||||
...s,
|
||||
panes: {
|
||||
...s.panes,
|
||||
[split.paneId]: { ...s.panes[split.paneId]!, tabs: [bTab], active: bTab.id, mru: [bTab.id] },
|
||||
},
|
||||
};
|
||||
const r = moveTabToNewSplit(s, split.paneId, bTab.id, first, "bottom")!;
|
||||
expect(r.state.panes[split.paneId]).toBeUndefined();
|
||||
expect(r.state.layout).toMatchObject({ kind: "split", dir: "column" });
|
||||
|
||||
@@ -54,7 +54,10 @@ export function serializeSession(
|
||||
if (!pane) return null;
|
||||
const kept = pane.tabs.filter(saved);
|
||||
if (!kept.length) return null;
|
||||
const active = Math.max(0, kept.findIndex((t) => t.id === pane.active));
|
||||
const active = Math.max(
|
||||
0,
|
||||
kept.findIndex((t) => t.id === pane.active),
|
||||
);
|
||||
return {
|
||||
kind: "pane",
|
||||
tabs: kept.map((t) => ({
|
||||
@@ -131,10 +134,19 @@ export function parseSession(raw: unknown): EditorSession | null {
|
||||
for (const [path, v] of Object.entries(r.files)) {
|
||||
const f = v as Partial<FileViewState> | null;
|
||||
if (f && Number.isInteger(f.anchor) && Number.isInteger(f.head) && f.anchor! >= 0 && f.head! >= 0)
|
||||
files[slashPath(path)] = { anchor: f.anchor!, head: f.head!, ...(Number.isInteger(f.topLine) && f.topLine! >= 0 ? { topLine: f.topLine } : {}) };
|
||||
files[slashPath(path)] = {
|
||||
anchor: f.anchor!,
|
||||
head: f.head!,
|
||||
...(Number.isInteger(f.topLine) && f.topLine! >= 0 ? { topLine: f.topLine } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { version: 1, layout, activePane: typeof r.activePane === "number" ? Math.max(0, Math.floor(r.activePane)) : 0, files };
|
||||
return {
|
||||
version: 1,
|
||||
layout,
|
||||
activePane: typeof r.activePane === "number" ? Math.max(0, Math.floor(r.activePane)) : 0,
|
||||
files,
|
||||
};
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
@@ -167,7 +179,12 @@ export function restoreTabsState(session: EditorSession, fileKey: (path: string)
|
||||
tabs.sort((a, b) => Number(b.pinned) - Number(a.pinned));
|
||||
const activeTab = l.tabs[l.active];
|
||||
const active = (activeTab && byKey.get(tabKey(activeTab))) ?? tabs[0]!;
|
||||
panes[paneId] = { id: paneId, tabs, active: active.id, mru: [active.id, ...tabs.filter((t) => t !== active).map((t) => t.id)] };
|
||||
panes[paneId] = {
|
||||
id: paneId,
|
||||
tabs,
|
||||
active: active.id,
|
||||
mru: [active.id, ...tabs.filter((t) => t !== active).map((t) => t.id)],
|
||||
};
|
||||
order.push(paneId);
|
||||
return { kind: "pane", paneId };
|
||||
}
|
||||
|
||||
@@ -18,7 +18,14 @@ import {
|
||||
type TransactionSpec,
|
||||
} from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
|
||||
import { _addEditor, _removeEditor, documentSynced, isExternalChange, type EditorDocContext, type TextEditorHandle } from "@/editor/api";
|
||||
import {
|
||||
_addEditor,
|
||||
_removeEditor,
|
||||
documentSynced,
|
||||
isExternalChange,
|
||||
type EditorDocContext,
|
||||
type TextEditorHandle,
|
||||
} from "@/editor/api";
|
||||
import { showContextMenu } from "@/ui";
|
||||
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
@@ -186,7 +193,13 @@ export class EditorSlot {
|
||||
}
|
||||
if (tr.docChanged && !isExternalChange(tr)) {
|
||||
this.model.onLocal(tr.changes, this);
|
||||
if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move") || tr.isUserEvent("undo") || tr.isUserEvent("redo"))
|
||||
if (
|
||||
tr.isUserEvent("input") ||
|
||||
tr.isUserEvent("delete") ||
|
||||
tr.isUserEvent("move") ||
|
||||
tr.isUserEvent("undo") ||
|
||||
tr.isUserEvent("redo")
|
||||
)
|
||||
this.host.onUserEdit(this, tr);
|
||||
}
|
||||
if (tr.selection || tr.docChanged) selection = true;
|
||||
@@ -241,7 +254,9 @@ export class EditorSlot {
|
||||
}
|
||||
this.view.dispatch({
|
||||
selection: EditorSelection.single(anchor, head),
|
||||
effects: EditorView.scrollIntoView(EditorSelection.range(anchor, head), { y: r.center === false ? "nearest" : "center" }),
|
||||
effects: EditorView.scrollIntoView(EditorSelection.range(anchor, head), {
|
||||
y: r.center === false ? "nearest" : "center",
|
||||
}),
|
||||
userEvent: "select.reveal",
|
||||
});
|
||||
}
|
||||
@@ -256,9 +271,14 @@ export class EditorSlot {
|
||||
/** Restores a saved caret / scroll position (session restore). */
|
||||
restoreView(v: { anchor: number; head: number; topLine?: number }) {
|
||||
const doc = this.currentState().doc;
|
||||
const selection = EditorSelection.single(Math.min(Math.max(0, v.anchor), doc.length), Math.min(Math.max(0, v.head), doc.length));
|
||||
const selection = EditorSelection.single(
|
||||
Math.min(Math.max(0, v.anchor), doc.length),
|
||||
Math.min(Math.max(0, v.head), doc.length),
|
||||
);
|
||||
const scroll =
|
||||
v.topLine !== undefined ? EditorView.scrollIntoView(doc.line(Math.min(v.topLine + 1, doc.lines)).from, { y: "start" }) : null;
|
||||
v.topLine !== undefined
|
||||
? EditorView.scrollIntoView(doc.line(Math.min(v.topLine + 1, doc.lines)).from, { y: "start" })
|
||||
: null;
|
||||
if (this.view) {
|
||||
this.view.dispatch({ selection, effects: scroll ? [scroll] : [] });
|
||||
return;
|
||||
|
||||
@@ -55,7 +55,12 @@ const nextId = (p: string) => `${p}${++seq}`;
|
||||
|
||||
export function initialTabsState(): TabsState {
|
||||
const id = nextId("pane");
|
||||
return { layout: { kind: "pane", paneId: id }, panes: { [id]: { id, tabs: [], active: null, mru: [] } }, activePane: id, closed: [] };
|
||||
return {
|
||||
layout: { kind: "pane", paneId: id },
|
||||
panes: { [id]: { id, tabs: [], active: null, mru: [] } },
|
||||
activePane: id,
|
||||
closed: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function paneOf(s: TabsState, paneId: string): Pane {
|
||||
@@ -206,10 +211,17 @@ function removeTabs(s: TabsState, paneId: string, ids: Set<string>): TabsState {
|
||||
let active = pane.active;
|
||||
if (active && ids.has(active)) {
|
||||
const at = pane.tabs.findIndex((t) => t.id === active);
|
||||
const left = pane.tabs.slice(0, at).reverse().find((t) => !ids.has(t.id));
|
||||
const left = pane.tabs
|
||||
.slice(0, at)
|
||||
.reverse()
|
||||
.find((t) => !ids.has(t.id));
|
||||
const right = pane.tabs.slice(at + 1).find((t) => !ids.has(t.id));
|
||||
const pick =
|
||||
tabOptions.activateOnClose === "left" ? (left ?? right) : tabOptions.activateOnClose === "right" ? (right ?? left) : undefined;
|
||||
tabOptions.activateOnClose === "left"
|
||||
? (left ?? right)
|
||||
: tabOptions.activateOnClose === "right"
|
||||
? (right ?? left)
|
||||
: undefined;
|
||||
active = pick?.id ?? mru[0] ?? tabs[0]?.id ?? null;
|
||||
}
|
||||
pane = { ...pane, tabs, mru, active };
|
||||
@@ -241,14 +253,32 @@ export function closeToRight(s: TabsState, paneId: string, tabId: string): TabsS
|
||||
const pane = paneOf(s, paneId);
|
||||
const idx = pane.tabs.findIndex((t) => t.id === tabId);
|
||||
if (idx < 0) return s;
|
||||
return removeTabs(s, paneId, new Set(pane.tabs.slice(idx + 1).filter((t) => !t.pinned).map((t) => t.id)));
|
||||
return removeTabs(
|
||||
s,
|
||||
paneId,
|
||||
new Set(
|
||||
pane.tabs
|
||||
.slice(idx + 1)
|
||||
.filter((t) => !t.pinned)
|
||||
.map((t) => t.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function closeToLeft(s: TabsState, paneId: string, tabId: string): TabsState {
|
||||
const pane = paneOf(s, paneId);
|
||||
const idx = pane.tabs.findIndex((t) => t.id === tabId);
|
||||
if (idx < 0) return s;
|
||||
return removeTabs(s, paneId, new Set(pane.tabs.slice(0, idx).filter((t) => !t.pinned).map((t) => t.id)));
|
||||
return removeTabs(
|
||||
s,
|
||||
paneId,
|
||||
new Set(
|
||||
pane.tabs
|
||||
.slice(0, idx)
|
||||
.filter((t) => !t.pinned)
|
||||
.map((t) => t.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** IDEA "Close Unmodified Tabs": closes the unpinned tabs `modified` says no to. */
|
||||
@@ -283,7 +313,10 @@ export function reopenClosed(s: TabsState): { state: TabsState; tabId: string; p
|
||||
const entry = closed.pop()!;
|
||||
if (openNow.has(entry.input.key) && findTab(s, entry.input.key, entry.paneId)?.paneId === entry.paneId) continue;
|
||||
const paneId = s.panes[entry.paneId] ? entry.paneId : s.activePane;
|
||||
const { state, tabId } = openTab({ ...s, closed }, paneId, entry.input, { index: entry.index, pinned: entry.pinned });
|
||||
const { state, tabId } = openTab({ ...s, closed }, paneId, entry.input, {
|
||||
index: entry.index,
|
||||
pinned: entry.pinned,
|
||||
});
|
||||
return { state, tabId, paneId };
|
||||
}
|
||||
return null;
|
||||
@@ -325,7 +358,10 @@ export function sortTabs(s: TabsState, paneId: string, title: (t: Tab) => string
|
||||
const pane = paneOf(s, paneId);
|
||||
const byTitle = (a: Tab, b: Tab) =>
|
||||
title(a).localeCompare(title(b), undefined, { sensitivity: "base" }) || title(a).localeCompare(title(b));
|
||||
const tabs = [...pane.tabs.filter((t) => t.pinned).sort(byTitle), ...pane.tabs.filter((t) => !t.pinned).sort(byTitle)];
|
||||
const tabs = [
|
||||
...pane.tabs.filter((t) => t.pinned).sort(byTitle),
|
||||
...pane.tabs.filter((t) => !t.pinned).sort(byTitle),
|
||||
];
|
||||
return tabs.every((t, i) => t === pane.tabs[i]) ? s : withPane(s, { ...pane, tabs });
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,9 @@ export const documentBanner: EditorBannerContribution = {
|
||||
order: -10,
|
||||
useBanner: (path) => {
|
||||
const banner = useDocMeta((s) => s[path]?.banner ?? null);
|
||||
return banner ? { text: TEXT[banner], icon: banner === "readOnly" || banner === "library" ? "lock" : "info" } : null;
|
||||
return banner
|
||||
? { text: TEXT[banner], icon: banner === "readOnly" || banner === "library" ? "lock" : "info" }
|
||||
: null;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -81,7 +81,11 @@ export const EDITOR_TAB_MIME = "application/x-openidea-editor-tab";
|
||||
type DropZone = SplitEdge | "center";
|
||||
|
||||
/** Where a tab dropped at (x, y) over an editor goes: an edge (new split) or the pane itself. */
|
||||
export function dropZoneAt(x: number, y: number, rect: { left: number; top: number; width: number; height: number }): DropZone {
|
||||
export function dropZoneAt(
|
||||
x: number,
|
||||
y: number,
|
||||
rect: { left: number; top: number; width: number; height: number },
|
||||
): DropZone {
|
||||
const fx = (x - rect.left) / Math.max(1, rect.width);
|
||||
const fy = (y - rect.top) / Math.max(1, rect.height);
|
||||
const edges: Array<[SplitEdge, number]> = [
|
||||
@@ -108,7 +112,8 @@ function useTitleHints(): Map<string, string> {
|
||||
const paths = useTabs(
|
||||
useShallow((s) => {
|
||||
const out: string[] = [];
|
||||
for (const p of Object.values(s.panes)) for (const t of p.tabs) if (t.input.kind === "file" && t.input.path) out.push(t.input.path);
|
||||
for (const p of Object.values(s.panes))
|
||||
for (const t of p.tabs) if (t.input.kind === "file" && t.input.path) out.push(t.input.path);
|
||||
return out.sort();
|
||||
}),
|
||||
);
|
||||
@@ -133,7 +138,8 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const [dropZone, setDropZone] = useState<DropZone | null>(null);
|
||||
const tabPrefs = useEditorPrefs().tabs;
|
||||
const distractionFree = useDistractionFree((s) => s.active);
|
||||
const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } = tabPrefs;
|
||||
const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } =
|
||||
tabPrefs;
|
||||
|
||||
const items: TabItem[] = useMemo(() => {
|
||||
const names = tabs.map((t) => tabTitle(t.input, kinds));
|
||||
@@ -266,7 +272,9 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const at = { x: e.clientX, y: e.clientY };
|
||||
const path = tab.input.kind === "file" ? tab.input.path : undefined;
|
||||
if (!path) return showContextMenu(at, ctrl.tabMenu(paneId, tab));
|
||||
void prepareMenuGroups("editorTab", { paths: [path] }).then(() => showContextMenu(at, ctrl.tabMenu(paneId, tab)));
|
||||
void prepareMenuGroups("editorTab", { paths: [path] }).then(() =>
|
||||
showContextMenu(at, ctrl.tabMenu(paneId, tab)),
|
||||
);
|
||||
}}
|
||||
trailing={trailing}
|
||||
/>
|
||||
|
||||
@@ -361,7 +361,12 @@ export function ReadOnlyStatus() {
|
||||
if (!meta || isVirtualUri(meta.path) || meta.banner === "binary" || meta.banner === "tooLarge") return null;
|
||||
const label = meta.readOnly ? "Make file writable" : "Make file read-only";
|
||||
return (
|
||||
<BarButton tooltip={label} aria-label={label} aria-pressed={meta.readOnly} onClick={() => void executeAction("file.toggleReadOnly")}>
|
||||
<BarButton
|
||||
tooltip={label}
|
||||
aria-label={label}
|
||||
aria-pressed={meta.readOnly}
|
||||
onClick={() => void executeAction("file.toggleReadOnly")}
|
||||
>
|
||||
<span className={styles.lock}>
|
||||
<Icon name={meta.readOnly ? "lock" : "unlock"} size={14} />
|
||||
</span>
|
||||
|
||||
@@ -37,7 +37,5 @@ export function TextEditorHost({ tabId }: { tabId: string }) {
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div ref={ref} className={styles.host} data-editor-host="" aria-busy={!slot || undefined} />
|
||||
);
|
||||
return <div ref={ref} className={styles.host} data-editor-host="" aria-busy={!slot || undefined} />;
|
||||
}
|
||||
@@ -3,22 +3,50 @@ import type { FileEntry, OutlineItem } from "@/platform/ipc";
|
||||
import { dirChildren, navSegments, stepSegment, symbolChildren } from "./navBar";
|
||||
|
||||
const r = { start: { line: 0, col: 0 }, end: { line: 9, col: 0 } };
|
||||
const sym = (name: string, children: OutlineItem[] = []): OutlineItem => ({ name, kind: "class", detail: null, range: r, selection_range: r, children });
|
||||
const sym = (name: string, children: OutlineItem[] = []): OutlineItem => ({
|
||||
name,
|
||||
kind: "class",
|
||||
detail: null,
|
||||
range: r,
|
||||
selection_range: r,
|
||||
children,
|
||||
});
|
||||
|
||||
describe("navigation bar popup model", () => {
|
||||
it("lists project › dirs › file › symbols, skipping the class named like its file", () => {
|
||||
const segs = navSegments({ root: "/p", name: "proj" }, "/p/src/a/Foo.java", [sym("Foo"), sym("run")]);
|
||||
expect(segs.map((s) => `${s.kind}:${s.label}`)).toEqual(["dir:proj", "dir:src", "dir:a", "file:Foo.java", "symbol:run"]);
|
||||
expect(segs.map((s) => `${s.kind}:${s.label}`)).toEqual([
|
||||
"dir:proj",
|
||||
"dir:src",
|
||||
"dir:a",
|
||||
"file:Foo.java",
|
||||
"symbol:run",
|
||||
]);
|
||||
expect(segs[2]).toMatchObject({ path: "/p/src/a" });
|
||||
});
|
||||
|
||||
it("shows only the parent folder outside the project (scratches)", () => {
|
||||
expect(navSegments({ root: "/p", name: "proj" }, "/data/scratches/scratch.py", []).map((s) => s.label)).toEqual(["scratches", "scratch.py"]);
|
||||
expect(navSegments({ root: "/p", name: "proj" }, "/data/scratches/scratch.py", []).map((s) => s.label)).toEqual([
|
||||
"scratches",
|
||||
"scratch.py",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists folder children without IDE-hidden names, and symbol children", () => {
|
||||
const e = (name: string, kind: FileEntry["kind"]) => ({ name, path: `/p/${name}`, kind, size: 0, mtimeMs: 0, ignored: false, excluded: false, hidden: false }) as FileEntry;
|
||||
expect(dirChildren([e(".git", "dir"), e("src", "dir"), e("a.ts", "file")]).map((c) => `${c.kind}:${c.label}`)).toEqual(["dir:src", "file:a.ts"]);
|
||||
const e = (name: string, kind: FileEntry["kind"]) =>
|
||||
({
|
||||
name,
|
||||
path: `/p/${name}`,
|
||||
kind,
|
||||
size: 0,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
}) as FileEntry;
|
||||
expect(
|
||||
dirChildren([e(".git", "dir"), e("src", "dir"), e("a.ts", "file")]).map((c) => `${c.kind}:${c.label}`),
|
||||
).toEqual(["dir:src", "file:a.ts"]);
|
||||
expect(symbolChildren("/p/a.ts", [sym("A", [sym("b")])]).map((c) => c.label)).toEqual(["A"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ describe("status bar navigation bar popup", () => {
|
||||
const anchor = document.createElement("button");
|
||||
document.body.appendChild(anchor);
|
||||
const onClose = vi.fn();
|
||||
render(<NavChildrenPopup segment={{ kind: "file", path: "/p/a.ts", label: "a.ts" }} anchor={anchor} onClose={onClose} />);
|
||||
render(
|
||||
<NavChildrenPopup segment={{ kind: "file", path: "/p/a.ts", label: "a.ts" }} anchor={anchor} onClose={onClose} />,
|
||||
);
|
||||
await act(async () => {});
|
||||
const list = screen.getByRole("listbox", { name: "a.ts" });
|
||||
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["first", "second"]);
|
||||
|
||||
@@ -2,25 +2,24 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { VirtualDocument } from "@/platform/ipc";
|
||||
|
||||
const JDT = "jdt://contents/lib-1.0.jar/org.example/Lib.class?=demo/%5C/m2%5C/lib-1.0.jar%3Corg.example%28Lib.class";
|
||||
const TEXT = "// Source code is unavailable, and was generated by the Fernflower decompiler.\npackage org.example;\n\npublic class Lib {\n void run() {}\n}\n";
|
||||
const TEXT =
|
||||
"// Source code is unavailable, and was generated by the Fernflower decompiler.\npackage org.example;\n\npublic class Lib {\n void run() {}\n}\n";
|
||||
|
||||
vi.mock("@/platform/virtualDocs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/virtualDocs")>();
|
||||
return {
|
||||
...actual,
|
||||
virtualDocument: vi.fn(
|
||||
async (uri: string): Promise<VirtualDocument> => {
|
||||
if (uri !== JDT) throw new Error(`no contents for ${uri}`);
|
||||
return {
|
||||
uri,
|
||||
text: TEXT,
|
||||
languageId: "java",
|
||||
title: "Lib.class",
|
||||
description: "/m2/lib-1.0.jar",
|
||||
decompiled: true,
|
||||
};
|
||||
},
|
||||
),
|
||||
virtualDocument: vi.fn(async (uri: string): Promise<VirtualDocument> => {
|
||||
if (uri !== JDT) throw new Error(`no contents for ${uri}`);
|
||||
return {
|
||||
uri,
|
||||
text: TEXT,
|
||||
languageId: "java",
|
||||
title: "Lib.class",
|
||||
description: "/m2/lib-1.0.jar",
|
||||
decompiled: true,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -81,7 +80,11 @@ describe("virtual editor input", () => {
|
||||
|
||||
const session = serializeSession(useTabs.getState(), {});
|
||||
expect(JSON.stringify(session)).not.toContain("jdt:");
|
||||
expect(ctrl.tabMenu(useTabs.getState().activePane, activeTab()).some((i) => "label" in i && i.label === "Reveal in Project")).toBe(false);
|
||||
expect(
|
||||
ctrl
|
||||
.tabMenu(useTabs.getState().activePane, activeTab())
|
||||
.some((i) => "label" in i && i.label === "Reveal in Project"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not open a tab when the server has no contents", async () => {
|
||||
|
||||
@@ -117,7 +117,10 @@ describe("list popup", () => {
|
||||
it("shows the selected row's preview, fetched lazily", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const preview = vi.fn(async () => ({ kind: "diff" as const, lines: [{ kind: "added" as const, text: "let x = 1;" }] }));
|
||||
const preview = vi.fn(async () => ({
|
||||
kind: "diff" as const,
|
||||
lines: [{ kind: "added" as const, text: "let x = 1;" }],
|
||||
}));
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor: { x: 0, y: 0 },
|
||||
@@ -171,7 +174,9 @@ describe("documentation", () => {
|
||||
fireEvent.keyDown(frame(), { key: "ArrowRight" });
|
||||
expect(frame().textContent).toContain("second");
|
||||
fireEvent.keyDown(frame(), { key: "F4" });
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }));
|
||||
await vi.waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }),
|
||||
);
|
||||
expect(container).toBeTruthy();
|
||||
});
|
||||
|
||||
|
||||
@@ -101,10 +101,17 @@ async function cleanup(view: EditorView, o: CleanupOptions) {
|
||||
}
|
||||
|
||||
/** Code action titles of Implement Methods (⌃I) and Override Methods (⌃O). */
|
||||
export const IMPLEMENT_TITLE = /\bimplement\b|\b(add|generate) (missing|unimplemented|all missing)\b|missing (members|methods|trait items)/i;
|
||||
export const IMPLEMENT_TITLE =
|
||||
/\bimplement\b|\b(add|generate) (missing|unimplemented|all missing)\b|missing (members|methods|trait items)/i;
|
||||
export const OVERRIDE_TITLE = /\boverride\b/i;
|
||||
|
||||
function editorAction(id: string, title: string, category: string, run: (view: EditorView) => unknown, extra: Partial<Action> = {}): Action {
|
||||
function editorAction(
|
||||
id: string,
|
||||
title: string,
|
||||
category: string,
|
||||
run: (view: EditorView) => unknown,
|
||||
extra: Partial<Action> = {},
|
||||
): Action {
|
||||
return { id, title, category, when: EDITOR_WHEN, run: withEditor(run), ...extra };
|
||||
}
|
||||
|
||||
@@ -149,9 +156,15 @@ export function registerLspActions(): () => void {
|
||||
keywords: ["javadoc", "docs", "hover"],
|
||||
}),
|
||||
editorAction("code.quickDefinition", "Quick Definition", "Code", quickDefinition),
|
||||
editorAction("code.quickTypeDefinition", "Quick Type Definition", "View", (v) => quickDefinition(v, "typeDefinition"), {
|
||||
keywords: ["type declaration", "preview"],
|
||||
}),
|
||||
editorAction(
|
||||
"code.quickTypeDefinition",
|
||||
"Quick Type Definition",
|
||||
"View",
|
||||
(v) => quickDefinition(v, "typeDefinition"),
|
||||
{
|
||||
keywords: ["type declaration", "preview"],
|
||||
},
|
||||
),
|
||||
editorAction("code.showIntentions", "Show Context Actions", "Code", showIntentions, {
|
||||
keywords: ["intention", "quick fix", "lightbulb"],
|
||||
}),
|
||||
@@ -164,13 +177,23 @@ export function registerLspActions(): () => void {
|
||||
editorAction("code.reformatDialog", "Reformat File…", "Code", (v) =>
|
||||
reformatDialog(v, (view) => applyKindSilently(view, "source.organizeImports")),
|
||||
),
|
||||
editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, { keywords: ["organize imports"] }),
|
||||
editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, {
|
||||
keywords: ["organize imports"],
|
||||
}),
|
||||
// Project view / editor tab variants: `{ path }` of a file, opened first.
|
||||
{ id: "code.reformatFile", title: "Reformat File", category: "Code", hidden: true, when: "projectOpen", run: inFile(reformat) },
|
||||
{
|
||||
id: "code.reformatFile",
|
||||
title: "Reformat File",
|
||||
category: "Code",
|
||||
hidden: true,
|
||||
when: "projectOpen",
|
||||
run: inFile(reformat),
|
||||
},
|
||||
{
|
||||
id: "code.cleanupFile",
|
||||
title: "Code Cleanup in File",
|
||||
description: "Code Cleanup on `{ path, fixAll?, optimizeImports?, reformat? }` (all steps by default), opened first.",
|
||||
description:
|
||||
"Code Cleanup on `{ path, fixAll?, optimizeImports?, reformat? }` (all steps by default), opened first.",
|
||||
category: "Code",
|
||||
hidden: true,
|
||||
when: "projectOpen",
|
||||
@@ -187,11 +210,21 @@ export function registerLspActions(): () => void {
|
||||
when: "projectOpen",
|
||||
run: inFile(optimizeImports),
|
||||
},
|
||||
editorAction("navigate.declaration", "Go to Declaration or Usages", "Navigate", (v) => gotoTargets(v, "definition"), {
|
||||
keywords: ["definition"],
|
||||
}),
|
||||
editorAction("navigate.implementation", "Go to Implementation(s)", "Navigate", (v) => gotoTargets(v, "implementation")),
|
||||
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) => gotoTargets(v, "typeDefinition")),
|
||||
editorAction(
|
||||
"navigate.declaration",
|
||||
"Go to Declaration or Usages",
|
||||
"Navigate",
|
||||
(v) => gotoTargets(v, "definition"),
|
||||
{
|
||||
keywords: ["definition"],
|
||||
},
|
||||
),
|
||||
editorAction("navigate.implementation", "Go to Implementation(s)", "Navigate", (v) =>
|
||||
gotoTargets(v, "implementation"),
|
||||
),
|
||||
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
|
||||
gotoTargets(v, "typeDefinition"),
|
||||
),
|
||||
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
|
||||
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
|
||||
editorAction("find.highlightUsages", "Highlight Usages in File", "Find", highlightUsages),
|
||||
@@ -208,13 +241,21 @@ export function registerLspActions(): () => void {
|
||||
},
|
||||
},
|
||||
editorAction("refactor.rename", "Rename…", "Refactor", startRename),
|
||||
editorAction("refactor.extractVariable", "Introduce Variable…", "Refactor", (v) => runRefactoring(v, "extractVariable")),
|
||||
editorAction("refactor.extractVariable", "Introduce Variable…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractVariable"),
|
||||
),
|
||||
editorAction("refactor.extractMethod", "Extract Method…", "Refactor", (v) => runRefactoring(v, "extractMethod")),
|
||||
editorAction("refactor.extractConstant", "Introduce Constant…", "Refactor", (v) => runRefactoring(v, "extractConstant")),
|
||||
editorAction("refactor.extractConstant", "Introduce Constant…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractConstant"),
|
||||
),
|
||||
editorAction("refactor.extractField", "Introduce Field…", "Refactor", (v) => runRefactoring(v, "extractField")),
|
||||
editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) => runRefactoring(v, "extractParameter")),
|
||||
editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractParameter"),
|
||||
),
|
||||
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
|
||||
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) => runRefactoring(v, "changeSignature")),
|
||||
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
|
||||
runRefactoring(v, "changeSignature"),
|
||||
),
|
||||
editorAction("refactor.safeDelete", "Safe Delete…", "Refactor", safeDelete),
|
||||
editorAction(
|
||||
"code.generate",
|
||||
@@ -222,7 +263,8 @@ export function registerLspActions(): () => void {
|
||||
"Code",
|
||||
(v) =>
|
||||
runKindAction(v, "", {
|
||||
title: /^(generate|implement|override|add (missing|derive|impl|getter|setter|constructor)|create (constructor|getter|setter))/i,
|
||||
title:
|
||||
/^(generate|implement|override|add (missing|derive|impl|getter|setter|constructor)|create (constructor|getter|setter))/i,
|
||||
none: "Nothing to generate here",
|
||||
label: "Generate",
|
||||
}),
|
||||
|
||||
@@ -36,7 +36,9 @@ export function authorLabel(s: AuthorSummary): string {
|
||||
}
|
||||
|
||||
export function authorTooltip(s: AuthorSummary): string {
|
||||
return s.others ? `Last changed by ${s.author}; also ${s.authors.slice(1).join(", ")}` : `Last changed by ${s.author}`;
|
||||
return s.others
|
||||
? `Last changed by ${s.author}; also ${s.authors.slice(1).join(", ")}`
|
||||
: `Last changed by ${s.author}`;
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
|
||||
@@ -20,7 +20,9 @@ const IMPORT_TITLE = /\bimport\b/i;
|
||||
|
||||
/** The single import fix among `actions`, if exactly one exists. */
|
||||
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
|
||||
const imports = actions.filter((a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")));
|
||||
const imports = actions.filter(
|
||||
(a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")),
|
||||
);
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,8 @@ export function lensTargets(items: readonly OutlineItem[]): LensTarget[] {
|
||||
const out: LensTarget[] = [];
|
||||
const walk = (list: readonly OutlineItem[]) => {
|
||||
for (const it of list) {
|
||||
if (LENS_KINDS.has(it.kind) && !anonymous(it.name)) out.push({
|
||||
if (LENS_KINDS.has(it.kind) && !anonymous(it.name))
|
||||
out.push({
|
||||
name: it.name,
|
||||
line: it.selection_range.start.line,
|
||||
col: it.selection_range.start.col,
|
||||
@@ -159,7 +160,9 @@ class UsagesLensPlugin {
|
||||
const { from, to } = view.viewport;
|
||||
const firstLine = Math.max(0, text.lineAt(from).number - 1 - MARGIN_LINES);
|
||||
const lastLine = text.lineAt(to).number - 1 + MARGIN_LINES;
|
||||
const visible = this.outline.targets.filter((t) => t.line >= firstLine && t.line <= lastLine).slice(0, MAX_PER_PASS);
|
||||
const visible = this.outline.targets
|
||||
.filter((t) => t.line >= firstLine && t.line <= lastLine)
|
||||
.slice(0, MAX_PER_PASS);
|
||||
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
|
||||
const todo = usages ? visible.filter((t) => !this.cache.has(key(t))) : [];
|
||||
let unavailable = false;
|
||||
@@ -185,7 +188,8 @@ class UsagesLensPlugin {
|
||||
for (const t of visible) {
|
||||
const offset = posToOffset(text, { line: t.line, col: t.col });
|
||||
const who = lines && authorSummary(lines, t.startLine, t.endLine);
|
||||
if (who) lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
|
||||
if (who)
|
||||
lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
|
||||
const n = usages ? this.cache.get(key(t)) : undefined;
|
||||
if (n === undefined) continue;
|
||||
lenses.push({
|
||||
|
||||
@@ -330,9 +330,9 @@ describe("typeColumnText", () => {
|
||||
const edit = (new_text: string) => [{ range: { start: { line: 0, col: 0 }, end: { line: 0, col: 0 } }, new_text }];
|
||||
|
||||
it("names the module an auto-import comes from", () => {
|
||||
expect(typeColumnText({ detail: "Auto-import", additionalEdits: edit("\nfrom collections import OrderedDict") })).toBe(
|
||||
"collections",
|
||||
);
|
||||
expect(
|
||||
typeColumnText({ detail: "Auto-import", additionalEdits: edit("\nfrom collections import OrderedDict") }),
|
||||
).toBe("collections");
|
||||
expect(typeColumnText({ detail: "Map<K, V>", additionalEdits: edit("import java.util.HashMap;\n") })).toBe(
|
||||
"Map<K, V> (java.util)",
|
||||
);
|
||||
@@ -343,9 +343,9 @@ describe("typeColumnText", () => {
|
||||
});
|
||||
|
||||
it("keeps a detail that already says where", () => {
|
||||
expect(typeColumnText({ detail: "java.util.ArrayList", additionalEdits: edit("import java.util.ArrayList;\n") })).toBe(
|
||||
"java.util.ArrayList",
|
||||
);
|
||||
expect(
|
||||
typeColumnText({ detail: "java.util.ArrayList", additionalEdits: edit("import java.util.ArrayList;\n") }),
|
||||
).toBe("java.util.ArrayList");
|
||||
expect(typeColumnText({ detail: "fn() ", additionalEdits: [] })).toBe("fn() ");
|
||||
});
|
||||
});
|
||||
Loaded 100 of 476 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача