mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-18 16:08:55 +00:00
feat(editor): rainbow brackets for generics and markup tags, with kind switches and 2–5 colours (#3832)
Rainbow brackets get per-kind switches (round, square, curly, and angle brackets and tags) and a palette length of 2–5 colours; defaults are unchanged. Angle brackets are coloured only inside syntax nodes a language definition names under [rainbow-brackets] (type argument/parameter lists for TypeScript/TSX, Java, Rust and C++; tags for HTML, XML, Vue, Svelte and JSX), so comparisons and shifts stay uncoloured. A kind switched off keeps the other brackets' depths. Colour schemes gain --syn-bracket-4/5; indent guides and sticky lines follow the palette length. Closes #3769 Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
This commit is contained in:
co-authored by
bertyhell
parent
e6daffae76
commit
5a0bd7d1fc
@@ -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();
|
||||
|
||||
@@ -1911,6 +1911,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegist
|
||||
framework_files: Vec::new(),
|
||||
formatter: None,
|
||||
scratch_template: None,
|
||||
rainbow_brackets: Default::default(),
|
||||
tree_sitter: None,
|
||||
language_servers: vec![],
|
||||
debugger: Some(ide_language::DebuggerConfig {
|
||||
|
||||
@@ -73,6 +73,21 @@ pub struct LanguageConfig {
|
||||
/// Content of a new scratch file; `$END$` marks where the caret goes.
|
||||
#[serde(default)]
|
||||
pub scratch_template: Option<String>,
|
||||
/// 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<String>,
|
||||
/// Markup tags (`<a>`, `</a>`, `<a/>`); an element's start and end tags pair up.
|
||||
pub tags: Vec<String>,
|
||||
}
|
||||
|
||||
/// An external formatting tool and its language-specific parser.
|
||||
@@ -302,6 +317,10 @@ pub struct LanguageInfo {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub scratch_template: Option<String>,
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 (`<a>`, `</a>`, `<a/>`). 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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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**. |
|
||||
|
||||
@@ -35,7 +35,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
|
||||
在 **设置 › 编辑器 › 配色方案** 中编辑方案:
|
||||
|
||||
- 在树中选择一个元素,修改其前景、背景、粗体、斜体和效果。修改按方案分别保存,**恢复默认值** 可以撤销。
|
||||
- **语言默认值** 中有 **语义高亮**(局部变量和参数按名称分配颜色)和 **彩虹括号**(按嵌套深度为括号着色)。
|
||||
- **语言默认值** 中有 **语义高亮**(局部变量和参数按名称分配颜色)和 **彩虹括号**(按嵌套深度为括号着色)。其下可选择为哪些括号着色,以及深度循环使用几种颜色(2–5)。关闭的括号种类仍计入其他括号的深度。**尖括号和标签** 只在语法树标记的位置为类型实参和类型形参列表以及 HTML、XML 和 JSX 标签着色,比较运算符永远不会被着色;它们计入所包含内容的深度,元素的开始和结束标签占一层,其内容占下一层。
|
||||
- **导入配色方案** 读取从 JetBrains IDE 导出的 IntelliJ 配色方案(`.icls`)。已有同名方案时,可以选择 **覆盖** 或 **保留两个**。**导出配色方案** 把当前方案导出为 `.icls`。
|
||||
|
||||
## IntelliJ 主题
|
||||
|
||||
@@ -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` | 字符串数组 | 标记语言的标签节点(`<a>`、`</a>`、`<a/>`)。元素的开始和结束标签占一层深度,其内容占下一层。 |
|
||||
|
||||
```toml
|
||||
[rainbow-brackets]
|
||||
angle = ["TypeArgList", "TypeParamList"]
|
||||
tags = ["JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"]
|
||||
```
|
||||
|
||||
## `[[language-servers]]`
|
||||
|
||||
每一项启动一个 LSP 服务器。服务器按顺序列出:普通服务器同时运行;`fallback` 服务器只有在排在它前面的服务器都缺失时才运行。
|
||||
|
||||
@@ -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` |
|
||||
|
||||
### 编辑器(编辑器配色方案)
|
||||
|
||||
|
||||
@@ -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` | **显示空白**。 |
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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]]
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -7,6 +7,10 @@ indent = { tab-size = 2, insert-spaces = true }
|
||||
# parses <script> as TypeScript and <style> as CSS, so components get highlighted.
|
||||
ui-mode = "HTML"
|
||||
|
||||
# Rainbow brackets › angle: editor syntax nodes of markup tags, whose `<` `>` pair up.
|
||||
[rainbow-brackets]
|
||||
tags = ["OpenTag", "CloseTag", "SelfClosingTag"]
|
||||
|
||||
[[language-servers]]
|
||||
name = "svelte-language-server"
|
||||
command = "svelteserver"
|
||||
|
||||
@@ -8,6 +8,10 @@ indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "TypeScript"
|
||||
tree-sitter = "typescript"
|
||||
|
||||
# Rainbow brackets › angle: editor syntax nodes whose `<` `>` pair up (never comparisons).
|
||||
[rainbow-brackets]
|
||||
angle = ["TypeArgList", "TypeParamList"]
|
||||
|
||||
[[framework-ui-modes]]
|
||||
ui-mode = "Angular TypeScript"
|
||||
root-markers = ["angular.json", "node_modules/@angular/core"]
|
||||
|
||||
@@ -8,6 +8,11 @@ indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "TSX"
|
||||
tree-sitter = "tsx"
|
||||
|
||||
# Rainbow brackets › angle: editor syntax nodes whose `<` `>` pair up (never comparisons).
|
||||
[rainbow-brackets]
|
||||
angle = ["TypeArgList", "TypeParamList"]
|
||||
tags = ["JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"]
|
||||
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
|
||||
@@ -6,6 +6,10 @@ block-comment = ["<!--", "-->"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "Vue"
|
||||
|
||||
# Rainbow brackets › angle: editor syntax nodes of markup tags, whose `<` `>` pair up.
|
||||
[rainbow-brackets]
|
||||
tags = ["OpenTag", "CloseTag", "SelfClosingTag"]
|
||||
|
||||
[[language-servers]]
|
||||
name = "vue-language-server"
|
||||
command = "vue-language-server"
|
||||
|
||||
@@ -8,6 +8,10 @@ indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "XML"
|
||||
tree-sitter = "xml"
|
||||
|
||||
# Rainbow brackets › angle: editor syntax nodes of markup tags, whose `<` `>` pair up.
|
||||
[rainbow-brackets]
|
||||
tags = ["OpenTag", "CloseTag", "SelfClosingTag"]
|
||||
|
||||
[[language-servers]]
|
||||
name = "lemminx"
|
||||
command = "lemminx"
|
||||
|
||||
@@ -75,6 +75,8 @@
|
||||
"--syn-bracket-1": "#f2d07a",
|
||||
"--syn-bracket-2": "#d7a0e0",
|
||||
"--syn-bracket-3": "#6fc3df",
|
||||
"--syn-bracket-4": "#93d48a",
|
||||
"--syn-bracket-5": "#ef9f7f",
|
||||
|
||||
// Editor
|
||||
"--fg-editor": "#d9dfe8",
|
||||
|
||||
+3
-1
@@ -277,7 +277,7 @@ from `type`, then map:
|
||||
| `--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` |
|
||||
@@ -495,6 +495,8 @@ a token.
|
||||
| `--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)
|
||||
|
||||
|
||||
@@ -5261,6 +5261,10 @@ export type EditorSettings_Deserialize = {
|
||||
docstringFormat?: string,
|
||||
/** Color Scheme › Language Defaults › Rainbow brackets: `()`, `[]`, `{}` coloured by depth. */
|
||||
rainbowBrackets?: boolean,
|
||||
/** The bracket kinds rainbow brackets colour. */
|
||||
rainbowBracketKinds?: RainbowBracketKinds,
|
||||
/** Colours the rainbow bracket depth cycles through (2–5). */
|
||||
rainbowBracketColors?: number,
|
||||
ligatures?: boolean,
|
||||
/** Fallback font for glyphs the main font lacks; empty = none. */
|
||||
fallbackFont?: string,
|
||||
@@ -5315,6 +5319,10 @@ export type EditorSettings_Serialize = {
|
||||
docstringFormat: string,
|
||||
/** Color Scheme › Language Defaults › Rainbow brackets: `()`, `[]`, `{}` coloured by depth. */
|
||||
rainbowBrackets: boolean,
|
||||
/** The bracket kinds rainbow brackets colour. */
|
||||
rainbowBracketKinds: RainbowBracketKinds,
|
||||
/** Colours the rainbow bracket depth cycles through (2–5). */
|
||||
rainbowBracketColors: number,
|
||||
ligatures: boolean,
|
||||
/** Fallback font for glyphs the main font lacks; empty = none. */
|
||||
fallbackFont: string,
|
||||
@@ -7311,6 +7319,8 @@ export type LanguageInfo_Deserialize = {
|
||||
firstLine?: string | null,
|
||||
/** Content of a new scratch file; `$END$` marks where the caret goes. */
|
||||
scratchTemplate?: string | null,
|
||||
/** Syntax nodes whose `<` `>` rainbow brackets colour (Color Scheme › Rainbow brackets). */
|
||||
rainbowBrackets?: RainbowBracketNodes,
|
||||
};
|
||||
|
||||
/** The UI-facing view of a language. */
|
||||
@@ -7332,6 +7342,8 @@ export type LanguageInfo_Serialize = {
|
||||
firstLine?: string | null,
|
||||
/** Content of a new scratch file; `$END$` marks where the caret goes. */
|
||||
scratchTemplate?: string | null,
|
||||
/** Syntax nodes whose `<` `>` rainbow brackets colour (Color Scheme › Rainbow brackets). */
|
||||
rainbowBrackets?: RainbowBracketNodes,
|
||||
};
|
||||
|
||||
export type LanguageServerSettings = LanguageServerSettings_Serialize | LanguageServerSettings_Deserialize;
|
||||
@@ -9506,6 +9518,27 @@ export type PythonSettings = {
|
||||
showInterpreterPaths?: boolean,
|
||||
};
|
||||
|
||||
/** Color Scheme › Language Defaults › Rainbow brackets: which delimiters are coloured. */
|
||||
export type RainbowBracketKinds = {
|
||||
round?: boolean,
|
||||
square?: boolean,
|
||||
curly?: boolean,
|
||||
/** Type argument / parameter delimiters and markup tags, where the syntax tree marks them. */
|
||||
angle?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* `[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.
|
||||
*/
|
||||
export type RainbowBracketNodes = {
|
||||
/** Nodes spanning `<` … `>` whose delimiters pair up: type argument and parameter lists. */
|
||||
angle?: string[],
|
||||
/** Markup tags (`<a>`, `</a>`, `<a/>`); an element's start and end tags pair up. */
|
||||
tags?: string[],
|
||||
};
|
||||
|
||||
/** Half-open range `[start, end)`. */
|
||||
export type Range = {
|
||||
start: Pos,
|
||||
|
||||
@@ -280,7 +280,7 @@ describe("rainbow guides of bracket blocks", () => {
|
||||
const depth = (n: number) => `var(--openidea-guide-${n})`;
|
||||
|
||||
it("takes the bracket colour for a level with a bracket block, the depth colour otherwise", () => {
|
||||
expect(guideVars(4, 4, true, 0, 0, [undefined, 4, undefined])!.images).toBe(
|
||||
expect(guideVars(4, 4, true, 0, 0, [undefined, 1, undefined])!.images).toBe(
|
||||
[bracket(2), depth(2), depth(3)].join(", "),
|
||||
);
|
||||
// Plain guides stay plain; the caret's and the brace guide still win.
|
||||
@@ -339,6 +339,16 @@ describe("rainbow guides of bracket blocks", () => {
|
||||
expect(images(line(v, 3))).toBe([depth(1), depth(2)].join(", "));
|
||||
});
|
||||
|
||||
it("follows the rainbow bracket palette length, also when it changes", () => {
|
||||
const doc = ["x {", " foo(bar(() => {", " body", " }))", "}"].join("\n");
|
||||
const brackets = new Compartment();
|
||||
const v = mount(doc, [brackets.of(rainbowBrackets({ colors: 5 }))], rainbowIndentGuides);
|
||||
// `{` after `x {`, `foo(`, `bar(`: depth 3, the fourth of five colours; of two, the second.
|
||||
expect(images(line(v, 2))).toBe(bracket(4));
|
||||
v.dispatch({ effects: brackets.reconfigure(rainbowBrackets({ colors: 2 })) });
|
||||
expect(images(line(v, 2))).toBe(bracket(2));
|
||||
});
|
||||
|
||||
it("updates after an edit that changes the nesting", () => {
|
||||
const v = mount(SOURCE, [rainbowBrackets()], rainbowIndentGuides);
|
||||
// `for x in y {` becomes `for x in (y) {`: same depth; then wrap the whole body in another block.
|
||||
|
||||
@@ -41,7 +41,8 @@ export const rainbowGuides = Facet.define<boolean, boolean>({ combine: (values)
|
||||
* indentation `levels` deep (in units of `step` columns), or null when it has
|
||||
* no guides; the guide at level `active` takes the selected colour, the one at
|
||||
* level `brace` the matched brace one. With `rainbow`, `brackets[level]` is the
|
||||
* bracket depth of the block a guide belongs to (its bracket colour), if any.
|
||||
* bracket colour of the block a guide belongs to (its depth within the rainbow
|
||||
* bracket palette), if any.
|
||||
* `.cm-openidea-guides` lines and code lens rows turn them into backgrounds (theme.ts).
|
||||
*/
|
||||
export function guideVars(
|
||||
@@ -191,7 +192,7 @@ export function braceGuide(state: EditorState, step: number): Guide | null {
|
||||
const LONG_LINE = 10_000;
|
||||
|
||||
/**
|
||||
* Bracket depth per guide level on each of the lines `first`..`last` (index `n - first`).
|
||||
* Bracket colour (depth within the palette) per guide level on each of the lines `first`..`last` (index `n - first`).
|
||||
* The guide at `level` belongs to the block opened by the nearest line above indented
|
||||
* exactly `level` units (none when the nearest line indented at most that much is indented
|
||||
* less, as for `blockGuide`); its depth is that of the bracket the opening line leaves open
|
||||
@@ -200,7 +201,7 @@ const LONG_LINE = 10_000;
|
||||
*/
|
||||
export function bracketGuideDepths(
|
||||
state: EditorState,
|
||||
scanner: Pick<BracketScanner, "openAt">,
|
||||
scanner: Pick<BracketScanner, "openAt" | "colors">,
|
||||
step: number,
|
||||
first: number,
|
||||
last: number,
|
||||
@@ -238,7 +239,7 @@ export function bracketGuideDepths(
|
||||
const depthOf = new Map<number, number>();
|
||||
lines.forEach((n, i) => {
|
||||
const bracket = open[i];
|
||||
if (bracket && bracket.from >= doc.line(n).from) depthOf.set(n, bracket.depth);
|
||||
if (bracket && bracket.from >= doc.line(n).from) depthOf.set(n, bracket.depth % scanner.colors);
|
||||
});
|
||||
const out: (number | undefined)[][] = [];
|
||||
let current: (number | undefined)[] = [];
|
||||
@@ -334,7 +335,7 @@ export const indentGuides: Extension = [
|
||||
private brackets: BracketCache[] = [];
|
||||
/** Guide variables of each decorated line, by its start: code lens rows above it repeat them. */
|
||||
private lineVars = new Map<number, { images: string; positions: string }>();
|
||||
private bracketsOn: boolean;
|
||||
private scanner: BracketScanner | null;
|
||||
constructor(readonly view: EditorView) {
|
||||
// Inherits the editor font from the scroller, outside the content CodeMirror observes;
|
||||
// the measured width goes on the scroller, where lines and code lens rows pick it up.
|
||||
@@ -344,7 +345,7 @@ export const indentGuides: Extension = [
|
||||
this.probe.textContent = " ".repeat(SPACE_SAMPLE);
|
||||
view.scrollDOM.appendChild(this.probe);
|
||||
const scanner = bracketScanner(view);
|
||||
this.bracketsOn = !!scanner;
|
||||
this.scanner = scanner;
|
||||
this.decorations = build(view, scanner, this.brackets, this.lineVars);
|
||||
this.measure();
|
||||
this.syncLenses();
|
||||
@@ -391,8 +392,10 @@ export const indentGuides: Extension = [
|
||||
update(u: ViewUpdate) {
|
||||
if (u.geometryChanged) this.measure();
|
||||
const scanner = bracketScanner(u.view);
|
||||
const bracketsChanged = !!scanner !== this.bracketsOn;
|
||||
this.bracketsOn = !!scanner;
|
||||
// A new scanner (rainbow brackets toggled or reconfigured) may colour blocks differently.
|
||||
const bracketsChanged = scanner !== this.scanner;
|
||||
if (bracketsChanged) this.brackets.length = 0;
|
||||
this.scanner = scanner;
|
||||
const rainbow = u.state.facet(rainbowGuides);
|
||||
if (
|
||||
u.docChanged ||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import type { BracketSyntax } from "./rainbowBrackets";
|
||||
import { _languageMode, editorsFor } from "@/editor/api";
|
||||
import { JS_TAGS } from "./jsTags";
|
||||
import { docCommentTags } from "./docCommentTags";
|
||||
@@ -43,6 +44,24 @@ export function languageInfo(id: string): LanguageInfo | undefined {
|
||||
return infos?.get(id);
|
||||
}
|
||||
|
||||
let syntaxOf: { infos: Map<string, LanguageInfo> | null; syntax: BracketSyntax } | null = null;
|
||||
|
||||
/**
|
||||
* Rainbow brackets' angle syntax: the `[rainbow-brackets]` node names of every language
|
||||
* definition, so embedded code (TypeScript in Vue, HTML in Markdown) is covered too.
|
||||
*/
|
||||
export function bracketSyntax(): BracketSyntax {
|
||||
if (syntaxOf && syntaxOf.infos === infos) return syntaxOf.syntax;
|
||||
const angle = new Set<string>();
|
||||
const tags = new Set<string>();
|
||||
for (const info of infos?.values() ?? []) {
|
||||
for (const name of info.rainbowBrackets?.angle ?? []) angle.add(name);
|
||||
for (const name of info.rainbowBrackets?.tags ?? []) tags.add(name);
|
||||
}
|
||||
syntaxOf = { infos, syntax: { angle: [...angle].sort(), tags: [...tags].sort() } };
|
||||
return syntaxOf.syntax;
|
||||
}
|
||||
|
||||
/**
|
||||
* The language list changed (a plugin added or removed languages): fetch it
|
||||
* again. Open documents follow through their `docLanguage` events.
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { Compartment, EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { completedSyntaxState } from "@/test/syntax";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import { BracketScanner, bracketClass, rainbowBrackets } from "./rainbowBrackets";
|
||||
import {
|
||||
BracketScanner,
|
||||
DEFAULT_RAINBOW_OPTIONS,
|
||||
bracketClass,
|
||||
rainbowBrackets,
|
||||
type RainbowBracketOptions,
|
||||
} from "./rainbowBrackets";
|
||||
import { heavyExtension } from "./setup";
|
||||
import { _resetLanguages, bracketSyntax, loadLanguageInfos } from "./languages";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import type { EditorSettings } from "@/platform/ipc";
|
||||
|
||||
const cStyle = EditorState.languageData.of(() => [
|
||||
@@ -33,7 +41,7 @@ function rendered(doc: string, extensions: Extension) {
|
||||
describe("rainbow brackets", () => {
|
||||
it("colours brackets by nesting depth, cycling through the palette", () => {
|
||||
expect(marks("f(a[b{c}d]e)")).toEqual(["(0", "[1", "{2", "}2", "]1", ")0"]);
|
||||
expect([0, 1, 2, 3, 4].map(bracketClass)).toEqual([
|
||||
expect([0, 1, 2, 3, 4].map((depth) => bracketClass(depth))).toEqual([
|
||||
"cm-rainbow-bracket-1",
|
||||
"cm-rainbow-bracket-2",
|
||||
"cm-rainbow-bracket-3",
|
||||
@@ -239,3 +247,305 @@ describe("rainbow brackets", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
/** The node names of the bundled language definitions (`languages/*.toml`, `[rainbow-brackets]`). */
|
||||
const SYNTAX = {
|
||||
angle: [
|
||||
"TypeArgList",
|
||||
"TypeParamList",
|
||||
"TypeArguments",
|
||||
"TypeParameters",
|
||||
"TemplateArgumentList",
|
||||
"TemplateParameterList",
|
||||
],
|
||||
tags: ["OpenTag", "CloseTag", "SelfClosingTag", "JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag", "JSXFragmentTag"],
|
||||
};
|
||||
const angleScanner = (options: Partial<RainbowBracketOptions> = {}) =>
|
||||
new BracketScanner({ ...DEFAULT_RAINBOW_OPTIONS, angle: true, syntax: SYNTAX, ...options });
|
||||
|
||||
describe("rainbow brackets: bracket kinds and palette", () => {
|
||||
it("leaves angle brackets alone by default, also with the language's syntax nodes known", async () => {
|
||||
const doc = "let m: Map<string, Array<T>> = f([1]);";
|
||||
const ext = await load("TypeScript");
|
||||
expect(marks(doc, ext, 0, doc.length, new BracketScanner({ ...DEFAULT_RAINBOW_OPTIONS, syntax: SYNTAX }))).toEqual([
|
||||
"(0",
|
||||
"[1",
|
||||
"]1",
|
||||
")0",
|
||||
]);
|
||||
expect(DEFAULT_RAINBOW_OPTIONS).toMatchObject({ round: true, square: true, curly: true, angle: false, colors: 3 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TypeScript", "let m: Map<string, Array<T>> = f(a < b); if (x > 1) y = z >> 1; class A<T extends B<C>> {}"],
|
||||
["Java", "Map<String, List<Integer>> m = new HashMap<>(); boolean b = a < c && d >> 2 > 1;"],
|
||||
["Rust", "let v: Vec<Vec<u8>> = Vec::<u8>::new(); if a < b && c >> 1 > 0 {}"],
|
||||
["C++", "std::vector<std::vector<int>> v; bool b = a < c; int s = x >> 1;"],
|
||||
])("colours %s type argument delimiters, never comparisons or shifts", async (name, doc) => {
|
||||
const got = marks(doc, await load(name), 0, doc.length, angleScanner());
|
||||
const expected = {
|
||||
TypeScript: ["<0", "<1", ">1", ">0", "(0", ")0", "(0", ")0", "<0", "<1", ">1", ">0", "{0", "}0"],
|
||||
Java: ["<0", "<1", ">1", ">0", "<0", ">0", "(0", ")0"],
|
||||
Rust: ["<0", "<1", ">1", ">0", "<0", ">0", "(0", ")0", "{0", "}0"],
|
||||
"C++": ["<0", "<1", ">1", ">0"],
|
||||
}[name];
|
||||
expect(got).toEqual(expected);
|
||||
});
|
||||
|
||||
it("nests the brackets inside type arguments one level deeper", async () => {
|
||||
const doc = "let f: Map<K, (x: V[]) => void> = g();";
|
||||
expect(marks(doc, await load("TypeScript"), 0, doc.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
"(1",
|
||||
"[2",
|
||||
"]2",
|
||||
")1",
|
||||
">0",
|
||||
"(0",
|
||||
")0",
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips angle brackets in strings and comments", async () => {
|
||||
const doc = 'List<String> a; // List<X>\nString s = "<a>"; /* Map<K, V> */';
|
||||
expect(marks(doc, await load("Java"), 0, doc.length, angleScanner())).toEqual(["<0", ">0"]);
|
||||
});
|
||||
|
||||
it("colours markup tags by element depth, with void and self-closing elements on their own", async () => {
|
||||
const html = '<div class="("><br><p>x</p><img src=a /></div>';
|
||||
expect(marks(html, await load("HTML"), 0, html.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
">0",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<0",
|
||||
">0",
|
||||
]);
|
||||
const xml = '<a x="1"><b/><c>t</c></a>';
|
||||
expect(marks(xml, await load("XML"), 0, xml.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
">0",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<0",
|
||||
">0",
|
||||
]);
|
||||
// Implied end tags (`<li>`) leave the element on one level with its siblings.
|
||||
const list = "<ul><li>a<li>b</ul>";
|
||||
expect(marks(list, await load("HTML"), 0, list.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
">0",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<0",
|
||||
">0",
|
||||
]);
|
||||
});
|
||||
|
||||
it("colours JSX tags and fragments, with embedded code a level deeper, but not comparisons in it", async () => {
|
||||
const doc = "const x = <div a={f(b < c)}>{g()}<br/><>t</></div>;";
|
||||
expect(marks(doc, await load("JSX"), 0, doc.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
"{1",
|
||||
"(2",
|
||||
")2",
|
||||
"}1",
|
||||
">0",
|
||||
"{1",
|
||||
"(2",
|
||||
")2",
|
||||
"}1",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<1",
|
||||
">1",
|
||||
"<0",
|
||||
">0",
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks unterminated tags and type arguments as unmatched and keeps the depth after them", async () => {
|
||||
const html = "<div><span></div><p>x</p";
|
||||
expect(marks(html, await load("HTML"), 0, html.length, angleScanner())).toEqual([
|
||||
"<0",
|
||||
">0",
|
||||
"<1",
|
||||
">1",
|
||||
"<0",
|
||||
">0",
|
||||
"<0",
|
||||
">0",
|
||||
"<!",
|
||||
]);
|
||||
const ts = "let x: Array<string = 1; f()";
|
||||
expect(marks(ts, await load("TypeScript"), 0, ts.length, angleScanner())).toEqual(["<!", "(0", ")0"]);
|
||||
});
|
||||
|
||||
it("colours tags and type arguments of embedded code (TypeScript in Vue)", async () => {
|
||||
const doc = '<template><div :a="b < c"><Comp/></div></template><script lang="ts">let x: Array<T>;</script>';
|
||||
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 = `<main>\n${"<p>text (</p>\n".repeat(800)}<section><b>x</b></section>\n</main>`;
|
||||
const ext = await load("HTML");
|
||||
const from = doc.indexOf("<section>");
|
||||
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 + "<section>".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<number[]> = [];",
|
||||
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<string, unknown>) => {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,24 +1,63 @@
|
||||
/**
|
||||
* Rainbow brackets (VS Code's bracket pair colorization): `()`, `[]`, `{}`
|
||||
* coloured by nesting depth (`--syn-bracket-<n>`, 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-<n>`, 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<typeof syntaxTree>;
|
||||
type NodeType = Tree["type"];
|
||||
|
||||
/** Number of `--syn-bracket-<n>` colours the depth cycles through. */
|
||||
export const BRACKET_COLORS = 3;
|
||||
/** Number of `--syn-bracket-<n>` 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 (`<a>`, `</a>`, `<a/>`); 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<number, number> = { 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 `<br>`, 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) === "</" &&
|
||||
charAt(doc, last.to - 1) === ">"
|
||||
)
|
||||
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<string, number> | null = null;
|
||||
private readonly angleKinds = new WeakMap<NodeType, number>();
|
||||
|
||||
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<number>();
|
||||
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<string, Decoration>();
|
||||
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<RainbowBracketOptions, RainbowBracketOptions>({
|
||||
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<RainbowBracketOptions> = {}): 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 })];
|
||||
}
|
||||
|
||||
@@ -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 }) : [],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<number, number>({
|
||||
@@ -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);
|
||||
|
||||
@@ -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 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "用于配色方案中所有以粗体显示文本的地方",
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user