diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index bcda10560..8653c7073 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -915,6 +915,10 @@ pub struct EditorSettings { pub docstring_format: String, /// Color Scheme › Language Defaults › Rainbow brackets: `()`, `[]`, `{}` coloured by depth. pub rainbow_brackets: bool, + /// The bracket kinds rainbow brackets colour. + pub rainbow_bracket_kinds: RainbowBracketKinds, + /// Colours the rainbow bracket depth cycles through (2–5). + pub rainbow_bracket_colors: u32, pub ligatures: bool, /// Fallback font for glyphs the main font lacks; empty = none. pub fallback_font: String, @@ -959,6 +963,8 @@ impl Default for EditorSettings { semantic_highlighting: false, docstring_format: "rest".into(), rainbow_brackets: false, + rainbow_bracket_kinds: RainbowBracketKinds::default(), + rainbow_bracket_colors: 3, ligatures: false, fallback_font: String::new(), font_weight: 400, @@ -982,6 +988,23 @@ impl Default for EditorSettings { } } +/// Color Scheme › Language Defaults › Rainbow brackets: which delimiters are coloured. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct RainbowBracketKinds { + pub round: bool, + pub square: bool, + pub curly: bool, + /// Type argument / parameter delimiters and markup tags, where the syntax tree marks them. + pub angle: bool, +} + +impl Default for RainbowBracketKinds { + fn default() -> Self { + Self { round: true, square: true, curly: true, angle: false } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct FileSettings { @@ -1774,6 +1797,29 @@ mod tests { } } + #[test] + fn rainbow_bracket_options_default_and_round_trip() { + let old: Settings = serde_json::from_str(r#"{"editor":{"rainbowBrackets":true}}"#).unwrap(); + assert!(old.editor.rainbow_brackets); + assert_eq!(old.editor.rainbow_bracket_kinds, RainbowBracketKinds::default()); + assert_eq!(old.editor.rainbow_bracket_colors, 3); + let defaults = Settings::default().editor; + assert!(!defaults.rainbow_brackets); + let kinds = defaults.rainbow_bracket_kinds; + assert!(kinds.round && kinds.square && kinds.curly && !kinds.angle); + + let mut settings = Settings::default(); + settings.editor.rainbow_bracket_kinds = + RainbowBracketKinds { round: false, square: true, curly: true, angle: true }; + settings.editor.rainbow_bracket_colors = 5; + let json = serde_json::to_value(&settings).unwrap(); + assert_eq!(json["editor"]["rainbowBracketKinds"]["angle"], true); + assert_eq!(json["editor"]["rainbowBracketColors"], 5); + let restored: Settings = serde_json::from_value(json).unwrap(); + assert_eq!(restored.editor.rainbow_bracket_kinds, settings.editor.rainbow_bracket_kinds); + assert_eq!(restored.editor.rainbow_bracket_colors, 5); + } + #[test] fn docstring_format_defaults_and_round_trips() { let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap(); diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index fa6baf64a..6010b949d 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -1911,6 +1911,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc, + /// Syntax nodes of the editor's grammar whose `<` `>` rainbow brackets colour. + #[serde(default)] + pub rainbow_brackets: RainbowBracketNodes, +} + +/// `[rainbow-brackets]` of a language definition: node names of its editor (Lezer) +/// grammar, so angle brackets are coloured only where the syntax tree says they +/// delimit something, never in comparisons or shifts. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default)] +pub struct RainbowBracketNodes { + /// Nodes spanning `<` … `>` whose delimiters pair up: type argument and parameter lists. + pub angle: Vec, + /// Markup tags (``, ``, ``); an element's start and end tags pair up. + pub tags: Vec, } /// An external formatting tool and its language-specific parser. @@ -302,6 +317,10 @@ pub struct LanguageInfo { #[serde(default)] #[specta(optional)] pub scratch_template: Option, + /// Syntax nodes whose `<` `>` rainbow brackets colour (Color Scheme › Rainbow brackets). + #[serde(default)] + #[specta(optional)] + pub rainbow_brackets: RainbowBracketNodes, } impl From<&LanguageConfig> for LanguageInfo { @@ -319,6 +338,7 @@ impl From<&LanguageConfig> for LanguageInfo { filenames: c.filenames.clone(), first_line: c.first_line.clone(), scratch_template: c.scratch_template.clone(), + rainbow_brackets: c.rainbow_brackets.clone(), } } } diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 16fc54e49..82f42fb29 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -667,6 +667,20 @@ mod tests { assert_eq!(rust.language_servers[0].name, "rust-analyzer"); } + #[test] + fn rainbow_bracket_nodes_reach_the_ui() { + let reg = reg(); + let tsx = reg.get(&LanguageId::new("typescriptreact")).unwrap(); + assert_eq!(tsx.rainbow_brackets.angle, ["TypeArgList", "TypeParamList"]); + assert!(tsx.rainbow_brackets.tags.iter().any(|t| t == "JSXOpenTag")); + let info = crate::LanguageInfo::from(®.get(&LanguageId::new("html")).unwrap()); + assert_eq!(info.rainbow_brackets.tags, ["OpenTag", "CloseTag", "SelfClosingTag"]); + let json = serde_json::to_value(&info).unwrap(); + assert_eq!(json["rainbowBrackets"]["tags"][0], "OpenTag"); + // Definitions without the table, as most are, get none. + assert_eq!(reg.get(&LanguageId::new("python")).unwrap().rainbow_brackets, Default::default()); + } + #[test] fn alternative_servers_are_fallbacks() { let reg = reg(); diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 6807cdc45..c5aee23ea 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -324,6 +324,7 @@ fn harness_languages(languages: &[MockLanguage<'_>], adjust: impl Fn(&mut Langua framework_files: Vec::new(), formatter: None, scratch_template: None, + rainbow_brackets: Default::default(), tree_sitter: None, language_servers: servers .iter() diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index 893b49c8d..a9f148437 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -58,6 +58,7 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig { framework_files: Vec::new(), formatter: None, scratch_template: None, + rainbow_brackets: Default::default(), tree_sitter: None, language_servers: vec![server], debugger: None, diff --git a/docs/en/guide/themes.mdx b/docs/en/guide/themes.mdx index 6f53d0751..5e57627e7 100644 --- a/docs/en/guide/themes.mdx +++ b/docs/en/guide/themes.mdx @@ -35,7 +35,7 @@ The editor's syntax colours come from a color scheme. In **Settings › Appearan **Settings › Editor › Color Scheme** edits schemes: - Select an element in the tree and change its foreground, background, bold, italic and effects. Changes are stored per scheme; **Restore Defaults** drops them. -- **Language Defaults** has **Semantic highlighting** (local variables and parameters get a colour derived from their name) and **Rainbow brackets** (brackets coloured by depth). +- **Language Defaults** has **Semantic highlighting** (local variables and parameters get a colour derived from their name) and **Rainbow brackets** (brackets coloured by depth). Below it, choose which kinds are coloured and how many colours (2–5) the depth cycles through. A kind switched off keeps counting toward the depth of the others. **Angle brackets and tags** colours type argument and parameter lists and HTML, XML and JSX tags only where the syntax tree marks them, never comparisons; they count toward the depth of what they enclose, with an element's start and end tags at one level and its content at the next. - **Import Scheme** reads an IntelliJ color scheme (`.icls`) exported from a JetBrains IDE. If a scheme with the same name exists, choose **Overwrite** or **Keep Both**. **Export Scheme** writes the selected scheme as `.icls`. ## IntelliJ themes diff --git a/docs/en/languages/adding.mdx b/docs/en/languages/adding.mdx index 096b3e3e0..7916979f6 100644 --- a/docs/en/languages/adding.mdx +++ b/docs/en/languages/adding.mdx @@ -66,6 +66,7 @@ All keys are kebab-case. Only `id` and `name` are required; a definition with no | `debugger` | table | Debug adapter; see below. | | `formatter` | table | External formatter; see below. | | `scratch-template` | string | Content of a new scratch file of this language. `$END$` marks where the caret goes. | +| `rainbow-brackets` | table | Syntax nodes whose angle brackets rainbow brackets colour; see below. | Bundled tree-sitter grammars: `bash`, `c`, `cmake`, `cpp`, `csharp`, `css`, `dart`, `elixir`, `gdscript`, `go`, `graphql`, `haskell`, `hcl`, `html`, `java`, `javascript`, `json`, `kotlin`, `lua`, `make`, `markdown`, `nix`, `ocaml`, `ocaml_interface`, `php`, `prisma`, `proto`, `python`, `ruby`, `rust`, `scala`, `swift`, `toml`, `tsx`, `typescript`, `xml`, `yaml`, `zig`. A new grammar has to be compiled into the IDE; a plugin can provide highlighting and structure for a language without a grammar instead (see [Language features](/en/plugins/guides/language-features)). @@ -84,6 +85,21 @@ ui-mode = "Angular Template" root-markers = ["angular.json", "node_modules/@angular/core"] ``` +### `[rainbow-brackets]` + +With **Angle brackets and tags** on (Color Scheme › Language Defaults › Rainbow brackets), the editor colours `<` and `>` only inside the nodes named here, so comparisons and shifts are never coloured. The names are node names of the `ui-mode` grammar. The names of every language apply in every editor, so embedded code (TypeScript in a Vue file, HTML in Markdown) is covered too. + +| Field | Type | Description | +| ------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | +| `angle` | string array | Nodes that start with `<` and end with `>`, such as type argument and parameter lists. Their `<` and `>` pair up like brackets. | +| `tags` | string array | Markup tag nodes (``, ``, ``). An element's start and end tags take one depth, and its content the next. | + +```toml +[rainbow-brackets] +angle = ["TypeArgList", "TypeParamList"] +tags = ["JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"] +``` + ## `[[language-servers]]` Each entry starts one LSP server. Servers are listed in order; all regular servers run side by side, and a `fallback` server runs only while every server listed before it is missing. diff --git a/docs/en/plugins/guides/themes.mdx b/docs/en/plugins/guides/themes.mdx index 9bb09a2b8..fef39524b 100644 --- a/docs/en/plugins/guides/themes.mdx +++ b/docs/en/plugins/guides/themes.mdx @@ -283,7 +283,7 @@ by hand: | `--fg-whitespace` | `editorWhitespace.foreground` | | `--bg-text-search-result`, `--bg-text-search-result-current` | `editor.findMatchHighlightBackground`, `editor.findMatchBackground` | | `--bg-matched-brace` | `editorBracketMatch.background` | -| `--syn-bracket-1` … `--syn-bracket-3` (Rainbow brackets) | `editorBracketHighlight.foreground1` … `foreground3` | +| `--syn-bracket-1` … `--syn-bracket-5` (Rainbow brackets) | `editorBracketHighlight.foreground1` … `foreground5` | | `--bg-identifier-under-caret`, `-write` | `editor.wordHighlightBackground`, `editor.wordHighlightStrongBackground` | | `--wave-error`, `--wave-warning` | `editorError.foreground`, `editorWarning.foreground` | | `--gutter-modified`, `--gutter-added`, `--gutter-deleted` | `editorGutter.modifiedBackground`, `.addedBackground`, `.deletedBackground` | @@ -488,6 +488,8 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme | `--syn-bracket-1` | `#e8c25b` | `#0431fa` | | `--syn-bracket-2` | `#d78bd6` | `#319331` | | `--syn-bracket-3` | `#4ea7f0` | `#7b3814` | +| `--syn-bracket-4` | `#6fc28b` | `#a3157f` | +| `--syn-bracket-5` | `#e5906f` | `#00737d` | ### Editor (editor scheme) diff --git a/docs/en/reference/settings.mdx b/docs/en/reference/settings.mdx index ea47c4b55..7c5adb3e3 100644 --- a/docs/en/reference/settings.mdx +++ b/docs/en/reference/settings.mdx @@ -128,6 +128,8 @@ Settings › Appearance & Behavior › Appearance, unless noted. | `colorScheme` | `"theme-default"` | Editor color scheme; `theme-default` follows the UI theme, otherwise a theme id or an imported scheme. | | `semanticHighlighting` | `false` | **Semantic highlighting** (Color Scheme › Language Defaults). | | `rainbowBrackets` | `false` | **Rainbow brackets** (Color Scheme › Language Defaults). | +| `rainbowBracketKinds` | all but `angle` | Brackets it colours: `round`, `square`, `curly`, and `angle` (type arguments and markup tags). | +| `rainbowBracketColors` | `3` | Colours the bracket depth cycles through (2–5). | | `tabSize` / `insertSpaces` | `4` / `true` | Default tab size, and whether indentation uses spaces. | | `softWrap` | `true` | Soft-wrap the files matching `general.softWrapFiles` (`*.md; *.txt; *.rst; *.adoc` by default). | | `showWhitespace` | `false` | **Show whitespaces**. | diff --git a/docs/zh/guide/themes.mdx b/docs/zh/guide/themes.mdx index f704f585a..2ec7e51a2 100644 --- a/docs/zh/guide/themes.mdx +++ b/docs/zh/guide/themes.mdx @@ -35,7 +35,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主 在 **设置 › 编辑器 › 配色方案** 中编辑方案: - 在树中选择一个元素,修改其前景、背景、粗体、斜体和效果。修改按方案分别保存,**恢复默认值** 可以撤销。 -- **语言默认值** 中有 **语义高亮**(局部变量和参数按名称分配颜色)和 **彩虹括号**(按嵌套深度为括号着色)。 +- **语言默认值** 中有 **语义高亮**(局部变量和参数按名称分配颜色)和 **彩虹括号**(按嵌套深度为括号着色)。其下可选择为哪些括号着色,以及深度循环使用几种颜色(2–5)。关闭的括号种类仍计入其他括号的深度。**尖括号和标签** 只在语法树标记的位置为类型实参和类型形参列表以及 HTML、XML 和 JSX 标签着色,比较运算符永远不会被着色;它们计入所包含内容的深度,元素的开始和结束标签占一层,其内容占下一层。 - **导入配色方案** 读取从 JetBrains IDE 导出的 IntelliJ 配色方案(`.icls`)。已有同名方案时,可以选择 **覆盖** 或 **保留两个**。**导出配色方案** 把当前方案导出为 `.icls`。 ## IntelliJ 主题 diff --git a/docs/zh/languages/adding.mdx b/docs/zh/languages/adding.mdx index 0b22b6507..700a0073a 100644 --- a/docs/zh/languages/adding.mdx +++ b/docs/zh/languages/adding.mdx @@ -66,6 +66,7 @@ install-hint = "Install CodeLLDB in Settings › Languages & Frameworks › Lang | `debugger` | 表 | 调试适配器,见下文。 | | `formatter` | 表 | 外部格式化工具,见下文。 | | `scratch-template` | 字符串 | 新建该语言草稿文件时的内容,`$END$` 表示光标位置。 | +| `rainbow-brackets` | 表 | 彩虹括号为其尖括号着色的语法节点,见下文。 | 内置的 tree-sitter 语法:`bash`、`c`、`cmake`、`cpp`、`csharp`、`css`、`dart`、`elixir`、`gdscript`、`go`、`graphql`、`haskell`、`hcl`、`html`、`java`、`javascript`、`json`、`kotlin`、`lua`、`make`、`markdown`、`nix`、`ocaml`、`ocaml_interface`、`php`、`prisma`、`proto`、`python`、`ruby`、`rust`、`scala`、`swift`、`toml`、`tsx`、`typescript`、`xml`、`yaml`、`zig`。新的语法需要编译进 IDE;没有语法的语言可以改由插件提供高亮和结构(见 [语言功能](/zh/plugins/guides/language-features))。 @@ -84,6 +85,21 @@ ui-mode = "Angular Template" root-markers = ["angular.json", "node_modules/@angular/core"] ``` +### `[rainbow-brackets]` + +打开**尖括号和标签**(配色方案 › 语言默认值 › 彩虹括号)后,编辑器只为这里列出的节点中的 `<` 和 `>` 着色,比较运算符和移位运算符永远不会被着色。名称是 `ui-mode` 语法中的节点名。所有语言的名称在每个编辑器中都生效,因此嵌入的代码(Vue 文件中的 TypeScript、Markdown 中的 HTML)也能着色。 + +| 字段 | 类型 | 说明 | +| ------- | ---------- | ---------------------------------------------------------------------------------------------- | +| `angle` | 字符串数组 | 以 `<` 开头、以 `>` 结尾的节点,例如类型实参和类型形参列表。它们的 `<` 和 `>` 像括号一样配对。 | +| `tags` | 字符串数组 | 标记语言的标签节点(``、``、``)。元素的开始和结束标签占一层深度,其内容占下一层。 | + +```toml +[rainbow-brackets] +angle = ["TypeArgList", "TypeParamList"] +tags = ["JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"] +``` + ## `[[language-servers]]` 每一项启动一个 LSP 服务器。服务器按顺序列出:普通服务器同时运行;`fallback` 服务器只有在排在它前面的服务器都缺失时才运行。 diff --git a/docs/zh/plugins/guides/themes.mdx b/docs/zh/plugins/guides/themes.mdx index 8b72d1da3..5cd00d574 100644 --- a/docs/zh/plugins/guides/themes.mdx +++ b/docs/zh/plugins/guides/themes.mdx @@ -254,7 +254,7 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light` | `--fg-whitespace` | `editorWhitespace.foreground` | | `--bg-text-search-result`, `--bg-text-search-result-current` | `editor.findMatchHighlightBackground`, `editor.findMatchBackground` | | `--bg-matched-brace` | `editorBracketMatch.background` | -| `--syn-bracket-1` … `--syn-bracket-3`(彩虹括号) | `editorBracketHighlight.foreground1` … `foreground3` | +| `--syn-bracket-1` … `--syn-bracket-5`(彩虹括号) | `editorBracketHighlight.foreground1` … `foreground5` | | `--bg-identifier-under-caret`, `-write` | `editor.wordHighlightBackground`, `editor.wordHighlightStrongBackground` | | `--wave-error`, `--wave-warning` | `editorError.foreground`, `editorWarning.foreground` | | `--gutter-modified`, `--gutter-added`, `--gutter-deleted` | `editorGutter.modifiedBackground`, `.addedBackground`, `.deletedBackground` | @@ -454,6 +454,8 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light` | `--syn-bracket-1` | `#e8c25b` | `#0431fa` | | `--syn-bracket-2` | `#d78bd6` | `#319331` | | `--syn-bracket-3` | `#4ea7f0` | `#7b3814` | +| `--syn-bracket-4` | `#6fc28b` | `#a3157f` | +| `--syn-bracket-5` | `#e5906f` | `#00737d` | ### 编辑器(编辑器配色方案) diff --git a/docs/zh/reference/settings.mdx b/docs/zh/reference/settings.mdx index 6ff007552..06d25b13b 100644 --- a/docs/zh/reference/settings.mdx +++ b/docs/zh/reference/settings.mdx @@ -128,6 +128,8 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | `colorScheme` | `"theme-default"` | 编辑器配色方案;`theme-default` 跟随界面主题,也可以是主题 id 或导入的方案。 | | `semanticHighlighting` | `false` | **语义高亮**(配色方案 › 语言默认值)。 | | `rainbowBrackets` | `false` | **彩虹括号**(配色方案 › 语言默认值)。 | +| `rainbowBracketKinds` | 除 `angle` 外全部 | 着色的括号:`round`、`square`、`curly` 和 `angle`(类型实参和标记语言标签)。 | +| `rainbowBracketColors` | `3` | 括号深度循环使用的颜色数(2–5)。 | | `tabSize` / `insertSpaces` | `4` / `true` | 默认制表符宽度,以及是否用空格缩进。 | | `softWrap` | `true` | 对匹配 `general.softWrapFiles` 的文件软换行(默认 `*.md; *.txt; *.rst; *.adoc`)。 | | `showWhitespace` | `false` | **显示空白**。 | diff --git a/languages/cpp.toml b/languages/cpp.toml index 8a51a9961..ca179f3f4 100644 --- a/languages/cpp.toml +++ b/languages/cpp.toml @@ -15,6 +15,10 @@ int main() { } ''' +# Rainbow brackets › angle: editor syntax nodes whose `<` `>` pair up (never comparisons). +[rainbow-brackets] +angle = ["TemplateArgumentList", "TemplateParameterList"] + [[language-servers]] name = "clangd" command = "clangd" diff --git a/languages/html.toml b/languages/html.toml index 77c71c20e..1b62c4238 100644 --- a/languages/html.toml +++ b/languages/html.toml @@ -8,6 +8,10 @@ indent = { tab-size = 2, insert-spaces = true } ui-mode = "HTML" tree-sitter = "html" +# Rainbow brackets › angle: editor syntax nodes of markup tags, whose `<` `>` pair up. +[rainbow-brackets] +tags = ["OpenTag", "CloseTag", "SelfClosingTag"] + # Angular projects: component templates, with bindings and interpolations # highlighted as expressions. [[framework-ui-modes]] diff --git a/languages/java.toml b/languages/java.toml index e88e28e60..080a7f453 100644 --- a/languages/java.toml +++ b/languages/java.toml @@ -14,6 +14,10 @@ class Scratch { } ''' +# Rainbow brackets › angle: editor syntax nodes whose `<` `>` pair up (never comparisons). +[rainbow-brackets] +angle = ["TypeArguments", "TypeParameters"] + # Microsoft java-debug runs inside jdtls as a bundle (`initializationOptions.bundles`, # added when installed); sessions start with `vscode.java.startDebugSession` and the # client connects to the returned port (`debugServer`). diff --git a/languages/javascriptreact.toml b/languages/javascriptreact.toml index 13f2ff0cd..8de15025b 100644 --- a/languages/javascriptreact.toml +++ b/languages/javascriptreact.toml @@ -8,6 +8,10 @@ indent = { tab-size = 2, insert-spaces = true } ui-mode = "JSX" tree-sitter = "javascript" +# Rainbow brackets › angle: editor syntax nodes of markup tags, whose `<` `>` pair up. +[rainbow-brackets] +tags = ["JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"] + [[language-servers]] name = "vtsls" tsserver-project = true diff --git a/languages/rust.toml b/languages/rust.toml index 766651082..41e315d6f 100644 --- a/languages/rust.toml +++ b/languages/rust.toml @@ -12,6 +12,10 @@ fn main() { } ''' +# Rainbow brackets › angle: editor syntax nodes whose `<` `>` pair up (never comparisons). +[rainbow-brackets] +angle = ["TypeArgList", "TypeParamList"] + [[language-servers]] name = "rust-analyzer" command = "rust-analyzer" diff --git a/languages/svelte.toml b/languages/svelte.toml index 9dfab158f..7e5741448 100644 --- a/languages/svelte.toml +++ b/languages/svelte.toml @@ -7,6 +7,10 @@ indent = { tab-size = 2, insert-spaces = true } # parses '; + expect(marks(doc, await load("Vue"), 0, doc.length, angleScanner())).toEqual([ + "<0", + ">0", + "<1", + ">1", + "<2", + ">2", + "<1", + ">1", + "<0", + ">0", + "<0", + ">0", + "<1", + ">1", + "<0", + ">0", + ]); + }); + + it("keeps tag depth across chunks and in a viewport far into the document", async () => { + const doc = `
\n${"

text (

\n".repeat(800)}
x
\n
`; + const ext = await load("HTML"); + const from = doc.indexOf("
"); + expect(marks(doc, ext, from, doc.length, angleScanner())).toEqual([ + "<1", + ">1", + "<2", + ">2", + "<2", + ">2", + "<1", + ">1", + "<0", + ">0", + ]); + const state = completedSyntaxState(EditorState.create({ doc, extensions: ext })); + const open = angleScanner().openAt(state, [from + "
".length]); + expect(open.map((m) => m && `${doc[m.from]}${m.depth}@${m.from}`)).toEqual([`<1@${from}`]); + }); + + it("leaves the depth of other brackets stable when a kind is switched off", () => { + const scanner = new BracketScanner({ ...DEFAULT_RAINBOW_OPTIONS, round: false }); + expect(marks("f(a[b{c(d)}e])", [], 0, 14, scanner)).toEqual(["[1", "{2", "}2", "]1"]); + expect(marks("x) [y]", [], 0, 6, new BracketScanner({ ...DEFAULT_RAINBOW_OPTIONS, round: false }))).toEqual([ + "[0", + "]0", + ]); + // A block opened by an uncoloured kind gives indent guides no bracket colour. + const state = EditorState.create({ doc: "f(\n [x" }); + expect(scanner.openAt(state, [2, state.doc.length]).map((m) => m && m.depth)).toEqual([null, 1]); + }); + + it("cycles through the chosen number of colours", () => { + expect([0, 1, 2, 3, 4, 5].map((d) => bracketClass(d, 5))).toEqual([ + "cm-rainbow-bracket-1", + "cm-rainbow-bracket-2", + "cm-rainbow-bracket-3", + "cm-rainbow-bracket-4", + "cm-rainbow-bracket-5", + "cm-rainbow-bracket-1", + ]); + expect([0, 1, 2].map((d) => bracketClass(d, 2))).toEqual([ + "cm-rainbow-bracket-1", + "cm-rainbow-bracket-2", + "cm-rainbow-bracket-1", + ]); + // Out of range palette lengths are clamped to 2–5. + expect(bracketClass(5, 9)).toBe("cm-rainbow-bracket-1"); + expect(bracketClass(1, 1)).toBe("cm-rainbow-bracket-2"); + expect(rendered("((((()))))", [cStyle, rainbowBrackets({ colors: 4 })])).toEqual([ + "(1", + "(2", + "(3", + "(4", + "(1", + ")1", + ")4", + ")3", + ")2", + ")1", + ]); + }); + + it("updates an open editor when the options change", async () => { + const options = new Compartment(); + const view = new EditorView({ + state: EditorState.create({ + doc: "let a: Array = [];", + extensions: [await load("TypeScript"), options.of(rainbowBrackets())], + }), + parent: document.body, + }); + const classes = () => + [...view.contentDOM.querySelectorAll("[class*=cm-rainbow-bracket]")].map( + (e) => `${e.textContent}${e.className.replace("cm-rainbow-bracket-", "")}`, + ); + expect(classes()).toEqual(["[1", "]1", "[1", "]1"]); + view.dispatch({ + effects: options.reconfigure(rainbowBrackets({ angle: true, square: false, colors: 2, syntax: SYNTAX })), + }); + expect(classes()).toEqual(["<1", ">1"]); + view.destroy(); + }); + + it("is configured by the bracket kind and colour settings", () => { + const render = (editor: Record) => { + const view = new EditorView({ + state: EditorState.create({ + doc: "f(a[b{c}])", + extensions: [cStyle, heavyExtension(10, { rainbowBrackets: true, ...editor } as unknown as EditorSettings)], + }), + parent: document.body, + }); + const classes = [...view.contentDOM.querySelectorAll("[class*=cm-rainbow-bracket]")].map( + (e) => `${e.textContent}${e.className.replace("cm-rainbow-bracket-", "")}`, + ); + view.destroy(); + return classes; + }; + expect(render({})).toEqual(["(1", "[2", "{3", "}3", "]2", ")1"]); + expect( + render({ rainbowBracketKinds: { round: false, square: true, curly: true }, rainbowBracketColors: 2 }), + ).toEqual(["[2", "{1", "}1", "]2"]); + }); + + it("takes the angle syntax of every language definition", async () => { + _resetLanguages(); + const info = (id: string, rainbowBrackets?: LanguageInfo["rainbowBrackets"]) => + ({ + id, + name: id, + extensions: [], + uiMode: null, + lineComment: null, + blockComment: null, + indent: null, + rainbowBrackets, + }) as LanguageInfo; + await loadLanguageInfos({ + languages: async () => [ + info("typescript", { angle: ["TypeArgList", "TypeParamList"], tags: [] }), + info("typescriptreact", { angle: ["TypeArgList"], tags: ["JSXOpenTag"] }), + info("html", { angle: [], tags: ["OpenTag"] }), + info("python"), + ], + } as unknown as DocBackend); + expect(bracketSyntax()).toEqual({ angle: ["TypeArgList", "TypeParamList"], tags: ["JSXOpenTag", "OpenTag"] }); + expect(bracketSyntax()).toBe(bracketSyntax()); + _resetLanguages(); + }); +}); diff --git a/src/editor/core/cm/rainbowBrackets.ts b/src/editor/core/cm/rainbowBrackets.ts index b8d40b255..fc4ab38dc 100644 --- a/src/editor/core/cm/rainbowBrackets.ts +++ b/src/editor/core/cm/rainbowBrackets.ts @@ -1,24 +1,63 @@ /** * Rainbow brackets (VS Code's bracket pair colorization): `()`, `[]`, `{}` - * coloured by nesting depth (`--syn-bracket-`, cycling), unmatched ones in - * the error colour. Strings, comments and markup literals are skipped: with - * the syntax tree when the language has one, else lexically with the - * language's comment tokens and quotes. Interpolated expressions stay - * visible as holes inside those literals. + * coloured by nesting depth (`--syn-bracket-`, cycling through the first + * 2–5 colours), unmatched ones in the error colour. Strings, comments and markup + * literals are skipped: with the syntax tree when the language has one, else + * lexically with the language's comment tokens and quotes. Interpolated + * expressions stay visible as holes inside those literals. + * + * A kind switched off is still tracked, so the other brackets keep their depth; + * it is only left uncoloured. The angle kind is the exception: off, `<` and `>` + * are not brackets at all. On, the `<` `>` of the syntax nodes the language + * definitions name (`[rainbow-brackets]`: type argument / parameter lists, markup + * tags) pair up and count toward the depth of what they enclose; an element's + * start and end tags take one depth and its content the next. Comparisons and + * shifts are never coloured, being no such node. * * Only the viewport is decorated. The nesting state at its start comes from * checkpoints saved every few KB while scanning, so scrolling and typing * rescan from the nearest checkpoint before the change, not from the top. */ -import { Prec, type EditorState, type Extension, type Text } from "@codemirror/state"; +import { Facet, Prec, type EditorState, type Extension, type Text } from "@codemirror/state"; import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from "@codemirror/view"; import { syntaxTree } from "@codemirror/language"; +import type { SyntaxNodeRef } from "@lezer/common"; type Tree = ReturnType; type NodeType = Tree["type"]; -/** Number of `--syn-bracket-` colours the depth cycles through. */ -export const BRACKET_COLORS = 3; +/** Number of `--syn-bracket-` colours a colour scheme defines. */ +export const BRACKET_COLORS = 5; +/** Colours the depth cycles through by default. */ +export const DEFAULT_BRACKET_COLORS = 3; + +/** Syntax nodes whose `<` `>` the angle kind colours, from the language definitions. */ +export interface BracketSyntax { + /** Nodes spanning `<` … `>` whose delimiters pair up: type argument and parameter lists. */ + angle: readonly string[]; + /** Markup tags (``, ``, ``); an element's start and end tags pair up. */ + tags: readonly string[]; +} + +/** Settings › Editor › Color Scheme › Language Defaults › Rainbow brackets. */ +export interface RainbowBracketOptions { + round: boolean; + square: boolean; + curly: boolean; + angle: boolean; + /** Colours the depth cycles through (2–5). */ + colors: number; + syntax: BracketSyntax; +} + +export const DEFAULT_RAINBOW_OPTIONS: RainbowBracketOptions = { + round: true, + square: true, + curly: true, + angle: false, + colors: DEFAULT_BRACKET_COLORS, + syntax: { angle: [], tags: [] }, +}; const CHUNK = 4096; /** How far past the viewport to look for the closers of visible openers. */ @@ -28,9 +67,27 @@ const TOKEN_SLACK = 8; /** Closer char code of each opener char code: `(` `[` `{`. */ const CLOSER: Record = { 40: 41, 91: 93, 123: 125 }; +/** + * `closer` of an angle bracket or tag delimiter (`>`), of an element whose end tag is still + * to come, and of an end tag without its element (its `>` is unmatched too). + */ +const GT = 62; +const ELEMENT = -1; +const LONE_GT = -2; + +/** Angle events at a `<` / `>` the syntax tree marks: opens, closes, ends a start tag, starts an end tag, or `<` never closed. */ +const OPEN = 0; +const CLOSE = 1; +const START_TAG_END = 2; +const END_TAG = 3; +const LONE = 4; +/** Node kinds of the angle syntax. */ +const ANGLE_NODE = 1; +const TAG_NODE = 2; /** An open bracket; the stack is a persistent list so checkpoints can share it. */ interface Opener { + /** Closer char code; `GT` / `LONE_GT` for `<`, `ELEMENT` for an element between its tags. */ closer: number; pos: number; depth: number; @@ -68,8 +125,52 @@ function skipsNode(type: NodeType): boolean { return v; } -/** Literal ranges, with holes for interpolated code (which may contain more literals). */ -function literalRanges(tree: Tree, from: number, to: number): number[] { +/** Collects angle events (offset from `from`, event, element start) while `literalRanges` walks the tree. */ +interface AngleEvents { + doc: Text; + kindOf: (type: NodeType) => number; + out: number[]; +} + +function charAt(doc: Text, pos: number): string { + return pos >= 0 && pos < doc.length ? doc.sliceString(pos, pos + 1) : ""; +} + +/** Angle events of node `n` (of angle kind `kind`) at its start, or at its end with `atEnd`. */ +function angleEvents(a: AngleEvents, n: SyntaxNodeRef, kind: number, from: number, to: number, atEnd: boolean) { + const { doc, out } = a; + if (n.to - n.from < 2 || charAt(doc, n.from) !== "<") return; + const closed = charAt(doc, n.to - 1) === ">"; + const endTag = kind === TAG_NODE && charAt(doc, n.from + 1) === "/"; + const pos = atEnd ? n.to - 1 : n.from; + if (pos < from || pos >= to || (atEnd && !closed)) return; + if (!atEnd) { + if (!closed) out.push(pos - from, LONE, 0); + else if (endTag) out.push(pos - from, END_TAG, n.node.parent?.from ?? -1); + else out.push(pos - from, OPEN, 0); + return; + } + let event = CLOSE; + if (kind === TAG_NODE && !endTag && charAt(doc, n.to - 2) !== "/") { + // A start tag opens its element only when the element has a whole end tag (not `
`, nor an implied end). + const last = n.node.parent?.lastChild; + if ( + last && + last.from > n.from && + a.kindOf(last.type) === TAG_NODE && + doc.sliceString(last.from, last.from + 2) === "" + ) + event = START_TAG_END; + } + out.push(pos - from, event, 0); +} + +/** + * Literal ranges, with holes for interpolated code (which may contain more literals); with + * `angles`, also the angle events in `[from, to)`. + */ +function literalRanges(tree: Tree, from: number, to: number, angles?: AngleEvents): number[] { const ranges: number[] = []; const parents: boolean[] = []; let skipping = false; @@ -87,8 +188,14 @@ function literalRanges(tree: Tree, from: number, to: number): number[] { parents.push(skipping); if (skipsNode(n.type)) setSkipping(true, n.from); else if (INTERPOLATION_NODE.test(n.name)) setSkipping(false, n.from); + const kind = angles ? angles.kindOf(n.type) : 0; + if (kind) angleEvents(angles!, n, kind, from, to, false); + }, + leave: (n) => { + setSkipping(parents.pop()!, n.to); + const kind = angles ? angles.kindOf(n.type) : 0; + if (kind) angleEvents(angles!, n, kind, from, to, true); }, - leave: (n) => setSkipping(parents.pop()!, n.to), }); return ranges; } @@ -100,6 +207,34 @@ function literalRanges(tree: Tree, from: number, to: number): number[] { export class BracketScanner { private checkpoints: ScanState[] = []; private tree: Tree | null = null; + /** Whether brackets with each closer char code are coloured (1). */ + private readonly shown = new Uint8Array(128); + /** Angle node kind of each node name, or null while the angle kind is off. */ + private readonly angleNames: Map | null = null; + private readonly angleKinds = new WeakMap(); + + constructor(readonly options: RainbowBracketOptions = DEFAULT_RAINBOW_OPTIONS) { + this.shown[41] = +options.round; + this.shown[93] = +options.square; + this.shown[125] = +options.curly; + this.shown[GT] = +options.angle; + if (options.angle && (options.syntax.angle.length || options.syntax.tags.length)) { + this.angleNames = new Map(); + for (const name of options.syntax.angle) this.angleNames.set(name, ANGLE_NODE); + for (const name of options.syntax.tags) this.angleNames.set(name, TAG_NODE); + } + } + + /** Colours the depth cycles through. */ + get colors(): number { + return clampColors(this.options.colors); + } + + private readonly kindOf = (type: NodeType): number => { + let kind = this.angleKinds.get(type); + if (kind === undefined) this.angleKinds.set(type, (kind = this.angleNames!.get(type.name) ?? 0)); + return kind; + }; /** Forget checkpoints after `pos` (first changed position of the old document). */ invalidate(pos: number) { @@ -141,7 +276,9 @@ export class BracketScanner { const cp = this.start(pos); if (!s || s.pos > pos || cp.pos > s.pos) s = cp; this.scan(doc, tree, comments, s, pos, () => {}); - out.push(s.stack ? { from: s.stack.pos, depth: s.stack.depth } : null); + const top = s.stack; + const shown = top && (top.closer === ELEMENT || this.shown[top.closer]); + out.push(shown ? { from: top.pos, depth: top.depth } : null); } return out; } @@ -169,7 +306,7 @@ export class BracketScanner { open = s.stack; if (s.pos >= doc.length && (open?.depth ?? -1) >= shallowest) { const unmatched = new Set(); - for (let o = open; o && o.depth >= shallowest; o = o.prev) unmatched.add(o.pos); + for (let o = open; o && o.depth >= shallowest; o = o.prev) if (o.closer !== ELEMENT) unmatched.add(o.pos); for (const m of out) if (unmatched.has(m.from)) m.depth = -1; } } @@ -205,14 +342,19 @@ export class BracketScanner { untilBelow = -1, ) { const cps = this.checkpoints; + const shown = this.shown; const lineFirst = comments.line ? comments.line.charCodeAt(0) : -1; const blockFirst = comments.block ? comments.block.open.charCodeAt(0) : -1; + const angles: AngleEvents | undefined = tree && this.angleNames ? { doc, kindOf: this.kindOf, out: [] } : undefined; while (s.pos < end) { const chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK); const base = s.pos; const text = doc.sliceString(base, Math.min(doc.length, chunkEnd + TOKEN_SLACK)); const stop = chunkEnd - base; - const skips = tree ? literalRanges(tree, base, chunkEnd) : []; + if (angles) angles.out.length = 0; + const skips = tree ? literalRanges(tree, base, chunkEnd, angles) : []; + const events = angles?.out ?? []; + let e = 0; let k = 0; let i = 0; while (i < stop) { @@ -235,18 +377,28 @@ export class BracketScanner { } } if (ch === 40 || ch === 91 || ch === 123) { + const closer = CLOSER[ch]!; const depth = s.stack ? s.stack.depth + 1 : 0; - visit(base + i, depth); - s.stack = { closer: CLOSER[ch]!, pos: base + i, depth, prev: s.stack }; + if (shown[closer]) visit(base + i, depth); + s.stack = { closer, pos: base + i, depth, prev: s.stack }; } else if (ch === 41 || ch === 93 || ch === 125) { if (s.stack && s.stack.closer === ch) { - visit(base + i, s.stack.depth); + if (shown[ch]) visit(base + i, s.stack.depth); s.stack = s.stack.prev; if ((s.stack?.depth ?? -1) < untilBelow) { s.pos = base + i + 1; return; } - } else visit(base + i, -1); + } else if (shown[ch]) visit(base + i, -1); + } else if ((ch === 60 || ch === 62) && e < events.length) { + while (e < events.length && events[e]! < i) e += 3; + if (events[e] === i) { + angleStep(s, base + i, events[e + 1]!, events[e + 2]!, visit); + if ((s.stack?.depth ?? -1) < untilBelow) { + s.pos = base + i + 1; + return; + } + } } i++; } @@ -257,6 +409,40 @@ export class BracketScanner { } } +/** Applies the angle event `event` at `pos` (a `<` or `>`) to the stack. */ +function angleStep( + s: ScanState, + pos: number, + event: number, + elementFrom: number, + visit: (pos: number, depth: number) => void, +) { + const top = s.stack; + if (event === OPEN) { + const depth = top ? top.depth + 1 : 0; + visit(pos, depth); + s.stack = { closer: GT, pos, depth, prev: top }; + } else if (event === LONE) visit(pos, -1); + else if (event === END_TAG) { + // The element's entry, past anything left open inside it; the end tag takes its depth. + let o = top; + while (o && !(o.closer === ELEMENT && o.pos === elementFrom)) o = o.prev; + if (!o) { + visit(pos, -1); + s.stack = { closer: LONE_GT, pos, depth: top ? top.depth + 1 : 0, prev: top }; + } else { + visit(pos, o.depth); + s.stack = { closer: GT, pos, depth: o.depth, prev: o.prev }; + } + } else if (top && top.closer === GT) { + visit(pos, top.depth); + s.stack = event === START_TAG_END ? { closer: ELEMENT, pos: top.pos, depth: top.depth, prev: top.prev } : top.prev; + } else { + visit(pos, -1); + if (top && top.closer === LONE_GT) s.stack = top.prev; + } +} + /** The syntax tree when the editor has a language, else null (lexical scanning). */ function treeOf(state: EditorState): Tree | null { const tree = syntaxTree(state); @@ -310,14 +496,19 @@ function lexSkip(text: string, i: number, stop: number, s: ScanState, c: Comment return i; } -/** Class of a bracket at `depth` (-1: unmatched); the palette repeats every `BRACKET_COLORS` levels. */ -export function bracketClass(depth: number): string { - return depth < 0 ? "cm-rainbow-bracket-unmatched" : `cm-rainbow-bracket-${(depth % BRACKET_COLORS) + 1}`; +/** A palette length within 2–`BRACKET_COLORS`. */ +function clampColors(colors: number): number { + return Number.isFinite(colors) ? Math.min(BRACKET_COLORS, Math.max(2, Math.round(colors))) : DEFAULT_BRACKET_COLORS; +} + +/** Class of a bracket at `depth` (-1: unmatched); the palette repeats every `colors` levels. */ +export function bracketClass(depth: number, colors = DEFAULT_BRACKET_COLORS): string { + return depth < 0 ? "cm-rainbow-bracket-unmatched" : `cm-rainbow-bracket-${(depth % clampColors(colors)) + 1}`; } const markCache = new Map(); -function markFor(depth: number): Decoration { - const cls = bracketClass(depth); +function markFor(depth: number, colors: number): Decoration { + const cls = bracketClass(depth, colors); let m = markCache.get(cls); if (!m) markCache.set(cls, (m = Decoration.mark({ class: cls }))); return m; @@ -325,26 +516,46 @@ function markFor(depth: number): Decoration { function build(view: EditorView, scanner: BracketScanner): DecorationSet { const { from, to } = view.viewport; + const colors = scanner.colors; return Decoration.set( - scanner.marks(view.state, from, to).map((m) => markFor(m.depth).range(m.from, m.from + 1)), + scanner.marks(view.state, from, to).map((m) => markFor(m.depth, colors).range(m.from, m.from + 1)), true, ); } +const sameNames = (a: readonly string[], b: readonly string[]) => + a.length === b.length && a.every((x, i) => x === b[i]); + +const optionsFacet = Facet.define({ + combine: (values) => values[0] ?? DEFAULT_RAINBOW_OPTIONS, + compare: (a, b) => + a.round === b.round && + a.square === b.square && + a.curly === b.curly && + a.angle === b.angle && + a.colors === b.colors && + sameNames(a.syntax.angle, b.syntax.angle) && + sameNames(a.syntax.tags, b.syntax.tags), +}); + const plugin = ViewPlugin.fromClass( class { - scanner = new BracketScanner(); + scanner: BracketScanner; decorations: DecorationSet; constructor(view: EditorView) { + this.scanner = new BracketScanner(view.state.facet(optionsFacet)); this.decorations = build(view, this.scanner); } update(u: ViewUpdate) { - if (u.docChanged) { + const options = u.state.facet(optionsFacet); + const reconfigured = options !== u.startState.facet(optionsFacet); + if (reconfigured) this.scanner = new BracketScanner(options); + else if (u.docChanged) { let first = Infinity; u.changes.iterChangedRanges((fromA) => (first = Math.min(first, fromA))); this.scanner.invalidate(first); } - if (u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state)) + if (reconfigured || u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state)) this.decorations = build(u.view, this.scanner); } }, @@ -360,7 +571,7 @@ export function bracketScanner(view: EditorView): BracketScanner | null { } /** Rainbow brackets for one editor (Settings › Editor › Color Scheme › Rainbow brackets). */ -export function rainbowBrackets(): Extension { +export function rainbowBrackets(options: Partial = {}): Extension { // Above the syntax highlighter so the bracket colour is the innermost span. - return Prec.high(plugin); + return [Prec.high(plugin), optionsFacet.of({ ...DEFAULT_RAINBOW_OPTIONS, ...options })]; } diff --git a/src/editor/core/cm/setup.ts b/src/editor/core/cm/setup.ts index 6a72fe4e4..0cd6768f6 100644 --- a/src/editor/core/cm/setup.ts +++ b/src/editor/core/cm/setup.ts @@ -45,7 +45,7 @@ import { codeLensExtension } from "./codeLens"; import { iconAreaExtension } from "./iconArea"; import { renderedDocsExtension } from "./renderedDocs"; import { caretExtension, fontZoom, methodLinesField, prefsExtension, softWrapActive } from "./prefs"; -import { commentTokens } from "./languages"; +import { bracketSyntax, commentTokens } from "./languages"; import { multiCaretMouse } from "./multiCaret"; import { columnModeExtension } from "./columnMode"; import { bracketBlockSelect } from "./bracketBlockSelect"; @@ -240,7 +240,9 @@ export function heavyExtension(docLength: number, settings?: EditorSettings): Ex return [ prefs.codeEditing.highlightBraces ? bracketMatching({ renderMatch }) : [], prefs.appearance.indentGuides ? (prefs.appearance.rainbowIndentGuides ? rainbowIndentGuides : indentGuides) : [], - prefs.rainbowBrackets ? rainbowBrackets() : [], + prefs.rainbowBrackets + ? rainbowBrackets({ ...prefs.rainbowBracketKinds, colors: prefs.rainbowBracketColors, syntax: bracketSyntax() }) + : [], prefs.codeEditing.highlightSelection ? highlightSelectionMatches({ minSelectionLength: 2, maxMatches: 500 }) : [], ]; } diff --git a/src/editor/core/cm/stickyScroll.test.ts b/src/editor/core/cm/stickyScroll.test.ts index a6e32f260..f3b1244de 100644 --- a/src/editor/core/cm/stickyScroll.test.ts +++ b/src/editor/core/cm/stickyScroll.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { EditorState } from "@codemirror/state"; import { languages } from "@codemirror/language-data"; import { completedSyntaxState } from "@/test/syntax"; -import { BracketScanner } from "./rainbowBrackets"; +import { BracketScanner, DEFAULT_RAINBOW_OPTIONS } from "./rainbowBrackets"; import { renderLineContent, selectedSpans } from "./stickyScroll"; describe("selectedSpans", () => { @@ -64,6 +64,14 @@ describe("sticky line content", () => { expect(brackets(render(state, 2, false))).toEqual([]); }); + it("follows the rainbow bracket palette length", () => { + const state = EditorState.create({ doc: "a(b(c(d(e())))) {" }); + const el = document.createElement("span"); + const scanner = new BracketScanner({ ...DEFAULT_RAINBOW_OPTIONS, colors: 4 }); + renderLineContent(state, 1, el, scanner.marks(state, 0, state.doc.length), scanner.colors); + expect(brackets(el).slice(0, 6)).toEqual(["(1", "(2", "(3", "(4", "(1", ")1"]); + }); + it("wraps the token's highlight inside the bracket colour, as the editor does", async () => { const js = await languages.find((l) => l.name === "JavaScript")!.load(); const state = completedSyntaxState( diff --git a/src/editor/core/cm/stickyScroll.ts b/src/editor/core/cm/stickyScroll.ts index 3d62b7b98..50398cc38 100644 --- a/src/editor/core/cm/stickyScroll.ts +++ b/src/editor/core/cm/stickyScroll.ts @@ -12,7 +12,7 @@ import { highlightTree } from "@lezer/highlight"; import { backendFolds } from "./folding"; import { openideaHighlightStyle } from "./highlight"; import { LINE_INSET } from "./lineInset"; -import { bracketClass, bracketScanner, type BracketMark } from "./rainbowBrackets"; +import { bracketClass, bracketScanner, DEFAULT_BRACKET_COLORS, type BracketMark } from "./rainbowBrackets"; /** Maximum number of sticky lines (Settings › Editor › Code Editing). */ export const stickyMaxLines = Facet.define({ @@ -64,6 +64,7 @@ export function renderLineContent( lineNo: number, target: HTMLElement, brackets: readonly BracketMark[] = [], + colors = DEFAULT_BRACKET_COLORS, ) { const line = state.doc.line(lineNo); const text = line.text.length > MAX_TEXT ? line.text.slice(0, MAX_TEXT) : line.text; @@ -90,7 +91,7 @@ export function renderLineContent( } if (bracket.from > pos) target.appendChild(node(bracket.from, cls)); const wrap = document.createElement("span"); - wrap.className = bracketClass(bracket.depth); + wrap.className = bracketClass(bracket.depth, colors); wrap.appendChild(node(bracket.from + 1, cls)); target.appendChild(wrap); } @@ -170,7 +171,7 @@ class StickyScroll { * Text and syntax tree the rows were rendered from (re-render when either changes), and * the document while bracket colours are on (an edit above may change their depth). */ - private renderedFrom: { texts: string[]; tree: unknown; doc: unknown } | null = null; + private renderedFrom: { texts: string[]; tree: unknown; doc: unknown; scanner: unknown } | null = null; private gutterWidth = 0; private numberLeft = 0; private scheduled = false; @@ -253,6 +254,7 @@ class StickyScroll { !!prev && prev.tree === tree && prev.doc === (scanner ? state.doc : null) && + prev.scanner === scanner && texts.every((t, i) => t === prev.texts[i]); if (!lines.length) { this.dom.style.display = "none"; @@ -264,7 +266,7 @@ class StickyScroll { const rebuild = !same || gutterWidth !== this.gutterWidth || numberLeft !== this.numberLeft; if (rebuild) { this.lines = lines; - this.renderedFrom = { texts, tree, doc: scanner ? state.doc : null }; + this.renderedFrom = { texts, tree, doc: scanner ? state.doc : null, scanner }; this.gutterWidth = gutterWidth; this.numberLeft = numberLeft; const frag = document.createDocumentFragment(); @@ -290,6 +292,7 @@ class StickyScroll { n, inner, scanner?.marks(state, line.from, line.from + Math.min(MAX_TEXT, line.length)), + scanner?.colors, ); text.appendChild(inner); row.append(num, text); diff --git a/src/features/settings/pages/editor/colorScheme.tsx b/src/features/settings/pages/editor/colorScheme.tsx index 2b4f86a18..b051e221f 100644 --- a/src/features/settings/pages/editor/colorScheme.tsx +++ b/src/features/settings/pages/editor/colorScheme.tsx @@ -1758,6 +1758,18 @@ export const COLOR_SCHEME_PAGES: PageSpec[] = [ key: "editor.rainbowBrackets", label: "Rainbow brackets", hint: "Color (), [] and {} by nesting depth; unmatched brackets use the error color.", + children: [ + { t: "check", key: "editor.rainbowBracketKinds.round", label: "Round brackets ( )" }, + { t: "check", key: "editor.rainbowBracketKinds.square", label: "Square brackets [ ]" }, + { t: "check", key: "editor.rainbowBracketKinds.curly", label: "Curly braces { }" }, + { + t: "check", + key: "editor.rainbowBracketKinds.angle", + label: "Angle brackets and tags < >", + hint: "Type arguments and parameters, and HTML, XML and JSX tags, where the syntax tree marks them; comparisons stay uncolored. They count toward the depth of what they enclose: an element's tags take one level, its content the next.", + }, + { t: "number", key: "editor.rainbowBracketColors", label: "Number of colors", min: 2, max: 5 }, + ], }, ], }, diff --git a/src/platform/clientSettings.ts b/src/platform/clientSettings.ts index 370b888ca..0eaed127c 100644 --- a/src/platform/clientSettings.ts +++ b/src/platform/clientSettings.ts @@ -31,6 +31,8 @@ export const CLIENT_SETTINGS_KEYS = [ "editor.semanticHighlighting", "editor.docstringFormat", "editor.rainbowBrackets", + "editor.rainbowBracketKinds", + "editor.rainbowBracketColors", "editor.softWrap", "editor.showWhitespace", "editor.inlayHints", diff --git a/src/platform/colorScheme.ts b/src/platform/colorScheme.ts index b3c0116fd..730b567e4 100644 --- a/src/platform/colorScheme.ts +++ b/src/platform/colorScheme.ts @@ -313,7 +313,7 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [ syn("markupTag", "Markup › Tag", [LD], "tag"), syn("markupAttribute", "Markup › Attribute", [LD], "attribute"), ...[1, 2, 3, 4, 5].map((n) => syn(`semantic${n}`, `Semantic highlighting › Color ${n}`, [LD], `rainbow-${n}`)), - ...[1, 2, 3].map((n) => syn(`bracket${n}`, `Rainbow brackets › Level ${n}`, [LD], `bracket-${n}`)), + ...[1, 2, 3, 4, 5].map((n) => syn(`bracket${n}`, `Rainbow brackets › Level ${n}`, [LD], `bracket-${n}`)), // Python's tree mirrors PyCharm's colour page (PythonColorsPage.java): every key the editor can // restyle, in the page's order. Language-scoped like java.*: shared-token attributes reuse the diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts index 3e9969f4e..4c43e51a7 100644 --- a/src/platform/editorSettings.ts +++ b/src/platform/editorSettings.ts @@ -78,6 +78,10 @@ export const EDITOR_EXTRA_DEFAULTS = { docstringFormat: "rest" as DocstringFormat, /** Color Scheme › Language Defaults › Rainbow brackets. */ rainbowBrackets: false, + /** The bracket kinds rainbow brackets colour; angle: generics and markup tags. */ + rainbowBracketKinds: { round: true, square: true, curly: true, angle: false }, + /** Colours the rainbow bracket depth cycles through (2–5). */ + rainbowBracketColors: 3, ligatures: false, fallbackFont: "", /** Typography Settings › Main / Bold font weight (CSS weights, IDEA's Regular / Bold). */ @@ -271,6 +275,7 @@ export function validateEditorExtras(raw: unknown): EditorExtras { if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest"; for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const) if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top"; + out.rainbowBracketColors = Math.min(5, Math.max(2, Math.round(out.rainbowBracketColors))); out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight); out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight); return out; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index a92329983..b62a9a1f3 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1232,6 +1232,12 @@ "Fork": "Fork", "Fork Conversation from Here": "Fork Conversation from Here", "Rainbow indent guides": "Rainbow indent guides", + "Round brackets ( )": "Round brackets ( )", + "Square brackets [ ]": "Square brackets [ ]", + "Curly braces { }": "Curly braces { }", + "Angle brackets and tags < >": "Angle brackets and tags < >", + "Type arguments and parameters, and HTML, XML and JSX tags, where the syntax tree marks them; comparisons stay uncolored. They count toward the depth of what they enclose: an element's tags take one level, its content the next.": "Type arguments and parameters, and HTML, XML and JSX tags, where the syntax tree marks them; comparisons stay uncolored. They count toward the depth of what they enclose: an element's tags take one level, its content the next.", + "Number of colors": "Number of colors", "Color picker": "Color picker", "HEX": "HEX", "Red": "Red", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 5bee2dfa4..9052d3766 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -4538,6 +4538,12 @@ "Local variables and parameters get a colour derived from their name (needs a language server).": "局部变量和参数使用根据其名称生成的颜色(需要语言服务器)。", "Rainbow brackets": "彩虹括号", "Color (), [] and {} by nesting depth; unmatched brackets use the error color.": "按嵌套深度为 ()、[] 和 {} 着色;不匹配的括号使用错误颜色。", + "Round brackets ( )": "圆括号 ( )", + "Square brackets [ ]": "方括号 [ ]", + "Curly braces { }": "花括号 { }", + "Angle brackets and tags < >": "尖括号和标签 < >", + "Type arguments and parameters, and HTML, XML and JSX tags, where the syntax tree marks them; comparisons stay uncolored. They count toward the depth of what they enclose: an element's tags take one level, its content the next.": "语法树标记的类型实参和类型形参,以及 HTML、XML 和 JSX 标签;比较运算符不着色。它们计入所包含内容的深度:元素的标签占一层,其内容占下一层。", + "Number of colors": "颜色数", "Main font weight": "主字重", "Bold font weight": "粗体字重", "Used wherever the color scheme shows text in bold": "用于配色方案中所有以粗体显示文本的地方", diff --git a/src/styles/tokens.css b/src/styles/tokens.css index acf1f01ac..3a98d1f8c 100644 --- a/src/styles/tokens.css +++ b/src/styles/tokens.css @@ -185,6 +185,8 @@ html { --syn-bracket-1: #e8c25b; --syn-bracket-2: #d78bd6; --syn-bracket-3: #4ea7f0; + --syn-bracket-4: #6fc28b; + --syn-bracket-5: #e5906f; /* editor (scheme colours) */ --fg-editor: #bcbec4; @@ -641,6 +643,8 @@ html { --syn-bracket-1: #0431fa; --syn-bracket-2: #319331; --syn-bracket-3: #7b3814; + --syn-bracket-4: #a3157f; + --syn-bracket-5: #00737d; /* editor */ --fg-editor: #080808; @@ -939,6 +943,8 @@ html { --syn-bracket-1: #ffd700; --syn-bracket-2: #ee90ee; --syn-bracket-3: #87cefa; + --syn-bracket-4: #8fef8f; + --syn-bracket-5: #ffa07a; --fg-editor: #e3e4e8; --caret: #ffffff; @@ -1326,6 +1332,8 @@ html { --syn-bracket-1: var(--palette-yellow); --syn-bracket-2: var(--palette-magenta); --syn-bracket-3: var(--palette-blue); + --syn-bracket-4: var(--palette-green); + --syn-bracket-5: var(--palette-orange); --ansi-black: var(--palette-ansi-black); --ansi-bright-black: var(--palette-ansi-bright-black); --ansi-red: var(--palette-ansi-red);