【发布时间】:2020-05-01 04:28:26
【问题描述】:
是否可以使用 VSCode API 查询当前行是否为注释?
【问题讨论】:
-
您找到解决方案了吗?我正在编写扩展程序并想知道同样的事情。我发现的只是不同的“commentControllers”
-
你们有没有找到任何东西?
标签: visual-studio-code vscode-extensions
是否可以使用 VSCode API 查询当前行是否为注释?
【问题讨论】:
标签: visual-studio-code vscode-extensions
这个解决方案不是最优的,但它确实有效。
您可以生成一个配置文件,列出当前安装的扩展程序中所有语言特定的关键字/符号。
然后使用此文件获取注释配置和注释分隔符(用于行注释和注释块)。
我为此实现了一个类,借鉴了上述提交:
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
interface CommentConfig {
lineComment?: string;
blockComment?: [string, string];
}
export class CommentConfigHandler {
private readonly languageToConfigPath = new Map<string, string>();
private readonly commentConfig = new Map<string, CommentConfig | undefined>();
public constructor() {
this.updateLanguagesDefinitions();
}
/**
* Generate a map of language configuration file by language defined by extensions
* External extensions can override default configurations os VSCode
*/
public updateLanguagesDefinitions() {
this.commentConfig.clear();
for (const extension of vscode.extensions.all) {
const packageJSON = extension.packageJSON as any;
if (packageJSON.contributes && packageJSON.contributes.languages) {
for (const language of packageJSON.contributes.languages) {
if (language.configuration) {
const configPath = path.join(extension.extensionPath, language.configuration);
this.languageToConfigPath.set(language.id, configPath);
}
}
}
}
}
/**
* Return the comment config for `languageCode`
* @param languageCode The short code of the current language
*/
public getCommentConfig(languageCode: string): CommentConfig | undefined {
if (this.commentConfig.has(languageCode)) {
return this.commentConfig.get(languageCode);
}
if (!this.languageToConfigPath.has(languageCode)) {
return undefined;
}
const file = this.languageToConfigPath.get(languageCode) as string;
const content = fs.readFileSync(file, { encoding: 'utf8' });
try {
// Using normal JSON because json5 behaved buggy.
// Might need JSON5 in the future to parse language jsons with comments.
const config = JSON.parse(content);
this.commentConfig.set(languageCode, config.comments);
return config.comments;
} catch (error) {
this.commentConfig.set(languageCode, undefined);
return undefined;
}
}
}
要检测一行是否是注释,您可以使用上面的类获取注释配置,转义分隔符,并在正则表达式中使用它们。
类似这样的:
activeEditor = vscode.window.activeTextEditor;
const commentConfigHandler = new CommentConfig();
const commentCfg = commentConfigHandler.getCommentConfig(activeEditor.document.languageId);
function escapeRegex(string: string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
const commentLineDelimiter = commentCfg.lineComment;
const regex = new RegExp(`\s*${escapeRegex(commentLineDelimiter )}.*`, "ig");
const isComment = regex.test(lineText)
请注意,上述示例仅测试单行 cmets,需要使用更广泛的正则表达式(包括 commentCfg.blockComment[0] 和 commentCfg.blockComment[1])扩展块 cmets。
【讨论】: