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

..
Автор SHA1 Повідомлення Дата
l0ng-ai f98134c5d5 fix(vcs): show a committed directory symlink's target in revision diffs
Revision content was decoded with the working file's encoding, read
whenever the path existed. For a symlink to a folder that path is a
directory, so loading it failed and the Git Log diff showed
"<path> is a directory" instead of the link target. The working file is
now consulted only when it is a regular file; otherwise the encoding is
detected from the revision's blob.

Closes #3528
2026-11-15 23:11:38 +08:00
46 змінених файлів з 58 додано та 691 видалено

No files matched your search

-5
Переглянути файл
@@ -170,11 +170,6 @@ pub struct LanguageServerConfig {
/// basedpyright): only used while none of those is installed.
#[serde(default)]
pub fallback: bool,
/// Names of servers listed after this one that it makes redundant (a PHP server
/// with its own Laravel support replaces `laravel-lsp`): they aren't used while
/// this one serves the file.
#[serde(default)]
pub replaces: Vec<String>,
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
/// capabilities it announces are ignored, so a refactoring-only server next
+1 -4
Переглянути файл
@@ -758,10 +758,7 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "laravel-lsp"]);
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
+9 -26
Переглянути файл
@@ -660,17 +660,15 @@ impl LspManager {
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it have given up (missing, not
/// launchable, or crashed for good). One that requires a root marker serves
/// only files below one, and stands in for no other. One that a server before
/// it `replaces` is left out while that server serves the file.
/// only files below one, and stands in for no other.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
if let Some(servers) = self.arduino_servers(language, path) {
return servers;
}
let mut out = Vec::new();
let mut available_before = false;
let mut replaced: Vec<String> = Vec::new();
for sc in &self.language_servers(language) {
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
if sc.fallback && available_before {
continue;
}
if sc.require_root_marker
@@ -680,9 +678,6 @@ impl LspManager {
}
let server = self.server_for(sc, language, path);
available_before |= !sc.require_root_marker && !server.gave_up();
if !server.gave_up() {
replaced.extend(sc.replaces.iter().cloned());
}
out.push(server);
}
out
@@ -870,7 +865,7 @@ impl LspManager {
ide_core::event::ServerStatus::Missing,
Some(message),
) {
self.fallbacks_take_over().await;
self.attach_fallbacks();
}
return;
}
@@ -883,7 +878,7 @@ impl LspManager {
ide_core::event::ServerStatus::Misconfigured,
Some(message),
) {
self.fallbacks_take_over().await;
self.attach_fallbacks();
}
return;
}
@@ -896,7 +891,7 @@ impl LspManager {
ide_core::event::ServerStatus::Crashed,
Some(message),
) {
self.fallbacks_take_over().await;
self.attach_fallbacks();
}
return;
}
@@ -1044,7 +1039,7 @@ impl LspManager {
}
}
// Gave up (crashed repeatedly, or its build expired): the fallbacks it hid take over.
None => self.fallbacks_take_over().await,
None => self.attach_fallbacks(),
}
}
@@ -3469,10 +3464,7 @@ impl LspManager {
virtual_doc::is_decompiled(&text)
};
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
let mut detected = self.languages.detect(Path::new(&title), None);
if let Some(stem) = title.strip_suffix(".class").filter(|_| virtual_doc::is_java_class_stub(&text)) {
detected = self.languages.detect(Path::new(&format!("{stem}.java")), None);
}
let detected = self.languages.detect(Path::new(&title), None);
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
@@ -3836,16 +3828,8 @@ impl LspManager {
}
}
/// A server gave up: its fallbacks take over the open documents, and the servers
/// they replace leave.
async fn fallbacks_take_over(&self) {
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
}
/// A server enabled again shadows the fallbacks attached in its place, and a
/// fallback that took over may replace a server attached earlier: they leave the
/// open documents, and stop once no document uses them.
/// A server enabled again shadows the fallbacks attached in its place: they
/// leave the open documents, and stop once no document uses them.
async fn detach_shadowed_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
@@ -3861,7 +3845,6 @@ impl LspManager {
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
})
.map(|a| a.server.id)
-22
Переглянути файл
@@ -110,17 +110,6 @@ pub fn is_decompiled(text: &str) -> bool {
})
}
/// Whether a `.class` stub is written in Java: its first `package` or `import` line ends with `;`.
/// The Kotlin language server shows Java classes from jars as Java and Kotlin ones as Kotlin, under
/// the same `.class` name.
pub fn is_java_class_stub(text: &str) -> bool {
text.lines()
.take(200)
.map(str::trim)
.find(|line| line.starts_with("package ") || line.starts_with("import "))
.is_some_and(|line| line.ends_with(';'))
}
/// `scheme` of a URI (`jdt` for `jdt://…`).
pub fn scheme(uri: &str) -> &str {
uri.split_once(':').map(|(s, _)| s).unwrap_or("")
@@ -216,17 +205,6 @@ mod tests {
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
#[test]
fn class_stubs_in_java_or_kotlin() {
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
let kotlin = "// IntelliJ API Decompiler stub source generated from a class file\n// Implementation of methods is not available\n\npackage kotlin.collections\n\npublic fun <T> listOf(): List<T> { /* compiled code */ }\n";
let imports_only = "import java.util.List;\n\npublic class A {}\n";
assert!(is_java_class_stub(java));
assert!(is_java_class_stub(imports_only));
assert!(!is_java_class_stub(kotlin));
assert!(!is_java_class_stub("public class A {}"));
}
#[test]
fn csharp_metadata_titles_and_kinds() {
for (uri, expected) in [
-62
Переглянути файл
@@ -264,7 +264,6 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -3287,67 +3286,6 @@ async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
h.wait_status("alt", ServerStatus::Ready).await;
}
/// A server that `replaces` another (a PHP server with its own Laravel support and
/// `laravel-lsp`) keeps it away while it serves, and only then.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_server_stays_away_while_its_replacement_serves() {
let servers = [("main", incremental_caps()), ("alt", incremental_caps()), ("framework", incremental_caps())];
let configure = |cfg: &mut LanguageServerConfig| match cfg.name.as_str() {
"alt" => {
cfg.fallback = true;
cfg.replaces = vec!["framework".into()];
}
"framework" => cfg.require_root_marker = true,
_ => {}
};
let h = harness_configured("mock", "mk", &servers, configure);
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
// The preferred server serves: the framework's server joins it, the alternative stays away.
h.wait_status("main", ServerStatus::Ready).await;
h.wait_status("framework", ServerStatus::Ready).await;
eventually(|| h.launcher.state("framework").docs.lock().contains_key(&uri)).await;
assert!(h.statuses("alt").is_empty());
// The alternative takes over: the server it replaces closes the document and stops.
disabled.lock().push("main".into());
h.mgr.reconfigure().await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("framework").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("framework").last(), Some(&ServerStatus::Stopped));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
// The preferred server again: the framework's server comes back with it.
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("main", ServerStatus::Ready).await;
eventually(|| h.statuses("framework").last() == Some(&ServerStatus::Ready)).await;
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
// A preferred server that is not installed: the alternative replaces the framework's
// server although that one attached first.
let servers = [("ghost", json!({})), ("alt", incremental_caps()), ("framework", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, configure);
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
h.wait_status("ghost", ServerStatus::Missing).await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
eventually(|| !h.mgr.servers().iter().any(|s| s.name == "framework")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
-3
Переглянути файл
@@ -419,7 +419,6 @@ async fn missing_binary_is_reported_with_install_hint() {
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -693,7 +692,6 @@ async fn typescript_language_server_end_to_end() {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -747,7 +745,6 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
-1
Переглянути файл
@@ -1306,7 +1306,6 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
}),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
-1
Переглянути файл
@@ -35,7 +35,6 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
-22
Переглянути файл
@@ -170,28 +170,6 @@ mod tests {
assert_eq!(select_asset(&["laravel-lsp"], rules, LINUX_X64), None);
}
#[test]
fn phoxite_assets() {
let names = [
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-x86_64-pc-windows-msvc.exe",
// Not for any platform here: the musl build, the checksums, the VS Code packages.
"phoxite-lsp-x86_64-unknown-linux-musl",
"phoxite-lsp-x86_64-unknown-linux-gnu.sha256",
"phoxite-lsp-x86_64-pc-windows-msvc.exe.sha256",
"phoxite-linux-x64-0.2.1.vsix",
];
let rules = crate::registry::find("phoxite").unwrap().asset_rules();
assert_eq!(select_asset(&names, rules, MAC_ARM), Some(names[0]));
assert_eq!(select_asset(&names, rules, MAC_X64), Some(names[1]));
assert_eq!(select_asset(&names, rules, LINUX_ARM), Some(names[2]));
assert_eq!(select_asset(&names, rules, LINUX_X64), Some(names[3]));
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
}
#[test]
fn kmp_lsp_assets_include_the_native_jar_indexer() {
let names = [
-32
Переглянути файл
@@ -458,38 +458,6 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
kind: LanguageServer,
commands: &["phoxite-lsp"],
// Plain binaries per platform (`phoxite-lsp-<target triple>[.exe]`), each with a
// `.sha256` beside it.
method: Method::Release {
source: ReleaseSource::GitHub { repo: "samehelhawary/phoxite" },
assets: &[
rule(Mac, Arm64, "phoxite-lsp-aarch64-apple-darwin"),
rule(Mac, X64, "phoxite-lsp-x86_64-apple-darwin"),
rule(Linux, Arm64, "phoxite-lsp-aarch64-unknown-linux-gnu"),
rule(Linux, X64, "phoxite-lsp-x86_64-unknown-linux-gnu"),
rule(Windows, Arm64, "phoxite-lsp-aarch64-pc-windows-msvc.exe"),
rule(Windows, X64, "phoxite-lsp-x86_64-pc-windows-msvc.exe"),
],
locate: &[
"phoxite-lsp",
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-aarch64-pc-windows-msvc",
"phoxite-lsp-x86_64-pc-windows-msvc",
],
},
fallback: None,
version: ver("phoxite-lsp"),
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
-1
Переглянути файл
@@ -101,7 +101,6 @@ Each entry starts one LSP server. Servers are listed in order; all regular serve
| `settings` | table | Answers the server's `workspace/configuration` requests. Without it, the requested sections are looked up in `initialization-options`. |
| `install-hint` | string | Shown when the server is missing and the IDE cannot install it. |
| `fallback` | bool | An alternative to the servers listed before it; used only while none of them is installed. |
| `replaces` | string array | Names of servers listed after this one that it makes redundant. They are not used while this server serves the file. Use it for an alternative that covers what an added server does. |
| `features` | string array | Use the server only for these features; empty means everything. Values: `completion`, `inline-completion`, `hover`, `signature-help`, `definition`, `declaration`, `type-definition`, `implementation`, `references`, `document-highlight`, `document-symbol`, `workspace-symbol`, `code-action`, `code-lens`, `rename`, `formatting`, `inlay-hint`, `semantic-tokens`, `document-link`, `call-hierarchy`, `type-hierarchy`, `folding-range`, `selection-range`, `diagnostics`. |
| `code-action-kinds` | string array | Keep only these code action kinds, matched by prefix (`refactor` keeps `refactor.extract`); empty keeps all. |
| `connect` | string | `host:port` of a server that speaks LSP over TCP. See [TCP servers](#tcp-servers). |
+1 -1
Переглянути файл
@@ -148,7 +148,7 @@ The table lists every built-in language definition. Server and debugger names in
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
+7 -11
Переглянути файл
@@ -7,14 +7,11 @@ OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.p
## Language servers
| Server | When it runs |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
While Phoxite serves a project, `laravel-lsp` is not started: Phoxite answers the Laravel strings itself.
| Server | When it runs |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
@@ -28,7 +25,6 @@ When a `.php` file opens and Intelephense is missing, a notification offers **In
| ------------------ | ---------------------------------------------------------------------- |
| Intelephense | npm (`intelephense`) |
| Laravel LSP | GitHub release (`laravel/lsp`) |
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
@@ -81,12 +77,12 @@ See [Debugging](/en/guide/debugging).
## Framework support
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration.
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
## Limitations
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
- No Blade or Twig template support; only `.php` files get PHP code insight.
- phpactor is not installed by the IDE.
- Run with Coverage is not available for PHPUnit.
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
-1
Переглянути файл
@@ -101,7 +101,6 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
| `settings` | 表 | 用于响应服务器的 `workspace/configuration` 请求。不写时,从 `initialization-options` 中查找请求的配置节。 |
| `install-hint` | 字符串 | 服务器缺失且 IDE 无法安装时显示的提示。 |
| `fallback` | 布尔 | 作为前面服务器的备选,只在它们都未安装时使用。 |
| `replaces` | 字符串数组 | 排在它后面、因它而变得多余的服务器名称。它为文件提供服务时,这些服务器不会被使用。用于能覆盖附加服务器功能的备选服务器。 |
| `features` | 字符串数组 | 只把服务器用于这些功能;为空表示全部。可选值:`completion`、`inline-completion`、`hover`、`signature-help`、`definition`、`declaration`、`type-definition`、`implementation`、`references`、`document-highlight`、`document-symbol`、`workspace-symbol`、`code-action`、`code-lens`、`rename`、`formatting`、`inlay-hint`、`semantic-tokens`、`document-link`、`call-hierarchy`、`type-hierarchy`、`folding-range`、`selection-range`、`diagnostics`。 |
| `code-action-kinds` | 字符串数组 | 只保留这些种类的代码操作,按前缀匹配(`refactor` 包含 `refactor.extract`);为空则全部保留。 |
| `connect` | 字符串 | 通过 TCP 提供 LSP 的服务器地址 `host:port`,见 [TCP 服务器](#tcp-服务器)。 |
+1 -1
Переглянути файл
@@ -143,7 +143,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
+7 -11
Переглянути файл
@@ -7,14 +7,11 @@ OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老
## 语言服务器
| 服务器 | 启用条件 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
Phoxite 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由 Phoxite 自己处理。
| 服务器 | 启用条件 |
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
@@ -28,7 +25,6 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
| ------------------ | -------------------------------------------------- |
| Intelephense | npm(`intelephense`) |
| Laravel LSP | GitHub release(`laravel/lsp`) |
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
@@ -81,12 +77,12 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
## 框架支持
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
## 已知限制
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
- 不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。
- IDE 不会安装 phpactor。
- PHPUnit 不支持使用覆盖率运行。
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
-11
Переглянути файл
@@ -26,17 +26,6 @@ args = ["language-server"]
root-markers = ["composer.json", ".phpactor.json"]
install-hint = "Install phpactor (https://phpactor.readthedocs.io/en/master/usage/standalone.html)"
# Alternative with its own Laravel and Blade support. https://github.com/samehelhawary/phoxite
[[language-servers]]
name = "phoxite"
fallback = true
command = "phoxite-lsp"
args = []
root-markers = ["composer.json", "artisan", "index.php"]
# It answers the Laravel strings itself.
replaces = ["laravel-lsp"]
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
# Laravel projects only: hover, definition and completion inside
# config('…'), route('…') and view('…'). Last: Intelephense keeps PHP hover,
# rename and symbols. https://github.com/laravel/lsp
+2 -25
Переглянути файл
@@ -75,7 +75,7 @@ import { resetAllEditorsFontZoom, stepAllEditorsFontZoom } from "./cm/prefs";
import { useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { menuGroupItems, notifications } from "@/workbench/contributions";
import { notifications } from "@/workbench/contributions";
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { toggleReadOnly } from "./fileAttributes";
@@ -529,29 +529,7 @@ function copyReference(reference: Promise<string>) {
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
const path = slot.model.path;
const { doc, selection } = view.state;
const line = doc.lineAt(selection.main.head).number;
const { from, to } = selection.main;
// The selected lines, leaving out the one a selection ends at the start of.
const first = doc.lineAt(from).number;
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
const contributed = menuGroupItems("copyPath", {
paths: [path],
line: first - 1,
endLine: last > first ? last - 1 : undefined,
}).flatMap((item) =>
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
? [
{
id: item.id,
label: item.verbatim ? item.label : tx(item.label),
preview: item.preview,
shortcut: shortcutLabel(item.id),
run: item.run,
},
]
: [],
);
const line = view.state.doc.lineAt(view.state.selection.main.head).number;
const flavours = [
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
{ id: "project.copyFileName", label: "File Name", value: pathToCopy("name", path) },
@@ -579,7 +557,6 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
void executeAction(f.id, f.id === "editor.copyPathWithLineNumber" ? f.value : path);
},
})),
...contributed,
{
id: "editor.copyReference",
label: tx("Reference"),
+2 -5
Переглянути файл
@@ -1,7 +1,4 @@
import { tags as t, type styleTags } from "@lezer/highlight";
/**
* @lezer/javascript styles `.` as a deref operator, but not `?.`; it tags `this` as `self` (Python's
* `self` colour) and `super` as an atom, which WebStorm colours as keywords.
*/
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator, "this super": t.keyword };
/** @lezer/javascript styles `.` as a deref operator, but not `?.`. */
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator };
-25
Переглянути файл
@@ -270,31 +270,6 @@ describe("language modes", () => {
}
});
it("colours `this` and `super` as keywords in Java, JavaScript, TypeScript and C++", async () => {
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.self, class: "self" },
{ tag: t.atom, class: "atom" },
]);
for (const [mode, path, doc, expected] of [
["Java", "/p/A.java", "class A extends B { A() { super(); this.a = 1; } }", ["super", "this"]],
["JavaScript", "/p/a.js", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
["TypeScript", "/p/a.ts", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
["C++", "/p/a.cpp", "void A::m() { this->a = 1; }", ["this"]],
] as const) {
const support = await loadSupport(findLanguageDescription(mode, path)!);
const found: Array<[string, string]> = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
found.push([doc.slice(from, to), style]),
);
const words = new Set<string>(expected);
expect(
found.filter(([text]) => words.has(text)),
mode,
).toEqual(expected.map((word) => [word, "keyword"]));
}
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
+1 -5
Переглянути файл
@@ -293,11 +293,9 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
"ClassName IdName PseudoClassName ColorLiteral CallTag": t.tagName,
};
// @lezer/java tags annotations as plain identifiers, and `this` as `self` (Python's `self` colour);
// IntelliJ colours `this` as a keyword.
// @lezer/java tags annotations as plain identifiers.
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
this: t.keyword,
};
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
@@ -308,8 +306,6 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
JSX: JS_TAGS,
TSX: JS_TAGS,
Java: JAVA_TAGS,
// CLion colours `this` as a keyword.
"C++": { this: t.keyword },
PHP: {
"; ,": t.separator,
"ClassDeclaration/Name BaseClause/Name InterfaceClause/Name": t.className,
+1 -39
Переглянути файл
@@ -10,7 +10,7 @@ import { LspPopups } from "@/editor/lsp/Popups";
import { registerProjectActions } from "@/features/project-tree/actions";
import { useProjectTree } from "@/features/project-tree/store";
import { useContextMenuStore } from "@/ui";
import { provideNotificationService, registerMenuGroup, type MenuGroupContext } from "@/workbench/contributions";
import { provideNotificationService } from "@/workbench/contributions";
import * as controller from "./controller";
import { createMemoryBackend } from "./backend";
import { registerEditorActions } from "./actions";
@@ -189,44 +189,6 @@ describe("editor Copy Path/Reference chooser", () => {
expect(useLspPopup.getState().popup).toBeNull();
});
it("lists contributed links before Reference, for the selected lines", async () => {
const contexts: MenuGroupContext[] = [];
const run = vi.fn();
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => {
contexts.push(ctx);
return [{ id: "test.copyLink", label: "Host Link", verbatim: true, preview: "https://host/a#L1", run }];
},
}),
);
const view = ctrl.activeSlot!.view!;
await executeAction("editor.copyPathReference");
expect(
popup()
.items.map((item) => item.label)
.slice(-2),
).toEqual(["Host Link", "Reference"]);
expect(popup().items.at(-2)).toMatchObject({
preview: "https://host/a#L1",
shortcut: shortcutLabel("test.copyLink"),
});
await popup().items.at(-2)!.run();
expect(run).toHaveBeenCalledOnce();
// From the first line into the second; then ending at the start of the second line.
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
await executeAction("editor.copyPathReference");
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
await executeAction("editor.copyPathReference");
expect(contexts.map(({ paths, line, endLine }) => [paths, line, endLine])).toEqual([
[[path], 1, undefined],
[[path], 0, 1],
[[path], 0, undefined],
]);
});
it("adds the chooser to Copy / Paste Special", () => {
vi.spyOn(ctrl.activeSlot!.view!, "posAtCoords").mockReturnValue(null);
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
+1 -1
Переглянути файл
@@ -52,7 +52,7 @@
justify-content: space-between;
gap: 6px;
padding: 4px 8px;
background: var(--bg-hover);
background: var(--bg-subtle);
border-radius: var(--radius-control);
font-family: var(--font-mono);
font-size: var(--fs-small);
+1 -1
Переглянути файл
@@ -48,7 +48,7 @@
justify-content: space-between;
gap: 6px;
padding: 4px 8px;
background: var(--bg-hover);
background: var(--bg-subtle);
border-radius: var(--radius-control);
}
-2
Переглянути файл
@@ -499,7 +499,6 @@ describe("launch", () => {
path: "/x/b.txt",
left: { type: "file", path: "/x/a.txt", label: "/x/a.txt" },
right: { type: "worktree", label: "/x/b.txt" },
swappable: true,
},
]);
});
@@ -515,7 +514,6 @@ describe("launch", () => {
path: "/p/b.txt",
left: { type: "file", path: "/p/a.txt", label: "a.txt" },
right: { type: "worktree", label: "b.txt" },
swappable: true,
},
]);
});
-2
Переглянути файл
@@ -78,9 +78,7 @@ export function appActions(): Action[] {
id,
title: t(key),
category: t("app.category.edit"),
// The native ⌘C / Ctrl+C keep working unbound; listed so another key can be added (IDEA's $Copy…).
hidden: true,
keymap: true,
run: editCommand(command),
});
return [
-19
Переглянути файл
@@ -100,25 +100,6 @@ describe("project view context menu", () => {
}
});
it("lists contributed links in Copy Path/Reference…", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [
{ label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined },
],
}),
);
expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"Link /p/src true",
]);
});
it("follows IDEA's order for a file", () => {
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
expect(labels(items)).toEqual([
-2
Переглянути файл
@@ -215,8 +215,6 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
{
+3 -3
Переглянути файл
@@ -129,14 +129,14 @@
border: none;
border-radius: 4px;
color: var(--fg-secondary);
background: var(--bg-elev);
background: var(--bg-toolbar);
opacity: 0.6;
}
.consoleFindOpen:hover,
.consoleFindOpen:focus-visible {
opacity: 1;
color: var(--fg-strong);
color: var(--fg-primary);
}
.consoleWrap {
@@ -871,7 +871,7 @@
.envHeader {
position: sticky;
top: 0;
background: var(--bg-popup);
background: var(--bg-popup, var(--bg));
color: var(--fg-subtle);
font-size: var(--fs-small);
border-bottom: 1px solid var(--border-popup);
-37
Переглянути файл
@@ -1,37 +0,0 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { openConnectionDialog, ServicesDialogHost } from "./dialogs";
afterEach(() => {
cleanup();
useProject.setState({ settings: null });
});
describe("Docker connection dialog", () => {
it("offers the SSH configurations of Settings › Tools › SSH Configurations", () => {
const config = {
id: "ssh1",
name: "Build server",
host: "build-server",
port: 2222,
user: "ops",
auth: "openSsh",
keyFile: "",
saveSecret: false,
};
useProject.setState({ settings: { ssh: { configs: [config] } } as unknown as Settings });
render(<ServicesDialogHost />);
act(() =>
openConnectionDialog({
id: "c1",
name: "Docker",
endpoint: { kind: "tcp", host: "ssh://ops@build-server:2222", tlsCertDir: null },
} as never),
);
const picker = screen.getByRole("button", { name: /SSH configuration/ });
expect(picker.textContent).toContain("Build server");
expect(picker.textContent).not.toContain("missing");
});
});
-1
Переглянути файл
@@ -234,7 +234,6 @@ function ConnectionDialog({ existing, onDone }: { existing?: DockerConnection; o
<SshConfigSelect
value={shown}
onChange={pickSsh}
configs={sshConfigs}
none="None — type the Engine API URL below"
aria-label="SSH configuration"
/>
-5
Переглянути файл
@@ -267,11 +267,6 @@ describe("shortcut search", () => {
{ id: "internal.x", title: "Internal", hidden: true, run },
];
const draft = { preset: "intellij-macos", overrides: {} };
// Hidden from Search Everywhere but keymap-listed (Cut / Copy / Paste) still shows.
const copy = { id: "edit.copy", title: "Copy", category: "Edit", hidden: true, keymap: true, run };
const withCopy = buildKeymapTree([...actions, copy], draft, "copy", "");
const edit = withCopy[0]!.kind === "group" ? withCopy[0]!.children[0] : undefined;
expect(edit?.kind === "group" && edit.children.map((n) => n.key)).toEqual(["edit.copy"]);
const all = buildKeymapTree(actions, draft, "", "");
expect(all.map((n) => n.key)).toEqual(["grp:Main Menu"]);
const menu = all[0]!.kind === "group" ? all[0]!.children : [];
-5
Переглянути файл
@@ -14,9 +14,4 @@ describe("settings window bridge", () => {
expect(info).toEqual({ id: "a.b", title: "B", when: "editorFocus" });
expect(JSON.parse(JSON.stringify(info))).toEqual(info);
});
it("keeps the keymap flag so hidden Cut / Copy / Paste stay in the settings window's Keymap", () => {
const [info] = describeActions([{ id: "edit.copy", title: "Copy", hidden: true, keymap: true, run: () => {} }]);
expect(info).toMatchObject({ hidden: true, keymap: true });
});
});
+1 -6
Переглянути файл
@@ -29,12 +29,7 @@ export function resolveBindings(draft: KeymapDraft, id: string): string[] {
/** Hidden actions with shortcuts stay configurable even after their bindings are removed. */
export function isKeymapAction(action: Action, draft: KeymapDraft): boolean {
return (
!action.hidden ||
!!action.keymap ||
action.id in draft.overrides ||
presetBindings(draft.preset, action.id).length > 0
);
return !action.hidden || action.id in draft.overrides || presetBindings(draft.preset, action.id).length > 0;
}
export function isModified(draft: KeymapDraft, id: string): boolean {
+2 -3
Переглянути файл
@@ -21,7 +21,7 @@ const EXEC = "openidea://settings/exec";
export type ActionInfo = Pick<
Action,
"id" | "title" | "category" | "description" | "icon" | "when" | "keywords" | "hidden" | "keymap"
"id" | "title" | "category" | "description" | "icon" | "when" | "keywords" | "hidden"
>;
function currentLabel(): string | null {
@@ -39,7 +39,7 @@ export function settingsWindowParent(label = currentLabel()): string | null {
}
export function describeActions(actions: Iterable<Action> = allActions()): ActionInfo[] {
return [...actions].map(({ id, title, category, description, icon, when, keywords, hidden, keymap }) => ({
return [...actions].map(({ id, title, category, description, icon, when, keywords, hidden }) => ({
id,
title,
category,
@@ -48,7 +48,6 @@ export function describeActions(actions: Iterable<Action> = allActions()): Actio
when,
keywords,
hidden,
keymap,
}));
}
-123
Переглянути файл
@@ -1,123 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { executeAction, registerActions, registerAction } from "@/platform/actions";
import { clearContext, setContext } from "@/platform/context";
import { menuGroupItems, provideNotificationService } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
const config = vi.hoisted(() => new Map<string, string>());
const configReads = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
call: vi.fn(async (request: Promise<unknown>) => request),
commands: {
...real.commands,
vcsConfigGet: async (root: string, key: string) => {
configReads(root, key);
return config.get(`${root} ${key}`) ?? null;
},
},
};
});
import { openOnRemoteActions, registerOpenOnRemote } from "../openOnRemote";
import { useVcs } from "../store";
const writeText = vi.fn(async (_text: string) => undefined);
const hint = vi.fn();
const notify = vi.fn();
const disposers: Array<() => void> = [];
type Item = Extract<MenuItem, { kind?: "item" }>;
const items = (ctx: Parameters<typeof menuGroupItems>[1]) =>
menuGroupItems("copyPath", ctx).filter((i): i is Item => i.kind !== "separator" && "run" in i);
async function start() {
disposers.push(registerOpenOnRemote());
await vi.waitFor(() => expect(items({ paths: ["/p/a.ts"] })).not.toEqual([]));
}
beforeEach(() => {
vi.clearAllMocks();
config.clear();
config.set("/p remote.origin.url", "[email protected]:group/sub/app.git");
vi.stubGlobal("navigator", { clipboard: { writeText }, userAgent: navigator.userAgent });
provideNotificationService({ notify });
setContext("vcsAvailable", true);
useVcs.setState({
root: "/p",
repo: "/p",
roots: ["/p"],
branch: { name: "feature/x", upstream: "origin/feature/x" } as never,
heads: {},
});
disposers.push(
registerActions(openOnRemoteActions),
registerAction({ id: "editor.showHint", title: "Hint", run: ({ arg }) => hint(arg) }),
);
});
afterEach(() => {
disposers
.splice(0)
.reverse()
.forEach((dispose) => dispose());
useVcs.setState({ root: null, repo: null, roots: [], branch: null, heads: {} } as never);
clearContext("vcsAvailable");
vi.unstubAllGlobals();
});
describe("Copy Path/Reference… › <hosting> Link", () => {
it("offers the file's link at the selected lines and copies it", async () => {
await start();
const [item] = items({ paths: ["/p/src/a b.ts"], line: 9, endLine: 19 });
expect(item).toMatchObject({
id: "vcs.copyRemoteLink",
label: "GitLab Link",
preview: "https://gitlab.example.com/group/sub/app/-/blob/feature/x/src/a%20b.ts#L10-20",
});
item!.run!();
await vi.waitFor(() => expect(writeText).toHaveBeenCalledExactlyOnceWith(item!.preview));
expect(hint).toHaveBeenCalledWith({ text: `Copied ${item!.preview}` });
});
it("links a single line, a directory, and the HEAD commit without an upstream", async () => {
await start();
expect(items({ paths: ["/p/a.ts"], line: 0 })[0]?.preview).toBe(
"https://gitlab.example.com/group/sub/app/-/blob/feature/x/a.ts#L1",
);
expect(items({ paths: ["/p/src"], dirs: [true] })[0]?.preview).toBe(
"https://gitlab.example.com/group/sub/app/-/tree/feature/x/src",
);
useVcs.setState({
branch: { name: "main", upstream: null } as never,
heads: { "/p": { headCommit: "abc123" } as never },
});
expect(items({ paths: ["/p/a.ts"], line: 2 })[0]?.preview).toBe(
"https://gitlab.example.com/group/sub/app/-/blob/abc123/a.ts#L3",
);
});
it("offers nothing outside a repository, without a web remote, or for several paths", async () => {
await start();
expect(items({ paths: ["/elsewhere/a.ts"] })).toEqual([]);
expect(items({ paths: ["/p/a.ts", "/p/b.ts"] })).toEqual([]);
disposers.splice(-1).forEach((dispose) => dispose());
config.set("/p remote.origin.url", "/srv/git/app.git");
configReads.mockClear();
disposers.push(registerOpenOnRemote());
await vi.waitFor(() => expect(configReads).toHaveBeenCalledWith("/p", "remote.origin.url"));
await new Promise((resolve) => setTimeout(resolve));
expect(items({ paths: ["/p/a.ts"] })).toEqual([]);
});
it("warns instead of copying when the file has no page on a remote", async () => {
await executeAction("vcs.copyRemoteLink", { path: "/elsewhere/a.ts", line: 0 });
await vi.waitFor(() =>
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "This file has no page on a Git remote" })),
);
expect(writeText).not.toHaveBeenCalled();
});
});
-25
Переглянути файл
@@ -51,29 +51,4 @@ describe("fileWebUrl", () => {
"https://bitbucket.org/team/repo/src/main/a.py#lines-5",
);
});
it("selects a range of lines in each hosting's syntax", () => {
const opts = { line: 9, endLine: 19 };
expect(fileWebUrl("[email protected]:o/r.git", "main", "a.ts", opts)).toBe(
"https://github.com/o/r/blob/main/a.ts#L10-L20",
);
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", opts)).toBe(
"https://gitlab.com/g/r/-/blob/main/a.ts#L10-20",
);
expect(fileWebUrl("[email protected]:o/r.git", "main", "a.ts", opts)).toBe(
"https://bitbucket.org/o/r/src/main/a.ts#lines-10:20",
);
});
it("keeps a single line when the range ends on it or before, and none for directories", () => {
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", { line: 4, endLine: 4 })).toBe(
"https://gitlab.com/g/r/-/blob/main/a.ts#L5",
);
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", { line: 4, endLine: 2 })).toBe(
"https://gitlab.com/g/r/-/blob/main/a.ts#L5",
);
expect(fileWebUrl("[email protected]:g/r.git", "main", "src", { dir: true, line: 4, endLine: 8 })).toBe(
"https://gitlab.com/g/r/-/tree/main/src",
);
});
});
+5 -7
Переглянути файл
@@ -214,28 +214,26 @@ export function remoteHosting(url: string): { name: string; kind: HostingKind }
/**
* Page of a file or directory at `revision` on the remote's web UI, with the 0-based `line`
* (through `endLine`, when later) selected. `relative` is the `/`-separated path inside the
* repository ("" for its root).
* selected. `relative` is the `/`-separated path inside the repository ("" for its root).
*/
export function fileWebUrl(
remoteUrl: string,
revision: string,
relative: string,
opts: { dir?: boolean; line?: number; endLine?: number } = {},
opts: { dir?: boolean; line?: number } = {},
): string | null {
const base = remoteWebUrl(remoteUrl);
const hosting = remoteHosting(remoteUrl);
if (!base || !hosting) return null;
const path = [...revision.split("/"), ...relative.split("/")].filter(Boolean).map(encodeURIComponent).join("/");
const line = opts.line !== undefined && !opts.dir ? opts.line + 1 : null;
const end = line && opts.endLine !== undefined && opts.endLine + 1 > line ? opts.endLine + 1 : null;
switch (hosting.kind) {
case "github":
return `${base}/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}${end ? `-L${end}` : ""}` : ""}`;
return `${base}/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}` : ""}`;
case "gitlab":
return `${base}/-/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}${end ? `-${end}` : ""}` : ""}`;
return `${base}/-/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}` : ""}`;
case "bitbucket":
return `${base}/src/${path}${line ? `#lines-${line}${end ? `:${end}` : ""}` : ""}`;
return `${base}/src/${path}${line ? `#lines-${line}` : ""}`;
}
}
+10 -66
Переглянути файл
@@ -1,12 +1,9 @@
/**
* Open In › GitHub / GitLab / Bitbucket: the file (at the caret line) or directory on the web UI
* of its repository's remote, at the current branch's upstream (else the HEAD commit).
* Copy Path/Reference… › <hosting> Link copies that page's address, with the selected lines.
*/
import { call, commands } from "@/platform/ipc";
import { executeAction, type Action } from "@/platform/actions";
import { writeClipboardText } from "@/platform/clipboard";
import { tx } from "@/platform/i18n";
import type { Action } from "@/platform/actions";
import { notifications, registerMenuGroup } from "@/workbench/contributions";
import { openUrl } from "./issueLinks";
import { fileWebUrl, remoteHosting, rootOf } from "./model";
@@ -16,7 +13,6 @@ interface Target {
path: string;
dir?: boolean;
line?: number;
endLine?: number;
}
/** Root → its remote's URL (null: none), read when the repositories change. */
@@ -48,40 +44,14 @@ function targetArg(arg: unknown): Target | null {
return null;
}
/** The target's page on its remote, from the remote URL read for its root (`url`). */
function pageFor(target: Target, root: string, url: string | null | undefined): string | null {
const rev = revision(root);
return url && rev ? fileWebUrl(url, rev, target.path.slice(root.length).replace(/^\/+/, ""), target) : null;
}
async function remotePage(target: Target): Promise<string | null> {
const root = rootOf(target.path, useVcs.getState().roots);
return root ? pageFor(target, root, remoteUrls.get(root) ?? (await readRemoteUrl(root))) : null;
}
function noPage() {
notifications().notify({ group: "vcs", level: "warning", title: "This file has no page on a Git remote" });
}
async function openOnRemote(target: Target) {
const page = await remotePage(target);
const root = rootOf(target.path, useVcs.getState().roots);
const url = root ? (remoteUrls.get(root) ?? (await readRemoteUrl(root))) : null;
const rev = root ? revision(root) : null;
const page =
root && url && rev ? fileWebUrl(url, rev, target.path.slice(root.length).replace(/^\/+/, ""), target) : null;
if (page) await openUrl(page);
else noPage();
}
async function copyRemoteLink(target: Target) {
const text = await remotePage(target);
if (!text) return noPage();
try {
await writeClipboardText(text);
void executeAction("editor.showHint", { text: tx`Copied ${text}` });
} catch (error) {
notifications().notify({
level: "error",
title: tx("Cannot access the clipboard"),
body: error instanceof Error ? error.message : String(error),
});
}
else notifications().notify({ group: "vcs", level: "warning", title: "This file has no page on a Git remote" });
}
export const openOnRemoteActions: Action[] = [
@@ -98,19 +68,6 @@ export const openOnRemoteActions: Action[] = [
if (target) void openOnRemote(target);
},
},
{
id: "vcs.copyRemoteLink",
title: "Copy Link to Git Remote",
description: "Copies the address of the file, its selected lines or the directory on its repository's remote.",
category: "Git",
icon: "copy",
when: "vcsAvailable",
hidden: true,
run: ({ arg }) => {
const target = targetArg(arg);
if (target) void copyRemoteLink(target);
},
},
];
/** Open In › <hosting>, for files and directories inside a repository with a web remote. */
@@ -125,28 +82,15 @@ export function registerOpenOnRemote(): () => void {
});
const unregister = registerMenuGroup({
id: "vcs.openOnRemote",
menus: ["openIn", "copyPath"],
items: (menu, { paths, dirs, line, endLine }) => {
menus: ["openIn"],
items: (_menu, { paths, dirs, line }) => {
if (paths.length !== 1) return [];
const path = paths[0]!;
const root = rootOf(path, useVcs.getState().roots);
const url = root ? remoteUrls.get(root) : null;
const hosting = url ? remoteHosting(url) : null;
if (!root || !hosting) return [];
if (!hosting) return [];
const target: Target = { path, dir: dirs?.[0] ?? false, line };
if (menu === "copyPath") {
const page = pageFor({ ...target, endLine }, root, url);
if (!page) return [];
return [
{
id: "vcs.copyRemoteLink",
label: tx`${hosting.name} Link`,
verbatim: true,
preview: page,
run: () => void executeAction("vcs.copyRemoteLink", { ...target, endLine }),
},
];
}
return [
{
id: "vcs.openOnRemote",
-2
Переглянути файл
@@ -49,8 +49,6 @@ export interface Action {
verbatim?: boolean;
/** Hidden from Search Everywhere (internal / parameterised actions). */
hidden?: boolean;
/** Listed in Settings › Keymap although `hidden`, so it can get a shortcut (Cut / Copy / Paste). */
keymap?: boolean;
/**
* Marks a toggle action (IDEA's ToggleAction): returns the current state.
* Search Everywhere shows an ON/OFF switch and keeps the popup open.
-11
Переглянути файл
@@ -26,17 +26,6 @@ export const vscodeMacos: Record<string, string[]> = {
"db.goToColumn": ["Meta+Shift+O"],
"db.submitChanges": ["Meta+Enter"],
"db.revertChanges": ["Meta+Alt+Z"],
// Data editor commands: VS Code has no counterpart.
"db.reloadPage": [],
"db.firstPage": [],
"db.previousPage": [],
"db.nextPage": [],
"db.lastPage": [],
"db.addRow": [],
"db.deleteRows": [],
"db.restoreRows": [],
"db.exportData": [],
"db.editCell": [],
"navigate.relatedSymbol": [],
"navigate.nextError": ["F8"],
"navigate.prevError": ["Shift+F8"],
+1 -5
Переглянути файл
@@ -1570,9 +1570,6 @@
"Open on Git Remote": "Open on Git Remote",
"Opens the file or directory on the web page of its repository's remote.": "Opens the file or directory on the web page of its repository's remote.",
"This file has no page on a Git remote": "This file has no page on a Git remote",
"Copy Link to Git Remote": "Copy Link to Git Remote",
"Copies the address of the file, its selected lines or the directory on its repository's remote.": "Copies the address of the file, its selected lines or the directory on its repository's remote.",
"{name} Link": "{name} Link",
"Run Agent Command": "Run Agent Command",
"Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.": "Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.",
"Archived agent tabs: {count}": "Archived agent tabs: {count}",
@@ -1883,6 +1880,5 @@
"No playful words: the status stays factual": "No playful words: the status stays factual",
"e.g. Reticulating splines…": "e.g. Reticulating splines…",
"New playful word": "New playful word",
"Restore Built-in Words": "Restore Built-in Words",
"None — type the Engine API URL below": "None — type the Engine API URL below"
"Restore Built-in Words": "Restore Built-in Words"
}
+1 -5
Переглянути файл
@@ -7966,9 +7966,6 @@
"Open on Git Remote": "在 Git 远程上打开",
"Opens the file or directory on the web page of its repository's remote.": "在仓库远程的网页上打开该文件或目录。",
"This file has no page on a Git remote": "该文件在 Git 远程上没有对应页面",
"Copy Link to Git Remote": "复制 Git 远程链接",
"Copies the address of the file, its selected lines or the directory on its repository's remote.": "复制文件、所选行或目录在其仓库远程上的地址。",
"{name} Link": "{name} 链接",
"Run Agent Command": "运行智能体命令",
"Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.": "在智能体标签 `name` 中运行 MCP 服务器 `run_command` 传来的 `{ name, command, cwd, env }`;未能启动时抛出错误。",
"Archived agent tabs: {count}": "已归档的智能体标签:{count}",
@@ -8284,6 +8281,5 @@
"No playful words: the status stays factual": "没有趣味文字:状态只显示实际进展",
"e.g. Reticulating splines…": "例如:正在网格化样条曲线…",
"New playful word": "新的趣味文字",
"Restore Built-in Words": "恢复内置文字",
"None — type the Engine API URL below": "无(在下方输入 Engine API URL)"
"Restore Built-in Words": "恢复内置文字"
}
-38
Переглянути файл
@@ -1,38 +0,0 @@
// @vitest-environment node
/**
* A `var(--x)` with no fallback whose `--x` is declared nowhere resolves to the property's
* initial value: a transparent background, inherited text. Nothing else catches it, so this
* lists every such use.
*
* A name ending in `-` is the start of one assembled at runtime (`--diff-${kind}`).
*/
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { expect, it } from "vitest";
const SRC = join(import.meta.dirname, "..");
function sources(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const path = join(dir, e.name);
if (e.isDirectory()) return sources(path);
return /\.(css|tsx?)$/.test(e.name) ? [path] : [];
});
}
it("every custom property read without a fallback is declared somewhere", () => {
const declared = new Set<string>();
const reads: { name: string; where: string }[] = [];
for (const path of sources(SRC)) {
const text = readFileSync(path, "utf8");
for (const m of text.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) declared.add(m[1]!);
for (const m of text.matchAll(/["'`](--[\w-]+)/g)) declared.add(m[1]!); // setProperty("--x", …), { "--x": … }
if (/\.test\.tsx?$/.test(path)) continue;
for (const m of text.matchAll(/var\(\s*(--[\w-]+)\s*\)/g)) {
const line = text.slice(0, m.index).split("\n").length;
reads.push({ name: m[1]!, where: `${path.slice(SRC.length + 1)}:${line}` });
}
}
const undeclared = reads.filter((r) => !declared.has(r.name) && !r.name.endsWith("-"));
expect(undeclared.map((r) => `${r.name} at ${r.where}`)).toEqual([]);
});
-2
Переглянути файл
@@ -51,8 +51,6 @@ export type MenuItem =
/** The pointer or the keyboard made it the active item (not on opening the menu). */
onActive?: () => void;
submenu?: MenuItem[];
/** The text the item copies, for choosers that show it (Copy Path/Reference…). */
preview?: string;
};
interface Resolved {
+1 -6
Переглянути файл
@@ -1206,8 +1206,6 @@ export function projectViewRoots(map: ReadonlyMap<string, ProjectViewRootContrib
// `selectIn` is the Select In chooser (⌥F1): targets for a file besides the project view.
// `new` is the New popup / New › submenu (IDEA's NewGroup): file kinds a feature creates
// in `paths[0]`, the target directory (features/templates: file templates, http-client: HTTP Request).
// `copyPath` is the Copy Path/Reference… chooser: more things to copy for a file (features/vcs: its
// link on the Git remote), each item's `preview` the copied text.
export type ContextMenuId =
| "editor"
@@ -1219,8 +1217,7 @@ export type ContextMenuId =
| "openIn"
| "stopProcess"
| "selectIn"
| "new"
| "copyPath";
| "new";
/**
* Entries of open menu slots: the native main menu's (src-tauri/src/menu.rs
@@ -1260,8 +1257,6 @@ export interface MenuGroupContext {
text?: string;
/** Editor menu: 0-based caret line; gutter menu: the clicked line. */
line?: number;
/** Copy Path/Reference… in the editor: the selection's last line, when it spans several. */
endLine?: number;
/** Zero-based UTF-16 column for problem/search result commands. */
column?: number;
/** The tab's input, when the menu is for an editor tab without a path. */