Monaco 中的 TypeDefinitionProvider 和 ImplementationProvider、DefinitionProvider 类似,右键点击变量名称,现在 “选择转到类型定义”, 跳到指定位置。
通过 registerTypeDefinitionProvider 添加 TypeDefinitionProvider 处理方法
实现 provideTypeDefinition 并返回 Definition
Definition 中定义了跳转位置
代码实现如下
export function typeDefinitionProvider(
editor: monacoEditor.editor.IStandaloneCodeEditor,
monaco: typeof monacoEditor
) {
monaco.languages.registerTypeDefinitionProvider("mySpecialLanguage", {
provideTypeDefinition(model, position, token) {
const word = model.getWordAtPosition(position);
if (!word) {
return null;
}
const text = model.getValue();
const regex = new RegExp(`\\b${word.word}\\b`, 'g');
let match;
let firstOccurrenceRange: monacoEditor.Range | null = null;
while ((match = regex.exec(text)) !== null) {
const start = model.getPositionAt(match.index);
const end = model.getPositionAt(match.index + word.word.length);
firstOccurrenceRange = new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column);
break;
}
if (firstOccurrenceRange) {
return [
{
uri: model.uri,
range: firstOccurrenceRange,
}
];
}
// Provide a dummy type definition as an example
const typeDefinitionRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
return [
{
uri: model.uri,
range: typeDefinitionRange,
}
];
}
})
}