1. 程式人生 > >為新語言編寫Visual Studio Code語法高亮外掛

為新語言編寫Visual Studio Code語法高亮外掛

本文原始碼庫: program-in-chinese/quan4-highlighter

語法高亮是一個開發環境的基本功能. 此文嘗試為之前的"圈4"語言(詳見程式語言試驗之Antlr4+JavaScript實現"圈4")編寫一個高亮外掛, 僅為演示之用. 參考的是Visual Studio Code官方文件: Add Themes, Snippets and Colorizers to Visual Studio Code. 首先建立外掛如下, 為".圈4"的原始檔新增高亮:

$ yo code

     _-----_     ╭──────────────────────────╮
    |       |    │   Welcome to the Visual  │
    |--(o)--|    │   Studio Code Extension  │
   `---------´   │        generator!        │
    ( _´U`_ )    ╰──────────────────────────╯
    /___A___\   /
     |  ~  |     
   __'.___.'__   
 ´   `  |° ´ Y ` 

? What type of extension do you want to create? New Language Support
Enter the URL (http, https) or the file path of the tmLanguage grammar or press ENTER to start with a new grammar.
? URL or file to import, or none for new: 
? What's the name of your extension? 圈4高亮
? What's the identifier of your extension? quan4-highlighter
? What's the description of your extension? 圈4語言的VS Code外掛
? What's your publisher name (more info: https://code.visualstudio.com/docs/tools/vscecli#_publishing-extensions)? nobody
Enter the id of the language. The id is an identifier and is single, lower-case name such as 'php', 'javascript'
? Language id: quan4
Enter the name of the language. The name will be shown in the VS Code editor mode selector.
? Language name: 圈4
Enter the file extensions of the language. Use commas to separate multiple entries (e.g. .ruby, .rb)
? File extensions: .圈4
Enter the root scope name of the grammar (e.g. source.ruby)
? Scope names: source.圈4
   create quan4-highlighter/syntaxes/quan4.tmLanguage.json
   create quan4-highlighter/.vscode/launch.json
   create quan4-highlighter/package.json
   create quan4-highlighter/README.md
   create quan4-highlighter/CHANGELOG.md
   create quan4-highlighter/vsc-extension-quickstart.md
   create quan4-highlighter/language-configuration.json
   create quan4-highlighter/.vscodeignore
   create quan4-highlighter/.gitignore

Your extension quan4-highlighter has been created!

預設語法檔案syntaxes/quan4.tmLanguage.json中, 關鍵詞的模式匹配為:

"match": "\\b(if|while|for|return)\\b"

直接改為:

"match": "求約數"

執行外掛後(F5新執行, Command+R可以在外掛修改後重新整理)實現:

很明顯它是最直接的正則表示式匹配. 還不確定是否能做到空格敏感, 以及語法檢驗.

這只是第一步, 之後還需對語法定義格式(TextMate Manual & Language Grammars)進行深入學習.