дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
20
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
345cc7ec81 | ||
|
|
a404804ee7 | ||
|
|
2d7726cf53 | ||
|
|
eb67595e72 | ||
|
|
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")?)
|
||||
});
|
||||
|
||||
@@ -8,6 +8,9 @@ pub async fn open(host: &Host, window: &str, path: PathBuf) -> IdeResult<Documen
|
||||
host.blocking(move || {
|
||||
let info = project.documents.open(&path)?;
|
||||
project.index.mark_recent(&path);
|
||||
if let Some(dir) = path.parent().filter(|_| project.light) {
|
||||
project.watch_light_dir(dir);
|
||||
}
|
||||
Ok(info)
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -38,7 +38,7 @@ pub async fn open(host: &Arc<Host>, window: &str, path: &Path) -> IdeResult<Arc<
|
||||
}
|
||||
|
||||
pub fn current(host: &Host, window: &str) -> Option<ProjectInfo> {
|
||||
host.project(window).ok().map(|p| info(&p))
|
||||
host.project(window).ok().filter(|p| !p.light).map(|p| info(&p))
|
||||
}
|
||||
|
||||
/// Effective settings for the window's project, or global settings without one.
|
||||
@@ -75,7 +75,8 @@ pub fn set_settings(
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(value).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
|
||||
let current = host.project(window).ok();
|
||||
let project_scope = matches!(scope, SettingsScope::Project) && current.is_some();
|
||||
// A LightEdit window has no project layer: its values are global.
|
||||
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
|
||||
let settings = match ¤t {
|
||||
Some(p) if project_scope => p.settings.set(scope, key, value)?,
|
||||
Some(p) => {
|
||||
@@ -90,7 +91,7 @@ pub fn set_settings(
|
||||
// A global value reaches every other open project too.
|
||||
if !project_scope {
|
||||
for project in host.projects() {
|
||||
if current.as_ref().is_some_and(|c| c.root == project.root) {
|
||||
if current.as_ref().is_some_and(|c| Arc::ptr_eq(c, &project)) {
|
||||
continue;
|
||||
}
|
||||
let effective = project.settings.reload();
|
||||
|
||||
@@ -50,6 +50,9 @@ pub struct Project {
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
pub(crate) _scratch_watcher: Option<Watcher>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
/// nothing indexed, no language servers, repositories or project services.
|
||||
pub light: bool,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
@@ -66,6 +69,7 @@ impl Host {
|
||||
// it, with its warm index, language servers and unsaved documents.
|
||||
if let Ok(current) = self.project(window)
|
||||
&& current.root == root
|
||||
&& !current.light
|
||||
{
|
||||
return Ok(current);
|
||||
}
|
||||
@@ -275,29 +279,7 @@ impl Host {
|
||||
mark("git");
|
||||
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
|
||||
|
||||
let db = Arc::new(ide_db::DbManager::new(
|
||||
root.clone(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
));
|
||||
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(&project_key)));
|
||||
let agents = Arc::new(ide_agent::AgentManager::new(
|
||||
ide_agent::AgentPaths {
|
||||
project_root: root.clone(),
|
||||
store_dir: self.data_dir.join("agents").join(&project_key),
|
||||
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
|
||||
worktrees_dir: dirs::home_dir()
|
||||
.unwrap_or_else(|| self.data_dir.clone())
|
||||
.join(".openidea")
|
||||
.join("worktrees")
|
||||
.join(&project_key),
|
||||
models_file: self.data_dir.join("agents").join("models.json"),
|
||||
custom_agents_dir: Some(self.config_dir.join("agents")),
|
||||
home_dir: dirs::home_dir(),
|
||||
},
|
||||
self.runtime.clone(),
|
||||
));
|
||||
let (db, http_history, agents) = self.project_services(&root, &project_key);
|
||||
let project = Arc::new(Project {
|
||||
root,
|
||||
sink,
|
||||
@@ -319,6 +301,7 @@ impl Host {
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
_scratch_watcher: scratch_watcher,
|
||||
light: false,
|
||||
});
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
@@ -329,6 +312,146 @@ impl Host {
|
||||
self.insert_project(window, project.clone());
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
/// Database connections, HTTP Client history and coding agents of the project at `root`.
|
||||
pub(crate) fn project_services(
|
||||
&self,
|
||||
root: &Path,
|
||||
project_key: &str,
|
||||
) -> (Arc<ide_db::DbManager>, Arc<ide_http::History>, Arc<ide_agent::AgentManager>) {
|
||||
let db = Arc::new(ide_db::DbManager::new(
|
||||
root.to_path_buf(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
));
|
||||
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
|
||||
let agents = Arc::new(ide_agent::AgentManager::new(
|
||||
ide_agent::AgentPaths {
|
||||
project_root: root.to_path_buf(),
|
||||
store_dir: self.data_dir.join("agents").join(project_key),
|
||||
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
|
||||
worktrees_dir: dirs::home_dir()
|
||||
.unwrap_or_else(|| self.data_dir.clone())
|
||||
.join(".openidea")
|
||||
.join("worktrees")
|
||||
.join(project_key),
|
||||
models_file: self.data_dir.join("agents").join("models.json"),
|
||||
custom_agents_dir: Some(self.config_dir.join("agents")),
|
||||
home_dir: dirs::home_dir(),
|
||||
},
|
||||
self.runtime.clone(),
|
||||
));
|
||||
(db, http_history, agents)
|
||||
}
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Opens `window` for editing loose files (LightEdit), `file` first: documents
|
||||
/// with syntax highlighting, saving and Local History over the global settings,
|
||||
/// without an index, language servers, repositories or project settings. A
|
||||
/// window already in LightEdit keeps its session; only its watchers grow.
|
||||
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
|
||||
let file = dunce::canonicalize(file)?;
|
||||
if file.is_dir() {
|
||||
return Err(IdeError::invalid(format!("{} is a folder", file.display())));
|
||||
}
|
||||
let dir = file.parent().map(Path::to_path_buf).ok_or_else(|| IdeError::invalid("no parent folder"))?;
|
||||
if let Ok(current) = self.project(window)
|
||||
&& current.light
|
||||
{
|
||||
current.watch_light_dir(&dir);
|
||||
return Ok(current);
|
||||
}
|
||||
self.close_project(window);
|
||||
let sink: SharedSink = (self.sink_for)(window);
|
||||
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
|
||||
let effective = settings.effective();
|
||||
let languages = Arc::new(self.languages.fork());
|
||||
languages.set_file_types(FileTypes::from_settings(&effective.files, None));
|
||||
let documents = {
|
||||
let languages = languages.clone();
|
||||
Arc::new(Documents::new(
|
||||
sink.clone(),
|
||||
Box::new(move |p: &Path, first: Option<&str>| languages.detect(p, first)),
|
||||
))
|
||||
};
|
||||
documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, None));
|
||||
let history = Arc::new(LocalHistory::open(&self.data_dir.join("history"), &dir)?);
|
||||
let index = ProjectIndex::unindexed(&dir, languages.clone(), self.syntax(), sink.clone())?;
|
||||
let lsp = LspManager::new(dir.clone(), languages.clone(), sink.clone());
|
||||
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
let watcher = light_watcher(&dir, &sink, &documents, &history)?;
|
||||
let project_key = project_key(&dir);
|
||||
let (db, http_history, agents) = self.project_services(&dir, &project_key);
|
||||
let project = Arc::new(Project {
|
||||
sink,
|
||||
languages,
|
||||
settings,
|
||||
documents,
|
||||
history,
|
||||
moves: FileMoves::new(),
|
||||
index,
|
||||
lsp,
|
||||
repos: Arc::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
detected_roots: Arc::default(),
|
||||
cache_dir: self.data_dir.join("cache").join(&project_key),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
watcher,
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
light: true,
|
||||
root: dir,
|
||||
});
|
||||
tracing::info!("window {window} edits {} without a project", file.display());
|
||||
self.insert_project(window, project.clone());
|
||||
Ok(project)
|
||||
}
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
pub fn watch_light_dir(&self, dir: &Path) {
|
||||
if !self.light {
|
||||
return;
|
||||
}
|
||||
let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
let mut watchers = self.content_watchers.lock();
|
||||
if dir == self.root || watchers.iter().any(|(p, _)| *p == dir) {
|
||||
return;
|
||||
}
|
||||
match light_watcher(&dir, &self.sink, &self.documents, &self.history) {
|
||||
Ok(w) => watchers.push((dir, w)),
|
||||
Err(e) => tracing::warn!("watching {}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn light_watcher(
|
||||
dir: &Path,
|
||||
sink: &SharedSink,
|
||||
documents: &Arc<Documents>,
|
||||
history: &Arc<LocalHistory>,
|
||||
) -> IdeResult<Watcher> {
|
||||
let (documents, history) = (documents.clone(), history.clone());
|
||||
Watcher::start_with(
|
||||
dir,
|
||||
Vec::new(),
|
||||
sink.clone(),
|
||||
Box::new(move |batch| {
|
||||
let changed: Vec<PathBuf> = batch.created.iter().chain(&batch.modified).cloned().collect();
|
||||
documents.on_disk_changed(&changed);
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
}),
|
||||
ide_vfs::WatchMode::Flat,
|
||||
)
|
||||
}
|
||||
|
||||
/// Looks for repositories nested below the project (and the one containing it);
|
||||
@@ -516,6 +639,9 @@ impl Project {
|
||||
/// Applies changed content roots and exclude settings to the index (which
|
||||
/// rescans in the background) and the file watchers, without reopening the project.
|
||||
pub fn refresh_index_scope(&self) {
|
||||
if self.light {
|
||||
return;
|
||||
}
|
||||
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
|
||||
self.index.set_scope(roots.clone(), excludes.clone());
|
||||
self.watcher.set_excludes(&excludes);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! LightEdit: a window editing loose files without a project.
|
||||
|
||||
use ide_core::{ChangeSet, NullSink, TextChange};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn host(base: &std::path::Path) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn edits_loose_files_without_project_services() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp_root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (a_dir, b_dir) = (tmp_root.join("a"), tmp_root.join("b"));
|
||||
std::fs::create_dir_all(a_dir.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(&b_dir).unwrap();
|
||||
std::fs::write(a_dir.join("one.py"), "print(1)\n").unwrap();
|
||||
std::fs::write(b_dir.join("two.rs"), "fn main() {}\n").unwrap();
|
||||
let host = host(&tmp_root.join("app"));
|
||||
|
||||
let light = host.open_light("main", &a_dir.join("one.py")).unwrap();
|
||||
assert!(light.light);
|
||||
assert_eq!(light.root, a_dir);
|
||||
assert!(host.open_light("main", &b_dir).is_err(), "a folder is not opened for LightEdit");
|
||||
|
||||
let doc = ops::doc::open(&host, "main", a_dir.join("one.py")).await.unwrap();
|
||||
assert!(doc.text.starts_with("print"));
|
||||
let changes = ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "#\n".into() }] };
|
||||
let version = ops::doc::edit(&host, "main", doc.id, doc.version, changes).unwrap();
|
||||
assert!(version > doc.version);
|
||||
ops::doc::save(&host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(a_dir.join("one.py")).unwrap(), "#\nprint(1)\n");
|
||||
|
||||
// More files join the same session, wherever they are.
|
||||
let again = host.open_light("main", &b_dir.join("two.rs")).unwrap();
|
||||
assert!(Arc::ptr_eq(&light, &again));
|
||||
ops::doc::open(&host, "main", b_dir.join("two.rs")).await.unwrap();
|
||||
|
||||
assert!(light.index.wait_idle(Duration::from_secs(10)));
|
||||
assert_eq!(light.index.status().files, 0, "nothing is indexed");
|
||||
assert!(light.lsp.servers().is_empty(), "no language servers");
|
||||
assert!(light.repos().is_empty(), "no repositories");
|
||||
|
||||
// Opening the folder as a project replaces the LightEdit session.
|
||||
let project = host.open_project("main", &a_dir).unwrap();
|
||||
assert!(!project.light);
|
||||
assert!(!Arc::ptr_eq(&project, &light));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn light_windows_ignore_project_scoped_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = dunce::canonicalize(tmp.path()).unwrap().join("loose");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("notes.txt"), "x\n").unwrap();
|
||||
let host = host(&tmp.path().join("app"));
|
||||
host.open_light("main", &dir.join("notes.txt")).unwrap();
|
||||
let applied = ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"general.projectName",
|
||||
"\"loose\"",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!applied.project_scope);
|
||||
assert!(!dir.join(".openidea").exists(), "no project settings next to the file");
|
||||
}
|
||||
@@ -90,11 +90,29 @@ impl ProjectIndex {
|
||||
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
|
||||
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
|
||||
Self::start(shared, root, true)
|
||||
}
|
||||
|
||||
/// An index that never scans or persists anything (a window editing loose
|
||||
/// files): queries answer empty, recent files are kept in memory only.
|
||||
pub fn unindexed(
|
||||
root: &Path,
|
||||
languages: Arc<LanguageRegistry>,
|
||||
syntax: Arc<Syntax>,
|
||||
sink: SharedSink,
|
||||
) -> IdeResult<Arc<Self>> {
|
||||
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_owned());
|
||||
let filter = filter::PathFilter::new(&root, &[], &[]);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, None));
|
||||
Self::start(shared, root, false)
|
||||
}
|
||||
|
||||
fn start(shared: Arc<Shared>, root: PathBuf, scan: bool) -> IdeResult<Arc<Self>> {
|
||||
let worker = {
|
||||
let shared = shared.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-index".into())
|
||||
.spawn(move || shared.run())
|
||||
.spawn(move || shared.run(scan))
|
||||
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
|
||||
};
|
||||
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)), root }))
|
||||
|
||||
@@ -473,3 +473,25 @@ fn file_type_changes_reparse_affected_files() {
|
||||
assert_eq!(symbols(&idx, "beta", SymbolFilter::All), ["beta"]);
|
||||
assert_eq!(idx.shared.parsed.load(Ordering::SeqCst), parsed + 1, "only the affected file is re-parsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unindexed_index_never_scans_or_persists() {
|
||||
let fx = Fixture::new(&[("a.rs", "fn alpha() {}\n")]);
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().push(e))
|
||||
};
|
||||
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
|
||||
let idx = ProjectIndex::unindexed(&fx.root, languages, Arc::new(Syntax::new()), sink).unwrap();
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
let st = idx.status();
|
||||
assert!(!st.indexing);
|
||||
assert_eq!(st.files, 0);
|
||||
assert!(files(&idx, "a").is_empty());
|
||||
idx.mark_recent(&fx.root.join("a.rs"));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(idx.recent_files(), vec![fx.root.join("a.rs")]);
|
||||
assert!(!fx.cache.exists());
|
||||
assert!(!events.lock().iter().any(|e| matches!(e, IdeEvent::Task { .. })), "no indexing task");
|
||||
}
|
||||
@@ -127,13 +127,18 @@ impl Shared {
|
||||
|
||||
// ---------------------------------------------------------------- thread
|
||||
|
||||
pub(crate) fn run(&self) {
|
||||
/// `scan`: load the persisted index and scan the roots before serving updates.
|
||||
pub(crate) fn run(&self, scan: bool) {
|
||||
{
|
||||
let mut q = self.queue.lock();
|
||||
q.busy = true;
|
||||
}
|
||||
self.load_persisted();
|
||||
self.full_scan();
|
||||
if scan {
|
||||
self.load_persisted();
|
||||
self.full_scan();
|
||||
} else {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
}
|
||||
{
|
||||
let mut q = self.queue.lock();
|
||||
q.busy = false;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -32,6 +32,8 @@ pub enum WatchMode {
|
||||
/// One non-recursive watch per directory, skipping excluded and ignored
|
||||
/// directories; new directories are picked up as they appear.
|
||||
PerDirectory,
|
||||
/// The root's own entries only (loose files edited outside a project).
|
||||
Flat,
|
||||
}
|
||||
|
||||
impl Default for WatchMode {
|
||||
@@ -81,7 +83,8 @@ impl Watcher {
|
||||
on_change(batch);
|
||||
};
|
||||
let inner = match mode {
|
||||
WatchMode::Recursive => Self::start_recursive(root, filter, emit),
|
||||
WatchMode::Recursive => Self::start_recursive(root, filter, emit, RecursiveMode::Recursive),
|
||||
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
|
||||
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
|
||||
}?;
|
||||
Ok(Self { inner, excludes: shared })
|
||||
@@ -94,7 +97,7 @@ impl Watcher {
|
||||
*self.excludes.write() = ExcludeMatcher::new(excludes);
|
||||
}
|
||||
|
||||
/// Number of OS-level watches (1 in recursive mode).
|
||||
/// Number of OS-level watches (1 in recursive and flat mode).
|
||||
pub fn watch_count(&self) -> usize {
|
||||
match &self.inner {
|
||||
Inner::Recursive(_) => 1,
|
||||
@@ -106,6 +109,7 @@ impl Watcher {
|
||||
root: PathBuf,
|
||||
filter: EventFilter,
|
||||
emit: impl Fn(&FsBatch) + Send + 'static,
|
||||
recursive: RecursiveMode,
|
||||
) -> IdeResult<Inner> {
|
||||
// No file-id cache: building it walks and stats the whole tree before `watch` returns,
|
||||
// which made opening large projects block for seconds. Renames arrive as remove + create.
|
||||
@@ -125,9 +129,7 @@ impl Watcher {
|
||||
let mut debouncer =
|
||||
new_debouncer_opt::<_, RecommendedWatcher, _>(DEBOUNCE, None, handler, NoCache, notify::Config::default())
|
||||
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
|
||||
debouncer
|
||||
.watch(&root, RecursiveMode::Recursive)
|
||||
.map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
|
||||
debouncer.watch(&root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
|
||||
Ok(Inner::Recursive(debouncer))
|
||||
}
|
||||
|
||||
@@ -787,4 +789,30 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(batches.lock().len(), n, "no events after drop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_mode_reports_the_roots_own_entries_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("sub")).unwrap();
|
||||
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
|
||||
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
|
||||
let watcher = {
|
||||
let batches = batches.clone();
|
||||
Watcher::start_with(
|
||||
&root,
|
||||
Vec::new(),
|
||||
sink,
|
||||
Box::new(move |b| batches.lock().push(b.clone())),
|
||||
WatchMode::Flat,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(watcher.watch_count(), 1);
|
||||
std::fs::write(root.join("sub/deep.txt"), "x").unwrap();
|
||||
std::fs::write(root.join("a.txt"), "x").unwrap();
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("a.txt"))), "{:?}", batches.lock());
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(!all_paths(&batches.lock()).contains(&root.join("sub/deep.txt")));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -61,6 +61,22 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Edits the loose file `path` in this window without a project (LightEdit);
|
||||
/// a window already in LightEdit keeps its files. Returns the effective (global) settings.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn light_edit_open(window: Window, path: PathBuf) -> IdeResult<Settings> {
|
||||
let app = window.app_handle().clone();
|
||||
let label = window.label().to_owned();
|
||||
if app.state::<AppState>().project(&label).is_ok_and(|p| !p.light) {
|
||||
crate::windows::close_settings_window(&app, &label);
|
||||
}
|
||||
let project = tauri::async_runtime::spawn_blocking(move || app.state::<AppState>().open_light(&label, &path))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
Ok(project.settings.effective())
|
||||
}
|
||||
|
||||
fn project_info(project: &crate::state::Project) -> ProjectInfo {
|
||||
ide_host::ops::project::info(project)
|
||||
}
|
||||
@@ -200,7 +216,7 @@ pub fn project_roots(window: Window, state: State<'_, AppState>) -> IdeResult<id
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn project_current(window: Window, state: State<'_, AppState>) -> Option<ProjectInfo> {
|
||||
state.project(window.label()).ok().map(|p| project_info(&p))
|
||||
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -59,6 +59,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
app::recent_projects,
|
||||
app::remove_recent_project,
|
||||
app::open_project,
|
||||
app::light_edit_open,
|
||||
app::project_current,
|
||||
app::close_project,
|
||||
app::languages,
|
||||
@@ -296,6 +297,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
sdk::sdk_python_packages,
|
||||
sdk::sdk_python_pip,
|
||||
window::window_open_project,
|
||||
window::window_open_files,
|
||||
window::window_open_remote,
|
||||
window::window_new,
|
||||
window::window_open_settings,
|
||||
|
||||
@@ -11,10 +11,25 @@ use tauri::{AppHandle, Manager, State, WebviewWindow};
|
||||
|
||||
/// Opens `path` in a new window (`new_window`) or tells the caller to open it
|
||||
/// itself (`current`). A project already open in some window is focused instead.
|
||||
/// `files` then open in that project's editor.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_project(app: AppHandle, path: PathBuf, new_window: bool) -> IdeResult<OpenOutcome> {
|
||||
windows::open_project_window(&app, &path, new_window)
|
||||
pub async fn window_open_project(
|
||||
app: AppHandle,
|
||||
path: PathBuf,
|
||||
new_window: bool,
|
||||
files: Vec<PathBuf>,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
windows::open_project_window(&app, &path, new_window, files)
|
||||
}
|
||||
|
||||
/// Loose `files` opened from a window without a local project: handed to the LightEdit
|
||||
/// window when another one exists (`focused`), opened in a new one from a remote project
|
||||
/// window (`opened`), else `current` (the caller opens them in LightEdit itself).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_files(app: AppHandle, window: WebviewWindow, files: Vec<PathBuf>) -> IdeResult<OpenOutcome> {
|
||||
windows::open_files_window(&app, window.label(), files)
|
||||
}
|
||||
|
||||
/// [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
@@ -94,7 +109,7 @@ pub fn window_open_projects(
|
||||
Ok(windows::project_window_labels(&app)
|
||||
.into_iter()
|
||||
.filter_map(|label| {
|
||||
let project = state.project(&label).ok()?;
|
||||
let project = state.project(&label).ok().filter(|p| !p.light)?;
|
||||
Some(OpenProject {
|
||||
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
root: project.root.clone(),
|
||||
|
||||
@@ -82,7 +82,7 @@ pub fn run() {
|
||||
if let Ok(cwd) = std::env::current_dir()
|
||||
&& let Some(path) = windows::cli_path(&std::env::args().collect::<Vec<_>>(), &cwd)
|
||||
{
|
||||
windows.set_launch("main", windows::Launch { project: Some(path.into()), ..Default::default() });
|
||||
windows.set_launch("main", windows::path_launch(path));
|
||||
}
|
||||
let menu_state = menu::MenuState::default();
|
||||
menu::install(app.handle(), &menu_state, &state.recent.list());
|
||||
|
||||
+161
-17
@@ -207,6 +207,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.new", "New…"),
|
||||
act("file.newScratchFile", "New Scratch File…"),
|
||||
act("file.openProject", "Open…"),
|
||||
act("file.openFile", "Open File…"),
|
||||
act("file.openInNewWindow", "Open in New Window…"),
|
||||
sub(
|
||||
"openRecent",
|
||||
@@ -408,8 +409,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("navigate.gotoTest", "Test"),
|
||||
SEP,
|
||||
act("navigate.fileStructure", "File Structure"),
|
||||
act("navigate.showFilePath", "File Path"),
|
||||
act("navigate.callHierarchy", "Call Hierarchy"),
|
||||
act("navigate.typeHierarchy", "Type Hierarchy"),
|
||||
act("navigate.customRegion", "Custom Folding…"),
|
||||
SEP,
|
||||
act("navigate.nextMethod", "Next Method"),
|
||||
act("navigate.previousMethod", "Previous Method"),
|
||||
@@ -438,6 +441,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("code.parameterInfo", "Parameter Info"),
|
||||
act("code.quickDocumentation", "Quick Documentation"),
|
||||
act("code.expressionTypeInfo", "Expression Type Info"),
|
||||
act("code.showErrorDescription", "Error Description"),
|
||||
act("code.showIntentions", "Show Context Actions"),
|
||||
act("code.generate", "Generate…"),
|
||||
act("code.overrideMethods", "Override Methods…"),
|
||||
@@ -445,9 +449,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
SEP,
|
||||
act("code.insertLiveTemplate", "Insert Live Template…"),
|
||||
act("code.surroundWith", "Surround With…"),
|
||||
act("code.surroundWithLiveTemplate", "Surround with Live Template…"),
|
||||
act("code.unwrap", "Unwrap/Remove…"),
|
||||
SEP,
|
||||
act("code.reformat", "Reformat Code"),
|
||||
act("code.autoIndentLines", "Auto-Indent Lines"),
|
||||
act("code.optimizeImports", "Optimize Imports"),
|
||||
act("code.cleanup", "Code Cleanup…"),
|
||||
SEP,
|
||||
@@ -458,6 +464,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("code.shrinkSelection", "Shrink Selection"),
|
||||
act("code.duplicateLine", "Duplicate Line or Selection"),
|
||||
act("code.deleteLine", "Delete Line"),
|
||||
act("code.moveStatementUp", "Move Statement Up"),
|
||||
act("code.moveStatementDown", "Move Statement Down"),
|
||||
act("code.moveElementLeft", "Move Element Left"),
|
||||
act("code.moveElementRight", "Move Element Right"),
|
||||
act("code.moveLineUp", "Move Line Up"),
|
||||
act("code.moveLineDown", "Move Line Down"),
|
||||
SEP,
|
||||
@@ -468,13 +478,43 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("code.foldToggle", "Expand/Collapse"),
|
||||
act("code.foldAll", "Collapse All"),
|
||||
act("code.unfoldAll", "Expand All"),
|
||||
sub(
|
||||
"expandToLevel",
|
||||
"Expand to Level",
|
||||
vec![
|
||||
act("code.expandToLevel1", "1"),
|
||||
act("code.expandToLevel2", "2"),
|
||||
act("code.expandToLevel3", "3"),
|
||||
act("code.expandToLevel4", "4"),
|
||||
act("code.expandToLevel5", "5"),
|
||||
],
|
||||
),
|
||||
sub(
|
||||
"expandAllToLevel",
|
||||
"Expand All to Level",
|
||||
vec![
|
||||
act("code.expandAllToLevel1", "1"),
|
||||
act("code.expandAllToLevel2", "2"),
|
||||
act("code.expandAllToLevel3", "3"),
|
||||
act("code.expandAllToLevel4", "4"),
|
||||
act("code.expandAllToLevel5", "5"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("code.collapseBlock", "Fold Code Block"),
|
||||
act("code.foldSelection", "Fold Selection / Remove Region"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("analyze.inspectCode", "Inspect Code…"),
|
||||
sub("analyzeCode", "Analyze Code", vec![act("analyze.locateDuplicates", "Locate Duplicates…")]),
|
||||
sub(
|
||||
"analyzeCode",
|
||||
"Analyze Code",
|
||||
vec![
|
||||
act("analyze.inspectFile", "Inspect Current File"),
|
||||
act("analyze.locateDuplicates", "Locate Duplicates…"),
|
||||
],
|
||||
),
|
||||
act("analyze.stackTrace", "Analyze Stack Trace or Thread Dump…"),
|
||||
],
|
||||
));
|
||||
@@ -496,6 +536,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("refactor.inline", "Inline…"),
|
||||
SEP,
|
||||
act("refactor.move", "Move…"),
|
||||
act("project.copyElement", "Copy…"),
|
||||
act("refactor.safeDelete", "Safe Delete…"),
|
||||
],
|
||||
));
|
||||
@@ -525,6 +566,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("run.stop", "Stop"),
|
||||
SEP,
|
||||
act("run.chooseConfig", "Run…"),
|
||||
act("run.chooseDebugConfig", "Debug…"),
|
||||
act("runAnything.show", "Run Anything…"),
|
||||
act("run.editConfigs", "Edit Configurations…"),
|
||||
act("debug.attachToProcess", "Attach to Process…"),
|
||||
@@ -542,6 +584,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("debug.showExecutionPoint", "Show Execution Point"),
|
||||
act("debug.resetFrame", "Reset Frame"),
|
||||
act("debug.evaluate", "Evaluate Expression…"),
|
||||
act("debug.quickEvaluate", "Quick Evaluate Expression"),
|
||||
sub(
|
||||
"debuggingActions",
|
||||
"Debugging Actions",
|
||||
@@ -568,8 +611,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 +628,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 +638,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 +679,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"),
|
||||
],
|
||||
));
|
||||
|
||||
@@ -684,6 +748,16 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("toolwindow.hideActive", "Hide Active Tool Window"),
|
||||
act("toolwindow.maximize", "Maximize Tool Window"),
|
||||
act("toolwindow.closeContent", "Close Active Tab"),
|
||||
sub(
|
||||
"resizeToolWindow",
|
||||
"Resize",
|
||||
vec![
|
||||
act("toolwindow.resizeLeft", "Stretch to Left"),
|
||||
act("toolwindow.resizeRight", "Stretch to Right"),
|
||||
act("toolwindow.resizeUp", "Stretch to Top"),
|
||||
act("toolwindow.resizeDown", "Stretch to Bottom"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("toolwindow.jumpToLast", "Jump to Last Tool Window"),
|
||||
act("toolwindow.focusEditor", "Focus Editor"),
|
||||
@@ -706,6 +780,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("editor.splitDown", "Split Down"),
|
||||
act("editor.unsplit", "Unsplit"),
|
||||
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
|
||||
act("editor.nextSplitter", "Go to Next Splitter"),
|
||||
act("editor.prevSplitter", "Go to Previous Splitter"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
@@ -1213,6 +1289,7 @@ mod tests {
|
||||
"app.about",
|
||||
"app.quit",
|
||||
"file.openProject",
|
||||
"file.openFile",
|
||||
"file.openInNewWindow",
|
||||
"file.closeProject",
|
||||
"file.save",
|
||||
@@ -1404,6 +1481,10 @@ mod tests {
|
||||
"toolwindow.closeContent",
|
||||
"toolwindow.jumpToLast",
|
||||
"toolwindow.focusEditor",
|
||||
"toolwindow.resizeLeft",
|
||||
"toolwindow.resizeRight",
|
||||
"toolwindow.resizeUp",
|
||||
"toolwindow.resizeDown",
|
||||
]
|
||||
.contains(id)
|
||||
}));
|
||||
@@ -1436,6 +1517,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 {
|
||||
|
||||
@@ -138,6 +138,12 @@ impl AppState {
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
|
||||
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
|
||||
self.remote_dev.disconnect(window);
|
||||
self.host.open_light(window, file)
|
||||
}
|
||||
|
||||
pub fn close_project(&self, window: &str) {
|
||||
self.remote_dev.disconnect(window);
|
||||
self.host.close_project(window);
|
||||
|
||||
@@ -38,6 +38,9 @@ const SETTINGS_MIN_SIZE: (f64, f64) = (640.0, 420.0);
|
||||
pub struct Launch {
|
||||
/// Project folder to open.
|
||||
pub project: Option<ide_core::IpcPath>,
|
||||
/// Files to open in the editor: in `project` once it is open, else in this
|
||||
/// window's project or (without one) in LightEdit.
|
||||
pub files: Vec<ide_core::IpcPath>,
|
||||
/// Remote project to open (Remote Development).
|
||||
pub remote: Option<RemoteLaunch>,
|
||||
/// Settings windows: the page to show.
|
||||
@@ -189,10 +192,26 @@ pub fn find_project_window(app: &AppHandle, root: &Path) -> Option<WebviewWindow
|
||||
let state = app.try_state::<AppState>()?;
|
||||
app.webview_windows().into_iter().filter(|(label, _)| !is_settings_window(label)).find_map(|(label, w)| {
|
||||
let project = state.project(&label).ok()?;
|
||||
(project.root == root).then_some(w)
|
||||
(project.root == root && !project.light).then_some(w)
|
||||
})
|
||||
}
|
||||
|
||||
/// The window editing loose files (LightEdit), if any: more files open there.
|
||||
pub fn find_light_window(app: &AppHandle) -> Option<WebviewWindow> {
|
||||
let state = app.try_state::<AppState>()?;
|
||||
let windows = app.webview_windows();
|
||||
let labels = sorted_labels(windows.keys().map(String::as_str).filter(|l| !is_settings_window(l)));
|
||||
labels.into_iter().find(|l| state.project(l).is_ok_and(|p| p.light)).and_then(|l| windows.get(&l).cloned())
|
||||
}
|
||||
|
||||
/// Hands `files` to the already loaded `window` (its frontend takes them on [`LAUNCH_EVENT`]) and focuses it.
|
||||
fn send_files(app: &AppHandle, window: &WebviewWindow, files: Vec<PathBuf>) {
|
||||
let launch = Launch { files: files.into_iter().map(Into::into).collect(), ..Default::default() };
|
||||
app.state::<WindowsState>().set_launch(window.label(), launch);
|
||||
let _ = app.emit_to(window.label(), LAUNCH_EVENT, ());
|
||||
focus(window);
|
||||
}
|
||||
|
||||
fn has_project(app: &AppHandle, label: &str) -> bool {
|
||||
app.try_state::<AppState>().is_some_and(|s| s.project(label).is_ok() || s.remote_dev.get(label).is_some())
|
||||
}
|
||||
@@ -282,8 +301,15 @@ pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
|
||||
|
||||
/// Creates a new project window; `project` is opened by its frontend on load.
|
||||
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
|
||||
let title = project.as_deref().and_then(Path::file_name).map(|n| n.to_string_lossy().into_owned());
|
||||
create_window_for(app, title, Launch { project: project.map(Into::into), ..Default::default() })
|
||||
create_window_with(app, project, Vec::new())
|
||||
}
|
||||
|
||||
/// [`create_window`] that also opens `files` (without `project`: in LightEdit).
|
||||
fn create_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) -> IdeResult<WebviewWindow> {
|
||||
let title = project.as_deref().or(files.first().map(PathBuf::as_path)).and_then(Path::file_name);
|
||||
let title = title.map(|n| n.to_string_lossy().into_owned());
|
||||
let files = files.into_iter().map(Into::into).collect();
|
||||
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() })
|
||||
}
|
||||
|
||||
fn create_window_for(app: &AppHandle, title: Option<String>, launch: Launch) -> IdeResult<WebviewWindow> {
|
||||
@@ -313,9 +339,13 @@ fn create_window_for(app: &AppHandle, title: Option<String>, launch: Launch) ->
|
||||
/// `create_window` off the event-loop thread (building a window from a
|
||||
/// main-thread callback can deadlock on Windows).
|
||||
pub fn spawn_window(app: &AppHandle, project: Option<PathBuf>) {
|
||||
spawn_window_with(app, project, Vec::new());
|
||||
}
|
||||
|
||||
fn spawn_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathBuf>) {
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = create_window(&app, project) {
|
||||
if let Err(e) = create_window_with(&app, project, files) {
|
||||
tracing::warn!("cannot open window: {}", e.message);
|
||||
}
|
||||
});
|
||||
@@ -333,17 +363,43 @@ pub enum OpenOutcome {
|
||||
Current,
|
||||
}
|
||||
|
||||
pub fn open_project_window(app: &AppHandle, path: &Path, new_window: bool) -> IdeResult<OpenOutcome> {
|
||||
/// Opens folder `path` as a project and then `files` in its editor; see [`OpenOutcome`]
|
||||
/// (`Current`: the caller opens both itself).
|
||||
pub fn open_project_window(
|
||||
app: &AppHandle,
|
||||
path: &Path,
|
||||
new_window: bool,
|
||||
files: Vec<PathBuf>,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
let root = dunce::canonicalize(path).map_err(|e| IdeError::not_found(format!("{}: {e}", path.display())))?;
|
||||
tracing::info!("open_project_window {} new_window={new_window}", root.display());
|
||||
if let Some(w) = find_project_window(app, &root) {
|
||||
focus(&w);
|
||||
if files.is_empty() {
|
||||
focus(&w);
|
||||
} else {
|
||||
send_files(app, &w, files);
|
||||
}
|
||||
return Ok(OpenOutcome::Focused { label: w.label().to_owned() });
|
||||
}
|
||||
if !new_window {
|
||||
return Ok(OpenOutcome::Current);
|
||||
}
|
||||
let window = create_window(app, Some(root))?;
|
||||
let window = create_window_with(app, Some(root), files)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
/// Loose local `files` asked for by a window without a local project: they join
|
||||
/// the LightEdit window when another one has it open; a window busy with a (remote)
|
||||
/// project gets a new LightEdit window; else the caller opens them itself (`Current`).
|
||||
pub fn open_files_window(app: &AppHandle, caller: &str, files: Vec<PathBuf>) -> IdeResult<OpenOutcome> {
|
||||
if let Some(w) = find_light_window(app).filter(|w| w.label() != caller) {
|
||||
send_files(app, &w, files);
|
||||
return Ok(OpenOutcome::Focused { label: w.label().to_owned() });
|
||||
}
|
||||
if !has_project(app, caller) {
|
||||
return Ok(OpenOutcome::Current);
|
||||
}
|
||||
let window = create_window_with(app, None, files)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
@@ -366,35 +422,52 @@ pub fn open_remote_window(app: &AppHandle, ssh_config: &str, path: &str, new_win
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
/// Opens `path` from the command line / a second instance: focuses the window
|
||||
/// that has it, else reuses a window without a project, else makes a new one.
|
||||
/// Opens `path` from the command line / a second instance: a folder focuses the
|
||||
/// window that has it, a file joins the LightEdit window; else a window without
|
||||
/// a project is reused, else a new one is made.
|
||||
pub fn open_path(app: &AppHandle, path: &Path) {
|
||||
let root = match dunce::canonicalize(path) {
|
||||
Ok(r) if r.is_dir() => r,
|
||||
Ok(r) => r.parent().map(Path::to_path_buf).unwrap_or(r),
|
||||
let path = match dunce::canonicalize(path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot open {}: {e}", path.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(w) = find_project_window(app, &root) {
|
||||
let is_dir = path.is_dir();
|
||||
if is_dir && let Some(w) = find_project_window(app, &path) {
|
||||
focus(&w);
|
||||
return;
|
||||
}
|
||||
if !is_dir && let Some(w) = find_light_window(app) {
|
||||
send_files(app, &w, vec![path]);
|
||||
return;
|
||||
}
|
||||
let free = target_window(app)
|
||||
.filter(|w| !has_project(app, w.label()))
|
||||
.filter(|w| !is_settings_window(w.label()))
|
||||
.or_else(|| {
|
||||
app.webview_windows().into_values().find(|w| !is_settings_window(w.label()) && !has_project(app, w.label()))
|
||||
});
|
||||
let launch = path_launch(path);
|
||||
match free {
|
||||
Some(w) => {
|
||||
app.state::<WindowsState>()
|
||||
.set_launch(w.label(), Launch { project: Some(root.into()), ..Default::default() });
|
||||
app.state::<WindowsState>().set_launch(w.label(), launch);
|
||||
let _ = app.emit_to(w.label(), LAUNCH_EVENT, ());
|
||||
focus(&w);
|
||||
}
|
||||
None => spawn_window(app, Some(root)),
|
||||
None => {
|
||||
let files = launch.files.into_iter().map(ide_core::IpcPath::into_path_buf).collect();
|
||||
spawn_window_with(app, launch.project.map(ide_core::IpcPath::into_path_buf), files)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a window opens for a command-line path: a folder as its project, a file in LightEdit.
|
||||
pub fn path_launch(path: PathBuf) -> Launch {
|
||||
if path.is_dir() {
|
||||
Launch { project: Some(path.into()), ..Default::default() }
|
||||
} else {
|
||||
Launch { files: vec![path.into()], ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -568,6 +641,15 @@ mod tests {
|
||||
assert_eq!(cli_path(&s(&["openidea", "-psn_0_123"]), cwd), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_line_folders_open_as_projects_and_files_in_light_edit() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert_eq!(path_launch(dir.clone()).project, Some(dir.into()));
|
||||
let file = std::env::current_exe().unwrap();
|
||||
let launch = path_launch(file.clone());
|
||||
assert_eq!((launch.project, launch.files), (None, vec![file.into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_are_taken_once() {
|
||||
let st = WindowsState::default();
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
-7
@@ -11,6 +11,11 @@ export const commands = {
|
||||
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
|
||||
removeRecentProject: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remove_recent_project", { path })),
|
||||
openProject: (path: string) => typedError<ProjectInfo_Serialize, IdeError>(__TAURI_INVOKE("open_project", { path })),
|
||||
/**
|
||||
* Edits the loose file `path` in this window without a project (LightEdit);
|
||||
* a window already in LightEdit keeps its files. Returns the effective (global) settings.
|
||||
*/
|
||||
lightEditOpen: (path: string) => typedError<Settings_Serialize, IdeError>(__TAURI_INVOKE("light_edit_open", { path })),
|
||||
/** The project open in this window (a settings window: its parent's), if any. */
|
||||
projectCurrent: () => __TAURI_INVOKE<{
|
||||
root: IpcPath,
|
||||
@@ -61,7 +66,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 +77,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 })),
|
||||
@@ -576,8 +583,15 @@ export const commands = {
|
||||
/**
|
||||
* Opens `path` in a new window (`new_window`) or tells the caller to open it
|
||||
* itself (`current`). A project already open in some window is focused instead.
|
||||
* `files` then open in that project's editor.
|
||||
*/
|
||||
windowOpenProject: (path: string, newWindow: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_project", { path, newWindow })),
|
||||
windowOpenProject: (path: string, newWindow: boolean, files: string[]) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_project", { path, newWindow, files })),
|
||||
/**
|
||||
* Loose `files` opened from a window without a local project: handed to the LightEdit
|
||||
* window when another one exists (`focused`), opened in a new one from a remote project
|
||||
* window (`opened`), else `current` (the caller opens them in LightEdit itself).
|
||||
*/
|
||||
windowOpenFiles: (files: string[]) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_files", { files })),
|
||||
/**
|
||||
* [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
* `ssh_config` (Remote Development); a new window connects itself.
|
||||
@@ -598,6 +612,11 @@ export const commands = {
|
||||
windowTakeLaunch: () => __TAURI_INVOKE<{
|
||||
/** Project folder to open. */
|
||||
project: IpcPath | null,
|
||||
/**
|
||||
* Files to open in the editor: in `project` once it is open, else in this
|
||||
* window's project or (without one) in LightEdit.
|
||||
*/
|
||||
files: IpcPath[],
|
||||
/** Remote project to open (Remote Development). */
|
||||
remote: RemoteLaunch | null,
|
||||
/** Settings windows: the page to show. */
|
||||
@@ -1001,7 +1020,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 +1046,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 +1102,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 +1658,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 +2938,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 +3148,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.
|
||||
@@ -3514,6 +3579,11 @@ export type LanguagesSettings = {
|
||||
export type Launch = {
|
||||
/** Project folder to open. */
|
||||
project: IpcPath | null,
|
||||
/**
|
||||
* Files to open in the editor: in `project` once it is open, else in this
|
||||
* window's project or (without one) in LightEdit.
|
||||
*/
|
||||
files: IpcPath[],
|
||||
/** Remote project to open (Remote Development). */
|
||||
remote: RemoteLaunch | null,
|
||||
/** Settings windows: the page to show. */
|
||||
@@ -5007,6 +5077,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 +5655,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 +5689,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];
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
/** Editor actions (ids from keymaps/intellij-macos.ts). */
|
||||
import { EditorSelection, type EditorState } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { addCursorAbove, addCursorBelow, moveLineDown, moveLineUp, toggleBlockComment } from "@codemirror/commands";
|
||||
import { syntaxTree, toggleFold } from "@codemirror/language";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import {
|
||||
addCursorAbove,
|
||||
addCursorBelow,
|
||||
indentSelection,
|
||||
moveLineDown,
|
||||
moveLineUp,
|
||||
toggleBlockComment,
|
||||
} from "@codemirror/commands";
|
||||
import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
|
||||
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
@@ -23,12 +30,39 @@ 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,
|
||||
collapseBlock,
|
||||
expandToLevelEffects,
|
||||
foldAtCaret,
|
||||
foldSelection,
|
||||
unfoldAtCaret,
|
||||
} from "./cm/folding";
|
||||
import { reverseLines, sortLines } from "./cm/lines";
|
||||
import { cursorCodeBlockEnd, cursorCodeBlockStart, cursorMatchBrace, scrollToCenter, splitLine } from "./cm/caretCommands";
|
||||
import { customRegions } from "./cm/regions";
|
||||
import { moveElementLeft, moveElementRight } from "./cm/moveElement";
|
||||
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
|
||||
import {
|
||||
cursorCodeBlockEnd,
|
||||
cursorCodeBlockStart,
|
||||
cursorMatchBrace,
|
||||
scrollToCenter,
|
||||
selectCodeBlockEnd,
|
||||
selectCodeBlockStart,
|
||||
splitLine,
|
||||
} from "./cm/caretCommands";
|
||||
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
|
||||
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
|
||||
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
|
||||
@@ -86,19 +120,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 +167,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 +209,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 +237,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 +298,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,15 +314,70 @@ 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);
|
||||
});
|
||||
}
|
||||
|
||||
/** Navigate › Custom Folding (⌥⌘.): the file's custom regions; picking one moves the caret to it. */
|
||||
function showCustomRegions(view: EditorView) {
|
||||
const regions = customRegions(view.state.doc);
|
||||
if (!regions.length) return void executeAction("editor.showHint", { text: "No custom folding regions in this file" });
|
||||
const head = view.state.selection.main.head;
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor: caretAnchor(view, head),
|
||||
title: "Custom Folding Regions",
|
||||
items: regions.map((r) => ({
|
||||
id: String(r.startLine),
|
||||
label: r.name || "(no description)",
|
||||
detail: `:${r.startLine}`,
|
||||
icon: "folder",
|
||||
run: () => {
|
||||
const line = view.state.doc.line(Math.min(r.startLine, view.state.doc.lines));
|
||||
const at = line.from + /^\s*/.exec(line.text)![0].length;
|
||||
view.dispatch({
|
||||
selection: { anchor: at },
|
||||
effects: EditorView.scrollIntoView(at, { y: "start", yMargin: 40 }),
|
||||
userEvent: "select.navigate",
|
||||
});
|
||||
view.focus();
|
||||
},
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
/** Folding › Expand to Level / Expand All to Level (titles kept literal for the text catalog). */
|
||||
const FOLD_LEVELS: Array<[number, string, string]> = [
|
||||
[1, "Expand to Level 1", "Expand All to Level 1"],
|
||||
[2, "Expand to Level 2", "Expand All to Level 2"],
|
||||
[3, "Expand to Level 3", "Expand All to Level 3"],
|
||||
[4, "Expand to Level 4", "Expand All to Level 4"],
|
||||
[5, "Expand to Level 5", "Expand All to Level 5"],
|
||||
];
|
||||
|
||||
function foldLevel(view: EditorView, level: number, all: boolean) {
|
||||
const effects = expandToLevelEffects(view.state, level, all);
|
||||
if (!effects.length) return;
|
||||
// A caret inside a new fold would unfold it again: it moves to the fold's start.
|
||||
const head = view.state.selection.main.head;
|
||||
const hiding = effects
|
||||
.filter((e) => e.is(foldEffect))
|
||||
.map((e) => e.value as { from: number; to: number })
|
||||
.filter((r) => r.from < head && head < r.to)
|
||||
.sort((a, b) => a.from - b.from)[0];
|
||||
view.dispatch({ effects, selection: hiding ? { anchor: hiding.from } : undefined });
|
||||
}
|
||||
|
||||
// --- cyclic expand word / copy reference ------------------------------------------------
|
||||
|
||||
/** Text of the other open documents for Cyclic Expand Word (bounded). */
|
||||
@@ -299,7 +422,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 +433,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 +454,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",
|
||||
@@ -356,24 +489,42 @@ export function registerEditorActions(): () => void {
|
||||
text("code.deleteLine", "Delete Line", (v) => deleteLine(v)),
|
||||
text("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)),
|
||||
text("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
|
||||
text("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), {
|
||||
keywords: ["swap argument", "move parameter"],
|
||||
}),
|
||||
text("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), {
|
||||
keywords: ["swap argument", "move parameter"],
|
||||
}),
|
||||
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 +537,61 @@ 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.codeBlockStartWithSelection",
|
||||
"Move Caret to Code Block Start with Selection",
|
||||
(v) => selectCodeBlockStart(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
text(
|
||||
"editor.codeBlockEndWithSelection",
|
||||
"Move Caret to Code Block End with Selection",
|
||||
(v) => selectCodeBlockEnd(v),
|
||||
{
|
||||
category: "Editor Actions",
|
||||
},
|
||||
),
|
||||
text("navigate.customRegion", "Custom Folding…", (v) => showCustomRegions(v), {
|
||||
category: "Navigate",
|
||||
keywords: ["region", "editor-fold", "go to region"],
|
||||
}),
|
||||
...FOLD_LEVELS.flatMap(([level, one, all]) => [
|
||||
text(`code.expandToLevel${level}`, one, (v) => foldLevel(v, level, false), {
|
||||
category: "Folding",
|
||||
keywords: ["unfold", "fold level"],
|
||||
}),
|
||||
text(`code.expandAllToLevel${level}`, all, (v) => foldLevel(v, level, true), {
|
||||
category: "Folding",
|
||||
keywords: ["unfold", "fold level"],
|
||||
}),
|
||||
]),
|
||||
text("code.collapseBlock", "Fold Code Block", (v) => collapseBlock(v), { category: "Folding", keywords: ["fold"] }),
|
||||
text("code.autoIndentLines", "Auto-Indent Lines", (v) => !v.state.readOnly && indentSelection(v), {
|
||||
keywords: ["reindent", "fix indentation"],
|
||||
}),
|
||||
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 +609,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 +643,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 +829,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",
|
||||
@@ -639,6 +852,22 @@ export function registerEditorActions(): () => void {
|
||||
when: "editorTabsOpen",
|
||||
run: () => ctrl.split(useTabs.getState().activePane, "column"),
|
||||
},
|
||||
{
|
||||
id: "editor.nextSplitter",
|
||||
title: "Go to Next Splitter",
|
||||
category: "Window",
|
||||
keywords: ["split", "editor group", "pane"],
|
||||
when: "editorSplit",
|
||||
run: () => ctrl.focusSplitter(1),
|
||||
},
|
||||
{
|
||||
id: "editor.prevSplitter",
|
||||
title: "Go to Previous Splitter",
|
||||
category: "Window",
|
||||
keywords: ["split", "editor group", "pane"],
|
||||
when: "editorSplit",
|
||||
run: () => ctrl.focusSplitter(-1),
|
||||
},
|
||||
{
|
||||
id: "editor.moveToOppositeGroup",
|
||||
title: "Move to Opposite Group",
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -78,18 +78,38 @@ export function codeBlockEnd(state: EditorState, pos: number): number | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function moveToBlock(find: (state: EditorState, pos: number) => number | null): Command {
|
||||
function moveToBlock(find: (state: EditorState, pos: number) => number | null, extend = false): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
const target = find(state, state.selection.main.head);
|
||||
const main = state.selection.main;
|
||||
const target = find(state, main.head);
|
||||
if (target == null) return false;
|
||||
view.dispatch({ selection: EditorSelection.cursor(target), scrollIntoView: true, userEvent: "select.navigate" });
|
||||
view.dispatch({
|
||||
selection: extend ? EditorSelection.range(main.anchor, target) : EditorSelection.cursor(target),
|
||||
scrollIntoView: true,
|
||||
userEvent: extend ? "select" : "select.navigate",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export const cursorCodeBlockStart = moveToBlock(codeBlockStart);
|
||||
export const cursorCodeBlockEnd = moveToBlock(codeBlockEnd);
|
||||
export const selectCodeBlockStart = moveToBlock(codeBlockStart, true);
|
||||
export const selectCodeBlockEnd = moveToBlock(codeBlockEnd, true);
|
||||
|
||||
/**
|
||||
* The inside of the `{…}` block around `pos` (between the braces) for Collapse Block;
|
||||
* after a `}` the block it closes. `null` outside any block.
|
||||
*/
|
||||
export function enclosingCodeBlock(state: EditorState, pos: number): { from: number; to: number } | null {
|
||||
const start = codeBlockStart(state, pos);
|
||||
if (start == null) return null;
|
||||
const open = braceAt(state, start) === "{" ? start : start - 1;
|
||||
const end = codeBlockEnd(state, open);
|
||||
if (end == null) return null;
|
||||
return { from: open + 1, to: end - 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where Go to Matching Brace (⌃M) goes from `pos`: from a brace next to the
|
||||
@@ -125,6 +145,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];
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { codeFolding, foldEffect, foldedRanges } from "@codemirror/language";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { enclosingCodeBlock, selectCodeBlockEnd, selectCodeBlockStart } from "./caretCommands";
|
||||
import { collapseBlock, collapseBlockEffects } from "./folding";
|
||||
|
||||
const text = "fn a() {\n if x { y(); }\n z();\n}\n";
|
||||
const at = (needle: string) => text.indexOf(needle);
|
||||
const state = (pos: number) =>
|
||||
EditorState.create({ doc: text, selection: EditorSelection.cursor(pos), extensions: [codeFolding()] });
|
||||
|
||||
describe("enclosingCodeBlock", () => {
|
||||
it("is the inside of the innermost block", () => {
|
||||
expect(enclosingCodeBlock(state(0), at("y()"))).toEqual({ from: at("{ y") + 1, to: at("}\n z") });
|
||||
});
|
||||
|
||||
it("after a closing brace is the block it closes", () => {
|
||||
expect(enclosingCodeBlock(state(0), at("}\n z") + 1)).toEqual({ from: at("{ y") + 1, to: at("}\n z") });
|
||||
});
|
||||
|
||||
it("is null outside any block", () => {
|
||||
expect(enclosingCodeBlock(state(0), 0)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapseBlockEffects", () => {
|
||||
it("folds the block around the caret, then the enclosing one", () => {
|
||||
const s = state(at("y()"));
|
||||
const first = collapseBlockEffects(s);
|
||||
expect(first.map((e) => e.value)).toEqual([{ from: at("{ y") + 1, to: at("}\n z") }]);
|
||||
const folded = s.update({ effects: first }).state;
|
||||
expect(collapseBlockEffects(folded).map((e) => e.value)).toEqual([
|
||||
{ from: at("{\n") + 1, to: text.lastIndexOf("}") },
|
||||
]);
|
||||
expect(first.every((e) => e.is(foldEffect))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("code block with selection", () => {
|
||||
it("extends the selection to the block start and end", () => {
|
||||
const view = new EditorView({ state: state(at("z()")) });
|
||||
selectCodeBlockEnd(view);
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: at("z()"), head: text.lastIndexOf("}") });
|
||||
view.dispatch({ selection: EditorSelection.cursor(at("z()")) });
|
||||
selectCodeBlockStart(view);
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: at("z()"), head: at("{\n") + 1 });
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapseBlock", () => {
|
||||
it("keeps the fold by moving a caret inside it onto the fold", () => {
|
||||
const view = new EditorView({ state: state(at("y()")) });
|
||||
collapseBlock(view);
|
||||
// A later selection change would unfold a fold around the caret.
|
||||
view.dispatch({ selection: view.state.selection });
|
||||
expect(foldedRanges(view.state).size).toBe(1);
|
||||
expect(view.state.selection.main.head).toBe(at("{ y") + 1);
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { codeFolding, foldEffect, foldService, foldedRanges } from "@codemirror/language";
|
||||
import { enclosingFoldRange, foldSelectionEffects, foldToExpand, foldsFromRanges } from "./folding";
|
||||
import {
|
||||
enclosingFoldRange,
|
||||
expandToLevelEffects,
|
||||
foldSelectionEffects,
|
||||
foldToExpand,
|
||||
foldsFromRanges,
|
||||
} from "./folding";
|
||||
|
||||
/** Folds `{ … }` blocks whose header line ends with `{`. */
|
||||
const braces = foldService.of((state, from, to) => {
|
||||
@@ -71,6 +77,12 @@ describe("foldsFromRanges", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("folds a custom region from its start marker through its end marker", () => {
|
||||
const s = EditorState.create({ doc: "class A {\n //region Fields\n int a;\n //endregion\n}\n" });
|
||||
const [f] = foldsFromRanges(s, [fold(1, 3)]);
|
||||
expect(f).toMatchObject({ from: s.doc.line(2).from + 2, to: s.doc.line(4).to, custom: true });
|
||||
});
|
||||
|
||||
it("keeps a brace line that follows a statement or comment", () => {
|
||||
const s = EditorState.create({ doc: "x();\n{\n y();\n}\n// c\n{\n}\n" });
|
||||
expect(foldsFromRanges(s, [fold(1, 3), fold(5, 6)]).map((f) => s.doc.lineAt(f.from).number)).toEqual([2, 6]);
|
||||
@@ -88,3 +100,26 @@ describe("foldSelectionEffects (⌘.)", () => {
|
||||
expect(foldedRanges(s).size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandToLevelEffects", () => {
|
||||
const folded = (s: EditorState) => {
|
||||
const out: number[] = [];
|
||||
foldedRanges(s).between(0, s.doc.length, (a) => void out.push(s.doc.lineAt(a).number));
|
||||
return out;
|
||||
};
|
||||
|
||||
it("Expand All to Level 1 keeps top-level regions open and folds nested ones", () => {
|
||||
let s = make();
|
||||
s = s.update({ effects: expandToLevelEffects(s, 1, true) }).state;
|
||||
expect(folded(s)).toEqual([2]);
|
||||
s = s.update({ effects: expandToLevelEffects(s, 2, true) }).state;
|
||||
expect(folded(s)).toEqual([]);
|
||||
});
|
||||
|
||||
it("Expand to Level counts from the region around the caret", () => {
|
||||
let s = make().update({ selection: { anchor: text.indexOf("y()") } }).state;
|
||||
s = s.update({ effects: expandToLevelEffects(s, 1, true) }).state;
|
||||
s = s.update({ selection: { anchor: text.indexOf("z()") } }).state;
|
||||
expect(folded(s.update({ effects: expandToLevelEffects(s, 2) }).state)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,10 +3,28 @@
|
||||
* with CodeMirror's syntax folding (`foldNodeProp`) as fallback, IDEA-style
|
||||
* chevrons in the gutter (open chevrons only on gutter hover).
|
||||
*/
|
||||
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Line } from "@codemirror/state";
|
||||
import {
|
||||
EditorSelection,
|
||||
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";
|
||||
import { enclosingCodeBlock } from "./caretCommands";
|
||||
import { regionMarker, regionNameAt } from "./regions";
|
||||
|
||||
export interface BackendFold {
|
||||
/** Offset where the fold starts (end of the header line). */
|
||||
@@ -14,6 +32,8 @@ export interface BackendFold {
|
||||
to: number;
|
||||
/** 0-based header line at the time the folds were computed (for sticky scroll). */
|
||||
kind: FoldRange["kind"];
|
||||
/** A custom region (`//region` … `//endregion`): folds from its start marker, which the placeholder names. */
|
||||
custom?: boolean;
|
||||
}
|
||||
|
||||
export const setBackendFolds = StateEffect.define<FoldRange[]>();
|
||||
@@ -36,8 +56,14 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
|
||||
const lines = state.doc.lines;
|
||||
for (const r of ranges) {
|
||||
if (r.start_line + 1 > lines || r.end_line + 1 > lines || r.end_line <= r.start_line) continue;
|
||||
const start = allmanHeader(state, state.doc.line(r.start_line + 1));
|
||||
const first = state.doc.line(r.start_line + 1);
|
||||
const end = state.doc.line(r.end_line + 1);
|
||||
if (regionMarker(first.text)?.start) {
|
||||
const from = first.from + /^\s*/.exec(first.text)![0].length;
|
||||
if (end.to > from) out.push({ from, to: end.to, kind: r.kind, custom: true });
|
||||
continue;
|
||||
}
|
||||
const start = allmanHeader(state, first);
|
||||
const trimmed = end.text.trimStart();
|
||||
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA.
|
||||
const to = /^[}\])]/.test(trimmed) ? end.from + (end.text.length - trimmed.length) : end.to;
|
||||
@@ -73,8 +99,8 @@ function foldAtLine(folds: readonly BackendFold[], lineStart: number, lineEnd: n
|
||||
let best: BackendFold | null = null;
|
||||
for (let i = lo; i < folds.length && folds[i]!.from <= lineEnd; i++) {
|
||||
const f = folds[i]!;
|
||||
// Only folds whose header ends on this line; keep the widest.
|
||||
if (f.from === lineEnd && (!best || f.to > best.to)) best = f;
|
||||
// Only folds whose header ends on this line (custom regions: on this line); keep the widest.
|
||||
if ((f.from === lineEnd || f.custom) && (!best || f.to > best.to)) best = f;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -154,6 +180,38 @@ export function unfoldAtCaret(view: EditorView): boolean {
|
||||
return effects.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA "Collapse Block" (⇧⌘.): folds the inside of the `{…}` block around the
|
||||
* caret, whether or not the language offers a fold there; an already folded
|
||||
* block passes on to the one enclosing it.
|
||||
*/
|
||||
export function collapseBlockEffects(state: EditorState): StateEffect<unknown>[] {
|
||||
const effects: StateEffect<unknown>[] = [];
|
||||
for (const range of state.selection.ranges) {
|
||||
let block = enclosingCodeBlock(state, range.head);
|
||||
while (block && isFolded(state, block)) block = enclosingCodeBlock(state, block.from - 1);
|
||||
if (block && block.to > block.from) effects.push(foldEffect.of(block));
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
|
||||
export function collapseBlock(view: EditorView): boolean {
|
||||
const effects = collapseBlockEffects(view.state);
|
||||
if (!effects.length) return false;
|
||||
// A caret inside a fold would unfold it again: it moves to the fold, as in IDEA.
|
||||
const folds = effects.map((e) => e.value as { from: number; to: number });
|
||||
const sel = view.state.selection;
|
||||
const selection = EditorSelection.create(
|
||||
sel.ranges.map((r) => {
|
||||
const f = folds.find((x) => x.from < r.head && r.head < x.to);
|
||||
return f ? EditorSelection.cursor(f.from) : r;
|
||||
}),
|
||||
sel.mainIndex,
|
||||
);
|
||||
view.dispatch({ effects, selection });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA "Fold Selection / Remove Region" (⌘.): folds each selection (without
|
||||
* a trailing line break); with no selection, toggles the region at the caret.
|
||||
@@ -182,7 +240,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 +255,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);
|
||||
@@ -226,6 +289,34 @@ export function collapseAllEffects(state: EditorState): StateEffect<unknown>[] {
|
||||
}
|
||||
|
||||
/** IDEA "Expand All" (⌘⇧=): every folded region, or those inside the selection. */
|
||||
/**
|
||||
* IDEA "Expand to Level N" (⌘* N) / "Expand All to Level N" (⌘⇧* N): the
|
||||
* regions of the region around the caret (of the file with `all`) nested at most
|
||||
* `level` deep are expanded, deeper ones collapsed.
|
||||
*/
|
||||
export function expandToLevelEffects(state: EditorState, level: number, all = false): StateEffect<unknown>[] {
|
||||
const regions = foldableRegions(state);
|
||||
let scope = regions;
|
||||
if (!all) {
|
||||
const head = state.selection.main.head;
|
||||
const around = regions.filter((r) => r.from <= head && head <= r.to);
|
||||
const root = around.reduce<(typeof regions)[number] | null>(
|
||||
(best, r) => (!best || r.to - r.from < best.to - best.from ? r : best),
|
||||
null,
|
||||
);
|
||||
if (!root) return [];
|
||||
scope = regions.filter((r) => r.from >= root.from && r.to <= root.to);
|
||||
}
|
||||
const effects: StateEffect<unknown>[] = [];
|
||||
for (const r of scope) {
|
||||
const depth = scope.filter((o) => o !== r && o.from <= r.from && r.to <= o.to).length + 1;
|
||||
const folded = isFolded(state, r);
|
||||
if (depth <= level && folded) effects.push(unfoldEffect.of(r));
|
||||
else if (depth > level && !folded) effects.push(foldEffect.of(r));
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
|
||||
export function expandAllEffects(state: EditorState): StateEffect<unknown>[] {
|
||||
const all: Array<{ from: number; to: number }> = [];
|
||||
foldedRanges(state).between(0, state.doc.length, (from, to) => void all.push({ from, to }));
|
||||
@@ -268,9 +359,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");
|
||||
@@ -300,10 +397,12 @@ export function foldingExtension(showOutline = true): Extension {
|
||||
backendFolds,
|
||||
backendFoldService,
|
||||
codeFolding({
|
||||
placeholderDOM: (_view, onclick) => {
|
||||
// A folded custom region shows its name, as in IDEA.
|
||||
preparePlaceholder: (state, range) => regionNameAt(state, range.from),
|
||||
placeholderDOM: (_view, onclick, name: string | null) => {
|
||||
const el = document.createElement("span");
|
||||
el.className = "cm-foldPlaceholder";
|
||||
el.textContent = "…";
|
||||
el.textContent = name ?? "…";
|
||||
el.title = "Expand";
|
||||
el.setAttribute("aria-label", "folded code");
|
||||
el.onclick = onclick;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { moveElementLeft, moveElementRight } from "./moveElement";
|
||||
|
||||
/** `|` marks the caret; returns the text (with caret) after running `cmd`. */
|
||||
function run(text: string, cmd: typeof moveElementLeft): string {
|
||||
const pos = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: text.replace("|", ""), selection: EditorSelection.cursor(pos) }),
|
||||
});
|
||||
cmd(view);
|
||||
const head = view.state.selection.main.head;
|
||||
const doc = view.state.doc.toString();
|
||||
view.destroy();
|
||||
return doc.slice(0, head) + "|" + doc.slice(head);
|
||||
}
|
||||
|
||||
describe("Move Element Left / Right", () => {
|
||||
it("swaps call arguments, keeping the caret in the moved one", () => {
|
||||
expect(run("f(a|lpha, b)", moveElementRight)).toBe("f(b, a|lpha)");
|
||||
expect(run("f(alpha, b|eta)", moveElementLeft)).toBe("f(b|eta, alpha)");
|
||||
});
|
||||
|
||||
it("moves a nested call within the enclosing list", () => {
|
||||
expect(run("f(g(|x), y)", moveElementRight)).toBe("f(y, g(|x))");
|
||||
});
|
||||
|
||||
it("ignores commas in strings and nested brackets", () => {
|
||||
expect(run('f("a, b", [1, 2], |c)', moveElementLeft)).toBe('f("a, b", |c, [1, 2])');
|
||||
});
|
||||
|
||||
it("does nothing at the end of the list", () => {
|
||||
expect(run("f(a, |b)", moveElementRight)).toBe("f(a, |b)");
|
||||
});
|
||||
|
||||
it("works across lines", () => {
|
||||
expect(run("[\n one,\n |two,\n]", moveElementLeft)).toBe("[\n |two,\n one,\n]");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Move Element Left / Right (⌥⇧⌘← / →): swaps the element at the caret with its
|
||||
* neighbour in the enclosing comma-separated list — call arguments, parameters,
|
||||
* array and object literal entries.
|
||||
*/
|
||||
import { EditorSelection, type EditorState } from "@codemirror/state";
|
||||
import type { Command } from "@codemirror/view";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
|
||||
const OPEN = "([{";
|
||||
const CLOSE = ")]}";
|
||||
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
|
||||
/** Lists longer than this are not scanned. */
|
||||
const MAX_SCAN = 20_000;
|
||||
|
||||
function inCode(state: EditorState, pos: number): boolean {
|
||||
const tree = syntaxTree(state);
|
||||
return !tree.length || !NOT_CODE.test(tree.resolveInner(pos, 1).name);
|
||||
}
|
||||
|
||||
/** `[open, close]` offsets of the innermost bracket pair around `pos` that holds a comma list. */
|
||||
function enclosingList(state: EditorState, pos: number): [number, number] | null {
|
||||
const doc = state.doc;
|
||||
const min = Math.max(0, pos - MAX_SCAN);
|
||||
const stack: string[] = [];
|
||||
for (let p = pos - 1; p >= min; p--) {
|
||||
const ch = doc.sliceString(p, p + 1);
|
||||
const close = CLOSE.indexOf(ch);
|
||||
const open = OPEN.indexOf(ch);
|
||||
if (close < 0 && open < 0) continue;
|
||||
if (!inCode(state, p)) continue;
|
||||
if (close >= 0) stack.push(OPEN[close]!);
|
||||
else if (stack.length) {
|
||||
if (stack.pop() !== ch) return null;
|
||||
} else {
|
||||
const end = matchingClose(state, p, ch);
|
||||
if (end != null && end >= pos) return [p, end];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function matchingClose(state: EditorState, open: number, ch: string): number | null {
|
||||
const doc = state.doc;
|
||||
const want = CLOSE[OPEN.indexOf(ch)]!;
|
||||
const max = Math.min(doc.length, open + MAX_SCAN);
|
||||
let depth = 0;
|
||||
for (let p = open + 1; p < max; p++) {
|
||||
const c = doc.sliceString(p, p + 1);
|
||||
if (c === ch && inCode(state, p)) depth++;
|
||||
else if (c === want && inCode(state, p)) {
|
||||
if (depth === 0) return p;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The trimmed top-level elements between `from` and `to`. */
|
||||
export function listElements(state: EditorState, from: number, to: number): { from: number; to: number }[] {
|
||||
const text = state.sliceDoc(from, to);
|
||||
const out: { from: number; to: number }[] = [];
|
||||
let depth = 0;
|
||||
let quote: string | null = null;
|
||||
let start = 0;
|
||||
const push = (end: number) => {
|
||||
const raw = text.slice(start, end);
|
||||
const lead = raw.length - raw.trimStart().length;
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed) out.push({ from: from + start + lead, to: from + start + lead + trimmed.length });
|
||||
};
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text[i]!;
|
||||
if (quote) {
|
||||
if (c === "\\") i++;
|
||||
else if (c === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (c === '"' || c === "'" || c === "`") quote = c;
|
||||
else if ("([{".includes(c)) depth++;
|
||||
else if (")]}".includes(c)) depth--;
|
||||
else if (c === "," && depth === 0) {
|
||||
push(i);
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
push(text.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The swap Move Element would make at `pos`, or null when there is no neighbour. */
|
||||
export function elementSwap(
|
||||
state: EditorState,
|
||||
pos: number,
|
||||
dir: -1 | 1,
|
||||
): { a: { from: number; to: number }; b: { from: number; to: number }; caret: number } | null {
|
||||
// The innermost list with more than one element: in `f(g(x), y)` at `x`, `g(x)` moves.
|
||||
let items: { from: number; to: number }[] = [];
|
||||
for (let at = pos, depth = 0; items.length < 2; depth++) {
|
||||
const list = depth < 16 ? enclosingList(state, at) : null;
|
||||
if (!list) return null;
|
||||
items = listElements(state, list[0] + 1, list[1]);
|
||||
at = list[0];
|
||||
}
|
||||
// The last element starting at or before the caret (the one before a comma it follows).
|
||||
let i = 0;
|
||||
items.forEach((it, k) => {
|
||||
if (it.from <= pos) i = k;
|
||||
});
|
||||
const j = i + dir;
|
||||
if (j < 0 || j >= items.length) return null;
|
||||
const cur = items[i]!;
|
||||
const other = items[j]!;
|
||||
const offset = Math.max(0, Math.min(pos - cur.from, cur.to - cur.from));
|
||||
// Where the moved element starts once both are swapped.
|
||||
const start = dir === 1 ? other.to - (cur.to - cur.from) : other.from;
|
||||
return { a: cur, b: other, caret: start + offset };
|
||||
}
|
||||
|
||||
function moveElement(dir: -1 | 1): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
if (state.readOnly || state.selection.ranges.length > 1) return false;
|
||||
const swap = elementSwap(state, state.selection.main.head, dir);
|
||||
if (!swap) return false;
|
||||
const { a, b } = swap;
|
||||
view.dispatch({
|
||||
changes: [
|
||||
{ from: a.from, to: a.to, insert: state.sliceDoc(b.from, b.to) },
|
||||
{ from: b.from, to: b.to, insert: state.sliceDoc(a.from, a.to) },
|
||||
],
|
||||
selection: EditorSelection.cursor(swap.caret),
|
||||
scrollIntoView: true,
|
||||
userEvent: "move.element",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export const moveElementLeft = moveElement(-1);
|
||||
export const moveElementRight = moveElement(1);
|
||||
@@ -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 ?? [],
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { customRegions, regionMarker, regionNameAt } from "./regions";
|
||||
|
||||
describe("regionMarker", () => {
|
||||
it.each([
|
||||
["//region Accessors", "Accessors"],
|
||||
[" // region Accessors", "Accessors"],
|
||||
["#region Setup", "Setup"],
|
||||
["# region Setup", "Setup"],
|
||||
["//#region Setup", "Setup"],
|
||||
['// <editor-fold desc="Getters">', "Getters"],
|
||||
['<!-- <editor-fold desc="Head"> -->', "Head"],
|
||||
["/* region Block */", "Block"],
|
||||
["//region", ""],
|
||||
])("start %s", (line, name) => {
|
||||
expect(regionMarker(line)).toEqual({ start: true, name });
|
||||
});
|
||||
|
||||
it.each(["//endregion", "# endregion", "#endregion", "// </editor-fold>", "<!-- </editor-fold> -->"])(
|
||||
"end %s",
|
||||
(line) => {
|
||||
expect(regionMarker(line)).toEqual({ start: false });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["const region = 1;", "// the region below", "regions.push(x)"])("not a marker: %s", (line) => {
|
||||
expect(regionMarker(line)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("customRegions", () => {
|
||||
it("matches nested markers and drops unclosed ones", () => {
|
||||
const doc = Text.of(["//region A", "//region B", "x", "//endregion", "//endregion", "//region C"]);
|
||||
expect(customRegions(doc)).toEqual([
|
||||
{ name: "A", startLine: 1, endLine: 5 },
|
||||
{ name: "B", startLine: 2, endLine: 4 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("regionNameAt", () => {
|
||||
it("names a fold starting at a start marker", () => {
|
||||
const state = EditorState.create({ doc: " //region Fields\nint a;\n//endregion" });
|
||||
expect(regionNameAt(state, 2)).toBe("Fields");
|
||||
expect(regionNameAt(state, 5)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Custom folding regions: `//region Name` … `//endregion`, `#region` (C#, Python…),
|
||||
* `<editor-fold desc="Name">` … `</editor-fold>`, in any line comment style.
|
||||
* The backend folds them; this names their placeholders and lists them for
|
||||
* Navigate › Custom Folding (⌥⌘.).
|
||||
*/
|
||||
import type { EditorState, Text } from "@codemirror/state";
|
||||
|
||||
export type RegionMarker = { start: true; name: string } | { start: false };
|
||||
|
||||
const COMMENT_START = /^\s*(?:\/\/+|\/\*+|#|--|;+|%|<!--|')?\s*/;
|
||||
const START = /^#?region\b\s*(.*)$/i;
|
||||
const END = /^(?:#?endregion\b|<\/editor-fold\s*>)/i;
|
||||
const FOLD = /^<editor-fold\b([^>]*)>/i;
|
||||
const DESC = /\bdesc\s*=\s*"([^"]*)"/i;
|
||||
|
||||
/** The region marker on a line of text, if it is one. */
|
||||
export function regionMarker(line: string): RegionMarker | null {
|
||||
if (!/region|editor-fold/i.test(line)) return null;
|
||||
const body = line.replace(COMMENT_START, "").trimEnd();
|
||||
if (END.test(body)) return { start: false };
|
||||
const fold = FOLD.exec(body);
|
||||
if (fold) return { start: true, name: DESC.exec(fold[1]!)?.[1]?.trim() ?? "" };
|
||||
const region = START.exec(body);
|
||||
if (!region) return null;
|
||||
const name = region[1]!
|
||||
.replace(/\s*(?:\*\/|-->)\s*$/, "")
|
||||
.replace(/^"(.*)"$/, "$1")
|
||||
.trim();
|
||||
return { start: true, name };
|
||||
}
|
||||
|
||||
export interface CustomRegion {
|
||||
name: string;
|
||||
/** 1-based lines of the start and end markers. */
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
}
|
||||
|
||||
/** Every matched region of `doc`, in document order of their start markers. */
|
||||
export function customRegions(doc: Text): CustomRegion[] {
|
||||
const out: CustomRegion[] = [];
|
||||
const open: { name: string; line: number; index: number }[] = [];
|
||||
for (let n = 1; n <= doc.lines; n++) {
|
||||
const m = regionMarker(doc.line(n).text);
|
||||
if (!m) continue;
|
||||
if (m.start) {
|
||||
open.push({ name: m.name, line: n, index: out.length });
|
||||
out.push({ name: m.name, startLine: n, endLine: -1 });
|
||||
} else {
|
||||
const s = open.pop();
|
||||
if (s) out[s.index]!.endLine = n;
|
||||
}
|
||||
}
|
||||
return out.filter((r) => r.endLine > 0);
|
||||
}
|
||||
|
||||
/** The name of the region whose start marker begins at `pos` (a fold's start), for its placeholder. */
|
||||
export function regionNameAt(state: EditorState, pos: number): string | null {
|
||||
const line = state.doc.lineAt(pos);
|
||||
if (state.sliceDoc(line.from, pos).trim()) return null;
|
||||
const m = regionMarker(line.text);
|
||||
return m?.start && m.name ? m.name : null;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
highlightSpecialChars,
|
||||
keymap,
|
||||
lineNumbers,
|
||||
tooltips,
|
||||
} from "@codemirror/view";
|
||||
import {
|
||||
bracketMatching,
|
||||
@@ -107,7 +108,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 +168,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 +189,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 +235,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 {
|
||||
@@ -280,8 +302,20 @@ export interface SetupOptions {
|
||||
extra?: Extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tooltips (hints, docs, completion) stay below the editor's top edge: one
|
||||
* above the first lines flips below them instead of hiding under the tabs.
|
||||
*/
|
||||
const tooltipSpace = tooltips({
|
||||
tooltipSpace: (view) => {
|
||||
const top = view.scrollDOM.getBoundingClientRect().top;
|
||||
return { top, left: 0, right: window.innerWidth, bottom: window.innerHeight };
|
||||
},
|
||||
});
|
||||
|
||||
export function baseExtensions(o: SetupOptions): Extension {
|
||||
return [
|
||||
tooltipSpace,
|
||||
compartments.font.of(fontExtension(o.settings)),
|
||||
openideaTheme,
|
||||
compartments.lineNumbers.of(lineNumbersExtension(o.settings)),
|
||||
@@ -310,7 +344,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 +359,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();
|
||||
|
||||
@@ -217,6 +217,7 @@ export class EditorController implements SlotHost {
|
||||
tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose;
|
||||
let prevSettings = useProject.getState().settings;
|
||||
let prevRoot = useProject.getState().project?.root ?? null;
|
||||
let prevLight = useProject.getState().lightEdit;
|
||||
this.disposers.push(
|
||||
useProject.subscribe((s) => {
|
||||
if (s.settings !== prevSettings) {
|
||||
@@ -226,8 +227,10 @@ export class EditorController implements SlotHost {
|
||||
this.manager.applySettings();
|
||||
}
|
||||
const root = s.project?.root ?? null;
|
||||
if (root !== prevRoot) {
|
||||
// Entering or leaving LightEdit replaces the backend's documents too.
|
||||
if (root !== prevRoot || s.lightEdit !== prevLight) {
|
||||
prevRoot = root;
|
||||
prevLight = s.lightEdit;
|
||||
this.saveSession();
|
||||
this.sessionRoot = null;
|
||||
this.closeEverything();
|
||||
@@ -335,7 +338,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). */
|
||||
@@ -865,6 +871,15 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
}
|
||||
|
||||
/** Window › Editor Tabs › Goto Next / Previous Splitter: the active tab of the next split pane, wrapping. */
|
||||
focusSplitter(dir: 1 | -1) {
|
||||
const s = useTabs.getState();
|
||||
const ids = paneIds(s).filter((id) => s.panes[id]?.active);
|
||||
if (ids.length < 2) return;
|
||||
const next = ids[(ids.indexOf(s.activePane) + dir + ids.length) % ids.length]!;
|
||||
this.activate(next, s.panes[next]!.active!);
|
||||
}
|
||||
|
||||
// --- tab commands -----------------------------------------------------------------------------
|
||||
|
||||
private apply(f: (s: TabsState) => TabsState) {
|
||||
@@ -912,7 +927,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 +1093,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 +1105,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 +1198,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) => {
|
||||
@@ -73,6 +75,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 20,
|
||||
component: CaretStatus,
|
||||
title: "Line:Column Number",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.lineEnding",
|
||||
@@ -80,6 +83,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 30,
|
||||
component: LineEndingStatus,
|
||||
title: "Line Separator",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.encoding",
|
||||
@@ -87,6 +91,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 40,
|
||||
component: EncodingStatus,
|
||||
title: "File Encoding",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.indent",
|
||||
@@ -94,6 +99,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 50,
|
||||
component: IndentStatus,
|
||||
title: "Indentation",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.readOnly",
|
||||
@@ -101,6 +107,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 55,
|
||||
component: ReadOnlyStatus,
|
||||
title: "Read-only Attribute",
|
||||
lightEdit: true,
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
|
||||
@@ -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 },
|
||||
|
||||
Loaded 100 of 527 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача