简体   繁体   English

在 visual-studio-code 扩展中返回一个单词

[英]Return a word in a visual-studio-code extension

I am making an extension in visual-studio-code, in typescript.我正在 typescript 中的 visual-studio-code 中进行扩展。 And I need to return a word (in combination with dots and hyphens) after the '{{>' prefix.而且我需要在'{{>'前缀之后返回一个单词(结合点和连字符)。

{{>word-test }}
{{> word-test}}
{{> word-test }}
{{> word-test class="class_name"}}
// returns 'word-test'

// On this one the regex doesn't seem to work
{{> word-test 
    class="class_name"
}}
// returns all the text in the file

{{> word-test.test }}
// returns 'word-test.test'

To get the words I use the 'getWordRangeAtPosition' built in in visual-studio-code with a regex in the parameter.为了获得单词,我使用 visual-studio-code 中内置的“getWordRangeAtPosition” ,参数中带有正则表达式。

The problem问题

I have tried a few regex combinations, but when there is a line-break I never get the 'word-test' returned in visual-studio-code.我尝试了一些正则表达式组合,但是当出现换行符时,我永远不会在 visual-studio-code 中返回“单词测试”。 Instead i get all the text in the file.相反,我得到了文件中的所有文本。

Here is the most recent regex combination I have tried:这是我尝试过的最新正则表达式组合:

/(?<={{>[ \s]{0,1})(.*?)(?=[\n\s\}\}])/

It works all fine in a regex tester, but not in visual-studio-code itself.它在正则表达式测试器中一切正常,但在 visual-studio-code 本身中却不行。

see the regex tester: https://regexr.com/4o4d8请参阅正则表达式测试器: https://regexr.com/4o4d8

Rather than a complicated RegEx, can you write the logic in your extension code?您可以在扩展代码中编写逻辑而不是复杂的 RegEx 吗?

You can find the word on position, then get the leading text from the same line in the document, and test that the leading text ends with {{> :可以在 position 上找到这个词,然后从文档的同一行获取前导文本,并测试前导文本是否以{{>结尾:

let wordRange = document.getWordRangeAtPosition(position, /\w[-\w\.]*/g);
let leadingText = document.getText(new Range(wordRange.start.with({ character: 0 }), wordRange.start));
let hasCorrectPrefix = leadingText.match(/{{>\s?$/);

Similarly you could compare the suffix, if it is really necessary for the functionality.同样,如果功能确实需要,您可以比较后缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM