дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
20
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f2cfdea8ca | ||
|
|
c7f75cb693 | ||
|
|
e0af8ccce1 | ||
|
|
af3ed649b7 | ||
|
|
aeb190ffda | ||
|
|
a28600c55a | ||
|
|
b35035f8d9 | ||
|
|
cfd2970531 | ||
|
|
11362a36f8 | ||
|
|
e43b0b81c7 | ||
|
|
0c9c51b0f5 | ||
|
|
7e6919010f | ||
|
|
e803d82202 | ||
|
|
a7c970a6db | ||
|
|
0184a9c395 | ||
|
|
4a15936acb | ||
|
|
811da13a76 | ||
|
|
1d383e608c | ||
|
|
2d7726cf53 | ||
|
|
eb67595e72 |
No files matched your search
Створено
@@ -4372,6 +4372,7 @@ dependencies = [
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"which",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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",
|
||||
@@ -705,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"),
|
||||
@@ -727,6 +781,11 @@ 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.openInOppositeGroup", "Open in Opposite Group"),
|
||||
act("editor.changeSplitOrientation", "Change Splitter Orientation"),
|
||||
act("editor.unsplitAll", "Unsplit All"),
|
||||
act("editor.nextSplitter", "Go to Next Splitter"),
|
||||
act("editor.prevSplitter", "Go to Previous Splitter"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
@@ -1234,6 +1293,7 @@ mod tests {
|
||||
"app.about",
|
||||
"app.quit",
|
||||
"file.openProject",
|
||||
"file.openFile",
|
||||
"file.openInNewWindow",
|
||||
"file.closeProject",
|
||||
"file.save",
|
||||
@@ -1425,6 +1485,10 @@ mod tests {
|
||||
"toolwindow.closeContent",
|
||||
"toolwindow.jumpToLast",
|
||||
"toolwindow.focusEditor",
|
||||
"toolwindow.resizeLeft",
|
||||
"toolwindow.resizeRight",
|
||||
"toolwindow.resizeUp",
|
||||
"toolwindow.resizeDown",
|
||||
]
|
||||
.contains(id)
|
||||
}));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -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. */
|
||||
@@ -2429,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`. */
|
||||
@@ -3562,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. */
|
||||
|
||||
@@ -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";
|
||||
@@ -37,16 +44,24 @@ import {
|
||||
collapseRecursively,
|
||||
expandAll,
|
||||
expandRecursively,
|
||||
collapseBlock,
|
||||
expandToLevelEffects,
|
||||
foldAtCaret,
|
||||
foldSelection,
|
||||
unfoldAtCaret,
|
||||
} from "./cm/folding";
|
||||
import { reverseLines, sortLines } from "./cm/lines";
|
||||
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";
|
||||
@@ -314,6 +329,68 @@ function completeCurrentStatement(view: EditorView, slot: EditorSlot) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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). */
|
||||
@@ -425,6 +502,12 @@ 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), {
|
||||
@@ -490,6 +573,42 @@ export function registerEditorActions(): () => void {
|
||||
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), {
|
||||
@@ -663,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.
|
||||
@@ -750,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",
|
||||
@@ -767,6 +904,30 @@ export function registerEditorActions(): () => void {
|
||||
when: "editorSplit",
|
||||
run: () => ctrl.unsplit(useTabs.getState().activePane),
|
||||
},
|
||||
{
|
||||
id: "editor.unsplitAll",
|
||||
title: "Unsplit All",
|
||||
category: "Window",
|
||||
when: "editorSplit",
|
||||
run: () => ctrl.unsplitAll(useTabs.getState().activePane),
|
||||
},
|
||||
{
|
||||
id: "editor.changeSplitOrientation",
|
||||
title: "Change Splitter Orientation",
|
||||
category: "Window",
|
||||
when: "editorSplit",
|
||||
run: () => ctrl.changeSplitOrientation(useTabs.getState().activePane),
|
||||
},
|
||||
{
|
||||
id: "editor.openInOppositeGroup",
|
||||
title: "Open in Opposite Group",
|
||||
category: "Window",
|
||||
when: TABS_WHEN,
|
||||
run: () => {
|
||||
const t = activePaneTab();
|
||||
if (t) ctrl.openInOpposite(t.paneId, t.tabId);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "editor.copyPath",
|
||||
title: "Copy Path",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,7 +3,15 @@
|
||||
* 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,
|
||||
@@ -15,6 +23,8 @@ import {
|
||||
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). */
|
||||
@@ -22,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[]>();
|
||||
@@ -44,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;
|
||||
@@ -81,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;
|
||||
}
|
||||
@@ -162,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.
|
||||
@@ -239,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 }));
|
||||
@@ -319,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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
@@ -451,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(" ") }) : [],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -301,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)),
|
||||
|
||||
@@ -8,6 +8,62 @@
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { BRACKET_COLORS } from "./rainbowBrackets";
|
||||
|
||||
/** The `--editor-*` locals of `findStyles`, for the `&` rule. */
|
||||
export const findLocals = {
|
||||
"--editor-search": "var(--bg-search-match, color-mix(in srgb, var(--warning) 30%, transparent))",
|
||||
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
|
||||
};
|
||||
|
||||
/** Find in file highlights (cm/find.ts), also for viewers with their own theme (diff). */
|
||||
export const findStyles = {
|
||||
".cm-openidea-findMatch": {
|
||||
backgroundColor: "var(--editor-search)",
|
||||
borderRadius: "2px",
|
||||
},
|
||||
".cm-openidea-findExcluded": {
|
||||
textDecoration: "line-through",
|
||||
textDecorationColor: "var(--fg-muted)",
|
||||
},
|
||||
".cm-openidea-findScope": {
|
||||
backgroundColor: "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
|
||||
},
|
||||
".cm-openidea-findMatch-current": {
|
||||
backgroundColor: "var(--editor-search-current)",
|
||||
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
|
||||
},
|
||||
};
|
||||
|
||||
/** The caret and Settings › Editor › General › Appearance caret options (`caretExtension`), also for viewers. */
|
||||
export const caretStyles = {
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
borderLeft: "2px solid var(--caret, var(--fg-strong))",
|
||||
marginLeft: "-1px",
|
||||
},
|
||||
// Use block caret (Settings › Editor › General › Appearance)
|
||||
"&.cm-openidea-blockCaret .cm-cursor": {
|
||||
borderLeft: "none",
|
||||
width: "1ch",
|
||||
marginLeft: "0",
|
||||
background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 55%, transparent)",
|
||||
},
|
||||
// Use smooth caret blinking: fade through CodeMirror's blink keyframes instead of stepping; rounded caret.
|
||||
"&.cm-openidea-smoothCaretBlink.cm-focused > .cm-scroller > .cm-cursorLayer": {
|
||||
animationTimingFunction: "cubic-bezier(0.7, 0, 0.3, 1)",
|
||||
},
|
||||
"&.cm-openidea-smoothCaretBlink .cm-cursor": { borderRadius: "1px" },
|
||||
"&.cm-openidea-smoothCaretBlink.cm-openidea-blockCaret .cm-cursor": { borderRadius: "2px" },
|
||||
// Use smooth caret movement: Snappy lands at once and settles, Gliding travels visibly.
|
||||
"&.cm-openidea-caretMotion-snappy": { "--openidea-caret-motion": "110ms cubic-bezier(0.16, 1, 0.3, 1)" },
|
||||
"&.cm-openidea-caretMotion-gliding": { "--openidea-caret-motion": "180ms cubic-bezier(0.45, 0, 0.25, 1)" },
|
||||
".cm-cursorLayer.cm-openidea-caretGlide > .cm-cursor": {
|
||||
transition:
|
||||
"left var(--openidea-caret-motion), top var(--openidea-caret-motion), width var(--openidea-caret-motion), height var(--openidea-caret-motion)",
|
||||
},
|
||||
"@media (prefers-reduced-motion: reduce)": {
|
||||
".cm-cursorLayer.cm-openidea-caretGlide > .cm-cursor": { transition: "none" },
|
||||
},
|
||||
};
|
||||
|
||||
export const openideaTheme = EditorView.theme({
|
||||
"&": {
|
||||
height: "100%",
|
||||
@@ -21,8 +77,7 @@ export const openideaTheme = EditorView.theme({
|
||||
"--editor-selection-inactive":
|
||||
"var(--bg-editor-selection-inactive, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
"--editor-indent-guide": "var(--border-indent-guide, var(--border))",
|
||||
"--editor-search": "var(--bg-search-match, color-mix(in srgb, var(--warning) 30%, transparent))",
|
||||
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
|
||||
...findLocals,
|
||||
"--editor-brace": "var(--bg-matched-brace, color-mix(in srgb, var(--accent) 22%, transparent))",
|
||||
"--editor-fold-chip": "var(--bg-fold-placeholder, color-mix(in srgb, var(--fg-muted) 14%, transparent))",
|
||||
},
|
||||
@@ -42,17 +97,7 @@ export const openideaTheme = EditorView.theme({
|
||||
caretColor: "var(--caret, var(--fg-strong))",
|
||||
},
|
||||
".cm-line": { padding: "0 16px 0 6px" },
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
borderLeft: "2px solid var(--caret, var(--fg-strong))",
|
||||
marginLeft: "-1px",
|
||||
},
|
||||
// Use block caret (Settings › Editor › General › Appearance)
|
||||
"&.cm-openidea-blockCaret .cm-cursor": {
|
||||
borderLeft: "none",
|
||||
width: "1ch",
|
||||
marginLeft: "0",
|
||||
background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 55%, transparent)",
|
||||
},
|
||||
...caretStyles,
|
||||
"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {
|
||||
fontVariantLigatures: "normal",
|
||||
},
|
||||
@@ -199,21 +244,7 @@ export const openideaTheme = EditorView.theme({
|
||||
},
|
||||
|
||||
// Find in file (cm/find.ts)
|
||||
".cm-openidea-findMatch": {
|
||||
backgroundColor: "var(--editor-search)",
|
||||
borderRadius: "2px",
|
||||
},
|
||||
".cm-openidea-findExcluded": {
|
||||
textDecoration: "line-through",
|
||||
textDecorationColor: "var(--fg-muted)",
|
||||
},
|
||||
".cm-openidea-findScope": {
|
||||
backgroundColor: "var(--editor-selection-inactive)",
|
||||
},
|
||||
".cm-openidea-findMatch-current": {
|
||||
backgroundColor: "var(--editor-search-current)",
|
||||
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
|
||||
},
|
||||
...findStyles,
|
||||
|
||||
// Overlays
|
||||
".cm-tooltip": {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorController, openFilePaths, useEditorStatus, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { useDocMeta } from "./model/document";
|
||||
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -65,6 +66,60 @@ describe("EditorController", () => {
|
||||
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts", "/p/b.ts"]);
|
||||
});
|
||||
|
||||
it("opens a copy of a tab in the opposite group, splitting when there is none", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
await ctrl.openFile("/p/b.ts", { focus: false });
|
||||
const paths = (paneId: string) => useTabs.getState().panes[paneId]!.tabs.map((t) => t.input.path);
|
||||
const first = useTabs.getState().activePane;
|
||||
const tabA = useTabs.getState().panes[first]!.tabs[0]!.id;
|
||||
ctrl.openInOpposite(first, tabA);
|
||||
const second = useTabs.getState().activePane;
|
||||
expect(second).not.toBe(first);
|
||||
expect(paths(second)).toEqual(["/p/a.ts"]);
|
||||
ctrl.openInOpposite(first, useTabs.getState().panes[first]!.tabs[1]!.id);
|
||||
expect(paths(second)).toEqual(["/p/a.ts", "/p/b.ts"]);
|
||||
expect(paths(first)).toEqual(["/p/a.ts", "/p/b.ts"]);
|
||||
});
|
||||
|
||||
it("closes read-only tabs and keeps a preview tab open from the tab menu", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/p/c.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
await ctrl.openFile("/p/b.ts", { focus: false });
|
||||
await ctrl.openFile("/p/c.ts", { focus: false, preview: true });
|
||||
const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!;
|
||||
const labels = () => resolveMenuItems(ctrl!.tabMenu(pane().id, pane().tabs[2]!)).map((i) => i.label);
|
||||
expect(labels()).toContain("Keep Tab Open");
|
||||
expect(labels()).not.toContain("Close All Read-Only Tabs");
|
||||
ctrl.keepTab(pane().id, pane().tabs[2]!.id);
|
||||
expect(pane().tabs[2]!.preview).toBe(false);
|
||||
useDocMeta.setState({ "/p/b.ts": { ...useDocMeta.getState()["/p/b.ts"]!, readOnly: true } });
|
||||
expect(labels()).toContain("Close All Read-Only Tabs");
|
||||
ctrl.closeReadOnly(pane().id);
|
||||
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
|
||||
});
|
||||
|
||||
it("reopens the LightEdit files the next time a window switches to LightEdit", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/x/a.txt": "a", "/y/b.md": "b" }));
|
||||
ctrl.start();
|
||||
useProject.setState({ lightEdit: true });
|
||||
await ctrl.openFile("/x/a.txt", { focus: false });
|
||||
await ctrl.openFile("/y/b.md", { focus: false });
|
||||
// The LightEdit window closes with its tabs open.
|
||||
useProject.setState({ lightEdit: false });
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([]);
|
||||
useProject.setState({ lightEdit: true });
|
||||
expect(openFilePaths(useTabs.getState())).toEqual(["/x/a.txt", "/y/b.md"]);
|
||||
// Closing every tab leaves nothing to reopen.
|
||||
ctrl.closeEverything();
|
||||
useProject.setState({ lightEdit: false });
|
||||
useProject.setState({ lightEdit: true });
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([]);
|
||||
useProject.setState({ lightEdit: false });
|
||||
});
|
||||
|
||||
it("closes a tab by its input key", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend());
|
||||
ctrl.start();
|
||||
|
||||
@@ -31,6 +31,7 @@ import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import {
|
||||
activateTab,
|
||||
changeSplitOrientation,
|
||||
closeAll,
|
||||
closeKey,
|
||||
closeOthers,
|
||||
@@ -57,6 +58,7 @@ import {
|
||||
splitPane,
|
||||
tabOptions,
|
||||
togglePin,
|
||||
unsplitAll,
|
||||
type SplitEdge,
|
||||
type Tab,
|
||||
type TabsState,
|
||||
@@ -102,6 +104,9 @@ export function isTextInput(input: EditorInput): input is EditorInput & { path:
|
||||
|
||||
export const useTabs = create<TabsState>(() => initialTabsState());
|
||||
|
||||
/** Session key of the LightEdit window: its tabs reopen the next time a window switches to LightEdit. */
|
||||
export const LIGHT_EDIT_SESSION = "<lightEdit>";
|
||||
|
||||
export interface EditorStatus {
|
||||
path: string;
|
||||
doc: number;
|
||||
@@ -179,7 +184,7 @@ export class EditorController implements SlotHost {
|
||||
activeSlot: EditorSlot | null = null;
|
||||
private statusScheduled = false;
|
||||
private disposers: Array<() => void> = [];
|
||||
/** Project root whose editor session is being tracked (null while switching). */
|
||||
/** Project root (or {@link LIGHT_EDIT_SESSION}) whose editor session is being tracked (null while switching). */
|
||||
private sessionRoot: string | null = null;
|
||||
private sessionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
/** Restored caret / scroll per path, applied when the file's first slot is created. */
|
||||
@@ -217,6 +222,7 @@ export class EditorController implements SlotHost {
|
||||
tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose;
|
||||
let prevSettings = useProject.getState().settings;
|
||||
let prevRoot = useProject.getState().project?.root ?? null;
|
||||
let prevLight = useProject.getState().lightEdit;
|
||||
this.disposers.push(
|
||||
useProject.subscribe((s) => {
|
||||
if (s.settings !== prevSettings) {
|
||||
@@ -226,14 +232,17 @@ export class EditorController implements SlotHost {
|
||||
this.manager.applySettings();
|
||||
}
|
||||
const root = s.project?.root ?? null;
|
||||
if (root !== prevRoot) {
|
||||
// Entering or leaving LightEdit replaces the backend's documents too.
|
||||
if (root !== prevRoot || s.lightEdit !== prevLight) {
|
||||
prevRoot = root;
|
||||
prevLight = s.lightEdit;
|
||||
this.saveSession();
|
||||
this.sessionRoot = null;
|
||||
this.closeEverything();
|
||||
this.nav.clear();
|
||||
this.edits.clear();
|
||||
if (root) this.restoreSession(root);
|
||||
else if (s.lightEdit) this.restoreSession(LIGHT_EDIT_SESSION);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -868,6 +877,15 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
}
|
||||
|
||||
/** Window › Editor Tabs › Goto Next / Previous Splitter: the active tab of the next split pane, wrapping. */
|
||||
focusSplitter(dir: 1 | -1) {
|
||||
const s = useTabs.getState();
|
||||
const ids = paneIds(s).filter((id) => s.panes[id]?.active);
|
||||
if (ids.length < 2) return;
|
||||
const next = ids[(ids.indexOf(s.activePane) + dir + ids.length) % ids.length]!;
|
||||
this.activate(next, s.panes[next]!.active!);
|
||||
}
|
||||
|
||||
// --- tab commands -----------------------------------------------------------------------------
|
||||
|
||||
private apply(f: (s: TabsState) => TabsState) {
|
||||
@@ -897,6 +915,10 @@ export class EditorController implements SlotHost {
|
||||
};
|
||||
this.apply((s) => closeUnmodified(s, paneId, modified));
|
||||
}
|
||||
closeReadOnly(paneId: string) {
|
||||
const writable = (t: Tab) => !t.input.path || !useDocMeta.getState()[t.input.path]?.readOnly;
|
||||
this.apply((s) => closeUnmodified(s, paneId, writable));
|
||||
}
|
||||
/** Reload from Disk: re-reads the open, unmodified documents of `paths`. */
|
||||
async reloadFromDisk(paths: string[]) {
|
||||
for (const path of paths) {
|
||||
@@ -993,6 +1015,30 @@ export class EditorController implements SlotHost {
|
||||
unsplit(paneId: string) {
|
||||
this.apply((s) => removePane(s, paneId));
|
||||
}
|
||||
unsplitAll(paneId: string) {
|
||||
this.apply((s) => unsplitAll(s, paneId));
|
||||
this.focus();
|
||||
}
|
||||
changeSplitOrientation(paneId: string) {
|
||||
this.apply((s) => changeSplitOrientation(s, paneId));
|
||||
}
|
||||
/** IDEA "Open in Opposite Group": the tab stays and a copy opens next door (or in a new split). */
|
||||
openInOpposite(paneId: string, tabId: string) {
|
||||
const s = useTabs.getState();
|
||||
const tab = s.panes[paneId]?.tabs.find((t) => t.id === tabId);
|
||||
if (!tab) return;
|
||||
const target = neighbourPane(s, paneId);
|
||||
if (!target) {
|
||||
this.activate(paneId, tabId, false);
|
||||
return this.split(paneId, "row");
|
||||
}
|
||||
const r = openTab(s, target, tab.input);
|
||||
useTabs.setState(r.state, true);
|
||||
void this.ensureSlot(r.tabId, { from: this.slots.get(tabId) }).then((slot) => {
|
||||
if (slot?.view) slot.focus();
|
||||
else if (slot) slot.wantsFocus = true;
|
||||
});
|
||||
}
|
||||
|
||||
closeActiveTab() {
|
||||
const s = useTabs.getState();
|
||||
@@ -1147,8 +1193,12 @@ export class EditorController implements SlotHost {
|
||||
...(tabs.some((t) => t.pinned)
|
||||
? ([{ label: "Close All but Pinned", run: () => this.closeAll(paneId, true) }] as MenuItem[])
|
||||
: []),
|
||||
...(tabs.some((t) => !t.pinned && !!t.input.path && useDocMeta.getState()[t.input.path]?.readOnly)
|
||||
? ([{ label: "Close All Read-Only Tabs", run: () => this.closeReadOnly(paneId) }] as MenuItem[])
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
{ label: tab.pinned ? "Unpin Tab" : "Pin Tab", icon: "pin", run: () => this.togglePin(paneId, tab.id) },
|
||||
...(tab.preview ? ([{ label: "Keep Tab Open", run: () => this.keepTab(paneId, tab.id) }] as MenuItem[]) : []),
|
||||
{ kind: "separator" },
|
||||
{ label: "Split and Move Right", run: () => this.moveTabToSplit(paneId, tab.id, paneId, "right") },
|
||||
{ label: "Split and Move Down", run: () => this.moveTabToSplit(paneId, tab.id, paneId, "bottom") },
|
||||
@@ -1167,7 +1217,10 @@ export class EditorController implements SlotHost {
|
||||
...(split
|
||||
? ([
|
||||
{ label: "Move to Opposite Group", run: () => this.moveToOpposite(paneId, tab.id) },
|
||||
{ label: "Open in Opposite Group", run: () => this.openInOpposite(paneId, tab.id) },
|
||||
{ label: "Change Splitter Orientation", run: () => this.changeSplitOrientation(paneId) },
|
||||
{ label: "Unsplit", run: () => this.unsplit(paneId) },
|
||||
{ label: "Unsplit All", run: () => this.unsplitAll(paneId) },
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -75,6 +75,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 20,
|
||||
component: CaretStatus,
|
||||
title: "Line:Column Number",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.lineEnding",
|
||||
@@ -82,6 +83,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 30,
|
||||
component: LineEndingStatus,
|
||||
title: "Line Separator",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.encoding",
|
||||
@@ -89,6 +91,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 40,
|
||||
component: EncodingStatus,
|
||||
title: "File Encoding",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.indent",
|
||||
@@ -96,6 +99,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 50,
|
||||
component: IndentStatus,
|
||||
title: "Indentation",
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerStatusItem({
|
||||
id: "editor.readOnly",
|
||||
@@ -103,6 +107,7 @@ export function activate(): void | (() => void) {
|
||||
priority: 55,
|
||||
component: ReadOnlyStatus,
|
||||
title: "Read-only Attribute",
|
||||
lightEdit: true,
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
changeSplitOrientation,
|
||||
closeAll,
|
||||
closeKey,
|
||||
closeOthers,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
splitPane,
|
||||
tabOptions,
|
||||
togglePin,
|
||||
unsplitAll,
|
||||
type TabsState,
|
||||
} from "./tabs";
|
||||
import { NavigationHistory } from "./navHistory";
|
||||
@@ -168,6 +170,29 @@ describe("tab model", () => {
|
||||
expect(s.layout).toEqual({ kind: "pane", paneId: split.paneId });
|
||||
});
|
||||
|
||||
it("flips the orientation of a split and unsplits everything", () => {
|
||||
let s = open(initialTabsState(), "a");
|
||||
const first = s.activePane;
|
||||
const right = splitPane(s, first, "row");
|
||||
const below = splitPane(right.state, right.paneId, "column");
|
||||
s = below.state;
|
||||
const dirs = (st: TabsState) =>
|
||||
st.layout.kind === "split"
|
||||
? [st.layout.dir, ...st.layout.children.map((c) => (c.kind === "split" ? c.dir : "pane"))]
|
||||
: [];
|
||||
expect(dirs(s)).toEqual(["row", "pane", "column"]);
|
||||
// The nested split turns side by side and merges into the outer row.
|
||||
s = changeSplitOrientation(s, below.paneId);
|
||||
expect(dirs(s)).toEqual(["row", "pane", "pane", "pane"]);
|
||||
s = changeSplitOrientation(s, first);
|
||||
expect(dirs(s)).toEqual(["column", "pane", "pane", "pane"]);
|
||||
expect(changeSplitOrientation(open(initialTabsState(), "x"), "nope").layout.kind).toBe("pane");
|
||||
s = unsplitAll(s, right.paneId);
|
||||
expect(paneIds(s)).toEqual([right.paneId]);
|
||||
expect(s.activePane).toBe(right.paneId);
|
||||
expect(labels(s)).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("closes a key everywhere and cycles tabs", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "a");
|
||||
|
||||
@@ -437,6 +437,30 @@ export function removePane(s: TabsState, paneId: string): TabsState {
|
||||
return { ...s, layout, panes, activePane };
|
||||
}
|
||||
|
||||
/** Flips the split that directly holds `paneId` between side by side and stacked. */
|
||||
export function changeSplitOrientation(s: TabsState, paneId: string): TabsState {
|
||||
let changed = false;
|
||||
const flipped = mapLayout(s.layout, (n) => {
|
||||
if (n.kind !== "split" || !n.children.some((c) => c.kind === "pane" && c.paneId === paneId)) return n;
|
||||
changed = true;
|
||||
const dir = n.dir === "row" ? "column" : "row";
|
||||
return { ...n, dir, children: n.children.flatMap((c) => (c.kind === "split" && c.dir === dir ? c.children : [c])) };
|
||||
})!;
|
||||
// The parent flattens a flipped split that now runs its way; the flipped one absorbs its children.
|
||||
return changed ? { ...s, layout: flipped } : s;
|
||||
}
|
||||
|
||||
/** Removes every pane except `keepPane`. */
|
||||
export function unsplitAll(s: TabsState, keepPane: string): TabsState {
|
||||
if (!s.panes[keepPane]) return s;
|
||||
return {
|
||||
...s,
|
||||
layout: { kind: "pane", paneId: keepPane },
|
||||
panes: { [keepPane]: s.panes[keepPane] },
|
||||
activePane: keepPane,
|
||||
};
|
||||
}
|
||||
|
||||
/** The pane right of / below `paneId`, if any (for "open to the side"). */
|
||||
export function neighbourPane(s: TabsState, paneId: string): string | null {
|
||||
const order = paneIds(s);
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* menu (Search In Selection ⌥E — on by default when Replace opens over a
|
||||
* multi-line selection — and the search scope: anywhere, in / except comments
|
||||
* and string literals), n/N counter, ↑/↓ (⇧↵ / ↵), Replace / Replace All /
|
||||
* Exclude with Preserve Case, Esc closes.
|
||||
* Exclude with Preserve Case, Esc closes. `FindPanel` is the bar itself, for
|
||||
* any CodeMirror view (the diff viewer's sides); `FindBar` is it on an editor pane.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
@@ -57,12 +58,45 @@ const useFindScoped = create<Record<string, boolean>>(() => ({}));
|
||||
/** The selection the bar was opened over, for toggling "In Selection" on later. */
|
||||
const openSelections = new Map<string, FindScope>();
|
||||
|
||||
/** The editor a find bar searches. */
|
||||
export interface FindTarget {
|
||||
/** Keys the bar's counter and selection scope. */
|
||||
id: string;
|
||||
view(): EditorView | null;
|
||||
/** Calls `fn` on document / selection changes of the searched editor; returns the unsubscribe. */
|
||||
watch(fn: (u: { docChanged: boolean; selectionSet: boolean }) => void): () => void;
|
||||
/** Still open: an unmount that isn't a close (React's dev-mode remount) keeps the highlights. */
|
||||
isOpen(): boolean;
|
||||
}
|
||||
|
||||
function activeView(paneId: string): EditorView | null {
|
||||
const pane = useTabs.getState().panes[paneId];
|
||||
if (!pane?.active) return null;
|
||||
return editorController().slotFor(pane.active)?.view ?? null;
|
||||
}
|
||||
|
||||
const paneTargets = new Map<string, FindTarget>();
|
||||
|
||||
function paneTarget(paneId: string): FindTarget {
|
||||
let target = paneTargets.get(paneId);
|
||||
if (!target) {
|
||||
target = {
|
||||
id: paneId,
|
||||
view: () => activeView(paneId),
|
||||
watch(fn) {
|
||||
const tab = useTabs.getState().panes[paneId]?.active;
|
||||
const slot = tab ? editorController().slotFor(tab) : null;
|
||||
if (!slot) return () => {};
|
||||
slot.listeners.add(fn);
|
||||
return () => void slot.listeners.delete(fn);
|
||||
},
|
||||
isOpen: () => !!useFindBars.getState()[paneId],
|
||||
};
|
||||
paneTargets.set(paneId, target);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export function closeFindBar(paneId: string) {
|
||||
useFindBars.setState({ [paneId]: undefined });
|
||||
}
|
||||
@@ -77,12 +111,18 @@ const MAX_QUERY = 10_000;
|
||||
* multi-line query isn't kept for a later search without a selection.
|
||||
*/
|
||||
export function openFindBar(paneId: string, replace: boolean) {
|
||||
const view = activeView(paneId);
|
||||
seedFind(paneTarget(paneId), replace);
|
||||
useFindBars.setState((s) => ({ [paneId]: { replace, seq: (s[paneId]?.seq ?? 0) + 1 } }));
|
||||
}
|
||||
|
||||
/** The query and scope a bar opening over `target`'s selection starts with (see openFindBar). */
|
||||
export function seedFind(target: FindTarget, replace: boolean) {
|
||||
const view = target.view();
|
||||
const sel = view?.state.selection.main;
|
||||
if (view && sel && !sel.empty) {
|
||||
const text = view.state.sliceDoc(sel.from, sel.to);
|
||||
const multiline = text.includes("\n");
|
||||
openSelections.set(paneId, { from: sel.from, to: sel.to });
|
||||
openSelections.set(target.id, { from: sel.from, to: sel.to });
|
||||
if (multiline && replace) {
|
||||
view.dispatch({ effects: setFindScope.of({ from: sel.from, to: sel.to }) });
|
||||
useFindOptions.setState({ search: "" });
|
||||
@@ -94,7 +134,6 @@ export function openFindBar(paneId: string, replace: boolean) {
|
||||
} else if (useFindOptions.getState().search.includes("\n")) {
|
||||
useFindOptions.setState({ search: "" });
|
||||
}
|
||||
useFindBars.setState((s) => ({ [paneId]: { replace, seq: (s[paneId]?.seq ?? 0) + 1 } }));
|
||||
}
|
||||
|
||||
/** Show / Hide Replace on the open bar, keeping its query and scope. */
|
||||
@@ -104,44 +143,49 @@ function setReplaceShown(paneId: string, replace: boolean) {
|
||||
|
||||
/** ⌘G / ⇧⌘G: next / previous occurrence of the last search, with or without the bar. */
|
||||
export function findAgain(paneId: string, forward: boolean) {
|
||||
const view = activeView(paneId);
|
||||
const opts = useFindOptions.getState();
|
||||
const target = paneTarget(paneId);
|
||||
const view = target.view();
|
||||
if (!view) return;
|
||||
if (!opts.search || (opts.regexp && !regexValid(opts.search))) {
|
||||
openFindBar(paneId, false);
|
||||
return;
|
||||
}
|
||||
if (!searchAgain(target, forward)) openFindBar(paneId, false);
|
||||
}
|
||||
|
||||
/** Next / previous occurrence of the last search in `target`; false without a usable query. */
|
||||
export function searchAgain(target: FindTarget, forward: boolean): boolean {
|
||||
const view = target.view();
|
||||
const opts = useFindOptions.getState();
|
||||
if (!view || !opts.search || (opts.regexp && !regexValid(opts.search))) return false;
|
||||
setQuery(view, opts);
|
||||
if (forward) findNext(view);
|
||||
else findPrevious(view);
|
||||
if (useFindBars.getState()[paneId]) recount(paneId);
|
||||
if (target.isOpen()) recount(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Toggles "In Selection": limit to the selection the bar was opened over (or the current one). */
|
||||
function toggleScope(paneId: string) {
|
||||
const view = activeView(paneId);
|
||||
function toggleScope(target: FindTarget) {
|
||||
const view = target.view();
|
||||
if (!view) return;
|
||||
if (view.state.field(findScope, false)) {
|
||||
view.dispatch({ effects: setFindScope.of(null) });
|
||||
} else {
|
||||
const main = view.state.selection.main;
|
||||
const len = view.state.doc.length;
|
||||
const saved = openSelections.get(paneId);
|
||||
const saved = openSelections.get(target.id);
|
||||
const range = saved && saved.to <= len && saved.to - saved.from > main.to - main.from ? saved : main;
|
||||
if (range.to <= range.from) return;
|
||||
view.dispatch({ effects: setFindScope.of({ from: range.from, to: range.to }) });
|
||||
}
|
||||
recount(paneId);
|
||||
recount(target);
|
||||
}
|
||||
|
||||
function recount(paneId: string) {
|
||||
const view = activeView(paneId);
|
||||
function recount(target: FindTarget) {
|
||||
const view = target.view();
|
||||
if (!view) return;
|
||||
const opts = useFindOptions.getState();
|
||||
const r = countMatches(view.state);
|
||||
const { from, to } = view.state.selection.main;
|
||||
useFindCounts.setState({ [paneId]: opts.search ? { ...r, excluded: isExcluded(view.state, from, to) } : null });
|
||||
useFindScoped.setState({ [paneId]: !!view.state.field(findScope, false) });
|
||||
useFindCounts.setState({ [target.id]: opts.search ? { ...r, excluded: isExcluded(view.state, from, to) } : null });
|
||||
useFindScoped.setState({ [target.id]: !!view.state.field(findScope, false) });
|
||||
view.dispatch({ effects: setFindMarks.of(opts.search ? r.starts : []) });
|
||||
}
|
||||
|
||||
@@ -153,15 +197,41 @@ function rememberQuery(replace: boolean) {
|
||||
|
||||
export function FindBar({ paneId }: { paneId: string }) {
|
||||
const bar = useFindBars((s) => s[paneId]);
|
||||
const activeTab = useTabs((s) => s.panes[paneId]?.active ?? null);
|
||||
if (!bar) return null;
|
||||
return <FindBarInner paneId={paneId} replace={bar.replace} seq={bar.seq} />;
|
||||
return (
|
||||
<FindPanel
|
||||
target={paneTarget(paneId)}
|
||||
version={activeTab}
|
||||
replace={bar.replace}
|
||||
seq={bar.seq}
|
||||
onReplaceShown={(replace) => setReplaceShown(paneId, replace)}
|
||||
onClose={() => {
|
||||
closeFindBar(paneId);
|
||||
activeView(paneId)?.focus();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boolean; seq: number }) {
|
||||
const activeTab = useTabs((s) => s.panes[paneId]?.active ?? null);
|
||||
export interface FindPanelProps {
|
||||
target: FindTarget;
|
||||
/** Changes when the target's view does (another tab, a rebuilt viewer). */
|
||||
version: unknown;
|
||||
replace: boolean;
|
||||
/** Bumped by each open (⌘F again): refocuses the field. */
|
||||
seq: number;
|
||||
/** Show / Hide Replace; without it the bar only finds. */
|
||||
onReplaceShown?: (replace: boolean) => void;
|
||||
/** Closes the bar (the owner unmounts it) and focuses the editor. */
|
||||
onClose(): void;
|
||||
}
|
||||
|
||||
export function FindPanel({ target, version, replace, seq, onReplaceShown, onClose }: FindPanelProps) {
|
||||
const id = target.id;
|
||||
const opts = useFindOptions();
|
||||
const count = useFindCounts((s) => s[paneId] ?? null);
|
||||
const scoped = useFindScoped((s) => !!s[paneId]);
|
||||
const count = useFindCounts((s) => s[id] ?? null);
|
||||
const scoped = useFindScoped((s) => !!s[id]);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const replaceRef = useRef<HTMLInputElement>(null);
|
||||
const findBoxRef = useRef<HTMLDivElement>(null);
|
||||
@@ -179,7 +249,7 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
|
||||
// Push the query into the editor; incremental search selects the nearest match.
|
||||
useEffect(() => {
|
||||
const view = activeView(paneId);
|
||||
const view = target.view();
|
||||
if (!view) return;
|
||||
const valid = !opts.regexp || regexValid(opts.search);
|
||||
setQuery(view, valid ? opts : { ...opts, search: "" });
|
||||
@@ -189,43 +259,39 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
view.dispatch({ selection: { anchor: from } });
|
||||
findNext(view);
|
||||
}
|
||||
recount(paneId);
|
||||
}, [opts, paneId, activeTab]);
|
||||
recount(target);
|
||||
}, [opts, target, version]);
|
||||
|
||||
// Keep the counter current while the document / selection changes.
|
||||
useEffect(() => {
|
||||
const slot = activeTab ? editorController().slotFor(activeTab) : null;
|
||||
if (!slot) return;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listener = (u: { docChanged: boolean; selectionSet: boolean }) => {
|
||||
const unwatch = target.watch((u) => {
|
||||
if (!u.docChanged && !u.selectionSet) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => recount(paneId), u.docChanged ? 150 : 0);
|
||||
};
|
||||
slot.listeners.add(listener);
|
||||
timer = setTimeout(() => recount(target), u.docChanged ? 150 : 0);
|
||||
});
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
slot.listeners.delete(listener);
|
||||
unwatch();
|
||||
};
|
||||
}, [activeTab, paneId]);
|
||||
}, [target, version]);
|
||||
|
||||
// Closing clears highlights, marks and the selection scope (not React's dev-mode remount).
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (!useFindBars.getState()[paneId]) activeView(paneId)?.dispatch({ effects: [setFindOpen.of(false)] });
|
||||
if (!target.isOpen()) target.view()?.dispatch({ effects: [setFindOpen.of(false)] });
|
||||
},
|
||||
[paneId],
|
||||
[target],
|
||||
);
|
||||
|
||||
const close = () => {
|
||||
rememberQuery(replace);
|
||||
closeFindBar(paneId);
|
||||
activeView(paneId)?.focus();
|
||||
onClose();
|
||||
};
|
||||
const run = (cmd: (v: EditorView) => boolean) => {
|
||||
const view = activeView(paneId);
|
||||
const view = target.view();
|
||||
if (view) cmd(view);
|
||||
recount(paneId);
|
||||
recount(target);
|
||||
};
|
||||
const doReplace = () => {
|
||||
rememberQuery(true);
|
||||
@@ -239,9 +305,9 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
useFindOptions.setState((o) => ({ [key]: !o[key] }));
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent, field: "find" | "replace") => {
|
||||
const target = e.target as HTMLTextAreaElement | HTMLInputElement;
|
||||
const input = e.target as HTMLTextAreaElement | HTMLInputElement;
|
||||
// Inside a multi-line query the arrows move the caret between its lines.
|
||||
const multiLine = target.value.includes("\n");
|
||||
const multiLine = input.value.includes("\n");
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -271,7 +337,7 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
toggle(k);
|
||||
} else if (e.code === "KeyE") {
|
||||
e.preventDefault();
|
||||
toggleScope(paneId);
|
||||
toggleScope(target);
|
||||
} else if (replace && e.code === "KeyP") {
|
||||
e.preventDefault();
|
||||
doReplace();
|
||||
@@ -312,7 +378,7 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
: [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }];
|
||||
};
|
||||
const filterItems: MenuItem[] = [
|
||||
{ label: "Search In Selection", shortcut: "⌥E", checked: scoped || undefined, run: () => toggleScope(paneId) },
|
||||
{ label: "Search In Selection", shortcut: "⌥E", checked: scoped || undefined, run: () => toggleScope(target) },
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Search Scope" },
|
||||
...SEARCH_CONTEXTS.map((c) => ({
|
||||
@@ -384,13 +450,15 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
pressed={scoped || opts.context !== "any"}
|
||||
onClick={() => setFilterMenu(true)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="replace"
|
||||
title={replace ? "Hide Replace" : "Show Replace"}
|
||||
size="small"
|
||||
pressed={replace}
|
||||
onClick={() => setReplaceShown(paneId, !replace)}
|
||||
/>
|
||||
{onReplaceShown && (
|
||||
<IconButton
|
||||
icon="replace"
|
||||
title={replace ? "Hide Replace" : "Show Replace"}
|
||||
size="small"
|
||||
pressed={replace}
|
||||
onClick={() => onReplaceShown(!replace)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
|
||||
{replace && (
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
|
||||
const disk = new Map<string, string>();
|
||||
const editors = new Map<string, EditorState>();
|
||||
|
||||
vi.mock(import("@/platform/ipc"), async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
commands: { fsReadText: (path: string) => path } as never,
|
||||
call: (async (path: string) => disk.get(path) ?? Promise.reject(new Error("missing"))) as never,
|
||||
}));
|
||||
vi.mock("@/editor/api", () => ({
|
||||
editorsFor: (path: string) => {
|
||||
const state = editors.get(path);
|
||||
return state ? [{ view: { state } }] : [];
|
||||
},
|
||||
}));
|
||||
|
||||
const { clearLineTokens, lineTokens, peekLineTokens } = await import("./lineTokens");
|
||||
|
||||
const SOURCE = ["/**", " * A read-only virtual document (library", " */", 'const lib = "x";'].join("\n");
|
||||
const classesOf = (text: string, tokens: Array<{ from: number; to: number; cls: string }>) =>
|
||||
tokens.map((t) => `${text.slice(t.from, t.to)}:${t.cls}`);
|
||||
|
||||
describe("lineTokens", () => {
|
||||
beforeEach(() => {
|
||||
clearLineTokens();
|
||||
disk.clear();
|
||||
editors.clear();
|
||||
});
|
||||
|
||||
it("colours a line inside a block comment with the whole file as context", async () => {
|
||||
disk.set("/p/a.ts", SOURCE);
|
||||
const text = "* A read-only virtual document (library";
|
||||
const tokens = await lineTokens({ path: "/p/a.ts", line: 1, col: 1 }, text);
|
||||
expect(classesOf(text, tokens)).toEqual([`${text}:tok-comment`]);
|
||||
expect(peekLineTokens({ path: "/p/a.ts", line: 1, col: 1 }, text)).toBe(tokens);
|
||||
});
|
||||
|
||||
it("keeps positions relative to the shown text", async () => {
|
||||
disk.set("/p/a.ts", SOURCE);
|
||||
const text = 'lib = "x";';
|
||||
const tokens = await lineTokens({ path: "/p/a.ts", line: 3, col: 6 }, text);
|
||||
expect(classesOf(text, tokens)).toContain('"x":tok-string');
|
||||
});
|
||||
|
||||
it("parses the line on its own when the file no longer has it there", async () => {
|
||||
disk.set("/p/a.ts", SOURCE);
|
||||
const text = "* A read-only virtual document (library";
|
||||
const tokens = await lineTokens({ path: "/p/a.ts", line: 0, col: 0 }, text);
|
||||
expect(classesOf(text, tokens)).not.toContain(`${text}:tok-comment`);
|
||||
});
|
||||
|
||||
it("parses again when the open editor's document changes", async () => {
|
||||
editors.set("/p/a.ts", EditorState.create({ doc: SOURCE.replace("/**", "//") }));
|
||||
const text = "* A read-only virtual document (library";
|
||||
expect(classesOf(text, await lineTokens({ path: "/p/a.ts", line: 1, col: 1 }, text))).not.toContain(
|
||||
`${text}:tok-comment`,
|
||||
);
|
||||
editors.set("/p/a.ts", EditorState.create({ doc: SOURCE }));
|
||||
expect(classesOf(text, await lineTokens({ path: "/p/a.ts", line: 1, col: 1 }, text))).toEqual([
|
||||
`${text}:tok-comment`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses a big file in slices, letting other tasks run in between", async () => {
|
||||
const body = "const a = 1; // filler line for the parser\n".repeat(8000);
|
||||
disk.set("/p/big.ts", `${body}const lib = "x";`);
|
||||
let ticks = 0;
|
||||
const timer = setInterval(() => ticks++, 0);
|
||||
const text = 'lib = "x";';
|
||||
const tokens = await lineTokens({ path: "/p/big.ts", line: 8000, col: 6 }, text);
|
||||
clearInterval(timer);
|
||||
expect(classesOf(text, tokens)).toContain('"x":tok-string');
|
||||
expect(ticks).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("leaves files of unknown languages plain", async () => {
|
||||
disk.set("/p/a.unknownext", SOURCE);
|
||||
expect(await lineTokens({ path: "/p/a.unknownext", line: 1, col: 1 }, "* A read-only")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* Syntax colours for result lines (Find in Files, Show Usages), like IDEA's
|
||||
* `ChunkExtractor`: each file is parsed whole once, so a line inside a block
|
||||
* comment or a multi-line string is coloured as such.
|
||||
*/
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { editorsFor } from "@/editor/api";
|
||||
import { codeHighlighter, highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
|
||||
|
||||
export type { CodeToken };
|
||||
|
||||
/** Where a result line's `text` sits in its file: 0-based `line`, column `col`. */
|
||||
export interface LineSource {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
const texts = new Map<string, Promise<string>>();
|
||||
|
||||
/**
|
||||
* Text of a file that isn't open (a library source or a read-only backend
|
||||
* read that doesn't open a document), cached until `clearLineTokens`.
|
||||
*/
|
||||
export function readFileText(path: string): Promise<string> {
|
||||
let p = texts.get(path);
|
||||
if (!p) {
|
||||
p = isVirtualUri(path) ? virtualDocument(path).then((d) => d.text) : call(commands.fsReadText(path));
|
||||
p.catch(() => texts.delete(path));
|
||||
texts.set(path, p);
|
||||
if (texts.size > 40) texts.delete(texts.keys().next().value!);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Drops cached file texts and parses (a new search reads the files again). */
|
||||
export function clearLineTokens() {
|
||||
texts.clear();
|
||||
highlighted.clear();
|
||||
}
|
||||
|
||||
/** Bigger files aren't parsed whole: their result lines are coloured on their own. */
|
||||
const MAX_PARSE = 500_000;
|
||||
|
||||
interface Parsed {
|
||||
doc: Text;
|
||||
highlight: (from: number, to: number) => CodeToken[];
|
||||
}
|
||||
|
||||
/**
|
||||
* One file parsed whole: `source` is the editor document or the text it was
|
||||
* parsed from, so an edit (a new `Text`) or a re-read (a new string) parses
|
||||
* again.
|
||||
*/
|
||||
interface Highlighted {
|
||||
source: Text | string;
|
||||
parsed: Promise<Parsed | null>;
|
||||
/** Tokens per result line (`lineKey`). */
|
||||
lines: Map<string, CodeToken[]>;
|
||||
}
|
||||
const highlighted = new Map<string, Highlighted>();
|
||||
|
||||
const lineKey = (line: number, col: number, text: string) => `${line}\u0000${col}\u0000${text}`;
|
||||
|
||||
/** `lineTokens` already computed for the file as last parsed (for a first render without flicker). */
|
||||
export function peekLineTokens({ path, line, col }: LineSource, text: string): CodeToken[] | null {
|
||||
return highlighted.get(path)?.lines.get(lineKey(line, col, text)) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Syntax tokens of a result line (`text` at `source`), positions within
|
||||
* `text`, coloured with the whole file as context. When the file no longer
|
||||
* has `text` there (changed since the search) or is too big, the line is
|
||||
* parsed on its own.
|
||||
*/
|
||||
export async function lineTokens({ path, line, col }: LineSource, text: string): Promise<CodeToken[]> {
|
||||
const language = languageForPath(path);
|
||||
if (!language || !text) return [];
|
||||
const source = editorsFor(path)[0]?.view.state.doc ?? (await readFileText(path).catch(() => null));
|
||||
if (source == null) return highlightTokens(text, language);
|
||||
let h = highlighted.get(path);
|
||||
if (h?.source !== source) {
|
||||
h = { source, parsed: parseWhole(source, language), lines: new Map() };
|
||||
highlighted.delete(path);
|
||||
highlighted.set(path, h);
|
||||
if (highlighted.size > 40) highlighted.delete(highlighted.keys().next().value!);
|
||||
}
|
||||
const key = lineKey(line, col, text);
|
||||
const known = h.lines.get(key);
|
||||
if (known) return known;
|
||||
const parsed = await h.parsed;
|
||||
let tokens: CodeToken[] | null = null;
|
||||
if (parsed && line < parsed.doc.lines) {
|
||||
const l = parsed.doc.line(line + 1);
|
||||
if (l.text.slice(col, col + text.length) === text) {
|
||||
const from = l.from + col;
|
||||
tokens = parsed.highlight(from, from + text.length).map((t) => ({ ...t, from: t.from - from, to: t.to - from }));
|
||||
}
|
||||
}
|
||||
tokens ??= await highlightTokens(text, language);
|
||||
h.lines.set(key, tokens);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
async function parseWhole(source: Text | string, language: string): Promise<Parsed | null> {
|
||||
if (source.length > MAX_PARSE) return null;
|
||||
const text = typeof source === "string" ? source : source.toString();
|
||||
const highlight = await codeHighlighter(text, language);
|
||||
if (!highlight) return null;
|
||||
// Splitting on "\n" alone keeps a "\r" in its line, so offsets match `text`.
|
||||
return { doc: typeof source === "string" ? Text.of(text.split("\n")) : source, highlight };
|
||||
}
|
||||
|
||||
/** `lineTokens` for a rendered line; null until known (and without a `source`). */
|
||||
export function useLineTokens(source: LineSource | undefined, text: string): CodeToken[] | null {
|
||||
const path = source?.path ?? null;
|
||||
const line = source?.line ?? 0;
|
||||
const col = source?.col ?? 0;
|
||||
const key = `${path}\u0000${line}\u0000${col}\u0000${text}`;
|
||||
const [loaded, setLoaded] = useState<{ key: string; tokens: CodeToken[] } | null>(null);
|
||||
useEffect(() => {
|
||||
if (path == null) return;
|
||||
let alive = true;
|
||||
void lineTokens({ path, line, col }, text).then((tokens) => {
|
||||
if (alive) setLoaded({ key, tokens });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [key, path, line, col, text]);
|
||||
if (path == null) return null;
|
||||
return loaded?.key === key ? loaded.tokens : peekLineTokens({ path, line, col }, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* `text` between `from` and `to` as spans with the tokens' `tok-*` classes
|
||||
* (styled by the caller); `key` prefixes the React keys.
|
||||
*/
|
||||
export function tokenSpans(
|
||||
text: string,
|
||||
from: number,
|
||||
to: number,
|
||||
tokens: readonly CodeToken[] | null,
|
||||
key = "",
|
||||
): ReactNode[] {
|
||||
if (!tokens?.length) return [text.slice(from, to)];
|
||||
const out: ReactNode[] = [];
|
||||
let pos = from;
|
||||
for (const t of tokens) {
|
||||
if (t.to <= pos) continue;
|
||||
if (t.from >= to) break;
|
||||
const s = Math.max(t.from, pos);
|
||||
const e = Math.min(t.to, to);
|
||||
if (s > pos) out.push(text.slice(pos, s));
|
||||
out.push(
|
||||
<span key={`${key}${s}`} className={t.cls}>
|
||||
{text.slice(s, e)}
|
||||
</span>,
|
||||
);
|
||||
pos = e;
|
||||
}
|
||||
if (pos < to) out.push(text.slice(pos, to));
|
||||
return out;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Actions of the LSP editor layer (ids from keymaps/intellij-macos.ts). */
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { registerActions, type Action } from "@/platform/actions";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { activeEditor, editorsFor, registerSaveParticipant, type TextEditorHandle } from "@/editor/api";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -8,8 +8,8 @@ import { explicitCompletion } from "./completion";
|
||||
import { triggerSignatureHelp } from "./signature";
|
||||
import { quickDefinition, quickDocumentation } from "./hover";
|
||||
import { expressionTypeInfo } from "./typeInfo";
|
||||
import { gotoTargets, highlightUsages } from "./navigation";
|
||||
import { gotoDiagnostic } from "./diagnostics";
|
||||
import { gotoHighlightedUsage, gotoTargets, highlightUsages } from "./navigation";
|
||||
import { gotoDiagnostic, showErrorDescription } from "./diagnostics";
|
||||
import { applyKindSilently, applyQuickFix, runKindAction, showIntentions } from "./intentions";
|
||||
import { implementPythonAbstractMethods } from "./pythonMembers";
|
||||
import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings";
|
||||
@@ -227,7 +227,25 @@ export function registerLspActions(): () => void {
|
||||
),
|
||||
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
|
||||
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
|
||||
editorAction("code.showErrorDescription", "Error Description", "View", showErrorDescription, {
|
||||
keywords: ["problem", "warning", "tooltip"],
|
||||
}),
|
||||
editorAction("find.highlightUsages", "Highlight Usages in File", "Find", highlightUsages),
|
||||
// Shares Next / Previous Occurrence's key on Windows (as in IDEA): that runs without highlighted usages.
|
||||
editorAction(
|
||||
"navigate.nextHighlightedUsage",
|
||||
"Next Highlighted Usage",
|
||||
"Navigate",
|
||||
(v) => gotoHighlightedUsage(v, 1) || executeAction("navigate.nextOccurrence"),
|
||||
{ keyWhen: "editorTextFocus" },
|
||||
),
|
||||
editorAction(
|
||||
"navigate.prevHighlightedUsage",
|
||||
"Previous Highlighted Usage",
|
||||
"Navigate",
|
||||
(v) => gotoHighlightedUsage(v, -1) || executeAction("navigate.prevOccurrence"),
|
||||
{ keyWhen: "editorTextFocus" },
|
||||
),
|
||||
{
|
||||
// Also outside an editor, where nothing applies: IDEA's "Nothing here" popup.
|
||||
id: "refactor.thisMenu",
|
||||
|
||||
@@ -304,3 +304,18 @@ export function gotoDiagnostic(view: EditorView, dir: 1 | -1): boolean {
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/** ⌘F1 Show Error Description: the problems at the caret, worst first. */
|
||||
export function showErrorDescription(view: EditorView): boolean {
|
||||
const at = diagnosticsAt(view, view.state.selection.main.head);
|
||||
if (!at.length) {
|
||||
showHint(view, "No problems at the caret");
|
||||
return false;
|
||||
}
|
||||
const worst = at[0]!.diagnostic.severity;
|
||||
showHint(view, [...new Set(at.map((p) => p.diagnostic.message))].join("\n"), {
|
||||
tone: worst === "error" ? "error" : worst === "warning" ? "warning" : "info",
|
||||
timeout: 10000,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -34,6 +34,20 @@ describe("semanticRanges", () => {
|
||||
);
|
||||
expect(semanticRanges(doc, input, false, "java")[0]?.className).toBe("cm-sem-property cm-sem-static");
|
||||
});
|
||||
|
||||
it("ignores type and modifier names that only exist on Object.prototype", () => {
|
||||
const input = {
|
||||
tokenTypes: ["method", "toString"],
|
||||
tokenModifiers: ["valueOf"],
|
||||
data: [0, 0, 3, 0, 1, 0, 4, 3, 1, 1],
|
||||
};
|
||||
expect(semanticRanges(doc, input)).toEqual([{ from: 0, to: 3, className: "cm-sem-function" }]);
|
||||
});
|
||||
|
||||
it("colours a constructor (jdtls: class + `constructor`) as a function", () => {
|
||||
const input = { tokenTypes: ["class"], tokenModifiers: ["constructor", "declaration"], data: [0, 0, 3, 0, 0b11] };
|
||||
expect(semanticRanges(doc, input)[0]?.className).toBe("cm-sem-function cm-sem-declaration");
|
||||
});
|
||||
});
|
||||
|
||||
describe("semantic highlighting (rainbow identifiers)", () => {
|
||||
|
||||
@@ -10,7 +10,8 @@ import { txTemplate } from "@/platform/i18n";
|
||||
|
||||
interface Hint {
|
||||
pos: number;
|
||||
content: string | (() => HTMLElement);
|
||||
/** Text, or DOM built when shown (with `destroy` when it holds e.g. a React root). */
|
||||
content: string | (() => HTMLElement | { dom: HTMLElement; destroy: () => void });
|
||||
tone: "info" | "error" | "warning";
|
||||
}
|
||||
|
||||
@@ -34,9 +35,17 @@ const hintField = StateField.define<Hint | null>({
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hint cm-lsp-hint-${h.tone}`;
|
||||
dom.setAttribute("role", "status");
|
||||
if (typeof h.content === "string") dom.textContent = txTemplate(h.content);
|
||||
else dom.appendChild(h.content());
|
||||
return { dom };
|
||||
if (typeof h.content === "string") {
|
||||
dom.textContent = txTemplate(h.content);
|
||||
return { dom };
|
||||
}
|
||||
const built = h.content();
|
||||
if (built instanceof HTMLElement) {
|
||||
dom.appendChild(built);
|
||||
return { dom };
|
||||
}
|
||||
dom.appendChild(built.dom);
|
||||
return { dom, destroy: built.destroy };
|
||||
},
|
||||
}
|
||||
: null,
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
* is prefetched when the app goes idle; until then markup shows as plain text.
|
||||
*/
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
import { LanguageDescription } from "@codemirror/language";
|
||||
import { LanguageDescription, type Language } from "@codemirror/language";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import { classHighlighter, highlightCode } from "@lezer/highlight";
|
||||
import { classHighlighter, highlightTree } from "@lezer/highlight";
|
||||
import type { Markup } from "@/bindings";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
@@ -114,26 +114,55 @@ export interface CodeToken {
|
||||
|
||||
/** Highlighted ranges of `text`; empty when the language is unknown or its grammar fails to load. */
|
||||
export async function highlightTokens(text: string, language: string | null): Promise<CodeToken[]> {
|
||||
return (await codeHighlighter(text, language))?.(0, text.length) ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses `text` once; the result gives the highlighted ranges (positions in
|
||||
* `text`) between `from` and `to`, so a line is coloured with the whole file
|
||||
* as context. Null when the language is unknown or its grammar fails to load.
|
||||
*/
|
||||
export async function codeHighlighter(
|
||||
text: string,
|
||||
language: string | null,
|
||||
): Promise<((from: number, to: number) => CodeToken[]) | null> {
|
||||
const desc = language ? findLanguage(language) : null;
|
||||
if (!desc) return [];
|
||||
if (!desc) return null;
|
||||
try {
|
||||
const support = desc.support ?? (await desc.load());
|
||||
const tree = support.language.parser.parse(text);
|
||||
const out: CodeToken[] = [];
|
||||
let pos = 0;
|
||||
highlightCode(
|
||||
text,
|
||||
tree,
|
||||
classHighlighter,
|
||||
(t, cls) => {
|
||||
if (cls) out.push({ from: pos, to: pos + t.length, cls });
|
||||
pos += t.length;
|
||||
},
|
||||
() => pos++,
|
||||
);
|
||||
return out;
|
||||
const tree = await parseSliced(support.language.parser, text);
|
||||
return (from, to) => {
|
||||
const out: CodeToken[] = [];
|
||||
highlightTree(
|
||||
tree,
|
||||
classHighlighter,
|
||||
(a, b, cls) => {
|
||||
const s = Math.max(a, from);
|
||||
const e = Math.min(b, to);
|
||||
if (e > s) out.push({ from: s, to: e, cls });
|
||||
},
|
||||
from,
|
||||
to,
|
||||
);
|
||||
return out;
|
||||
};
|
||||
} catch {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse budget per task: a whole file (up to ~1s) yields to input and rendering in between. */
|
||||
const PARSE_SLICE_MS = 8;
|
||||
|
||||
async function parseSliced(parser: Language["parser"], text: string): Promise<ReturnType<Language["parser"]["parse"]>> {
|
||||
const parse = parser.startParse(text);
|
||||
for (;;) {
|
||||
const start = performance.now();
|
||||
while (performance.now() - start < PARSE_SLICE_MS) {
|
||||
const tree = parse.advance();
|
||||
if (tree) return tree;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -627,6 +627,23 @@ export function highlightUsages(view: EditorView) {
|
||||
void fetchHighlights(view, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* ⌃⌥↓ / ⌃⌥↑: the next (previous) highlighted usage of the element at the caret,
|
||||
* wrapping, with the caret at the same offset inside it.
|
||||
*/
|
||||
export function gotoHighlightedUsage(view: EditorView, dir: 1 | -1): boolean {
|
||||
const st = view.state.field(highlightField, false);
|
||||
const ranges: { from: number; to: number }[] = [];
|
||||
st?.deco.between(0, view.state.doc.length, (from, to) => void ranges.push({ from, to }));
|
||||
const head = view.state.selection.main.head;
|
||||
const current = ranges.findIndex((r) => r.from <= head && head <= r.to);
|
||||
if (ranges.length < 2 || current < 0) return false;
|
||||
const target = ranges[(current + dir + ranges.length) % ranges.length]!;
|
||||
const pos = Math.min(target.from + (head - ranges[current]!.from), target.to);
|
||||
view.dispatch({ selection: EditorSelection.cursor(pos), scrollIntoView: true, userEvent: "select.navigate" });
|
||||
return true;
|
||||
}
|
||||
|
||||
const highlightPlugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
private request = debounce(() => void fetchHighlights(this.view, false), 300);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, Prec, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
|
||||
// One `property` token over the whole word, as jdtls reports an instance field.
|
||||
const lspSemanticTokens = vi.fn(async () => ({
|
||||
status: "ok" as const,
|
||||
data: { data: [0, 0, 13, 0, 0], tokenTypes: ["property"], tokenModifiers: [] },
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSemanticTokens } };
|
||||
});
|
||||
|
||||
const { semanticExtension } = await import("./semantic");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
/** A syntax-highlighter mark at the same precedence CodeMirror's `treeHighlighter` uses. */
|
||||
const syntaxMark = (cls: string, from = 0, to = 13): Extension =>
|
||||
Prec.high(EditorView.decorations.of(Decoration.set([Decoration.mark({ class: cls }).range(from, to)])));
|
||||
|
||||
async function editor(extensions: Extension[]) {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "nasProperties",
|
||||
extensions: [
|
||||
lspDoc.of({ doc: 1, path: "/p/A.java", language: "java", uiMode: "Java", readOnly: false }),
|
||||
...extensions,
|
||||
],
|
||||
}),
|
||||
});
|
||||
document.body.append(view.dom);
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
return view;
|
||||
}
|
||||
|
||||
describe("semantic decorations vs the syntax highlighter", () => {
|
||||
it("puts the semantic mark inside the syntax span, whichever is added last", async () => {
|
||||
vi.useFakeTimers();
|
||||
for (const extensions of [
|
||||
[semanticExtension(), syntaxMark("tok-variableName")],
|
||||
[syntaxMark("tok-variableName"), semanticExtension()],
|
||||
]) {
|
||||
const view = await editor(extensions);
|
||||
const sem = view.contentDOM.querySelector(".cm-sem-property");
|
||||
expect(sem).not.toBeNull();
|
||||
// Inner nodes win their own colour: the field must not be wrapped by a
|
||||
// syntax span that re-sets `color`.
|
||||
expect(sem!.children.length).toBe(0);
|
||||
expect(lspSemanticTokens).toHaveBeenCalled();
|
||||
view.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -96,12 +96,15 @@ export function semanticRanges(doc: Text, tokens: SemanticTokens, rainbow = fals
|
||||
const names: string[] = [];
|
||||
for (let b = 0; b < tokenModifiers.length; b++) if (mods & (1 << b)) names.push(tokenModifiers[b]!);
|
||||
const classes: string[] = [];
|
||||
let base = TYPE_CLASS[type];
|
||||
let base = Object.hasOwn(TYPE_CLASS, type) ? TYPE_CLASS[type] : undefined;
|
||||
// jdtls marks constructors as a class with a `constructor` modifier; IDEA colours them as methods.
|
||||
if (names.includes("constructor")) base = "function";
|
||||
const constant =
|
||||
names.includes("constant") || (type === "variable" && names.includes("readonly") && names.includes("static"));
|
||||
if (constant && (type === "variable" || type === "property")) base = "constant";
|
||||
if (base && base !== "variable") classes.push(`cm-sem-${base}`);
|
||||
for (const n of names) if (MODIFIER_CLASS[n]) classes.push(`cm-sem-${MODIFIER_CLASS[n]}`);
|
||||
// `hasOwn`: servers send names like `constructor` (jdtls) that `Object.prototype` also has.
|
||||
for (const n of names) if (Object.hasOwn(MODIFIER_CLASS, n)) classes.push(`cm-sem-${MODIFIER_CLASS[n]}`);
|
||||
if (language === "python" && names.includes("static")) classes.push("cm-sem-python-static");
|
||||
const local =
|
||||
rainbow &&
|
||||
@@ -197,7 +200,11 @@ const semanticPlugin = ViewPlugin.fromClass(
|
||||
|
||||
export function semanticExtension(): Extension {
|
||||
// Higher-precedence decoration sources create the *inner* DOM nodes, so this
|
||||
// must outrank Lezer's highlighter (default precedence) for semantic colours
|
||||
// to win; they only set colour / style, never backgrounds.
|
||||
return [semanticField, semanticPlugin, Prec.high(EditorView.decorations.from(semanticField))];
|
||||
// must outrank Lezer's highlighter for semantic colours to win; they only set
|
||||
// colour / style, never backgrounds. `Prec.highest`, not `Prec.high`: the
|
||||
// highlighter (`treeHighlighter` in @codemirror/language) is itself
|
||||
// `Prec.high`, and at equal precedence the later source ends up outside —
|
||||
// its inner span then re-set the colour (a field's `variableName` grey hid
|
||||
// `cm-sem-property`).
|
||||
return [semanticField, semanticPlugin, Prec.highest(EditorView.decorations.from(semanticField))];
|
||||
}
|
||||
@@ -274,7 +274,6 @@ export const lspTheme = EditorView.theme({
|
||||
textUnderlineOffset: "2px",
|
||||
cursor: "pointer",
|
||||
},
|
||||
".cm-lsp-link *": { color: "var(--link)" },
|
||||
".cm-lsp-occurrence": {
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
},
|
||||
@@ -383,6 +382,8 @@ export const lspTheme = EditorView.theme({
|
||||
},
|
||||
]),
|
||||
),
|
||||
// After the semantic classes: the link wraps their (innermost) spans, and its colour must win.
|
||||
".cm-lsp-link *": { color: "var(--link)" },
|
||||
|
||||
...markdown,
|
||||
});
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
import { AnalysisDialogHost } from "./dialogs";
|
||||
import { resetDuplicates } from "./duplicates";
|
||||
import { DuplicatesHeaderActions, DuplicatesView } from "./DuplicatesView";
|
||||
import { installInspectionProfileSync, resetInspection } from "./inspect";
|
||||
import { installInspectionProfileSync, resetInspection, runInspection } from "./inspect";
|
||||
import { defaultScope } from "./scope";
|
||||
import { InspectionHeaderActions, InspectionView, useInspectionHeaderMenu } from "./InspectionView";
|
||||
|
||||
export function activate(): () => void {
|
||||
@@ -57,6 +58,16 @@ export function activate(): () => void {
|
||||
keywords: ["inspection", "analyze", "diagnostics", "problems"],
|
||||
run: () => void showInspectCodeDialog(),
|
||||
},
|
||||
{
|
||||
// IDEA's "Inspect Code with Editor Settings": the current file, no scope dialog.
|
||||
id: "analyze.inspectFile",
|
||||
title: "Inspect Current File",
|
||||
category: "Code",
|
||||
icon: "toolwindow-inspection",
|
||||
when: "projectOpen && textEditorActive",
|
||||
keywords: ["inspect code with editor settings", "inspection", "analyze file"],
|
||||
run: () => runInspection(defaultScope("file")),
|
||||
},
|
||||
{
|
||||
id: "code.cleanup",
|
||||
title: "Code Cleanup…",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/** LightEdit status bar entry: opens the current file's folder as a full project. */
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useT } from "@/platform/i18n";
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { BarButton, Icon } from "@/ui";
|
||||
|
||||
export const LIGHT_EDIT_OPEN_PROJECT = "lightEdit.openProject";
|
||||
|
||||
export function LightEditStatus() {
|
||||
const t = useT();
|
||||
const lightEdit = useProject((s) => s.lightEdit);
|
||||
const path = useEditorRegistry((s) => s.active?.ctx.path);
|
||||
if (!lightEdit || !path || isVirtualUri(path)) return null;
|
||||
return (
|
||||
<BarButton
|
||||
emphasis
|
||||
tooltip={t("app.lightEdit.openProjectTooltip", { folder: dirname(path) })}
|
||||
onClick={() => void executeAction(LIGHT_EDIT_OPEN_PROJECT)}
|
||||
>
|
||||
<Icon name="folder-open" size={14} />
|
||||
{t("app.lightEdit.openProject")}
|
||||
</BarButton>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { provideEditorService, type EditorInput, type OpenEditorTab } from "@/workbench/contributions";
|
||||
import { installLightEditAutoClose } from "../windows";
|
||||
|
||||
/** An editor service whose tabs the test drives. */
|
||||
function fakeEditor() {
|
||||
const listeners = new Set<(input: EditorInput | null) => void>();
|
||||
let tabs: string[] = [];
|
||||
provideEditorService({
|
||||
openFile: async () => {},
|
||||
openInput: async () => {},
|
||||
activePath: () => tabs.at(-1) ?? null,
|
||||
activeCursor: () => null,
|
||||
saveAll: async () => {},
|
||||
openTabs: () => tabs.map((path) => ({ input: { kind: "file", key: path, path } }) as OpenEditorTab),
|
||||
onActiveInputChange: (fn) => {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
});
|
||||
return {
|
||||
setTabs(next: string[]) {
|
||||
tabs = next;
|
||||
const path = next.at(-1);
|
||||
for (const fn of listeners) fn(path ? ({ kind: "file", key: path, path } as EditorInput) : null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("LightEdit window", () => {
|
||||
const close = vi.fn(async () => {});
|
||||
let dispose: () => void = () => {};
|
||||
beforeEach(() => close.mockClear());
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
});
|
||||
|
||||
it("closes when its last editor tab closes", () => {
|
||||
const editor = fakeEditor();
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
dispose = installLightEditAutoClose(close);
|
||||
editor.setTabs(["/x/a.txt", "/x/b.txt"]);
|
||||
editor.setTabs(["/x/a.txt"]);
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
editor.setTabs([]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stays open in a project window or while leaving LightEdit", () => {
|
||||
const editor = fakeEditor();
|
||||
dispose = installLightEditAutoClose(close);
|
||||
useProject.setState({ project: { root: "/p", name: "p" }, lightEdit: false } as never);
|
||||
editor.setTabs(["/p/a.rs"]);
|
||||
editor.setTabs([]);
|
||||
// Closing the project (or the LightEdit session) closes every tab after `lightEdit` is off.
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
editor.setTabs([]);
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,16 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const windowOpenProject = vi.fn();
|
||||
const windowOpenFiles = vi.fn();
|
||||
const windowTakeLaunch = vi.fn();
|
||||
const openProject = vi.fn(async (path: string) => ({ root: path, name: path, isGit: false, settings: {} }));
|
||||
// The backend answers with the global settings, here: whatever the test set up.
|
||||
const lightEditOpen = vi.fn(async (_path: string) => ({ status: "ok", data: useProject.getState().settings ?? {} }));
|
||||
const fsReadDir = vi.fn(async (_path: string) => ({ status: "ok", data: [] }));
|
||||
const openProject = vi.fn(async (path: string) => {
|
||||
const project = { root: path, name: path, isGit: false, settings: {} };
|
||||
useProject.setState({ project, lightEdit: false } as never);
|
||||
return project;
|
||||
});
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
@@ -12,7 +20,10 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
commands: {
|
||||
...real.commands,
|
||||
windowOpenProject: (...a: unknown[]) => windowOpenProject(...a),
|
||||
windowOpenFiles: (...a: unknown[]) => windowOpenFiles(...a),
|
||||
windowTakeLaunch: () => windowTakeLaunch(),
|
||||
lightEditOpen: (p: string) => lightEditOpen(p),
|
||||
fsReadDir: (p: string) => fsReadDir(p),
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -21,45 +32,187 @@ vi.mock("@/platform/project", async (orig) => {
|
||||
return { ...real, openProject: (p: string) => openProject(p) };
|
||||
});
|
||||
|
||||
const { openProjectInWindow, consumeLaunch } = await import("../windows");
|
||||
const { openProjectInWindow, consumeLaunch, openFiles, openPaths, openLightEditFileAsProject, windowActions } =
|
||||
await import("../windows");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { provideEditorService } = await import("@/workbench/contributions");
|
||||
|
||||
const opened: string[] = [];
|
||||
let activePath: string | null = null;
|
||||
provideEditorService({
|
||||
openFile: async (path, options) => void opened.push(`${path}${options?.focus ? " (focus)" : ""}`),
|
||||
openInput: async () => {},
|
||||
activePath: () => activePath,
|
||||
activeCursor: () => null,
|
||||
saveAll: async () => {},
|
||||
});
|
||||
|
||||
const ok = (data: unknown) => ({ status: "ok", data });
|
||||
const projectState = (root: string) => ({ project: { root, name: root, isGit: false, settings: {} } });
|
||||
|
||||
beforeEach(() => {
|
||||
windowOpenProject.mockReset();
|
||||
windowTakeLaunch.mockReset();
|
||||
openProject.mockClear();
|
||||
useProject.setState({ project: null });
|
||||
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch]) f.mockReset();
|
||||
for (const f of [lightEditOpen, fsReadDir, openProject]) f.mockClear();
|
||||
opened.length = 0;
|
||||
activePath = null;
|
||||
useProject.setState({ project: null, lightEdit: false, settings: null } as never);
|
||||
});
|
||||
|
||||
describe("openProjectInWindow", () => {
|
||||
it("opens in this window when the backend says `current`", async () => {
|
||||
windowOpenProject.mockResolvedValue({ status: "ok", data: { kind: "current" } });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", false, []);
|
||||
expect(openProject).toHaveBeenCalledWith("/p/a");
|
||||
});
|
||||
|
||||
it("asks for a new window when this one already has a project", async () => {
|
||||
useProject.setState({ project: { root: "/p/b", name: "b", isGit: false, settings: {} } });
|
||||
windowOpenProject.mockResolvedValue({ status: "ok", data: { kind: "opened", label: "project-1" } });
|
||||
useProject.setState(projectState("/p/b") as never);
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, []);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("asks for a new window from a LightEdit window", async () => {
|
||||
useProject.setState({ lightEdit: true });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, []);
|
||||
});
|
||||
|
||||
it("does nothing locally when another window was focused", async () => {
|
||||
windowOpenProject.mockResolvedValue({ status: "ok", data: { kind: "focused", label: "main" } });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "focused", label: "main" }));
|
||||
await openProjectInWindow("/p/a", true);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("loose files (LightEdit)", () => {
|
||||
it("turns a window without a project into LightEdit when no LightEdit window exists", async () => {
|
||||
windowOpenFiles.mockResolvedValue(ok(["/x/a.txt", "/y/b.md"]));
|
||||
await openFiles(["/x/a.txt", "/y/b.md"]);
|
||||
expect(windowOpenFiles).toHaveBeenCalledWith(["/x/a.txt", "/y/b.md"]);
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(useProject.getState()).toMatchObject({ project: null, lightEdit: true });
|
||||
expect(opened).toEqual(["/x/a.txt", "/y/b.md (focus)"]);
|
||||
});
|
||||
|
||||
it("leaves files to the existing LightEdit window or their project's window", async () => {
|
||||
windowOpenFiles.mockResolvedValue(ok([]));
|
||||
await openFiles(["/x/a.txt"]);
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(opened).toEqual([]);
|
||||
expect(useProject.getState().lightEdit).toBe(false);
|
||||
});
|
||||
|
||||
it("opens only the files the backend leaves to this window", async () => {
|
||||
windowOpenFiles.mockResolvedValue(ok(["/x/b.txt"]));
|
||||
await openFiles(["/p/a.rs", "/x/b.txt"]);
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/b.txt");
|
||||
expect(opened).toEqual(["/x/b.txt (focus)"]);
|
||||
});
|
||||
|
||||
it("adds tabs to this LightEdit window", async () => {
|
||||
useProject.setState({ lightEdit: true });
|
||||
windowOpenFiles.mockResolvedValue(ok(["/x/c.txt"]));
|
||||
await openFiles(["/x/c.txt"]);
|
||||
expect(windowOpenFiles).toHaveBeenCalledWith(["/x/c.txt"]);
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(opened).toEqual(["/x/c.txt (focus)"]);
|
||||
});
|
||||
|
||||
it("opens files in the project's editor in a project window", async () => {
|
||||
useProject.setState(projectState("/p") as never);
|
||||
await openFiles(["/elsewhere/a.txt"]);
|
||||
expect(windowOpenFiles).not.toHaveBeenCalled();
|
||||
expect(opened).toEqual(["/elsewhere/a.txt (focus)"]);
|
||||
expect(useProject.getState().lightEdit).toBe(false);
|
||||
});
|
||||
|
||||
it("routes dropped files to LightEdit and the dropped folder to a project", async () => {
|
||||
windowOpenFiles.mockResolvedValue(ok(["/x/a.txt"]));
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
useProject.setState({ settings: { general: { openProjectIn: "new" } } } as never);
|
||||
await openPaths(["/x/a.txt", "/work/app"], async (p) => p === "/work/app");
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/work/app", true, []);
|
||||
});
|
||||
|
||||
it("opens a dropped folder alone exactly as before", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openPaths(["/work/app"], async () => true);
|
||||
expect(windowOpenFiles).not.toHaveBeenCalled();
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(openProject).toHaveBeenCalledWith("/work/app");
|
||||
});
|
||||
|
||||
it("classifies paths through the file system by default", async () => {
|
||||
fsReadDir.mockResolvedValueOnce({ status: "error", error: { kind: "notFound", message: "not a dir" } } as never);
|
||||
windowOpenFiles.mockResolvedValue(ok(["/x/a.txt"]));
|
||||
await openPaths(["/x/a.txt"]);
|
||||
expect(fsReadDir).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Open Containing Folder as Project", () => {
|
||||
it("is an action available in LightEdit only", () => {
|
||||
const action = windowActions().find((a) => a.id === "lightEdit.openProject");
|
||||
expect(action?.when).toBe("lightEdit");
|
||||
expect(windowActions().some((a) => a.id === "file.openFile")).toBe(true);
|
||||
});
|
||||
|
||||
it("opens the folder in a new window with the file, per 'Open project in'", async () => {
|
||||
useProject.setState({ lightEdit: true, settings: { general: { openProjectIn: "new" } } } as never);
|
||||
activePath = "/x/notes/a.txt";
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openLightEditFileAsProject();
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", true, ["/x/notes/a.txt"]);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("or turns this window into the project and reopens the file there", async () => {
|
||||
useProject.setState({ lightEdit: true, settings: { general: { openProjectIn: "same" } } } as never);
|
||||
activePath = "/x/notes/a.txt";
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openLightEditFileAsProject();
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", false, ["/x/notes/a.txt"]);
|
||||
expect(openProject).toHaveBeenCalledWith("/x/notes");
|
||||
expect(useProject.getState()).toMatchObject({ lightEdit: false, project: { root: "/x/notes" } });
|
||||
expect(opened).toEqual(["/x/notes/a.txt (focus)"]);
|
||||
});
|
||||
|
||||
it("does nothing outside LightEdit", async () => {
|
||||
useProject.setState(projectState("/p") as never);
|
||||
activePath = "/p/a.txt";
|
||||
await openLightEditFileAsProject();
|
||||
expect(windowOpenProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("launch", () => {
|
||||
it("opens the pending project once", async () => {
|
||||
windowTakeLaunch.mockResolvedValueOnce({ project: "/p/launch" }).mockResolvedValueOnce(null);
|
||||
windowTakeLaunch.mockResolvedValueOnce({ project: "/p/launch", files: [] }).mockResolvedValueOnce(null);
|
||||
await consumeLaunch();
|
||||
await consumeLaunch();
|
||||
expect(openProject).toHaveBeenCalledTimes(1);
|
||||
expect(openProject).toHaveBeenCalledWith("/p/launch");
|
||||
});
|
||||
|
||||
it("opens launched files in LightEdit without a project", async () => {
|
||||
windowTakeLaunch.mockResolvedValueOnce({ project: null, files: ["/x/a.txt"] });
|
||||
await consumeLaunch();
|
||||
expect(windowOpenFiles).not.toHaveBeenCalled();
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(opened).toEqual(["/x/a.txt (focus)"]);
|
||||
});
|
||||
|
||||
it("opens launched files in the launched project", async () => {
|
||||
windowTakeLaunch.mockResolvedValueOnce({ project: "/x/notes", files: ["/x/notes/a.txt"] });
|
||||
await consumeLaunch();
|
||||
expect(openProject).toHaveBeenCalledWith("/x/notes");
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(opened).toEqual(["/x/notes/a.txt (focus)"]);
|
||||
});
|
||||
});
|
||||
@@ -99,9 +99,9 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
try {
|
||||
const ctx = await commands.windowCloseContext();
|
||||
const s = useProject.getState();
|
||||
// Closing the last project window closes its project and shows the welcome screen
|
||||
// (to open another one); closing the welcome screen, or quitting, closes the window.
|
||||
if (!ctx.quitting && ctx.windows <= 1 && s.project) {
|
||||
// Closing the last project (or LightEdit) window closes its project and shows the welcome
|
||||
// screen (to open another one); closing the welcome screen, or quitting, closes the window.
|
||||
if (!ctx.quitting && ctx.windows <= 1 && (s.project || s.lightEdit)) {
|
||||
if (await confirmLeave(deps)) await closeProject();
|
||||
return false;
|
||||
}
|
||||
@@ -148,7 +148,7 @@ export function installCloseGuard(deps: CloseDeps = defaultDeps): () => void {
|
||||
else dirtyDocs.delete(e.doc);
|
||||
}),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) dirtyDocs.clear();
|
||||
if (s.project?.root !== prev.project?.root || s.lightEdit !== prev.lightEdit) dirtyDocs.clear();
|
||||
}),
|
||||
provideLeaveProjectGuard(() => confirmLeave(deps)),
|
||||
];
|
||||
|
||||
@@ -2,19 +2,20 @@
|
||||
* Desktop shell integration: native menu bridge, multi-window, window title,
|
||||
* close / quit guards, About, Keymap Reference, logs, update check and i18n wiring.
|
||||
*/
|
||||
import { registerOverlay } from "@/workbench/contributions";
|
||||
import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
|
||||
import { AboutOverlay } from "./AboutDialog";
|
||||
import { appActions, checkForUpdatesOnStartup, updateActions } from "./appActions";
|
||||
import { installCloseGuard } from "./closeGuard";
|
||||
import { InvalidateCachesOverlay, registerInvalidateCachesActions } from "./InvalidateCaches";
|
||||
import { buildInfo } from "./host";
|
||||
import { KeymapReferenceOverlay } from "./KeymapReference";
|
||||
import { LightEditStatus } from "./LightEditStatus";
|
||||
import { installLocaleSync, registerLocalizedActions } from "./locale";
|
||||
import { installMenuBridge } from "./menuBridge";
|
||||
import { NewProjectOverlay } from "./NewProject";
|
||||
import { projectActions, registerPowerSaveBanner } from "./projectActions";
|
||||
import { installWindowTitle } from "./title";
|
||||
import { installLaunchHandling, windowActions } from "./windows";
|
||||
import { installLaunchHandling, installLightEditAutoClose, windowActions } from "./windows";
|
||||
|
||||
/** The UI locale of a secondary (Settings) window. */
|
||||
export const activateLocale = installLocaleSync;
|
||||
@@ -27,6 +28,13 @@ export function activate(): () => void {
|
||||
registerOverlay({ id: "app.keymapReference", component: KeymapReferenceOverlay }),
|
||||
registerOverlay({ id: "app.invalidateCaches", component: InvalidateCachesOverlay }),
|
||||
registerOverlay({ id: "app.newProject", component: NewProjectOverlay }),
|
||||
registerStatusItem({
|
||||
id: "app.lightEdit",
|
||||
align: "left",
|
||||
priority: 20,
|
||||
component: LightEditStatus,
|
||||
lightEdit: true,
|
||||
}),
|
||||
registerLocalizedActions(projectActions),
|
||||
registerPowerSaveBanner(),
|
||||
registerInvalidateCachesActions(),
|
||||
@@ -34,6 +42,7 @@ export function activate(): () => void {
|
||||
installWindowTitle(),
|
||||
installCloseGuard(),
|
||||
installLaunchHandling(),
|
||||
installLightEditAutoClose(),
|
||||
];
|
||||
let disposed = false;
|
||||
void buildInfo().then((b) => {
|
||||
|
||||
@@ -2,14 +2,26 @@
|
||||
* Multi-window: one project per window. New windows are created by the
|
||||
* backend (`window_open_project` / `window_new`) and told what to open via a
|
||||
* pending launch, taken here on startup and on `openidea://launch`.
|
||||
*
|
||||
* Loose files opened without a project (dropped on the Welcome screen, File ›
|
||||
* Open File…, a file path on the command line) open in LightEdit: a window with
|
||||
* editor tabs only. One LightEdit window collects them all.
|
||||
*/
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename, confirmLeaveProject, openProject, provideStartupLaunch, useProject } from "@/platform/project";
|
||||
import { connectRemote } from "@/platform/remote";
|
||||
import {
|
||||
basename,
|
||||
confirmLeaveProject,
|
||||
dirname,
|
||||
openLightEdit,
|
||||
openProject,
|
||||
provideStartupLaunch,
|
||||
useProject,
|
||||
} from "@/platform/project";
|
||||
import { connectRemote, isRemoteWindow } from "@/platform/remote";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { chooseProjectWindow } from "@/workbench/projectWindow";
|
||||
|
||||
export const LAUNCH_EVENT = "openidea://launch";
|
||||
@@ -24,59 +36,126 @@ function desktopOnly(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async function openHere(path: string) {
|
||||
if (useProject.getState().project?.root === path) return;
|
||||
if (!(await confirmLeaveProject())) return;
|
||||
function openFailed(path: string, e: unknown) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
body: errorText(e),
|
||||
key: `app.open:${path}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** Opens project `path` in this window; true once it is this window's project. */
|
||||
async function openHere(path: string): Promise<boolean> {
|
||||
if (useProject.getState().project?.root === path) return true;
|
||||
if (!(await confirmLeaveProject())) return false;
|
||||
try {
|
||||
await openProject(path);
|
||||
return true;
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
body: errorText(e),
|
||||
key: `app.open:${path}`,
|
||||
});
|
||||
openFailed(path, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens `files` as editor tabs of this window, focusing the last. */
|
||||
async function openInEditor(files: readonly string[]): Promise<void> {
|
||||
for (const [i, path] of files.entries())
|
||||
await editorService()
|
||||
.openFile(path, { focus: i === files.length - 1 })
|
||||
.catch((e) => console.warn(`could not open ${path}`, e));
|
||||
}
|
||||
|
||||
/** Opens `files` in this window: in its project's editor or, without one, in LightEdit. */
|
||||
async function openFilesHere(files: readonly string[]): Promise<void> {
|
||||
const s = useProject.getState();
|
||||
if (!s.project && !s.lightEdit) {
|
||||
try {
|
||||
await openLightEdit(files[0]!);
|
||||
} catch (e) {
|
||||
return openFailed(files[0]!, e);
|
||||
}
|
||||
}
|
||||
await openInEditor(files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens loose `files`: in this window's local project; else a file inside a project open in
|
||||
* another window opens there and the rest in LightEdit (this window's session, the LightEdit
|
||||
* window, or this window turns into one; a remote project window gets a new one).
|
||||
*/
|
||||
export async function openFiles(files: readonly string[]): Promise<void> {
|
||||
if (!files.length) return;
|
||||
const s = useProject.getState();
|
||||
if (s.project && !isRemoteWindow()) return openInEditor(files);
|
||||
if (desktopOnly()) return;
|
||||
try {
|
||||
const here = await call(commands.windowOpenFiles([...files]));
|
||||
if (here.length) await openFilesHere(here);
|
||||
} catch (e) {
|
||||
openFailed(files[0]!, e);
|
||||
}
|
||||
}
|
||||
|
||||
const pathIsDir = (path: string) => call(commands.fsReadDir(path)).then(() => true);
|
||||
|
||||
/** Opens dropped paths: files as loose files ({@link openFiles}), the first folder as a project. */
|
||||
export async function openPaths(
|
||||
paths: readonly string[],
|
||||
isDir: (path: string) => Promise<boolean> = pathIsDir,
|
||||
): Promise<void> {
|
||||
const kinds = await Promise.all(paths.map((p) => isDir(p).catch(() => false)));
|
||||
const files = paths.filter((_, i) => !kinds[i]);
|
||||
const dir = paths.find((_, i) => kinds[i]);
|
||||
await openFiles(files);
|
||||
if (dir) await openProjectWithPolicy(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `path`, focusing the window that already has it. `newWindow`: always a
|
||||
* new window; otherwise this window unless it already has a project.
|
||||
* new window; otherwise this window unless it already has a project or LightEdit
|
||||
* session. `files` then open in the project's editor.
|
||||
*/
|
||||
export async function openProjectInWindow(path: string, newWindow: boolean): Promise<void> {
|
||||
export async function openProjectInWindow(path: string, newWindow: boolean, files: readonly string[] = []) {
|
||||
if (desktopOnly()) return;
|
||||
const inNew = newWindow || useProject.getState().project !== null;
|
||||
const s = useProject.getState();
|
||||
const inNew = newWindow || s.project !== null || s.lightEdit;
|
||||
try {
|
||||
const outcome = await call(commands.windowOpenProject(path, inNew));
|
||||
if (outcome.kind === "current") await openHere(path);
|
||||
const outcome = await call(commands.windowOpenProject(path, inNew, [...files]));
|
||||
if (outcome.kind === "current" && (await openHere(path))) await openInEditor(files);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
body: errorText(e),
|
||||
key: `app.open:${path}`,
|
||||
});
|
||||
openFailed(path, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens `path` following "Open project in" when this window already has a project. */
|
||||
export async function openProjectWithPolicy(path: string): Promise<void> {
|
||||
/**
|
||||
* Opens `path` following "Open project in" when this window already has a
|
||||
* project or LightEdit session, then `files` in its editor.
|
||||
*/
|
||||
export async function openProjectWithPolicy(path: string, files: readonly string[] = []): Promise<void> {
|
||||
if (desktopOnly()) return;
|
||||
const current = useProject.getState().project;
|
||||
if (!current) return openProjectInWindow(path, false);
|
||||
if (current.root === path) return;
|
||||
const { project: current, lightEdit } = useProject.getState();
|
||||
if (!current && !lightEdit) return openProjectInWindow(path, false, files);
|
||||
if (current?.root === path) return openInEditor(files);
|
||||
const mode = await chooseProjectWindow(basename(path));
|
||||
if (!mode) return;
|
||||
if (mode === "new") return openProjectInWindow(path, true);
|
||||
if (mode === "new") return openProjectInWindow(path, true, files);
|
||||
try {
|
||||
// A window that already has the project is focused instead.
|
||||
const outcome = await call(commands.windowOpenProject(path, false));
|
||||
if (outcome.kind === "current") await openHere(path);
|
||||
const outcome = await call(commands.windowOpenProject(path, false, [...files]));
|
||||
if (outcome.kind === "current" && (await openHere(path))) await openInEditor(files);
|
||||
} catch {
|
||||
await openHere(path);
|
||||
if (await openHere(path)) await openInEditor(files);
|
||||
}
|
||||
}
|
||||
|
||||
/** LightEdit: opens the current file's folder as a project ("Open project in" applies) and the file there. */
|
||||
export async function openLightEditFileAsProject(): Promise<void> {
|
||||
if (!useProject.getState().lightEdit) return;
|
||||
const path = maybeEditorService()?.activePath();
|
||||
if (path) await openProjectWithPolicy(dirname(path), [path]);
|
||||
}
|
||||
|
||||
/** System Settings › Project › "Default directory" for folder pickers. */
|
||||
export function defaultProjectDirectory(): string | undefined {
|
||||
return useProject.getState().settings?.general?.defaultProjectDirectory?.trim() || undefined;
|
||||
@@ -89,11 +168,20 @@ async function pickFolder(title: string): Promise<string | null> {
|
||||
return path ?? null;
|
||||
}
|
||||
|
||||
/** Takes this window's pending launch (if any) and opens its project. */
|
||||
async function pickFiles(title: string): Promise<string[]> {
|
||||
const { open } = await import("@tauri-apps/plugin-dialog");
|
||||
const picked = await open({ directory: false, multiple: true, title, defaultPath: defaultProjectDirectory() });
|
||||
return picked === null ? [] : Array.isArray(picked) ? picked : [picked];
|
||||
}
|
||||
|
||||
/** Takes this window's pending launch (if any) and opens its project and files. */
|
||||
export async function consumeLaunch(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const launch = await commands.windowTakeLaunch().catch(() => null);
|
||||
if (launch?.project) await openHere(launch.project);
|
||||
const files = launch?.files ?? [];
|
||||
if (launch?.project) {
|
||||
if (await openHere(launch.project)) await openInEditor(files);
|
||||
} else if (files.length) await openFilesHere(files);
|
||||
else if (launch?.remote) {
|
||||
const { sshConfig, path } = launch.remote;
|
||||
await connectRemote(sshConfig, path).catch((e) =>
|
||||
@@ -121,6 +209,36 @@ export function windowActions(): Action[] {
|
||||
if (path) await openProjectInWindow(path, true);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "file.openFile",
|
||||
title: t("app.action.openFile"),
|
||||
category: t("app.category.file"),
|
||||
icon: "file",
|
||||
keywords: ["file", "light edit"],
|
||||
run: async () => {
|
||||
if (desktopOnly()) return;
|
||||
await openFiles(await pickFiles(t("app.window.pickFileTitle")));
|
||||
},
|
||||
},
|
||||
{
|
||||
// Files and folders dropped on the Welcome screen.
|
||||
id: "file.openPaths",
|
||||
title: "Open Paths",
|
||||
category: t("app.category.file"),
|
||||
hidden: true,
|
||||
run: async (c) => {
|
||||
if (Array.isArray(c.arg)) await openPaths(c.arg.filter((p): p is string => typeof p === "string"));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "lightEdit.openProject",
|
||||
title: t("app.action.lightEditOpenProject"),
|
||||
category: t("app.category.file"),
|
||||
icon: "folder-open",
|
||||
keywords: ["light edit", "project", "folder"],
|
||||
when: "lightEdit",
|
||||
run: openLightEditFileAsProject,
|
||||
},
|
||||
{
|
||||
id: "file.openRecentProject",
|
||||
title: t("app.action.openRecentProject"),
|
||||
@@ -178,6 +296,25 @@ export function windowActions(): Action[] {
|
||||
];
|
||||
}
|
||||
|
||||
async function closeThisWindow(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const { getCurrentWindow } = await import("@tauri-apps/api/window");
|
||||
await getCurrentWindow().close();
|
||||
}
|
||||
|
||||
/**
|
||||
* LightEdit: closing its last editor tab closes the window (through the close guard,
|
||||
* so the last window shows the Welcome screen instead).
|
||||
*/
|
||||
export function installLightEditAutoClose(closeWindow: () => Promise<void> = closeThisWindow): () => void {
|
||||
const editor = maybeEditorService();
|
||||
const off = editor?.onActiveInputChange?.((input) => {
|
||||
if (input || !useProject.getState().lightEdit || editor?.openTabs?.().length) return;
|
||||
void closeWindow().catch((e) => console.warn("could not close the window", e));
|
||||
});
|
||||
return () => off?.();
|
||||
}
|
||||
|
||||
export function installLaunchHandling(): () => void {
|
||||
if (!isTauri()) return () => {};
|
||||
let disposed = false;
|
||||
|
||||
@@ -92,6 +92,40 @@
|
||||
color: var(--fg-search-match, inherit);
|
||||
border-radius: 2px;
|
||||
}
|
||||
/* Lezer classHighlighter tokens of usage lines (same colours as Find in Files results). */
|
||||
.preview :global(.tok-keyword),
|
||||
.preview :global(.tok-modifier),
|
||||
.preview :global(.tok-controlKeyword),
|
||||
.preview :global(.tok-operatorKeyword) {
|
||||
color: var(--syn-keyword);
|
||||
}
|
||||
.preview :global(.tok-string),
|
||||
.preview :global(.tok-string2) {
|
||||
color: var(--syn-string);
|
||||
}
|
||||
.preview :global(.tok-number),
|
||||
.preview :global(.tok-bool),
|
||||
.preview :global(.tok-atom) {
|
||||
color: var(--syn-number);
|
||||
}
|
||||
.preview :global(.tok-typeName),
|
||||
.preview :global(.tok-className),
|
||||
.preview :global(.tok-namespace) {
|
||||
color: var(--syn-type);
|
||||
}
|
||||
.preview :global(.tok-comment) {
|
||||
color: var(--syn-comment);
|
||||
}
|
||||
.preview :global(.tok-meta),
|
||||
.preview :global(.tok-macroName) {
|
||||
color: var(--syn-annotation);
|
||||
}
|
||||
.preview :global(.tok-propertyName) {
|
||||
color: var(--syn-property);
|
||||
}
|
||||
.preview :global(.tok-variableName.tok-definition) {
|
||||
color: var(--syn-function);
|
||||
}
|
||||
|
||||
.note {
|
||||
min-width: 0;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import { tokenSpans, useLineTokens } from "@/editor/lineTokens";
|
||||
import { formatMessage, useTx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
@@ -46,12 +47,13 @@ type Node =
|
||||
| { kind: "usage"; key: string; usage: Usage };
|
||||
|
||||
export function UsagePreview({ usage }: { usage: Usage }) {
|
||||
const { text, from, to } = trimPreview(usage);
|
||||
const { text, textCol, from, to } = trimPreview(usage);
|
||||
const tokens = useLineTokens({ path: usage.path, line: usage.line, col: textCol }, text);
|
||||
return (
|
||||
<span className={styles.preview}>
|
||||
{text.slice(0, from)}
|
||||
<mark className={styles.match}>{text.slice(from, to)}</mark>
|
||||
{text.slice(to)}
|
||||
{tokenSpans(text, 0, from, tokens, "b:")}
|
||||
<mark className={styles.match}>{tokenSpans(text, from, to, tokens, "m:")}</mark>
|
||||
{tokenSpans(text, to, text.length, tokens, "a:")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
|
||||
vi.mock(import("@/platform/ipc"), async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
commands: { fsReadText: (path: string) => path } as never,
|
||||
call: (async () => "/**\n * Uses foo()\n */\n const x = foo();\n") as never,
|
||||
}));
|
||||
vi.mock(import("@/editor/api"), async (importOriginal) => ({ ...(await importOriginal()), editorsFor: () => [] }));
|
||||
|
||||
const { UsagePreview } = await import("./UsagesView");
|
||||
|
||||
describe("UsagePreview", () => {
|
||||
it("colours the usage line with its file as context", async () => {
|
||||
const { container } = render(
|
||||
<UsagePreview usage={{ path: "/p/a.ts", line: 3, col: 12, endCol: 15, text: " const x = foo();" }} />,
|
||||
);
|
||||
await waitFor(() => expect(container.querySelector(".tok-keyword")?.textContent).toBe("const"));
|
||||
expect(container.querySelector("mark")?.textContent).toBe("foo");
|
||||
expect(container.textContent).toBe("const x = foo();");
|
||||
});
|
||||
|
||||
it("colours a usage inside a doc comment as a comment", async () => {
|
||||
const { container } = render(
|
||||
<UsagePreview usage={{ path: "/p/a.ts", line: 1, col: 8, endCol: 11, text: " * Uses foo()" }} />,
|
||||
);
|
||||
await waitFor(() => expect(container.querySelector("mark .tok-comment")?.textContent).toBe("foo"));
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Find Usages (⌥F7 → "usages" tool window) and Show Usages (⌥⌘F7 → popup). */
|
||||
import { create } from "zustand";
|
||||
import type { Location, ReferencesIncomplete, RequestId } from "@/bindings";
|
||||
import { clearLineTokens } from "@/editor/lineTokens";
|
||||
import { commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { toolWindowService } from "@/workbench/contributions";
|
||||
import {
|
||||
@@ -57,12 +58,12 @@ export function usageCount(groups: readonly UsageGroup[]): number {
|
||||
}
|
||||
|
||||
/** Trims leading whitespace of a preview line, shifting the match range accordingly. */
|
||||
export function trimPreview(u: Usage): { text: string; from: number; to: number } {
|
||||
export function trimPreview(u: Usage): { text: string; textCol: number; from: number; to: number } {
|
||||
const lead = u.text.length - u.text.trimStart().length;
|
||||
const text = u.text.trim();
|
||||
const from = Math.max(0, u.col - lead);
|
||||
const to = Math.max(from, Math.min(text.length, u.endCol - lead));
|
||||
return { text, from, to };
|
||||
return { text, textCol: lead, from, to };
|
||||
}
|
||||
|
||||
export interface UsageSearch {
|
||||
@@ -170,6 +171,8 @@ export function incompleteNote(reason: ReferencesIncomplete, word: string | null
|
||||
* Cancel with `commands.cancelRequest(request)`.
|
||||
*/
|
||||
export async function fetchUsages(c: CaretContext, request: RequestId = nextRequestId()): Promise<FetchedUsages> {
|
||||
// Usage lines are read afresh: so are the files their syntax colours come from.
|
||||
clearLineTokens();
|
||||
let locs: Location[];
|
||||
let note: string | null = null;
|
||||
try {
|
||||
@@ -259,6 +262,7 @@ export async function showUsageResults(arg: unknown) {
|
||||
const base = { id, symbol, rerun: null };
|
||||
openUsageTab({ ...base, loading: true, groups: [], error: null, note: null });
|
||||
toolWindowService().show("usages");
|
||||
clearLineTokens();
|
||||
const files = await readManyFileLines(locs.map((l) => l.path));
|
||||
replaceUsageTab(id, { ...base, loading: false, groups: groupUsages(locs, files), error: null, note: null });
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ describe("usages", () => {
|
||||
]);
|
||||
expect(usageCount(groups)).toBe(3);
|
||||
expect(groups[0]!.usages[0]!.text).toBe("");
|
||||
expect(trimPreview(groups[1]!.usages[1]!)).toEqual({ text: "const x = foo();", from: 10, to: 13 });
|
||||
expect(trimPreview(groups[1]!.usages[1]!)).toEqual({ text: "const x = foo();", textCol: 2, from: 10, to: 13 });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { call, commands, isCancelled, isTauri, nextRequestId, type RunConfig, ty
|
||||
import { downloadJdkActions } from "@/platform/jdk";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
|
||||
import { maybeEditorService, notifications, showStatusInfo, toolWindowService } from "@/workbench/contributions";
|
||||
import { canPlaceBreakpoint } from "./breakpoints/languages";
|
||||
import {
|
||||
removeAllBreakpoints,
|
||||
@@ -22,6 +22,7 @@ import { debugUnsupportedReason, launchConfigFor } from "./launch";
|
||||
import { isRemoteConfig, REMOTE_JVM, remoteAttachConfig, remoteJvmTarget } from "./remote";
|
||||
import {
|
||||
activeSession,
|
||||
evaluate,
|
||||
isLive,
|
||||
rerunSession,
|
||||
revealFrame,
|
||||
@@ -34,7 +35,9 @@ import {
|
||||
type DebugSession,
|
||||
} from "./state";
|
||||
import { focusedDebugView } from "./ui/focusedView";
|
||||
import { expressionAt } from "./editor/valueTooltip";
|
||||
import { browseFocusedConsoleHistory } from "./ui/expressionHistory";
|
||||
import { expressionAt, valueHint } from "./editor/valueTooltip";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { pausedLineTargets, startInlineSmartStep } from "./editor/smartStep";
|
||||
import {
|
||||
openBreakpointsDialog,
|
||||
@@ -147,6 +150,22 @@ function evaluateSeed(): string {
|
||||
return expressionAt(ed.view, sel.head)?.text ?? "";
|
||||
}
|
||||
|
||||
async function quickEvaluate() {
|
||||
const view = activeEditor()?.view;
|
||||
if (!view) return;
|
||||
const sel = view.state.selection.main;
|
||||
const expression = evaluateSeed().trim();
|
||||
if (!expression) return showHint(view, "Nothing to evaluate at the caret");
|
||||
const session = activeSession();
|
||||
try {
|
||||
const value = await evaluate(expression, "hover", session);
|
||||
if (!session) return;
|
||||
showHint(view, () => valueHint(expression, value, session.id), { pos: sel.from, timeout: 60_000 });
|
||||
} catch (e) {
|
||||
showHint(view, e instanceof Error ? e.message : String(e), { pos: sel.from, tone: "error" });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remote JVM Debug in listen mode: the IDE listens and the remote JVM connects; java-debug
|
||||
* then attaches through a loopback relay. Null when cancelled.
|
||||
@@ -592,6 +611,24 @@ export function registerDebugActions(): () => void {
|
||||
when: "debugSessionActive",
|
||||
run: () => openEvaluateDialog(evaluateSeed()),
|
||||
},
|
||||
{
|
||||
id: "debug.browseConsoleHistory",
|
||||
title: "Browse Console History",
|
||||
category: "Debug",
|
||||
keywords: ["history", "previous expressions", "repl"],
|
||||
when: "debugSessionActive",
|
||||
run: () => {
|
||||
if (!browseFocusedConsoleHistory()) showStatusInfo(tx("Focus the debug console input first"));
|
||||
},
|
||||
},
|
||||
{
|
||||
// ⌥⌘F8: the selection (or expression at the caret) evaluated in a value hint, no dialog.
|
||||
id: "debug.quickEvaluate",
|
||||
title: "Quick Evaluate Expression",
|
||||
category: "Debug",
|
||||
when: "debugSessionActive && textEditorActive",
|
||||
run: () => quickEvaluate(),
|
||||
},
|
||||
{
|
||||
id: "debug.showToolWindow",
|
||||
title: "Show Debug Tool Window",
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* evaluates it in the selected frame.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import type { DebugSessionId, Variable } from "@/bindings";
|
||||
import { hoverTooltip, type EditorView } from "@codemirror/view";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { navigationModifierHeld } from "@/platform/navigationModifier";
|
||||
@@ -37,6 +38,46 @@ export function expressionAt(view: EditorView, pos: number): { from: number; to:
|
||||
return { from: line.from + start, to: line.from + end, text };
|
||||
}
|
||||
|
||||
/** IDEA's value hint: `expression = value {type}`, objects expandable into a variables tree in place. */
|
||||
export function valueHint(
|
||||
expression: string,
|
||||
value: Variable,
|
||||
session: DebugSessionId,
|
||||
): { dom: HTMLElement; destroy: () => void } {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `${styles.valueTooltip} ${selectableText}`;
|
||||
let tree: { unmount(): void } | null = null;
|
||||
if (value.variablesReference > 0) {
|
||||
// IDEA's value hint: the "+" expands the object into a variables tree in place.
|
||||
const expand = document.createElement("button");
|
||||
expand.type = "button";
|
||||
expand.className = styles.valueExpand!;
|
||||
expand.setAttribute("aria-label", tx("Expand value"));
|
||||
expand.setAttribute("aria-expanded", "false");
|
||||
expand.innerHTML = iconMarkup("chevron-right", 12) ?? "";
|
||||
expand.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
expand.addEventListener("click", () => {
|
||||
if (tree) return;
|
||||
expand.remove();
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expression, value, session);
|
||||
});
|
||||
dom.append(expand);
|
||||
}
|
||||
const name = document.createElement("span");
|
||||
name.className = styles.valueName!;
|
||||
name.textContent = `${expression} = `;
|
||||
dom.append(name, inlineValue(value.value, 400));
|
||||
if (value.typeName) {
|
||||
const type = document.createElement("span");
|
||||
type.className = styles.valueType!;
|
||||
type.textContent = ` {${value.typeName}}`;
|
||||
dom.append(type);
|
||||
}
|
||||
return { dom, destroy: () => tree?.unmount() };
|
||||
}
|
||||
|
||||
export function valueTooltip(): Extension {
|
||||
return hoverTooltip(
|
||||
async (view, pos) => {
|
||||
@@ -61,38 +102,7 @@ export function valueTooltip(): Extension {
|
||||
end: expr.to,
|
||||
above: true,
|
||||
create: () => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `${styles.valueTooltip} ${selectableText}`;
|
||||
let tree: { unmount(): void } | null = null;
|
||||
if (value.variablesReference > 0) {
|
||||
// IDEA's value hint: the "+" expands the object into a variables tree in place.
|
||||
const expand = document.createElement("button");
|
||||
expand.type = "button";
|
||||
expand.className = styles.valueExpand!;
|
||||
expand.setAttribute("aria-label", tx("Expand value"));
|
||||
expand.setAttribute("aria-expanded", "false");
|
||||
expand.innerHTML = iconMarkup("chevron-right", 12) ?? "";
|
||||
expand.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
expand.addEventListener("click", () => {
|
||||
if (tree) return;
|
||||
expand.remove();
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expr.text, value, session.id);
|
||||
});
|
||||
dom.append(expand);
|
||||
}
|
||||
const name = document.createElement("span");
|
||||
name.className = styles.valueName!;
|
||||
name.textContent = `${expr.text} = `;
|
||||
dom.append(name, inlineValue(value.value, 400));
|
||||
if (value.typeName) {
|
||||
const type = document.createElement("span");
|
||||
type.className = styles.valueType!;
|
||||
type.textContent = ` {${value.typeName}}`;
|
||||
dom.append(type);
|
||||
}
|
||||
return { dom, destroy: () => tree?.unmount() };
|
||||
return valueHint(expr.text, value, session.id);
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
type DebugSession,
|
||||
} from "../state";
|
||||
import { VariablesView, type VarRoot } from "./VariablesView";
|
||||
import { pushHistory, readHistory, setConsoleHistoryBrowser } from "./expressionHistory";
|
||||
import styles from "./DebugToolWindow.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -542,8 +543,9 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const stick = useRef(true);
|
||||
const [input, setInput] = useState("");
|
||||
const history = useRef<string[]>([]);
|
||||
const history = useRef<string[]>(readHistory("console"));
|
||||
const historyPos = useRef(-1);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
@@ -553,7 +555,8 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
const submit = async () => {
|
||||
const e = input.trim();
|
||||
if (!e) return;
|
||||
history.current = [e, ...history.current.filter((h) => h !== e)].slice(0, 100);
|
||||
pushHistory("console", e);
|
||||
history.current = readHistory("console");
|
||||
historyPos.current = -1;
|
||||
setInput("");
|
||||
appendConsole(session.id, "input", `> ${e}\n`);
|
||||
@@ -565,6 +568,24 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
}
|
||||
};
|
||||
|
||||
/** IDEA's Browse History popup: the expressions typed before, most recent first. */
|
||||
const browseHistory = () => {
|
||||
const el = inputRef.current;
|
||||
const r = el?.getBoundingClientRect();
|
||||
const items: MenuItem[] = history.current.length
|
||||
? history.current.slice(0, 30).map((h, i) => ({
|
||||
id: String(i),
|
||||
label: h.length > 120 ? `${h.slice(0, 120)}…` : h,
|
||||
run: () => {
|
||||
setInput(h);
|
||||
historyPos.current = i;
|
||||
el?.focus();
|
||||
},
|
||||
}))
|
||||
: [{ id: "none", label: "No history", disabled: true }];
|
||||
showContextMenu({ x: r?.left ?? 120, y: (r?.top ?? 200) - 4 }, items);
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
@@ -607,7 +628,10 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
›
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className={styles.evalInput}
|
||||
onFocus={() => setConsoleHistoryBrowser(browseHistory)}
|
||||
onBlur={() => setConsoleHistoryBrowser(null)}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Per-project history of expressions typed into the debugger (breakpoint
|
||||
* conditions, Evaluate), most recent first, as IDEA keeps them.
|
||||
* conditions, Evaluate, the debug console), most recent first, as IDEA keeps them.
|
||||
*/
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
export type HistoryKind = "condition" | "evaluate";
|
||||
export type HistoryKind = "condition" | "evaluate" | "console";
|
||||
|
||||
const PREFIX = "openidea.debugger.history.";
|
||||
const MAX = 50;
|
||||
@@ -36,3 +36,16 @@ export function pushHistory(kind: HistoryKind, expression: string) {
|
||||
// Storage unavailable: no history.
|
||||
}
|
||||
}
|
||||
|
||||
/** Browse History (⌥⌘E) of the focused debug console input, while one has focus. */
|
||||
let browseConsoleHistory: (() => void) | null = null;
|
||||
|
||||
export function setConsoleHistoryBrowser(fn: (() => void) | null) {
|
||||
browseConsoleHistory = fn;
|
||||
}
|
||||
|
||||
export function browseFocusedConsoleHistory(): boolean {
|
||||
if (!browseConsoleHistory) return false;
|
||||
browseConsoleHistory();
|
||||
return true;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, type MenuItem } from "@/ui";
|
||||
import { VIEW_MODES, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
|
||||
import type { SortKey } from "./model";
|
||||
|
||||
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
|
||||
export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
|
||||
@@ -11,7 +12,10 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
|
||||
};
|
||||
}
|
||||
|
||||
export const OPTION_LABELS: Array<[keyof ViewOptions, string]> = [
|
||||
/** The on / off view options. */
|
||||
export type ToggleOption = { [K in keyof ViewOptions]: ViewOptions[K] extends boolean ? K : never }[keyof ViewOptions];
|
||||
|
||||
export const OPTION_LABELS: Array<[ToggleOption, string]> = [
|
||||
["showHidden", "Show Hidden Files"],
|
||||
["showExcluded", "Show Excluded Files"],
|
||||
["compact", "Compact Middle Packages"],
|
||||
@@ -40,6 +44,12 @@ export function ProjectHeaderActions() {
|
||||
);
|
||||
}
|
||||
|
||||
export const SORT_LABELS: Array<[SortKey, string]> = [
|
||||
["name", "Sort by Name"],
|
||||
["type", "Sort by Type"],
|
||||
["modified", "Sort by Modification Time"],
|
||||
];
|
||||
|
||||
/** View options in the header's "⋮" menu (IDEA: Project › Options › Appearance / Behavior). */
|
||||
export function useProjectHeaderMenu(): MenuItem[] {
|
||||
const options = useProjectTree((s) => s.options);
|
||||
@@ -47,11 +57,18 @@ export function useProjectHeaderMenu(): MenuItem[] {
|
||||
{ kind: "header", label: "Appearance" },
|
||||
...OPTION_LABELS.slice(0, 4).map(([key, label]) => option(key, label, options)),
|
||||
{ kind: "separator" },
|
||||
...SORT_LABELS.map(([sortBy, label]): MenuItem => ({
|
||||
id: `sort.${sortBy}`,
|
||||
label,
|
||||
checked: options.sortBy === sortBy,
|
||||
run: () => setViewOption("sortBy", sortBy),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Behavior" },
|
||||
...OPTION_LABELS.slice(4).map(([key, label]) => option(key, label, options)),
|
||||
];
|
||||
}
|
||||
|
||||
function option(key: keyof ViewOptions, label: string, options: ViewOptions): MenuItem {
|
||||
function option(key: ToggleOption, label: string, options: ViewOptions): MenuItem {
|
||||
return { id: key, label, checked: options[key], run: () => setViewOption(key, !options[key]) };
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { getAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import { showContextMenu, type MenuItem } from "@/ui";
|
||||
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
|
||||
import { OPTION_LABELS } from "./HeaderActions";
|
||||
import { OPTION_LABELS, SORT_LABELS } from "./HeaderActions";
|
||||
import { newMenuItems, revealLabel } from "./contextMenu";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
import type { ProjectNode } from "./model";
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
findFileUsages,
|
||||
folderOf,
|
||||
leadNode,
|
||||
openCopyDialog,
|
||||
openMoveDialog,
|
||||
openRenameDialog,
|
||||
openSelection,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
type PathKind,
|
||||
} from "./operations";
|
||||
import { nameOf, parentOf } from "./paths";
|
||||
import { showFilePathPopup } from "./filePath";
|
||||
import { showNewPopup, treeHandle } from "./ProjectView";
|
||||
import { lastFileRefactoring, undoFileRefactoring } from "./fileRefactor";
|
||||
import {
|
||||
@@ -170,6 +172,15 @@ export function registerProjectActions(): () => void {
|
||||
},
|
||||
}));
|
||||
|
||||
const sorts: Action[] = SORT_LABELS.map(([sortBy, label]) => ({
|
||||
id: `project.sortBy.${sortBy}`,
|
||||
title: tx`Project View: ${label}`,
|
||||
category: "View",
|
||||
keywords: ["project", "tree", "sort", "order"],
|
||||
toggled: () => useProjectTree.getState().options.sortBy === sortBy,
|
||||
run: () => setViewOption("sortBy", sortBy),
|
||||
}));
|
||||
|
||||
return registerActions([
|
||||
{
|
||||
// A path argument (links, breadcrumbs, Open In › Project View) selects it in the project view.
|
||||
@@ -317,6 +328,33 @@ export function registerProjectActions(): () => void {
|
||||
keywords: ["remove", "trash"],
|
||||
run: ({ arg }) => deleteSelection(nodesFrom(arg)),
|
||||
},
|
||||
{
|
||||
// F5 (CopyElement): the Copy dialog for the selection, or for the file in the editor.
|
||||
id: "project.copyElement",
|
||||
title: "Copy…",
|
||||
category: "Project View",
|
||||
icon: "copy",
|
||||
when: OPEN,
|
||||
keyWhen: `${FOCUS} || editorFocus`,
|
||||
keywords: ["copy file", "duplicate file", "clone"],
|
||||
run: ({ arg, ctx }) => {
|
||||
if (arg !== undefined || ctx.projectViewFocus) return openCopyDialog(nodesFrom(arg));
|
||||
const path = activeEditor()?.ctx.path;
|
||||
if (path) openCopyDialog(nodesFrom(path));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "navigate.showFilePath",
|
||||
title: "File Path",
|
||||
category: "Navigate",
|
||||
when: OPEN,
|
||||
keywords: ["reveal in finder", "show in explorer", "path popup"],
|
||||
run: ({ arg, ctx }) => {
|
||||
const node = typeof arg === "string" || ctx.projectViewFocus ? nodesFrom(arg)[0] : undefined;
|
||||
const path = node?.path ?? activeEditor()?.ctx.path;
|
||||
if (path) showFilePathPopup(path, node?.dir ?? false);
|
||||
},
|
||||
},
|
||||
{ id: "project.copy", title: "Copy", category: "Project View", when: FOCUS, run: () => copySelection(false) },
|
||||
{ id: "project.cut", title: "Cut", category: "Project View", when: FOCUS, run: () => copySelection(true) },
|
||||
{ id: "project.paste", title: "Paste", category: "Project View", when: FOCUS, run: () => paste() },
|
||||
@@ -470,5 +508,6 @@ export function registerProjectActions(): () => void {
|
||||
},
|
||||
...toggles,
|
||||
...modes,
|
||||
...sorts,
|
||||
]);
|
||||
}
|
||||
@@ -105,7 +105,7 @@ describe("project view context menu", () => {
|
||||
"-",
|
||||
"Compare With…",
|
||||
]);
|
||||
expect(sub(items, "Refactor")).toEqual(["Rename…", "Move File…", "-", "Safe Delete…"]);
|
||||
expect(sub(items, "Refactor")).toEqual(["Rename…", "Move File…", "Copy File…", "-", "Safe Delete…"]);
|
||||
expect(sub(items, "Open In")).toEqual([revealLabel(), "Terminal"]);
|
||||
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
deleteSelection,
|
||||
findFileUsages,
|
||||
folderOf,
|
||||
openCopyDialog,
|
||||
openMoveDialog,
|
||||
openRenameDialog,
|
||||
paste,
|
||||
@@ -225,6 +226,12 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
shortcut: keyLabel("project.move"),
|
||||
run: () => openMoveDialog(nonRoot),
|
||||
},
|
||||
nonRoot.length > 0 && {
|
||||
id: "copy",
|
||||
label: nonRoot.length === 1 ? (nonRoot[0]!.dir ? "Copy Directory…" : "Copy File…") : "Copy…",
|
||||
shortcut: keyLabel("project.copyElement"),
|
||||
run: () => openCopyDialog(nonRoot),
|
||||
},
|
||||
nonRoot.length > 0 && { kind: "separator" },
|
||||
nonRoot.length > 0 && {
|
||||
id: "safeDelete",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { filePathChain } from "./filePath";
|
||||
|
||||
describe("filePathChain", () => {
|
||||
it("lists the file then every folder up to the root", () => {
|
||||
expect(filePathChain("/work/app/src/main.ts")).toEqual([
|
||||
"/work/app/src/main.ts",
|
||||
"/work/app/src",
|
||||
"/work/app",
|
||||
"/work",
|
||||
"/",
|
||||
]);
|
||||
});
|
||||
|
||||
it("stops at a Windows drive root", () => {
|
||||
expect(filePathChain("C:/Users/me/a.txt")).toEqual(["C:/Users/me/a.txt", "C:/Users/me", "C:/Users", "C:/"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Navigate › File Path (⌥⌘F12): the file and its folders, each revealed in the OS file manager. */
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { nameOf, parentOf } from "./paths";
|
||||
import { revealLabel } from "./contextMenu";
|
||||
|
||||
const DRIVE_ROOT = /^[A-Za-z]:\/?$/;
|
||||
|
||||
/** `path` then each folder above it, up to the file system (or drive) root. */
|
||||
export function filePathChain(path: string): string[] {
|
||||
const out = [path];
|
||||
for (let p = path; p !== "/" && !DRIVE_ROOT.test(p);) {
|
||||
const parent = parentOf(p);
|
||||
if (parent === p) break;
|
||||
p = /^[A-Za-z]:$/.test(parent) ? `${parent}/` : parent;
|
||||
out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function reveal(path: string) {
|
||||
try {
|
||||
const { revealItemInDir } = await import("@tauri-apps/plugin-opener");
|
||||
await revealItemInDir(path);
|
||||
} catch (e) {
|
||||
const fileManager = revealLabel();
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx`Cannot reveal in ${fileManager}`,
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function showFilePathPopup(path: string, isDir = false) {
|
||||
const items = filePathChain(path).map((p, i) => ({
|
||||
id: p,
|
||||
label: nameOf(p) || p,
|
||||
detail: i === 0 ? undefined : p,
|
||||
icon: i === 0 && !isDir ? "file" : "folder",
|
||||
run: () => reveal(p),
|
||||
}));
|
||||
openPopup({ kind: "list", anchor: { x: window.innerWidth / 2 - 160, y: 96 }, title: "File Path", items });
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
mergeListing,
|
||||
nodeKeyFor,
|
||||
planRefresh,
|
||||
visibleEntries,
|
||||
visibleInfo,
|
||||
type Listings,
|
||||
type TreeOptions,
|
||||
@@ -191,3 +192,23 @@ describe("mergeListing", () => {
|
||||
expect(mergeListing(undefined, prev)).toBe(prev);
|
||||
});
|
||||
});
|
||||
|
||||
describe("visibleEntries sorting", () => {
|
||||
const files = [
|
||||
entry("/r/b.ts", "file", { mtimeMs: 30 }),
|
||||
entry("/r/a.md", "file", { mtimeMs: 10 }),
|
||||
entry("/r/c.md", "file", { mtimeMs: 20 }),
|
||||
entry("/r/src", "dir", { mtimeMs: 5 }),
|
||||
];
|
||||
const names = (sortBy: TreeOptions["sortBy"], foldersFirst = true) =>
|
||||
visibleEntries(files, { ...DEFAULT_TREE_OPTIONS, sortBy, foldersFirst }).map((e) => e.name);
|
||||
|
||||
it("sorts by type, then name, folders first", () => {
|
||||
expect(names("type")).toEqual(["src", "a.md", "c.md", "b.ts"]);
|
||||
});
|
||||
|
||||
it("sorts by modification time, newest first", () => {
|
||||
expect(names("modified")).toEqual(["src", "b.ts", "c.md", "a.md"]);
|
||||
expect(names("modified", false)).toEqual(["b.ts", "c.md", "a.md", "src"]);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача