Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Background: Theme styles are predefined in the project, and only relevant variables are used when colors are used in code writing. However, when using variables, it is often difficult to remember what color each theme value represents, and it is necessary to refer to the document repeatedly. Therefore, it is hoped that the color represented by the current variable can be known during coding. Multiple maps are supported to enable theme switching (e.g., text_color #333 under the default theme, #d9d9d9 under the dark theme).

Scenarios where custom theme values are considered are quite common, so refer to the plugin Color Highlight used in the project to finalize the plugin form as a custom highlighted character.

Good memory is better than bad writing ✏️, write an article to record the knowledge points used in the development of plug-ins.

Ps: There are plenty of other good articles on initialization of plug-in projects, the role of package.json configurations, etc. See the references in the appendix at the end of this article for a quick overview. This article only covers the core apis used to implement the desired functionality

Plug-in demo & feature introduction

Take a look at the final implementation, plug-in support

  • Highlight custom characters
  • Subject switch

When configured as a rule, the editor highlights the target character in the specified color

Click on the lower right corner to switch predefined themes

Core function API

Initialization engineering

Erection of scaffolding

npm install -g yo generator-code
Copy the code

Initialization engineering

yo code

? What type of extension do you want to create? New Extension (TypeScript)
? What's the name of your extension? highlight-my-word-api-demo
? What's the identifier of your extension? highlight-my-word-api-demo
? What's the description of your extension? highlight-my-word-api-demo
? Initialize a git repository? Yes
? Bundle the source code with webpack? No
? Which package manager to use? npm
Copy the code

Set the style at the editor target

The following example 🌰 shows how to highlight the first target field in the editor

import * as vscode from 'vscode';

export const highlightTargetStr = (str = 'primary') = > {

  // create a decorator
  const decorator = vscode.window.createTextEditorDecorationType({
    overviewRulerLane: vscode.OverviewRulerLane.Center,
    borderRadius: '2px'.color: '#fff'.backgroundColor: '#3072f6'});// get the visible editor instance
  const visibleTextEditors = vscode.window.visibleTextEditors;
  visibleTextEditors.forEach((editor) = > {
  
    // Get the document instance
    const { document } = editor;
    
    // ③ Get the target string position from the document instance
    const startIndex = document.getText().indexOf(str);
    const startPos = document.positionAt(startIndex);
    const endPos = document.positionAt(startIndex + str.length);
    const range = [new vscode.Range(startPos, endPos)];
    
    // set the decorator at the target position
    editor.setDecorations(decorator, range);
  });
};
Copy the code

The effect of the relevant code is commented, and the final effect is as follows:

Matters needing attention:

  1. Dispose () releases resources. Dispose () can be called again with the same decorator. The style is no longer valid

  2. To refresh the scope of the decorations, set a new range with the second parameter of editor. setdesk.

  3. If set only once, the decoration style will always apply to the area, even if new text is inserted in the middle

So the need according to the changes of the content (vscode. Workspace. OnDidChangeTextDocument) to update the decorator range

Reading and writing configuration

Registration package. Json

// package.json{..."contributes": {
    "configuration": [{"title": "%extension-title%"."properties": {
          "highlight-my-word-api-demo.themes": {
            "type": "object"."description": "%configuration-themes%"}}}]}}Copy the code

The %% wrapped variables are defined in package.nls. Json

// package.nls.json
{
  "extension-title": "highlight my word"."configuration-themes": "Custom theme",}Copy the code

After the configuration is complete, you can configure it in setting.json and read the configuration in the plug-in in the following ways

loadConfig = () = > {
  const config = vscode.workspace.getConfiguration('highlight-my-word-api-demo').get('themes'{});console.log("config", config);
};

Copy the code

Listening for configuration changes

// extension.ts
export function activate(context: vscode.ExtensionContext) {
	context.subscriptions.push(
		vscode.workspace.onDidChangeConfiguration((e) = > {
			console.log(e); })); }Copy the code

Update the configuration in the code

updateConfig = () = > {
  vscode.workspace.getConfiguration('highlight-my-word-api-demo').update('themes', { value: 'Updated value' });
};

Copy the code

The previous API can be used to implement configurable custom highlighting, but so far switching the theme needs to be configured in setting.json, which is not very friendly. In order to make the experience more pleasant and add the function of quick switching, the following API is used

Bottom status bar

export const displayStatusBar = () = > {
  // Save this object to update copy, control display, etc
  const statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right);
  statusBar.text = 'Highlight My Word';
  statusBar.tooltip = 'Click to switch themes';
   // Click on the response event to bind the corresponding command identifier
  statusBar.command = 'highlight-my-word-api-demo.changeTheme';

  statusBar.show();
};
Copy the code

Click the status bar to respond to command, through command to call a shortcut selection popover can realize the shortcut to switch the theme

Register & implement Command

Packge. Json configuration

// package.json{..."contributes": {
    "commands": [{"command": "highlight-my-word-api-demo.changeTheme"."title": "ChangeTheme"}}}]Copy the code

registered

// extension.ts 

export function activate(context: vscode.ExtensionContext) {
	context.subscriptions.push(
		vscode.commands.registerCommand('highlight-my-word-api-demo.changeTheme', showQuickPick),
	);
}
Copy the code

ShowQuickPick is the way to show the quick popover below

Quick selection box

const showQuickPick = () = > {
  vscode.window.showQuickPick([
    Theme '1'.Theme '2',] and {canPickMany: false.placeHolder: "Choose your theme"
  }).then((res) = > {
    console.log(res);
  });
};
Copy the code

Note: Even if nothing is selected, the promise still calls back, returning undefined

The final VISUAL studio Code plugin is achieved through the above API, welcome to the App Store search highlight My Word experience using ☘️☘️

The appendix

The resources

[1] Xiaoming – VSCode plug-in development Guide [2] VSCode [3] VS official website [4] Boy, I have passed the COLLECTION of VS code API to you

The project address

[1] Demo github address [2