дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
764ce2ee0e | ||
|
|
48ebbe15e7 | ||
|
|
825f190030 | ||
|
|
7fa1d08b94 |
No files matched your search
Створено
+26
-26
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -3976,7 +3976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -3991,7 +3991,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4003,7 +4003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4017,7 +4017,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4034,7 +4034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4054,7 +4054,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4067,7 +4067,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4081,7 +4081,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4121,7 +4121,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4136,7 +4136,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4188,7 +4188,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4211,7 +4211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4229,7 +4229,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4242,7 +4242,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4260,7 +4260,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4277,7 +4277,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4311,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4324,7 +4324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4336,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4356,7 +4356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4373,7 +4373,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4393,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5817,7 +5817,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.7"
|
||||
version = "0.1.5"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -37,23 +37,6 @@ pub struct Settings {
|
||||
pub terminal: TerminalSettings,
|
||||
pub actions_on_save: ActionsOnSaveSettings,
|
||||
pub external_tools: Vec<ExternalTool>,
|
||||
/// Language servers / debug adapters at a user-chosen location, by the
|
||||
/// command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
pub tools: BTreeMap<String, ToolSettings>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
/// Executable to launch instead of the managed / `PATH` one; empty = auto-detect.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// The configured executable for `command`, if any (`~/` not yet expanded).
|
||||
pub fn tool_path(&self, command: &str) -> Option<&str> {
|
||||
self.tools.get(command).map(|t| t.path.trim()).filter(|p| !p.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -76,7 +59,6 @@ impl Default for Settings {
|
||||
terminal: TerminalSettings::default(),
|
||||
actions_on_save: ActionsOnSaveSettings::default(),
|
||||
external_tools: Vec::new(),
|
||||
tools: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,17 +522,6 @@ impl DebugManager {
|
||||
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
|
||||
/// Events of the session (including cargo build output) go to `owner` only.
|
||||
pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult<DebugSessionId> {
|
||||
self.start_with(config, owner, |_| None).await
|
||||
}
|
||||
|
||||
/// [`start`](Self::start) with the adapter executable chosen by `custom_command`
|
||||
/// (the configured command → a user-chosen executable, from settings).
|
||||
pub async fn start_with(
|
||||
&self,
|
||||
config: LaunchConfig,
|
||||
owner: SessionOwner,
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
let cwd = config
|
||||
.cwd
|
||||
@@ -542,9 +531,6 @@ impl DebugManager {
|
||||
let dbg = adapter::find_config(&self.languages, &config.adapter)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
|
||||
let mut spec = adapter::resolve(&dbg, cwd.clone());
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
|
||||
if config.adapter == "debugpy" {
|
||||
let python = match arguments.get("python") {
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
; GraphQL highlighting (the grammar crate ships no query). Later patterns win.
|
||||
|
||||
(comment) @comment
|
||||
(description (string_value) @comment.doc)
|
||||
(string_value) @string
|
||||
(int_value) @number
|
||||
(float_value) @number
|
||||
[(boolean_value) (null_value)] @keyword
|
||||
(enum_value (name) @constant)
|
||||
|
||||
(variable) @variable
|
||||
(argument (name) @variable.parameter)
|
||||
(input_value_definition (name) @variable.parameter)
|
||||
(object_field (name) @property)
|
||||
|
||||
(field (name) @property)
|
||||
(alias (name) @property)
|
||||
(field_definition (name) @property)
|
||||
(enum_value_definition (enum_value (name) @constant))
|
||||
|
||||
(named_type (name) @type)
|
||||
(object_type_definition (name) @type)
|
||||
(interface_type_definition (name) @type)
|
||||
(union_type_definition (name) @type)
|
||||
(enum_type_definition (name) @type)
|
||||
(input_object_type_definition (name) @type)
|
||||
(scalar_type_definition (name) @type)
|
||||
(object_type_extension (name) @type)
|
||||
(interface_type_extension (name) @type)
|
||||
(union_type_extension (name) @type)
|
||||
(enum_type_extension (name) @type)
|
||||
(input_object_type_extension (name) @type)
|
||||
(scalar_type_extension (name) @type)
|
||||
|
||||
(operation_definition (name) @function)
|
||||
(fragment_name (name) @function)
|
||||
(directive_definition (name) @attribute)
|
||||
(directive (name) @attribute)
|
||||
"@" @attribute
|
||||
(directive_location) @constant
|
||||
|
||||
(operation_type) @keyword
|
||||
[
|
||||
"query" "mutation" "subscription" "fragment" "on" "type" "interface" "union"
|
||||
"enum" "input" "scalar" "schema" "extend" "implements" "directive" "repeatable"
|
||||
] @keyword
|
||||
|
||||
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
|
||||
[":" "=" "|" "&" "!" "..."] @punctuation.delimiter
|
||||
@@ -1,29 +0,0 @@
|
||||
; HCL / Terraform highlighting (the grammar crate ships no query). Later patterns win.
|
||||
|
||||
(comment) @comment
|
||||
(string_lit) @string
|
||||
(quoted_template) @string
|
||||
(heredoc_template) @string
|
||||
[(heredoc_start) (heredoc_identifier)] @string.special
|
||||
(template_literal) @string
|
||||
(numeric_lit) @number
|
||||
[(bool_lit) (null_lit)] @keyword
|
||||
|
||||
(identifier) @variable
|
||||
(attribute (identifier) @property)
|
||||
(object_elem key: (expression (variable_expr (identifier) @property)))
|
||||
(get_attr (identifier) @property)
|
||||
(function_call (identifier) @function)
|
||||
; `resource "aws_instance" "web" {`
|
||||
(block (identifier) @keyword)
|
||||
(block (string_lit (template_literal) @type))
|
||||
|
||||
(template_interpolation) @embedded
|
||||
[(template_interpolation_start) (template_interpolation_end)] @punctuation.special
|
||||
[(template_directive_start) (template_directive_end) (strip_marker)] @punctuation.special
|
||||
["for" "in" "if" "else" "endfor" "endif"] @keyword
|
||||
|
||||
(operation) @operator
|
||||
["!" "!=" "%" "&&" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "||" "?" "=>"] @operator
|
||||
["=" ":" "," "."] @punctuation.delimiter
|
||||
["(" ")" "[" "]" "{" "}" "[*]" ".*"] @punctuation.bracket
|
||||
@@ -12,10 +12,7 @@ use std::collections::BTreeMap;
|
||||
mod registry;
|
||||
mod syntax;
|
||||
pub use registry::LanguageRegistry;
|
||||
pub use syntax::{
|
||||
MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
|
||||
SyntaxHighlights, TreeError,
|
||||
};
|
||||
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -5,10 +5,7 @@
|
||||
//! Structure / folding / Extend Selection on a large file cost an incremental
|
||||
//! parse instead of a full one.
|
||||
|
||||
use super::{
|
||||
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
|
||||
parse_cancellable, selection,
|
||||
};
|
||||
use super::{Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, TreeError, folding, outline, parse_cancellable, selection};
|
||||
use crate::FoldRange;
|
||||
use ide_core::{DocId, LanguageId, OutlineItem, Range};
|
||||
use ide_text::ByteEdit;
|
||||
@@ -62,7 +59,6 @@ struct Memo {
|
||||
key: Option<(u32, LanguageId)>,
|
||||
outline: Option<Arc<Vec<OutlineItem>>>,
|
||||
folding: Option<Arc<Vec<FoldRange>>>,
|
||||
highlights: Option<Arc<Vec<u32>>>,
|
||||
}
|
||||
|
||||
impl Memo {
|
||||
@@ -215,21 +211,6 @@ impl SyntaxCache {
|
||||
)
|
||||
}
|
||||
|
||||
/// Highlighting from the grammar's own query; empty without one.
|
||||
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
|
||||
SyntaxHighlights::new(self.memoized(
|
||||
doc,
|
||||
lang,
|
||||
version,
|
||||
|m| &mut m.highlights,
|
||||
|| {
|
||||
self.with_tree(doc, lang, version, text, |g, tree, text| {
|
||||
Some(highlight::highlights(g.highlight_query()?, tree, text))
|
||||
})
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
|
||||
fn memoized<T: Clone>(
|
||||
&self,
|
||||
|
||||
@@ -9,8 +9,6 @@ pub(crate) struct Spec {
|
||||
pub language: LanguageFn,
|
||||
/// `queries/<name>/outline.scm`; see `queries/README.md` for the capture vocabulary.
|
||||
pub outline: &'static str,
|
||||
/// The grammar's `highlights.scm`, for languages without a CodeMirror mode.
|
||||
pub highlights: Option<Highlights>,
|
||||
/// Node kinds folded when they span several lines (in addition to every
|
||||
/// bracket-delimited node, which is folded generically).
|
||||
pub fold_nodes: &'static [&'static str],
|
||||
@@ -22,21 +20,6 @@ pub(crate) struct Spec {
|
||||
pub constructors: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// A highlights query and how its patterns rank against each other.
|
||||
pub(crate) struct Highlights {
|
||||
pub query: &'static str,
|
||||
/// For the same node, the first matching pattern wins (tree-sitter CLI /
|
||||
/// GitHub queries) instead of the last one (nvim / Zed queries).
|
||||
pub first_wins: bool,
|
||||
}
|
||||
|
||||
/// Our own `queries/<name>/highlights.scm`, for grammars that ship none.
|
||||
macro_rules! highlights {
|
||||
($name:literal) => {
|
||||
include_str!(concat!("../../queries/", $name, "/highlights.scm"))
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! outline {
|
||||
($name:literal) => {
|
||||
include_str!(concat!("../../queries/", $name, "/outline.scm"))
|
||||
@@ -50,7 +33,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "rust",
|
||||
language: tree_sitter_rust::LANGUAGE,
|
||||
outline: outline!("rust"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["use_declaration", "extern_crate_declaration"],
|
||||
@@ -60,7 +42,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "typescript",
|
||||
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
|
||||
outline: outline!("typescript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -70,7 +51,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "tsx",
|
||||
language: tree_sitter_typescript::LANGUAGE_TSX,
|
||||
outline: outline!("typescript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string", "jsx_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -80,7 +60,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "javascript",
|
||||
language: tree_sitter_javascript::LANGUAGE,
|
||||
outline: outline!("javascript"),
|
||||
highlights: None,
|
||||
fold_nodes: &["template_string", "jsx_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -90,7 +69,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "python",
|
||||
language: tree_sitter_python::LANGUAGE,
|
||||
outline: outline!("python"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string"],
|
||||
fold_bodies: &["block"],
|
||||
imports: &["import_statement", "import_from_statement", "future_import_statement"],
|
||||
@@ -100,7 +78,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "go",
|
||||
language: tree_sitter_go::LANGUAGE,
|
||||
outline: outline!("go"),
|
||||
highlights: None,
|
||||
fold_nodes: &["raw_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_declaration"],
|
||||
@@ -110,7 +87,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "java",
|
||||
language: tree_sitter_java::LANGUAGE,
|
||||
outline: outline!("java"),
|
||||
highlights: None,
|
||||
fold_nodes: &["text_block"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_declaration"],
|
||||
@@ -120,7 +96,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "kotlin",
|
||||
language: tree_sitter_kotlin_ng::LANGUAGE,
|
||||
outline: outline!("kotlin"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["import"],
|
||||
@@ -130,7 +105,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "scala",
|
||||
language: tree_sitter_scala::LANGUAGE,
|
||||
outline: outline!("scala"),
|
||||
highlights: None,
|
||||
fold_nodes: &["string"],
|
||||
fold_bodies: &["indented_block", "template_body"],
|
||||
imports: &["import_declaration"],
|
||||
@@ -140,7 +114,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "c",
|
||||
language: tree_sitter_c::LANGUAGE,
|
||||
outline: outline!("c"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include"],
|
||||
@@ -150,7 +123,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "cpp",
|
||||
language: tree_sitter_cpp::LANGUAGE,
|
||||
outline: outline!("cpp"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def", "raw_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include", "using_declaration"],
|
||||
@@ -160,7 +132,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "csharp",
|
||||
language: tree_sitter_c_sharp::LANGUAGE,
|
||||
outline: outline!("csharp"),
|
||||
highlights: None,
|
||||
fold_nodes: &["preproc_region", "raw_string_literal", "verbatim_string_literal"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["using_directive"],
|
||||
@@ -170,7 +141,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "swift",
|
||||
language: tree_sitter_swift::LANGUAGE,
|
||||
outline: outline!("swift"),
|
||||
highlights: None,
|
||||
// Control-flow statements hold `{ statements }` without a block node of their own.
|
||||
fold_nodes: &[
|
||||
"multi_line_string_literal",
|
||||
@@ -190,7 +160,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ruby",
|
||||
language: tree_sitter_ruby::LANGUAGE,
|
||||
outline: outline!("ruby"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"method",
|
||||
"singleton_method",
|
||||
@@ -216,7 +185,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "php",
|
||||
language: tree_sitter_php::LANGUAGE_PHP,
|
||||
outline: outline!("php"),
|
||||
highlights: None,
|
||||
fold_nodes: &["heredoc", "nowdoc"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["namespace_use_declaration"],
|
||||
@@ -226,7 +194,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "lua",
|
||||
language: tree_sitter_lua::LANGUAGE,
|
||||
outline: outline!("lua"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"function_declaration",
|
||||
"function_definition",
|
||||
@@ -245,7 +212,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "dart",
|
||||
language: tree_sitter_dart::LANGUAGE,
|
||||
outline: outline!("dart"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_or_export", "library_name", "part_directive", "part_of_directive"],
|
||||
@@ -255,7 +221,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "zig",
|
||||
language: tree_sitter_zig::LANGUAGE,
|
||||
outline: outline!("zig"),
|
||||
highlights: Some(Highlights { query: tree_sitter_zig::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -265,7 +230,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "elixir",
|
||||
language: tree_sitter_elixir::LANGUAGE,
|
||||
outline: outline!("elixir"),
|
||||
highlights: Some(Highlights { query: tree_sitter_elixir::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: &["do_block", "anonymous_function", "string", "sigil"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -275,7 +239,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "haskell",
|
||||
language: tree_sitter_haskell::LANGUAGE,
|
||||
outline: outline!("haskell"),
|
||||
highlights: None,
|
||||
// `bind`: equations without arguments (`main = do …`).
|
||||
fold_nodes: &["function", "bind", "data_type", "newtype", "class", "instance", "signature"],
|
||||
fold_bodies: NONE,
|
||||
@@ -286,7 +249,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ocaml",
|
||||
language: tree_sitter_ocaml::LANGUAGE_OCAML,
|
||||
outline: outline!("ocaml"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"value_definition",
|
||||
"type_definition",
|
||||
@@ -304,7 +266,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ocaml_interface",
|
||||
language: tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE,
|
||||
outline: outline!("ocaml_interface"),
|
||||
highlights: None,
|
||||
fold_nodes: &["module_definition", "module_type_definition", "signature", "type_definition"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["open_module"],
|
||||
@@ -314,7 +275,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "bash",
|
||||
language: tree_sitter_bash::LANGUAGE,
|
||||
outline: outline!("bash"),
|
||||
highlights: None,
|
||||
fold_nodes: &["do_group", "if_statement", "case_statement", "heredoc_body"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -324,7 +284,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "html",
|
||||
language: tree_sitter_html::LANGUAGE,
|
||||
outline: outline!("html"),
|
||||
highlights: None,
|
||||
fold_nodes: &["element", "script_element", "style_element"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -334,7 +293,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "xml",
|
||||
language: tree_sitter_xml::LANGUAGE_XML,
|
||||
outline: outline!("xml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["element", "CDSect"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -344,7 +302,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "css",
|
||||
language: tree_sitter_css::LANGUAGE,
|
||||
outline: outline!("css"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import_statement"],
|
||||
@@ -354,7 +311,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "json",
|
||||
language: tree_sitter_json::LANGUAGE,
|
||||
outline: outline!("json"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -364,7 +320,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "yaml",
|
||||
language: tree_sitter_yaml::LANGUAGE,
|
||||
outline: outline!("yaml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["block_mapping_pair", "block_sequence_item", "block_scalar"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -374,7 +329,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "toml",
|
||||
language: tree_sitter_toml_ng::LANGUAGE,
|
||||
outline: outline!("toml"),
|
||||
highlights: None,
|
||||
fold_nodes: &["table", "table_array_element", "string"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -384,7 +338,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "markdown",
|
||||
language: tree_sitter_md::LANGUAGE,
|
||||
outline: outline!("markdown"),
|
||||
highlights: None,
|
||||
fold_nodes: &["section", "fenced_code_block", "list", "block_quote", "html_block"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -394,7 +347,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "hcl",
|
||||
language: tree_sitter_hcl::LANGUAGE,
|
||||
outline: outline!("hcl"),
|
||||
highlights: Some(Highlights { query: highlights!("hcl"), first_wins: false }),
|
||||
fold_nodes: &["block", "heredoc_template"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -404,7 +356,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "nix",
|
||||
language: tree_sitter_nix::LANGUAGE,
|
||||
outline: outline!("nix"),
|
||||
highlights: Some(Highlights { query: tree_sitter_nix::HIGHLIGHTS_QUERY, first_wins: true }),
|
||||
fold_nodes: &["let_expression", "indented_string_expression"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -414,7 +365,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "proto",
|
||||
language: tree_sitter_proto::LANGUAGE,
|
||||
outline: outline!("proto"),
|
||||
highlights: None,
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: &["import"],
|
||||
@@ -424,7 +374,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "graphql",
|
||||
language: tree_sitter_graphql::LANGUAGE,
|
||||
outline: outline!("graphql"),
|
||||
highlights: Some(Highlights { query: highlights!("graphql"), first_wins: false }),
|
||||
fold_nodes: NONE,
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
@@ -434,7 +383,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "make",
|
||||
language: tree_sitter_make::LANGUAGE,
|
||||
outline: outline!("make"),
|
||||
highlights: Some(Highlights { query: tree_sitter_make::HIGHLIGHTS_QUERY, first_wins: false }),
|
||||
fold_nodes: &["rule", "conditional", "define_directive"],
|
||||
fold_bodies: NONE,
|
||||
imports: &["include_directive"],
|
||||
@@ -444,7 +392,6 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "cmake",
|
||||
language: tree_sitter_cmake::LANGUAGE,
|
||||
outline: outline!("cmake"),
|
||||
highlights: None,
|
||||
fold_nodes: &["function_def", "macro_def", "if_condition", "foreach_loop", "while_loop", "block_def"],
|
||||
fold_bodies: NONE,
|
||||
imports: NONE,
|
||||
|
||||
@@ -1,483 +0,0 @@
|
||||
//! Syntax highlighting from a grammar's own `highlights.scm`, for languages the
|
||||
//! UI has no CodeMirror mode for.
|
||||
//!
|
||||
//! Capture names follow the nvim-treesitter / Zed conventions (`@keyword`,
|
||||
//! `@string.special.symbol`, ...) and are folded into [`SyntaxHighlightKind`] by
|
||||
//! their longest known dotted prefix. Overlaps resolve the way those editors
|
||||
//! do: a smaller node wins over the node containing it, and for the same node
|
||||
//! the later pattern wins (the first one for tree-sitter CLI style queries). `@embedded` (string interpolation) clears the
|
||||
//! surrounding colour. Besides tree-sitter's own text predicates, nvim's
|
||||
//! `#lua-match?` is understood; patterns with other predicates never match.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tree_sitter::{Language, Query, QueryCursor, QueryMatch, QueryPredicateArg, StreamingIterator, Tree};
|
||||
|
||||
/// Highlight classes sent to the UI, which maps each onto a Lezer tag.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyntaxHighlightKind {
|
||||
Keyword,
|
||||
String,
|
||||
StringSpecial,
|
||||
Escape,
|
||||
Regexp,
|
||||
Atom,
|
||||
Number,
|
||||
Constant,
|
||||
Comment,
|
||||
DocComment,
|
||||
Function,
|
||||
FunctionCall,
|
||||
Builtin,
|
||||
Type,
|
||||
Namespace,
|
||||
Variable,
|
||||
SelfVariable,
|
||||
Property,
|
||||
Attribute,
|
||||
Macro,
|
||||
Label,
|
||||
Tag,
|
||||
Operator,
|
||||
Punctuation,
|
||||
}
|
||||
|
||||
impl SyntaxHighlightKind {
|
||||
/// Every kind, in `as u32` order: the legend for [`SyntaxHighlights::data`].
|
||||
pub const ALL: [Self; 24] = [
|
||||
Self::Keyword,
|
||||
Self::String,
|
||||
Self::StringSpecial,
|
||||
Self::Escape,
|
||||
Self::Regexp,
|
||||
Self::Atom,
|
||||
Self::Number,
|
||||
Self::Constant,
|
||||
Self::Comment,
|
||||
Self::DocComment,
|
||||
Self::Function,
|
||||
Self::FunctionCall,
|
||||
Self::Builtin,
|
||||
Self::Type,
|
||||
Self::Namespace,
|
||||
Self::Variable,
|
||||
Self::SelfVariable,
|
||||
Self::Property,
|
||||
Self::Attribute,
|
||||
Self::Macro,
|
||||
Self::Label,
|
||||
Self::Tag,
|
||||
Self::Operator,
|
||||
Self::Punctuation,
|
||||
];
|
||||
}
|
||||
|
||||
/// Highlighted ranges of a whole document, packed like LSP semantic tokens.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyntaxHighlights {
|
||||
/// Legend: `data` kind `i` is `kinds[i]`.
|
||||
pub kinds: Vec<SyntaxHighlightKind>,
|
||||
/// `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets.
|
||||
pub data: Vec<u32>,
|
||||
}
|
||||
|
||||
impl SyntaxHighlights {
|
||||
pub(crate) fn new(data: Vec<u32>) -> Self {
|
||||
Self { kinds: SyntaxHighlightKind::ALL.to_vec(), data }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a capture paints over its node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Paint {
|
||||
Kind(SyntaxHighlightKind),
|
||||
/// `@embedded`: code inside a string, uncoloured unless captured itself.
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// Capture name prefixes, most specific first within each family.
|
||||
const CAPTURES: &[(&str, Paint)] = {
|
||||
use Paint::{Clear, Kind};
|
||||
use SyntaxHighlightKind as K;
|
||||
&[
|
||||
("embedded", Clear),
|
||||
("keyword", Kind(K::Keyword)),
|
||||
("include", Kind(K::Keyword)),
|
||||
("import", Kind(K::Keyword)),
|
||||
("conditional", Kind(K::Keyword)),
|
||||
("repeat", Kind(K::Keyword)),
|
||||
("exception", Kind(K::Keyword)),
|
||||
("boolean", Kind(K::Keyword)),
|
||||
("string.escape", Kind(K::Escape)),
|
||||
("escape", Kind(K::Escape)),
|
||||
("string.regex", Kind(K::Regexp)),
|
||||
("string.regexp", Kind(K::Regexp)),
|
||||
("string.special.symbol", Kind(K::Atom)),
|
||||
("symbol", Kind(K::Atom)),
|
||||
("string.special", Kind(K::StringSpecial)),
|
||||
("string", Kind(K::String)),
|
||||
("character", Kind(K::String)),
|
||||
("number", Kind(K::Number)),
|
||||
("float", Kind(K::Number)),
|
||||
("constant.builtin", Kind(K::Constant)),
|
||||
("constant.macro", Kind(K::Macro)),
|
||||
("constant", Kind(K::Constant)),
|
||||
// nvim greys out unused bindings (`_acc`); IDEA shows them as variables.
|
||||
("comment.unused", Kind(K::Variable)),
|
||||
("comment.doc", Kind(K::DocComment)),
|
||||
("comment.documentation", Kind(K::DocComment)),
|
||||
("comment", Kind(K::Comment)),
|
||||
("function.builtin", Kind(K::Builtin)),
|
||||
("function.macro", Kind(K::Macro)),
|
||||
("function.definition", Kind(K::Function)),
|
||||
("function", Kind(K::FunctionCall)),
|
||||
("method", Kind(K::FunctionCall)),
|
||||
("constructor", Kind(K::Type)),
|
||||
("type.builtin", Kind(K::Builtin)),
|
||||
("type", Kind(K::Type)),
|
||||
("module", Kind(K::Namespace)),
|
||||
("namespace", Kind(K::Namespace)),
|
||||
("variable.builtin", Kind(K::SelfVariable)),
|
||||
("variable.member", Kind(K::Property)),
|
||||
("variable.field", Kind(K::Property)),
|
||||
("variable", Kind(K::Variable)),
|
||||
("parameter", Kind(K::Variable)),
|
||||
("property", Kind(K::Property)),
|
||||
("field", Kind(K::Property)),
|
||||
("attribute", Kind(K::Attribute)),
|
||||
("label", Kind(K::Label)),
|
||||
("tag", Kind(K::Tag)),
|
||||
("operator", Kind(K::Operator)),
|
||||
("punctuation", Kind(K::Punctuation)),
|
||||
]
|
||||
};
|
||||
|
||||
/// The paint for a capture name: its longest prefix (on `.` boundaries) in
|
||||
/// [`CAPTURES`]. Private captures (`@__name__`) and unknown names paint nothing.
|
||||
fn paint_for(name: &str) -> Option<Paint> {
|
||||
if name.starts_with('_') {
|
||||
return None;
|
||||
}
|
||||
let mut prefix = name;
|
||||
loop {
|
||||
if let Some((_, p)) = CAPTURES.iter().find(|(n, _)| *n == prefix) {
|
||||
return Some(*p);
|
||||
}
|
||||
prefix = &prefix[..prefix.rfind('.')?];
|
||||
}
|
||||
}
|
||||
|
||||
/// A predicate tree-sitter leaves to the caller.
|
||||
enum Check {
|
||||
/// `#lua-match?` / `#not-lua-match?` on a capture's text.
|
||||
Matches {
|
||||
capture: u32,
|
||||
regex: regex_lite::Regex,
|
||||
negate: bool,
|
||||
},
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
pub(crate) struct HighlightQuery {
|
||||
query: Query,
|
||||
/// By capture index.
|
||||
paints: Vec<Option<Paint>>,
|
||||
/// By pattern index.
|
||||
checks: Vec<Vec<Check>>,
|
||||
first_wins: bool,
|
||||
}
|
||||
|
||||
impl HighlightQuery {
|
||||
pub(crate) fn new(language: &Language, source: &str, first_wins: bool) -> Result<Self, tree_sitter::QueryError> {
|
||||
let query = Query::new(language, source)?;
|
||||
let paints = query.capture_names().iter().map(|n| paint_for(n)).collect();
|
||||
let checks = (0..query.pattern_count())
|
||||
.map(|i| {
|
||||
query
|
||||
.general_predicates(i)
|
||||
.iter()
|
||||
.filter_map(|p| match (&*p.operator, &*p.args) {
|
||||
// Locals are not tracked: builtins are assumed not to be shadowed.
|
||||
("is-not?", [QueryPredicateArg::String(s)]) if &**s == "local" => None,
|
||||
(
|
||||
op @ ("lua-match?" | "not-lua-match?"),
|
||||
[QueryPredicateArg::Capture(c), QueryPredicateArg::String(pat)],
|
||||
) => Some(match regex_lite::Regex::new(&lua_pattern_to_regex(pat)) {
|
||||
Ok(regex) => Check::Matches { capture: *c, regex, negate: op.starts_with("not-") },
|
||||
Err(_) => Check::Unsupported,
|
||||
}),
|
||||
_ => Some(Check::Unsupported),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
Ok(Self { query, paints, checks, first_wins })
|
||||
}
|
||||
|
||||
fn accepts(&self, m: &QueryMatch<'_, '_>, text: &str) -> bool {
|
||||
self.checks[m.pattern_index].iter().all(|check| match check {
|
||||
Check::Matches { capture, regex, negate } => m
|
||||
.captures
|
||||
.iter()
|
||||
.filter(|c| c.index == *capture)
|
||||
.all(|c| regex.is_match(&text[c.node.byte_range()]) != *negate),
|
||||
Check::Unsupported => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates the Lua patterns used by nvim queries (`^[A-Z][A-Z_0-9]+$`, `^//!`) to regex syntax.
|
||||
fn lua_pattern_to_regex(pat: &str) -> String {
|
||||
let class = |c: char| match c {
|
||||
'a' => Some("A-Za-z"),
|
||||
'd' => Some("0-9"),
|
||||
'l' => Some("a-z"),
|
||||
'u' => Some("A-Z"),
|
||||
'w' => Some("A-Za-z0-9"),
|
||||
's' => Some("\\s"),
|
||||
'x' => Some("0-9A-Fa-f"),
|
||||
'p' => Some("[:punct:]"),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = String::with_capacity(pat.len() + 8);
|
||||
let mut in_set = false;
|
||||
let mut chars = pat.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'%' => {
|
||||
let Some(next) = chars.next() else { break };
|
||||
match class(next) {
|
||||
Some(set) if in_set => out.push_str(set),
|
||||
Some(set) => {
|
||||
out.push('[');
|
||||
out.push_str(set);
|
||||
out.push(']');
|
||||
}
|
||||
None => out.push_str(®ex_lite::escape(&next.to_string())),
|
||||
}
|
||||
}
|
||||
'[' if !in_set => {
|
||||
in_set = true;
|
||||
out.push(c);
|
||||
}
|
||||
']' if in_set => {
|
||||
in_set = false;
|
||||
out.push(c);
|
||||
}
|
||||
// Lua's lazy `*` (inside a set, `-` is a range).
|
||||
'-' if !in_set => out.push_str("*?"),
|
||||
'\\' | '{' | '}' | '|' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte value for "no colour" in the paint buffer; kinds are `1 + index`.
|
||||
const NONE: u8 = 0;
|
||||
|
||||
/// `[from, to, kind]` UTF-16 triples for `text`; see [`SyntaxHighlights::data`].
|
||||
pub(crate) fn highlights(q: &HighlightQuery, tree: &Tree, text: &str) -> Vec<u32> {
|
||||
// (byte len, rank, start, end, paint): painted largest first, then by rank,
|
||||
// so inner nodes and winning patterns overwrite.
|
||||
let mut captures: Vec<(usize, usize, usize, usize, Paint)> = Vec::new();
|
||||
let mut cursor = QueryCursor::new();
|
||||
let mut matches = cursor.matches(&q.query, tree.root_node(), text.as_bytes());
|
||||
while let Some(m) = matches.next() {
|
||||
if !q.accepts(m, text) {
|
||||
continue;
|
||||
}
|
||||
for c in m.captures {
|
||||
if let Some(paint) = q.paints[c.index as usize] {
|
||||
let r = c.node.byte_range();
|
||||
if r.start < r.end {
|
||||
let rank = if q.first_wins { usize::MAX - m.pattern_index } else { m.pattern_index };
|
||||
captures.push((r.end - r.start, rank, r.start, r.end, paint));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
captures.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
|
||||
|
||||
let mut painted = vec![NONE; text.len()];
|
||||
for &(_, _, start, end, paint) in &captures {
|
||||
let v = match paint {
|
||||
Paint::Kind(k) => 1 + k as u8,
|
||||
Paint::Clear => NONE,
|
||||
};
|
||||
painted[start..end].fill(v);
|
||||
}
|
||||
|
||||
let lines = LineIndex::new(text);
|
||||
let mut data = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < painted.len() {
|
||||
let v = painted[i];
|
||||
let start = i;
|
||||
while i < painted.len() && painted[i] == v {
|
||||
i += 1;
|
||||
}
|
||||
// Node boundaries are char boundaries; whitespace-only runs stay uncoloured.
|
||||
if v != NONE && text.is_char_boundary(start) && text.is_char_boundary(i) && !text[start..i].trim().is_empty() {
|
||||
data.extend([lines.utf16_at(start) as u32, lines.utf16_at(i) as u32, (v - 1) as u32]);
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_names_fold_to_the_longest_known_prefix() {
|
||||
use SyntaxHighlightKind as K;
|
||||
assert_eq!(paint_for("keyword.function"), Some(Paint::Kind(K::Keyword)));
|
||||
assert_eq!(paint_for("string.special.symbol"), Some(Paint::Kind(K::Atom)));
|
||||
assert_eq!(paint_for("string.special.path"), Some(Paint::Kind(K::StringSpecial)));
|
||||
assert_eq!(paint_for("comment.doc.__attribute__"), Some(Paint::Kind(K::DocComment)));
|
||||
assert_eq!(paint_for("punctuation.bracket"), Some(Paint::Kind(K::Punctuation)));
|
||||
assert_eq!(paint_for("embedded"), Some(Paint::Clear));
|
||||
assert_eq!(paint_for("__name__"), None);
|
||||
assert_eq!(paint_for("spell"), None);
|
||||
}
|
||||
|
||||
/// `(text, kind)` of every highlighted range.
|
||||
fn spans(lang: &str, text: &str) -> Vec<(String, SyntaxHighlightKind)> {
|
||||
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new(lang), text).unwrap();
|
||||
let units: Vec<u16> = text.encode_utf16().collect();
|
||||
h.data
|
||||
.chunks(3)
|
||||
.map(|t| (String::from_utf16(&units[t[0] as usize..t[1] as usize]).unwrap(), h.kinds[t[2] as usize]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_elixir() {
|
||||
use SyntaxHighlightKind as K;
|
||||
let src = "defmodule Greeter do\n @moduledoc \"Hi\"\n # 😀 note\n def hello(name, _opts) do\n IO.puts(\"Hello #{name}\")\n :ok\n end\nend\n";
|
||||
let got = spans("elixir", src);
|
||||
let kind = |t: &str| got.iter().find(|(s, _)| s == t).map(|(_, k)| *k);
|
||||
assert_eq!(kind("defmodule"), Some(K::Keyword));
|
||||
assert_eq!(kind("Greeter"), Some(K::Namespace));
|
||||
assert_eq!(kind("\"Hi\""), Some(K::DocComment));
|
||||
assert_eq!(kind("# 😀 note"), Some(K::Comment));
|
||||
assert_eq!(kind("def"), Some(K::Keyword));
|
||||
assert_eq!(kind("hello"), Some(K::FunctionCall));
|
||||
assert_eq!(kind("_opts"), Some(K::Variable));
|
||||
assert_eq!(kind("puts"), Some(K::FunctionCall));
|
||||
// Interpolation clears the string colour; its contents are coloured on their own.
|
||||
assert_eq!(kind("\"Hello "), Some(K::String));
|
||||
assert_eq!(kind("#{"), Some(K::Punctuation));
|
||||
assert_eq!(kind(":ok"), Some(K::Atom));
|
||||
assert_eq!(kind("end"), Some(K::Keyword));
|
||||
// Sorted and non-overlapping.
|
||||
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new("elixir"), src).unwrap();
|
||||
assert!(h.data.chunks(3).zip(h.data.chunks(3).skip(1)).all(|(a, b)| a[0] < a[1] && a[1] <= b[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_other_grammar_only_languages() {
|
||||
use SyntaxHighlightKind as K;
|
||||
type Expect<'a> = &'a [(&'a str, SyntaxHighlightKind)];
|
||||
let cases: &[(&str, &str, Expect)] = &[
|
||||
(
|
||||
"zig",
|
||||
"const std = @import(\"std\");\n// hi\npub fn main() void {\n var x: u32 = 42;\n _ = x;\n}\n",
|
||||
&[
|
||||
("const", K::Keyword),
|
||||
("\"std\"", K::String),
|
||||
("// hi", K::Comment),
|
||||
("42", K::Number),
|
||||
("u32", K::Builtin),
|
||||
],
|
||||
),
|
||||
(
|
||||
"nix",
|
||||
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
|
||||
&[
|
||||
("let", K::Keyword),
|
||||
("# hi", K::Comment),
|
||||
("1", K::Number),
|
||||
("\"dev\"", K::String),
|
||||
("import", K::Builtin),
|
||||
],
|
||||
),
|
||||
(
|
||||
"graphql",
|
||||
"# hi\nquery Hero($id: ID!) @cached {\n hero(id: $id) { name ...Friends }\n}\nenum Episode { NEWHOPE }\n",
|
||||
&[
|
||||
("# hi", K::Comment),
|
||||
("query", K::Keyword),
|
||||
("Hero", K::FunctionCall),
|
||||
("$id", K::Variable),
|
||||
("ID", K::Type),
|
||||
("@cached", K::Attribute),
|
||||
("name", K::Property),
|
||||
("Friends", K::FunctionCall),
|
||||
("NEWHOPE", K::Constant),
|
||||
],
|
||||
),
|
||||
(
|
||||
"hcl",
|
||||
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
|
||||
&[
|
||||
("# hi", K::Comment),
|
||||
("resource", K::Keyword),
|
||||
("aws_instance", K::Type),
|
||||
("ami", K::Property),
|
||||
("2", K::Number),
|
||||
("upper", K::FunctionCall),
|
||||
("\"web-", K::String),
|
||||
("env", K::Property),
|
||||
("var", K::Variable),
|
||||
],
|
||||
),
|
||||
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
|
||||
];
|
||||
for (lang, src, expect) in cases {
|
||||
let got = spans(lang, src);
|
||||
for (text, kind) in *expect {
|
||||
assert!(got.iter().any(|(s, k)| s == text && k == kind), "{lang}: {text:?} as {kind:?} in {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn languages_without_a_query_have_none() {
|
||||
assert_eq!(crate::Syntax::new().highlights(&ide_core::LanguageId::new("rust"), "fn a() {}"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_highlights_query_compiles() {
|
||||
for spec in super::super::grammars::SPECS {
|
||||
if let Some(h) = &spec.highlights {
|
||||
let lang = Language::new(spec.language);
|
||||
if let Err(e) = HighlightQuery::new(&lang, h.query, h.first_wins) {
|
||||
panic!("{}: {e}", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lua_patterns_translate() {
|
||||
assert_eq!(lua_pattern_to_regex("^[A-Z][A-Z_0-9]+$"), "^[A-Z][A-Z_0-9]+$");
|
||||
assert_eq!(lua_pattern_to_regex("^//!"), "^//!");
|
||||
assert_eq!(lua_pattern_to_regex("^%u[%w_]*$"), "^[A-Z][A-Za-z0-9_]*$");
|
||||
assert_eq!(lua_pattern_to_regex("a.-b%."), "a.*?b\\.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legend_matches_discriminants() {
|
||||
for (i, k) in SyntaxHighlightKind::ALL.iter().enumerate() {
|
||||
assert_eq!(*k as usize, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
|
||||
}
|
||||
|
||||
/// UTF-16 offset of a char-boundary byte offset.
|
||||
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
|
||||
fn utf16_at(&self, byte: usize) -> usize {
|
||||
if self.checkpoints.is_empty() {
|
||||
return byte;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
|
||||
|
||||
mod cache;
|
||||
mod folding;
|
||||
mod grammars;
|
||||
mod highlight;
|
||||
pub(crate) mod lines;
|
||||
mod outline;
|
||||
mod selection;
|
||||
@@ -11,7 +10,6 @@ mod selection;
|
||||
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
|
||||
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
|
||||
use grammars::{SPECS, Spec};
|
||||
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
|
||||
use ide_core::{LanguageId, OutlineItem, Range};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
@@ -33,7 +31,6 @@ pub(crate) struct Grammar {
|
||||
pub(crate) spec: &'static Spec,
|
||||
pub(crate) language: Language,
|
||||
outline: OnceLock<Option<outline::OutlineQuery>>,
|
||||
highlights: OnceLock<Option<highlight::HighlightQuery>>,
|
||||
kinds: OnceLock<folding::KindTable>,
|
||||
}
|
||||
|
||||
@@ -53,17 +50,6 @@ impl Grammar {
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn highlight_query(&self) -> Option<&highlight::HighlightQuery> {
|
||||
self.highlights
|
||||
.get_or_init(|| {
|
||||
let h = self.spec.highlights.as_ref()?;
|
||||
highlight::HighlightQuery::new(&self.language, h.query, h.first_wins)
|
||||
.inspect_err(|e| tracing::error!("highlights query for {} is invalid: {e}", self.spec.name))
|
||||
.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -86,7 +72,6 @@ impl Syntax {
|
||||
spec,
|
||||
language: Language::new(spec.language),
|
||||
outline: OnceLock::new(),
|
||||
highlights: OnceLock::new(),
|
||||
kinds: OnceLock::new(),
|
||||
})
|
||||
.collect();
|
||||
@@ -165,13 +150,6 @@ impl Syntax {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Highlighting from the grammar's own query; `None` without one.
|
||||
pub fn highlights(&self, lang: &LanguageId, text: &str) -> Option<SyntaxHighlights> {
|
||||
self.analyze(lang, text, |g, tree, text| {
|
||||
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
|
||||
pub fn selection_ranges(&self, lang: &LanguageId, text: &str, offset_utf16: u32) -> Vec<Range> {
|
||||
match self.analyze(lang, text, |_, tree, text| Some(selection::selection_ranges(tree, text, offset_utf16))) {
|
||||
|
||||
@@ -16,7 +16,7 @@ fn non_empty(s: &str) -> Option<&str> {
|
||||
}
|
||||
|
||||
/// Resolves `~/` and project-relative paths of a setting.
|
||||
pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
|
||||
fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
|
||||
let s = non_empty(s)?;
|
||||
let p = match s.strip_prefix("~/") {
|
||||
Some(rest) => crate::home_dir()?.join(rest),
|
||||
@@ -153,9 +153,6 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
|
||||
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
|
||||
/// `root` is the project root, `server_root` the server's workspace root.
|
||||
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
|
||||
cfg.command = custom.to_string_lossy().into_owned();
|
||||
}
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
let name = cfg.name.clone();
|
||||
let name = name.as_str();
|
||||
|
||||
@@ -255,18 +255,3 @@ fn detect_on_this_machine() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tool_path_replaces_the_command() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.tools.insert("elixir-ls".into(), ide_core::settings::ToolSettings { path: "tools/ls/language_server.sh".into() });
|
||||
s.tools.insert("zls".into(), ide_core::settings::ToolSettings { path: " ".into() });
|
||||
let mut cfg = server("elixir-ls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(Path::new(&cfg.command), tmp.path().join("tools/ls/language_server.sh"));
|
||||
// A blank path keeps auto-detection.
|
||||
let mut cfg = server("zls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(cfg.command, "zls");
|
||||
}
|
||||
@@ -177,27 +177,6 @@ pub fn locate(root: &Path, names: &[String]) -> Option<PathBuf> {
|
||||
|
||||
/// Creates `bin_dir/<command>` that runs `target`: a shell wrapper on Unix
|
||||
/// (keeps the target's own directory layout intact), a `.cmd` shim on Windows.
|
||||
/// Like [`link_executable`], with `env` set for `target`.
|
||||
pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &Path)]) -> IdeResult<PathBuf> {
|
||||
fs::create_dir_all(bin_dir)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let quote = |p: &Path| format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"));
|
||||
let vars: String = env.iter().map(|(k, v)| format!("{k}={} ", quote(v))).collect();
|
||||
let link = bin_dir.join(command);
|
||||
fs::write(&link, format!("#!/bin/sh\n{vars}exec {} \"$@\"\n", quote(target)))?;
|
||||
make_executable(&link)?;
|
||||
Ok(link)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResult<PathBuf> {
|
||||
fs::create_dir_all(bin_dir)?;
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -39,8 +39,6 @@ pub enum ToolStatus {
|
||||
Installed,
|
||||
/// Found on the system `PATH`.
|
||||
OnPath,
|
||||
/// The executable chosen in settings.
|
||||
Custom,
|
||||
Missing,
|
||||
}
|
||||
|
||||
@@ -68,8 +66,6 @@ pub struct ToolInfo {
|
||||
/// Manual install instructions from the language definition.
|
||||
pub install_hint: Option<String>,
|
||||
pub homepage: Option<String>,
|
||||
/// Why the executable chosen in settings cannot be used (status is then `Missing`).
|
||||
pub custom_error: Option<String>,
|
||||
}
|
||||
|
||||
/// Streamed install progress.
|
||||
@@ -120,9 +116,7 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
|
||||
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
|
||||
match spec.method {
|
||||
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
|
||||
Method::Go { .. } | Method::Gem { .. } | Method::DotnetTool { .. } | Method::Release { .. } => {
|
||||
Some(root.join(spec.name).join("bin"))
|
||||
}
|
||||
Method::Go { .. } | Method::Release { .. } => Some(root.join(spec.name).join("bin")),
|
||||
Method::PipVenv { .. } => {
|
||||
Some(root.join(spec.name).join("venv").join(if platform.os == Os::Windows { "Scripts" } else { "bin" }))
|
||||
}
|
||||
@@ -218,15 +212,8 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
for s in &l.language_servers {
|
||||
add(&s.name, &s.command, ToolKind::LanguageServer, s.install_hint.as_ref(), &l.name);
|
||||
}
|
||||
}
|
||||
let servers: HashSet<&str> = langs.iter().flat_map(|l| &l.language_servers).map(|s| s.name.as_str()).collect();
|
||||
for l in langs {
|
||||
if let Some(d) = &l.debugger {
|
||||
// An adapter named like a server but launched differently (ElixirLS's
|
||||
// `elixir-ls-debugger`) is a tool of its own, listed by its command.
|
||||
let name =
|
||||
if servers.contains(d.adapter.as_str()) && d.command != d.adapter { &d.command } else { &d.adapter };
|
||||
add(name, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
|
||||
add(&d.adapter, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
|
||||
}
|
||||
}
|
||||
for (plugin, host) in registry::PLUGIN_HOSTS {
|
||||
@@ -273,8 +260,6 @@ pub struct Tools {
|
||||
/// `PATH` handed to installer child processes.
|
||||
child_path: OsString,
|
||||
platform: Platform,
|
||||
/// Executables chosen in settings, by command.
|
||||
custom: BTreeMap<String, PathBuf>,
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
@@ -288,13 +273,7 @@ impl Tools {
|
||||
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
|
||||
let system_path = std::env::join_paths(&system).unwrap_or_default();
|
||||
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
|
||||
Self { root, system_path, child_path, platform, custom: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// Reports the executables chosen in settings (command → path) as the tools' location.
|
||||
pub fn with_custom_paths(mut self, custom: BTreeMap<String, PathBuf>) -> Self {
|
||||
self.custom = custom;
|
||||
self
|
||||
Self { root, system_path, child_path, platform }
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
@@ -364,12 +343,6 @@ impl Tools {
|
||||
|
||||
/// Requirement check for installing `spec` right now.
|
||||
fn unavailable_reason(&self, spec: &ToolSpec) -> Option<String> {
|
||||
self.installer_missing(spec)
|
||||
.or_else(|| spec.needs.iter().find(|(cmd, _)| self.which(cmd).is_none()).map(|(_, why)| why.to_string()))
|
||||
}
|
||||
|
||||
/// What the install method itself lacks (npm, a build for this platform, …).
|
||||
fn installer_missing(&self, spec: &ToolSpec) -> Option<String> {
|
||||
let need = |ok: bool, msg: &str| (!ok).then(|| msg.to_string());
|
||||
match spec.method {
|
||||
Method::Rustup { .. } => need(self.which("rustup").is_some(), "rustup is required (https://rustup.rs)"),
|
||||
@@ -378,10 +351,6 @@ impl Tools {
|
||||
"npm or pnpm is required: install Node.js (https://nodejs.org)",
|
||||
),
|
||||
Method::Go { .. } => need(self.which("go").is_some(), "Go is required (https://go.dev/dl)"),
|
||||
Method::Gem { .. } => need(self.which("gem").is_some(), "Ruby is required (https://www.ruby-lang.org)"),
|
||||
Method::DotnetTool { .. } => {
|
||||
need(self.which("dotnet").is_some(), ".NET SDK is required (https://dotnet.microsoft.com/download)")
|
||||
}
|
||||
Method::PipVenv { .. } => need(
|
||||
self.which("uv").is_some() || self.python().is_some(),
|
||||
"Python 3 or uv is required (https://www.python.org)",
|
||||
@@ -425,9 +394,7 @@ impl Tools {
|
||||
can_uninstall: false,
|
||||
install_hint,
|
||||
homepage: None,
|
||||
custom_error: None,
|
||||
})
|
||||
.map(|info| self.apply_custom(info, None));
|
||||
});
|
||||
};
|
||||
let (status, path, version) = self.detect(spec);
|
||||
let unavailable_reason = self.unavailable_reason(spec);
|
||||
@@ -447,34 +414,7 @@ impl Tools {
|
||||
can_uninstall,
|
||||
install_hint,
|
||||
homepage: Some(spec.homepage.to_string()),
|
||||
custom_error: None,
|
||||
})
|
||||
.map(|info| self.apply_custom(info, Some(spec)))
|
||||
}
|
||||
|
||||
/// Overrides the detected location with the executable chosen in settings.
|
||||
fn apply_custom(&self, mut info: ToolInfo, spec: Option<&ToolSpec>) -> ToolInfo {
|
||||
let Some(path) = self.custom.get(&info.command) else { return info };
|
||||
if !path.is_file() {
|
||||
info.status = ToolStatus::Missing;
|
||||
info.custom_error = Some(format!("{} does not exist", path.display()));
|
||||
info.path = None;
|
||||
info.version = None;
|
||||
return info;
|
||||
}
|
||||
info.version = spec.and_then(|spec| {
|
||||
let (cmd, args) = spec.version?;
|
||||
// The version command is the tool itself, whatever the chosen file is called.
|
||||
let program =
|
||||
if cmd == spec.commands[0] { path.clone() } else { path.parent().and_then(|d| self.exe_in(d, cmd))? };
|
||||
let mut c = self.command(program);
|
||||
c.args(args);
|
||||
let (ok, out) = run_quiet(c, Duration::from_secs(4))?;
|
||||
if ok { parse_version(&out) } else { None }
|
||||
});
|
||||
info.status = ToolStatus::Custom;
|
||||
info.path = Some(path.clone().into());
|
||||
info
|
||||
}
|
||||
|
||||
fn detect(&self, spec: &ToolSpec) -> (ToolStatus, Option<PathBuf>, Option<String>) {
|
||||
@@ -599,8 +539,6 @@ impl Tools {
|
||||
}
|
||||
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
@@ -680,96 +618,6 @@ impl Tools {
|
||||
self.write_manifest(spec.name, &Manifest { version, source: Some(module.to_string()) })
|
||||
}
|
||||
|
||||
fn install_gem(&self, spec: &ToolSpec, gem: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let home = dir.join("gems");
|
||||
std::fs::create_dir_all(&home)?;
|
||||
let mut c = self.command(self.which("gem").expect("checked"));
|
||||
c.args(["install", "--no-document", "--install-dir"]).arg(&home).arg("--bindir").arg(home.join("bin")).arg(gem);
|
||||
let result = run_streamed(c, cancel, emit).and_then(|_| {
|
||||
// RubyGems' stubs only find their gems through GEM_HOME / GEM_PATH.
|
||||
let env = [("GEM_HOME", home.as_path()), ("GEM_PATH", home.as_path())];
|
||||
for cmd in spec.commands {
|
||||
let stub = self
|
||||
.exe_in(&home.join("bin"), cmd)
|
||||
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("gem {gem} did not install `{cmd}`")))?;
|
||||
archive::env_wrapper(&dir.join("bin"), cmd, &stub, &env)?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = result {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(e);
|
||||
}
|
||||
// `gems/gems/<gem>-<version>/`
|
||||
let version = std::fs::read_dir(home.join("gems")).ok().and_then(|entries| {
|
||||
entries.flatten().find_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
name.strip_prefix(&format!("{gem}-"))
|
||||
.filter(|v| v.starts_with(|c: char| c.is_ascii_digit()))
|
||||
.map(String::from)
|
||||
})
|
||||
});
|
||||
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("rubygems:{gem}")) })
|
||||
}
|
||||
|
||||
fn install_dotnet_tool(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let tool = dir.join("tool");
|
||||
std::fs::create_dir_all(&tool)?;
|
||||
let dotnet = self.which("dotnet").expect("checked");
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool);
|
||||
let result = run_streamed(c, cancel, emit).and_then(|_| {
|
||||
// The tool's apphost looks for .NET in the default location only; a
|
||||
// Homebrew / user-local SDK must be named through DOTNET_ROOT.
|
||||
let root = self.dotnet_root(&dotnet);
|
||||
for cmd in spec.commands {
|
||||
let exe = self
|
||||
.exe_in(&tool, cmd)
|
||||
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("{package} did not install `{cmd}`")))?;
|
||||
match &root {
|
||||
Some(root) => archive::env_wrapper(&dir.join("bin"), cmd, &exe, &[("DOTNET_ROOT", root)])?,
|
||||
None => archive::link_executable(&dir.join("bin"), cmd, &exe)?,
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = result {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(e);
|
||||
}
|
||||
// `Package Id Version Commands` table.
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "list", "--tool-path"]).arg(&tool);
|
||||
let version = run_quiet(c, Duration::from_secs(20)).and_then(|(_, out)| {
|
||||
out.lines().find_map(|l| {
|
||||
let mut cols = l.split_whitespace();
|
||||
cols.next().filter(|id| id.eq_ignore_ascii_case(package))?;
|
||||
cols.next().map(String::from)
|
||||
})
|
||||
});
|
||||
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("nuget:{package}")) })
|
||||
}
|
||||
|
||||
/// The .NET install `dotnet` runs from: `Microsoft.NETCore.App 9.0.1 [<root>/shared/Microsoft.NETCore.App]`.
|
||||
fn dotnet_root(&self, dotnet: &Path) -> Option<PathBuf> {
|
||||
let mut c = self.command(dotnet);
|
||||
c.arg("--list-runtimes");
|
||||
let (_, out) = run_quiet(c, Duration::from_secs(20))?;
|
||||
let line = out.lines().find(|l| l.starts_with("Microsoft.NETCore.App "))?;
|
||||
let shared = line.rsplit_once('[')?.1.trim_end().strip_suffix(']')?;
|
||||
Path::new(shared).parent()?.parent().map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
fn install_venv(&self, spec: &ToolSpec, package: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -1049,12 +897,7 @@ impl Tools {
|
||||
run_streamed(c, &cancel, &quiet)?;
|
||||
}
|
||||
}
|
||||
Method::Go { .. }
|
||||
| Method::Gem { .. }
|
||||
| Method::DotnetTool { .. }
|
||||
| Method::PipVenv { .. }
|
||||
| Method::PipTarget { .. }
|
||||
| Method::Release { .. } => {
|
||||
Method::Go { .. } | Method::PipVenv { .. } | Method::PipTarget { .. } | Method::Release { .. } => {
|
||||
let dir = self.root.join(spec.name);
|
||||
if dir.exists() {
|
||||
std::fs::remove_dir_all(&dir)?;
|
||||
|
||||
@@ -44,11 +44,6 @@ pub enum Method {
|
||||
/// A pure-Python package unpacked into `<tools>/<name>/lib` (`pip install --target`,
|
||||
/// universal wheel), put on `PYTHONPATH` of whichever interpreter runs it.
|
||||
PipTarget { package: &'static str, module: &'static str },
|
||||
/// `gem install` into `<tools>/<name>/gems`, launched through `GEM_HOME` wrappers in `bin/`.
|
||||
Gem { gem: &'static str },
|
||||
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`.
|
||||
DotnetTool { package: &'static str },
|
||||
/// Platform archive download into `<tools>/<name>/`.
|
||||
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
|
||||
}
|
||||
@@ -59,8 +54,6 @@ impl Method {
|
||||
Method::Rustup { .. } => "rustup",
|
||||
Method::Npm { .. } => "npm",
|
||||
Method::Go { .. } => "go install",
|
||||
Method::Gem { .. } => "gem",
|
||||
Method::DotnetTool { .. } => "dotnet tool",
|
||||
Method::PipVenv { .. } => "pip (virtualenv)",
|
||||
Method::PipUser { .. } => "pip --user",
|
||||
Method::PipTarget { .. } => "pip (private copy)",
|
||||
@@ -85,8 +78,6 @@ pub struct ToolSpec {
|
||||
/// Version query: a command (looked up next to the main binary first) and its args.
|
||||
pub version: Option<(&'static str, &'static [&'static str])>,
|
||||
pub homepage: &'static str,
|
||||
/// Runtimes the tool runs on, found on `PATH`: command and why it is needed.
|
||||
pub needs: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
impl ToolSpec {
|
||||
@@ -103,11 +94,6 @@ use Os::{Linux, Mac, Windows};
|
||||
use ToolKind::{Debugger, LanguageServer, Plugin};
|
||||
|
||||
const V: Option<(&str, &[&str])> = None;
|
||||
const JAVA: &[(&str, &str)] = &[("java", "Java is required (https://adoptium.net)")];
|
||||
const NODE: &[(&str, &str)] = &[("node", "Node.js is required (https://nodejs.org)")];
|
||||
const ELIXIR: &[(&str, &str)] = &[("elixir", "Elixir is required (https://elixir-lang.org/install.html)")];
|
||||
const ELIXIR_LS_ASSETS: &[AssetRule] =
|
||||
&[any_arch(Mac, "elixir-ls-v*.zip"), any_arch(Linux, "elixir-ls-v*.zip"), any_arch(Windows, "elixir-ls-v*.zip")];
|
||||
const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str])> {
|
||||
Some((cmd, &["--version"]))
|
||||
}
|
||||
@@ -121,7 +107,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Rustup { component: "rust-analyzer" },
|
||||
version: ver("rust-analyzer"),
|
||||
homepage: "https://rust-analyzer.github.io",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vtsls",
|
||||
@@ -131,7 +116,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["@vtsls/language-server"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/yioneko/vtsls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "typescript-language-server",
|
||||
@@ -141,7 +125,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["typescript-language-server", "typescript"] },
|
||||
version: ver("typescript-language-server"),
|
||||
homepage: "https://github.com/typescript-language-server/typescript-language-server",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "pyright",
|
||||
@@ -151,7 +134,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["pyright"] },
|
||||
version: ver("pyright"),
|
||||
homepage: "https://github.com/microsoft/pyright",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "basedpyright",
|
||||
@@ -161,7 +143,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::PipVenv { package: "basedpyright" },
|
||||
version: ver("basedpyright"),
|
||||
homepage: "https://docs.basedpyright.com",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-language-server",
|
||||
@@ -171,7 +152,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["bash-language-server"] },
|
||||
version: ver("bash-language-server"),
|
||||
homepage: "https://github.com/bash-lsp/bash-language-server",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "yaml-language-server",
|
||||
@@ -181,7 +161,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["yaml-language-server"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/redhat-developer/yaml-language-server",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vscode-json-language-server",
|
||||
@@ -191,7 +170,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vscode-css-language-server",
|
||||
@@ -201,7 +179,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vscode-html-language-server",
|
||||
@@ -211,7 +188,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "dockerfile-language-server",
|
||||
@@ -221,7 +197,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["dockerfile-language-server-nodejs"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/rcjsuen/dockerfile-language-server",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "svelte-language-server",
|
||||
@@ -231,7 +206,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["svelte-language-server"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/sveltejs/language-tools",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vue-language-server",
|
||||
@@ -241,7 +215,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["@vue/language-server"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/vuejs/language-tools",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "graphql-lsp",
|
||||
@@ -251,7 +224,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["graphql-language-service-cli"] },
|
||||
version: V,
|
||||
homepage: "https://github.com/graphql/graphiql",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "intelephense",
|
||||
@@ -261,7 +233,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Npm { packages: &["intelephense"] },
|
||||
version: V,
|
||||
homepage: "https://intelephense.com",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "gopls",
|
||||
@@ -271,7 +242,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Go { module: "golang.org/x/tools/gopls@latest" },
|
||||
version: Some(("gopls", &["version"])),
|
||||
homepage: "https://pkg.go.dev/golang.org/x/tools/gopls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "sqls",
|
||||
@@ -281,7 +251,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Go { module: "github.com/sqls-server/sqls@latest" },
|
||||
version: Some(("sqls", &["--version"])),
|
||||
homepage: "https://github.com/sqls-server/sqls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "delve",
|
||||
@@ -291,7 +260,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::Go { module: "github.com/go-delve/delve/cmd/dlv@latest" },
|
||||
version: Some(("dlv", &["version"])),
|
||||
homepage: "https://github.com/go-delve/delve",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "debugpy",
|
||||
@@ -301,7 +269,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
method: Method::PipTarget { package: "debugpy", module: "debugpy" },
|
||||
version: V,
|
||||
homepage: "https://github.com/microsoft/debugpy",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "clangd",
|
||||
@@ -319,7 +286,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: ver("clangd"),
|
||||
homepage: "https://clangd.llvm.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "lua-language-server",
|
||||
@@ -339,7 +305,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: ver("lua-language-server"),
|
||||
homepage: "https://luals.github.io",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "marksman",
|
||||
@@ -358,7 +323,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: ver("marksman"),
|
||||
homepage: "https://github.com/artempyanykh/marksman",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "taplo",
|
||||
@@ -378,7 +342,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: ver("taplo"),
|
||||
homepage: "https://taplo.tamasfe.dev",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "zls",
|
||||
@@ -398,7 +361,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: ver("zls"),
|
||||
homepage: "https://github.com/zigtools/zls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "terraform-ls",
|
||||
@@ -418,7 +380,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: Some(("terraform-ls", &["version"])),
|
||||
homepage: "https://github.com/hashicorp/terraform-ls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "codelldb",
|
||||
@@ -443,7 +404,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/vadimcn/codelldb",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "js-debug",
|
||||
@@ -462,7 +422,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/microsoft/vscode-js-debug",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "jdtls",
|
||||
@@ -480,7 +439,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/eclipse-jdtls/eclipse.jdt.ls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "java-debug",
|
||||
@@ -499,7 +457,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/microsoft/java-debug",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "lombok",
|
||||
@@ -518,7 +475,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://projectlombok.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "kotlin-lsp",
|
||||
@@ -542,280 +498,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/Kotlin/kotlin-lsp",
|
||||
needs: &[],
|
||||
},
|
||||
// ElixirLS ships launcher scripts only: on first start they build the server
|
||||
// with the Elixir / OTP found for the project (Mix.install, needs network).
|
||||
ToolSpec {
|
||||
name: "elixir-ls",
|
||||
display: "ElixirLS",
|
||||
kind: LanguageServer,
|
||||
commands: &["elixir-ls"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
|
||||
assets: ELIXIR_LS_ASSETS,
|
||||
locate: &["language_server.sh", "language_server.bat"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/elixir-lsp/elixir-ls",
|
||||
needs: ELIXIR,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "elixir-ls-debugger",
|
||||
display: "ElixirLS Debugger",
|
||||
kind: Debugger,
|
||||
commands: &["elixir-ls-debugger"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
|
||||
assets: ELIXIR_LS_ASSETS,
|
||||
locate: &["debug_adapter.sh", "debug_adapter.bat"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/elixir-lsp/elixir-ls",
|
||||
needs: ELIXIR,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "buf",
|
||||
display: "Buf (Protocol Buffers)",
|
||||
kind: LanguageServer,
|
||||
commands: &["buf"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "bufbuild/buf" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "buf-Darwin-arm64.tar.gz"),
|
||||
rule(Mac, X64, "buf-Darwin-x86_64.tar.gz"),
|
||||
rule(Linux, X64, "buf-Linux-x86_64.tar.gz"),
|
||||
rule(Linux, Arm64, "buf-Linux-aarch64.tar.gz"),
|
||||
rule(Windows, X64, "buf-Windows-x86_64.zip"),
|
||||
rule(Windows, Arm64, "buf-Windows-arm64.zip"),
|
||||
],
|
||||
locate: &["buf"],
|
||||
},
|
||||
version: ver("buf"),
|
||||
homepage: "https://buf.build",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "clojure-lsp",
|
||||
display: "clojure-lsp",
|
||||
kind: LanguageServer,
|
||||
commands: &["clojure-lsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "clojure-lsp/clojure-lsp" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "clojure-lsp-native-macos-aarch64.zip"),
|
||||
rule(Mac, X64, "clojure-lsp-native-macos-amd64.zip"),
|
||||
rule(Linux, X64, "clojure-lsp-native-linux-amd64.zip"),
|
||||
rule(Linux, Arm64, "clojure-lsp-native-linux-aarch64.zip"),
|
||||
rule(Windows, X64, "clojure-lsp-native-windows-amd64.zip"),
|
||||
],
|
||||
locate: &["clojure-lsp"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://clojure-lsp.io",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "texlab",
|
||||
display: "TexLab (LaTeX)",
|
||||
kind: LanguageServer,
|
||||
commands: &["texlab"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "latex-lsp/texlab" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "texlab-aarch64-macos.tar.gz"),
|
||||
rule(Mac, X64, "texlab-x86_64-macos.tar.gz"),
|
||||
rule(Linux, X64, "texlab-x86_64-linux.tar.gz"),
|
||||
rule(Linux, Arm64, "texlab-aarch64-linux.tar.gz"),
|
||||
rule(Windows, X64, "texlab-x86_64-windows.zip"),
|
||||
rule(Windows, Arm64, "texlab-aarch64-windows.zip"),
|
||||
],
|
||||
locate: &["texlab"],
|
||||
},
|
||||
version: ver("texlab"),
|
||||
homepage: "https://github.com/latex-lsp/texlab",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "neocmakelsp",
|
||||
display: "neocmakelsp (CMake)",
|
||||
kind: LanguageServer,
|
||||
commands: &["neocmakelsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "Decodetalkers/neocmakelsp" },
|
||||
assets: &[
|
||||
any_arch(Mac, "neocmakelsp-universal-apple-darwin.tar.gz"),
|
||||
rule(Linux, X64, "neocmakelsp-x86_64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Linux, Arm64, "neocmakelsp-aarch64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Windows, X64, "neocmakelsp-x86_64-pc-windows-msvc.zip"),
|
||||
rule(Windows, Arm64, "neocmakelsp-aarch64-pc-windows-msvc.zip"),
|
||||
],
|
||||
locate: &["neocmakelsp"],
|
||||
},
|
||||
version: ver("neocmakelsp"),
|
||||
homepage: "https://github.com/Decodetalkers/neocmakelsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "lemminx",
|
||||
display: "LemMinX (XML)",
|
||||
kind: LanguageServer,
|
||||
commands: &["lemminx"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "redhat-developer/vscode-xml" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "lemminx-osx-aarch_64.zip"),
|
||||
rule(Mac, X64, "lemminx-osx-x86_64.zip"),
|
||||
rule(Linux, X64, "lemminx-linux-x86_64.zip"),
|
||||
rule(Linux, Arm64, "lemminx-linux-aarch_64.zip"),
|
||||
rule(Windows, X64, "lemminx-win32.zip"),
|
||||
],
|
||||
locate: &["lemminx-*"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/eclipse/lemminx",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "perlnavigator",
|
||||
display: "Perl Navigator",
|
||||
kind: LanguageServer,
|
||||
commands: &["perlnavigator"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "bscan/PerlNavigator" },
|
||||
assets: &[
|
||||
any_arch(Mac, "perlnavigator-macos-x86_64.zip"),
|
||||
rule(Linux, X64, "perlnavigator-linux-x86_64.zip"),
|
||||
rule(Windows, X64, "perlnavigator-win-x86_64.zip"),
|
||||
],
|
||||
locate: &["perlnavigator"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/bscan/PerlNavigator",
|
||||
needs: &[("perl", "Perl is required (https://www.perl.org/get.html)")],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "kotlin-language-server",
|
||||
display: "Kotlin Language Server (fwcd)",
|
||||
kind: LanguageServer,
|
||||
commands: &["kotlin-language-server"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-language-server" },
|
||||
assets: &[any_arch(Mac, "server.zip"), any_arch(Linux, "server.zip"), any_arch(Windows, "server.zip")],
|
||||
locate: &["kotlin-language-server"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/fwcd/kotlin-language-server",
|
||||
needs: JAVA,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "kotlin-debug-adapter",
|
||||
display: "Kotlin Debug Adapter",
|
||||
kind: Debugger,
|
||||
commands: &["kotlin-debug-adapter"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-debug-adapter" },
|
||||
assets: &[any_arch(Mac, "adapter.zip"), any_arch(Linux, "adapter.zip"), any_arch(Windows, "adapter.zip")],
|
||||
locate: &["kotlin-debug-adapter"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/fwcd/kotlin-debug-adapter",
|
||||
needs: JAVA,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "netcoredbg",
|
||||
display: "netcoredbg (.NET debugger)",
|
||||
kind: Debugger,
|
||||
commands: &["netcoredbg"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "Samsung/netcoredbg" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "netcoredbg-osx-arm64.zip"),
|
||||
rule(Linux, X64, "netcoredbg-linux-amd64.tar.gz"),
|
||||
rule(Linux, Arm64, "netcoredbg-linux-arm64.tar.gz"),
|
||||
rule(Windows, X64, "netcoredbg-win64.zip"),
|
||||
],
|
||||
locate: &["netcoredbg"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/Samsung/netcoredbg",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-debug",
|
||||
display: "Bash Debug",
|
||||
kind: Debugger,
|
||||
commands: &["bash-debug-adapter"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::OpenVsx { namespace: "rogalmic", extension: "bash-debug" },
|
||||
assets: &[
|
||||
any_arch(Mac, "rogalmic.bash-debug-*.vsix"),
|
||||
any_arch(Linux, "rogalmic.bash-debug-*.vsix"),
|
||||
any_arch(Windows, "rogalmic.bash-debug-*.vsix"),
|
||||
],
|
||||
locate: &["bashDebug.js"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/rogalmic/vscode-bash-debug",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "php-debug",
|
||||
display: "PHP Debug (Xdebug)",
|
||||
kind: Debugger,
|
||||
commands: &["php-debug-adapter"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::OpenVsx { namespace: "xdebug", extension: "php-debug" },
|
||||
assets: &[
|
||||
any_arch(Mac, "xdebug.php-debug-*.vsix"),
|
||||
any_arch(Linux, "xdebug.php-debug-*.vsix"),
|
||||
any_arch(Windows, "xdebug.php-debug-*.vsix"),
|
||||
],
|
||||
locate: &["phpDebug.js"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://github.com/xdebug/vscode-php-debug",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "ruby-lsp",
|
||||
display: "Ruby LSP (Shopify)",
|
||||
kind: LanguageServer,
|
||||
commands: &["ruby-lsp"],
|
||||
method: Method::Gem { gem: "ruby-lsp" },
|
||||
version: V,
|
||||
homepage: "https://shopify.github.io/ruby-lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "solargraph",
|
||||
display: "Solargraph (Ruby)",
|
||||
kind: LanguageServer,
|
||||
commands: &["solargraph"],
|
||||
method: Method::Gem { gem: "solargraph" },
|
||||
version: ver("solargraph"),
|
||||
homepage: "https://solargraph.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "csharp-ls",
|
||||
display: "csharp-ls",
|
||||
kind: LanguageServer,
|
||||
commands: &["csharp-ls"],
|
||||
method: Method::DotnetTool { package: "csharp-ls" },
|
||||
version: V,
|
||||
homepage: "https://github.com/razzmatazz/csharp-language-server",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "fsautocomplete",
|
||||
display: "FsAutoComplete (F#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["fsautocomplete"],
|
||||
method: Method::DotnetTool { package: "fsautocomplete" },
|
||||
version: V,
|
||||
homepage: "https://github.com/ionide/FsAutoComplete",
|
||||
needs: &[],
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -68,12 +68,10 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
|
||||
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
|
||||
// Servers without an installer are listed with their manual hint.
|
||||
let hls = find(&list, "haskell-language-server");
|
||||
assert_eq!(hls.install_method, None);
|
||||
assert!(!hls.can_install);
|
||||
assert_eq!(hls.status, ToolStatus::Missing);
|
||||
// Gem tools need Ruby.
|
||||
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
|
||||
let ruby = find(&list, "solargraph");
|
||||
assert_eq!(ruby.install_method, None);
|
||||
assert!(!ruby.can_install);
|
||||
assert_eq!(ruby.status, ToolStatus::Missing);
|
||||
// Shared npm package: each server is its own row.
|
||||
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
|
||||
assert!(find(&list, "delve").kind == ToolKind::Debugger);
|
||||
@@ -157,7 +155,7 @@ fn bin_dirs_cover_every_managed_layout() {
|
||||
fn unknown_or_manual_tools_cannot_be_installed() {
|
||||
let env = Env::new();
|
||||
let tools = env.tools();
|
||||
let err = tools.install("haskell-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let err = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert!(err.message.contains("cannot be installed automatically"));
|
||||
assert_eq!(tools.info("nope", &langs()).unwrap_err().kind, ErrorKind::NotFound);
|
||||
@@ -288,97 +286,3 @@ fn installed_bundle_is_detected_and_resolvable() {
|
||||
assert_eq!(managed_bundle(app_data, "java-debug"), Some(bin.join("com.microsoft.java.debug.plugin.jar")));
|
||||
assert_eq!(managed_bundle(app_data, "jdtls"), None, "not a bundle");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn custom_paths_win_and_report_their_version() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "gopls", "echo 'golang.org/x/tools/gopls v0.16.1'");
|
||||
let elsewhere = env.sys.parent().unwrap().join("opt/go/bin");
|
||||
env.script(&elsewhere, "my-gopls", "echo 'golang.org/x/tools/gopls v0.17.0'");
|
||||
let custom =
|
||||
BTreeMap::from([("gopls".to_string(), elsewhere.join("my-gopls")), ("zls".to_string(), elsewhere.join("zls"))]);
|
||||
let list = env.tools().with_custom_paths(custom).list(&langs());
|
||||
let gopls = find(&list, "gopls");
|
||||
assert_eq!(gopls.status, ToolStatus::Custom);
|
||||
assert_eq!(gopls.path.as_deref(), Some(elsewhere.join("my-gopls").as_path()));
|
||||
assert_eq!(gopls.version.as_deref(), Some("0.17.0"));
|
||||
assert_eq!(gopls.custom_error, None);
|
||||
// A path that does not exist is reported, not silently replaced by detection.
|
||||
let zls = find(&list, "zls");
|
||||
assert_eq!(zls.status, ToolStatus::Missing);
|
||||
assert!(zls.custom_error.as_deref().unwrap().contains("does not exist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_debugger_named_like_its_server_is_listed_by_its_command() {
|
||||
let list = Env::new().tools().list(&langs());
|
||||
let server = find(&list, "elixir-ls");
|
||||
assert_eq!((server.kind, server.command.as_str()), (ToolKind::LanguageServer, "elixir-ls"));
|
||||
let debugger = find(&list, "elixir-ls-debugger");
|
||||
assert_eq!((debugger.kind, debugger.command.as_str()), (ToolKind::Debugger, "elixir-ls-debugger"));
|
||||
assert_eq!(debugger.languages, vec!["Elixir".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn elixir_ls_needs_elixir_and_lists_its_debugger() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 0");
|
||||
let list = env.tools().list(&langs());
|
||||
let server = find(&list, "elixir-ls");
|
||||
assert_eq!(server.install_method.as_deref(), Some("GitHub release"));
|
||||
assert!(!server.can_install);
|
||||
assert!(server.unavailable_reason.as_deref().unwrap().contains("Elixir is required"));
|
||||
let debugger = find(&list, "elixir-ls-debugger");
|
||||
assert_eq!((debugger.kind, debugger.languages.as_slice()), (ToolKind::Debugger, ["Elixir".to_string()].as_slice()));
|
||||
|
||||
env.script(&env.sys, "elixir", "exit 0");
|
||||
let list = env.tools().list(&langs());
|
||||
assert!(find(&list, "elixir-ls").can_install);
|
||||
assert!(find(&list, "elixir-ls-debugger").can_install);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gem_install_wraps_stubs_with_gem_home() {
|
||||
let env = Env::new();
|
||||
// `gem install --no-document --install-dir <home> --bindir <bin> solargraph`
|
||||
env.script(
|
||||
&env.sys,
|
||||
"gem",
|
||||
r#"home="$4"; bin="$6"; /bin/mkdir -p "$home/gems/solargraph-0.50.0" "$bin"
|
||||
printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/solargraph""#,
|
||||
);
|
||||
let tools = env.tools();
|
||||
let info = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("0.50.0"));
|
||||
let wrapper = env.root.join("solargraph/bin/solargraph");
|
||||
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
|
||||
let out = std::process::Command::new(&wrapper).output().unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), env.root.join("solargraph/gems").to_string_lossy());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_install_into_tool_path() {
|
||||
let env = Env::new();
|
||||
env.script(
|
||||
&env.sys,
|
||||
"dotnet",
|
||||
r#"case "$2" in
|
||||
install) /bin/mkdir -p "$5"; printf '#!/bin/sh\necho "$DOTNET_ROOT"\n' > "$5/csharp-ls"; /bin/chmod +x "$5/csharp-ls" ;;
|
||||
list) printf 'Package Id Version Commands\n----\ncsharp-ls 0.15.0 csharp-ls\n' ;;
|
||||
esac
|
||||
[ "$1" = --list-runtimes ] && echo 'Microsoft.NETCore.App 9.0.1 [/opt/dotnet/shared/Microsoft.NETCore.App]'
|
||||
exit 0"#,
|
||||
);
|
||||
let info = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("0.15.0"));
|
||||
let wrapper = env.root.join("csharp-ls/bin/csharp-ls");
|
||||
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
|
||||
let out = std::process::Command::new(&wrapper).output().unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "/opt/dotnet");
|
||||
}
|
||||
@@ -14,6 +14,6 @@ root-markers = ["mix.exs"]
|
||||
install-hint = "Install ElixirLS (https://github.com/elixir-lsp/elixir-ls/releases) and expose language_server.sh as `elixir-ls`"
|
||||
|
||||
[debugger]
|
||||
adapter = "elixir-ls-debugger"
|
||||
adapter = "elixir-ls"
|
||||
command = "elixir-ls-debugger"
|
||||
install-hint = "Install ElixirLS and expose debug_adapter.sh as `elixir-ls-debugger`"
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.5",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -148,8 +148,8 @@ pub fn settings_set(
|
||||
.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, Some(&project.root)));
|
||||
}
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
if ["languages", "tools"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
|
||||
// A new interpreter / toolchain restarts the language servers it affects.
|
||||
if key == "languages" || key.starts_with("languages.") {
|
||||
let affected = if project_scope { current.iter().cloned().collect() } else { state.projects() };
|
||||
for project in affected {
|
||||
let lsp = project.lsp.clone();
|
||||
|
||||
@@ -14,16 +14,7 @@ pub async fn debug_start(
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let label = window.label();
|
||||
let owner = SessionOwner::new(AppState::owner_window(label), state.window_sink(label));
|
||||
let settings = match state.project(label) {
|
||||
Ok(project) => project.settings.effective(),
|
||||
Err(_) => state.global_settings.effective(),
|
||||
};
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
let custom = |command: &str| {
|
||||
let path = ide_sdk::apply::setting_path(&root, settings.tool_path(command)?)?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
state.debugger.start_with(config, owner, custom).await
|
||||
state.debugger.start(config, owner).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::state::AppState;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeResult, OutlineItem, Range};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_language::FoldRange;
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentInfo, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
@@ -136,22 +136,6 @@ pub async fn doc_folding(window: Window, state: State<'_, AppState>, doc: DocId)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
|
||||
/// empty when the grammar has no highlights query or the document is large.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_highlights(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<SyntaxHighlights> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
if snap.large {
|
||||
return Ok(SyntaxHighlights::default());
|
||||
}
|
||||
Ok(project.syntax.highlights(doc, &snap.language, snap.version, &snap.text))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
|
||||
/// Large documents fall back to word / line / document ranges.
|
||||
#[tauri::command]
|
||||
|
||||
@@ -74,7 +74,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
doc::doc_set_line_ending,
|
||||
doc::doc_outline,
|
||||
doc::doc_folding,
|
||||
doc::doc_highlights,
|
||||
doc::doc_selection_ranges,
|
||||
syntax::syntax_support,
|
||||
syntax::syntax_node_at,
|
||||
|
||||
@@ -4,21 +4,11 @@ use crate::state::AppState;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_tools::{InstallEvent, ToolInfo, Tools};
|
||||
use tauri::ipc::Channel;
|
||||
use tauri::{AppHandle, Manager, State, Window};
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
|
||||
/// The installer, reporting the executables chosen in the window's settings.
|
||||
fn tools(app: &AppHandle, state: &AppState, window: &Window) -> IdeResult<Tools> {
|
||||
fn tools(app: &AppHandle) -> IdeResult<Tools> {
|
||||
let data = app.path().app_data_dir().map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let (settings, root) = match state.project(window.label()) {
|
||||
Ok(project) => (project.settings.effective(), project.root.clone()),
|
||||
Err(_) => (state.global_settings.effective(), Default::default()),
|
||||
};
|
||||
let custom = settings
|
||||
.tools
|
||||
.iter()
|
||||
.filter_map(|(command, t)| Some((command.clone(), ide_sdk::apply::setting_path(&root, &t.path)?)))
|
||||
.collect();
|
||||
Ok(Tools::new(&data).with_custom_paths(custom))
|
||||
Ok(Tools::new(&data))
|
||||
}
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
@@ -28,8 +18,8 @@ fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
/// Status of every known language server / debug adapter and the languages using it.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn tools_list(app: AppHandle, window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ToolInfo>> {
|
||||
let tools = tools(&app, &state, &window)?;
|
||||
pub async fn tools_list(app: AppHandle, state: State<'_, AppState>) -> IdeResult<Vec<ToolInfo>> {
|
||||
let tools = tools(&app)?;
|
||||
let langs = state.languages.all();
|
||||
tauri::async_runtime::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
|
||||
}
|
||||
@@ -40,13 +30,12 @@ pub async fn tools_list(app: AppHandle, window: Window, state: State<'_, AppStat
|
||||
#[specta::specta]
|
||||
pub async fn tools_install(
|
||||
app: AppHandle,
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
name: String,
|
||||
request: RequestId,
|
||||
on_event: Channel<InstallEvent>,
|
||||
) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(&app, &state, &window)?;
|
||||
let tools = tools(&app)?;
|
||||
let langs = state.languages.all();
|
||||
let cancel = state.begin_request(request);
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
@@ -67,13 +56,8 @@ pub async fn tools_install(
|
||||
/// Removes a tool the IDE installed.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn tools_uninstall(
|
||||
app: AppHandle,
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
name: String,
|
||||
) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(&app, &state, &window)?;
|
||||
pub async fn tools_uninstall(app: AppHandle, state: State<'_, AppState>, name: String) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(&app)?;
|
||||
let langs = state.languages.all();
|
||||
let info =
|
||||
tauri::async_runtime::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.5",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+1
-36
@@ -92,11 +92,6 @@ export const commands = {
|
||||
*/
|
||||
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
|
||||
docFolding: (doc: DocId) => typedError<FoldRange[], IdeError>(__TAURI_INVOKE("doc_folding", { doc })),
|
||||
/**
|
||||
* Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
|
||||
* empty when the grammar has no highlights query or the document is large.
|
||||
*/
|
||||
docHighlights: (doc: DocId) => typedError<SyntaxHighlights, IdeError>(__TAURI_INVOKE("doc_highlights", { doc })),
|
||||
/**
|
||||
* Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
|
||||
* Large documents fall back to word / line / document ranges.
|
||||
@@ -3421,11 +3416,6 @@ export type Settings_Deserialize = {
|
||||
terminal?: TerminalSettings,
|
||||
actionsOnSave?: ActionsOnSaveSettings,
|
||||
externalTools?: ExternalTool[],
|
||||
/**
|
||||
* Language servers / debug adapters at a user-chosen location, by the
|
||||
* command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
*/
|
||||
tools?: { [key in string]: ToolSettings },
|
||||
};
|
||||
|
||||
export type Settings_Serialize = {
|
||||
@@ -3459,11 +3449,6 @@ export type Settings_Serialize = {
|
||||
terminal: TerminalSettings,
|
||||
actionsOnSave: ActionsOnSaveSettings,
|
||||
externalTools: ExternalTool[],
|
||||
/**
|
||||
* Language servers / debug adapters at a user-chosen location, by the
|
||||
* command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
*/
|
||||
tools: { [key in string]: ToolSettings },
|
||||
};
|
||||
|
||||
export type Severity = "error" | "warning" | "info" | "hint";
|
||||
@@ -3698,17 +3683,6 @@ export type SyntaxErrors = {
|
||||
truncated: boolean,
|
||||
};
|
||||
|
||||
/** Highlight classes sent to the UI, which maps each onto a Lezer tag. */
|
||||
export type SyntaxHighlightKind = "keyword" | "string" | "stringSpecial" | "escape" | "regexp" | "atom" | "number" | "constant" | "comment" | "docComment" | "function" | "functionCall" | "builtin" | "type" | "namespace" | "variable" | "selfVariable" | "property" | "attribute" | "macro" | "label" | "tag" | "operator" | "punctuation";
|
||||
|
||||
/** Highlighted ranges of a whole document, packed like LSP semantic tokens. */
|
||||
export type SyntaxHighlights = {
|
||||
/** Legend: `data` kind `i` is `kinds[i]`. */
|
||||
kinds: SyntaxHighlightKind[],
|
||||
/** `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets. */
|
||||
data: number[],
|
||||
};
|
||||
|
||||
/** One tree-sitter node. */
|
||||
export type SyntaxNode = {
|
||||
/** Grammar node kind, e.g. `method_invocation`, `identifier`, `;`. */
|
||||
@@ -3870,26 +3844,17 @@ export type ToolInfo = {
|
||||
/** Manual install instructions from the language definition. */
|
||||
installHint: string | null,
|
||||
homepage: string | null,
|
||||
/** Why the executable chosen in settings cannot be used (status is then `Missing`). */
|
||||
customError: string | null,
|
||||
};
|
||||
|
||||
export type ToolKind = "languageServer" | "debugger" |
|
||||
/** Loaded into another tool's process, e.g. a jdtls agent. */
|
||||
"plugin";
|
||||
|
||||
export type ToolSettings = {
|
||||
/** Executable to launch instead of the managed / `PATH` one; empty = auto-detect. */
|
||||
path?: string,
|
||||
};
|
||||
|
||||
export type ToolStatus =
|
||||
/** Installed by the IDE (managed tools dir or a toolchain component it manages). */
|
||||
"installed" |
|
||||
/** Found on the system `PATH`. */
|
||||
"onPath" |
|
||||
/** The executable chosen in settings. */
|
||||
"custom" | "missing";
|
||||
"onPath" | "missing";
|
||||
|
||||
export type TypeScriptSettings = {
|
||||
/**
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
type LineEnding,
|
||||
type OutlineItem,
|
||||
type Range,
|
||||
type SyntaxHighlights,
|
||||
type TextChange,
|
||||
} from "@/platform/ipc";
|
||||
|
||||
@@ -44,8 +43,6 @@ export interface DocBackend {
|
||||
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<string>;
|
||||
outline(doc: DocId): Promise<OutlineItem[]>;
|
||||
folding(doc: DocId): Promise<FoldRange[]>;
|
||||
/** Tree-sitter highlighting, for languages without a CodeMirror mode. */
|
||||
highlights(doc: DocId): Promise<SyntaxHighlights>;
|
||||
selectionRanges(doc: DocId, offset: number): Promise<Range[]>;
|
||||
languages(): Promise<LanguageInfo[]>;
|
||||
onPatched(handler: (e: DocPatchedEvent) => void): () => void;
|
||||
@@ -65,7 +62,6 @@ export const ipcBackend: DocBackend = {
|
||||
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
|
||||
outline: (doc) => call(commands.docOutline(doc)),
|
||||
folding: (doc) => call(commands.docFolding(doc)),
|
||||
highlights: (doc) => call(commands.docHighlights(doc)),
|
||||
selectionRanges: (doc, offset) => call(commands.docSelectionRanges(doc, offset)),
|
||||
languages: () => commands.languages(),
|
||||
onPatched: (h) => onIdeEvent("docPatched", (e) => h(e)),
|
||||
@@ -347,9 +343,6 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
}
|
||||
return items;
|
||||
},
|
||||
async highlights() {
|
||||
return { kinds: [], data: [] };
|
||||
},
|
||||
async folding(doc) {
|
||||
const d = get(doc);
|
||||
const out: FoldRange[] = [];
|
||||
|
||||
@@ -25,7 +25,6 @@ import { openideaTheme } from "./theme";
|
||||
import { caretRowHighlight } from "./caretRow";
|
||||
import { changeLane, overviewLane } from "./lanes";
|
||||
import { foldingExtension } from "./folding";
|
||||
import { syntaxHighlightField } from "./syntaxHighlight";
|
||||
import { indentGuides } from "./indentGuides";
|
||||
import { stickyMaxLines, stickyScroll } from "./stickyScroll";
|
||||
import { findExtension } from "./find";
|
||||
@@ -268,7 +267,6 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
clipboardHistoryExtension,
|
||||
indentOnInput(),
|
||||
syntaxHighlighting(openideaHighlightStyle),
|
||||
syntaxHighlightField,
|
||||
closeBrackets(),
|
||||
caretRowHighlight,
|
||||
fontZoom,
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { highlightingFor, syntaxHighlighting } from "@codemirror/language";
|
||||
import { tags as t } from "@lezer/highlight";
|
||||
import { openideaHighlightStyle } from "./highlight";
|
||||
import { setSyntaxHighlights, syntaxHighlightField } from "./syntaxHighlight";
|
||||
|
||||
function marks(state: EditorState) {
|
||||
const out: { text: string; cls: string }[] = [];
|
||||
state.field(syntaxHighlightField).between(0, state.doc.length, (from, to, d) => {
|
||||
out.push({ text: state.doc.sliceString(from, to), cls: d.spec.class as string });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("syntaxHighlightField", () => {
|
||||
const create = () =>
|
||||
EditorState.create({ doc: "def hi, do: :ok", extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField] });
|
||||
|
||||
it("styles backend ranges with the active highlight style and maps them through edits", () => {
|
||||
let state = create();
|
||||
state = state.update({
|
||||
effects: setSyntaxHighlights.of({ kinds: ["keyword", "atom", "functionCall"], data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0] }),
|
||||
}).state;
|
||||
const keyword = highlightingFor(state, [t.keyword]);
|
||||
const atom = highlightingFor(state, [t.atom]);
|
||||
expect(keyword).toBeTruthy();
|
||||
expect(marks(state)).toEqual([
|
||||
{ text: "def", cls: keyword },
|
||||
{ text: "hi", cls: highlightingFor(state, [t.function(t.variableName)]) },
|
||||
{ text: ":ok", cls: atom },
|
||||
]);
|
||||
|
||||
state = state.update({ changes: { from: 0, insert: " " } }).state;
|
||||
expect(marks(state).map((m) => m.text)).toEqual(["def", "hi", ":ok"]);
|
||||
});
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
/**
|
||||
* Tree-sitter highlighting (`doc_highlights`) for languages without a
|
||||
* CodeMirror mode (Elixir, ...): backend kinds → Lezer tags, so the colours
|
||||
* come from the same highlight style and Color Scheme settings as Lezer
|
||||
* highlighting. Refreshed with folding; in between, marks are mapped through
|
||||
* the changes.
|
||||
*/
|
||||
import { StateEffect, StateField, type EditorState } from "@codemirror/state";
|
||||
import { Decoration, EditorView, type DecorationSet } from "@codemirror/view";
|
||||
import { highlightingFor } from "@codemirror/language";
|
||||
import { tags as t, type Tag } from "@lezer/highlight";
|
||||
import type { SyntaxHighlightKind, SyntaxHighlights } from "@/platform/ipc";
|
||||
|
||||
const TAGS: Record<SyntaxHighlightKind, Tag> = {
|
||||
keyword: t.keyword,
|
||||
string: t.string,
|
||||
stringSpecial: t.special(t.string),
|
||||
escape: t.escape,
|
||||
regexp: t.regexp,
|
||||
atom: t.atom,
|
||||
number: t.number,
|
||||
constant: t.constant(t.variableName),
|
||||
comment: t.comment,
|
||||
docComment: t.docComment,
|
||||
function: t.function(t.definition(t.variableName)),
|
||||
functionCall: t.function(t.variableName),
|
||||
builtin: t.standard(t.variableName),
|
||||
type: t.typeName,
|
||||
namespace: t.namespace,
|
||||
variable: t.variableName,
|
||||
selfVariable: t.self,
|
||||
property: t.propertyName,
|
||||
attribute: t.annotation,
|
||||
macro: t.macroName,
|
||||
label: t.labelName,
|
||||
tag: t.tagName,
|
||||
operator: t.operator,
|
||||
punctuation: t.punctuation,
|
||||
};
|
||||
|
||||
export const setSyntaxHighlights = StateEffect.define<SyntaxHighlights>();
|
||||
|
||||
function decorations(state: EditorState, h: SyntaxHighlights): DecorationSet {
|
||||
const marks = h.kinds.map((k) => {
|
||||
const cls = highlightingFor(state, [TAGS[k]]);
|
||||
return cls ? Decoration.mark({ class: cls }) : null;
|
||||
});
|
||||
const len = state.doc.length;
|
||||
const ranges = [];
|
||||
for (let i = 0; i + 2 < h.data.length; i += 3) {
|
||||
const from = h.data[i]!;
|
||||
const to = Math.min(h.data[i + 1]!, len);
|
||||
const mark = marks[h.data[i + 2]!];
|
||||
if (mark && from < to) ranges.push(mark.range(from, to));
|
||||
}
|
||||
return Decoration.set(ranges, true);
|
||||
}
|
||||
|
||||
export const syntaxHighlightField = StateField.define<DecorationSet>({
|
||||
create: () => Decoration.none,
|
||||
update(deco, tr) {
|
||||
for (const e of tr.effects) if (e.is(setSyntaxHighlights)) return decorations(tr.state, e.value);
|
||||
return tr.docChanged ? deco.map(tr.changes) : deco;
|
||||
},
|
||||
provide: (f) => EditorView.decorations.from(f),
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import type { LanguageDescription, LanguageSupport } from "@codemirror/language";
|
||||
import { create } from "zustand";
|
||||
import type { EditorConfigProps } from "@/bindings";
|
||||
import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings, SyntaxHighlights } from "@/platform/ipc";
|
||||
import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings } from "@/platform/ipc";
|
||||
import {
|
||||
_emitEditorEvent,
|
||||
_saveParticipants,
|
||||
@@ -22,7 +22,6 @@ import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import { findLanguageDescription, languageInfo, loadLanguageInfos, loadSupport, loadedSupport, commentTokens } from "../cm/languages";
|
||||
import { foldEffect } from "@codemirror/language";
|
||||
import { backendFolds, setBackendFolds } from "../cm/folding";
|
||||
import { setSyntaxHighlights } from "../cm/syntaxHighlight";
|
||||
import {
|
||||
caretFor,
|
||||
compartments,
|
||||
@@ -266,7 +265,6 @@ export class DocModel {
|
||||
|
||||
addSlot(slot: EditorSlot) {
|
||||
this.slots.add(slot);
|
||||
if (this.highlights?.counter === this.changeCounter) slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
|
||||
}
|
||||
|
||||
removeSlot(slot: EditorSlot) {
|
||||
@@ -334,8 +332,6 @@ export class DocModel {
|
||||
indentOverride: { tabSize: number; insertSpaces: boolean } | null = null;
|
||||
/** Indentation detected in the file's text at open time. */
|
||||
detectedIndent: { insertSpaces: boolean; size?: number } | null = null;
|
||||
/** Last tree-sitter highlighting, for slots opened before the next refresh. */
|
||||
private highlights: { counter: number; value: SyntaxHighlights } | null = null;
|
||||
/** Fold-by-default has been applied (first folding ranges of the document). */
|
||||
private initialFolds = false;
|
||||
/** Signature of settings that require contributions to be rebuilt. */
|
||||
@@ -427,12 +423,7 @@ export class DocModel {
|
||||
await this.sync.whenIdle();
|
||||
const counter = this.changeCounter;
|
||||
const backend = this.manager.backend;
|
||||
const [folds, outline, highlights] = await Promise.allSettled([
|
||||
backend.folding(this.doc),
|
||||
backend.outline(this.doc),
|
||||
// Without a CodeMirror mode, colours come from the grammar's tree-sitter query.
|
||||
this.desc ? null : backend.highlights(this.doc),
|
||||
]);
|
||||
const [folds, outline] = await Promise.allSettled([backend.folding(this.doc), backend.outline(this.doc)]);
|
||||
if (this.closed) return;
|
||||
if (counter !== this.changeCounter) {
|
||||
this.scheduleRefresh();
|
||||
@@ -445,10 +436,6 @@ export class DocModel {
|
||||
this.foldByDefault();
|
||||
}
|
||||
}
|
||||
if (highlights.status === "fulfilled" && highlights.value) {
|
||||
this.highlights = { counter, value: highlights.value };
|
||||
for (const s of this.slots) s.reconfigure([setSyntaxHighlights.of(highlights.value)]);
|
||||
}
|
||||
if (outline.status === "fulfilled") {
|
||||
useOutline.setState({ [this.path]: outline.value });
|
||||
const lines = methodLines(outline.value);
|
||||
|
||||
@@ -37,11 +37,7 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.repo {
|
||||
min-width: 0;
|
||||
margin-left: 8px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
@@ -591,10 +591,5 @@ export function PullRequestsView() {
|
||||
export function PullRequestsHeader() {
|
||||
const availability = useGithub((s) => s.availability);
|
||||
if (availability?.kind !== "ready") return null;
|
||||
const name = availability.repo.nameWithOwner;
|
||||
return (
|
||||
<span className={styles.repo} title={name}>
|
||||
{name}
|
||||
</span>
|
||||
);
|
||||
return <span className={styles.repo}>{availability.repo.nameWithOwner}</span>;
|
||||
}
|
||||
@@ -63,7 +63,5 @@ describe("language pages", () => {
|
||||
expect(filterPackages(pkgs, "dj").map((p) => p.name)).toEqual(["Django"]);
|
||||
expect(filterPackages(pkgs, "")).toHaveLength(2);
|
||||
expect(tildify("/Users/me/p/.venv/bin/python")).toBe("~/p/.venv/bin/python");
|
||||
expect(tildify("C:/Users/me/.m2/wrapper/dists/apache-maven-3.9.16")).toBe("~/.m2/wrapper/dists/apache-maven-3.9.16");
|
||||
expect(tildify("C:/Program Files/Java/jdk-21")).toBe("C:/Program Files/Java/jdk-21");
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,7 @@ export function useProjectSetting<T>(key: string): [T, (v: T) => void] {
|
||||
return useSetting<T>(key, hasProject ? "project" : "global");
|
||||
}
|
||||
|
||||
const HOME = /^(?:\/(?:Users|home)|[A-Za-z]:[\\/]Users)[\\/][^\\/]+/;
|
||||
const HOME = /^\/(?:Users|home)\/[^/]+/;
|
||||
|
||||
/** `~/…` for paths in the home directory. */
|
||||
export function tildify(path: string): string {
|
||||
|
||||
@@ -3,58 +3,36 @@
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
min-height: 420px;
|
||||
}
|
||||
.intro {
|
||||
margin: 0;
|
||||
margin: 0 0 4px;
|
||||
max-width: 680px;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* list */
|
||||
.side {
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
width: 300px;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin: 8px 8px 6px;
|
||||
gap: 8px;
|
||||
}
|
||||
.search {
|
||||
width: 240px;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.segmented {
|
||||
display: flex;
|
||||
display: inline-flex;
|
||||
height: var(--h-control-small);
|
||||
margin: 0 8px 6px;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
overflow: hidden;
|
||||
}
|
||||
.segment {
|
||||
flex: 1;
|
||||
padding: 0 6px;
|
||||
padding: 0 10px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--fg-secondary);
|
||||
font: inherit;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.segment:hover {
|
||||
background: var(--bg-hover);
|
||||
@@ -67,70 +45,67 @@
|
||||
background: var(--bg-selected);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 0 0 4px;
|
||||
list-style: none;
|
||||
.error,
|
||||
.rowError {
|
||||
color: var(--danger);
|
||||
}
|
||||
.error {
|
||||
padding: 6px 0;
|
||||
}
|
||||
.tableWrap {
|
||||
min-width: 0;
|
||||
overflow: auto;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
.groupHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: var(--h-row);
|
||||
padding: 0 12px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
.table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: auto;
|
||||
}
|
||||
.groupCount {
|
||||
font-variant-numeric: tabular-nums;
|
||||
.table th {
|
||||
height: var(--h-header);
|
||||
padding: 0 8px;
|
||||
text-align: left;
|
||||
font-weight: normal;
|
||||
color: var(--fg-secondary);
|
||||
background: var(--bg-island);
|
||||
border-bottom: 1px solid var(--border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table td {
|
||||
padding: 4px 8px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
/* IDEA tables: no row rules, selection-like hover. */
|
||||
.row td {
|
||||
border-top: 0;
|
||||
}
|
||||
.table th + th {
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
.row:first-child td {
|
||||
border-top: 0;
|
||||
}
|
||||
.row:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.rowSelected,
|
||||
.rowSelected:hover {
|
||||
background: var(--bg-selected);
|
||||
.detailRow td {
|
||||
padding-top: 0;
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
.rowMain {
|
||||
.toolName {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
height: var(--h-row);
|
||||
padding: 0 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
gap: 6px;
|
||||
min-height: var(--h-row);
|
||||
}
|
||||
.rowMain:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.rowName {
|
||||
flex: none;
|
||||
max-width: 60%;
|
||||
overflow: hidden;
|
||||
.display {
|
||||
color: var(--fg-strong);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rowLanguages {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
text-align: right;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.kindTag {
|
||||
flex: none;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-control);
|
||||
@@ -138,108 +113,35 @@
|
||||
font-size: var(--fs-tiny);
|
||||
line-height: 16px;
|
||||
}
|
||||
.listEmpty {
|
||||
padding: 8px 12px;
|
||||
.sub {
|
||||
max-width: 320px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* details */
|
||||
.details {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 12px 16px 16px;
|
||||
overflow: auto;
|
||||
}
|
||||
.detailsEmpty {
|
||||
flex: 1;
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
}
|
||||
.headerText {
|
||||
min-width: 0;
|
||||
}
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--fg-strong);
|
||||
font-size: var(--fs-input-large);
|
||||
font-weight: 600;
|
||||
}
|
||||
.subtitle {
|
||||
margin-top: 2px;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
column-gap: 16px;
|
||||
row-gap: 8px;
|
||||
align-items: baseline;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.field {
|
||||
display: contents;
|
||||
}
|
||||
.fieldLabel {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.fieldValue {
|
||||
min-width: 0;
|
||||
color: var(--fg);
|
||||
}
|
||||
code.fieldValue {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.breakAll {
|
||||
overflow-wrap: anywhere;
|
||||
.languages {
|
||||
max-width: 200px;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.version {
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.pathRow {
|
||||
/* Status, Version and actions take their content's width; Tool and Languages share the rest. */
|
||||
.fitHead,
|
||||
.actionsHead {
|
||||
width: 1%;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.pathInput {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.fieldHint {
|
||||
margin-top: 2px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.fieldError,
|
||||
.error {
|
||||
color: var(--danger);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.fieldError {
|
||||
margin-top: 2px;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.notice {
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-control);
|
||||
color: var(--fg-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.job {
|
||||
display: flex;
|
||||
@@ -264,10 +166,14 @@ code.fieldValue {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.hint {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.log {
|
||||
margin: 0;
|
||||
margin: 4px 0 0;
|
||||
padding: 6px 8px;
|
||||
max-height: 240px;
|
||||
max-height: 200px;
|
||||
overflow: auto;
|
||||
background: var(--bg-app);
|
||||
color: var(--fg-secondary);
|
||||
@@ -278,3 +184,15 @@ code.fieldValue {
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.empty {
|
||||
padding: 12px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.visuallyHidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -1,18 +1,12 @@
|
||||
/**
|
||||
* Settings › Languages & Frameworks › Language Servers, laid out like the
|
||||
* Plugins page: language servers and debug adapters in a list on the left,
|
||||
* the selected tool's location, custom path and install actions on the right.
|
||||
*/
|
||||
import { useEffect, useId, useMemo, useState, type KeyboardEvent } from "react";
|
||||
/** Settings › Languages & Frameworks › Language Servers: status + install/uninstall of LSP servers and debug adapters. */
|
||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { ToolInfo } from "@/bindings";
|
||||
import { Badge, Button, EmptyState, IconButton, Input, ProgressBar, SearchField, Spinner, T } from "@/ui";
|
||||
import { toolsBackend } from "./backend";
|
||||
import { Badge, Button, IconButton, ProgressBar, SearchField, Spinner, T } from "@/ui";
|
||||
import {
|
||||
cancelInstall,
|
||||
installTool,
|
||||
refreshTools,
|
||||
setCustomPath,
|
||||
STATUS_LABEL,
|
||||
uninstallTool,
|
||||
useTools,
|
||||
@@ -25,16 +19,9 @@ type Filter = "all" | "missing" | "installed";
|
||||
const STATUS_TONE: Record<ToolInfo["status"], "success" | "accent" | "warning"> = {
|
||||
installed: "success",
|
||||
onPath: "accent",
|
||||
custom: "accent",
|
||||
missing: "warning",
|
||||
};
|
||||
|
||||
const KIND_LABEL: Record<ToolInfo["kind"], string> = {
|
||||
languageServer: "Language server",
|
||||
debugger: "Debugger",
|
||||
plugin: "Plugin",
|
||||
};
|
||||
|
||||
export function filterTools(tools: readonly ToolInfo[], query: string, filter: Filter): ToolInfo[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
return tools.filter((t) => {
|
||||
@@ -61,308 +48,217 @@ function JobRow({ name, job }: { name: string; job: InstallJob }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ToolRow({ tool, selected, onSelect }: { tool: ToolInfo; selected: boolean; onSelect: () => void }) {
|
||||
function Actions({
|
||||
tool,
|
||||
busy,
|
||||
onToggleLog,
|
||||
hasLog,
|
||||
logOpen,
|
||||
}: {
|
||||
tool: ToolInfo;
|
||||
busy: boolean;
|
||||
hasLog: boolean;
|
||||
logOpen: boolean;
|
||||
onToggleLog: () => void;
|
||||
}) {
|
||||
const label = tool.displayName;
|
||||
return (
|
||||
<li className={clsx(styles.row, selected && styles.rowSelected)}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.rowMain}
|
||||
aria-current={selected || undefined}
|
||||
data-tool={tool.name}
|
||||
title={`${tool.displayName} — ${tool.languages.join(", ")}`}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<Badge dot tone={STATUS_TONE[tool.status]}>
|
||||
{STATUS_LABEL[tool.status]}
|
||||
</Badge>
|
||||
<span className={styles.rowName}>{tool.displayName}</span>
|
||||
{tool.kind !== "languageServer" && (
|
||||
<span className={styles.kindTag}>
|
||||
<T>{KIND_LABEL[tool.kind]}</T>
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.rowLanguages}>{tool.languages.join(", ")}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Path" field: an executable to launch instead of the detected one, saved when committed. */
|
||||
function CustomPath({ tool }: { tool: ToolInfo }) {
|
||||
const id = useId();
|
||||
const saved = tool.status === "custom" || tool.customError ? (tool.path ?? "") : "";
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const value = draft ?? (tool.status === "custom" ? saved : "");
|
||||
const commit = async (next: string) => {
|
||||
setDraft(null);
|
||||
if (next.trim() !== saved) await setCustomPath(tool.command, next);
|
||||
};
|
||||
return (
|
||||
<div className={styles.field}>
|
||||
<label className={styles.fieldLabel} htmlFor={id}>
|
||||
<T>Path</T>
|
||||
</label>
|
||||
<div className={styles.fieldValue}>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={value}
|
||||
invalid={!!tool.customError}
|
||||
placeholder={tool.status !== "custom" && tool.path ? tool.path : "Auto-detect"}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={() => draft !== null && void commit(draft)}
|
||||
onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") void commit(e.currentTarget.value);
|
||||
if (e.key === "Escape" && draft !== null) {
|
||||
e.stopPropagation();
|
||||
setDraft(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const picked = await toolsBackend().chooseExecutable(`Select ${tool.command}`, value || undefined);
|
||||
if (picked) await commit(picked);
|
||||
}}
|
||||
/>
|
||||
{tool.status === "custom" && (
|
||||
<IconButton icon="close" size="small" title="Use auto-detected" onClick={() => void commit("")} />
|
||||
)}
|
||||
</span>
|
||||
{tool.customError ? (
|
||||
<div className={styles.fieldError} role="alert">
|
||||
{tool.customError}
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.fieldHint}>
|
||||
<T>Leave empty to use the IDE-installed copy, else the one on PATH.</T>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Details({ tool }: { tool: ToolInfo }) {
|
||||
const job = useTools((s) => s.jobs[tool.name]);
|
||||
const last = useTools((s) => s.logs[tool.name]);
|
||||
const [logOpen, setLogOpen] = useState(false);
|
||||
const log = job?.lines ?? last?.lines ?? [];
|
||||
const lastError = !job && last?.error !== "Cancelled" ? last?.error : null;
|
||||
const busy = !!job;
|
||||
const manualHint = !tool.canInstall && tool.status === "missing";
|
||||
return (
|
||||
<div className={styles.details} aria-label={`${tool.displayName} details`}>
|
||||
<div className={styles.header}>
|
||||
<div className={styles.headerText}>
|
||||
<div className={styles.title}>
|
||||
<span>{tool.displayName}</span>
|
||||
<Badge tone={STATUS_TONE[tool.status]}>{STATUS_LABEL[tool.status]}</Badge>
|
||||
</div>
|
||||
<div className={styles.subtitle}>
|
||||
<T>{KIND_LABEL[tool.kind]}</T>
|
||||
{tool.languages.length > 0 && <> · {tool.languages.join(", ")}</>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.actions}>
|
||||
{tool.canInstall && (
|
||||
<Button
|
||||
size="small"
|
||||
variant={tool.status === "missing" ? "primary" : "secondary"}
|
||||
disabled={busy}
|
||||
onClick={() => void installTool(tool.name)}
|
||||
aria-label={`${tool.status === "installed" ? "Reinstall" : "Install"} ${tool.displayName}`}
|
||||
>
|
||||
{tool.status === "installed" ? "Reinstall" : "Install"}
|
||||
</Button>
|
||||
)}
|
||||
{tool.canUninstall && (
|
||||
<Button size="small" variant="ghost" disabled={busy} onClick={() => void uninstallTool(tool.name)}>
|
||||
<T>Uninstall</T>
|
||||
</Button>
|
||||
)}
|
||||
{log.length > 0 && (
|
||||
<Button size="small" variant="ghost" aria-expanded={logOpen} onClick={() => setLogOpen(!logOpen)}>
|
||||
{logOpen ? "Hide install log" : "Show install log"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{job && <JobRow name={tool.displayName} job={job} />}
|
||||
{lastError && (
|
||||
<div className={styles.error} role="alert">
|
||||
{lastError}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
{tool.canInstall && (
|
||||
<Button
|
||||
size="small"
|
||||
variant={tool.status === "missing" ? "primary" : "secondary"}
|
||||
disabled={busy}
|
||||
onClick={() => void installTool(tool.name)}
|
||||
aria-label={`${tool.status === "missing" ? "Install" : tool.status === "installed" ? "Reinstall" : "Install managed copy of"} ${label}`}
|
||||
>
|
||||
{tool.status === "missing" ? "Install" : tool.status === "installed" ? "Reinstall" : "Install"}
|
||||
</Button>
|
||||
)}
|
||||
{manualHint && (
|
||||
<div className={styles.notice} role="note">
|
||||
{tool.unavailableReason ?? tool.installHint ?? "Install it manually and put it on PATH."}
|
||||
</div>
|
||||
{tool.canUninstall && (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void uninstallTool(tool.name)}
|
||||
aria-label={`Uninstall ${label}`}
|
||||
>
|
||||
<T>Uninstall</T>
|
||||
</Button>
|
||||
)}
|
||||
{tool.canInstall && tool.status === "missing" && tool.unavailableReason === null && tool.installMethod && (
|
||||
<div className={styles.fieldHint}>
|
||||
<T>Installs into the IDE's own tools folder via</T> {tool.installMethod}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.fields}>
|
||||
<div className={styles.field}>
|
||||
<span className={styles.fieldLabel}>
|
||||
<T>Command</T>
|
||||
</span>
|
||||
<code className={styles.fieldValue}>{tool.command}</code>
|
||||
</div>
|
||||
{tool.kind !== "plugin" && <CustomPath key={`${tool.name}:${tool.path ?? ""}`} tool={tool} />}
|
||||
{tool.status !== "custom" && (
|
||||
<div className={styles.field}>
|
||||
<span className={styles.fieldLabel}>
|
||||
<T>Location</T>
|
||||
</span>
|
||||
<code className={clsx(styles.fieldValue, styles.breakAll)}>{tool.path ?? "—"}</code>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.field}>
|
||||
<span className={styles.fieldLabel}>
|
||||
<T>Version</T>
|
||||
</span>
|
||||
<span className={clsx(styles.fieldValue, styles.version)}>{tool.version ?? "—"}</span>
|
||||
</div>
|
||||
{tool.homepage && (
|
||||
<div className={styles.field}>
|
||||
<span className={styles.fieldLabel}>
|
||||
<T>Homepage</T>
|
||||
</span>
|
||||
<a
|
||||
className={clsx(styles.fieldValue, styles.breakAll)}
|
||||
href={tool.homepage}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{tool.homepage}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{logOpen && log.length > 0 && (
|
||||
<pre className={styles.log} aria-label={`${tool.displayName} install log`}>
|
||||
{log.join("\n")}
|
||||
</pre>
|
||||
{hasLog && (
|
||||
<IconButton
|
||||
icon="terminal"
|
||||
size="small"
|
||||
title={logOpen ? "Hide install log" : "Show install log"}
|
||||
pressed={logOpen}
|
||||
onClick={onToggleLog}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LanguageServersPage() {
|
||||
const { tools, loaded, loading, error } = useTools();
|
||||
const { tools, loaded, loading, error, jobs, logs } = useTools();
|
||||
const [query, setQuery] = useState("");
|
||||
const [filter, setFilter] = useState<Filter>("all");
|
||||
const [selectedName, setSelectedName] = useState<string | null>(null);
|
||||
const [openLog, setOpenLog] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshTools();
|
||||
}, []);
|
||||
|
||||
const shown = useMemo(() => filterTools(tools, query, filter), [tools, query, filter]);
|
||||
const ready = shown.filter((t) => t.status !== "missing");
|
||||
const missing = shown.filter((t) => t.status === "missing");
|
||||
const ordered = [...ready, ...missing];
|
||||
const selected = ordered.find((t) => t.name === selectedName) ?? ordered[0] ?? null;
|
||||
const missingCount = tools.filter((t) => t.status === "missing").length;
|
||||
|
||||
const onListKey = (e: KeyboardEvent<HTMLUListElement>) => {
|
||||
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
|
||||
e.preventDefault();
|
||||
const i = selected ? ordered.indexOf(selected) : -1;
|
||||
const next = ordered[Math.min(ordered.length - 1, Math.max(0, i + (e.key === "ArrowDown" ? 1 : -1)))];
|
||||
if (!next) return;
|
||||
setSelectedName(next.name);
|
||||
e.currentTarget.querySelector<HTMLElement>(`[data-tool="${CSS.escape(next.name)}"]`)?.focus();
|
||||
};
|
||||
|
||||
const group = (title: string, list: ToolInfo[]) =>
|
||||
list.length > 0 && (
|
||||
<>
|
||||
<li className={styles.groupHeader} role="presentation">
|
||||
<T>{title}</T> <span className={styles.groupCount}>{list.length}</span>
|
||||
</li>
|
||||
{list.map((t) => (
|
||||
<ToolRow key={t.name} tool={t} selected={t === selected} onSelect={() => setSelectedName(t.name)} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<p className={styles.intro}>
|
||||
Language servers and debug adapters used by the IDE. Missing tools can be installed into the IDE's own
|
||||
tools folder; nothing is downloaded until you click Install.
|
||||
</p>
|
||||
<div className={styles.toolbar}>
|
||||
<SearchField
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Filter by tool or language"
|
||||
aria-label="Filter language servers"
|
||||
/>
|
||||
<div className={styles.segmented} role="radiogroup" aria-label="Show">
|
||||
{(["all", "missing", "installed"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={filter === f}
|
||||
className={clsx(styles.segment, filter === f && styles.segmentOn)}
|
||||
onClick={() => setFilter(f)}
|
||||
>
|
||||
{f === "all" ? "All" : f === "missing" ? `Missing (${missingCount})` : "Available"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className={styles.spacer} />
|
||||
{loading && <Spinner size={14} label="Checking tools" />}
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Re-check installed tools"
|
||||
onClick={() => void refreshTools()}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.body}>
|
||||
<div className={styles.side}>
|
||||
<div className={styles.toolbar}>
|
||||
<SearchField
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Filter by tool or language"
|
||||
aria-label="Filter language servers"
|
||||
/>
|
||||
{loading ? (
|
||||
<Spinner size={14} label="Checking tools" />
|
||||
) : (
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
size="small"
|
||||
title="Re-check installed tools"
|
||||
onClick={() => void refreshTools()}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className={styles.tableWrap}>
|
||||
<table className={styles.table} aria-label="Language servers and debug adapters">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">
|
||||
<T>Tool</T>
|
||||
</th>
|
||||
<th scope="col">
|
||||
<T>Languages</T>
|
||||
</th>
|
||||
<th scope="col" className={styles.fitHead}>
|
||||
<T>Status</T>
|
||||
</th>
|
||||
<th scope="col" className={styles.fitHead}>
|
||||
<T>Version</T>
|
||||
</th>
|
||||
<th scope="col" className={styles.actionsHead}>
|
||||
<span className={styles.visuallyHidden}>
|
||||
<T>Actions</T>
|
||||
</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{shown.map((t) => {
|
||||
const job = jobs[t.name];
|
||||
const log = job?.lines ?? logs[t.name]?.lines ?? [];
|
||||
const lastError = !job ? logs[t.name]?.error : null;
|
||||
const logOpen = openLog === t.name;
|
||||
return (
|
||||
<Fragment key={t.name}>
|
||||
<tr className={styles.row} data-tool={t.name}>
|
||||
<td>
|
||||
<div className={styles.toolName}>
|
||||
<span className={styles.display}>{t.displayName}</span>
|
||||
{t.kind === "debugger" && (
|
||||
<span className={styles.kindTag}>
|
||||
<T>Debugger</T>
|
||||
</span>
|
||||
)}
|
||||
{t.kind === "plugin" && (
|
||||
<span className={styles.kindTag}>
|
||||
<T>Plugin</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(t.path ?? (t.command !== t.displayName ? t.command : null)) && (
|
||||
<div className={styles.sub} title={t.path ?? undefined}>
|
||||
{t.path ?? t.command}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className={styles.languages}>{t.languages.join(", ") || "—"}</td>
|
||||
<td>
|
||||
<Badge tone={STATUS_TONE[t.status]}>{STATUS_LABEL[t.status]}</Badge>
|
||||
</td>
|
||||
<td className={styles.version}>{t.version ?? "—"}</td>
|
||||
<td>
|
||||
<Actions
|
||||
tool={t}
|
||||
busy={!!job}
|
||||
hasLog={log.length > 0}
|
||||
logOpen={logOpen}
|
||||
onToggleLog={() => setOpenLog(logOpen ? null : t.name)}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
{(job || lastError || logOpen || (!t.canInstall && t.status === "missing")) && (
|
||||
<tr className={styles.detailRow}>
|
||||
<td colSpan={5}>
|
||||
{job && <JobRow name={t.displayName} job={job} />}
|
||||
{lastError && lastError !== "Cancelled" && (
|
||||
<div className={styles.rowError} role="alert">
|
||||
{lastError}
|
||||
</div>
|
||||
)}
|
||||
{!t.canInstall && t.status === "missing" && (
|
||||
<div className={styles.hint}>
|
||||
{t.unavailableReason ?? t.installHint ?? "Install it manually and put it on PATH."}
|
||||
</div>
|
||||
)}
|
||||
{logOpen && log.length > 0 && (
|
||||
<pre className={styles.log} aria-label={`${t.displayName} install log`}>
|
||||
{log.join("\n")}
|
||||
</pre>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{loaded && shown.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>No tools match.</T>
|
||||
</div>
|
||||
<div className={styles.segmented} role="radiogroup" aria-label="Show">
|
||||
{(["all", "missing", "installed"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={filter === f}
|
||||
className={clsx(styles.segment, filter === f && styles.segmentOn)}
|
||||
onClick={() => setFilter(f)}
|
||||
>
|
||||
{f === "all" ? "All" : f === "missing" ? `Missing (${missingCount})` : "Available"}
|
||||
</button>
|
||||
))}
|
||||
)}
|
||||
{!loaded && !error && (
|
||||
<div className={styles.empty}>
|
||||
<T>Checking installed tools…</T>
|
||||
</div>
|
||||
<ul className={styles.list} aria-label="Language servers and debug adapters" onKeyDown={onListKey}>
|
||||
{group("Available", ready)}
|
||||
{group("Missing", missing)}
|
||||
{loaded && shown.length === 0 && (
|
||||
<li className={styles.listEmpty}>
|
||||
<T>No tools match.</T>
|
||||
</li>
|
||||
)}
|
||||
{!loaded && !error && (
|
||||
<li className={styles.listEmpty}>
|
||||
<T>Checking installed tools…</T>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
{selected ? (
|
||||
<Details key={selected.name} tool={selected} />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={loaded ? "No tool selected" : "Loading…"} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -126,59 +126,29 @@ describe("missing language server prompt", () => {
|
||||
});
|
||||
|
||||
describe("LanguageServersPage", () => {
|
||||
const listItem = (name: string) =>
|
||||
screen.getByRole("list", { name: /language servers/i }).querySelector<HTMLElement>(`[data-tool="${name}"]`)!;
|
||||
|
||||
it("lists tools and installs from the details pane", async () => {
|
||||
it("lists tools and installs from the table", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageServersPage />);
|
||||
await screen.findByText("gopls");
|
||||
await user.click(listItem("gopls"));
|
||||
const details = screen.getByLabelText("gopls details");
|
||||
expect(within(details).getByText("Missing")).toBeInTheDocument();
|
||||
await user.click(within(details).getByRole("button", { name: "Install gopls" }));
|
||||
await waitFor(() => expect(screen.getByLabelText("gopls details")).toHaveTextContent("Installed"));
|
||||
expect(screen.getByLabelText("gopls details")).toHaveTextContent("1.0.0");
|
||||
// Installed tools move to the Available group, still selected.
|
||||
expect(listItem("gopls")).toHaveAttribute("aria-current", "true");
|
||||
const table = await screen.findByRole("table", { name: /language servers/i });
|
||||
const row = await within(table).findByText("gopls");
|
||||
const tr = row.closest("tr")!;
|
||||
expect(within(tr).getByText("Missing")).toBeInTheDocument();
|
||||
await user.click(within(tr).getByRole("button", { name: "Install gopls" }));
|
||||
await waitFor(() => expect(within(table).getByText("gopls").closest("tr")!).toHaveTextContent("Installed"));
|
||||
expect(within(table).getByText("gopls").closest("tr")!).toHaveTextContent("1.0.0");
|
||||
// The install log can be shown afterwards.
|
||||
await user.click(screen.getByRole("button", { name: "Show install log" }));
|
||||
await user.click(
|
||||
within(within(table).getByText("gopls").closest("tr")!).getByRole("button", { name: "Show install log" }),
|
||||
);
|
||||
expect(screen.getByLabelText("gopls install log")).toHaveTextContent("Installing gopls");
|
||||
});
|
||||
|
||||
it("explains why a tool cannot be installed", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageServersPage />);
|
||||
await screen.findByText("solargraph");
|
||||
await user.click(listItem("solargraph"));
|
||||
expect(screen.getByText("gem install solargraph")).toBeInTheDocument();
|
||||
await user.click(listItem("zls"));
|
||||
expect(await screen.findByText("gem install solargraph")).toBeInTheDocument();
|
||||
expect(screen.getByText("curl is required to download tools")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("sets and clears a custom path", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageServersPage />);
|
||||
await screen.findByText("gopls");
|
||||
await user.click(listItem("gopls"));
|
||||
const path = within(screen.getByLabelText("gopls details")).getByRole("textbox", { name: "Path" });
|
||||
await user.type(path, "/opt/go/bin/gopls{Enter}");
|
||||
await waitFor(() => expect(screen.getByLabelText("gopls details")).toHaveTextContent("Custom"));
|
||||
expect(backend.customPaths).toEqual({ gopls: "/opt/go/bin/gopls" });
|
||||
await user.click(screen.getByRole("button", { name: "Use auto-detected" }));
|
||||
await waitFor(() => expect(backend.customPaths).toEqual({}));
|
||||
expect(screen.getByLabelText("gopls details")).toHaveTextContent("Missing");
|
||||
});
|
||||
|
||||
it("moves the selection with the arrow keys", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageServersPage />);
|
||||
await screen.findByText("gopls");
|
||||
await user.click(listItem("rust-analyzer"));
|
||||
await user.keyboard("{ArrowDown}");
|
||||
expect(screen.getByLabelText("typescript-language-server details")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters to missing tools", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageServersPage />);
|
||||
@@ -188,7 +158,7 @@ describe("LanguageServersPage", () => {
|
||||
expect(screen.getByText("gopls")).toBeInTheDocument();
|
||||
await user.type(screen.getByRole("textbox", { name: /filter language servers/i }), "zig");
|
||||
expect(screen.queryByText("gopls")).not.toBeInTheDocument();
|
||||
expect(listItem("zls")).toHaveTextContent("ZLS (Zig)");
|
||||
expect(screen.getByText("ZLS (Zig)")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows backend errors", async () => {
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import type { InstallEvent, RequestId, ToolInfo } from "@/bindings";
|
||||
import { call, commands, IpcError, isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
export interface ToolsBackend {
|
||||
list(): Promise<ToolInfo[]>;
|
||||
@@ -14,10 +13,6 @@ export interface ToolsBackend {
|
||||
cancel(request: RequestId): void;
|
||||
/** Restarts running language servers named `name` (after an install). */
|
||||
restartServers(name: string): Promise<void>;
|
||||
/** Launches `command` from `path` instead of the detected one (global setting); "" clears it. */
|
||||
setCustomPath(command: string, path: string): Promise<void>;
|
||||
/** File chooser for an executable; null when cancelled. */
|
||||
chooseExecutable(title: string, defaultPath?: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
export const tauriToolsBackend: ToolsBackend = {
|
||||
@@ -40,18 +35,6 @@ export const tauriToolsBackend: ToolsBackend = {
|
||||
servers.filter((s) => s.name === name).map((s) => call(commands.lspRestart(s.id)).catch(() => {})),
|
||||
);
|
||||
},
|
||||
setCustomPath: async (command, path) => {
|
||||
const tools = { ...(await commands.settingsGet()).tools };
|
||||
if (path) tools[command] = { path };
|
||||
else delete tools[command];
|
||||
const settings = await call(commands.settingsSet("global", "tools", JSON.stringify(tools)));
|
||||
useProject.setState({ settings });
|
||||
},
|
||||
chooseExecutable: async (title, defaultPath) => {
|
||||
const { open } = await import("@tauri-apps/plugin-dialog");
|
||||
const picked = await open({ directory: false, multiple: false, title, defaultPath: defaultPath || undefined });
|
||||
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
|
||||
},
|
||||
};
|
||||
|
||||
function tool(partial: Partial<ToolInfo> & Pick<ToolInfo, "name" | "languages">): ToolInfo {
|
||||
@@ -68,7 +51,6 @@ function tool(partial: Partial<ToolInfo> & Pick<ToolInfo, "name" | "languages">)
|
||||
canUninstall: false,
|
||||
installHint: null,
|
||||
homepage: null,
|
||||
customError: null,
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
@@ -201,23 +183,6 @@ export class MemoryToolsBackend implements ToolsBackend {
|
||||
async restartServers(name: string) {
|
||||
this.restarted.push(name);
|
||||
}
|
||||
|
||||
/** Paths set through `setCustomPath`, by command. */
|
||||
customPaths: Record<string, string> = {};
|
||||
/** What `chooseExecutable` answers. */
|
||||
chosen: string | null = null;
|
||||
|
||||
async setCustomPath(command: string, path: string) {
|
||||
if (path) this.customPaths[command] = path;
|
||||
else delete this.customPaths[command];
|
||||
for (const t of this.tools.filter((x) => x.command === command)) {
|
||||
this.replace(path ? { ...t, status: "custom", path, version: null } : { ...t, status: "missing", path: null });
|
||||
}
|
||||
}
|
||||
|
||||
async chooseExecutable() {
|
||||
return this.chosen;
|
||||
}
|
||||
}
|
||||
|
||||
let backend: ToolsBackend | null = null;
|
||||
|
||||
@@ -179,26 +179,8 @@ export async function uninstallTool(name: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Launches `command` from `path` (empty: auto-detect again), then re-checks the tools. */
|
||||
export async function setCustomPath(command: string, path: string): Promise<boolean> {
|
||||
try {
|
||||
await toolsBackend().setCustomPath(command, path.trim());
|
||||
await refreshTools();
|
||||
return true;
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
group: "tools",
|
||||
level: "error",
|
||||
title: `Failed to set the path of ${command}`,
|
||||
body: errorText(e),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const STATUS_LABEL: Record<ToolInfo["status"], string> = {
|
||||
installed: "Installed",
|
||||
onPath: "On PATH",
|
||||
custom: "Custom",
|
||||
missing: "Missing",
|
||||
};
|
||||
@@ -111,16 +111,14 @@ function LogView() {
|
||||
const commits = useGitLog((s) => s.commits);
|
||||
const selected = useGitLog((s) => s.selected);
|
||||
const root = useVcs((s) => s.root);
|
||||
const repo = useVcs((s) => s.repo);
|
||||
const lastRefs = useRef<string | null>(null);
|
||||
|
||||
// On mount, when the window switches to another project and when another of its
|
||||
// repositories is selected (its branches are needed to notice its refs moving).
|
||||
// On mount and when the window switches to another repository.
|
||||
useEffect(() => {
|
||||
lastRefs.current = null;
|
||||
if (!useGitLog.getState().commits.length) void reloadLog();
|
||||
void loadBranches().catch(() => undefined);
|
||||
}, [root, repo]);
|
||||
}, [root]);
|
||||
|
||||
// HEAD or a branch tip moved (commit, undo, reset, rebase, fetch…): reload (keeps the selection).
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { isNestedRepoEntry, rollbackCandidates } from "../changeOps";
|
||||
|
||||
const fs = (rel: string, unstaged: FileStatus["unstaged"]): FileStatus => ({
|
||||
path: `/r/${rel}`,
|
||||
relPath: rel,
|
||||
staged: null,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
});
|
||||
|
||||
describe("rollback candidates with a submodule", () => {
|
||||
const roots = ["/r", "/r/libs/core"];
|
||||
const status = [
|
||||
fs("app.txt", "modified"),
|
||||
fs("libs/core", "modified"),
|
||||
fs("libs/core/core.txt", "modified"),
|
||||
fs("libs/core/wip.txt", "untracked"),
|
||||
];
|
||||
const paths = (files: FileStatus[]) => files.map((f) => f.path);
|
||||
|
||||
it("never offers the submodule's own entry", () => {
|
||||
expect(isNestedRepoEntry("/r/libs/core", roots)).toBe(true);
|
||||
expect(isNestedRepoEntry("/r", roots)).toBe(false);
|
||||
expect(paths(rollbackCandidates(undefined, status, roots))).toEqual(["/r/app.txt", "/r/libs/core/core.txt"]);
|
||||
});
|
||||
|
||||
it("takes a selected change alone, not the submodule's changes below its path", () => {
|
||||
expect(rollbackCandidates(["/r/libs/core"], status, roots)).toEqual([]);
|
||||
expect(paths(rollbackCandidates(["/r/app.txt", "/r/libs/core"], status, roots))).toEqual(["/r/app.txt"]);
|
||||
});
|
||||
|
||||
it("takes the changes below a selected folder", () => {
|
||||
expect(paths(rollbackCandidates(["/r/libs"], status, roots))).toEqual(["/r/libs/core/core.txt"]);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { editorService, maybeEditorService, notifications, toolWindowService } f
|
||||
import { annotationsShown, toggleAnnotations } from "./blame";
|
||||
import { showBranchesPopup } from "./BranchWidget";
|
||||
import { checkoutRevision, newBranch } from "./branchOps";
|
||||
import { addToVcs, isNestedRepoEntry, rollbackCandidates, showRollbackDialog, stashChanges } from "./changeOps";
|
||||
import { addToVcs, rollbackCandidates, showRollbackDialog, stashChanges } from "./changeOps";
|
||||
import { useCommit } from "./commitStore";
|
||||
import { gotoConflict, resolveAtCaret, showConflictsDialog } from "./conflictsUi";
|
||||
import { focusedDiffNavigator } from "./diffNavigator";
|
||||
@@ -20,7 +20,7 @@ import { allRepos, runRemote } from "./ops";
|
||||
import { showPushDialog, showUpdateDialog, type PushTarget } from "./remoteUi";
|
||||
import { chooseRevision } from "./RevisionChooser";
|
||||
import { showCloneDialog } from "./clone";
|
||||
import { refreshNow, repoName } from "./store";
|
||||
import { refreshNow } from "./store";
|
||||
|
||||
const VCS = "vcsAvailable";
|
||||
|
||||
@@ -171,18 +171,7 @@ export function registerVcsActions(): () => void {
|
||||
const explicit = argPaths(arg);
|
||||
const sel = useCommit.getState().selection;
|
||||
const paths = explicit?.length ? explicit : commitWindowFocused() && sel.length ? sel : undefined;
|
||||
if (paths) {
|
||||
const candidates = rollbackCandidates(paths);
|
||||
const submodule = paths.find((p) => isNestedRepoEntry(p));
|
||||
if (!candidates.length && submodule)
|
||||
return notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: "Submodule changes cannot be rolled back here",
|
||||
body: `${repoName(submodule)} points to another commit. Check out the recorded commit in the submodule (git submodule update) to revert it.`,
|
||||
});
|
||||
return showRollbackDialog(candidates);
|
||||
}
|
||||
if (paths) return showRollbackDialog(rollbackCandidates(paths));
|
||||
const active = maybeEditorService()?.activePath();
|
||||
const activeChanged = active ? rollbackCandidates([active]) : [];
|
||||
showRollbackDialog(activeChanged.length ? activeChanged : rollbackCandidates());
|
||||
|
||||
@@ -77,32 +77,20 @@ export async function commitChanges(): Promise<string | undefined> {
|
||||
}
|
||||
|
||||
/** Files the Rollback action applies to by default. */
|
||||
export function rollbackCandidates(
|
||||
paths?: readonly string[],
|
||||
status: readonly FileStatus[] = useVcs.getState().status,
|
||||
roots: readonly string[] = useVcs.getState().roots,
|
||||
): FileStatus[] {
|
||||
// A nested repository's own entry (a submodule's checked-out commit) is not rolled back
|
||||
// from the enclosing repository: it is changed by checking out a commit in the submodule.
|
||||
const changed = status.filter((f) => {
|
||||
export function rollbackCandidates(paths?: readonly string[]): FileStatus[] {
|
||||
const status = useVcs.getState().status.filter((f) => {
|
||||
const g = groupOf(f);
|
||||
return (g === "changes" || g === "conflicts") && !isNestedRepoEntry(f.path, roots);
|
||||
return g === "changes" || g === "conflicts";
|
||||
});
|
||||
if (!paths?.length) return changed;
|
||||
if (!paths?.length) return status;
|
||||
const set = new Set(paths.map(stripSlash));
|
||||
// A selected change is just that change; other paths are folders and take the changes below them.
|
||||
const entries = new Set(status.map((f) => stripSlash(f.path)));
|
||||
const folders = [...set].filter((s) => !entries.has(s));
|
||||
return changed.filter((f) => {
|
||||
const picked = status.filter((f) => {
|
||||
const p = stripSlash(f.path);
|
||||
return set.has(p) || folders.some((s) => p.startsWith(s + "/"));
|
||||
if (set.has(p)) return true;
|
||||
for (const s of set) if (p.startsWith(s + "/")) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/** `path` is the root of a repository nested in another one (its submodule / untracked-folder entry there). */
|
||||
export function isNestedRepoEntry(path: string, roots: readonly string[] = useVcs.getState().roots): boolean {
|
||||
const p = stripSlash(path);
|
||||
return roots.includes(p) && roots.some((r) => p.startsWith(r + "/"));
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1945,7 +1945,6 @@
|
||||
"Structure unavailable": "结构不可用",
|
||||
"Subject line length": "主题行长度",
|
||||
"Submit": "提交",
|
||||
"Submodule changes cannot be rolled back here": "子模块的变更无法在此回滚",
|
||||
"Subpixel": "子像素",
|
||||
"Suggested names": "建议的名称",
|
||||
"Super Method": "超方法",
|
||||
@@ -2313,16 +2312,5 @@
|
||||
"Group By": "分组依据",
|
||||
"The search hit its limit; only usages found so far are replaced.": "搜索已达上限,只替换目前找到的用法。",
|
||||
"Review": "审查",
|
||||
"Commit and Push…": "提交并推送…",
|
||||
"Language server": "语言服务器",
|
||||
"Path": "路径",
|
||||
"Missing": "缺失",
|
||||
"Leave empty to use the IDE-installed copy, else the one on PATH.": "留空则使用 IDE 安装的副本,否则使用 PATH 上的版本。",
|
||||
"Installs into the IDE's own tools folder via": "安装到 IDE 自己的工具目录,方式:",
|
||||
"No tool selected": "未选择工具",
|
||||
"Use auto-detected": "使用自动检测",
|
||||
"Custom": "自定义",
|
||||
"On PATH": "PATH 中",
|
||||
"Reinstall": "重新安装",
|
||||
"Auto-detect": "自动检测"
|
||||
"Commit and Push…": "提交并推送…"
|
||||
}
|
||||
@@ -72,35 +72,13 @@
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.sizer {
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
visibility: hidden;
|
||||
}
|
||||
/* Mirrors a List row: inset, padding and gap. */
|
||||
.sizerRow {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin: 0 var(--list-inset, 6px);
|
||||
padding: 0 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.optionLabel {
|
||||
flex: 1 0 auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* The label keeps its width (up to most of the row); a long detail (a path) is cut instead. */
|
||||
.withDetail {
|
||||
max-width: 70%;
|
||||
}
|
||||
.detail {
|
||||
flex: 0 1 auto;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.detail {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.disabled {
|
||||
|
||||
@@ -127,16 +127,6 @@ export function Select<V extends string = string>({
|
||||
className={styles.popup}
|
||||
>
|
||||
<div tabIndex={-1} data-autofocus onKeyDown={onPopupKey} className={styles.popupInner}>
|
||||
{/* Virtualised rows are absolutely positioned; this sizes the popup to the widest label. */}
|
||||
<div aria-hidden className={styles.sizer}>
|
||||
{options.map((o) => (
|
||||
<div key={o.value} className={styles.sizerRow}>
|
||||
<span className={styles.check} />
|
||||
{o.icon && <Icon name={o.icon} size={14} />}
|
||||
<span>{tx(o.label)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<List
|
||||
items={options}
|
||||
getKey={(o) => o.value}
|
||||
@@ -154,12 +144,8 @@ export function Select<V extends string = string>({
|
||||
<>
|
||||
<span className={styles.check}>{o.value === value && <Icon name="check" size={12} />}</span>
|
||||
{o.icon && <Icon name={o.icon} size={14} />}
|
||||
<span className={clsx(styles.optionLabel, o.detail && styles.withDetail)}>{tx(o.label)}</span>
|
||||
{o.detail && (
|
||||
<span className={styles.detail} title={o.detail}>
|
||||
{tx(o.detail)}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.optionLabel}>{tx(o.label)}</span>
|
||||
{o.detail && <span className={styles.detail}>{o.detail}</span>}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
Reference in new issue
Заблокувати користувача