Visual Studio Code扩展的文档高亮器并不总是触发。

huangapple go评论60阅读模式
英文:

Visual Studio Code extension's document highlighter not always firing

问题

我的自定义VS Code扩展的文档高亮事件 registerDocumentHighlightProvider 不会在某些字符上触发,比如: [, ], {, }。然而,它会在其他字符如 A-Z 上触发。有没有一种方法可以触发所有字符的文档高亮?

入门 示例出发,我使用了以下TypeScript代码进行测试(完整的程序):

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World from HelloWorld!');
    });

    let docSelector: vscode.DocumentSelector = { scheme: 'file', language: 'json' };
    let highlight: Highlighter = new Highlighter();
    context.subscriptions.push(
        vscode.languages.registerDocumentHighlightProvider(docSelector, highlight),
        disposable
    );
}

export class Highlighter implements vscode.DocumentHighlightProvider {
    provideDocumentHighlights(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) {
        // 高亮光标处的单个字符
        let range = new vscode.Range(position.line, position.character, position.line, position.character + 1);
        let highlight = new vscode.DocumentHighlight(range, vscode.DocumentHighlightKind.Write);
        return [highlight];
    }
}

export function deactivate() {}

在VS Code中调试扩展时,我测试了以下JSON文件:

{
  "test": "[`${SOMEFUNC(param1)} etc.]",
}

当光标位于字符 [, ], {, }, ) 上时,provideDocumentHighlights 中的断点不会触发,但对于 A-Z 字符会触发断点。

英文:

My custom VS Code extension's document highlight event registerDocumentHighlightProvider doesn't fire on certain characters like: [, ], {, }. However it does fire for other characters like A-Z. Is there a way to fire document highlighting for all characters?

Working off the Getting Started example, I tested with this TypeScript code (my complete program):

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
	let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
		vscode.window.showInformationMessage('Hello World from HelloWorld!');
	});
	
	let docSelector: vscode.DocumentSelector = { scheme: 'file', language: 'json' };
	let highlight: Highlighter = new Highlighter();
	context.subscriptions.push(
		vscode.languages.registerDocumentHighlightProvider(docSelector, highlight),
		disposable
	);
}

export class Highlighter implements vscode.DocumentHighlightProvider {
    provideDocumentHighlights(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) {
		// highlight single character at cursor 
		let range = new vscode.Range(position.line, position.character, position.line, position.character + 1);
		let highlight = new vscode.DocumentHighlight(range, vscode.DocumentHighlightKind.Write);
		return [ highlight ];
    }
}

export function deactivate() {}

Debugging the extension in VS Code, I tested with this JSON file:

{
  "test": "[`${SOMEFUNC(param1)} etc.`]",
}

A breakpoint in provideDocumentHighlights would not fire when the cursor was on characters: [, ], {, }, ), but would hit breakpoints on A-Z characters.

答案1

得分: 0

我放弃了使用 registerDocumentHighlightProvider 的方法。相反,我通过语法高亮的注入语法和嵌套语言,以及语言配置实现了匹配括号的高亮显示。以下是我完整的解决方案,以便其他人也能找到帮助。

./src/extension.ts - 从主程序中删除了 registerDocumentHighlightProvider

import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
	let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
		vscode.window.showInformationMessage('Hello World from HelloWorld!');
	});
	context.subscriptions.push(disposable);
}
export function deactivate() {}

./package.json - 在 contributes 部分添加了语言和语法:

{
  "contributes": {
    "languages": [
      {
        "id": "customscript",
        "extensions": [ ".customscript" ],
        "configuration": "./customscript.language-configuration.json"
      }
    ],
    "grammars": [
      {
        "language": "customscript",
        "scopeName": "source.customscript",
        "path": "./syntaxes/customscript.tmLanguage.json"
      },
      {
        "scopeName": "customscript-json.injection",
        "path": "./syntaxes/injection.json",
        "injectTo": [ "source.json"],
        "embeddedLanguages": {
          "meta.embedded.customscript.expression": "customscript"
        }
      }
    ]
  }
}

./customscript.language-configuration.json - 添加配置文件以使 VS Code 匹配括号:

{
	"brackets": [
		["{", "}"],
		["[", "]"],
		["(", ")"]
	],
	"autoClosingPairs": [
		{ "open": "{", "close": "}" },
		{ "open": "[", "close": "]" },
		{ "open": "(", "close": ")" }
	],
	"surroundingPairs": [
		["{", "}"],
		["[", "]"],
		["(", ")"]
	]
}

./syntaxes/customscript.tmLanguage.json - 为我的自定义脚本语言添加语法文件:

{
  "scopeName": "source.customscript",
  "patterns": [{ "include": "#expression" }],
  "repository": {
    "expression": {
      "begin": "\\[",
      "beginCaptures": { "0": { "name": "punctuation.expression.open.customscript" } },
      "end": "\\]",
      "endCaptures": { "0": { "name": "punctuation.expression.close.customscript" } },
      "name": "meta.embedded.customscript.expression"
    }
  }
}

./syntaxes/injection.json - 添加注入文件,将自定义脚本和 JSON 链接在一起:

{
  "scopeName": "customscript-json.injection",
  "injectionSelector": "L:string.quoted.double.json",
  "patterns": [ { "include": "source.customscript" } ]
}

package.jsoncustomscript.tmLanguage.json 共享嵌套范围 meta.embedded.customscript.expression,这有助于使一切正常工作。在 VS Code 调试器中运行的结果以及在问题中提到的 test.json 如下图所示:
Visual Studio Code扩展的文档高亮器并不总是触发。

英文:

I discarded the registerDocumentHighlightProvider approach. Instead, I got matching parenthesis highlighting working using Syntax Highlighting's injection grammar and embedded languages, as well as Language Configuration. Here's my full solution in case others find it helpful.

./src/extension.ts - removed registerDocumentHighlightProvider from my main program:

import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
	let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
		vscode.window.showInformationMessage('Hello World from HelloWorld!');
	});
	context.subscriptions.push(disposable);
}
export function deactivate() {}

./package.json - added languages and grammars to contributes section

{
  "contributes": {
    "languages": [
      {
        "id": "customscript",
        "extensions": [ ".customscript" ],
        "configuration": "./customscript.language-configuration.json"
      }
    ],
    "grammars": [
      {
        "language": "customscript",
        "scopeName": "source.customscript",
        "path": "./syntaxes/customscript.tmLanguage.json"
      },
      {
        "scopeName": "customscript-json.injection",
        "path": "./syntaxes/injection.json",
        "injectTo": [ "source.json"],
        "embeddedLanguages": {
          "meta.embedded.customscript.expression": "customscript"
        }
      }
    ]
  }
}

./customscript.language-configuration.json - added configuration file so VS Code matches parenthesis

{
	"brackets": [
		["{", "}"],
		["[", "]"],
		["(", ")"]
	],
	"autoClosingPairs": [
		{ "open": "{", "close": "}" },
		{ "open": "[", "close": "]" },
		{ "open": "(", "close": ")" }
	],
	"surroundingPairs": [
		["{", "}"],
		["[", "]"],
		["(", ")"]
	]
}

./syntaxes/customscript.tmLanguage.json - added grammar file for my custom script language

{
  "scopeName": "source.customscript",
  "patterns": [{ "include": "#expression" }],
  "repository": {
    "expression": {
      "begin": "\\[",
      "beginCaptures": { "0": { "name": "punctuation.expression.open.customscript" } },
      "end": "\\]",
      "endCaptures": { "0": { "name": "punctuation.expression.close.customscript" } },
      "name": "meta.embedded.customscript.expression"
    }
  }
}

./syntaxes/injection.json - added injection file that links together the custom script and json

{
  "scopeName": "customscript-json.injection",
  "injectionSelector": "L:string.quoted.double.json",
  "patterns": [ { "include": "source.customscript" } ]
}

The package.json and the customscript.tmLanguage.json share the embedded scope meta.embedded.customscript.expression which helped make everything work. Here's the result running in VS Code debugger and with test.json mentioned in the question:
Visual Studio Code扩展的文档高亮器并不总是触发。

huangapple
  • 本文由 发表于 2023年2月24日 07:38:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定