简体   繁体   中英

Return a word in a visual-studio-code extension

I am making an extension in visual-studio-code, in typescript. 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.

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. 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.

see the regex tester: https://regexr.com/4o4d8

Rather than a complicated RegEx, can you write the logic in your extension code?

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 {{> :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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