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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 6d0b644e20 fix(editor): remove remaining gutter icon hover backgrounds 2026-11-07 14:06:39 +08:00
arookieofc 6efff739dd fix(vcs): reopen the repository when the pack directory changes (#1920)
Repo::gix() reopened the cached gitoxide handle only when config or packed-refs changed. An external git fetch/pull/repack writes new packs under objects/pack and moves refs, but never touches those files — so the ODB kept serving the snapshot taken at open, and refs whose tip lived only in the new pack failed to peel: branches vanished and status warned "Could not peel reference". Watch the pack directory's mtime too and reopen when it changes, so externally added objects become visible (issue #1919).

Fixes #1919
2026-11-07 13:32:05 +08:00
Jaw 8ca6e4bc01 fix(debugger): copy structured variable values with their contents (#1904) (#1917) 2026-11-07 13:15:27 +08:00
arookieofc 8d909598d5 fix(vfs): warn when the inotify watch limit leaves folders unwatched (#1918)
* fix(vfs): warn when the inotify watch limit leaves folders unwatched

When watch() hits the OS watch limit mid-tree (inotify ENOSPC/EMFILE), the affected directories were silently never watched: the project stayed stale with no hint. Record the failure on DirState and surface it through the new Watcher::unwatched_reason() — the host emits the 'sync may be slow' warning once the project opens and once on the first event batch after a late failure (deferred walk / update_watches).

Fixes #1915

* fix(vfs): latch the startup watch-limit warning so batches don't repeat it
2026-11-07 12:54:07 +08:00
l0ng-ai b99fe1704b fix(vcs): keep Git Log rows painted while dragging the scrollbar (#1914)
Dragging the Git Log scrollbar through a long history stuttered and showed
blank rows: the native scrollbar scrolls asynchronously in WebKit, so the
virtual list rendered rows a frame or more after the new offset was painted.

The list now uses a scrollbar drawn in the DOM (`Scrollbar` in `src/ui`) that
sets the offset from pointer events and notifies scroll listeners at once, so
the virtualizer renders the matching rows before the next paint. Rows are
keyed by slot so a large jump updates the mounted rows instead of rebuilding
them, overscan is lowered, and rows rendered mid-scroll draw their graph
without edge hit targets, which come back once scrolling stops.

Adds a `gitLogScrollbar` perf scenario with budgets.
2026-11-07 12:14:09 +08:00
l0ng-ai 159c2d6fd2 fix(lsp): find Go usages in build-constrained files and list their callers (#1911)
gopls builds a module for the host's GOOS/GOARCH only, so usages in files such as foo_windows.go were missing from Find Usages on macOS, and renaming left them behind, breaking the build for that platform. Those files of the searched modules are now resolved the way other modules are: each mention of the name in its own view (gopls builds one for the file's platform), added after gopls' answer and included in Rename.

Incoming Calls now also lists the callers found this way, in other modules and in build-constrained files: the declaration containing each call site.
2026-11-07 11:45:06 +08:00
l0ng-aiтаtiube00001 5084388a68 fix(lsp): find Go usages without reopening gopls' files, and in other modules (#1909)
Finding usages of a common Go name such as New opened every project file that mentions it and asked gopls again, which took up to seconds and found nothing more: gopls answers from the view of the file it is asked about, and opened files only get views of their own. Go searches now skip that widening.

Usages in other modules of the project that use the declaration's module through a local replace (a multi-module repository without go.work) are found the way GoLand finds them: each mention of the name there is resolved in its own module's view, and those resolving to the declaration are added after gopls' own answer. Rename edits them too.

Supersedes #1749.

Co-authored-by: tiube00001 <[email protected]>
2026-11-07 11:29:53 +08:00
l0ng-ai 68342b32bf test(run): synchronize process shutdown tests to fix flaky CI (#1908) 2026-11-07 11:25:54 +08:00
Jaw 352efc02a7 feat(angular): highlight inline templates and auto-close tags (#1897)
Angular component templates in @Component({ template }) were parsed as TypeScript strings, so template highlighting and tag closing never applied. TypeScript files in Angular projects (angular.json or @angular/core) now use an Angular TypeScript mode that mounts the Angular template parser on literal template strings; other strings and non-Angular projects are unchanged. Inline and external templates both close tags on /, with multiple cursors and undo.

Closes #1895

Co-authored-by: jaw52 <[email protected]>
2026-11-07 11:13:09 +08:00
LU XIANGRUIтаwildcatDownstairs 24ffb9f16e fix(workbench): even out the tool window stripes' spacing and draw their icons at 20px (#1741)
Stripe icon buttons were 28px with a 2px gap, plus an extra gap at each group boundary, and their 20px icons were drawn at 18px, off the pixel grid. Stripe buttons are now 30px and repeat at the title bar's height (40px, 32px compact), so the title bar's Settings button reads as the right stripe's first one; the empty drop slot after a group no longer adds a gap. Stripe, title bar and Run widget icons render at 20px.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-07 11:13:00 +08:00
Jaw 8ebf839d8e feat(project): rename Autoscroll from Source to Always Select Opened File (#1694)
Following the active editor already worked, but the option kept IDEA's pre-2023 name and sat second under Behavior, so people didn't find it (#1666). It is now Always Select Opened File, listed first, and the header's Select Opened File button hides while it's on. Find Action still matches the old name; the setting key is unchanged.

Closes #1666

Co-authored-by: jaw52 <[email protected]>
2026-11-07 11:12:50 +08:00
Kamal ElFadlтаelfadl 14a31fe8a1 feat(editor): add syntax highlighting for go.mod and go.work files (#1695)
go.mod and go.work opened as plain text: their language definitions had no ui-mode, so no CodeMirror language loaded. Add a GoMod mode (a small stream parser): directives as keywords, module paths as strings, versions as numbers, // comments; shared by go.mod and go.work.

Co-authored-by: elfadl <[email protected]>
2026-11-07 11:12:41 +08:00
Ilya Lтаmushketer888 1af1744290 feat(editor): highlight Arduino sketches as C++ (#1874)
Open .ino sketches with C++ highlighting and the C++ file icon. Sketches get their own Arduino language with no language server: clangd can't compile a sketch on its own (implicit Arduino.h, generated prototypes) and reported "Unable to handle compilation" on line 1 of every sketch.

Co-authored-by: mushketer888 <[email protected]>
2026-11-07 11:12:32 +08:00
47 змінених файлів з 1723 додано та 94 видалено

No files matched your search

+38 -2
Переглянути файл
@@ -56,7 +56,7 @@ pub struct Project {
pub notebooks: Arc<crate::notebook::NotebookService>,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) watcher: Watcher,
pub(crate) watcher: Arc<Watcher>,
/// Watchers of the Project Structure content roots outside the project folder.
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
/// Watchers of folders outside the project that language servers registered file
@@ -305,6 +305,12 @@ impl Host {
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
// Shared handle: `unwatched_reason` is a live query on the watcher,
// filled after `start` returns so the on-change callback can reach it.
let watcher_weak = Arc::new(std::sync::OnceLock::<std::sync::Weak<Watcher>>::new());
// One-shot latch for the post-start watch-limit warning (#1915): the
// synchronous startup walk and a later batch can both observe it.
let notify_watch_exhausted = Arc::new(AtomicBool::new(false));
let watcher = {
let kotlin_bridge = kotlin_bridge.clone();
let phpstan = phpstan.clone();
@@ -322,6 +328,8 @@ impl Host {
let lsp = lsp.clone();
let trusted = trusted.clone();
let build_cache = build_cache.clone();
let notify_watch_exhausted = notify_watch_exhausted.clone();
let watcher_weak = watcher_weak.clone();
Watcher::start(
&root.clone(),
excludes.clone(),
@@ -408,9 +416,26 @@ impl Host {
if git_dirs || vcs_moved {
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
// A watch limit hit after startup (per-directory mode, Linux):
// folders past the limit never sync — surface it once, like
// the polling fallback below (#1915). The check itself is
// deferred to here, on a batch that already had events.
if !notify_watch_exhausted.load(Ordering::Relaxed)
&& let Some(msg) =
watcher_weak.get().and_then(std::sync::Weak::upgrade).and_then(|w| w.unwatched_reason())
{
sink.emit(IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "External file changes sync may be slow".into(),
body: Some(msg),
});
notify_watch_exhausted.store(true, Ordering::Relaxed);
}
}),
)?
};
let watcher = Arc::new(watcher);
let _ = watcher_weak.set(Arc::downgrade(&watcher));
if let Some(reason) = watcher.polling() {
sink.emit(IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
@@ -418,6 +443,17 @@ impl Host {
body: Some(reason.into()),
});
}
// A watch can also be refused part-way through the synchronous startup
// walk (large tree, SYNC_WATCH_BUDGET) — after start() returns, before
// any batch. Emit the same warning so the limit isn't silent there either.
if let Some(reason) = watcher.unwatched_reason() {
sink.emit(IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "External file changes sync may be slow".into(),
body: Some(reason),
});
notify_watch_exhausted.store(true, Ordering::Relaxed);
}
// Scratch files live outside the project; watch them too so the
// Project view and open editors follow changes made there.
@@ -644,7 +680,7 @@ impl Host {
notebooks,
kotlin_bridge: None,
phpstan: None,
watcher,
watcher: Arc::new(watcher),
content_watchers: Mutex::new(Vec::new()),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: None,
+11 -2
Переглянути файл
@@ -9,6 +9,7 @@ use std::sync::{Arc, OnceLock};
/// Built-in definitions, embedded at compile time. Add new languages here.
const BUILTIN: &[(&str, &str)] = &[
("arduino", include_str!("../../../languages/arduino.toml")),
("asciidoc", include_str!("../../../languages/asciidoc.toml")),
("astro", include_str!("../../../languages/astro.toml")),
("bat", include_str!("../../../languages/bat.toml")),
@@ -601,9 +602,11 @@ mod tests {
"MsGenny",
"Vue",
"Angular Template",
"Angular TypeScript",
"ERB",
"JSP",
"Astro",
"GoMod",
];
fn reg() -> LanguageRegistry {
@@ -716,7 +719,7 @@ mod tests {
}
#[test]
fn html_of_angular_projects_is_an_angular_template() {
fn angular_projects_use_framework_modes() {
let reg = reg();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
@@ -727,7 +730,12 @@ mod tests {
assert_eq!(mode("html", "apps/web/src/app/app.html").as_deref(), Some("Angular Template"));
assert_eq!(mode("html", "apps/admin/src/index.html").as_deref(), Some("Angular Template"));
assert_eq!(mode("html", "docs/index.html"), None);
assert_eq!(mode("typescript", "apps/web/src/app/app.ts"), None);
for file in ["apps/web/src/app/app.ts", "apps/admin/src/app.mts", "apps/admin/src/app.cts"] {
assert_eq!(mode("typescript", file).as_deref(), Some("Angular TypeScript"), "{file}");
}
assert_eq!(mode("typescript", "docs/example.ts"), None);
assert_eq!(mode("javascript", "apps/web/src/app/app.js"), None);
assert_eq!(mode("typescriptreact", "apps/web/src/app/app.tsx"), None);
assert!(reg.is_framework_marker(&root.join("apps/admin/angular.json")));
assert!(!reg.is_framework_marker(&root.join("apps/admin/package.json")));
}
@@ -860,6 +868,7 @@ mod tests {
("x.h", "c"),
("x.hpp", "cpp"),
("x.cc", "cpp"),
("blink.ino", "arduino"),
("P.cs", "csharp"),
("V.swift", "swift"),
("AppDelegate.m", "objective-c"),
+354
Переглянути файл
@@ -0,0 +1,354 @@
//! Go files a gopls search does not reach.
//!
//! gopls answers a search from the view of the file it is asked about: the
//! modules of a `go.work`, or that file's own module, built for the host's
//! GOOS/GOARCH without extra tags. Opening more files does not widen it (each
//! gets a view of its own), so the generic scope widening is skipped for Go.
//! Usages it leaves out are found as GoLand finds them, by resolving each
//! mention of the name in its own file's view: files of other modules that use
//! the declaration's module through a local `replace` (a multi-module
//! repository without `go.work`), and files whose build constraints exclude
//! them from the default build (`_windows.go`, `//go:build`).
use ide_core::{Pos, Range};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
/// The files of `candidates` the search at `origin` does not cover and that can refer to
/// `declaration`: those of the covered modules excluded from their default build, and those
/// of the declaration's own module or one replacing it with its directory when not covered.
pub(crate) fn files_beyond_search(origin: &Path, declaration: &Path, candidates: Vec<PathBuf>) -> Vec<PathBuf> {
let mut modules = ModuleRoots::default();
let (Some(origin_module), Some(declaring)) = (modules.of(origin), modules.of(declaration)) else {
return Vec::new();
};
let Some(declaring_path) = read_module_path(&declaring) else { return Vec::new() };
let mut covered: HashSet<PathBuf> = workspace_modules(&origin_module).into_iter().collect();
covered.insert(origin_module);
let mut uses: HashMap<PathBuf, bool> = HashMap::new();
candidates
.into_iter()
.filter(|file| {
let Some(module) = modules.of(file) else { return false };
// The covered modules share the search's view: only their excluded files are missed.
if covered.contains(&module) {
return !in_default_build(file);
}
*uses.entry(module.clone()).or_insert_with(|| {
module == declaring
|| std::fs::read_to_string(module.join("go.mod")).is_ok_and(|text| {
local_replacements(&text, &module)
.iter()
.any(|(path, dir)| *path == declaring_path && *dir == declaring)
})
})
})
.collect()
}
/// Whether gopls' default view builds `file`: no build constraint other than the host's
/// own GOOS/GOARCH file name suffix.
fn in_default_build(file: &Path) -> bool {
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let stem = name.strip_suffix(".go").unwrap_or(&name);
let stem = stem.strip_suffix("_test").unwrap_or(stem);
let parts: Vec<&str> = stem.split('_').collect();
// `name_GOOS`, `name_GOARCH`, `name_GOOS_GOARCH`; a file named just `linux.go` has no constraint.
let host = |part: &&str| *part == host_goos() || *part == host_goarch();
if parts.len() > 1 {
let last = parts[parts.len() - 1];
if (GOOS.contains(&last) || GOARCH.contains(&last)) && !host(&last) {
return false;
}
if parts.len() > 2 && GOARCH.contains(&last) {
let os = parts[parts.len() - 2];
if GOOS.contains(&os) && !host(&os) {
return false;
}
}
}
std::fs::read_to_string(file).is_ok_and(|text| !constrained_header(&text))
}
/// A `//go:build` or `// +build` line before the package clause.
fn constrained_header(text: &str) -> bool {
for line in text.lines() {
let line = line.trim();
if line.starts_with("package ") {
return false;
}
if line.starts_with("//go:build") || line.starts_with("// +build") {
return true;
}
}
false
}
fn host_goos() -> &'static str {
match std::env::consts::OS {
"macos" => "darwin",
os => os,
}
}
fn host_goarch() -> &'static str {
match std::env::consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
"x86" => "386",
"powerpc64" => "ppc64",
arch => arch,
}
}
const GOOS: &[&str] = &[
"aix",
"android",
"darwin",
"dragonfly",
"freebsd",
"hurd",
"illumos",
"ios",
"js",
"linux",
"nacl",
"netbsd",
"openbsd",
"plan9",
"solaris",
"wasip1",
"windows",
"zos",
];
const GOARCH: &[&str] = &[
"386",
"amd64",
"amd64p32",
"arm",
"armbe",
"arm64",
"arm64be",
"loong64",
"mips",
"mipsle",
"mips64",
"mips64le",
"mips64p32",
"mips64p32le",
"ppc",
"ppc64",
"ppc64le",
"riscv",
"riscv64",
"s390",
"s390x",
"sparc",
"sparc64",
"wasm",
];
/// Whole-word occurrences of `word` in `text`, as ranges in UTF-16 columns.
pub(crate) fn word_ranges(text: &str, word: &str) -> Vec<Range> {
let ident = |c: char| c.is_alphanumeric() || c == '_';
let mut out = Vec::new();
for (line_no, line) in text.lines().enumerate() {
let code = line.split("//").next().unwrap_or(line);
for (at, _) in code.match_indices(word) {
let before = code[..at].chars().next_back();
let after = code[at + word.len()..].chars().next();
if before.is_some_and(ident) || after.is_some_and(ident) {
continue;
}
let col = code[..at].encode_utf16().count() as u32;
let len = word.encode_utf16().count() as u32;
out.push(Range::new(Pos::new(line_no as u32, col), Pos::new(line_no as u32, col + len)));
}
}
out
}
/// Nearest enclosing `go.mod` directory, cached per directory.
#[derive(Default)]
struct ModuleRoots(HashMap<PathBuf, Option<PathBuf>>);
impl ModuleRoots {
fn of(&mut self, file: &Path) -> Option<PathBuf> {
let dir = file.parent()?.to_path_buf();
self.dir(&dir)
}
fn dir(&mut self, dir: &Path) -> Option<PathBuf> {
if let Some(found) = self.0.get(dir) {
return found.clone();
}
let found =
if dir.join("go.mod").is_file() { Some(dir.to_path_buf()) } else { dir.parent().and_then(|p| self.dir(p)) };
self.0.insert(dir.to_path_buf(), found.clone());
found
}
}
fn read_module_path(module: &Path) -> Option<String> {
let text = std::fs::read_to_string(module.join("go.mod")).ok()?;
text.lines().find_map(|line| Some(unquote(line.trim().strip_prefix("module ")?.trim())))
}
/// The modules a `go.work` above `module` uses, as gopls loads them together.
fn workspace_modules(module: &Path) -> Vec<PathBuf> {
let Some(work) = module.ancestors().map(|d| d.join("go.work")).find(|p| p.is_file()) else { return Vec::new() };
let Ok(text) = std::fs::read_to_string(&work) else { return Vec::new() };
let base = work.parent().unwrap_or(Path::new(""));
directives(&text, "use").into_iter().map(|dir| normalize(&base.join(dir))).collect()
}
/// `replace <module> [version] => <local directory>` entries, directories resolved against `base`.
fn local_replacements(go_mod: &str, base: &Path) -> Vec<(String, PathBuf)> {
directives(go_mod, "replace")
.into_iter()
.filter_map(|entry| {
let (from, to) = entry.split_once("=>")?;
let from = unquote(from.split_whitespace().next()?);
let to = unquote(to.split_whitespace().next()?);
let local = to.starts_with("./")
|| to.starts_with("../")
|| Path::new(&to).is_absolute()
|| to == "."
|| to == "..";
local.then(|| (from, normalize(&base.join(to))))
})
.collect()
}
/// The arguments of `keyword` directives, single-line and block form.
fn directives(text: &str, keyword: &str) -> Vec<String> {
let mut out = Vec::new();
let mut in_block = false;
for line in text.lines() {
let line = line.split("//").next().unwrap_or("").trim();
if in_block {
if line == ")" {
in_block = false;
} else if !line.is_empty() {
out.push(line.to_owned());
}
} else if let Some(rest) = line.strip_prefix(keyword)
&& rest.starts_with([' ', '\t', '('])
{
let rest = rest.trim();
if rest == "(" {
in_block = true;
} else if !rest.is_empty() {
out.push(rest.to_owned());
}
}
}
out
}
fn unquote(s: &str) -> String {
s.trim_matches(|c| c == '"' || c == '`').to_owned()
}
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in path.components() {
match c {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
out.pop();
}
c => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str, text: &str) -> PathBuf {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
}
fn names(root: &Path, files: Vec<PathBuf>) -> Vec<String> {
files.iter().map(|f| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")).collect()
}
#[test]
fn modules_replacing_the_declarations_module_are_searched() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "go.mod", "module example.com/app\n");
let origin = write(root, "app.go", "package app\nfunc New() {}\n");
write(root, "example/a/go.mod", "module a\n\nreplace example.com/app => ../..\n");
write(root, "example/b/go.mod", "module b\n\nreplace (\n\texample.com/app v1.0.0 => \"../../\"\n)\n");
write(root, "example/c/go.mod", "module c\n\nrequire example.com/app v1.0.0\n");
write(root, "example/d/go.mod", "module d\n\nreplace example.com/app => github.com/fork/app v1.0.0\n");
let candidates = vec![
write(root, "same.go", "package app\n"),
write(root, "same_plan9.go", "package app\n"),
write(root, &format!("same_{}.go", host_goos()), "package app\n"),
write(root, "same_plan9_test.go", "package app\n"),
write(root, "tagged.go", "// Copyright\n\n//go:build integration\n\npackage app\n"),
write(root, "plan9.go", "package app\n"),
write(root, "example/a/main.go", "package main\n"),
write(root, "example/b/main.go", "package main\n"),
write(root, "example/c/main.go", "package main\n"),
write(root, "example/d/main.go", "package main\n"),
];
assert_eq!(
names(root, files_beyond_search(&origin, &origin, candidates)),
["same_plan9.go", "same_plan9_test.go", "tagged.go", "example/a/main.go", "example/b/main.go"]
);
}
#[test]
fn go_work_modules_are_covered_by_the_first_search() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "go.work", "go 1.22\n\nuse (\n\t./lib // shared\n\t./app\n)\n");
write(root, "lib/go.mod", "module example.com/lib\n");
write(root, "app/go.mod", "module example.com/app\n\nreplace example.com/lib => ../lib\n");
write(root, "tool/go.mod", "module example.com/tool\n\nreplace example.com/lib => ../lib\n");
let declaration = write(root, "lib/lib.go", "package lib\n");
let candidates = vec![
write(root, "app/main.go", "package main\n"),
write(root, "app/main_plan9.go", "package main\n"),
write(root, "tool/main.go", "package main\n"),
];
assert_eq!(
names(root, files_beyond_search(&declaration, &declaration, candidates)),
["app/main_plan9.go", "tool/main.go"]
);
}
#[test]
fn a_usage_site_in_another_module_searches_the_declaring_module() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "go.mod", "module example.com/app\n");
let declaration = write(root, "app.go", "package app\n");
write(root, "cmd/go.mod", "module cmd\n\nreplace example.com/app => ../\n");
let origin = write(root, "cmd/main.go", "package main\n");
let candidates = vec![write(root, "other.go", "package app\n"), write(root, "cmd/util.go", "package main\n")];
assert_eq!(names(root, files_beyond_search(&origin, &declaration, candidates)), ["other.go"]);
}
#[test]
fn word_ranges_are_whole_words_outside_line_comments() {
let text = "x := app.New() // New here\nNewer := New\n\tvar é = New()\n";
assert_eq!(
word_ranges(text, "New"),
[
Range::new(Pos::new(0, 9), Pos::new(0, 12)),
Range::new(Pos::new(1, 9), Pos::new(1, 12)),
Range::new(Pos::new(2, 9), Pos::new(2, 12)),
]
);
}
}
+38 -2
Переглянути файл
@@ -13,6 +13,7 @@ mod convert;
mod external_project;
mod file_ops;
mod file_watch;
mod go_scope;
mod handler;
mod inspect;
pub mod jdtls;
@@ -53,7 +54,7 @@ use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use server::{Conn, Running, Server};
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
@@ -1688,6 +1689,19 @@ impl LspManager {
}
let mut v = out.finish(References::default())?;
convert::dedup_locations(&mut v.locations);
if project_wide && let Some(t) = targets.first().filter(|_| snap.language.as_str() == "go") {
// Usages in other modules take a view per module: those in reach come first.
if let Some(partial) = partial
&& !v.locations.is_empty()
{
partial(v.clone());
}
v.locations.extend(self.go_mentions_beyond_search(&snap, t, pos, &cancel, false).await.locations);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
convert::dedup_locations(&mut v.locations);
}
Ok(v)
}
@@ -2120,7 +2134,20 @@ impl LspManager {
};
let w = self.widened(snap, t, pos, cancel, query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(Renamed { edit: w.second.unwrap_or(w.first), incomplete: w.incomplete })
let mut edit = w.second.unwrap_or(w.first);
let mut more: BTreeMap<PathBuf, Vec<TextEdit>> = BTreeMap::new();
for l in self.go_mentions_beyond_search(snap, t, pos, cancel, false).await.locations {
more.entry(l.path.to_path_buf())
.or_default()
.push(TextEdit { range: l.range, new_text: new_name.to_owned() });
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let files =
more.into_iter().map(|(path, edits)| ide_core::FileEdit::Edit { path: path.into(), edits, version: None });
convert::merge_workspace_edit(&mut edit, WorkspaceEdit { files: files.collect(), ..Default::default() });
Ok(Renamed { edit, incomplete: w.incomplete })
}
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
@@ -2565,6 +2592,15 @@ impl LspManager {
}
HierarchyDirection::Outgoing => (query().await?, None),
};
let mut out = out;
if direction == HierarchyDirection::Incoming {
for caller in self.go_mentions_beyond_search(&snap, t, pos, cancel, true).await.callers {
match out.iter_mut().find(|i| i.path == caller.path && i.range == caller.range) {
Some(item) => item.from_ranges.extend(caller.from_ranges),
None => out.push(caller),
}
}
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
+184 -3
Переглянути файл
@@ -10,9 +10,11 @@
//! closed again. Diagnostics the server publishes for them are dropped.
use crate::server::{Running, Server};
use crate::types::ReferencesIncomplete;
use crate::text::DocText;
use crate::types::{HierarchyItem, ReferencesIncomplete};
use crate::{DocSnap, LspManager, Target};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos};
use futures::StreamExt;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos};
use lsp_types as lsp;
use serde_json::json;
use std::collections::HashSet;
@@ -51,6 +53,14 @@ pub struct CandidateFiles {
/// blocking thread and should stop early when cancelled.
pub type CandidateFn = dyn Fn(&CandidateQuery, &CancellationToken) -> CandidateFiles + Send + Sync;
/// What a Go search adds beyond gopls' own answer.
#[derive(Default)]
pub(crate) struct GoMentions {
pub locations: Vec<Location>,
/// The declarations containing them, as incoming calls (when asked for).
pub callers: Vec<HierarchyItem>,
}
/// A reference-based answer and, when files were opened for it, the second one.
pub(crate) struct Widened<R> {
pub first: R,
@@ -110,7 +120,9 @@ impl LspManager {
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let word = search_word(snap, pos).filter(|_| t.caps().open_close);
// gopls searches the view of the file asked about; files opened for it only get views of
// their own (see `go_scope`).
let word = search_word(snap, pos).filter(|_| t.caps().open_close && snap.language.as_str() != "go");
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
@@ -162,6 +174,175 @@ impl LspManager {
}
}
/// Go: usages of the symbol at `pos` that the search at `pos` does not reach (see
/// `go_scope`), each mention of the name resolved in its own file's view; with `callers`,
/// also the declarations containing them, as incoming calls.
pub(crate) async fn go_mentions_beyond_search(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
cancel: &CancellationToken,
callers: bool,
) -> GoMentions {
if snap.language.as_str() != "go" || !t.caps().open_close {
return GoMentions::default();
}
let Some(word) = search_word(snap, pos) else { return GoMentions::default() };
let declarations: Vec<Location> = self
.goto_in(snap, std::slice::from_ref(t), "textDocument/definition", pos, Some(cancel), None)
.await
.unwrap_or_default()
.into_iter()
.filter(|l| l.uri.is_none())
.collect();
let Some(declaration) = declarations.first() else { return GoMentions::default() };
let Some(candidates) = self.candidates(t, word.clone(), cancel).await else { return GoMentions::default() };
let (origin, declared) = (snap.path.clone(), declaration.path.to_path_buf());
let files = tokio::task::spawn_blocking(move || {
crate::go_scope::files_beyond_search(&origin, &declared, candidates.files)
.into_iter()
.filter_map(|f| {
let text = std::fs::read_to_string(&f).ok()?;
let ranges = crate::go_scope::word_ranges(&text, &word);
(!ranges.is_empty()).then(|| (f, DocText::new(&text), ranges))
})
.collect::<Vec<_>>()
})
.await
.unwrap_or_default();
if files.is_empty() || cancel.is_cancelled() {
return GoMentions::default();
}
// Open, each file gives gopls a view to resolve its mentions in (its module, its build).
let _opened = self.open_transient(t, files.iter().map(|(f, _, _)| f.clone()).collect(), cancel).await;
let texts: Vec<(PathBuf, Arc<DocText>)> =
files.iter().map(|(path, text, _)| (path.clone(), Arc::new(text.clone()))).collect();
let probes: Vec<(PathBuf, Arc<DocText>, ide_core::Range)> = files
.into_iter()
.zip(&texts)
.flat_map(|((path, _, ranges), (_, text))| {
let text = text.clone();
ranges.into_iter().map(move |r| (path.clone(), text.clone(), r))
})
.collect();
let declarations = &declarations;
let found: Vec<Option<Location>> = futures::stream::iter(probes)
.map(|(path, text, range)| async move {
let params = json!({
"textDocument": { "uri": crate::uri::path_to_uri_string(&path) },
"position": text.ide_to_lsp(t.enc(), range.start),
});
let r = crate::loading::while_loading(
&t.server,
Some(cancel),
crate::loading::LOADING_WAIT,
crate::goto_is_empty,
|| {
self.call::<_, Option<lsp::GotoDefinitionResponse>>(
t,
"textDocument/definition",
params.clone(),
Some(cancel),
crate::DEFAULT_TIMEOUT,
)
},
)
.await;
let targets = match r {
Ok(Some(r)) => crate::convert::goto_response(&self.conv(t.enc()), r),
_ => return None,
};
let same = targets
.iter()
.any(|l| declarations.iter().any(|d| d.path == l.path && d.range.start == l.range.start));
same.then(|| Location { path: path.into(), range, uri: None })
})
.buffer_unordered(8)
.collect()
.await;
let locations: Vec<Location> = found.into_iter().flatten().collect();
let mut out = GoMentions { callers: Vec::new(), locations };
if callers && !cancel.is_cancelled() {
for (path, text) in &texts {
let here: Vec<ide_core::Range> =
out.locations.iter().filter(|l| l.path == *path).map(|l| l.range).collect();
if !here.is_empty() {
out.callers.extend(self.go_callers_in(t, path, text, &here, cancel).await);
}
}
}
if cancel.is_cancelled() {
return GoMentions::default();
}
out
}
/// The declarations of `path` containing `calls`, innermost first, each with its call sites.
async fn go_callers_in(
&self,
t: &Target,
path: &Path,
text: &DocText,
calls: &[ide_core::Range],
cancel: &CancellationToken,
) -> Vec<HierarchyItem> {
let params = json!({ "textDocument": { "uri": crate::uri::path_to_uri_string(path) } });
let r: IdeResult<Option<lsp::DocumentSymbolResponse>> =
self.call(t, "textDocument/documentSymbol", params, Some(cancel), crate::DEFAULT_TIMEOUT).await;
let range =
|r: lsp::Range| ide_core::Range::new(text.lsp_to_ide(t.enc(), r.start), text.lsp_to_ide(t.enc(), r.end));
// (name, kind, detail, range, selection range) of every declaration.
let mut symbols = Vec::new();
match r {
Ok(Some(lsp::DocumentSymbolResponse::Nested(nested))) => {
let mut stack = nested;
while let Some(s) = stack.pop() {
symbols.push((s.name, s.kind, s.detail, range(s.range), range(s.selection_range)));
stack.extend(s.children.unwrap_or_default());
}
}
#[allow(deprecated)]
Ok(Some(lsp::DocumentSymbolResponse::Flat(flat))) => {
for s in flat {
let r = range(s.location.range);
symbols.push((s.name, s.kind, None, r, r));
}
}
_ => return Vec::new(),
}
let contains =
|outer: &ide_core::Range, inner: &ide_core::Range| outer.start <= inner.start && inner.end <= outer.end;
let mut items: Vec<HierarchyItem> = Vec::new();
for call in calls {
// The innermost function or method; a package-level declaration otherwise.
let callable = |k: lsp::SymbolKind| matches!(k, lsp::SymbolKind::FUNCTION | lsp::SymbolKind::METHOD);
let innermost = |pick: &dyn Fn(lsp::SymbolKind) -> bool| {
symbols
.iter()
.filter(|(_, kind, _, r, _)| pick(*kind) && contains(r, call))
.min_by_key(|(_, _, _, r, _)| (r.end.line - r.start.line, r.end.col.saturating_sub(r.start.col)))
};
let Some((name, kind, detail, r, selection)) = innermost(&callable).or_else(|| innermost(&|_| true)) else {
continue;
};
match items.iter_mut().find(|i| i.range == *r && i.name == *name) {
Some(item) => item.from_ranges.push(*call),
None => items.push(HierarchyItem {
name: name.clone(),
kind: crate::convert::symbol_kind(*kind),
detail: detail.clone(),
path: path.to_path_buf().into(),
uri: None,
range: *r,
selection_range: *selection,
from_ranges: vec![*call],
}),
}
}
items
}
/// Opens `files` on `t` (read from disk) unless the user has them open;
/// they are closed when the returned guard drops. Files too large or not
/// readable as text are left out and flagged on the guard.
+159
Переглянути файл
@@ -2930,6 +2930,165 @@ async fn references_open_unopened_files_that_mention_the_name() {
assert_eq!(seen.lock().len(), 2);
}
/// A Go project: the module at the root, `tools` replacing it with `../` and `other` requiring a
/// published copy. The mock answers a definition in `tools` like gopls in that module's view.
fn go_modules_harness() -> (Harness, Arc<MockState>, PathBuf, PathBuf, PathBuf, PathBuf) {
let h = harness_for("go", "go", &[("gopls", incremental_caps())], &[]);
let s = h.launcher.state("gopls");
let write = |rel: &str, text: &str| {
let path = h.root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
};
write("go.mod", "module example.com/app\n");
write("tools/go.mod", "module example.com/tools\n\nreplace example.com/app => ../\n");
write("other/go.mod", "module example.com/other\n\nrequire example.com/app v1.0.0\n");
let same = write("same.go", "package app\nvar x = New()\n");
// Line 1 uses the declaration; line 2 is a local `New` of the tools module.
let tools = write("tools/gen.go", "package tools\nvar a = app.New()\nfunc New() {}\n");
write("other/o.go", "package other\nvar b = app.New()\n");
// Built for plan9 only: outside gopls' default view of the root module.
let plan9 = write("boot_plan9.go", "package app\nfunc boot() { New() }\n");
let decl = h.root.join("a.go");
let candidates = vec![same.clone(), tools.clone(), h.root.join("other/o.go"), plan9.clone()];
h.mgr.set_candidates_hook(Box::new(move |_, _| ide_lsp::CandidateFiles {
files: candidates.clone(),
limit_hit: false,
}));
let at = |line: u32, col: u32| json!({ "start": { "line": line, "character": col }, "end": { "line": line, "character": col + 3 } });
let (decl_uri, same_uri, tools_uri, plan9_uri) = (uri_of(&decl), uri_of(&same), uri_of(&tools), uri_of(&plan9));
let span = |line: u32, from: u32, to: u32| json!({ "start": { "line": line, "character": from }, "end": { "line": line, "character": to } });
*s.responder.lock() = Some(Arc::new(move |_, method, params| {
let uri = params["textDocument"]["uri"].as_str().unwrap_or_default().to_owned();
let line = params["position"]["line"].as_u64().unwrap_or(0);
match method {
// The view of the root module: the declaration and its usage in same.go.
"textDocument/references" => Some(json!([
{ "uri": decl_uri, "range": at(0, 5) },
{ "uri": same_uri, "range": at(1, 8) },
])),
"textDocument/rename" => Some(json!({ "changes": {
decl_uri.clone(): [{ "range": at(0, 5), "newText": "Make" }],
same_uri.clone(): [{ "range": at(1, 8), "newText": "Make" }],
} })),
"textDocument/definition" if uri == decl_uri => Some(json!({ "uri": decl_uri, "range": at(0, 5) })),
"textDocument/definition" if uri == tools_uri && line == 1 => {
Some(json!({ "uri": decl_uri, "range": at(0, 5) }))
}
"textDocument/definition" if uri == tools_uri => Some(json!({ "uri": tools_uri, "range": at(2, 5) })),
"textDocument/definition" if uri == plan9_uri => Some(json!({ "uri": decl_uri, "range": at(0, 5) })),
"textDocument/documentSymbol" if uri == tools_uri => Some(json!([
{ "name": "a", "kind": 13, "range": span(1, 0, 17), "selectionRange": span(1, 4, 5) },
{ "name": "New", "kind": 12, "range": span(2, 0, 13), "selectionRange": span(2, 5, 8) },
])),
"textDocument/documentSymbol" if uri == plan9_uri => Some(json!([
{ "name": "boot", "kind": 12, "range": span(1, 0, 20), "selectionRange": span(1, 5, 9) },
])),
"textDocument/prepareCallHierarchy" => Some(
json!([{ "name": "New", "kind": 12, "uri": decl_uri, "range": span(0, 0, 13), "selectionRange": at(0, 5) }]),
),
"callHierarchy/incomingCalls" => Some(json!([{
"from": { "name": "x", "kind": 13, "uri": same_uri, "range": span(1, 0, 13), "selectionRange": span(1, 4, 5) },
"fromRanges": [at(1, 8)],
}])),
_ => None,
}
}));
(h, s, decl, same, tools, plan9)
}
#[tokio::test(flavor = "multi_thread")]
async fn go_searches_resolve_other_modules_that_replace_the_declarations_module() {
let (h, s, decl, same, tools, plan9) = go_modules_harness();
let (doc, _) = h.open("a.go", "func New() {}\n");
h.wait_status("gopls", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let partials = Arc::new(Mutex::new(Vec::new()));
let seen = partials.clone();
let partial = move |r: ide_lsp::types::References| seen.lock().push(r.locations.len());
let refs = h
.mgr
.references_streaming(doc, Pos::new(0, 5), true, true, true, Default::default(), Some(&partial))
.await
.unwrap();
let mut found: Vec<(PathBuf, u32)> =
refs.locations.iter().map(|l| (l.path.to_path_buf(), l.range.start.line)).collect();
found.sort();
let mut want = vec![(decl.clone(), 0), (same.clone(), 1), (tools.clone(), 1), (plan9.clone(), 1)];
want.sort();
assert_eq!(found, want);
// Those in gopls' reach arrive first.
assert_eq!(*partials.lock(), [2]);
// Only the module replacing the declaration's module was opened, never the root module's file.
let opened = uris(&s.notified("textDocument/didOpen"));
assert!(opened.contains(&uri_of(&tools)));
assert!(opened.contains(&uri_of(&plan9)));
assert!(!opened.contains(&uri_of(&same)));
assert!(!opened.iter().any(|u| u.ends_with("other/o.go")));
assert_eq!(s.requested("textDocument/references").len(), 1);
let renamed = h.mgr.rename(doc, Pos::new(0, 5), "Make".into(), Default::default()).await.unwrap();
let mut edited: Vec<(PathBuf, Vec<u32>)> = renamed
.edit
.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, edits, .. } => {
Some((path.to_path_buf(), edits.iter().map(|e| e.range.start.line).collect()))
}
_ => None,
})
.collect();
edited.sort();
let mut want = vec![(decl, vec![0]), (same, vec![1]), (tools, vec![1]), (plan9, vec![1])];
want.sort();
assert_eq!(edited, want);
}
#[tokio::test(flavor = "multi_thread")]
async fn go_incoming_calls_include_callers_beyond_the_search() {
let (h, s, _, same, tools, plan9) = go_modules_harness();
let (doc, _) = h.open("a.go", "func New() {}\n");
h.wait_status("gopls", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let calls =
h.mgr.call_hierarchy(doc, Pos::new(0, 5), HierarchyDirection::Incoming, Default::default()).await.unwrap();
let mut callers: Vec<(PathBuf, String, Vec<u32>)> = calls
.items
.iter()
.map(|i| (i.path.to_path_buf(), i.name.clone(), i.from_ranges.iter().map(|r| r.start.line).collect()))
.collect();
callers.sort();
let mut want = vec![
(same, "x".to_owned(), vec![1]),
(tools, "a".to_owned(), vec![1]),
(plan9.clone(), "boot".to_owned(), vec![1]),
];
want.sort();
assert_eq!(callers, want);
let boot = calls.items.iter().find(|i| i.name == "boot").unwrap();
assert_eq!((boot.selection_range.start, boot.from_ranges[0].start), (Pos::new(1, 5), Pos::new(1, 14)));
}
#[tokio::test(flavor = "multi_thread")]
async fn go_searches_open_nothing_when_no_other_module_uses_the_declaration() {
let (h, s, _, same, _, plan9) = go_modules_harness();
std::fs::write(h.root.join("tools/go.mod"), "module example.com/tools\n").unwrap();
std::fs::remove_file(&plan9).unwrap();
let (doc, _) = h.open("a.go", "func New() {}\n");
h.wait_status("gopls", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(uris(&s.notified("textDocument/didOpen")).len(), 1, "only a.go");
assert!(s.requested("textDocument/definition").len() <= 1);
assert!(!uris(&s.notified("textDocument/didOpen")).contains(&uri_of(&same)));
}
#[tokio::test(flavor = "multi_thread")]
async fn references_never_reopen_or_close_the_users_files() {
let h = harness(&[("mock", incremental_caps())]);
+62 -30
Переглянути файл
@@ -23,38 +23,61 @@ fn wait_exit(events: &Receiver<IdeEvent>, id: RunId, timeout: Duration) -> Optio
let deadline = Instant::now() + timeout;
loop {
let left = deadline.saturating_duration_since(Instant::now());
match events.recv_timeout(left) {
Ok(IdeEvent::RunExited { run, code }) if run == id => return code,
Ok(_) => {}
Err(_) => return None,
match events.recv_timeout(left).expect("RunExited event") {
IdeEvent::RunExited { run, code } if run == id => return code,
_ => {}
}
}
}
fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !ready() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(20));
}
}
fn assert_still_running(events: &Receiver<IdeEvent>, timeout: Duration) {
let event = events.recv_timeout(timeout);
assert!(
matches!(event, Err(mpsc::RecvTimeoutError::Timeout)),
"run exited before shutdown was released: {event:?}"
);
}
#[test]
fn a_stopped_run_keeps_its_port_until_the_group_is_gone() {
let tmp = tempfile::tempdir().unwrap();
let (sink, events) = channel_sink();
let pm = ProcessManager::new();
// The `mvn`-starts-a-JVM shape: the direct child dies on SIGINT while the process it
// started ignores it and keeps its socket open for a moment.
// started ignores it and keeps its socket open until the test releases it.
let script = tmp.path().join("hold.py");
std::fs::write(
&script,
"import signal, socket, sys, time\n\
"import pathlib, signal, socket, sys, time\n\
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen()\n\
open(sys.argv[1], 'w').write(str(s.getsockname()[1]))\n\
time.sleep(2)\n",
while not pathlib.Path(sys.argv[2]).exists(): time.sleep(0.01)\n",
)
.unwrap();
let port_file = tmp.path().join("port");
let release_file = tmp.path().join("release");
let config = RunConfig {
id: "boot".into(),
name: "boot".into(),
kind: "shell".into(),
command: "/bin/sh".into(),
args: vec!["-c".into(), format!("python3 {} {} & sleep 60", script.display(), port_file.display())],
args: vec![
"-c".into(),
"python3 \"$1\" \"$2\" \"$3\" & sleep 60".into(),
"sh".into(),
script.display().to_string(),
port_file.display().to_string(),
release_file.display().to_string(),
],
cwd: None,
env: BTreeMap::new(),
detected: false,
@@ -64,18 +87,24 @@ fn a_stopped_run_keeps_its_port_until_the_group_is_gone() {
extras: Default::default(),
};
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
let deadline = Instant::now() + Duration::from_secs(10);
while std::fs::read_to_string(&port_file).is_err() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
wait_for("the listening port", || {
std::fs::read_to_string(&port_file).ok().is_some_and(|text| text.trim().parse::<u16>().is_ok())
});
let port: u16 = std::fs::read_to_string(&port_file).expect("port").trim().parse().unwrap();
let stopped = Instant::now();
pm.stop(info.id).unwrap();
let pid = info.pid.expect("child pid") as libc::pid_t;
wait_for("the direct child to exit", || unsafe { libc::kill(pid, 0) != 0 });
let exit = events.recv_timeout(Duration::from_secs(1));
let port_held = std::net::TcpStream::connect(("127.0.0.1", port)).is_ok();
std::fs::write(&release_file, "").unwrap();
assert!(
matches!(exit, Err(mpsc::RecvTimeoutError::Timeout)),
"run exited while its descendant held the port: {exit:?}"
);
assert!(port_held, "the descendant still holds its port");
let code = wait_exit(&events, info.id, Duration::from_secs(20));
let elapsed = stopped.elapsed();
assert!(code.is_some(), "the run reports its exit");
assert!(elapsed >= Duration::from_millis(1500), "exit came {elapsed:?} after Stop, before the port was free");
assert!(
std::net::TcpStream::connect(("127.0.0.1", port)).is_err(),
"the port is still bound when the run reports finished"
@@ -87,15 +116,16 @@ fn a_first_stop_does_not_kill_a_program_that_is_still_shutting_down() {
let tmp = tempfile::tempdir().unwrap();
let (sink, events) = channel_sink();
let pm = ProcessManager::new();
// Ignores SIGINT, then exits by itself after 2 s, like a slow Spring Boot shutdown: a first
// Stop waits for it instead of killing it (exit code 137).
// Ignores SIGINT until stdin releases the shutdown, like a slow Spring Boot shutdown.
// A first Stop must wait even past the grace period instead of killing it (exit code 137).
let script = tmp.path().join("slow.py");
let ready_file = tmp.path().join("ready");
std::fs::write(
&script,
"import signal, sys, time\n\
"import pathlib, signal, sys\n\
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
print('ready', flush=True)\n\
time.sleep(2)\n",
pathlib.Path(sys.argv[1]).touch()\n\
sys.stdin.readline()\n",
)
.unwrap();
let config = RunConfig {
@@ -103,7 +133,7 @@ fn a_first_stop_does_not_kill_a_program_that_is_still_shutting_down() {
name: "slow".into(),
kind: "shell".into(),
command: "python3".into(),
args: vec![script.display().to_string()],
args: vec![script.display().to_string(), ready_file.display().to_string()],
cwd: None,
env: BTreeMap::new(),
detected: false,
@@ -113,12 +143,12 @@ fn a_first_stop_does_not_kill_a_program_that_is_still_shutting_down() {
extras: Default::default(),
};
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
std::thread::sleep(Duration::from_millis(500)); // let the program install its handler
let start = Instant::now();
pm.stop(info.id).unwrap();
wait_for("the SIGINT handler", || ready_file.exists());
pm.stop_with_grace(info.id, Duration::from_millis(100)).unwrap();
assert_still_running(&events, Duration::from_secs(1));
pm.write_stdin(info.id, "finish shutdown\n").unwrap();
let code = wait_exit(&events, info.id, Duration::from_secs(10));
assert_eq!(code, Some(0), "the program exited by itself, not by SIGKILL");
assert!(start.elapsed() >= Duration::from_millis(1500), "stop waited for the shutdown, not a timer");
}
#[test]
@@ -127,11 +157,13 @@ fn a_second_stop_kills_a_program_that_ignores_the_first() {
let (sink, events) = channel_sink();
let pm = ProcessManager::new();
let script = tmp.path().join("stuck.py");
let ready_file = tmp.path().join("ready");
std::fs::write(
&script,
"import signal, time\n\
"import pathlib, signal, sys\n\
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
time.sleep(60)\n",
pathlib.Path(sys.argv[1]).touch()\n\
sys.stdin.readline()\n",
)
.unwrap();
let config = RunConfig {
@@ -139,7 +171,7 @@ fn a_second_stop_kills_a_program_that_ignores_the_first() {
name: "stuck".into(),
kind: "shell".into(),
command: "python3".into(),
args: vec![script.display().to_string()],
args: vec![script.display().to_string(), ready_file.display().to_string()],
cwd: None,
env: BTreeMap::new(),
detected: false,
@@ -149,9 +181,9 @@ fn a_second_stop_kills_a_program_that_ignores_the_first() {
extras: Default::default(),
};
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
std::thread::sleep(Duration::from_millis(500));
wait_for("the SIGINT handler", || ready_file.exists());
pm.stop(info.id).unwrap();
std::thread::sleep(Duration::from_millis(200));
assert_still_running(&events, Duration::from_millis(200));
pm.stop(info.id).unwrap();
let code = wait_exit(&events, info.id, Duration::from_secs(10));
assert_eq!(code, Some(137), "the second Stop SIGKILLs");
+16 -2
Переглянути файл
@@ -15,6 +15,11 @@ pub(crate) struct Cache {
repo: gix::ThreadSafeRepository,
files: [PathBuf; 4],
stamp: Vec<Option<(SystemTime, u64)>>,
/// `objects/pack` directory and its modification time. An external
/// `git fetch`/`pull`/`repack` adds packs without touching the `files`
/// above — watching the directory catches them (issue #1919).
pack_dir: PathBuf,
pack_stamp: Option<SystemTime>,
}
fn cache_files(git_dir: &Path, common_dir: &Path) -> [PathBuf; 4] {
@@ -36,6 +41,12 @@ fn stamp(files: &[PathBuf]) -> Vec<Option<(SystemTime, u64)>> {
.collect()
}
/// The pack directory's modification time: adding or removing a pack file
/// updates it. `None` when the directory can't be read.
fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
std::fs::metadata(pack_dir).ok()?.modified().ok()
}
pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let start = if path.is_file() { path.parent().unwrap_or(path) } else { path };
if let Err(e) = gix::discover::upwards(start) {
@@ -57,7 +68,8 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let git_dir = absolute(repo.git_dir())?;
let common_dir = absolute(repo.common_dir())?;
let files = cache_files(&git_dir, &common_dir);
let cache = Cache { stamp: stamp(&files), files, repo: ts };
let pack_dir = common_dir.join("objects").join("pack");
let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir };
Ok(Some(Repo {
execution_allowed: std::sync::atomic::AtomicBool::new(true),
root,
@@ -96,11 +108,13 @@ impl Repo {
}
let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let now = stamp(&cache.files);
if now != cache.stamp {
let pack_now = pack_stamp(&cache.pack_dir);
if now != cache.stamp || pack_now != cache.pack_stamp {
match gix::ThreadSafeRepository::open(&self.git_dir) {
Ok(fresh) => {
cache.repo = fresh;
cache.stamp = now;
cache.pack_stamp = pack_now;
}
Err(e) => tracing::warn!("reopening repository failed: {e}"),
}
+24
Переглянути файл
@@ -1366,6 +1366,30 @@ fn status_reflects_external_changes_without_reopen() {
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("x"));
}
#[test]
fn branches_in_newly_written_packs_stay_visible() {
let fx = Fixture::new();
fx.write("a", "1\n");
fx.commit_all("a");
let repo = fx.repo();
assert_eq!(repo.branches().unwrap().len(), 1);
// An external pull: objects move into a pack the IDE has never seen, then a
// new branch points at a commit living only in that pack.
fx.write("a", "2\n");
fx.commit_all("b");
fx.git(&["repack", "-adq"]);
fx.git(&["checkout", "-q", "-b", "uat"]);
let uat = fx.git(&["rev-parse", "uat"]);
assert!(std::fs::read_dir(fx.path(".git/objects/pack")).unwrap().count() >= 2);
let names: Vec<String> = repo.branches().unwrap().into_iter().map(|b| b.name).collect();
assert!(names.contains(&"uat".to_string()), "branches: {names:?}, want uat at {uat}");
// Status peels HEAD for the tree-index diff: the same failure drops it too.
assert!(repo.status().is_ok(), "status failed: {:?}", repo.status().unwrap_err());
}
#[test]
fn linked_worktree_and_submodule() {
let fx = Fixture::new();
+87 -5
Переглянути файл
@@ -117,6 +117,13 @@ impl Watcher {
self.polling.as_deref()
}
/// A watch failure past startup (the OS watch limit ran out mid-tree):
/// directories past the limit never sync (issue #1915). `None` while every
/// directory has a live watch.
pub fn unwatched_reason(&self) -> Option<String> {
self.inner.state.exhausted.lock().clone()
}
/// Replaces the exclude globs (Settings › Project Structure / File Types
/// changed): later events below newly excluded folders are dropped. In
/// per-directory mode, folders no longer excluded are watched once they change.
@@ -163,6 +170,7 @@ impl Watcher {
queue: Mutex::default(),
wake: Condvar::new(),
stop: AtomicBool::new(false),
exhausted: Mutex::new(None),
});
let weak: Weak<DirState> = Arc::downgrade(&state);
let watcher = W::new(
@@ -234,8 +242,9 @@ const MAX_WATCHES_HINT: &str = "the inotify watch limit is exhausted (fs.inotify
/// instance per watcher (`EMFILE`, os error 24) or one watch per directory
/// (`ENOSPC`, mapped by notify to [`ErrorKind::MaxFilesWatch`]). A bare OS
/// error sends users off to search engines otherwise (issue #788).
fn watcher_error(what: &str, error: notify::Error) -> IdeError {
let hint = match error.kind {
/// The fix hint when an OS watch limit is hit, or `None` for other errors.
fn watch_limit_hint(error: &notify::Error) -> Option<&'static str> {
match error.kind {
ErrorKind::MaxFilesWatch => Some(MAX_WATCHES_HINT),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(24) => Some(
"the inotify instance limit is exhausted (fs.inotify.max_user_instances); raise it, e.g. \
@@ -243,8 +252,11 @@ fn watcher_error(what: &str, error: notify::Error) -> IdeError {
),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(28) => Some(MAX_WATCHES_HINT),
_ => None,
};
match hint {
}
}
fn watcher_error(what: &str, error: notify::Error) -> IdeError {
match watch_limit_hint(&error) {
Some(hint) => io_error(format!("{what}: {error}; {hint}")),
None => io_error(format!("{what}: {error}")),
}
@@ -259,6 +271,10 @@ struct DirState {
queue: Mutex<Vec<(notify::Event, Instant)>>,
wake: Condvar,
stop: AtomicBool,
/// Set when a `watch()` call reports the OS watch limit (inotify
/// `ENOSPC`/`EMFILE`): later directories are never seen, so the project is
/// silently stale past that point — surfaced via [`Watcher::unwatched_reason`].
exhausted: Mutex<Option<String>>,
}
impl DirState {
@@ -362,7 +378,15 @@ impl DirState {
true
}
Err(e) => {
tracing::debug!("cannot watch {}: {e}", dir.display());
if let Some(hint) = watch_limit_hint(&e) {
tracing::warn!("cannot watch {}: {e}", dir.display());
// Recorded, not delivered: the watch may fail after start,
// on the debounce thread — the UI picks it up via
// `unwatched_reason()`.
*self.exhausted.lock() = Some(format!("cannot watch {}: {e}; {hint}", dir.display()));
} else {
tracing::debug!("cannot watch {}: {e}", dir.display());
}
false
}
}
@@ -1320,4 +1344,62 @@ mod tests {
let other = notify::Error::io(std::io::Error::from_raw_os_error(13));
assert!(!watcher_error("cannot start file watcher", other).message.contains("inotify"));
}
/// Watch calls succeed until `budget` is spent, then `ENOSPC` — mirrors
/// `fs.inotify.max_user_watches` running out part-way through a tree.
struct ExhaustedWatcher {
budget: std::sync::atomic::AtomicUsize,
}
impl notify::Watcher for ExhaustedWatcher {
fn new<F: notify::EventHandler>(_: F, _: notify::Config) -> notify::Result<Self> {
Ok(Self { budget: std::sync::atomic::AtomicUsize::new(3) })
}
fn watch(&mut self, _dir: &Path, _: RecursiveMode) -> notify::Result<()> {
if self.budget.fetch_sub(1, Ordering::SeqCst) == 0 {
return Err(notify::Error::new(ErrorKind::MaxFilesWatch));
}
Ok(())
}
fn unwatch(&mut self, _: &Path) -> notify::Result<()> {
Ok(())
}
fn kind() -> WatcherKind {
WatcherKind::NullWatcher
}
}
/// #1915: a watch refused mid-tree must not stay silent — the limit is
/// reported through `unwatched_reason` so the UI can warn like the
/// polling fallback does.
#[test]
fn unwatched_reason_reports_the_watch_limit() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for d in ["a", "b", "c", "d"] {
std::fs::create_dir_all(root.join(d)).unwrap();
}
let filter = EventFilter::new(root.clone(), &[]);
let (excludes, rules) = (filter.excludes.clone(), filter.gitignore.clone());
let (tx, _rx) = std::sync::mpsc::channel::<FsBatch>();
let emit: Emit = Arc::new(move |b| {
let _ = tx.send(b.clone());
});
let inner = Watcher::start_queued::<ExhaustedWatcher>(
&root,
filter,
emit,
WatchMode::PerDirectory,
notify::Config::default(),
)
.unwrap();
let watcher = Watcher { inner, excludes, rules, polling: None };
assert!(watcher.polling().is_none(), "the OS watcher did start");
let reason = watcher.unwatched_reason().expect("watch limit must be reported");
assert!(reason.contains("max_user_watches"), "{reason}");
assert!(reason.contains("cannot watch"), "{reason}");
}
}
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { expect, test } from "./fixtures";
import type { Page } from "@playwright/test";
async function placeCaret(page: Page, marker: string) {
await page.locator(".cm-content").evaluate((element, marker) => {
const view = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view;
const anchor = view.state.doc.toString().indexOf(marker) + marker.length;
view.dispatch({ selection: { anchor } });
view.focus();
}, marker);
}
test("Angular templates highlight and close tags in inline and external documents", async ({ workbench: page }) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
const files = docBackend().files;
files.set("/dev/acme-api/angular.json", "{}");
files.set(
"/dev/acme-api/app.ts",
'@Component({\n template: `<div [title]="name">{{ name }}</div>\n @if (ready) { <p>Ready</p> }\n <r-card\n <section\n <article><\n `\n})\nexport class App {}\n',
);
files.set("/dev/acme-api/app.html", "<r-card\n<div\n<article><");
files.set("/dev/acme-api/plain.ts", "const data = { template: `<r-card/>` };");
await editorService().openFile("/dev/acme-api/app.ts");
});
const inline = page.locator('.cm-editor[data-language="Angular TypeScript"]');
await expect(inline).toBeVisible();
await expect(inline.locator(".cm-content span").filter({ hasText: /^div$/ }).first()).toBeVisible();
await expect(inline.locator(".cm-content span").filter({ hasText: /^@if$/ })).toBeVisible();
for (const [marker, text, result] of [
["<r-card", "/", "<r-card/>"],
["<section", ">", "<section></section>"],
["<article><", "/", "<article></article>"],
]) {
await placeCaret(page, marker!);
await page.keyboard.type(text!);
await expect(inline.locator(".cm-content")).toContainText(result!);
}
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
await (await import(path)).editorService().openFile("/dev/acme-api/app.html");
});
const external = page.locator('.cm-editor[data-language="Angular Template"]');
await expect(external).toBeVisible();
for (const [marker, text, result] of [
["<r-card", "/", "<r-card/>"],
["<div", ">", "<div></div>"],
["<article><", "/", "<article></article>"],
]) {
await placeCaret(page, marker!);
await page.keyboard.type(text!);
await expect(external.locator(".cm-content")).toContainText(result!);
}
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
await (await import(path)).editorService().openFile("/dev/acme-api/plain.ts");
});
await expect(page.locator(".cm-content span").filter({ hasText: /^r-card$/ })).toHaveCount(0);
});
+10
Переглянути файл
@@ -0,0 +1,10 @@
id = "arduino"
name = "Arduino"
# Sketches are C++ with an implicit `Arduino.h` and generated prototypes; clangd can't compile
# them on its own, so they get C++ highlighting without a language server.
extensions = ["ino"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "C++"
tree-sitter = "cpp"
+1
Переглянути файл
@@ -3,6 +3,7 @@ name = "Go Module"
filenames = ["go.mod"]
line-comment = "//"
indent = { tab-size = 4, insert-spaces = false }
ui-mode = "GoMod"
[[language-servers]]
name = "gopls"
+1
Переглянути файл
@@ -3,6 +3,7 @@ name = "Go Workspace"
filenames = ["go.work"]
line-comment = "//"
indent = { tab-size = 4, insert-spaces = false }
ui-mode = "GoMod"
[[language-servers]]
name = "gopls"
+4
Переглянути файл
@@ -8,6 +8,10 @@ indent = { tab-size = 2, insert-spaces = true }
ui-mode = "TypeScript"
tree-sitter = "typescript"
[[framework-ui-modes]]
ui-mode = "Angular TypeScript"
root-markers = ["angular.json", "node_modules/@angular/core"]
[[language-servers]]
name = "vtsls"
tsserver-project = true
+17 -7
Переглянути файл
@@ -119,6 +119,8 @@ interface MemDoc {
const EXT_LANG: Record<string, string> = {
ts: "typescript",
mts: "typescript",
cts: "typescript",
tsx: "typescriptreact",
js: "javascript",
jsx: "javascriptreact",
@@ -155,7 +157,7 @@ const MEM_LANGUAGES: LanguageInfo[] = [
{
id: "typescript",
name: "TypeScript",
extensions: ["ts"],
extensions: ["ts", "mts", "cts"],
uiMode: "TypeScript",
lineComment: "//",
blockComment: ["/*", "*/"],
@@ -377,12 +379,20 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
...(d.uri ? { uri: d.uri } : {}),
...(d.uiMode ? { uiMode: d.uiMode } : {}),
});
// An Angular project's templates (an `angular.json` above them), like the backend's `framework-ui-modes`.
const uiModeOf = (path: string) =>
path.endsWith(".html") &&
[...store.keys()].some((f) => f.endsWith("/angular.json") && path.startsWith(f.slice(0, -"angular.json".length)))
? "Angular Template"
: null;
// Framework modes mirror the backend's `framework-ui-modes` definitions.
const uiModeOf = (path: string) => {
const angular = [...store.keys()].some((f) => {
const root = f.endsWith("/angular.json")
? f.slice(0, -"angular.json".length)
: f.includes("/node_modules/@angular/core/")
? f.slice(0, f.indexOf("/node_modules/@angular/core/") + 1)
: null;
return root !== null && path.startsWith(root);
});
if (!angular) return null;
if (path.endsWith(".html")) return "Angular Template";
return /\.(?:ts|mts|cts)$/.test(path) ? "Angular TypeScript" : null;
};
const get = (doc: DocId) => {
const d = docs.get(doc);
if (!d) throw new IpcError({ kind: "notFound", message: `document ${doc} is not open` });
+33
Переглянути файл
@@ -7,6 +7,8 @@
* parsed as one, and folding blocks.
*/
import { LRLanguage, LanguageSupport, foldService, matchBrackets, syntaxTree } from "@codemirror/language";
import { EditorSelection } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { html } from "@codemirror/lang-html";
import { javascriptLanguage } from "@codemirror/lang-javascript";
import { styleTags, tags as t } from "@lezer/highlight";
@@ -230,9 +232,40 @@ const blockFolding = foldService.of((state, lineStart, lineEnd) => {
return null;
});
const selfCloseTags = EditorView.inputHandler.of((view, from, to, text, insertTransaction) => {
const { state } = view;
if (view.composing || state.readOnly || from !== to || text !== "/") return false;
const heads = state.selection.ranges
.filter((range) => {
if (!range.empty || !angularLanguage.isActiveAt(state, range.head, -1)) return false;
const node = syntaxTree(state).resolveInner(range.head, -1);
return node.name === "TagName" && node.to === range.head && node.parent?.name === "OpenTag";
})
.map((range) => range.head);
if (!heads.length) return false;
const base = insertTransaction();
const mappedHeads = new Set(heads.map((head) => base.changes.mapPos(head, 1)));
const closing = base.state.changeByRange((range) => {
if (!range.empty || !mappedHeads.has(range.head) || base.state.sliceDoc(range.head - 1, range.head) !== "/")
return { range };
return {
range: EditorSelection.cursor(range.head + 1),
changes: {
from: range.head,
to: range.head + (base.state.sliceDoc(range.head, range.head + 1) === ">" ? 1 : 0),
insert: ">",
},
};
});
if (closing.changes.empty) return false;
view.dispatch([base, base.state.update(closing, { userEvent: "input.type", scrollIntoView: true })]);
return true;
});
export function angular(): LanguageSupport {
return new LanguageSupport(angularLanguage, [
baseHTML.support,
selfCloseTags,
blockFolding,
baseHTML.language.data.of({
closeBrackets: { brackets: ["[", "{", '"'] },
+161
Переглянути файл
@@ -0,0 +1,161 @@
import { describe, expect, it } from "vitest";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { history, undo } from "@codemirror/commands";
import { EditorView } from "@codemirror/view";
import { ensureSyntaxTree } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "../languages";
import { angular } from "./index";
async function inlineSupport() {
return (await loadSupport(findLanguageDescription("Angular TypeScript", "/p/app.ts")!))!;
}
const highlighter = tagHighlighter([
{ tag: t.tagName, class: "tag" },
{ tag: t.attributeName, class: "attr" },
{ tag: t.variableName, class: "var" },
{ tag: t.controlKeyword, class: "control" },
{ tag: t.definitionKeyword, class: "definition" },
{ tag: t.string, class: "string" },
]);
function tokens(state: EditorState) {
const out: string[] = [];
highlightTree(ensureSyntaxTree(state, state.doc.length, 5000)!, highlighter, (from, to, cls) =>
out.push(`${state.sliceDoc(from, to)}:${cls}`),
);
return out;
}
function type(view: EditorView, text: string) {
const { from, to } = view.state.selection.main;
const insert = () => view.state.update(view.state.replaceSelection(text), { userEvent: "input.type" });
if (!view.state.facet(EditorView.inputHandler).some((h) => h(view, from, to, text, insert))) view.dispatch(insert());
}
function editor(marked: string, extensions: Extension) {
const pos = marked.indexOf("|");
return new EditorView({
state: EditorState.create({
doc: marked.replace("|", ""),
selection: { anchor: pos },
extensions,
}),
});
}
describe("Angular inline templates", () => {
it.each(["`", "'", '"'])("highlights a %s-quoted component template", async (quote) => {
const template = '<div [title]="name">{{ name }} @if (ready) {} @for (x of xs; track x) {} @let y = count;</div>';
const body = quote === '"' ? template.replaceAll('"', "'") : template;
const state = EditorState.create({
doc: `@Component({ template: ${quote}${body}${quote} }) class App {}`,
extensions: await inlineSupport(),
});
expect(tokens(state)).toEqual(
expect.arrayContaining(["div:tag", "title:attr", "name:var", "@if:control", "@for:control", "@let:definition"]),
);
});
it.each([
"const x = { template: `<div>{{ name }}</div>` };",
"@Other({ template: `<div>{{ name }}</div>` }) class App {}",
"@Component({ nested: { template: `<div>{{ name }}</div>` } }) class App {}",
"@Component({ templateUrl: `<div>{{ name }}</div>` }) class App {}",
"Component({ template: `<div>{{ name }}</div>` });",
"@Component({ template: `<div>${name}</div>` }) class App {}",
"@Component({ template: `<div>` + suffix }) class App {}",
])("keeps unrelated strings plain: %s", async (doc) => {
expect(tokens(EditorState.create({ doc, extensions: await inlineSupport() }))).not.toContain("div:tag");
});
it("keeps ordinary TypeScript projects plain", async () => {
const support = await loadSupport(findLanguageDescription("TypeScript", "/p/app.ts")!);
expect(
tokens(EditorState.create({ doc: "@Component({ template: `<div/>` }) class App {}", extensions: support! })),
).not.toContain("div:tag");
});
it("supports quoted metadata keys and namespace decorators", async () => {
const state = EditorState.create({
doc: '@ng.Component({ "template": `<r-card/>` }) class App {}',
extensions: await inlineSupport(),
});
expect(tokens(state)).toContain("r-card:tag");
});
it.each([
"@Component(/* metadata */ { template /* key */ : /* value */ `<div/>` }) class App {}",
"@Component({ template: `<div",
"@Component({ template: '<div",
])("highlights unfinished and commented templates: %s", async (doc) => {
expect(tokens(EditorState.create({ doc, extensions: await inlineSupport() }))).toContain("div:tag");
});
it("matches a fresh parse after editing templates and decorator context", async () => {
const extensions = await inlineSupport();
let state = EditorState.create({
doc: "@Component({ template: `<div>{{ name }}</div>` }) class App {}",
extensions,
});
for (const [search, replacement] of [
["name", "user.name"],
["Component", "Other"],
["Other", "Component"],
["template:", "other:"],
]) {
const from = state.doc.toString().indexOf(search!);
state = state.update({ changes: { from, to: from + search!.length, insert: replacement } }).state;
expect(tokens(state)).toEqual(tokens(EditorState.create({ doc: state.doc, extensions })));
}
});
});
describe.each(["inline", "external"])("Angular tag closing (%s)", (mode) => {
async function support() {
return mode === "inline" ? inlineSupport() : angular();
}
function wrap(template: string) {
return mode === "inline" ? `@Component({ template: \`${template}\` }) class App {}` : template;
}
it.each([
["<div|", ">", "<div></div>"],
["<div><|", "/", "<div></div>"],
["<r-card|", "/", "<r-card/>"],
["<r-card|>", "/", "<r-card/>"],
["<input|", ">", "<input>"],
['<r-card title="a/b|"', "/", '<r-card title="a/b/"'],
["<!-- <r-card| -->", "/", "<!-- <r-card/ -->"],
["{{ count |}}", "/", "{{ count /}}"],
])("handles %s + %s", async (before, text, after) => {
const view = editor(wrap(before), await support());
try {
type(view, text);
expect(view.state.doc.toString()).toBe(wrap(after));
} finally {
view.destroy();
}
});
it("closes tags at multiple cursors in one undoable input", async () => {
const doc = wrap("<r-card\n<app-item");
const ranges = [doc.indexOf("<r-card") + 7, doc.indexOf("<app-item") + 9].map((p) => EditorSelection.cursor(p));
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.create(ranges),
extensions: [await support(), history(), EditorState.allowMultipleSelections.of(true)],
}),
});
try {
type(view, "/");
expect(view.state.doc.toString()).toBe(wrap("<r-card/>\n<app-item/>"));
expect(undo(view)).toBe(true);
expect(view.state.doc.toString()).toBe(doc);
} finally {
view.destroy();
}
});
});
+47
Переглянути файл
@@ -0,0 +1,47 @@
import { LanguageSupport, LRLanguage } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import { parseMixed, type Input, type NestedParse, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
import { angular, angularLanguage } from "./index";
function nextCode(node: SyntaxNode): SyntaxNode | null {
let next = node.nextSibling;
while (next && (next.name === "BlockComment" || next.name === "LineComment")) next = next.nextSibling;
return next;
}
function mixTemplate(node: SyntaxNodeRef, input: Input): NestedParse | null {
if (node.name !== "Decorator") return null;
const call = node.node.getChild("CallExpression");
const callee = call?.firstChild;
const name = callee?.name === "MemberExpression" ? callee.lastChild : callee;
if (!name || !["VariableName", "PropertyName"].includes(name.name) || input.read(name.from, name.to) !== "Component")
return null;
const args = call?.getChild("ArgList");
const metadata = args?.firstChild && nextCode(args.firstChild);
if (metadata?.name !== "ObjectExpression") return null;
for (const property of metadata.getChildren("Property")) {
const key = property.firstChild;
if (!key || !["template", "'template'", '"template"'].includes(input.read(key.from, key.to))) continue;
const colon = nextCode(key);
const value = colon?.name === ":" ? nextCode(colon) : null;
if (!value || nextCode(value) || !["String", "TemplateString"].includes(value.name)) continue;
// A dynamic JavaScript template retains its interpolation expressions.
if (value.getChild("Interpolation")) continue;
const quote = input.read(value.from, value.from + 1);
const from = value.from + 1;
const to = value.to - (!value.lastChild?.type.isError && input.read(value.to - 1, value.to) === quote ? 1 : 0);
if (from < to) return { parser: angularLanguage.parser, overlay: [{ from, to }] };
}
return null;
}
const typescript = javascript({ typescript: true });
export function angularTypescript(): LanguageSupport {
// Mount on the decorator so changing its name or metadata invalidates the template too.
const language = (typescript.language as LRLanguage).configure(
{ wrap: parseMixed(mixTemplate) },
"angular-typescript",
);
return new LanguageSupport(language, [typescript.support, angular().support]);
}
+73
Переглянути файл
@@ -0,0 +1,73 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { goModParser, initialGoModState, type GoModState } from "./gomod";
import { StringStream } from "@codemirror/language";
function tokenize(line: string, state: GoModState) {
const stream = new StringStream(line, 4, 1);
const tokens: { text: string; token: string | null }[] = [];
while (!stream.eol()) {
const start = stream.pos;
const kind = goModParser.token(stream, state);
if (stream.pos > start && kind !== null) {
tokens.push({ text: stream.string.slice(start, stream.pos), token: kind });
}
}
return tokens;
}
describe("goModParser", () => {
it("highlights module declaration and go version", () => {
const state = initialGoModState();
const line1 = tokenize("module onpay-aplikasi-api", state);
expect(line1).toEqual([
{ text: "module", token: "keyword" },
{ text: "onpay-aplikasi-api", token: "string" },
]);
const line2 = tokenize("go 1.27.0", state);
expect(line2).toEqual([
{ text: "go", token: "keyword" },
{ text: "1.27.0", token: "number" },
]);
});
it("highlights require blocks with module paths and versions", () => {
const state = initialGoModState();
const line1 = tokenize("require (", state);
expect(line1).toEqual([
{ text: "require", token: "keyword" },
{ text: "(", token: "paren" },
]);
const line2 = tokenize("\tcloud.google.com/go/auth v0.20.0", state);
expect(line2).toEqual([
{ text: "cloud.google.com/go/auth", token: "string" },
{ text: "v0.20.0", token: "number" },
]);
const line3 = tokenize("\tgithub.com/shopspring/decimal v1.4.0 // indirect", state);
expect(line3).toEqual([
{ text: "github.com/shopspring/decimal", token: "string" },
{ text: "v1.4.0", token: "number" },
{ text: "// indirect", token: "comment" },
]);
const line4 = tokenize(")", state);
expect(line4).toEqual([{ text: ")", token: "paren" }]);
});
it("highlights replace directive with operator", () => {
const state = initialGoModState();
const line = tokenize("replace example.com/foo => ../bar", state);
expect(line).toEqual([
{ text: "replace", token: "keyword" },
{ text: "example.com/foo", token: "string" },
{ text: "=>", token: "operator" },
{ text: "../bar", token: "string" },
]);
});
});
+98
Переглянути файл
@@ -0,0 +1,98 @@
import { StreamLanguage, type StreamParser } from "@codemirror/language";
const KEYWORDS = new Set(["module", "go", "toolchain", "require", "replace", "exclude", "retract", "use"]);
export interface GoModState {
currentKeyword: string | null;
inBlock: boolean;
expectVersion: boolean;
}
export function initialGoModState(): GoModState {
return {
currentKeyword: null,
inBlock: false,
expectVersion: false,
};
}
export const goModParser: StreamParser<GoModState> = {
name: "gomod",
startState: () => initialGoModState(),
token(stream, state) {
if (stream.eatSpace()) return null;
if (stream.sol()) {
if (!state.inBlock) {
state.currentKeyword = null;
}
state.expectVersion = false;
}
// Comment
if (stream.match(/^\/\/.*/)) {
return "comment";
}
// Punctuation & operators
if (stream.match(/^=>/)) {
state.expectVersion = false;
return "operator";
}
if (stream.eat("(")) {
state.inBlock = true;
return "paren";
}
if (stream.eat(")")) {
state.inBlock = false;
state.currentKeyword = null;
return "paren";
}
// String literals
if (stream.match(/^"(?:[^"\\]|\\.)*"/)) {
return "string";
}
if (stream.match(/^`[^`]*`/)) {
return "string";
}
// Check words/tokens
const wordMatch = stream.match(/^[^\s()]+/) as RegExpMatchArray | null;
if (!wordMatch) {
stream.next();
return null;
}
const token = wordMatch[0] ?? "";
// Keyword at start of statement (not expecting a version)
if (!state.expectVersion && KEYWORDS.has(token)) {
state.currentKeyword = token;
return "keyword";
}
// Semantic versions: v1.2.3, 1.22, 1.22.0, v0.0.0-2023..., v4.4.0+incompatible
const isVersion = /^v?[0-9]+(\.[0-9]+)*([+-][a-zA-Z0-9_.-]+)*$/.test(token) || /^\[v?[0-9]+.*\]$/.test(token);
if (isVersion) {
state.expectVersion = false;
return "number";
}
// In require/replace/use block or following module/require keyword:
// The first token is the module path/package name (string in GoLand: green)
if (state.currentKeyword) {
state.expectVersion = true;
return "string";
}
return null;
},
languageData: {
commentTokens: { line: "//" },
indentOnInput: /^\s*\)\s*$/,
},
};
export const goModLanguage = StreamLanguage.define(goModParser);
+14
Переглянути файл
@@ -151,4 +151,18 @@ describe("language modes", () => {
expect(derefs, mode).toEqual(["?.", ".", "?."]);
}
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
[null, "/project/go.mod"],
["GoMod", "/project/go.work"],
[null, "/project/go.work"],
] as const) {
const desc = findLanguageDescription(mode, path);
expect(desc?.name).toBe("GoMod");
const support = await loadSupport(desc!);
expect(support?.language).toBeTruthy();
}
});
});
+13 -1
Переглянути файл
@@ -113,6 +113,10 @@ const OWN_MODES = [
},
}),
),
LanguageDescription.of({
name: "Angular TypeScript",
load: () => import("./angular/inline").then((m) => m.angularTypescript()),
}),
LanguageDescription.of({ name: "Angular Template", load: () => import("./angular").then((m) => m.angular()) }),
LanguageDescription.of({
name: "ERB",
@@ -141,6 +145,13 @@ const OWN_MODES = [
);
},
}),
LanguageDescription.of({
name: "GoMod",
alias: ["gomod", "gowork"],
extensions: ["mod", "work"],
filename: /^(?:go\.mod|go\.work)$/,
load: async () => new LanguageSupport((await import("./gomod")).goModLanguage),
}),
];
const BATCH_KEYWORDS = new Set([
@@ -224,9 +235,9 @@ export function findLanguageDescription(uiMode: string | null, path: string): La
const loose = LanguageDescription.matchLanguageName(BUILTIN_MODES, uiMode, false);
if (loose) return OWN_MODES.find((l) => l.name === loose.name) ?? loose;
}
if (uiMode === null && infos) return null;
const own = LanguageDescription.matchFilename(OWN_MODES, path.slice(path.lastIndexOf("/") + 1));
if (own) return own;
if (uiMode === null && infos) return null;
const matched = LanguageDescription.matchFilename(BUILTIN_MODES, path.slice(path.lastIndexOf("/") + 1));
return OWN_MODES.find((l) => l.name === matched?.name) ?? matched;
}
@@ -267,6 +278,7 @@ export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
JavaScript: JS_TAGS,
TypeScript: JS_TAGS,
"Angular TypeScript": JS_TAGS,
JSX: JS_TAGS,
TSX: JS_TAGS,
Java: JAVA_TAGS,
+14
Переглянути файл
@@ -231,6 +231,20 @@ describe("DocumentManager + slots", () => {
expect(slot.currentState().facet(languageFacet)?.name).not.toBe("angular");
});
it.each(["ts", "mts", "cts"])("loads Angular inline templates for .%s documents", async (ext) => {
const path = `/p/src/app.${ext}`;
const { manager } = setup({
"/p/angular.json": "{}",
[path]: "@Component({ template: `<r-card/>` }) class App {}",
});
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
expect(model.getMeta()).toMatchObject({ language: "typescript", uiMode: "Angular TypeScript" });
expect(slot.currentState().facet(languageFacet)?.name).toBe("angular-typescript");
slot.dispose();
manager.stop();
});
it("Save All rejects a failed document save after saving the remaining dirty documents", async () => {
const { backend, manager } = setup({ "/p/a.txt": "a\n", "/p/b.txt": "b\n" }, { files: { autoSave: false } });
try {
-3
Переглянути файл
@@ -14,6 +14,3 @@
border-radius: var(--radius-small);
cursor: pointer;
}
.marker:hover {
background: var(--bg-hover);
}
+41
Переглянути файл
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import type { Variable } from "@/platform/ipc";
import { valueText } from "../valueText";
const v = (name: string, value: string, variablesReference = 0): Variable =>
({ name, value, variablesReference, typeName: null, evaluateName: null }) as Variable;
const fetcher = (tree: Record<number, Variable[]>) => async (ref: number) => tree[ref] ?? [];
describe("valueText", () => {
it("returns a scalar as is", async () => {
expect(await valueText({ value: "42", reference: 0 }, fetcher({}))).toBe("42");
});
it("copies a PHP array with its nested elements", async () => {
const tree = {
1: [v("name", '"Ann"'), v("tags", "array(2)", 2)],
2: [v("0", '"a"'), v("1", '"b"')],
};
expect(await valueText({ value: "array(2)", reference: 1 }, fetcher(tree))).toBe(
["array(2)", ' name: "Ann"', " tags: array(2)", ' 0: "a"', ' 1: "b"'].join("\n"),
);
});
it("stops at a cycle", async () => {
const tree = { 1: [v("self", "Node", 1)] };
expect(await valueText({ value: "Node", reference: 1 }, fetcher(tree))).toBe("Node\n self: Node");
});
it("truncates past the entry limit", async () => {
const tree = { 1: [v("0", "a"), v("1", "b"), v("2", "c")] };
const text = await valueText({ value: "arr", reference: 1 }, fetcher(tree), { depth: 8, entries: 2 });
expect(text).toBe("arr\n 0: a\n 1: b\n …");
});
it("truncates past the depth limit", async () => {
const tree = { 1: [v("a", "x", 2)], 2: [v("b", "y", 3)], 3: [v("c", "z")] };
const text = await valueText({ value: "r", reference: 1 }, fetcher(tree), { depth: 2, entries: 100 });
expect(text).toBe("r\n a: x\n b: y\n …");
});
});
+21 -1
Переглянути файл
@@ -11,6 +11,7 @@ import { methodAt } from "../breakpoints/symbols";
import { activeSession, addWatch, removeWatch, revealFrame, sessionSupports, setVariableValue } from "../state";
import { blurDebugView, focusDebugView } from "./focusedView";
import { classifyValue, oneLine, sortVariables } from "../values";
import { valueText } from "../valueText";
import { workflowSettings } from "@/platform/workflowSettings";
import styles from "./VariablesView.module.css";
@@ -270,6 +271,25 @@ export function VariablesView({
const canWatch = (n: VarNode) =>
session != null && n.kind === "var" && n.container > 0 && sessionSupports("dataBreakpoints");
const copyValue = async (node: VarNode) => {
let text = node.value;
if (session != null && node.reference > 0) {
try {
text = await valueText(node, (ref) => call(commands.debugVariables(session, ref)));
} catch (e) {
notifications().notify({
group: "run",
level: "error",
key: "debug.copyValue",
title: "Cannot copy the value",
body: e instanceof Error ? e.message : String(e),
});
return;
}
}
await navigator.clipboard?.writeText(text);
};
const onContextMenu = (node: VarNode | null, _sel: Set<string>, e: React.MouseEvent) => {
if (!node || node.kind === "message") return;
e.preventDefault();
@@ -281,7 +301,7 @@ export function VariablesView({
);
if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) });
if (node.kind !== "scope") {
items.push({ label: "Copy Value", icon: "copy", run: () => void navigator.clipboard?.writeText(node.value) });
items.push({ label: "Copy Value", icon: "copy", run: () => void copyValue(node) });
items.push({ label: "Copy Name", run: () => void navigator.clipboard?.writeText(node.name) });
if (node.kind === "var" && node.evaluateName)
items.push({ label: "Add to Watches", icon: "eye", run: () => addWatch(node.evaluateName!) });
+53
Переглянути файл
@@ -0,0 +1,53 @@
/** Text for "Copy Value": a structured value (array, object, map) is copied with its contents, not its summary. */
import type { Variable } from "@/platform/ipc";
export interface ValueTextRoot {
value: string;
reference: number;
}
export interface ValueTextLimits {
depth: number;
entries: number;
}
export const VALUE_TEXT_LIMITS: ValueTextLimits = { depth: 8, entries: 2000 };
/**
* `value` alone for a scalar; for an expandable value the summary line followed by its children,
* one per line and indented by depth. Cycles and anything past the limits end in an ellipsis line.
*/
export async function valueText(
root: ValueTextRoot,
fetchChildren: (reference: number) => Promise<Variable[]>,
limits: ValueTextLimits = VALUE_TEXT_LIMITS,
): Promise<string> {
if (root.reference <= 0) return root.value;
const lines = [root.value];
let budget = limits.entries;
const path = new Set<number>([root.reference]);
const walk = async (reference: number, depth: number): Promise<void> => {
const pad = " ".repeat(depth);
if (depth > limits.depth) {
lines.push(`${pad}…`);
return;
}
for (const child of await fetchChildren(reference)) {
if (budget-- <= 0) {
lines.push(`${pad}…`);
return;
}
lines.push(`${pad}${child.name}: ${child.value}`);
const ref = child.variablesReference;
if (ref > 0 && !path.has(ref)) {
path.add(ref);
await walk(ref, depth + 1);
path.delete(ref);
}
}
};
await walk(root.reference, 1);
return lines.join("\n");
}
-3
Переглянути файл
@@ -220,9 +220,6 @@
border-radius: var(--radius-small);
cursor: pointer;
}
.runMarker:hover {
background: var(--bg-hover);
}
/* Query result and variables: JSON in the editor's syntax colours. */
.output :global(.tok-propertyName),
+12 -8
Переглянути файл
@@ -29,8 +29,8 @@ export const OPTION_LABELS: Array<[ToggleOption, string]> = [
["showMembers", "Show Members"],
["compact", "Compact Middle Packages"],
["foldersFirst", "Sort Folders First"],
["autoscrollFromSource", "Always Select Opened File"],
["autoscrollToSource", "Autoscroll to Source"],
["autoscrollFromSource", "Autoscroll from Source"],
["singleClickOpen", "Open Files with Single Click"],
["singleClickExpand", "Expand Directories with Single Click"],
["previewTab", "Enable Preview Tab"],
@@ -38,15 +38,19 @@ export const OPTION_LABELS: Array<[ToggleOption, string]> = [
/** Header controls of the Project tool window (IDEA: Locate, Expand/Collapse All). */
export function ProjectHeaderActions() {
// IDEA hides Select Opened File while Always Select Opened File keeps the tree in sync.
const alwaysSelect = useProjectTree((s) => s.options.autoscrollFromSource);
return (
<>
<IconButton
icon="locate"
action="navigate.selectInProjectView"
title="Select Opened File"
shortcut={shortcutLabel("navigate.selectInProjectView")}
size="small"
/>
{!alwaysSelect && (
<IconButton
icon="locate"
action="navigate.selectInProjectView"
title="Select Opened File"
shortcut={shortcutLabel("navigate.selectInProjectView")}
size="small"
/>
)}
<IconButton icon="expand-all" action="project.expandAll" title="Expand All" size="small" />
<IconButton icon="collapse-all" action="project.collapseAll" title="Collapse All" size="small" />
</>
+34 -1
Переглянути файл
@@ -14,7 +14,8 @@ import { ProjectView } from "./ProjectView";
import { beginNew, canPaste } from "./operations";
import { initProjectTree, setViewOption, useProjectTree } from "./store";
import type { OutlineItem } from "@/bindings";
import { _emitEditorEvent } from "@/editor/api";
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
import { ProjectHeaderActions } from "./HeaderActions";
import { loadOutline } from "./store";
const ipc = vi.hoisted(() => ({
@@ -220,6 +221,38 @@ describe("ProjectView", () => {
act(() => setViewOption("previewTab", false));
});
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
const focusEditor = (path: string) => act(() => useEditorRegistry.setState({ active: { ctx: { path } } } as never));
const selected = () =>
screen
.getAllByRole("treeitem")
.filter((r) => r.getAttribute("aria-selected") === "true")
.map((r) => r.textContent);
try {
render(<ProjectHeaderActions />);
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
expect(screen.getByRole("button", { name: "Select Opened File" })).toBeTruthy();
focusEditor("/w/acme/src/Util.kt");
expect(rows()).not.toContain("Util.kt");
act(() => setViewOption("autoscrollFromSource", true));
await waitFor(() => expect(selected()).toEqual(["Util.kt"]));
expect(screen.queryByRole("button", { name: "Select Opened File" })).toBeNull();
focusEditor("/w/acme/README.md");
await waitFor(() => expect(selected()).toEqual(["README.md"]));
focusEditor("/w/acme/src/App.kt");
await waitFor(() => expect(selected()).toEqual(["App.kt"]));
act(() => setViewOption("autoscrollFromSource", false));
focusEditor("/w/acme/README.md");
expect(selected()).toEqual(["App.kt"]);
expect(screen.getByRole("button", { name: "Select Opened File" })).toBeTruthy();
} finally {
act(() => useEditorRegistry.setState({ active: null }));
}
});
it("expands and collapses folders on single click only when enabled", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
+2 -1
Переглянути файл
@@ -166,7 +166,8 @@ export function registerProjectActions(): () => void {
id: `project.option.${key}`,
title: tx`Project View: ${label}`,
category: "View",
keywords: ["project", "tree", "toggle"],
// IDEA's former name of Always Select Opened File.
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
toggled: () => useProjectTree.getState().options[key],
run: () => setViewOption(key, !useProjectTree.getState().options[key]),
}));
+1 -1
Переглянути файл
@@ -38,7 +38,7 @@ import { projectViewRoots, useProjectViewRoots, type ProjectViewRootContribution
import { ancestorsWithin, isSameOrInside, nameOf, type PackageKind } from "./paths";
export interface ViewOptions extends TreeOptions {
/** Select the active editor's file in the tree. */
/** Select the active editor's file in the tree (IDEA: Always Select Opened File). */
autoscrollFromSource: boolean;
/** Open the selected file while navigating the tree (preview, no focus change). */
autoscrollToSource: boolean;
+4 -4
Переглянути файл
@@ -90,7 +90,7 @@ export function RunWidget() {
<IconButton
icon="resume"
size="large"
iconSize={18}
iconSize={20}
className={styles.widgetButton}
title="Resume Program"
shortcut={shortcutLabel("debug.resume")}
@@ -113,7 +113,7 @@ export function RunWidget() {
<IconButton
icon="run"
size="large"
iconSize={18}
iconSize={20}
className={clsx(styles.widgetButton, styles.widgetRun)}
title={
selected
@@ -131,7 +131,7 @@ export function RunWidget() {
<IconButton
icon="debug"
size="large"
iconSize={18}
iconSize={20}
className={styles.widgetButton}
title={selected ? tx`Debug '${selected.name}'` : currentFile ? "Debug Current File" : "Debug"}
shortcut={shortcutLabel("run.debug")}
@@ -168,7 +168,7 @@ export function RunWidget() {
ref={moreRef}
icon="more"
size="large"
iconSize={18}
iconSize={20}
className={styles.widgetButton}
title="More Actions"
aria-haspopup="menu"
-3
Переглянути файл
@@ -160,9 +160,6 @@
border-radius: var(--radius-small);
cursor: pointer;
}
.marker:hover {
background: var(--bg-hover);
}
.fieldRow {
display: flex;
+2 -1
Переглянути файл
@@ -65,5 +65,6 @@
"Branch Conversation from Here": "Branch Conversation from Here",
"Couldn't regenerate the response": "Couldn't regenerate the response",
"Reasoning": "Reasoning",
"Branch '{name}'": "Branch '{name}'"
"Branch '{name}'": "Branch '{name}'",
"Cannot copy the value": "Cannot copy the value"
}
+1
Переглянути файл
@@ -227,6 +227,7 @@
"Allow placing breakpoints in any file": "Permitir colocar puntos de interrupción en cualquier archivo",
"Also expand in comments and strings": "Expandir también en comentarios y cadenas",
"Always": "Siempre",
"Always Select Opened File": "Seleccionar siempre el archivo abierto",
"Always show full path in window header": "Mostrar siempre la ruta completa en el encabezado de la ventana",
"Amend": "Enmendar",
"Analysing…": "Analizando…",
+1
Переглянути файл
@@ -175,6 +175,7 @@
"Allow placing breakpoints in any file": "Autoriser les points d'arrêt dans n'importe quel fichier",
"Also expand in comments and strings": "Développer aussi dans les commentaires et les chaînes",
"Always": "Toujours",
"Always Select Opened File": "Toujours sélectionner le fichier ouvert",
"Always show full path in window header": "Toujours afficher le chemin complet dans l'en-tête de la fenêtre",
"Amend": "Amender",
"Analysing…": "Analyse…",
+1
Переглянути файл
@@ -267,6 +267,7 @@
"Allow placing breakpoints in any file": "모든 파일에 중단점 설정 허용",
"Also expand in comments and strings": "주석과 문자열에서도 확장",
"Always": "항상",
"Always Select Opened File": "항상 열린 파일 선택",
"Always show full path in window header": "항상 창 헤더에 전체 경로 표시",
"Amend": "수정",
"Analysing…": "분석 중…",
+1
Переглянути файл
@@ -219,6 +219,7 @@
"Allow placing breakpoints in any file": "Zezwalaj na umieszczanie punktów przerwania w dowolnym pliku",
"Also expand in comments and strings": "Rozwijaj również w komentarzach i ciągach znaków",
"Always": "Zawsze",
"Always Select Opened File": "Zawsze zaznaczaj otwarty plik",
"Always show full path in window header": "Zawsze pokazuj pełną ścieżkę w nagłówku okna",
"Amend": "Popraw (Amend)",
"Analysing…": "Analizowanie…",
+1
Переглянути файл
@@ -219,6 +219,7 @@
"Allow placing breakpoints in any file": "Permitir colocar pontos de interrupção em qualquer arquivo",
"Also expand in comments and strings": "Também expandir em comentários e strings",
"Always": "Sempre",
"Always Select Opened File": "Sempre selecionar o arquivo aberto",
"Always show full path in window header": "Sempre mostrar o caminho completo no cabeçalho da janela",
"Amend": "Amend",
"Analysing…": "Analisando…",
+3 -1
Переглянути файл
@@ -271,6 +271,7 @@
"Allow placing breakpoints in any file": "允许在任意文件中设置断点",
"Also expand in comments and strings": "也在注释和字符串中展开",
"Always": "始终",
"Always Select Opened File": "始终选择打开的文件",
"Always show full path in window header": "始终在窗口标题中显示完整路径",
"Amend": "修改",
"Analysing…": "正在分析…",
@@ -6440,5 +6441,6 @@
"Regenerate Response": "重新生成回复",
"Branch Conversation from Here": "从此处创建分支对话",
"Couldn't regenerate the response": "无法重新生成回复",
"Reasoning": "思考过程"
"Reasoning": "思考过程",
"Cannot copy the value": "无法复制该值"
}
+1 -1
Переглянути файл
@@ -253,7 +253,7 @@ html {
--h-titlebar: 40px;
--titlebar-tool-button: 30px;
/* tool window stripe button, icons only */
--stripe-icon-button: 28px;
--stripe-icon-button: 30px;
--stripe-outer-padding: 4px;
--h-header: 40px;
--h-tabbar: 38px;
+1 -1
Переглянути файл
@@ -991,7 +991,7 @@ const EXT_ICONS = table({
"file-perl": "pl pm pod psgi cgi",
"file-c": "c",
"file-h": "h hpp hh hxx h++",
"file-cpp": "cpp cc cxx c++ ipp tpp inl ixx cppm",
"file-cpp": "cpp cc cxx c++ ipp tpp inl ixx cppm ino",
"file-objc": "m",
"file-objcpp": "mm",
"file-csharp": "cs csx",
+2 -2
Переглянути файл
@@ -235,7 +235,7 @@ function GearButton({ customize }: { customize: MenuItem[] }) {
ref={ref}
icon="settings"
title="IDE and Project Settings"
iconSize={18}
iconSize={20}
className={styles.tool}
aria-haspopup="menu"
aria-expanded={open}
@@ -263,7 +263,7 @@ function ToolbarEntry({ id, items }: { id: string; items: ReadonlyMap<string, Ti
action={action.id}
title={action.title}
shortcut={shortcutLabel(action.id) ?? (action.id === "navigate.searchEverywhere" ? "⇧⇧" : undefined)}
iconSize={18}
iconSize={20}
className={styles.tool}
/>
</div>
+16 -5
Переглянути файл
@@ -168,8 +168,10 @@
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 0 0 6px;
/* Icon buttons repeat at the title bar's height, so the title bar's Settings button reads as the right stripe's first one, as in IDEA. */
--stripe-gap: calc(var(--h-titlebar) - var(--stripe-icon-button));
gap: var(--stripe-gap);
padding: calc(var(--stripe-gap) / 2) 0 6px;
/* Transparent: stripes sit on the window frame so the project-colour wash flows from the title bar. */
background: transparent;
/* Short windows: scroll the buttons instead of clipping the last ones. */
@@ -182,7 +184,8 @@
}
.stripeWithNames {
--stripe-button: var(--stripe-drag, var(--stripe-button-w, 56px));
gap: 4px;
--stripe-gap: 4px;
padding-top: 0;
}
.stripeSideLeft {
padding-left: var(--stripe-pad);
@@ -256,7 +259,7 @@
padding: 6px 2px 5px;
}
.stripeMore {
height: 30px;
height: var(--stripe-icon-button);
}
.stripeWithNames .stripeMore {
width: var(--stripe-button);
@@ -426,9 +429,17 @@
display: flex;
flex-direction: column;
}
/* The drop target after a group's last button is empty: don't let it add a gap between groups. */
.stripeSlotEnd {
margin-top: calc(-1 * var(--stripe-gap));
}
.stripeSlotEnd .stripeDrop {
top: calc(var(--stripe-gap) / 2 - 1px);
}
.stripeDrop {
position: absolute;
top: -3px;
/* Centred in the gap above the slot; the end slot sits on the last button's bottom edge, so below it. */
top: calc(var(--stripe-gap) / -2 - 1px);
left: 6px;
right: 6px;
height: 2px;
+4 -4
Переглянути файл
@@ -218,7 +218,7 @@ function StripeHandle({
const el = e.currentTarget;
el.setPointerCapture(e.pointerId);
const origin = e.clientX;
const icons = parseFloat(getComputedStyle(stripe).getPropertyValue("--stripe-icon-button")) || 28;
const icons = parseFloat(getComputedStyle(stripe).getPropertyValue("--stripe-icon-button")) || 30;
const start = names ? width : icons;
const cursor = document.body.style.cursor;
document.body.style.cursor = "col-resize";
@@ -418,7 +418,7 @@ function StripeButton({
{...tooltipAttrs(tw.title, shortcut)}
>
<span className={styles.stripeIcon}>
<Icon name={tw.icon} size={18} />
<Icon name={tw.icon} size={20} />
{tw.useBadge && <StripeBadge useBadge={tw.useBadge} />}
</span>
{showName && (
@@ -459,7 +459,7 @@ function StripeMore({ windows }: { windows: ToolWindowContribution[] }) {
onClick={() => setOpen((v) => !v)}
{...tooltipAttrs("More Tool Windows")}
>
<Icon name="more-horizontal" size={18} />
<Icon name="more-horizontal" size={20} />
</button>
<Menu
open={open}
@@ -522,7 +522,7 @@ export function ToolWindowStripe({
<StripeButton tw={w} active={isActive(w)} focused={focused === w.id} side={side} showName={showNames} />
</div>
))}
<div className={styles.stripeSlot}>{indicator(slot, null)}</div>
<div className={clsx(styles.stripeSlot, styles.stripeSlotEnd)}>{indicator(slot, null)}</div>
</div>
);