A, install,

The installation is explained in detail at the beginning of the VS Code Plugin development tutorial – Tree View + Web View. If you are just getting started, please spend 5 minutes here to see how to install and use it initially.

Here I quickly explain again, do not understand the partners to see the link above ~

  • Terminal type:npm install -g yo generator-code
  • Terminal typeyo code
  • Choose the first optionNew Extension (TypeScript)
  • Re-open vscode and go to the project directory
  • Press theF5Start the plugin
  • Press thectrl+shift+Porcommand+chift+PThe command page is displayedHello WorldClick on the enter
  • If the bottom right corner pops upHello World“, the plug-in is successfully created

Add a point: the official website API here API please try to learn to use. It’s normal not to be able to read at first. Every time you encounter a new attribute, check it here. Over time, you can figure out a little bit. Google Chrome has translation.

Display text in the status bar

This feature is detailed in a.ts file.

Create the wordcount.ts file in the extension.ts sibling

Import what we need to get a couple of items from vscode

// All of this can be found in the API
// There are API screenshots below, please refer to them, but I hope you can check them out by yourself
import { window, StatusBarItem, StatusBarAlignment } from 'vscode';

export class WordCount {

  // Define a status bar property
  private statusBar : StatusBarItem | undefined;

  // Create one if it does not exist
  if(!this.statusBar) {
    this.statusBar  = window.createStatusBarItem(StatusBarAlignment.Left);
  }

  this.statusBar.text = 'This is my first StatusBar.';
  this.statusBar.show();

} 
Copy the code

All right. Step one is done. It is not possible to launch the plug-in now because we need to deactivate it and use it in the extension.ts file.

Start by opening the package.json file

Go to activationEvents and learn to register an activation event like helloWorld, which the user can activate after typing a command.

Next locate the contributes text, and do the same with helloWorld by publishing the content configuration, binding a command ID, and then using it in the command palette.

"activationEvents": [
  "onCommand:extension.helloWorld",
  "onCommand:extension.wordCount"
],
"main": "./out/extension.js",
"contributes": {
  "commands": [{
    "command": "extension.helloWorld",
    "title": "Hello World"
  }, {
    "command": "extension.wordCount",
    "title": "wordCount"
  }]
},
Copy the code

Next we open the extension.ts file

import { window } from 'vscode';
import { WordCount } from './WordCount';

export function activate(context: vscode.ExtensionContext) {...// instantiate WordCount
  let wordCount = new WordCount();

  // The function is bound to the command ID you registered
	context.subscriptions.push(vscode.commands.registerCommand('extension.wordCount', () = > {// Call the method in WordCount
		wordCount.updateWordCount();
		window.showInformationMessage('This plugin is a character that displays the output of the MD document, see the lower left corner of VS Code ~');
	}));
}
Copy the code

Ok, now press F5, press Command +chift+P, type wordCount, whether you can see the text on the status bar in the lower left corner and the message box in the lower right corner. If you can’t, don’t worry. Compare the above code to see if there is anything wrong with it.

The total number of words displayed on the status bar

If you just write dead words that much less interesting, let’s implement automatic total word count function.

And I want to show the word count only in the case of md documents. Otherwise, no presentation. Add code in wordcount.ts

// TextDocument: represents a TextDocument, such as the source file can view API ha
import { window, StatusBarItem, StatusBarAlignment, TextDocument } from 'vscode';
export class WordCount { private statusBar ! : StatusBarItem ; public updateWordCount() {if(!this.statusBar) {
      this.statusBar  = window.createStatusBarItem(StatusBarAlignment.Left);
    }

    // Get the current active editor
    let editor = window.activeTextEditor;

    // If the following code is deleted, an error will be reported
    if(! editor) {this.statusBar.hide();
      return;
    }

    // Get all information about the current document
    let doc = editor.document;

    // Read the language ID of the current file to determine whether it is an MD document
    if(doc.languageId === 'markdown') {
      let textNum = doc.getText().replace(/[\r\n\s]+/g.' ').length;
      this.statusBar.text = textNum === 0 ? 'There is no text yet : '$(Octoface) has been output${textNum}A word!! `;
      this.statusBar.show();
    } else {
      this.statusBar.hide(); }}// Destroy objects and free resources
  dispose() {
		this.statusBar.dispose(); }}Copy the code

$(Octoface): This is the official website API. Friends can choose their own ICONS

To summarize the steps here:

  • Start by getting the current text editor
  • Determine if the text editor exists (this is important)
  • Check whether the language ID of course ismdThe document
  • If: The number of words counted is displayed in the status bar

4. Automate the plug-in by adding listening events

If you do not open the md file, the status bar will not show the plugin functionality.

After opening the MD document, enable command+chift+P to run the plugin and see the total number of words displayed in the status bar.

But there’s one downside you should notice:

The number of words in the status bar cannot be changed as the document is written. You must re-execute command+chift+P each time to see the latest number of words. This is really inconvenient.

Is there a way to automatically count the word count when we open an MD document and update it in real time? Now let’s implement ~

Let’s continue to modify the contents of the wordcount.ts file:

import { Disposable } from 'vscode';
export class WordCount { private statusBar! : StatusBarItem;// Add a constructor to the class, similar to how we create objects and pass parameters
  constructor() {

    // The event that fires when the selection in the editor changes
    window.onDidChangeTextEditorSelection(this.updateWordCount,this);

    // Events that will be triggered when the active editor changes
    window.onDidChangeActiveTextEditor(this.updateWordCount, this); } public updateWordCount() {... }// Objects and free resources.
  // The destruction code here is very important, do not forget!! ~ ~
  dispose() {
		this.statusBar.dispose(); }}Copy the code

The second step is to modify the package.json file by opening package.json

Instead of executing commands on the command panel to start the plug-in, we now want to start the plug-in at any time, or automatically if the language ID of the current editor is MD.

So now our activationEvents activationEvents no longer require the onCommand command launch type.

Instead, replace it with onLanguage:markdown or *, meaning that the plug-in is activated when the language ID is markdown, or when the project starts. The latter is not recommended.

Since the onCommand command is no longer needed. So that contributes -> commands no longer requires the boot command.

"activationEvents": [onCommand: extension. The helloWorld, / / delete "onCommand: extension. The wordCount", / / delete "onLanguage: markdown]", "main" : "./out/extension.js", "contributes": {// All keys to commands": [{"command": "extension.wordCount", "title": "wordCount" }] },Copy the code

After modifying the package.json file, the last step is to modify the extension.ts file

import { WordCount } from './WordCount';
export function activate(context: vscode.ExtensionContext) {

  	// A simple two lines of code
	let wordCount = new WordCount();
 	context.subscriptions.push(wordCount);
}
Copy the code

Because we no longer need to order to start the activation function plugin, so no longer need to vscode.com mands. RegisterCommand

In WordCount class, we have added the dispose () to destroy events, so can directly context. Subscriptions. Push () the class.

Ok guys, now go test the effect.

5. Make a small tip(pop box to show the selected text)

I’m going to use a little bit simpler pseudocode here

Add the following code to the wordcount.ts file:

// Get the text editor selection
const selection = editor.selection;
const text = editor.document.getText(selection);
window.showInformationMessage(text);
Copy the code

You can test the effect directly

6. Add a small tip to show how many lines of text are selected.

// Pass the active text editor to the following function
public updateStatusBarItem(editor: TextEditor | undefined): number {
  let lines = 0;
  if(editor) {
    lines = editor.selections.reduce((prev,curr) = > prev + (curr.end.line - curr.start.line),0);
  }
  return lines;
}
Copy the code

Create the above method in the wordcount.ts file, pass the active text editor to the method, and return the line count.

If you want to display the number of selected lines in the status bar as well, repeat the above code to create a StatusBarItem and assign it a value.

Pay attention to

When we use Windows. ShowInformationMessage to display a number value of type is no good. It needs to be converted to string

All the code is here. If you need to take it by yourself, you are welcome

Remember the two chickens