1. Introduction

Friends who like or try to write articles may make a mistake in switching between Chinese and English when they need to type symbols. For example, if you type a wrong link or picture in markdown grammar, it will become the following

! I’m a picture hello

It is very annoying, some friends will write a complete article, CTRL +H to replace the full text

I used to replace the full text of that kind, remember to replace the good, if you forget or change the previous written, the Chinese and English punctuation interspersed, that cool acid

As an angry person, how can I handle that? , read VSCode plug-in API in anger, directly replace Chinese punctuation into English punctuation function written VSCode plug-in (VSCode documentation is very good, praise), so there is this article, hand to teach you to write a VSCode plug-in.


2. Prepare

We all know that VSCode is written based on the Electron framework, which is javaScript, so writing a plug-in is very front-end friendly.

2.1 Install the environment first

$ npm install -g yo generator-code
Copy the code

2.2 Running Commands

$ yo code
Copy the code

2.3 Selecting New Extension (TypeScript)

2.4 Filling in Project Configuration

# ? What type of extension do you want to create? New Extension (TypeScript)
# ? What's the name of your extension? `your-extension-name`
### Press <Enter> to choose default for all options below ###
# ? What's the identifier of your extension? `your-extension-name`
# ? What's the description of your extension? `some description`
# ? Initialize a git repository? Yes
# ? Bundle the source code with webpack? Yes
# ? Which package manager to use? npm
Copy the code
$ ? What type of extension do you want to create? New Extension (TypeScript)
$ ? What's the name of your extension? Test (your plug-in name)
$ ? What's the identifier of your extension? test(Your plugin's logo)
$ ? What's the description of your extension? Just a Test
$ ? Initialize a git repository? no
$ ? Bundle the source code with webpack? Yes
$ ? Which package manager to use? npm
Copy the code

2.5 Project Entry

$ cd `your-extension-name`
$ code .
Copy the code

2.6 Debug ready!

In the editor, press F5, or click on the beetle on the left to go into debug mode, and a new VSCode window will automatically open. This window is for you to debug plug-ins. CTRL +shift+P brings up the command panel, type Hello World, The message “Hello World from test” pops up in the bottom right corner. Now, a simple plug-in that outputs “Hello World” and pops up “Hello World from test” is complete.


3. Project Catalog

The moment you see the directory, you feel very familiar, because this is the Node project directory, ^3^

  1. Prepare the core file

Package. The json and the extension. Ts

  1. Hello World plug-in workflow and basic concepts

    If you open webpack.config.js and see entry ‘./ SRC/extensive.ts’, that’s the entry to the project

import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
 console.log('Congratulations, your extension "test" is now active! ');
 let disposable = vscode.commands.registerCommand("test.helloWorld".() = > {
   vscode.window.showInformationMessage("Hello World from test!");
 });
 context.subscriptions.push(disposable);
}
export function deactivate() {}
Copy the code

Activate and deactivate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate activate

The activate function calls two built-in apis and registers the command named test.helloworld, which is used to pass in the output you just saw written in the callback

The core logic is written here, so the question is, when will the plugin be enabled?

This brings us to the second core file, package.json


Json contains some general properties, such as name and version, but there are also some configuration properties that are specific to vscode, such as contributes, activationEvents, Eagle-eyed students may have noticed that activationEvents mentions the timing of enabling

"activationEvents": [
    "onCommand:test.helloWorld"]."contributes": {
    "commands": [{"command": "test.helloWorld"."title": "Hello World"}},Copy the code

Where activationEvents is described as follows, indicating the conditions for plug-in activation

The Commands configuration item that contributes is the mapping of the configuration command panel input string and the response command

HelloWorld process summary

  1. contributesthecommandsConfiguration item Configuration command panel input string and should respond to commands
  2. extension.tstheactivateRegister commands and command-specific logic in
  3. activationEventsConfigure plug-in enabling timing

4. Achieve your goals

We want to write a plug-in to replace Chinese characters with English characters in markdown files. How do we start? This is the time to make a cup of coffee, gently open the official website documents

As you can see from the official website, a plug-in can expand several aspects

  1. Common Capabilities
  2. Theming
  3. Declarative Language Features
  4. Programmatic Language Features
  5. Workbench Extensions
  6. Debugging

I don’t want to go into detail here, but please go to Extensions Overview

Back to requirements, the goal is that users can immediately convert Chinese punctuation into English punctuation by calling up the command panel or using shortcut keys, which can be divided into the following steps:

4.1 is first defined inpackage.jsonTo define commands and corresponding shortcut keys

"contributes": {
    "commands": {
        "command": "test.replace"."title": "markdown cp replacer"
    },
    "keybindings": {
        "command": "test.replace"."key": "alt+f"}},Copy the code

4.2 Setting the enabling time of the plug-in, obviously this is enabled when the file ends with.md

"activationEvents": [
    "onLanguage:markdown"].Copy the code

4.3 Write specific conversion logic

  • Registers a custom command
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
  vscode.commands.registerCommand("test.replace".() = >{ replace(); })); }Copy the code
  • Perfect conversion logic functions
const fs = require("fs");
// Chinese characters
const CP = [",".":"."?"."!"."。"."" "."" "."(".")"];
// The English character used for substitution
const EP = [",".":"."?"."!".".".'"'.'"'."(".")"];
const map = new Map(a);let len = CP.length;
for (let i = 0; i < len; i++) {
map.set(CP[i], EP[i]);
}
function replace() {
let fileName: string | undefined= vscode.window.activeTextEditor? .document.fileName;let content: string;
try {
  content = fs.readFileSync(fileName).toString();
} catch (err) {
  throw err;
}
let charArr = content.split("");
for (let i = 0; i < charArr.length; i++) {
  let char = charArr[i];
  if (map.has(char)) {
    charArr[i] = map.get(char);
  }
}
content = charArr.join("");
fs.writeFile(fileName, content, (err: Error) = > {
  if (err) {
    throwerr; }}); }Copy the code

4. Done! 🉑

Run debug and type Alt + F to replace it immediately.


5. Release and iterate

The official guide