VS Code语言扩展:字符串模式不覆盖GOTO命令着色问题
The core issue here is that once the parser enters a string scope (via the begin/end rules for strings), it won’t automatically check for other patterns like your GOTO commands unless you explicitly tell it to. Here’s how to adjust your grammar to fix this behavior:
Step 1: Fix the Case Mismatch
First, you’ve got a case inconsistency in your includes: your repository uses "GOTO" (uppercase) but your top-level pattern references "#goto" (lowercase). TextMate grammars are case-sensitive, so this would prevent your GOTO patterns from working correctly even outside strings. Let’s align those to use consistent casing.
Step 2: Include GOTO Patterns Inside Strings
Update your strings repository entry to include the GOTO patterns. This tells the parser to keep looking for GOTO commands even when it’s inside a string scope.
Corrected mylang.tmLanguage.json
{ "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", "name": "F-Script", "patterns": [ {"include": "#GOTO"}, {"include": "#strings"} ], "repository": { "GOTO": { "patterns": [ { "name": "support.function", "match": "/(?!«)[a-zA-Z0-9_.\\-«»/(/)]{1,}(?=»)\\b" }, { "name": "support.function", "match": "GOTO[(]{1}(# [a-zA-Z0-9_.-]{1,}|/)[)]{1}" } ] }, "strings": { "name": "string.quoted.double.f-script", "begin": "\"|'", "end": "\"|'", "patterns": [ { "name": "constant.character.escape.f-script", "match": "\\\\[\"']" }, {"include": "#GOTO"} // This line enables GOTO detection inside strings ] } }, "scopeName": "source.f-script" }
Key Changes Explained:
- Case Consistency: Changed the top-level include from
#gototo#GOTOto match the repository key, ensuring GOTO patterns are applied everywhere they should be. - Embedded GOTO Detection: The new
{"include": "#GOTO"}line inside the strings' patterns tells the parser to recognize GOTO commands even when inside a string. Inner patterns take precedence over outer scopes, so the GOTO will keep itssupport.functioncoloring. - Fixed Escape Character Match: Updated the escape pattern to actually match escaped quotes (
\"or\') instead of the incorrect$(which was matching end-of-line instead of escape sequences).
With these adjustments:
- Your first line
«GOTO(# THIS.COLOR.GOTO)»will retain its correct function coloring. - The third line
"This Should be formated like a String «GOTO(# THIS.COLOR.GOTO)»"will show string coloring for most of the line, but the embedded GOTO command will use the same function color as the first line.
内容的提问来源于stack exchange,提问作者Raydir

