Record of xmake vscode plug-in development process

2017/10/12 10:29
Reading amount 1.9K

Recently planned to give xmake Write some integrated plug-ins of IDE and editor. I found that the editor plug-in of vscode is easy to use. I first studied the development process of vscode plug-in and completed it xmake-vscode Plug in development.

Let's take a look at some final renderings:

Grammar highlighting and auto completion

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-completion.gif " width="60%" />

status bar

 statusbar

To achieve the above effect, it is not complicated. First, let's briefly introduce the basic process of vscode plug-in development:

Install plug-in development environment

Install cnpm

Because the domestic environment is complex, the direct installation with npm may be slow or the access is unstable, so cnpm is installed here to use the Taobao image source by default.

 $ npm install -g cnpm --registry= https://registry.npm.taobao.org

Create empty project

Install the yo tool through cnpm to create an empty project for the vscode plug-in

 $ cnpm install -g yo generator-code $ yo code

The general source code structure is as follows:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-yo-code.png " width="80%" />

After selecting to create a project, there are four inputs and one selection:

  • Enter your extended name xmake vscode
  • Enter a flag (used for the file name created by the project) xmake vscode
  • Enter a description of this extension
  • Enter a name to be used in future publishing (corresponding to a name in future publishing) tbox
  • Is it necessary to create a git repository for version management

After creating an empty project, we can directly open it with vscode, and then debug and load it:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-debug.png " width="80%" />

After loading, press F1 to open the command window and run the default hello world test command:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-hello1.png " width="80%" /> <img src=" http://tboox.org/static/img/xmake/xmake-vscode-hello2.png " width="80%" />

So far, a simple demo plug-in has been completed. Next, we will briefly introduce how to publish this plug-in to the vscode market.

Create Publisher

First, we need to marketplace.visualstudio.com Register an account on and create a publisher. Here I name it tbox

Then, we need to add a Personal Access Token (address: https://[your name].visualstudio.com/_details/security/tokens , note that Token is displayed only once, it is better to save a copy yourself)

Next, we will install the vsce tool to package, compile and publish the vscode plug-in project.

 $ cnpm install -g vsce

After installing vsce, we first create a publisher, which is tbox. Enter the token provided in the market account just now for binding.

 $ vsce create-publisher (publisher name)

Build Release

Finally, you only need to package or publish through the following command. If you just pack a local package and drag it into the vscode load test, you can run it:

 $ vsce package

This will generate a similar xmake-vscode-0.0.1.vslx The plug-in package file can be directly loaded and run with vscode.

If we have developed plug-ins and want to publish them to the market, we can execute:

 $ vsce publish [version]

At this time, we can xmake-vscode on marketplace You can also search, install and use your plug-ins directly through vscode.

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-market.png " width="60%" />

Plug in Development Details

Plug in loading mechanism

The plug-in is triggered by the activationEvents configured in the project root directory extension.json, for example:

 { "activationEvents": [ "workspaceContains:xmake.lua", "onCommand:xmake.sayHello" ] }

When vscode is opened with xmake.lua Directory or execution xmake.XXX When related commands are used, the xmake vscode plug-in will be loaded, and then the src/extension.ts The activate entry function in to load and initialize plug-ins.

 export function activate(context: vscode. ExtensionContext) { let disposable = vscode.commands.registerCommand('xmake.sayHello', () => { vscode.window.showInformationMessage('Hello XMake!'); }); context.subscriptions.push(disposable); }

The above code is registered when the plug-in is loaded sayHello Command, to display Hello XMake! Prompt information.

Create Custom Output

Vscode outputs its own log information by creating an OutputChannel. The code is as follows:

 import * as vscode from 'vscode'; let log = vscode.window.createOutputChannel("xmake/log"); log.show(); log.appendLine("hello xmake!");

When creating, you can specify a label name to distinguish different output channels. The final results are as follows:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-channel.png " width="60%" />

It should be noted that the log.show() , the output will be displayed, and the output behavior is refreshed with cache, and it will not output in real time, nor support color highlighting output.

Create and control terminals

Previously, xmake vscode used the channel method to output the build information of xmake. The effect was not very ideal, so the terminal direct execution method was used later. See the following effect diagram:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-build.gif " width="80%" />

How to control the terminal and execute its own commands is actually very simple:

 let terminal = vscode.window.createTerminal({name: "xmake"}); terminal.show(true); terminal.sendText("xmake");

The above code creates an independent terminal named xmake, and then sends the execution command: xmake , let the terminal execute xmake to build the project. Of course, if you want to display it, you should call the terminal.show(true)

Add and read global configuration

Some global vscode configuration items are added to xmake vscode to control the behavior of the xmake vscode plug-in. The configuration list is described in the package.json file, for example:

 { "configuration": { "type": "object", "title": "XMake configuration", "properties": { "xmake.logLevel": { "type": "string", "default": "normal", "description": "The Log Level: normal/verbose/minimal", "enum": [ "verbose", "normal", "minimal" ] }, "xmake.buildDirectory": { "type": "string", "default": "${workspaceRoot}/build", "description": "The Build Output Directory" }, "xmake.androidNDKDirectory": { "type": "string", "default": "", "description": "The Android NDK Directory" } } } }

Three configuration items have been added to the above configurations, all in xmake. Under the field, you can directly search the words related to xmake in the vscode configuration to find them.

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-configure.png " width="90%" />

It is also convenient to read the configuration. Just get the xmake related domain configuration and read it:

 const config = vscode.workspace.getConfiguration('xmake'); config.get("buildDirectory");

Create Status Bar

The buttons on the status bar can respond to the commands created previously, such as: xmake.sayHello Let's create a debug button on the status bar to debug the program built by xmake:

 let debugButton = vscode.window.createStatusBarItem(vscode. StatusBarAlignment.Left, 4.5); debugButton.command = 'xmake.onDebug'; debugButton.text = `$(bug)`; debugButton.tooltip = "Debug the given target"; debugButton.show();

The second parameter 4.5 in createStatusBarItem is used to control the layout order of buttons on the status bar. After creation, you can set some basic properties. Here, the button text is directly passed through $(bug) An icon is set for display, which is more intuitive.

More icons supported by vscode can be downloaded from octicons Go up to find it.

Click this button to trigger xmake.onDebug Command, and then execute on the terminal xmake run -d Command to run the debugger.

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-debug.gif " width="60%" />

Add option input list

stay xmake-vscode On the status bar of, we also add several quick configuration status buttons to quickly switch between different platforms, architectures, and compilation modes, such as:

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-configure.gif " width="60%" />

At this time, you need to have an option selection list. After clicking the button, list several options you can select, and then select Switch. How to create this option list? Code directly:

 //List of initialization options let items: vscode.QuickPickItem[] = []; items.push({label: "linux", description: "The Linux Platform"}); items.push({label: "macosx", description: "The MacOS Platform"}); items.push({label: "windows", description: "The Windows Platform"}); items.push({label: "android", description: "The Android Platform"}); items.push({label: "iphoneos", description: "The iPhoneOS Platform"}); items.push({label: "watchos", description: "The WatchOS Platform"}); items.push({label: "mingw", description: "The MingW Platform"}); items.push({label: "cross", description: "The Cross Platform"}); //Displays a list of options, prompting the user to select const chosen: vscode.QuickPickItem|undefined = await vscode.window.showQuickPick(items); if (chosen) { //Get the selected results, and then update the status bar button text platButton.text = chosen.label; }

Custom syntax highlighting

Syntax highlighting can be done through configuration files, without writing code. Of course, it can also be dynamically configured in code, which is a little cumbersome.

In xmake vscode, the syntax of the project xmake.lua description file needs to be highlighted. Therefore, a language type called xmake is defined in package.json. If the editor is opened xmake.lua The file will be syntax highlighted.

 { "contributes": { "languages": [ { "id": "xmake", "filenames": [ "xmake.lua" ], "aliases": [ "XMake" ], "configuration": "./languages/xmake-configuration.json" } ], "grammars": [ { "language": "xmake", "scopeName": "source.xmake", "path": "./languages/xmake-grammars.json" } ] } }

Descriptions related to syntax highlighting are placed in /languages/xmake-grammars.json In, we can use json to describe, and we can also use xml format to describe, but this is not very readable.

xmake-grammars.json The description rules in are extracted from lua's grammars file because xmake.lua It is based on lua syntax. For example, we match 'xxx' The rule of single quotation mark string is used to highlight string output.

 { "begin": "'", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.xmake" } }, "end": "'", "endCaptures": { "0": { "name": "punctuation.definition.string.end.xmake" } }, "name": "string.quoted.single.xmake", "patterns": [ { "include": "#escaped_char" } ] }

Implementation of automatic completion

The automatic prompt and completion of codes are troublesome. You need to write a user-defined class and register it through languages:

 vscode.languages.registerCompletionItemProvider("xmake", new Completion());

Here we define a Completion class, which is registered to the xmake language. The xmake language definition is just the configuration in package.json.

Then we implement the Completion class:

 export class Completion implements vscode.CompletionItemProvider { //Match the current input and provide a list of candidate texts to be completed public provideCompletionItems(document: vscode. TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.CompletionItem[]> { //Get the currently entered word text let wordAtPosition = document.getWordRangeAtPosition(position); var currentWord = ''; if (wordAtPosition && wordAtPosition.start.character < position.character) { var word = document.getText(wordAtPosition); currentWord = word.substr(0,  position.character - wordAtPosition.start.character); } //Guess the matching result and return the candidate list return new Promise(function (resolve, reject) { Promise.all([ getLuaKeywordsSuggestions(currentWord), getXMakeCommandsSuggestions(currentWord) ]).then(function (results) { var suggestions = Array.prototype.concat.apply([], results); resolve(suggestions); }).catch(err => { reject(err); }); }); } //Here, you can perform secondary processing on the candidate text list just returned, such as adding detailed document description information public resolveCompletionItem(item: vscode. CompletionItem, token: vscode.CancellationToken): Thenable<vscode.CompletionItem> { //Add document description to each candidate text return new Promise(function (resolve, reject) {  item.documentation = "xxxxxxxxxxx"; resolve(item); }); } }

There are many codes in this part, so they are not completely posted. For complete implementation, please refer to: completion.ts

<img src=" http://tboox.org/static/img/xmake/xmake-vscode-completion.gif " width="60%" />

epilogue

Some of the vscode plug-in code described in this article comes from xmake-vscode Interested students can directly refer to the source code and write their own plug-ins.

Expand to read the full text
Loading
Click to join the discussion 🔥 (1) Post and join the discussion 🔥
Reward
one comment
six Collection
one fabulous
 Back to top
Top