дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
23
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
e17a41fae9 | ||
|
|
aeb190ffda | ||
|
|
a28600c55a | ||
|
|
b35035f8d9 | ||
|
|
cfd2970531 | ||
|
|
11362a36f8 | ||
|
|
e43b0b81c7 | ||
|
|
0c9c51b0f5 | ||
|
|
7e6919010f | ||
|
|
e803d82202 | ||
|
|
a7c970a6db | ||
|
|
0184a9c395 | ||
|
|
4a15936acb | ||
|
|
811da13a76 | ||
|
|
1d383e608c | ||
|
|
2d7726cf53 | ||
|
|
eb67595e72 | ||
|
|
66c36a7361 | ||
|
|
8daeb21005 | ||
|
|
44b2d11b2d | ||
|
|
f8b3ef6840 | ||
|
|
55836e1b49 | ||
|
|
a94b4bff42 |
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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Створено
@@ -4372,6 +4372,7 @@ dependencies = [
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"which",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
|
||||
+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
|
||||
|
||||
@@ -55,7 +55,13 @@ pub struct EditorAppearanceSettings {
|
||||
pub caret_blinking: bool,
|
||||
/// Blink period in ms.
|
||||
pub caret_blink_period: u32,
|
||||
/// Fade the caret in and out instead of toggling it; rounds its corners.
|
||||
pub smooth_caret_blinking: bool,
|
||||
pub block_caret: bool,
|
||||
/// Animate the caret between positions when it is moved.
|
||||
pub smooth_caret_movement: bool,
|
||||
/// Smooth caret movement curve: `snappy` | `gliding`.
|
||||
pub caret_movement_style: String,
|
||||
pub line_numbers: bool,
|
||||
pub method_separators: bool,
|
||||
/// Sub-options of `editor.showWhitespace`.
|
||||
@@ -75,7 +81,10 @@ impl Default for EditorAppearanceSettings {
|
||||
Self {
|
||||
caret_blinking: true,
|
||||
caret_blink_period: 500,
|
||||
smooth_caret_blinking: false,
|
||||
block_caret: false,
|
||||
smooth_caret_movement: false,
|
||||
caret_movement_style: "snappy".into(),
|
||||
line_numbers: true,
|
||||
method_separators: false,
|
||||
whitespace_leading: true,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -69,6 +69,10 @@ pub struct LanguageServerConfig {
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`.
|
||||
#[serde(default)]
|
||||
pub root_markers: Vec<String>,
|
||||
/// Serve only files below a root marker, not the whole project: a framework's
|
||||
/// server (Angular) next to the language's own one.
|
||||
#[serde(default)]
|
||||
pub require_root_marker: bool,
|
||||
/// JSON passed as `initializationOptions`.
|
||||
#[serde(default)]
|
||||
pub initialization_options: Option<toml::Value>,
|
||||
|
||||
@@ -523,12 +523,35 @@ mod tests {
|
||||
("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();
|
||||
let got: Vec<(&str, bool)> = cfg
|
||||
.language_servers
|
||||
.iter()
|
||||
.filter(|s| !s.require_root_marker)
|
||||
.map(|s| (s.name.as_str(), s.fallback))
|
||||
.collect();
|
||||
let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_server_joins_typescript_and_html_in_angular_projects() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
// After the TypeScript fallback (an available server before it would hide
|
||||
// it); before the HTML server (hover, rename and symbols take the first).
|
||||
assert_eq!(names("typescript"), ["vtsls", "typescript-language-server", "angular-language-server"]);
|
||||
assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]);
|
||||
for lang in ["typescript", "html"] {
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
let angular = cfg.language_servers.iter().find(|s| s.name == "angular-language-server").unwrap();
|
||||
assert!(angular.require_root_marker && !angular.fallback, "{lang}");
|
||||
assert_eq!(angular.root_markers, ["angular.json", "node_modules/@angular/core"], "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_file_is_registered_and_parses() {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../languages");
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
//! The Angular Language Server next to vtsls in TypeScript files, asked like
|
||||
//! VS Code's Angular extension asks it: about positions only inside a
|
||||
//! component's template and styles, since it answers nothing elsewhere and
|
||||
//! answers late while it analyses the project.
|
||||
|
||||
pub(crate) const SERVER: &str = "angular-language-server";
|
||||
|
||||
/// Decorator fields holding templates, styles and host bindings.
|
||||
const PROPERTIES: [&str; 6] = ["template", "templateUrl", "styles", "styleUrls", "styleUrl", "host"];
|
||||
/// Decorators taking host bindings as string arguments.
|
||||
const DECORATORS: [&str; 2] = ["HostBinding", "HostListener"];
|
||||
|
||||
/// Whether the Angular server is asked about the position at byte `offset` of
|
||||
/// a `language` document: anywhere in a template file, in TypeScript only in
|
||||
/// a string of a decorator field.
|
||||
pub(crate) fn serves_position(language: &str, text: &str, offset: usize) -> bool {
|
||||
language != "typescript" || in_decorator_field(text, offset)
|
||||
}
|
||||
|
||||
/// Whether the Angular server is asked for the inlay hints of a `language`
|
||||
/// document: in TypeScript only with Angular imported.
|
||||
pub(crate) fn serves_inlay_hints(language: &str, text: &str) -> bool {
|
||||
language != "typescript" || text.contains("@angular/core")
|
||||
}
|
||||
|
||||
/// Whether byte `offset` is inside a string of one of [`PROPERTIES`] (`template:
|
||||
/// '...'`, `styles: ['...']`) or of an argument of one of [`DECORATORS`]. A
|
||||
/// port of the VS Code extension's token scan: false positives are fine, the
|
||||
/// server has the last word.
|
||||
fn in_decorator_field(text: &str, offset: usize) -> bool {
|
||||
let mut scanner = Scanner { text: text.as_bytes(), pos: 0, braces: 0, substitutions: Vec::new() };
|
||||
let (mut last, mut second_last, mut last_text) = (None, None, "");
|
||||
let (mut braces, mut brackets, mut parens) = (0i32, 0i32, 0i32);
|
||||
// The brace and bracket depth of the property whose value is being read.
|
||||
let mut property: Option<(i32, i32)> = None;
|
||||
// The paren depth of the decorator whose arguments are being read.
|
||||
let mut decorator: Option<i32> = None;
|
||||
while let Some((tok, start, end)) = scanner.next() {
|
||||
if start >= offset {
|
||||
break;
|
||||
}
|
||||
if last == Some(Tok::Ident) && tok == Tok::Colon && PROPERTIES.contains(&last_text) {
|
||||
property = Some((braces, brackets));
|
||||
continue;
|
||||
}
|
||||
if property == Some((braces, brackets)) && matches!(tok, Tok::Comma | Tok::Semicolon | Tok::CloseBrace) {
|
||||
property = None;
|
||||
}
|
||||
if second_last == Some(Tok::At)
|
||||
&& last == Some(Tok::Ident)
|
||||
&& tok == Tok::OpenParen
|
||||
&& DECORATORS.contains(&last_text)
|
||||
{
|
||||
decorator = Some(parens);
|
||||
}
|
||||
if tok == Tok::CloseParen && decorator == Some(parens - 1) {
|
||||
decorator = None;
|
||||
}
|
||||
match tok {
|
||||
Tok::OpenBrace => braces += 1,
|
||||
Tok::CloseBrace => braces -= 1,
|
||||
Tok::OpenBracket => brackets += 1,
|
||||
Tok::CloseBracket => brackets -= 1,
|
||||
Tok::OpenParen => parens += 1,
|
||||
Tok::CloseParen => parens -= 1,
|
||||
_ => {}
|
||||
}
|
||||
if (property.is_some() || decorator.is_some()) && tok == Tok::Str && offset <= end {
|
||||
return true;
|
||||
}
|
||||
last_text = text.get(start..end).unwrap_or("");
|
||||
second_last = last;
|
||||
last = Some(tok);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Tok {
|
||||
Ident,
|
||||
Colon,
|
||||
Comma,
|
||||
Semicolon,
|
||||
At,
|
||||
OpenBrace,
|
||||
CloseBrace,
|
||||
OpenBracket,
|
||||
CloseBracket,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
/// A string or a template literal without substitutions.
|
||||
Str,
|
||||
/// A part of a template literal with substitutions (`` `a${`` / `}b${` / `` }c` ``).
|
||||
Template,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// TypeScript tokens, enough to tell strings, names and brackets apart.
|
||||
/// Like the TypeScript scanner without its parser, `/` is never a regex.
|
||||
struct Scanner<'a> {
|
||||
text: &'a [u8],
|
||||
pos: usize,
|
||||
/// Open `{`, not counting those of template substitutions.
|
||||
braces: usize,
|
||||
/// The brace depth each open `${` started at, innermost last.
|
||||
substitutions: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scanner<'_> {
|
||||
/// The next token and its byte range.
|
||||
fn next(&mut self) -> Option<(Tok, usize, usize)> {
|
||||
self.skip_trivia();
|
||||
let start = self.pos;
|
||||
let c = *self.text.get(start)?;
|
||||
self.pos += 1;
|
||||
let tok = match c {
|
||||
b'\'' | b'"' => {
|
||||
self.string(c);
|
||||
Tok::Str
|
||||
}
|
||||
b'`' => {
|
||||
if self.template() {
|
||||
Tok::Template
|
||||
} else {
|
||||
Tok::Str
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
self.braces += 1;
|
||||
Tok::OpenBrace
|
||||
}
|
||||
// The end of a substitution: the template literal goes on.
|
||||
b'}' if self.substitutions.last() == Some(&self.braces) => {
|
||||
self.substitutions.pop();
|
||||
self.template();
|
||||
Tok::Template
|
||||
}
|
||||
b'}' => {
|
||||
self.braces = self.braces.saturating_sub(1);
|
||||
Tok::CloseBrace
|
||||
}
|
||||
b'[' => Tok::OpenBracket,
|
||||
b']' => Tok::CloseBracket,
|
||||
b'(' => Tok::OpenParen,
|
||||
b')' => Tok::CloseParen,
|
||||
b':' => Tok::Colon,
|
||||
b',' => Tok::Comma,
|
||||
b';' => Tok::Semicolon,
|
||||
b'@' => Tok::At,
|
||||
c if is_ident(c) => {
|
||||
while self.text.get(self.pos).is_some_and(|&c| is_ident(c)) {
|
||||
self.pos += 1;
|
||||
}
|
||||
if c.is_ascii_digit() { Tok::Other } else { Tok::Ident }
|
||||
}
|
||||
_ => Tok::Other,
|
||||
};
|
||||
Some((tok, start, self.pos))
|
||||
}
|
||||
|
||||
fn skip_trivia(&mut self) {
|
||||
loop {
|
||||
match (self.text.get(self.pos), self.text.get(self.pos + 1)) {
|
||||
(Some(c), _) if c.is_ascii_whitespace() => self.pos += 1,
|
||||
(Some(b'/'), Some(b'/')) => {
|
||||
while self.text.get(self.pos).is_some_and(|&c| c != b'\n') {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
(Some(b'/'), Some(b'*')) => {
|
||||
self.pos += 2;
|
||||
while self.pos < self.text.len() && !self.text[self.pos..].starts_with(b"*/") {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.pos = (self.pos + 2).min(self.text.len());
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a string opened by `quote`, which a line break ends too.
|
||||
fn string(&mut self, quote: u8) {
|
||||
while let Some(&c) = self.text.get(self.pos) {
|
||||
self.pos += if c == b'\\' { 2 } else { 1 };
|
||||
if c == quote || c == b'\n' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.pos = self.pos.min(self.text.len());
|
||||
}
|
||||
|
||||
/// The rest of a template literal part; `true` when a substitution opens it.
|
||||
fn template(&mut self) -> bool {
|
||||
while let Some(&c) = self.text.get(self.pos) {
|
||||
match c {
|
||||
b'\\' => self.pos += 2,
|
||||
b'`' => {
|
||||
self.pos += 1;
|
||||
return false;
|
||||
}
|
||||
b'$' if self.text.get(self.pos + 1) == Some(&b'{') => {
|
||||
self.pos += 2;
|
||||
self.substitutions.push(self.braces);
|
||||
return true;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
self.pos = self.pos.min(self.text.len());
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifier bytes; any non-ASCII byte belongs to one too.
|
||||
fn is_ident(c: u8) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whether the position marked `|` in `src` is in a decorator field.
|
||||
fn at_marker(src: &str) -> bool {
|
||||
let offset = src.find('|').expect("marker");
|
||||
in_decorator_field(&src.replacen('|', "", 1), offset)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_and_style_strings_are_decorator_fields() {
|
||||
assert!(at_marker("@Component({ selector: 'a', template: `<p>{{ |x }}</p>` })"));
|
||||
assert!(at_marker("@Component({\n template: '<p>|</p>',\n})"));
|
||||
assert!(at_marker("@Component({ templateUrl: './a.|html' })"));
|
||||
assert!(at_marker("@Component({ styles: ['p {}', 'a { |}'] })"));
|
||||
assert!(at_marker("@Component({ host: { '(click)': 'on|Click()' } })"));
|
||||
assert!(at_marker("class A { @HostListener('click', ['$event.|target']) on() {} }"));
|
||||
// Still being typed: the string runs to the end of the line.
|
||||
assert!(at_marker("@Component({ template: '<p>|"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_and_other_strings_are_not() {
|
||||
assert!(!at_marker("@Component({ selector: 'app-|root', template: '' })"));
|
||||
assert!(!at_marker("@Component({ template: '' })\nclass A { t|itle = 'x'; }"));
|
||||
assert!(!at_marker("@Component({ template: '' })\nclass A { title = '|x'; }"));
|
||||
assert!(!at_marker("@Component({ template: |`<p></p>` })"));
|
||||
assert!(!at_marker("@Component({ template: '', imports: [A|] })"));
|
||||
assert!(!at_marker("class A { @HostListener('click') on() { const s = '|'; } }"));
|
||||
assert!(!at_marker("// template: '|'\nclass A {}"));
|
||||
assert!(!at_marker("/* template: '|' */"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitutions_dont_end_template_literals() {
|
||||
// `}` closing `${...}` is not the end of the object holding `template`.
|
||||
assert!(at_marker("const a = `${ {b: 1} }`;\n@Component({ template: '<p>|</p>' })"));
|
||||
assert!(!at_marker("@Component({ template: `<p>${x}|</p>` })"));
|
||||
assert!(at_marker("const s = `${'}'}`; @Component({ template: '<i>|</i>' })"));
|
||||
assert!(!at_marker("const s = `${`${'a'}`}`; class A { b = '|'; }"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_positions_go_to_angular_only_in_decorator_fields() {
|
||||
let src = "@Component({ template: '<p></p>' })\nclass A {}";
|
||||
assert!(serves_position("html", src, src.find("class").unwrap()));
|
||||
assert!(!serves_position("typescript", src, src.find("class").unwrap()));
|
||||
assert!(serves_position("typescript", src, src.find("</p>").unwrap()));
|
||||
assert!(serves_inlay_hints("typescript", "import { Component } from '@angular/core';"));
|
||||
assert!(!serves_inlay_hints("typescript", "export const a = 1;"));
|
||||
assert!(serves_inlay_hints("html", ""));
|
||||
}
|
||||
}
|
||||
@@ -664,6 +664,36 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
WorkspaceEdit { files }
|
||||
}
|
||||
|
||||
/// Adds the changes of `extra`, another server's edit for the same request, to
|
||||
/// `edit` where they leave its own alone: what only the other server sees
|
||||
/// (Angular templates next to vtsls's TypeScript).
|
||||
pub fn merge_workspace_edit(edit: &mut WorkspaceEdit, extra: WorkspaceEdit) {
|
||||
let overlap =
|
||||
|a: &TextEdit, b: &TextEdit| a.range == b.range || (a.range.start < b.range.end && b.range.start < a.range.end);
|
||||
for file in extra.files {
|
||||
let FileEdit::Edit { path, edits } = file else {
|
||||
if !edit.files.contains(&file) {
|
||||
edit.files.push(file);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let own = edit.files.iter_mut().find_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits } if *p == path => Some(edits),
|
||||
_ => None,
|
||||
});
|
||||
match own {
|
||||
Some(own) => {
|
||||
let added: Vec<TextEdit> = edits.into_iter().filter(|e| !own.iter().any(|o| overlap(o, e))).collect();
|
||||
if !added.is_empty() {
|
||||
own.extend(added);
|
||||
own.sort_by_key(|e| e.range.start);
|
||||
}
|
||||
}
|
||||
None => edit.files.push(FileEdit::Edit { path, edits }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- navigation
|
||||
|
||||
pub fn goto_response(conv: &Conv, r: lsp::GotoDefinitionResponse) -> Vec<Location> {
|
||||
@@ -990,6 +1020,33 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn merged_rename_edits_keep_the_first_servers_ones() {
|
||||
let edit = |l: u32, c: u32, text: &str| TextEdit {
|
||||
range: Range::new(Pos::new(l, c), Pos::new(l, c + 5)),
|
||||
new_text: text.into(),
|
||||
};
|
||||
let file = |p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits };
|
||||
// vtsls renames a shorthand property with an alias; the Angular server
|
||||
// renames it plainly and adds the template.
|
||||
let mut merged =
|
||||
WorkspaceEdit { files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])] };
|
||||
let angular = WorkspaceEdit {
|
||||
files: vec![
|
||||
file("/a.ts", vec![edit(9, 4, "entries"), edit(3, 2, "entries"), edit(1, 14, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
],
|
||||
};
|
||||
merge_workspace_edit(&mut merged, angular);
|
||||
assert_eq!(
|
||||
merged.files,
|
||||
[
|
||||
file("/a.ts", vec![edit(1, 14, "entries"), edit(3, 2, "items: entries"), edit(9, 4, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snippet_text_takes_placeholder_defaults() {
|
||||
assert_eq!(snippet_text("foo(${1:a}, $2)$0"), "foo(a, )");
|
||||
|
||||
@@ -12,6 +12,9 @@ use lsp_types as lsp;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
/// Progress token standing for `angular/projectLoadingStart` … `Finish`.
|
||||
const ANGULAR_LOADING: &str = "angular/projectLoading";
|
||||
|
||||
pub struct ClientHandler {
|
||||
mgr: Weak<LspManager>,
|
||||
server: Arc<Server>,
|
||||
@@ -201,6 +204,17 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
}
|
||||
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
|
||||
// The Angular server's project loading, shown like `$/progress`; one
|
||||
// task while several projects load.
|
||||
"angular/projectLoadingStart" if !self.server.progress.lock().contains_key(ANGULAR_LOADING) => self
|
||||
.progress(
|
||||
&mgr,
|
||||
json!({ "token": ANGULAR_LOADING, "value": { "kind": "begin", "title": "Loading Angular project" } }),
|
||||
),
|
||||
"angular/projectLoadingStart" => {}
|
||||
"angular/projectLoadingFinish" => {
|
||||
self.progress(&mgr, json!({ "token": ANGULAR_LOADING, "value": { "kind": "end" } }))
|
||||
}
|
||||
"telemetry/event" | "$/logTrace" | "$/cancelRequest" => {}
|
||||
other => tracing::trace!("[{}] unhandled notification {other}", self.server.name),
|
||||
}
|
||||
|
||||
@@ -66,6 +66,11 @@ impl LspManager {
|
||||
pub fn serves_path(&self, path: &Path) -> bool {
|
||||
let lang = self.languages.detect(path, None);
|
||||
self.language_servers(&lang).iter().any(|ls| {
|
||||
if ls.require_root_marker
|
||||
&& crate::launch::marked_root(&self.project_root, path, &ls.root_markers).is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut cfg = ls.clone();
|
||||
if let Some(hook) = self.config_hook.read().clone() {
|
||||
hook(&mut cfg, &self.project_root);
|
||||
|
||||
@@ -228,6 +228,11 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
|
||||
if !file.starts_with(project_root) {
|
||||
return None;
|
||||
}
|
||||
Some(marked_root(project_root, file, markers).unwrap_or_else(|| project_root.to_path_buf()))
|
||||
}
|
||||
|
||||
/// The outermost ancestor of `file` within `project_root` containing a root marker.
|
||||
pub fn marked_root(project_root: &Path, file: &Path, markers: &[String]) -> Option<PathBuf> {
|
||||
let mut best = None;
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if !dir.starts_with(project_root) {
|
||||
@@ -237,7 +242,7 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
|
||||
best = Some(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
Some(best.unwrap_or_else(|| project_root.to_path_buf()))
|
||||
best
|
||||
}
|
||||
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
@@ -275,6 +280,19 @@ mod tests {
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_root_needs_a_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("apps/web/src/app.ts");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["angular.json".to_string(), "node_modules/@angular/core".to_string()];
|
||||
assert_eq!(marked_root(root, &file, &markers), None);
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
|
||||
assert_eq!(marked_root(root, &file, &markers), Some(root.join("apps/web")));
|
||||
assert_eq!(marked_root(root, &root.join("apps/api/main.ts"), &markers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_path_contains_env_path() {
|
||||
let p = search_path();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! IDE coordinates (UTF-16, 0-based) and returns IDE types from [`types`],
|
||||
//! never `lsp-types`, so the IPC surface stays stable.
|
||||
|
||||
mod angular;
|
||||
mod caps;
|
||||
mod convert;
|
||||
mod file_ops;
|
||||
@@ -125,6 +126,7 @@ impl Target {
|
||||
struct DocSnap {
|
||||
path: PathBuf,
|
||||
uri: lsp::Uri,
|
||||
language: LanguageId,
|
||||
text: Arc<DocText>,
|
||||
servers: Vec<Arc<Server>>,
|
||||
}
|
||||
@@ -142,6 +144,12 @@ impl DocSnap {
|
||||
fn pos_params(&self, t: &Target, pos: Pos) -> Value {
|
||||
json!({ "textDocument": self.ident(), "position": self.position(t, pos) })
|
||||
}
|
||||
/// Whether `t` is asked about `pos`: the Angular server not about the
|
||||
/// TypeScript outside a component's template and styles (see [`angular`]).
|
||||
fn asks(&self, t: &Target, pos: Pos) -> bool {
|
||||
t.server.name != angular::SERVER
|
||||
|| angular::serves_position(self.language.as_str(), self.text.as_str(), self.text.byte_offset(pos))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LspManager {
|
||||
@@ -306,7 +314,8 @@ impl LspManager {
|
||||
}
|
||||
|
||||
/// The servers serving `path`: every regular one, and each `fallback` one
|
||||
/// only while all servers listed before it are missing.
|
||||
/// only while all servers listed before it are missing. One that requires a
|
||||
/// root marker serves only files below one, and stands in for no other.
|
||||
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
|
||||
let mut out = Vec::new();
|
||||
let mut available_before = false;
|
||||
@@ -314,8 +323,11 @@ impl LspManager {
|
||||
if sc.fallback && available_before {
|
||||
continue;
|
||||
}
|
||||
if sc.require_root_marker && launch::marked_root(&self.project_root, path, &sc.root_markers).is_none() {
|
||||
continue;
|
||||
}
|
||||
let server = self.server_for(sc, language, path);
|
||||
available_before |= server.status() != ide_core::event::ServerStatus::Missing;
|
||||
available_before |= !sc.require_root_marker && server.status() != ide_core::event::ServerStatus::Missing;
|
||||
out.push(server);
|
||||
}
|
||||
out
|
||||
@@ -343,22 +355,24 @@ impl LspManager {
|
||||
let mut docs = self.docs.lock();
|
||||
for (id, servers) in wanted {
|
||||
let Some(d) = docs.get_mut(&id) else { continue };
|
||||
for server in servers {
|
||||
for server in &servers {
|
||||
if d.servers.iter().any(|a| a.server.id == server.id) {
|
||||
continue;
|
||||
}
|
||||
let mut attached = Attached { server: server.clone(), opened_gen: None };
|
||||
if let Some(run) = server.running() {
|
||||
if run.caps.read().open_close {
|
||||
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
|
||||
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params());
|
||||
}
|
||||
attached.opened_gen = Some(run.generation);
|
||||
}
|
||||
d.servers.push(attached);
|
||||
if !start.iter().any(|s: &Arc<Server>| s.id == server.id) {
|
||||
start.push(server);
|
||||
start.push(server.clone());
|
||||
}
|
||||
}
|
||||
// In definition order: the first server answers hover, rename and symbols.
|
||||
d.servers.sort_by_key(|a| servers.iter().position(|s| s.id == a.server.id).unwrap_or(usize::MAX));
|
||||
}
|
||||
}
|
||||
for server in &start {
|
||||
@@ -781,6 +795,7 @@ impl LspManager {
|
||||
Ok(DocSnap {
|
||||
path: d.path.clone(),
|
||||
uri: d.uri.clone(),
|
||||
language: d.language.clone(),
|
||||
text: d.text.clone(),
|
||||
servers: d.servers.iter().map(|a| a.server.clone()).collect(),
|
||||
})
|
||||
@@ -837,7 +852,7 @@ impl LspManager {
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<CompletionList> {
|
||||
let (snap, targets) = self.doc_targets(doc, "completion", |c| c.has("completionProvider")).await?;
|
||||
let requests = targets.iter().map(|t| {
|
||||
let requests = targets.iter().filter(|t| snap.asks(t, pos)).map(|t| {
|
||||
let context = match &trigger {
|
||||
Some(ch) if t.caps().completion_triggers().contains(ch) => {
|
||||
json!({ "triggerKind": 2, "triggerCharacter": ch })
|
||||
@@ -924,7 +939,7 @@ impl LspManager {
|
||||
pub async fn hover(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Option<Hover>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "hover", |c| c.has("hoverProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
for t in &targets {
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
let r: IdeResult<Option<lsp::Hover>> =
|
||||
self.call(t, "textDocument/hover", snap.pos_params(t, pos), Some(&cancel), DEFAULT_TIMEOUT).await;
|
||||
match r {
|
||||
@@ -945,7 +960,7 @@ impl LspManager {
|
||||
pub async fn signature_help(&self, doc: DocId, pos: Pos) -> IdeResult<Option<SignatureHelp>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "signature help", |c| c.has("signatureHelpProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
for t in &targets {
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["context"] = json!({ "triggerKind": 1, "isRetrigger": false });
|
||||
match self
|
||||
@@ -1007,7 +1022,7 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let mut out = Outcome::new();
|
||||
for t in targets {
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
match self
|
||||
.call::<_, Option<lsp::GotoDefinitionResponse>>(
|
||||
t,
|
||||
@@ -1049,6 +1064,9 @@ impl LspManager {
|
||||
let requests = targets.iter().map(|t| {
|
||||
let (snap, cancel) = (&snap, &cancel);
|
||||
async move {
|
||||
// The Angular server searches the file's own project only: more open
|
||||
// files don't widen it.
|
||||
let angular = t.server.name == angular::SERVER;
|
||||
let query = || async move {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["context"] = json!({ "includeDeclaration": include_declaration });
|
||||
@@ -1059,7 +1077,7 @@ impl LspManager {
|
||||
};
|
||||
let files =
|
||||
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
|
||||
let result = if project_wide {
|
||||
let result = if project_wide && !angular {
|
||||
self.widened(snap, t, pos, cancel, query, files).await
|
||||
} else {
|
||||
query().await.map(|first| {
|
||||
@@ -1070,12 +1088,25 @@ impl LspManager {
|
||||
(t, result)
|
||||
}
|
||||
});
|
||||
// The Angular server lists the declaration even when not asked to: the one
|
||||
// the definition at `pos` points to is taken out of its answer.
|
||||
let declarations = async {
|
||||
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
|
||||
return Vec::new();
|
||||
}
|
||||
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
|
||||
self.goto_in(&snap, &defining, "textDocument/definition", pos, Some(&cancel)).await.unwrap_or_default()
|
||||
};
|
||||
let (results, declarations) = futures::join!(join_all(requests), declarations);
|
||||
let mut out = Outcome::new();
|
||||
for (t, r) in join_all(requests).await {
|
||||
for (t, r) in results {
|
||||
match r {
|
||||
Ok(w) => {
|
||||
let acc = out.value.get_or_insert_with(References::default);
|
||||
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
|
||||
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
|
||||
if t.server.name == angular::SERVER {
|
||||
locs.retain(|l| !declarations.contains(l));
|
||||
}
|
||||
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
|
||||
acc.locations.extend(locs);
|
||||
acc.incomplete = acc.incomplete.or(w.incomplete);
|
||||
@@ -1296,7 +1327,19 @@ impl LspManager {
|
||||
|
||||
pub async fn prepare_rename(&self, doc: DocId, pos: Pos) -> IdeResult<Option<Range>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let t = &targets[0];
|
||||
let mut out = Outcome::new();
|
||||
for t in &targets {
|
||||
match self.prepare_rename_on(&snap, t, pos).await {
|
||||
Ok(Some(range)) => return Ok(Some(range)),
|
||||
Ok(None) => out.value = Some(None),
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(None)
|
||||
}
|
||||
|
||||
/// What `t` renames at `pos`; one without `prepareRename` renames the word there.
|
||||
async fn prepare_rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos) -> IdeResult<Option<Range>> {
|
||||
if !t.caps().has_sub("renameProvider", "prepareProvider") {
|
||||
return Ok(snap.text.word_range_at(pos));
|
||||
}
|
||||
@@ -1319,15 +1362,50 @@ impl LspManager {
|
||||
|
||||
/// Renames across the project: like [`Self::references`], files outside the
|
||||
/// server's analysis scope that mention the name are opened for the request.
|
||||
/// Every server that can rename there does: the Angular server adds the
|
||||
/// templates to vtsls's edit, whose own edits win where both change the same text.
|
||||
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let t = &targets[0];
|
||||
let renaming = self.rename_targets(&snap, &targets, pos).await;
|
||||
let edits = join_all(renaming.into_iter().map(|t| self.rename_on(&snap, t, pos, &new_name))).await;
|
||||
let mut out = Outcome::new();
|
||||
for edit in edits {
|
||||
match edit {
|
||||
Ok(edit) => match &mut out.value {
|
||||
Some(merged) => convert::merge_workspace_edit(merged, edit),
|
||||
None => out.value = Some(edit),
|
||||
},
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(WorkspaceEdit::default())
|
||||
}
|
||||
|
||||
/// The servers that can rename at `pos`, the first one when none can (a
|
||||
/// single one is asked without `prepareRename`).
|
||||
async fn rename_targets<'t>(&self, snap: &DocSnap, targets: &'t [Target], pos: Pos) -> Vec<&'t Target> {
|
||||
if targets.len() > 1 {
|
||||
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
|
||||
let able: Vec<&Target> =
|
||||
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
|
||||
if !able.is_empty() {
|
||||
return able;
|
||||
}
|
||||
}
|
||||
vec![&targets[0]]
|
||||
}
|
||||
|
||||
async fn rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos, new_name: &str) -> IdeResult<WorkspaceEdit> {
|
||||
let query = || async {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["newName"] = json!(new_name);
|
||||
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
|
||||
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
|
||||
};
|
||||
// The Angular server renames in the file's own project only, whatever is open.
|
||||
if t.server.name == angular::SERVER {
|
||||
return query().await;
|
||||
}
|
||||
let files = |e: &WorkspaceEdit| {
|
||||
e.files
|
||||
.iter()
|
||||
@@ -1337,7 +1415,7 @@ impl LspManager {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
let w = self.widened(snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
// The second edit covers the first: its files stay analysed.
|
||||
Ok(w.second.unwrap_or(w.first))
|
||||
}
|
||||
@@ -1488,7 +1566,8 @@ impl LspManager {
|
||||
|
||||
pub async fn inlay_hints(&self, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "inlay hints", |c| c.has("inlayHintProvider")).await?;
|
||||
let requests = targets.iter().map(|t| {
|
||||
let angular = angular::serves_inlay_hints(snap.language.as_str(), snap.text.as_str());
|
||||
let requests = targets.iter().filter(|t| angular || t.server.name != angular::SERVER).map(|t| {
|
||||
let params = json!({ "textDocument": snap.ident(), "range": snap.range(t, range) });
|
||||
async move {
|
||||
(
|
||||
|
||||
@@ -202,6 +202,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["mock.toml".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
|
||||
settings: None,
|
||||
install_hint: Some(format!("install {name}")),
|
||||
@@ -222,6 +223,16 @@ fn harness_with_fallbacks(servers: &[(&str, Value)], fallbacks: &[&str]) -> Harn
|
||||
}
|
||||
|
||||
fn harness_for(lang_id: &str, ext: &str, servers: &[(&str, Value)], fallbacks: &[&str]) -> Harness {
|
||||
harness_configured(lang_id, ext, servers, |cfg| cfg.fallback = fallbacks.contains(&cfg.name.as_str()))
|
||||
}
|
||||
|
||||
/// `adjust` changes each server's configuration.
|
||||
fn harness_configured(
|
||||
lang_id: &str,
|
||||
ext: &str,
|
||||
servers: &[(&str, Value)],
|
||||
adjust: impl Fn(&mut LanguageServerConfig),
|
||||
) -> Harness {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().to_path_buf();
|
||||
let lang = LanguageConfig {
|
||||
@@ -237,7 +248,11 @@ fn harness_for(lang_id: &str, ext: &str, servers: &[(&str, Value)], fallbacks: &
|
||||
tree_sitter: None,
|
||||
language_servers: servers
|
||||
.iter()
|
||||
.map(|(n, _)| LanguageServerConfig { fallback: fallbacks.contains(n), ..server_cfg(n) })
|
||||
.map(|(n, _)| {
|
||||
let mut cfg = server_cfg(n);
|
||||
adjust(&mut cfg);
|
||||
cfg
|
||||
})
|
||||
.collect(),
|
||||
debugger: None,
|
||||
};
|
||||
@@ -713,6 +728,28 @@ async fn progress_tasks_and_busy_status() {
|
||||
assert!(tasks[2].3);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_project_loading_shows_as_progress() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let peer = h.launcher.state("mock").peer();
|
||||
peer.notify("angular/projectLoadingStart", Value::Null).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
peer.notify("angular/projectLoadingFinish", Value::Null).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let tasks: Vec<(String, bool)> = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { title, done, .. } => Some((title.clone(), *done)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(tasks, [("Loading Angular project".into(), false), ("Loading Angular project".into(), true)]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn crash_restarts_and_reopens_documents() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -896,6 +933,45 @@ async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
|
||||
// `framework` next to `main` (one instance for the whole project), like the
|
||||
// Angular server next to vtsls.
|
||||
let servers = [("main", incremental_caps()), ("framework", incremental_caps())];
|
||||
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
|
||||
"framework" => cfg.require_root_marker = true,
|
||||
_ => cfg.root_markers.clear(),
|
||||
});
|
||||
for dir in ["plain", "app"] {
|
||||
std::fs::create_dir_all(h.root.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(h.root.join("app/mock.toml"), "").unwrap();
|
||||
let (_, plain) = h.open("plain/a.mk", "x");
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(h.statuses("framework").is_empty());
|
||||
|
||||
let (_, app) = h.open("app/b.mk", "y");
|
||||
h.wait_status("framework", ServerStatus::Ready).await;
|
||||
let framework = h.launcher.state("framework");
|
||||
eventually(|| framework.docs.lock().contains_key(&uri_of(&app))).await;
|
||||
assert!(!framework.docs.lock().contains_key(&uri_of(&plain)));
|
||||
eventually(|| h.launcher.state("main").docs.lock().len() == 2).await;
|
||||
|
||||
// It stands in for no other server: with `ghost` missing, its fallback serves too.
|
||||
let servers = [("ghost", json!({})), ("framework", incremental_caps()), ("alt", incremental_caps())];
|
||||
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
|
||||
"framework" => cfg.require_root_marker = true,
|
||||
"alt" => cfg.fallback = true,
|
||||
_ => {}
|
||||
});
|
||||
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("framework", ServerStatus::Ready).await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
|
||||
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
|
||||
@@ -1044,6 +1120,128 @@ async fn navigation_rename_format_and_decorations() {
|
||||
assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None);
|
||||
}
|
||||
|
||||
/// The edits of `edit` in `path`, by range.
|
||||
fn edits_in(edit: &WorkspaceEdit, path: &Path) -> Vec<(Range, String)> {
|
||||
edit.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| (e.range, e.new_text.clone())))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_merges_the_servers_that_can_rename_there() {
|
||||
// `ts` can't rename inside a template string (its `prepareRename` is null), `ng` can.
|
||||
let h = harness(&[("ts", incremental_caps()), ("ng", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "template: `{{ title }}`\ntitle = 1\n");
|
||||
h.wait_status("ts", ServerStatus::Ready).await;
|
||||
h.wait_status("ng", ServerStatus::Ready).await;
|
||||
let html = h.root.join("a.html");
|
||||
let (uri, html_uri) = (uri_of(&path), uri_of(&html));
|
||||
let r = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
|
||||
let ng = h.launcher.state("ng");
|
||||
ng.respond("textDocument/prepareRename", json!({ "range": r(0, 14, 19), "placeholder": "title" }));
|
||||
ng.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": {
|
||||
uri.clone(): [{ "range": r(0, 14, 19), "newText": "heading" }, { "range": r(1, 0, 5), "newText": "heading" }],
|
||||
html_uri: [{ "range": r(0, 3, 8), "newText": "heading" }],
|
||||
} }),
|
||||
);
|
||||
|
||||
assert_eq!(h.mgr.prepare_rename(doc, Pos::new(0, 15)).await.unwrap(), Some(rng(0, 14, 0, 19)));
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 15), "heading".into()).await.unwrap();
|
||||
assert_eq!(edits_in(&edit, &path).len(), 2);
|
||||
assert!(h.launcher.state("ts").requested("textDocument/rename").is_empty());
|
||||
|
||||
// Both can rename the declaration: `ng` adds what `ts` doesn't see, and
|
||||
// `ts`'s own edits win where both change the same text.
|
||||
let ts = h.launcher.state("ts");
|
||||
ts.respond("textDocument/prepareRename", json!({ "range": r(1, 0, 5), "placeholder": "title" }));
|
||||
ts.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": { uri: [{ "range": r(1, 0, 5), "newText": "heading: x" }] } }),
|
||||
);
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 2), "heading".into()).await.unwrap();
|
||||
assert_eq!(edits_in(&edit, &path), [(rng(0, 14, 0, 19), "heading".into()), (rng(1, 0, 1, 5), "heading: x".into())]);
|
||||
assert_eq!(edits_in(&edit, &html), [(rng(0, 3, 0, 8), "heading".into())]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_server_is_asked_about_typescript_only_in_component_templates() {
|
||||
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
|
||||
let h = harness_for("typescript", "ts", &servers, &[]);
|
||||
let (doc, _) = h.open("a.ts", "@Component({ template: '<p>{{ title }}</p>' })\nclass A { title = 1; }\n");
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
h.wait_status("angular-language-server", ServerStatus::Ready).await;
|
||||
let ng = h.launcher.state("angular-language-server");
|
||||
let asked = |method: &str| ng.requested(method).len();
|
||||
let mgr = &h.mgr;
|
||||
let ask = |pos: Pos| async move {
|
||||
mgr.completion(doc, pos, None, Default::default()).await.unwrap();
|
||||
mgr.hover(doc, pos, Default::default()).await.unwrap();
|
||||
mgr.goto(doc, pos, GotoKind::Definition).await.unwrap();
|
||||
};
|
||||
|
||||
// In the class: vtsls alone, though it has no answer.
|
||||
ask(Pos::new(1, 12)).await;
|
||||
assert_eq!(
|
||||
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
|
||||
(0, 0, 0)
|
||||
);
|
||||
// In the template: the Angular server too.
|
||||
ask(Pos::new(0, 31)).await;
|
||||
assert_eq!(
|
||||
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
|
||||
(1, 1, 1)
|
||||
);
|
||||
|
||||
// Inlay hints only where Angular is imported.
|
||||
let lines = rng(0, 0, 2, 0);
|
||||
h.mgr.inlay_hints(doc, lines).await.unwrap();
|
||||
assert_eq!(asked("textDocument/inlayHint"), 0);
|
||||
let (doc, _) = h.open("b.ts", "import { Component } from '@angular/core';\n");
|
||||
h.mgr.inlay_hints(doc, lines).await.unwrap();
|
||||
assert_eq!(asked("textDocument/inlayHint"), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_references_leave_out_the_declaration_unless_asked() {
|
||||
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
|
||||
let h = harness_for("typescript", "ts", &servers, &[]);
|
||||
let (doc, path) = h.open("a.ts", "class A { title = 1; }\n");
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
h.wait_status("angular-language-server", ServerStatus::Ready).await;
|
||||
let html = h.root.join("a.html");
|
||||
let declaration =
|
||||
json!({ "uri": uri_of(&path), "range": {"start":{"line":0,"character":10},"end":{"line":0,"character":15}} });
|
||||
let usage =
|
||||
json!({ "uri": uri_of(&html), "range": {"start":{"line":0,"character":3},"end":{"line":0,"character":8}} });
|
||||
// Like ngserver, it lists the declaration whatever `includeDeclaration` says;
|
||||
// vtsls knows where it is.
|
||||
let ng = h.launcher.state("angular-language-server");
|
||||
ng.respond("textDocument/references", json!([declaration, usage]));
|
||||
let vtsls = h.launcher.state("vtsls");
|
||||
vtsls.respond("textDocument/definition", json!([declaration]));
|
||||
|
||||
let mgr = &h.mgr;
|
||||
let found = |include_declaration: bool| async move {
|
||||
let refs = mgr.references(doc, Pos::new(0, 11), include_declaration, false, Default::default()).await;
|
||||
let mut v: Vec<(PathBuf, Range)> =
|
||||
refs.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(found(false).await, [(html.clone(), rng(0, 3, 0, 8))]);
|
||||
assert_eq!(found(true).await, [(html, rng(0, 3, 0, 8)), (path, rng(0, 10, 0, 15))]);
|
||||
assert_eq!(vtsls.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn utf8_server_positions_are_converted() {
|
||||
let h = harness(&[(
|
||||
|
||||
@@ -69,6 +69,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
root_markers: vec![],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: Some("npm i -g nope-ls".into()),
|
||||
@@ -237,6 +238,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
args: vec!["--stdio".into()],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["tsconfig.json".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
@@ -281,6 +283,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
args: vec!["--stdio".into()],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["package.json".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
@@ -346,3 +349,114 @@ async fn vue_hybrid_mode_end_to_end() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
|
||||
/// The lines `edit` changes in `path`, in order.
|
||||
fn edited_lines(edit: &ide_core::WorkspaceEdit, path: &Path) -> Vec<u32> {
|
||||
let mut lines: Vec<u32> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| e.range.start.line))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
lines.sort();
|
||||
lines
|
||||
}
|
||||
|
||||
/// The Angular Language Server next to vtsls, in an external and an inline
|
||||
/// template. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i
|
||||
/// @angular/language-server @vtsls/language-server @angular/core @angular/common
|
||||
/// @angular/compiler rxjs`; the project is created inside it, so that it
|
||||
/// resolves `@angular/core`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @angular/language-server, @vtsls/language-server and @angular/core (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn angular_language_server_end_to_end() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir_in(&tools).unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("angular.json"), "{\"version\":1,\"projects\":{}}").unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
"{\"compilerOptions\":{\"strict\":true},\"angularCompilerOptions\":{\"strictTemplates\":true},\"include\":[\"src/**/*.ts\"]}",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(root.join("src/app")).unwrap();
|
||||
let app_ts = root.join("src/app/app.ts");
|
||||
let app_html = root.join("src/app/app.html");
|
||||
let inline_ts = root.join("src/app/inline.ts");
|
||||
for (path, text) in [(&app_ts, NG_APP_TS), (&app_html, NG_APP_HTML), (&inline_ts, NG_INLINE_TS)] {
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
// The built-in definitions, with vtsls and the Angular server, and the probe
|
||||
// locations the settings hook adds.
|
||||
let builtin = LanguageRegistry::load(None).unwrap();
|
||||
let probes = tools.join("node_modules/@angular/language-server").to_string_lossy().into_owned();
|
||||
let languages = ["typescript", "html"].map(|id| {
|
||||
let mut cfg = builtin.get(&LanguageId::new(id)).unwrap();
|
||||
cfg.language_servers.retain(|s| s.name == "angular-language-server" || s.name == "vtsls");
|
||||
for server in &mut cfg.language_servers {
|
||||
let bin = if server.name == "vtsls" { "vtsls" } else { "ngserver" };
|
||||
server.command = tools.join("node_modules/.bin").join(bin).to_string_lossy().into_owned();
|
||||
}
|
||||
let server = cfg.language_servers.iter_mut().find(|s| s.name == "angular-language-server").unwrap();
|
||||
server.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes.clone()]);
|
||||
cfg
|
||||
});
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec()));
|
||||
let (html, ts, inline) = (DocId::next(), DocId::next(), DocId::next());
|
||||
mgr.did_open(ts, &app_ts, &LanguageId::new("typescript"), 1, NG_APP_TS);
|
||||
mgr.did_open(html, &app_html, &LanguageId::new("html"), 1, NG_APP_HTML);
|
||||
mgr.did_open(inline, &inline_ts, &LanguageId::new("typescript"), 1, NG_INLINE_TS);
|
||||
|
||||
// `title` in `{{ title }}`.
|
||||
let hover = retry("hover", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(html, Pos::new(0, 8), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("title"), "{}", hover.contents.value);
|
||||
let defs = mgr.goto(html, Pos::new(0, 8), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(defs[0].path, app_ts);
|
||||
assert_eq!(defs[0].range.start.line, 7);
|
||||
|
||||
// `missing` is no member of `App`.
|
||||
retry("template diagnostics", Duration::from_secs(60), || {
|
||||
let found = events
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path == &app_html && !items.is_empty()));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
|
||||
// `count` in the inline template, which vtsls can't rename: renamed there
|
||||
// and in the class.
|
||||
let count = Pos::new(4, 20);
|
||||
let range = mgr.prepare_rename(inline, count).await.unwrap();
|
||||
assert_eq!(range, Some(Range::new(Pos::new(4, 19), Pos::new(4, 24))));
|
||||
let edit = mgr.rename(inline, count, "total".into()).await.unwrap();
|
||||
assert_eq!(edited_lines(&edit, &inline_ts), [4, 7], "{edit:?}");
|
||||
|
||||
// `title` in the class, which both servers rename: vtsls's edit and the
|
||||
// template's from the Angular server.
|
||||
let title = Pos::new(7, 3);
|
||||
let edit = mgr.rename(ts, title, "heading".into()).await.unwrap();
|
||||
assert_eq!((edited_lines(&edit, &app_ts), edited_lines(&edit, &app_html)), (vec![7], vec![0]), "{edit:?}");
|
||||
// Its usage in the template, the declaration left out, from either file.
|
||||
for (doc, pos) in [(ts, title), (html, Pos::new(0, 8))] {
|
||||
let refs = mgr.references(doc, pos, false, false, Default::default()).await.unwrap();
|
||||
let found: Vec<(std::path::PathBuf, u32)> =
|
||||
refs.locations.iter().map(|l| (l.path.to_path_buf(), l.range.start.line)).collect();
|
||||
assert_eq!(found, [(app_html.clone(), 0)]);
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Run configuration detection from build files found at the project root.
|
||||
//! Run configuration detection from build files at the project root, or from the
|
||||
//! builds nested in a folder that holds several repositories.
|
||||
//!
|
||||
//! Detection never fails: unreadable or malformed files simply contribute nothing.
|
||||
|
||||
@@ -461,22 +462,89 @@ fn applies_application_plugin(text: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// How deep a build is looked for when the project root has none (a folder holding
|
||||
/// several repositories: `backend/pom.xml`, `apps/server/settings.gradle`).
|
||||
const NESTED_BUILD_DEPTH: usize = 3;
|
||||
|
||||
/// The builds marked by any of `markers`: the root itself, else the shallowest marked
|
||||
/// folder of each branch, up to [`NESTED_BUILD_DEPTH`] levels down.
|
||||
fn build_dirs(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
|
||||
let marked = |d: &Path| markers.iter().any(|m| d.join(m).is_file());
|
||||
if marked(root) {
|
||||
return vec![root.to_path_buf()];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut level = vec![root.to_path_buf()];
|
||||
for _ in 0..NESTED_BUILD_DEPTH {
|
||||
let mut next = Vec::new();
|
||||
for sub in level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src") && !d.ends_with("out")) {
|
||||
if marked(&sub) {
|
||||
out.push(sub);
|
||||
} else {
|
||||
next.push(sub);
|
||||
}
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Ids, names and working directory of the configurations of a build nested in
|
||||
/// `rel` (`None`: the build at the project root).
|
||||
struct Scope(Option<String>);
|
||||
|
||||
impl Scope {
|
||||
fn new(root: &Path, dir: &Path) -> Self {
|
||||
Self((dir != root).then(|| relative(root, dir).to_string_lossy().replace('\\', "/")))
|
||||
}
|
||||
fn id(&self, base: &str) -> String {
|
||||
match &self.0 {
|
||||
Some(l) => format!("{base}:{l}"),
|
||||
None => base.to_owned(),
|
||||
}
|
||||
}
|
||||
fn name(&self, base: &str) -> String {
|
||||
match &self.0 {
|
||||
Some(l) => format!("{l}: {base}"),
|
||||
None => base.to_owned(),
|
||||
}
|
||||
}
|
||||
fn cwd(&self) -> Option<PathBuf> {
|
||||
self.0.as_ref().map(PathBuf::from)
|
||||
}
|
||||
}
|
||||
|
||||
const GRADLE_SETTINGS: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
const GRADLE_BUILDS: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
|
||||
fn detect_gradle(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let names = ["build.gradle.kts", "build.gradle"];
|
||||
let has_settings = first_existing(root, &["settings.gradle.kts", "settings.gradle"]).is_some();
|
||||
let text = match collect_texts(root, &names) {
|
||||
let markers: Vec<&str> = GRADLE_SETTINGS.iter().chain(GRADLE_BUILDS).copied().collect();
|
||||
for dir in build_dirs(root, &markers) {
|
||||
detect_gradle_build(root, &dir, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_gradle_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let has_settings = first_existing(dir, GRADLE_SETTINGS).is_some();
|
||||
let text = match collect_texts(dir, GRADLE_BUILDS) {
|
||||
Some(t) => t,
|
||||
None if has_settings => collect_texts_from_subdirs(root, &names),
|
||||
None if has_settings => collect_texts_from_subdirs(dir, GRADLE_BUILDS),
|
||||
None => return,
|
||||
};
|
||||
let cmd = wrapper(root, "gradlew", "gradlew.bat", "gradle");
|
||||
out.push(config("gradle:build", "gradle build", "gradle", &cmd, &["build"]));
|
||||
out.push(config("gradle:test", "gradle test", "gradle", &cmd, &["test"]).test());
|
||||
let scope = Scope::new(root, dir);
|
||||
let cmd = wrapper(dir, "gradlew", "gradlew.bat", "gradle");
|
||||
let gradle = |id: &str, task: &str| {
|
||||
config(scope.id(id), scope.name(&format!("gradle {task}")), "gradle", &cmd, &[task]).in_dir(scope.cwd())
|
||||
};
|
||||
spring_boot_apps(root, dir, out);
|
||||
out.push(gradle("gradle:build", "build"));
|
||||
out.push(gradle("gradle:test", "test").test());
|
||||
if applies_application_plugin(&text) {
|
||||
out.push(config("gradle:run", "gradle run", "gradle", &cmd, &["run"]));
|
||||
out.push(gradle("gradle:run", "run"));
|
||||
}
|
||||
if text.contains("org.springframework.boot") {
|
||||
out.push(config("gradle:bootRun", "gradle bootRun", "gradle", &cmd, &["bootRun"]));
|
||||
out.push(gradle("gradle:bootRun", "bootRun"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -494,15 +562,170 @@ fn collect_texts_from_subdirs(root: &Path, names: &[&str]) -> String {
|
||||
}
|
||||
|
||||
fn detect_maven(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(text) = collect_texts(root, &["pom.xml"]) else { return };
|
||||
let cmd = wrapper(root, "mvnw", "mvnw.cmd", "mvn");
|
||||
out.push(config("maven:package", "mvn package", "maven", &cmd, &["package"]));
|
||||
out.push(config("maven:test", "mvn test", "maven", &cmd, &["test"]).test());
|
||||
if text.contains("spring-boot-maven-plugin") {
|
||||
out.push(config("maven:spring-boot:run", "mvn spring-boot:run", "maven", &cmd, &["spring-boot:run"]));
|
||||
for dir in build_dirs(root, &["pom.xml"]) {
|
||||
detect_maven_build(root, &dir, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_maven_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(text) = collect_texts(dir, &["pom.xml"]) else { return };
|
||||
let scope = Scope::new(root, dir);
|
||||
let cmd = wrapper(dir, "mvnw", "mvnw.cmd", "mvn");
|
||||
let maven = |id: &str, goal: &str| {
|
||||
config(scope.id(id), scope.name(&format!("mvn {goal}")), "maven", &cmd, &[goal]).in_dir(scope.cwd())
|
||||
};
|
||||
spring_boot_apps(root, dir, out);
|
||||
out.push(maven("maven:package", "package"));
|
||||
out.push(maven("maven:test", "test").test());
|
||||
if text.contains("spring-boot-maven-plugin") {
|
||||
out.push(maven("maven:spring-boot:run", "spring-boot:run"));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- spring boot
|
||||
|
||||
/// Source files read per build when looking for `@SpringBootApplication` classes.
|
||||
const SPRING_SCAN_FILES: usize = 400;
|
||||
|
||||
/// "Spring Boot" configurations for the `@SpringBootApplication` main classes of the
|
||||
/// modules of the build in `build` that apply the Spring Boot plugin:
|
||||
/// `java -cp ${classpath} <class>` in the module, the classpath resolved at launch.
|
||||
fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut budget = SPRING_SCAN_FILES;
|
||||
let mut modules = vec![build.to_path_buf()];
|
||||
let mut level = vec![build.to_path_buf()];
|
||||
for _ in 0..NESTED_BUILD_DEPTH {
|
||||
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
|
||||
modules.extend(level.iter().cloned());
|
||||
}
|
||||
for module in modules {
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
if !applies_spring_boot(&module) {
|
||||
continue;
|
||||
}
|
||||
let module_rel = (module != root).then(|| relative(root, &module).to_string_lossy().replace('\\', "/"));
|
||||
for class in spring_boot_classes(&module, &mut budget) {
|
||||
let simple = class.rsplit(['.', '$']).next().unwrap_or(&class).to_owned();
|
||||
let id = match &module_rel {
|
||||
Some(m) => format!("application:{m}:{class}"),
|
||||
None => format!("application:{class}"),
|
||||
};
|
||||
out.push(
|
||||
config(id, simple, "spring-boot", "java", &["-cp", "${classpath}", &class])
|
||||
.in_dir(module_rel.as_ref().map(PathBuf::from))
|
||||
.debug("java-debug"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The module's own build applies the Spring Boot plugin, and it has main sources.
|
||||
fn applies_spring_boot(module: &Path) -> bool {
|
||||
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(pom) = read(&module.join("pom.xml")) {
|
||||
return pom.contains("spring-boot-maven-plugin") && !pom.contains("<packaging>pom</packaging>");
|
||||
}
|
||||
GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| {
|
||||
text.lines().any(|l| {
|
||||
let l = l.split("//").next().unwrap_or_default();
|
||||
// The plugin id (`id("org.springframework.boot")`), not a dependency (`org.springframework.boot:…`).
|
||||
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
|
||||
&& !l.contains("apply false")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Binary names of the `@SpringBootApplication` classes with a `main` under
|
||||
/// `src/main/{java,kotlin}`, from the shallowest packages that declare one (the
|
||||
/// application class sits in the root package of the code it scans).
|
||||
fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut level: Vec<PathBuf> =
|
||||
["java", "kotlin"].iter().map(|l| module.join("src/main").join(l)).filter(|d| d.is_dir()).collect();
|
||||
while !level.is_empty() && found.is_empty() && *budget > 0 {
|
||||
let mut next = Vec::new();
|
||||
for dir in &level {
|
||||
let Ok(entries) = fs::read_dir(dir) else { continue };
|
||||
let mut files = Vec::new();
|
||||
for e in entries.filter_map(Result::ok) {
|
||||
let path = e.path();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() => next.push(path),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x == "java" || x == "kt") => {
|
||||
files.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
for file in files {
|
||||
if *budget == 0 {
|
||||
break;
|
||||
}
|
||||
*budget -= 1;
|
||||
if fs::metadata(&file).is_ok_and(|m| m.len() > 256 * 1024) {
|
||||
continue;
|
||||
}
|
||||
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file)) {
|
||||
found.push(class);
|
||||
}
|
||||
}
|
||||
}
|
||||
next.sort();
|
||||
level = next;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The class to launch for a source file declaring a `@SpringBootApplication` with a `main`.
|
||||
pub(crate) fn spring_boot_class(src: &str, file: &Path) -> Option<String> {
|
||||
let code: Vec<&str> = src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect();
|
||||
let code = code.join("\n");
|
||||
let at = code.find("@SpringBootApplication")?;
|
||||
let package = code
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|l| l.strip_prefix("package "))
|
||||
.map(|p| p.trim_end_matches(';').trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
let qualify = |name: &str| match &package {
|
||||
Some(p) => format!("{p}.{name}"),
|
||||
None => name.to_owned(),
|
||||
};
|
||||
if file.extension().is_some_and(|x| x == "kt") {
|
||||
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
|
||||
if code.lines().any(|l| l.starts_with("fun main(")) {
|
||||
let jvm_name = code
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
|
||||
let facade = jvm_name.unwrap_or_else(|| {
|
||||
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let mut chars = stem.chars();
|
||||
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
|
||||
format!("{upper}Kt")
|
||||
});
|
||||
return Some(qualify(&facade));
|
||||
}
|
||||
if !code.contains("fun main(") {
|
||||
return None;
|
||||
}
|
||||
} else if !code.contains("void main(") {
|
||||
return None;
|
||||
}
|
||||
let name: String = code[at..]
|
||||
.split_whitespace()
|
||||
.skip_while(|t| *t != "class")
|
||||
.nth(1)?
|
||||
.chars()
|
||||
.take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
|
||||
.collect();
|
||||
(!name.is_empty()).then(|| qualify(&name))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- go
|
||||
|
||||
fn is_go_main_package(dir: &Path) -> bool {
|
||||
|
||||
@@ -5,6 +5,7 @@ mod detect;
|
||||
pub mod envfile;
|
||||
pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod output_encoding;
|
||||
mod process;
|
||||
mod utf8;
|
||||
pub mod which;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Makes the output of JVM and Python processes match the console's encoding.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `javac` errors, Maven / Gradle logs, `print`), while the console decodes
|
||||
//! the configured encoding (UTF-8 by default). They are told which one to use:
|
||||
//! `java` through `stdout.encoding` / `stderr.encoding` (JDK 19+) and their
|
||||
//! `sun.*` forerunners (JDK 8–18), Maven and Gradle through `MAVEN_OPTS` /
|
||||
//! `GRADLE_OPTS`, Python through `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JAVA_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line, and
|
||||
/// environment variables to set.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
fn java_options(encoding: &str) -> Vec<String> {
|
||||
JAVA_PROPERTIES.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
fn sets_java_encoding(text: &str) -> bool {
|
||||
JAVA_PROPERTIES.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key));
|
||||
let name = crate::wrap::program_name(program).to_ascii_lowercase();
|
||||
match name.as_str() {
|
||||
"java" | "javaw" => {
|
||||
if !args.iter().any(|a| sets_java_encoding(a))
|
||||
&& !current("JDK_JAVA_OPTIONS").is_some_and(|o| sets_java_encoding(&o))
|
||||
{
|
||||
out.java_args = java_options(encoding);
|
||||
}
|
||||
}
|
||||
"mvn" | "mvnw" | "mvnd" | "gradle" | "gradlew" => {
|
||||
let key = if name.starts_with("gradle") { "GRADLE_OPTS" } else { "MAVEN_OPTS" };
|
||||
let opts = current(key).unwrap_or_default();
|
||||
if !sets_java_encoding(&opts) {
|
||||
let added = java_options(encoding).join(" ");
|
||||
let value = if opts.trim().is_empty() { added } else { format!("{} {added}", opts.trim()) };
|
||||
out.env.push((key.to_owned(), value));
|
||||
}
|
||||
}
|
||||
_ if is_python(&name) && current("PYTHONIOENCODING").is_none_or(|v| v.trim().is_empty()) => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(program: &str, args: &[&str], vars: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
let vars: BTreeMap<String, String> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
fix(program, &args, &vars, |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let expected = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
// The reported case: a source-file launch through the Oracle `javapath` shim.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe"] {
|
||||
let f = run(program, &["Main.java"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty());
|
||||
}
|
||||
assert_eq!(run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args[0], "-Dstdout.encoding=GBK");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
assert!(run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true).java_args.is_empty());
|
||||
assert!(
|
||||
run("java", &["Main"], &[("JDK_JAVA_OPTIONS", "-Dsun.stdout.encoding=GBK")], "UTF-8", true)
|
||||
.java_args
|
||||
.is_empty()
|
||||
);
|
||||
assert!(run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_tools_and_python_get_environment_variables() {
|
||||
let opts =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
for program in ["mvn.cmd", "mvnw.cmd", r"C:\maven\bin\mvn.cmd"] {
|
||||
assert_eq!(
|
||||
run(program, &["package"], &[], "UTF-8", true).env,
|
||||
[("MAVEN_OPTS".to_owned(), opts.to_owned())]
|
||||
);
|
||||
}
|
||||
for program in ["gradlew.bat", "gradle.bat"] {
|
||||
assert_eq!(run(program, &["build"], &[], "UTF-8", true).env, [("GRADLE_OPTS".to_owned(), opts.to_owned())]);
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment.
|
||||
let f = run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Xmx1g")], "UTF-8", true);
|
||||
assert_eq!(f.env, [("MAVEN_OPTS".to_owned(), format!("-Xmx1g {opts}"))]);
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == "GRADLE_OPTS").then(|| "-Xmx2g".into()), "UTF-8", true);
|
||||
assert_eq!(inherited.env, [("GRADLE_OPTS".to_owned(), format!("-Xmx2g {opts}"))]);
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,33 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu
|
||||
Ok(TempFile(Some(s.file)))
|
||||
}
|
||||
|
||||
/// Tells JVM and Python processes to write the encoding the console decodes (see
|
||||
/// [`crate::output_encoding`]).
|
||||
fn match_console_encoding(inv: &mut Invocation, env: &mut LaunchEnv, config: &RunConfig, options: &StartOptions) {
|
||||
if inv.raw_args {
|
||||
return;
|
||||
}
|
||||
let inherit = !env.clear;
|
||||
let fix = crate::output_encoding::fix(
|
||||
&inv.program.to_string_lossy(),
|
||||
&inv.args,
|
||||
&env.vars,
|
||||
|key| if inherit { std::env::var(key).ok() } else { None },
|
||||
options.encoding.as_deref().unwrap_or("UTF-8"),
|
||||
cfg!(windows),
|
||||
);
|
||||
env.vars.extend(fix.env);
|
||||
if !fix.java_args.is_empty() {
|
||||
inv.args.splice(0..0, fix.java_args);
|
||||
let mut display = quote(config.command.trim());
|
||||
for a in &inv.args {
|
||||
display.push(' ');
|
||||
display.push_str("e(a));
|
||||
}
|
||||
inv.display = display;
|
||||
}
|
||||
}
|
||||
|
||||
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
|
||||
struct TempFile(Option<PathBuf>);
|
||||
|
||||
@@ -275,7 +302,7 @@ impl ProcessManager {
|
||||
if extras.emulate_terminal && extras.stdin_file.is_some() {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let env = launch_env(root, config)?;
|
||||
let mut env = launch_env(root, config)?;
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
let on_output = match extras.output_file.as_deref() {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
@@ -286,6 +313,10 @@ impl ProcessManager {
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
if !extras.emulate_terminal {
|
||||
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
|
||||
match_console_encoding(&mut inv, &mut env, config, options);
|
||||
}
|
||||
let temp = shorten_java(&mut inv, config, &cwd)?;
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
|
||||
@@ -184,6 +184,130 @@ fn maven_projects() {
|
||||
assert_eq!(c[0].command, "mvn");
|
||||
}
|
||||
|
||||
const BOOT_POM: &str = "<project><artifactId>app</artifactId><build><plugins><plugin>\
|
||||
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>";
|
||||
const PARENT_POM: &str = "<project><packaging>pom</packaging><modules><module>app</module></modules>\
|
||||
<build><pluginManagement><plugins><plugin>\
|
||||
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></pluginManagement>\
|
||||
</build></project>";
|
||||
const BOOT_MAIN: &str = "package org.dromara;\n\nimport org.springframework.boot.SpringApplication;\n\
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n\
|
||||
/** Entry. */\n@SpringBootApplication\npublic class DromaraApplication {\n\
|
||||
\x20 public static void main(String[] args) {\n\
|
||||
\x20 SpringApplication.run(DromaraApplication.class, args);\n }\n}\n";
|
||||
|
||||
/// A folder holding a Maven back end and an npm front end, each its own repository
|
||||
/// (RuoYi-Vue-Plus + plus-ui): the Maven build is detected where it is.
|
||||
#[test]
|
||||
fn builds_nested_in_a_folder_of_repositories() {
|
||||
let dir = project(&[
|
||||
("RuoYi-Vue-Plus/pom.xml", PARENT_POM),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/pom.xml", BOOT_POM),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/DromaraApplication.java", BOOT_MAIN),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/web/Controller.java", "package org.dromara.web;"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/pom.xml", "<project><packaging>pom</packaging></project>"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/pom.xml", "<project/>"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/src/main/java/A.java", "class A {}"),
|
||||
("plus-ui/package.json", r#"{"scripts":{"dev":"vite"}}"#),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
let app = find(&c, "application:RuoYi-Vue-Plus/ruoyi-admin:org.dromara.DromaraApplication");
|
||||
assert_eq!(app.name, "DromaraApplication");
|
||||
assert_eq!(app.kind, "spring-boot");
|
||||
assert_eq!(cmdline(app), "java -cp ${classpath} org.dromara.DromaraApplication");
|
||||
assert_eq!(app.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus/ruoyi-admin")));
|
||||
assert_eq!(app.debug_adapter.as_deref(), Some("java-debug"));
|
||||
let package = find(&c, "maven:package:RuoYi-Vue-Plus");
|
||||
assert_eq!(package.name, "RuoYi-Vue-Plus: mvn package");
|
||||
assert_eq!(cmdline(package), "mvn package");
|
||||
assert_eq!(package.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus")));
|
||||
assert!(find(&c, "maven:test:RuoYi-Vue-Plus").is_test);
|
||||
assert!(ids(&c).contains(&"maven:spring-boot:run:RuoYi-Vue-Plus"));
|
||||
assert!(ids(&c).contains(&"npm:plus-ui:dev"));
|
||||
// Modules of the nested build are not builds of their own; only one application.
|
||||
assert!(!ids(&c).iter().any(|id| id.contains("ruoyi-common")));
|
||||
assert_eq!(c.iter().filter(|c| c.kind == "spring-boot").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_builds_of_every_kind_and_depth() {
|
||||
let dir = project(&[
|
||||
("services/api/settings.gradle.kts", "include(\"app\")"),
|
||||
("services/api/gradlew", "#!/bin/sh"),
|
||||
("services/api/app/build.gradle.kts", "plugins { id(\"org.springframework.boot\") version \"3.3.0\" }\n"),
|
||||
(
|
||||
"services/api/app/src/main/kotlin/com/acme/Api.kt",
|
||||
"package com.acme\n\n@SpringBootApplication\nclass Api\n\nfun main(args: Array<String>) {\n runApplication<Api>(*args)\n}\n",
|
||||
),
|
||||
("billing/pom.xml", BOOT_POM),
|
||||
("billing/mvnw", "#!/bin/sh"),
|
||||
(
|
||||
"billing/src/main/java/Billing.java",
|
||||
"@SpringBootApplication\nclass Billing { public static void main(String[] a) {} }",
|
||||
),
|
||||
// Deeper than a build is looked for.
|
||||
("a/b/c/d/pom.xml", "<project/>"),
|
||||
// Build output and sources are not searched.
|
||||
("web/node_modules/x/pom.xml", "<project/>"),
|
||||
("tool/src/pom.xml", "<project/>"),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
let boot = find(&c, "gradle:bootRun:services/api");
|
||||
assert_eq!(boot.name, "services/api: gradle bootRun");
|
||||
assert_eq!(boot.cwd.as_deref(), Some(Path::new("services/api")));
|
||||
if cfg!(unix) {
|
||||
assert_eq!(cmdline(boot), "./gradlew bootRun");
|
||||
assert_eq!(cmdline(find(&c, "maven:package:billing")), "./mvnw package");
|
||||
}
|
||||
assert!(find(&c, "gradle:test:services/api").is_test);
|
||||
let api = find(&c, "application:services/api/app:com.acme.ApiKt");
|
||||
assert_eq!(api.cwd.as_deref(), Some(Path::new("services/api/app")));
|
||||
let billing = find(&c, "application:billing:Billing");
|
||||
assert_eq!(billing.cwd.as_deref(), Some(Path::new("billing")));
|
||||
let builds: Vec<&str> =
|
||||
ids(&c).into_iter().filter(|id| id.starts_with("maven:package") || id.starts_with("gradle:build")).collect();
|
||||
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_build_disables_the_nested_scan() {
|
||||
let dir = project(&[
|
||||
("pom.xml", BOOT_POM),
|
||||
(
|
||||
"src/main/java/demo/App.java",
|
||||
"package demo;\n@SpringBootApplication public class App {\n public static void main(String[] args) {}\n}\n",
|
||||
),
|
||||
("tools/gen/pom.xml", "<project/>"),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(ids(&c).contains(&"maven:package"));
|
||||
assert!(!ids(&c).iter().any(|id| id.contains("tools")));
|
||||
let app = find(&c, "application:demo.App");
|
||||
assert_eq!(app.cwd, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spring_boot_applications_need_the_plugin_and_a_main() {
|
||||
let main =
|
||||
"package demo;\n@SpringBootApplication\npublic class App {\n public static void main(String[] args) {}\n}\n";
|
||||
// A library using Spring Boot without the plugin, a configuration class without `main`,
|
||||
// the annotation in a comment, a parent POM.
|
||||
let dir = project(&[
|
||||
("lib/pom.xml", "<project><dependencies>spring-boot-starter</dependencies></project>"),
|
||||
("lib/src/main/java/demo/App.java", main),
|
||||
("svc/pom.xml", BOOT_POM),
|
||||
("svc/src/main/java/demo/Config.java", "package demo;\n@SpringBootApplication\npublic class Config {}\n"),
|
||||
(
|
||||
"svc/src/main/java/demo/Old.java",
|
||||
"package demo;\n// @SpringBootApplication\nclass Old { public static void main(String[] a) {} }\n",
|
||||
),
|
||||
("gr/build.gradle", "dependencies { implementation 'org.springframework.boot:spring-boot-starter' }\n"),
|
||||
("gr/src/main/java/demo/App.java", main),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_projects() {
|
||||
let dir = project(&[
|
||||
|
||||
@@ -17,6 +17,7 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Angular Language Server (`ngserver`): its package, where TypeScript and
|
||||
//! `@angular/language-service` come from, and the project's Angular version.
|
||||
|
||||
use crate::npm::package_dir;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const SERVER: &str = "angular-language-server";
|
||||
const PACKAGE: &str = "@angular/language-server";
|
||||
|
||||
/// `@angular/language-server`'s directory for an `ngserver` executable.
|
||||
pub(crate) fn server_package(bin: &Path) -> Option<PathBuf> {
|
||||
package_dir(bin, PACKAGE)
|
||||
}
|
||||
|
||||
/// Why an `ngserver` whose package isn't found can't start: it loads TypeScript
|
||||
/// and `@angular/language-service` from there.
|
||||
pub(crate) fn missing_package_message(bin: &Path) -> String {
|
||||
format!(
|
||||
"Can't find the @angular/language-server package of {}, which brings the TypeScript and Angular \
|
||||
language service the server loads. Reinstall it in Settings › Languages & Frameworks › Language \
|
||||
Servers or with `npm i -g @angular/language-server`.",
|
||||
bin.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a server installed in a directory whose path has a comma can't start.
|
||||
pub(crate) fn comma_message(package: &str) -> String {
|
||||
format!(
|
||||
"The Angular Language Server can't load from {package}: its path has a comma. Install it in a \
|
||||
directory without one."
|
||||
)
|
||||
}
|
||||
|
||||
/// The version of the `@angular/core` that `dir` resolves (from its own or an
|
||||
/// ancestor's `node_modules`, like Node).
|
||||
pub(crate) fn core_version(dir: &Path) -> Option<String> {
|
||||
dir.ancestors().find_map(|a| {
|
||||
let text = std::fs::read_to_string(a.join("node_modules/@angular/core/package.json")).ok()?;
|
||||
let json: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
json.get("version")?.as_str().map(str::to_owned)
|
||||
})
|
||||
}
|
||||
|
||||
/// Arguments telling the server the project's Angular `version`: templates of
|
||||
/// projects before 17 have no blocks (`@if`), before 18.1 no `@let`.
|
||||
pub(crate) fn version_args(version: &str) -> Vec<String> {
|
||||
let mut parts = version.split(['.', '-', '+']).map(|p| p.parse::<u32>().ok());
|
||||
let (Some(Some(major)), Some(Some(minor))) = (parts.next(), parts.next()) else { return Vec::new() };
|
||||
// 0.0.0: a local build of Angular.
|
||||
if major == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut args = vec!["--angularCoreVersion".to_owned(), version.to_owned()];
|
||||
if major < 17 {
|
||||
args.push("--disableBlockSyntax".into());
|
||||
}
|
||||
if (major, minor) < (18, 1) {
|
||||
args.push("--disableLetSyntax".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn template_syntax_follows_the_angular_version() {
|
||||
let args = |v: &str| version_args(v).into_iter().skip(2).collect::<Vec<_>>();
|
||||
assert_eq!(version_args("22.2.3")[..2], ["--angularCoreVersion", "22.2.3"]);
|
||||
assert_eq!(args("22.0.0-next.1"), Vec::<String>::new());
|
||||
assert_eq!(args("18.1.0"), Vec::<String>::new());
|
||||
assert_eq!(args("18.0.5"), ["--disableLetSyntax"]);
|
||||
assert_eq!(args("17.3.12"), ["--disableLetSyntax"]);
|
||||
assert_eq!(args("16.2.0"), ["--disableBlockSyntax", "--disableLetSyntax"]);
|
||||
assert!(version_args("0.0.0-PLACEHOLDER").is_empty());
|
||||
assert!(version_args("next").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_version_is_found_in_an_ancestor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let core = tmp.path().join("node_modules/@angular/core");
|
||||
std::fs::create_dir_all(&core).unwrap();
|
||||
std::fs::write(core.join("package.json"), r#"{"name":"@angular/core","version":"19.2.1"}"#).unwrap();
|
||||
let app = tmp.path().join("apps/web");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
assert_eq!(core_version(&app).as_deref(), Some("19.2.1"));
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,13 @@
|
||||
|
||||
use crate::discover::{project_venv_python, workspace_tsdk};
|
||||
use crate::exec::{path_with, search_path};
|
||||
use crate::{angular, godot, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use crate::{godot, vue};
|
||||
use ide_core::settings::{LanguageServerSettings, Settings};
|
||||
use ide_language::{LanguageConfig, LanguageServerConfig};
|
||||
use ide_run::RunConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn non_empty(s: &str) -> Option<&str> {
|
||||
@@ -300,6 +301,11 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
let dirs: Vec<&Path> = path_dirs.iter().map(PathBuf::as_path).collect();
|
||||
cfg.env.insert("PATH".into(), path_with(&dirs));
|
||||
}
|
||||
|
||||
// Last: it finds the server on the `PATH` set above.
|
||||
if name == angular::SERVER {
|
||||
configure_angular(cfg, root, server_root, s);
|
||||
}
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
@@ -334,6 +340,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
args: Vec::new(),
|
||||
env: Default::default(),
|
||||
root_markers: ls.root_markers.clone(),
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: Some(match ls.command.trim() {
|
||||
@@ -394,6 +401,38 @@ fn configure_vue_typescript(cfg: &mut LanguageServerConfig, root: &Path, server_
|
||||
}
|
||||
}
|
||||
|
||||
/// ngserver loads TypeScript and `@angular/language-service` from probe
|
||||
/// locations: its own package (it depends on both), then the project. A selected
|
||||
/// TypeScript version goes first (`--tsdk`); the project's Angular version decides
|
||||
/// the template syntax. Without its package the server can't start.
|
||||
fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
// Found as the launcher finds it; missing, it asks to be installed.
|
||||
let path = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
|
||||
let Ok(bin) = which::which_in(&cfg.command, Some(path), server_root) else { return };
|
||||
let Some(package) = angular::server_package(&bin) else {
|
||||
cfg.launch_error = Some(angular::missing_package_message(&bin));
|
||||
return;
|
||||
};
|
||||
let package = package.to_string_lossy().into_owned();
|
||||
// The server splits the list at commas.
|
||||
if package.contains(',') {
|
||||
cfg.launch_error = Some(angular::comma_message(&package));
|
||||
return;
|
||||
}
|
||||
// Launch the server whose package is probed, not another one on the path.
|
||||
cfg.command = bin.to_string_lossy().into_owned();
|
||||
let project = server_root.to_string_lossy();
|
||||
let probes = if project.contains(',') { package } else { format!("{package},{project}") };
|
||||
cfg.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes]);
|
||||
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
|
||||
cfg.args.extend(["--tsdk".into(), lib.to_string_lossy().into_owned()]);
|
||||
}
|
||||
// The project root is an ancestor of the server's.
|
||||
if let Some(version) = angular::core_version(server_root) {
|
||||
cfg.args.extend(angular::version_args(&version));
|
||||
}
|
||||
}
|
||||
|
||||
fn is_python_command(cmd: &str) -> bool {
|
||||
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = name.strip_suffix(".exe").unwrap_or(&name);
|
||||
|
||||
@@ -14,9 +14,15 @@ pub fn search_path() -> OsString {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(home) = crate::home_dir() {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".volta/bin"] {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".bun/bin", ".npm-global/bin", ".volta/bin"] {
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
// nvm: newest installed node's bin, as language servers are launched.
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! - applying the selected toolchains from settings to language-server launch
|
||||
//! configs, run configurations and new terminal sessions ([`apply`]).
|
||||
|
||||
mod angular;
|
||||
pub mod apply;
|
||||
mod discover;
|
||||
mod exec;
|
||||
@@ -14,6 +15,7 @@ pub mod jdtls;
|
||||
pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
mod npm;
|
||||
pub mod python;
|
||||
mod vue;
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Node-based language servers installed with npm: the package behind a command.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `command` as given (a path) or found on `path`, npm shims included.
|
||||
pub(crate) fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
let p = Path::new(command);
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
|
||||
std::env::split_paths(path)
|
||||
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
|
||||
.find(|c| c.is_file())
|
||||
}
|
||||
|
||||
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
|
||||
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
|
||||
/// Unix global `<prefix>/bin` or a symlink into the package.
|
||||
pub(crate) fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
let dir = bin.parent()?;
|
||||
let mut candidates = vec![dir.join("node_modules").join(package)];
|
||||
if dir.file_name() == Some(OsStr::new(".bin"))
|
||||
&& let Some(node_modules) = dir.parent()
|
||||
{
|
||||
candidates.push(node_modules.join(package));
|
||||
}
|
||||
if let Ok(real) = dunce::canonicalize(bin) {
|
||||
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
|
||||
}
|
||||
if let Some(prefix) = dir.parent() {
|
||||
candidates.push(prefix.join("lib").join("node_modules").join(package));
|
||||
}
|
||||
candidates.into_iter().find(|c| c.join("package.json").is_file())
|
||||
}
|
||||
@@ -27,6 +27,7 @@ fn server(name: &str) -> LanguageServerConfig {
|
||||
args: vec![],
|
||||
env: BTreeMap::new(),
|
||||
root_markers: vec![],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
@@ -600,6 +601,78 @@ fn vue_language_server_gets_a_typescript_with_the_language_service_api() {
|
||||
assert_eq!(cfg.args, [format!("--tsdk={}", lib.to_string_lossy())]);
|
||||
}
|
||||
|
||||
/// An npm shim for `name` in `dir`: `name.cmd` on Windows, an executable elsewhere.
|
||||
fn npm_shim(dir: &Path, name: &str) -> std::path::PathBuf {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let shim = dir.join(if cfg!(windows) { format!("{name}.cmd") } else { name.to_owned() });
|
||||
std::fs::write(&shim, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(&shim, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
shim
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_language_server_probes_its_own_package_then_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tools = tmp.path().join("tools/node_modules");
|
||||
let project = tmp.path().join("app");
|
||||
let ngserver = npm_shim(&tools.join(".bin"), "ngserver");
|
||||
for (p, content) in [
|
||||
(tools.join("@angular/language-server/package.json"), "{}"),
|
||||
(project.join("node_modules/@angular/core/package.json"), r#"{"version":"17.3.0"}"#),
|
||||
(project.join("node_modules/typescript/lib/tsserver.js"), ""),
|
||||
] {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, content).unwrap();
|
||||
}
|
||||
let configured = |command: &str, s: &Settings| {
|
||||
let mut cfg = server("angular-language-server");
|
||||
cfg.command = command.into();
|
||||
cfg.args = vec!["--stdio".into()];
|
||||
configure_server(&mut cfg, &project, &project, s);
|
||||
cfg
|
||||
};
|
||||
let probes = format!("{},{}", tools.join("@angular/language-server").to_string_lossy(), project.to_string_lossy());
|
||||
let cfg = configured(&ngserver.to_string_lossy(), &Settings::default());
|
||||
assert_eq!(
|
||||
cfg.args,
|
||||
[
|
||||
"--stdio",
|
||||
"--ngProbeLocations",
|
||||
&probes,
|
||||
"--tsProbeLocations",
|
||||
&probes,
|
||||
"--angularCoreVersion",
|
||||
"17.3.0",
|
||||
"--disableLetSyntax"
|
||||
]
|
||||
);
|
||||
assert_eq!(cfg.launch_error, None);
|
||||
|
||||
// The project's TypeScript when selected.
|
||||
let mut s = Settings::default();
|
||||
s.languages.typescript.version = "workspace".into();
|
||||
let args = configured(&ngserver.to_string_lossy(), &s).args;
|
||||
let tsdk = args.iter().position(|a| a == "--tsdk").map(|i| args[i + 1].clone());
|
||||
assert_eq!(tsdk, Some(project.join("node_modules/typescript/lib").to_string_lossy().into_owned()));
|
||||
|
||||
// Found on the selected Node.js's PATH like the launcher finds it, and
|
||||
// launched from there.
|
||||
let mut s = Settings::default();
|
||||
s.languages.node.interpreter = tools.join(".bin/node").to_string_lossy().into_owned();
|
||||
let cfg = configured("ngserver", &s);
|
||||
assert_eq!(dunce::canonicalize(&cfg.command).unwrap(), dunce::canonicalize(&ngserver).unwrap());
|
||||
assert!(cfg.args.contains(&probes));
|
||||
|
||||
// Without its package the server can't start; not installed, it asks to be.
|
||||
let lone = npm_shim(&tmp.path().join("bin"), "ngserver");
|
||||
let cfg = configured(&lone.to_string_lossy(), &Settings::default());
|
||||
assert!(cfg.launch_error.is_some_and(|m| m.contains("@angular/language-server")));
|
||||
assert_eq!(cfg.args, ["--stdio"]);
|
||||
let cfg = configured(&tmp.path().join("nowhere/ngserver").to_string_lossy(), &Settings::default());
|
||||
assert_eq!((cfg.launch_error, cfg.args), (None, vec!["--stdio".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_java_picks_an_older_jdk() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Vue Language Server (Volar 3): the TypeScript it loads as a library, and the
|
||||
//! `@vue/typescript-plugin` that vtsls' tsserver hosts for it (hybrid mode).
|
||||
|
||||
use crate::npm::{find_command, package_dir};
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -14,38 +15,6 @@ pub(crate) fn has_ts_api(lib: &Path) -> bool {
|
||||
lib.join("typescript.js").is_file()
|
||||
}
|
||||
|
||||
/// `command` as given (a path) or found on `path`, npm shims included.
|
||||
fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
let p = Path::new(command);
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
|
||||
std::env::split_paths(path)
|
||||
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
|
||||
.find(|c| c.is_file())
|
||||
}
|
||||
|
||||
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
|
||||
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
|
||||
/// Unix global `<prefix>/bin` or a symlink into the package.
|
||||
fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
let dir = bin.parent()?;
|
||||
let mut candidates = vec![dir.join("node_modules").join(package)];
|
||||
if dir.file_name() == Some(OsStr::new(".bin"))
|
||||
&& let Some(node_modules) = dir.parent()
|
||||
{
|
||||
candidates.push(node_modules.join(package));
|
||||
}
|
||||
if let Ok(real) = dunce::canonicalize(bin) {
|
||||
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
|
||||
}
|
||||
if let Some(prefix) = dir.parent() {
|
||||
candidates.push(prefix.join("lib").join("node_modules").join(package));
|
||||
}
|
||||
candidates.into_iter().find(|c| c.join("package.json").is_file())
|
||||
}
|
||||
|
||||
/// `@vue/language-server`'s directory for the `vue-language-server` command.
|
||||
pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
package_dir(&find_command(command, path)?, PACKAGE)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -257,6 +257,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/vuejs/language-tools",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "angular-language-server",
|
||||
display: "Angular Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["ngserver"],
|
||||
// Brings the TypeScript and `@angular/language-service` it loads.
|
||||
method: Method::Npm { packages: &["@angular/language-server"] },
|
||||
version: V,
|
||||
homepage: "https://angular.dev/tools/language-service",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "graphql-lsp",
|
||||
display: "GraphQL Language Server",
|
||||
|
||||
@@ -72,6 +72,10 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert_eq!(ty.command, "ty");
|
||||
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
|
||||
assert!(ty.languages.iter().any(|language| language == "Python"));
|
||||
let angular = find(&list, "angular-language-server");
|
||||
assert_eq!(angular.command, "ngserver");
|
||||
assert_eq!(angular.install_method.as_deref(), Some("npm"));
|
||||
assert_eq!(angular.languages, ["HTML", "TypeScript"]);
|
||||
// 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>
|
||||
|
||||
@@ -7,6 +7,16 @@ indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "HTML"
|
||||
tree-sitter = "html"
|
||||
|
||||
# Angular projects only: component templates. First, so that hover, rename and
|
||||
# document symbols of templates come from it rather than plain HTML.
|
||||
[[language-servers]]
|
||||
name = "angular-language-server"
|
||||
command = "ngserver"
|
||||
args = ["--stdio", "--includeCompletionsWithSnippetText", "--includeAutomaticOptionalChainCompletions"]
|
||||
root-markers = ["angular.json", "node_modules/@angular/core"]
|
||||
require-root-marker = true
|
||||
install-hint = "npm i -g @angular/language-server"
|
||||
|
||||
[[language-servers]]
|
||||
name = "vscode-html-language-server"
|
||||
command = "vscode-html-language-server"
|
||||
|
||||
@@ -23,6 +23,17 @@ args = ["--stdio"]
|
||||
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
|
||||
install-hint = "npm i -g typescript@\"<7\" typescript-language-server"
|
||||
|
||||
# Angular projects only: templates inline in components (`template: ...`),
|
||||
# and their usages and renames in templates. Last: TypeScript's own hover,
|
||||
# definition and symbols come first.
|
||||
[[language-servers]]
|
||||
name = "angular-language-server"
|
||||
command = "ngserver"
|
||||
args = ["--stdio", "--includeCompletionsWithSnippetText", "--includeAutomaticOptionalChainCompletions"]
|
||||
root-markers = ["angular.json", "node_modules/@angular/core"]
|
||||
require-root-marker = true
|
||||
install-hint = "npm i -g @angular/language-server"
|
||||
|
||||
[debugger]
|
||||
adapter = "js-debug"
|
||||
command = "js-debug-adapter"
|
||||
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -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,8 +11,12 @@ use tauri::{State, Window};
|
||||
/// Detected configs followed by user-defined ones (user ids win on conflict).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn run_configs(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<RunConfig>> {
|
||||
ide_host::ops::run::configs(&state.host, window.label())
|
||||
pub async fn run_configs(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<RunConfig>> {
|
||||
// Detection reads build files (and Spring Boot sources): off the command thread.
|
||||
let (host, label) = (state.host.clone(), window.label().to_owned());
|
||||
tauri::async_runtime::spawn_blocking(move || ide_host::ops::run::configs(&host, &label))
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -11,10 +11,30 @@ 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: a file inside a local project
|
||||
/// open in some window goes to that window, the others to the LightEdit window (this one,
|
||||
/// another, or a new one from a remote project window). Returns the files this window opens
|
||||
/// itself, in LightEdit.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_files(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
files: Vec<PathBuf>,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
Ok(windows::open_files_window(&app, window.label(), files))
|
||||
}
|
||||
|
||||
/// [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
@@ -94,7 +114,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(),
|
||||
|
||||
@@ -13,7 +13,10 @@ mod state;
|
||||
mod theme_frame;
|
||||
mod windows;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use state::AppState;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tauri::{Emitter, Manager};
|
||||
use windows::WindowsState;
|
||||
|
||||
@@ -74,6 +77,9 @@ pub fn run() {
|
||||
#[cfg(debug_assertions)]
|
||||
let app = app.plugin(tauri_plugin_mcp_bridge::Builder::new().bind_address("127.0.0.1").build());
|
||||
|
||||
// Paths macOS asked to open (Finder's Open With, the Dock) before setup ran: the first window takes them.
|
||||
let early_opens: Arc<Mutex<Option<Vec<PathBuf>>>> = Arc::default();
|
||||
let setup_opens = early_opens.clone();
|
||||
app.invoke_handler(builder.invoke_handler())
|
||||
.setup(move |app| {
|
||||
builder.mount_events(app);
|
||||
@@ -82,13 +88,16 @@ 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());
|
||||
app.manage(state);
|
||||
app.manage(windows);
|
||||
app.manage(menu_state);
|
||||
if let Some(paths) = setup_opens.lock().take() {
|
||||
windows::open_paths_at_launch(app.handle(), paths);
|
||||
}
|
||||
app.on_menu_event(on_menu_event);
|
||||
windows::create_main_window(app.handle())?;
|
||||
Ok(())
|
||||
@@ -115,7 +124,18 @@ pub fn run() {
|
||||
})
|
||||
.build(context)
|
||||
.expect("error while running OpenIDEA")
|
||||
.run(|app, event| {
|
||||
.run(move |app, event| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Opened { urls } = &event {
|
||||
let paths = windows::opened_paths(urls);
|
||||
if app.try_state::<WindowsState>().is_some() {
|
||||
windows::open_paths(app, paths);
|
||||
} else {
|
||||
early_opens.lock().get_or_insert_default().extend(paths);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = &early_opens;
|
||||
// Quit after installing an update (`app_install_update`): relaunch.
|
||||
if let tauri::RunEvent::Exit = event
|
||||
&& app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested())
|
||||
|
||||
+162
-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,8 @@ 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("editor.contextInfo", "Context Info"),
|
||||
act("code.showIntentions", "Show Context Actions"),
|
||||
act("code.generate", "Generate…"),
|
||||
act("code.overrideMethods", "Override Methods…"),
|
||||
@@ -445,9 +450,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 +465,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 +479,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 +537,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 +567,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 +585,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 +612,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 +629,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 +639,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 +680,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 +749,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 +781,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 +1290,7 @@ mod tests {
|
||||
"app.about",
|
||||
"app.quit",
|
||||
"file.openProject",
|
||||
"file.openFile",
|
||||
"file.openInNewWindow",
|
||||
"file.closeProject",
|
||||
"file.save",
|
||||
@@ -1404,6 +1482,10 @@ mod tests {
|
||||
"toolwindow.closeContent",
|
||||
"toolwindow.jumpToLast",
|
||||
"toolwindow.focusEditor",
|
||||
"toolwindow.resizeLeft",
|
||||
"toolwindow.resizeRight",
|
||||
"toolwindow.resizeUp",
|
||||
"toolwindow.resizeDown",
|
||||
]
|
||||
.contains(id)
|
||||
}));
|
||||
@@ -1436,6 +1518,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);
|
||||
|
||||
+439
-36
@@ -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.
|
||||
@@ -74,6 +77,17 @@ impl WindowsState {
|
||||
self.launches.lock().remove(label)
|
||||
}
|
||||
|
||||
/// Adds `files` to `label`'s pending launch, so files sent before its frontend took the last batch aren't lost.
|
||||
pub fn add_files(&self, label: &str, files: Vec<PathBuf>) {
|
||||
let mut launches = self.launches.lock();
|
||||
let launch = launches.entry(label.to_owned()).or_default();
|
||||
launch.files.extend(files.into_iter().map(Into::into));
|
||||
}
|
||||
|
||||
fn pending(&self, label: &str) -> Option<Launch> {
|
||||
self.launches.lock().get(label).cloned()
|
||||
}
|
||||
|
||||
pub fn focused(&self, label: &str) {
|
||||
*self.last_focused.lock() = Some(label.to_owned());
|
||||
}
|
||||
@@ -189,12 +203,15 @@ 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)
|
||||
})
|
||||
}
|
||||
|
||||
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())
|
||||
/// 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>) {
|
||||
app.state::<WindowsState>().add_files(window.label(), files);
|
||||
let _ = app.emit_to(window.label(), LAUNCH_EVENT, ());
|
||||
focus(window);
|
||||
}
|
||||
|
||||
/// The focused window, else the last focused, else any.
|
||||
@@ -282,8 +299,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 +337,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,20 +361,40 @@ 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 window `caller` (File | Open File, a drop on the Welcome
|
||||
/// screen), routed like [`open_paths`]; returns the files `caller` opens itself.
|
||||
pub fn open_files_window(app: &AppHandle, caller: &str, files: Vec<PathBuf>) -> Vec<ide_core::IpcPath> {
|
||||
let files = files.into_iter().map(|f| dunce::canonicalize(&f).unwrap_or(f)).collect();
|
||||
let (steps, here) = plan_open_files(caller, files, &window_holds(app, Some(caller)));
|
||||
run_open(app, steps);
|
||||
here.into_iter().map(Into::into).collect()
|
||||
}
|
||||
|
||||
/// [`open_project_window`] for folder `path` on the host of SSH configuration
|
||||
/// `ssh_config` (Remote Development).
|
||||
pub fn open_remote_window(app: &AppHandle, ssh_config: &str, path: &str, new_window: bool) -> IdeResult<OpenOutcome> {
|
||||
@@ -366,35 +414,231 @@ 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.
|
||||
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),
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot open {}: {e}", path.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(w) = find_project_window(app, &root) {
|
||||
focus(&w);
|
||||
return;
|
||||
/// What a window holds, for routing paths opened from outside (command line, Finder).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Holds {
|
||||
/// Nothing yet (Welcome screen): free to take a launch.
|
||||
Nothing,
|
||||
LightEdit,
|
||||
Project(PathBuf),
|
||||
/// A remote project.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What window `label` holds: its open project, else what its pending launch is about to open.
|
||||
fn holds(app: &AppHandle, label: &str) -> Holds {
|
||||
let state = app.try_state::<AppState>();
|
||||
if let Some(project) = state.as_ref().and_then(|s| s.project(label).ok()) {
|
||||
return if project.light { Holds::LightEdit } else { Holds::Project(project.root.clone()) };
|
||||
}
|
||||
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()))
|
||||
});
|
||||
match free {
|
||||
Some(w) => {
|
||||
app.state::<WindowsState>()
|
||||
.set_launch(w.label(), Launch { project: Some(root.into()), ..Default::default() });
|
||||
let _ = app.emit_to(w.label(), LAUNCH_EVENT, ());
|
||||
focus(&w);
|
||||
if state.is_some_and(|s| s.remote_dev.get(label).is_some()) {
|
||||
return Holds::Other;
|
||||
}
|
||||
pending_holds(app.state::<WindowsState>().pending(label).as_ref())
|
||||
}
|
||||
|
||||
fn pending_holds(launch: Option<&Launch>) -> Holds {
|
||||
match launch {
|
||||
Some(Launch { project: Some(root), .. }) => Holds::Project(root.to_path_buf()),
|
||||
Some(Launch { remote: Some(_), .. }) => Holds::Other,
|
||||
Some(l) if !l.files.is_empty() => Holds::LightEdit,
|
||||
_ => Holds::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of opening paths from outside; see [`plan_open`].
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum OpenStep {
|
||||
/// The window already has the folder open.
|
||||
Focus(String),
|
||||
/// Files open in this window: in its project, or join its LightEdit session.
|
||||
Files(String, Vec<PathBuf>),
|
||||
/// A free window opens this.
|
||||
Launch(String, Launch),
|
||||
/// A new window opens the project folder or (without one) the files in LightEdit.
|
||||
New(Option<PathBuf>, Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// Where a file inside a project goes: a window with it open, or the step opening it.
|
||||
enum ProjectTarget {
|
||||
Window(String),
|
||||
Step(usize),
|
||||
}
|
||||
|
||||
/// Routes canonical `paths` (with whether each is a folder) over `windows` (the preferred
|
||||
/// free one first). A folder focuses the window that has it open, else takes a free window,
|
||||
/// else a new one. A file inside a local project being opened (the deepest root if nested)
|
||||
/// opens in that project's window; the others all join the LightEdit window, else a free
|
||||
/// window or a new one switches to LightEdit for them.
|
||||
pub fn plan_open(paths: Vec<(PathBuf, bool)>, windows: &[(String, Holds)]) -> Vec<OpenStep> {
|
||||
let mut free = windows.iter().filter(|(_, h)| *h == Holds::Nothing).map(|(l, _)| l.clone());
|
||||
let (mut dirs, mut files) = (Vec::new(), Vec::new());
|
||||
for (path, is_dir) in paths {
|
||||
let list = if is_dir { &mut dirs } else { &mut files };
|
||||
if !list.contains(&path) {
|
||||
list.push(path);
|
||||
}
|
||||
None => spawn_window(app, Some(root)),
|
||||
}
|
||||
let mut steps = Vec::new();
|
||||
let mut roots: Vec<(PathBuf, ProjectTarget)> = windows
|
||||
.iter()
|
||||
.filter_map(|(label, h)| match h {
|
||||
Holds::Project(root) => Some((root.clone(), ProjectTarget::Window(label.clone()))),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for dir in dirs {
|
||||
if let Some((label, _)) = windows.iter().find(|(_, h)| matches!(h, Holds::Project(root) if *root == dir)) {
|
||||
steps.push(OpenStep::Focus(label.clone()));
|
||||
continue;
|
||||
}
|
||||
roots.push((dir.clone(), ProjectTarget::Step(steps.len())));
|
||||
steps.push(match free.next() {
|
||||
Some(label) => OpenStep::Launch(label, path_launch_of(Some(dir), Vec::new())),
|
||||
None => OpenStep::New(Some(dir), Vec::new()),
|
||||
});
|
||||
}
|
||||
let mut in_windows: Vec<(String, Vec<PathBuf>)> = Vec::new();
|
||||
let mut loose = Vec::new();
|
||||
for file in files {
|
||||
let deepest =
|
||||
roots.iter().filter(|(root, _)| file.starts_with(root)).max_by_key(|(root, _)| root.components().count());
|
||||
match deepest.map(|(_, target)| target) {
|
||||
Some(ProjectTarget::Window(label)) => match in_windows.iter_mut().find(|(l, _)| l == label) {
|
||||
Some((_, list)) => list.push(file),
|
||||
None => in_windows.push((label.clone(), vec![file])),
|
||||
},
|
||||
Some(ProjectTarget::Step(i)) => match &mut steps[*i] {
|
||||
OpenStep::Launch(_, launch) => launch.files.push(file.into()),
|
||||
OpenStep::New(_, list) => list.push(file),
|
||||
OpenStep::Focus(_) | OpenStep::Files(..) => unreachable!("folders opened by the plan launch or open"),
|
||||
},
|
||||
None => loose.push(file),
|
||||
}
|
||||
}
|
||||
steps.extend(in_windows.into_iter().map(|(label, files)| OpenStep::Files(label, files)));
|
||||
if !loose.is_empty() {
|
||||
let light = windows.iter().find(|(_, h)| *h == Holds::LightEdit).map(|(l, _)| l.clone());
|
||||
steps.push(match (light, free.next()) {
|
||||
(Some(label), _) => OpenStep::Files(label, loose),
|
||||
(None, Some(label)) => OpenStep::Launch(label, path_launch_of(None, loose)),
|
||||
(None, None) => OpenStep::New(None, loose),
|
||||
});
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
fn path_launch_of(project: Option<PathBuf>, files: Vec<PathBuf>) -> Launch {
|
||||
Launch {
|
||||
project: project.map(Into::into),
|
||||
files: files.into_iter().map(Into::into).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`plan_open`] for loose `files` asked for by window `caller` (listed first in `windows`):
|
||||
/// no other free window takes them. Returns the steps for other windows and the files
|
||||
/// `caller` opens itself (in its LightEdit session, or turning into one).
|
||||
pub fn plan_open_files(
|
||||
caller: &str,
|
||||
files: Vec<PathBuf>,
|
||||
windows: &[(String, Holds)],
|
||||
) -> (Vec<OpenStep>, Vec<PathBuf>) {
|
||||
let windows: Vec<_> = windows.iter().filter(|(l, h)| l == caller || *h != Holds::Nothing).cloned().collect();
|
||||
let mut here = Vec::new();
|
||||
let mut steps = Vec::new();
|
||||
for step in plan_open(files.into_iter().map(|f| (f, false)).collect(), &windows) {
|
||||
match step {
|
||||
OpenStep::Files(label, files) if label == caller => here.extend(files),
|
||||
OpenStep::Launch(label, launch) if label == caller => here.extend(launch.files.into_iter().map(|f| f.0)),
|
||||
step => steps.push(step),
|
||||
}
|
||||
}
|
||||
(steps, here)
|
||||
}
|
||||
|
||||
/// Canonical existing `paths` with whether each is a folder; the others are logged and dropped.
|
||||
fn resolve(paths: Vec<PathBuf>) -> Vec<(PathBuf, bool)> {
|
||||
paths
|
||||
.into_iter()
|
||||
.filter_map(|path| match dunce::canonicalize(&path) {
|
||||
Ok(p) => {
|
||||
let is_dir = p.is_dir();
|
||||
Some((p, is_dir))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot open {}: {e}", path.display());
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Opens `path` from the command line / a second instance; see [`open_paths`].
|
||||
pub fn open_path(app: &AppHandle, path: &Path) {
|
||||
open_paths(app, vec![path.to_path_buf()]);
|
||||
}
|
||||
|
||||
/// Opens paths from outside the app (a second instance, Finder's Open With, the Dock):
|
||||
/// see [`plan_open`]; the focused window is the preferred free one.
|
||||
pub fn open_paths(app: &AppHandle, paths: Vec<PathBuf>) {
|
||||
let preferred = target_window(app).map(|w| w.label().to_owned());
|
||||
run_open(app, plan_open(resolve(paths), &window_holds(app, preferred.as_deref())));
|
||||
}
|
||||
|
||||
/// What each window holds, `preferred` first.
|
||||
fn window_holds(app: &AppHandle, preferred: Option<&str>) -> Vec<(String, Holds)> {
|
||||
let mut labels = project_window_labels(app);
|
||||
if let Some(i) = preferred.and_then(|p| labels.iter().position(|l| l == p)) {
|
||||
let first = labels.remove(i);
|
||||
labels.insert(0, first);
|
||||
}
|
||||
labels.into_iter().map(|l| (l.clone(), holds(app, &l))).collect()
|
||||
}
|
||||
|
||||
/// [`open_paths`] while the app is starting, before the `main` window exists: it takes them as its launch.
|
||||
pub fn open_paths_at_launch(app: &AppHandle, paths: Vec<PathBuf>) {
|
||||
let main = pending_holds(app.state::<WindowsState>().pending(MAIN).as_ref());
|
||||
run_open(app, plan_open(resolve(paths), &[(MAIN.to_owned(), main)]));
|
||||
}
|
||||
|
||||
fn run_open(app: &AppHandle, steps: Vec<OpenStep>) {
|
||||
let windows = app.state::<WindowsState>();
|
||||
for step in steps {
|
||||
match step {
|
||||
OpenStep::Focus(label) => {
|
||||
if let Some(w) = app.get_webview_window(&label) {
|
||||
focus(&w);
|
||||
}
|
||||
}
|
||||
OpenStep::Files(label, files) => match app.get_webview_window(&label) {
|
||||
Some(w) => send_files(app, &w, files),
|
||||
None => windows.add_files(&label, files),
|
||||
},
|
||||
OpenStep::Launch(label, launch) => {
|
||||
windows.set_launch(&label, launch);
|
||||
if let Some(w) = app.get_webview_window(&label) {
|
||||
let _ = app.emit_to(&label, LAUNCH_EVENT, ());
|
||||
focus(&w);
|
||||
}
|
||||
}
|
||||
OpenStep::New(project, files) => spawn_window_with(app, project, files),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Local files and folders of the URLs macOS asks the app to open (Finder's Open With, the Dock).
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn opened_paths(urls: &[tauri::Url]) -> Vec<PathBuf> {
|
||||
urls.iter().filter_map(|u| u.to_file_path().ok()).collect()
|
||||
}
|
||||
|
||||
/// 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 +812,165 @@ 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()]));
|
||||
}
|
||||
|
||||
fn p(s: &str) -> PathBuf {
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
fn w(label: &str, holds: Holds) -> (String, Holds) {
|
||||
(label.to_owned(), holds)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_at_launch_gives_the_first_window_files_or_folder() {
|
||||
let main = [w("main", Holds::Nothing)];
|
||||
let files = plan_open(vec![(p("/x/a.txt"), false), (p("/y/b.rs"), false)], &main);
|
||||
assert_eq!(files, [OpenStep::Launch("main".into(), path_launch_of(None, vec![p("/x/a.txt"), p("/y/b.rs")]))]);
|
||||
let dir = plan_open(vec![(p("/proj"), true)], &main);
|
||||
assert_eq!(dir, [OpenStep::Launch("main".into(), path_launch_of(Some(p("/proj")), Vec::new()))]);
|
||||
// Folder and files: the folder takes the first window, the files a new LightEdit one.
|
||||
let both = plan_open(vec![(p("/x/a.txt"), false), (p("/proj"), true)], &main);
|
||||
assert_eq!(
|
||||
both,
|
||||
[
|
||||
OpenStep::Launch("main".into(), path_launch_of(Some(p("/proj")), Vec::new())),
|
||||
OpenStep::New(None, vec![p("/x/a.txt")]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_opened_at_launch_join_files_from_the_command_line() {
|
||||
let cli = path_launch_of(None, vec![p("/x/a.txt")]);
|
||||
let main = [w("main", pending_holds(Some(&cli)))];
|
||||
assert_eq!(
|
||||
plan_open(vec![(p("/x/b.txt"), false)], &main),
|
||||
[OpenStep::Files("main".into(), vec![p("/x/b.txt")])]
|
||||
);
|
||||
let st = WindowsState::default();
|
||||
st.set_launch("main", cli);
|
||||
st.add_files("main", vec![p("/x/b.txt")]);
|
||||
assert_eq!(st.take_launch("main").unwrap().files, [p("/x/a.txt"), p("/x/b.txt")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_inside_an_open_project_open_in_its_window_and_the_others_in_light_edit() {
|
||||
let windows = [
|
||||
w("main", Holds::Project(p("/proj"))),
|
||||
w("project-1", Holds::LightEdit),
|
||||
w("project-2", Holds::Project(p("/proj/sub"))),
|
||||
];
|
||||
let steps = plan_open(
|
||||
vec![
|
||||
(p("/proj/src/a.rs"), false),
|
||||
(p("/x/b.txt"), false),
|
||||
(p("/proj/sub/c.rs"), false),
|
||||
(p("/projects/d.rs"), false),
|
||||
(p("/proj/e.rs"), false),
|
||||
],
|
||||
&windows,
|
||||
);
|
||||
assert_eq!(
|
||||
steps,
|
||||
[
|
||||
OpenStep::Files("main".into(), vec![p("/proj/src/a.rs"), p("/proj/e.rs")]),
|
||||
// The deepest root wins.
|
||||
OpenStep::Files("project-2".into(), vec![p("/proj/sub/c.rs")]),
|
||||
// `/projects` is not inside `/proj`.
|
||||
OpenStep::Files("project-1".into(), vec![p("/x/b.txt"), p("/projects/d.rs")]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_inside_a_folder_being_opened_open_in_its_project() {
|
||||
let opening = path_launch_of(Some(p("/a")), Vec::new());
|
||||
let windows = [w("main", pending_holds(Some(&opening))), w("project-1", Holds::Nothing)];
|
||||
let steps = plan_open(vec![(p("/a/x.rs"), false), (p("/b"), true), (p("/b/y.rs"), false)], &windows);
|
||||
assert_eq!(
|
||||
steps,
|
||||
[
|
||||
OpenStep::Launch("project-1".into(), path_launch_of(Some(p("/b")), vec![p("/b/y.rs")])),
|
||||
OpenStep::Files("main".into(), vec![p("/a/x.rs")]),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
plan_open(vec![(p("/c"), true), (p("/c/z.rs"), false)], &[]),
|
||||
[OpenStep::New(Some(p("/c")), vec![p("/c/z.rs")])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_projects_do_not_take_local_files() {
|
||||
let windows = [w("main", Holds::Other), w("project-1", Holds::LightEdit)];
|
||||
assert_eq!(
|
||||
plan_open(vec![(p("/home/me/a.rs"), false)], &windows),
|
||||
[OpenStep::Files("project-1".into(), vec![p("/home/me/a.rs")])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_opened_from_a_window_go_to_their_project_window_else_light_edit() {
|
||||
let windows = [
|
||||
w("main", Holds::Nothing),
|
||||
w("project-1", Holds::Project(p("/proj"))),
|
||||
w("project-2", Holds::Nothing),
|
||||
w("project-3", Holds::Other),
|
||||
];
|
||||
let files = vec![p("/proj/src/a.rs"), p("/x/b.txt")];
|
||||
// The Welcome window turns into LightEdit itself; another free window doesn't take the files.
|
||||
let (steps, here) = plan_open_files("main", files.clone(), &windows);
|
||||
assert_eq!(steps, [OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")])]);
|
||||
assert_eq!(here, [p("/x/b.txt")]);
|
||||
// A LightEdit window keeps loose files, even with another one open.
|
||||
let light =
|
||||
[w("main", Holds::LightEdit), w("project-1", Holds::Project(p("/proj"))), w("project-2", Holds::LightEdit)];
|
||||
let (steps, here) = plan_open_files("main", files.clone(), &light);
|
||||
assert_eq!(steps, [OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")])]);
|
||||
assert_eq!(here, [p("/x/b.txt")]);
|
||||
// An existing LightEdit window takes them from a Welcome window.
|
||||
let others = [w("main", Holds::Nothing), w("project-2", Holds::LightEdit)];
|
||||
let (steps, here) = plan_open_files("main", vec![p("/x/b.txt")], &others);
|
||||
assert_eq!((steps, here), (vec![OpenStep::Files("project-2".into(), vec![p("/x/b.txt")])], vec![]));
|
||||
// A remote project window gets a new LightEdit window, never a free one or its own.
|
||||
let (steps, here) = plan_open_files("project-3", files, &windows);
|
||||
assert_eq!(
|
||||
steps,
|
||||
[OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")]), OpenStep::New(None, vec![p("/x/b.txt")])]
|
||||
);
|
||||
assert!(here.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_opened_while_running_take_a_free_window_else_a_new_one() {
|
||||
let free = [w("main", Holds::Project(p("/proj"))), w("project-1", Holds::Nothing)];
|
||||
assert_eq!(
|
||||
plan_open(vec![(p("/x/a.txt"), false)], &free),
|
||||
[OpenStep::Launch("project-1".into(), path_launch_of(None, vec![p("/x/a.txt")]))]
|
||||
);
|
||||
let busy = [w("main", Holds::Project(p("/proj"))), w("project-1", Holds::Other)];
|
||||
assert_eq!(plan_open(vec![(p("/x/a.txt"), false)], &busy), [OpenStep::New(None, vec![p("/x/a.txt")])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_opened_while_running_focus_their_window_else_open_as_projects() {
|
||||
let windows = [w("main", Holds::LightEdit), w("project-1", Holds::Project(p("/a")))];
|
||||
let steps = plan_open(vec![(p("/a"), true), (p("/b"), true), (p("/b"), true)], &windows);
|
||||
assert_eq!(steps, [OpenStep::Focus("project-1".into()), OpenStep::New(Some(p("/b")), Vec::new())]);
|
||||
// A window still opening the folder (pending launch) counts as having it.
|
||||
let opening = path_launch_of(Some(p("/a")), Vec::new());
|
||||
let windows = [w("project-2", pending_holds(Some(&opening)))];
|
||||
assert_eq!(plan_open(vec![(p("/a"), true)], &windows), [OpenStep::Focus("project-2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_are_taken_once() {
|
||||
let st = WindowsState::default();
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"bundle": {
|
||||
"fileAssociations": [
|
||||
{
|
||||
"name": "Text and Source Code",
|
||||
"ext": [],
|
||||
"contentTypes": [
|
||||
"public.text",
|
||||
"public.plain-text",
|
||||
"public.source-code",
|
||||
"public.script",
|
||||
"public.shell-script",
|
||||
"public.json",
|
||||
"public.xml",
|
||||
"public.yaml",
|
||||
"public.python-script"
|
||||
],
|
||||
"role": "Editor",
|
||||
"rank": "Alternate"
|
||||
},
|
||||
{
|
||||
"name": "Source Code",
|
||||
"ext": [
|
||||
"rs",
|
||||
"go",
|
||||
"py",
|
||||
"pyi",
|
||||
"pyw",
|
||||
"cjs",
|
||||
"scss",
|
||||
"less",
|
||||
"rst",
|
||||
"tex",
|
||||
"ps1",
|
||||
"bat",
|
||||
"fish",
|
||||
"kt",
|
||||
"kts",
|
||||
"gradle",
|
||||
"groovy",
|
||||
"scala",
|
||||
"sc",
|
||||
"ts",
|
||||
"mts",
|
||||
"cts",
|
||||
"jsx",
|
||||
"vue",
|
||||
"svelte",
|
||||
"dart",
|
||||
"cs",
|
||||
"fs",
|
||||
"fsx",
|
||||
"hs",
|
||||
"ex",
|
||||
"exs",
|
||||
"erl",
|
||||
"clj",
|
||||
"cljs",
|
||||
"edn",
|
||||
"lua",
|
||||
"zig",
|
||||
"nix",
|
||||
"jl",
|
||||
"ml",
|
||||
"mli",
|
||||
"tf",
|
||||
"hcl",
|
||||
"proto",
|
||||
"graphql",
|
||||
"gql",
|
||||
"sql",
|
||||
"http",
|
||||
"properties",
|
||||
"ini",
|
||||
"cfg",
|
||||
"conf",
|
||||
"env",
|
||||
"lock",
|
||||
"log",
|
||||
"diff",
|
||||
"patch",
|
||||
"gitignore",
|
||||
"dockerignore",
|
||||
"editorconfig",
|
||||
"dockerfile"
|
||||
],
|
||||
"role": "Editor",
|
||||
"rank": "Alternate"
|
||||
},
|
||||
{
|
||||
"name": "Folder",
|
||||
"ext": [],
|
||||
"contentTypes": ["public.folder"],
|
||||
"role": "Viewer",
|
||||
"rank": "Alternate"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+62
-2
@@ -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,
|
||||
@@ -578,8 +583,16 @@ 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: a file inside a local project
|
||||
* open in some window goes to that window, the others to the LightEdit window (this one,
|
||||
* another, or a new one from a remote project window). Returns the files this window opens
|
||||
* itself, in LightEdit.
|
||||
*/
|
||||
windowOpenFiles: (files: string[]) => typedError<IpcPath[], 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.
|
||||
@@ -600,6 +613,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. */
|
||||
@@ -1641,6 +1659,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,
|
||||
@@ -2422,7 +2447,13 @@ export type EditorAppearanceSettings = {
|
||||
caretBlinking?: boolean,
|
||||
/** Blink period in ms. */
|
||||
caretBlinkPeriod?: number,
|
||||
/** Fade the caret in and out instead of toggling it; rounds its corners. */
|
||||
smoothCaretBlinking?: boolean,
|
||||
blockCaret?: boolean,
|
||||
/** Animate the caret between positions when it is moved. */
|
||||
smoothCaretMovement?: boolean,
|
||||
/** Smooth caret movement curve: `snappy` | `gliding`. */
|
||||
caretMovementStyle?: string,
|
||||
lineNumbers?: boolean,
|
||||
methodSeparators?: boolean,
|
||||
/** Sub-options of `editor.showWhitespace`. */
|
||||
@@ -2914,6 +2945,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 = {
|
||||
@@ -3544,6 +3586,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. */
|
||||
@@ -5037,6 +5084,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. */
|
||||
@@ -5609,10 +5662,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). */
|
||||
@@ -5637,6 +5696,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,40 @@ 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 { enclosingHeaders } from "./cm/stickyScroll";
|
||||
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 +121,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 +168,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 +210,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 +238,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 +299,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 +315,82 @@ 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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* View › Context Info (⌃⇧Q / Alt+Q): the declaration lines around the caret
|
||||
* (class, method, block headers), most useful when they are scrolled away.
|
||||
*/
|
||||
function showContextInfo(view: EditorView) {
|
||||
const state = view.state;
|
||||
const line = state.doc.lineAt(state.selection.main.head).number;
|
||||
const headers = enclosingHeaders(state, line);
|
||||
const text = headers.map((n) => state.doc.line(n).text.trimEnd()).join("\n");
|
||||
void executeAction("editor.showHint", { text: text || "No context information here" });
|
||||
}
|
||||
|
||||
/** 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 +435,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 +446,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 +467,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 +502,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 +550,65 @@ 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("editor.contextInfo", "Context Info", (v) => showContextInfo(v), {
|
||||
category: "View",
|
||||
keywords: ["enclosing method", "enclosing class", "where am I"],
|
||||
}),
|
||||
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 +626,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 +660,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] : []);
|
||||
},
|
||||
@@ -558,6 +782,8 @@ export function registerEditorActions(): () => void {
|
||||
category: "Navigate",
|
||||
keywords: ["breadcrumbs"],
|
||||
when: "projectOpen",
|
||||
// ⌘↑ / ⌘↓ inside a popup (Search Everywhere's previous / next group) stay with it.
|
||||
keyWhen: "!popupOpen",
|
||||
run: () => {
|
||||
if (activeSlot()) return openNavBarPopup();
|
||||
// No editor: the status bar breadcrumbs (StatusItems › Breadcrumbs) take focus.
|
||||
@@ -622,7 +848,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 +871,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"),
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
selectAllOccurrences,
|
||||
unselectOccurrence,
|
||||
} from "./editing";
|
||||
import { pasteReindentFilter } from "./prefs";
|
||||
import { caretExtension, pasteReindentFilter } from "./prefs";
|
||||
import { closesStringAt, skipClosingQuote } from "./smartKeys";
|
||||
import {
|
||||
collapseAllEffects,
|
||||
@@ -27,6 +27,7 @@ import { nearestMark, unfoldAround } from "./lanes";
|
||||
import { lineRangeSelection } from "./gutterDrag";
|
||||
import { matchBraceTarget } from "./caretCommands";
|
||||
import { overwriteField, toggleOverwrite } from "./overwrite";
|
||||
import { validateEditorExtras } from "@/platform/editorSettings";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
@@ -329,3 +330,32 @@ describe("overwrite mode", () => {
|
||||
expect(show(v)).toBe("abXYZ|\nx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("smooth caret", () => {
|
||||
const caret = (appearance: object) => caretExtension(validateEditorExtras({ appearance }));
|
||||
|
||||
it("marks the editor for smooth blinking and the chosen movement curve", () => {
|
||||
const v = make(
|
||||
"ab|c",
|
||||
caret({ smoothCaretBlinking: true, smoothCaretMovement: true, caretMovementStyle: "gliding" }),
|
||||
);
|
||||
expect(v.dom.classList.contains("cm-openidea-smoothCaretBlink")).toBe(true);
|
||||
expect(v.dom.classList.contains("cm-openidea-caretMotion-gliding")).toBe(true);
|
||||
const plain = make("ab|c", caret({ smoothCaretBlinking: false, smoothCaretMovement: false }));
|
||||
expect(plain.dom.className).not.toMatch(/smoothCaretBlink|caretMotion/);
|
||||
});
|
||||
|
||||
it("glides selection-only moves and puts the caret in place at once when typing", () => {
|
||||
const v = make("ab|c", caret({ smoothCaretMovement: true }));
|
||||
const layer = v.scrollDOM.querySelector(".cm-cursorLayer")!;
|
||||
const flush = () => (v as unknown as { measure(): void }).measure();
|
||||
// jsdom has no layout: every caret is on screen.
|
||||
v.coordsAtPos = () => ({ left: 0, right: 0, top: 0, bottom: 10 });
|
||||
v.scrollDOM.getBoundingClientRect = () => new DOMRect(0, 0, 100, 100);
|
||||
v.dispatch({ selection: { anchor: 1 } });
|
||||
flush();
|
||||
expect(layer.classList.contains("cm-openidea-caretGlide")).toBe(true);
|
||||
v.dispatch({ changes: { from: 1, insert: "x" }, selection: { anchor: 2 } });
|
||||
expect(layer.classList.contains("cm-openidea-caretGlide")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -424,11 +451,58 @@ export interface PrefsOptions {
|
||||
commentStyle?: LineCommentStyle;
|
||||
}
|
||||
|
||||
function caretOnScreen(view: EditorView, pos: number): boolean {
|
||||
const c = view.coordsAtPos(pos);
|
||||
if (!c) return false;
|
||||
const r = view.scrollDOM.getBoundingClientRect();
|
||||
return c.top >= r.top && c.bottom <= r.bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use smooth caret movement. The cursor layer reuses its caret elements, so a
|
||||
* CSS transition on their position animates a move (VS Code's
|
||||
* `cursorSmoothCaretAnimation: "explicit"`). Only moves of the selection
|
||||
* alone glide; typing, edits, a changed number of carets, layout changes and
|
||||
* moves that scroll the editor put the caret in place at once.
|
||||
*/
|
||||
const caretGlide = ViewPlugin.fromClass(
|
||||
class {
|
||||
on = false;
|
||||
constructor(readonly view: EditorView) {}
|
||||
update(u: ViewUpdate) {
|
||||
const from = u.startState.selection;
|
||||
const to = u.state.selection;
|
||||
if (!u.selectionSet || u.docChanged || u.geometryChanged || from.ranges.length !== to.ranges.length) {
|
||||
this.set(false);
|
||||
return;
|
||||
}
|
||||
// Measured before the editor scrolls the new caret into view.
|
||||
u.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => caretOnScreen(view, from.main.head) && caretOnScreen(view, to.main.head),
|
||||
write: (on) => this.set(on),
|
||||
});
|
||||
}
|
||||
set(on: boolean) {
|
||||
if (on === this.on) return;
|
||||
this.on = on;
|
||||
this.view.scrollDOM.querySelector(":scope > .cm-cursorLayer")?.classList.toggle("cm-openidea-caretGlide", on);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export function caretExtension(prefs: EditorExtras): Extension {
|
||||
const a = prefs.appearance;
|
||||
const classes = [
|
||||
a.blockCaret && "cm-openidea-blockCaret",
|
||||
a.smoothCaretBlinking && "cm-openidea-smoothCaretBlink",
|
||||
a.smoothCaretMovement && `cm-openidea-caretMotion-${a.caretMovementStyle === "gliding" ? "gliding" : "snappy"}`,
|
||||
].filter(Boolean);
|
||||
return [
|
||||
// Before drawSelection: its measure request must run before the cursor layer redraws.
|
||||
a.smoothCaretMovement ? caretGlide : [],
|
||||
drawSelection({ cursorBlinkRate: a.caretBlinking ? Math.max(100, Math.min(5000, a.caretBlinkPeriod)) * 2 : 0 }),
|
||||
a.blockCaret ? EditorView.editorAttributes.of({ class: "cm-openidea-blockCaret" }) : [],
|
||||
classes.length ? EditorView.editorAttributes.of({ class: classes.join(" ") }) : [],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -441,17 +515,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 +553,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,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;
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 560 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача