×
Community Blog Quick Start to VSCode Plug-Ins: Running Commands

Quick Start to VSCode Plug-Ins: Running Commands

In this tutorial series, we will look at VSCode plug-ins, use Scaffolding to generate a skeleton, use cursor movement commands, and use a plug-in to run multiple commands.

Quick Start to VSCode Plug-Ins: Running Commands

By Xulun

Since 2017, VSCode has grown leaps and bounds in popularity. In addition to its powerful functions as well as continuous upgrades, the excellent plug-ins feature of VSCode is probably also one major reason for its popularity. A considerable number of functions in VSCode are implemented through its plug-ins and extensions feature.

Compared with Atom IDE, which uses CoffeeScript as the main development language, VSCode uses TypeScript, which is popular with developers, as the main development language. This script provides a good boost for VSCode plug-in development.

And with the continuous improvement of the plug-in feature, document, example, and scaffolding tools also are also maturing quickly, making it is easier than ever to write a plug-in for VSCode.

As a programmer, you can write your own plug-in specifically to accelerate your development efficiency. Only you know your business development best. And so now is a good time for you to take advantage of tools like this plug-in feature to boost your productivity.

VSCode has a wide variety of plug-ins. So, in this part of this multi-part tutorial, let's first start by exploring the most traditional piece of VSCode: defining a new command. In this blog, we will explore how to define a command by specifically using Scaffolding to generate a skeleton, using cursor movement commands, and using a plug-in to implement multiple commands.

Using the Scaffolding to Generate a Skeleton

Like other mainstream front-end projects, we use the scaffolding to generate a plug-in skeleton. Microsoft provides a script based on Yeoman, a tool used to generate the scaffolding.

1

For this tutorial, we will use NPM to install the VSCode plug-in scaffolding. You can do so by running this install command.

npm install -g yo generator-code

Then, we can use the yo code command to generate the VSCode plug-in skeleton code. After which, scaffolding will prompt us to choose the type of plug-in to be generated:

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

? What type of extension do you want to create? (Use arrow keys)
 New Extension (TypeScript) 
  New Extension (JavaScript) 
  New Color Theme 
  New Language Support 
  New Code Snippets 
  New Keymap 
  New Extension Pack 

Let's choose New Extension (Typescript). We will continue to introduce other options in the following articles.

Let's start with moving the cursor, which is the simplest. For example, to write a script that moves the cursor to the beginning of the editing area, such as the header of an article or code. Specifically, for Emacs, the command is called move-beginning-of-buffer.

Using Cursor Movement Commands

As a source-code editor, VSCode certainly has similar functions. The function of moving the cursor to the beginning of the article does not need to be developed by ourselves. VSCode has already done it for us. A lot of cursor control commands are defined in VSCode. For example, the command of moving the cursor to the beginning of the article is called cursorTop.

Consider the commands below:

  • cursorTop: Used to move the cursor to the beginning of the article.
  • cursorBottom: Used to move the cursor to the end of the article.
  • cursorRight: Used to move the cursor to the right, which is equivalent to forward-char in Emacs.
  • cursorLeft: Used to move the cursor to the left, which is equivalent to backward-char in Emacs.
  • cursorDown: Used to move the cursor down a row, which is equivalent to next-line in Emacs.
  • cursorUp: Used to move the cursor up a row, which is equivalent to previous-line in Emacs.
  • cursorLineStart: Used to move the cursor to the beginning of a row, which is equivalent to move-beginning-of-line in Emacs.
  • cursorLineEnd: Used to move the cursor to the end of a row, which is equivalent to move-end-of-line in Emacs.

We will create a move.ts for cursor movement now. Let's take moving the cursor to the beginning of the article as an example. We use the vscode.commands.execute command function to execute the command.

For example:

import * as vscode from 'vscode';

export function moveBeginningOfBuffer(): void {
    vscode.commands.executeCommand('cursorTop');
}

In the main file extension.ts, first introduce the move.ts package:

import * as move from './move';

Then, register the command in the activate function:

    let disposable_begin_buffer = vscode.commands.registerCommand('extension.littleemacs.moveBeginningOfBuffer',
        move.moveBeginningOfBuffer);

    context.subscriptions.push(disposable_begin_buffer);

Finally, associate a shortcut key to it in the package.json. < and > are upper keys on the keyboard, so we will not use them. For example, associate the command to alt-[.

The modified contributions section is as follows:

    "contributes": {
        "commands": [{
            "command": "extension.littleemacs.moveBeginningOfBuffer",
            "title": "move-beginning-of-buffer"
        }],
        "keybindings": [{
            "command": "extension.littleemacs.moveBeginningOfBuffer",
            "key": "alt+["
        }]
    }

And we're done with that! When we use F5 to start debugging, a new VSCode interface will be started.

On the newly opened VSCode interface, open the command window (F1 or shift-cmd-p), and enter move-beginning-of-buffer to see the command:

2

We can move the cursor to the center of the file, and the cursor will return to the beginning of the file if we press alt+[.

The complete extension.ts code is:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as move from './move';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "littleemacs" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with registerCommand
    // The commandId parameter must match the command field in package.json
    let disposable_begin_buffer = vscode.commands.registerCommand('extension.littleemacs.moveBeginningOfBuffer',
        move.moveBeginningOfBuffer);

    context.subscriptions.push(disposable_begin_buffer);
}

// this method is called when your extension is deactivated
export function deactivate() {
    console.log('Plugin deactivated');
}

The corresponding complete package.json is:

{
    "name": "littleemacs",
    "displayName": "littleemacs",
    "description": "Some operations just like emacs",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.33.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension.littleemacs.moveBeginningOfBuffer"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [{
            "command": "extension.littleemacs.moveBeginningOfBuffer",
            "title": "move-beginning-of-buffer"
        }],
        "keybindings": [{
            "command": "extension.littleemacs.moveBeginningOfBuffer",
            "key": "alt+["
        }]
    },
    "scripts": {
        "vscode:prepublish": "yarn run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "postinstall": "node ./node_modules/vscode/bin/install",
        "test": "yarn run compile && node ./node_modules/vscode/bin/test"
    },
    "devDependencies": {
        "typescript": "^3.3.1",
        "vscode": "^1.1.28",
        "tslint": "^5.12.1",
        "@types/node": "^10.12.21",
        "@types/mocha": "^2.2.42"
    }
}

Use One Plug-In to Implement Multiple Commands

One command is not enough, right? Let's write another one:

activate function:

    let disposable_begin_buffer = vscode.commands.registerCommand('extension.littleemacs.beginningOfBuffer',
        move.beginningOfBuffer);

    let disposable_end_buffer = vscode.commands.registerCommand('extension.littleemacs.endOfBuffer',
        move.endOfBuffer);

    context.subscriptions.push(disposable_begin_buffer);
    context.subscriptions.push(disposable_end_buffer);

Function implementation function:

import * as vscode from 'vscode';

export function beginningOfBuffer(): void {
    vscode.commands.executeCommand('cursorTop');
}

export function endOfBuffer() {
    vscode.commands.executeCommand('cursorBottom');
}

package.json:

    "activationEvents": [
        "onCommand:extension.littleemacs.beginningOfBuffer",
        "onCommand:extension.littleemacs.endOfBuffer"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [{
                "command": "extension.littleemacs.beginningOfBuffer",
                "title": "beginning-of-buffer"
            },
            {
                "command": "extension.littleemacs.endOfBuffer",
                "title": "end-of-buffer"
            }
        ],
        "keybindings": [{
                "command": "extension.littleemacs.beginningOfBuffer",
                "key": "alt+["
            },
            {
                "command": "extension.littleemacs.endOfBuffer",
                "key": "alt+]"
            }
        ]
    },
0 0 0
Share on

Louis Liu

7 posts | 0 followers

You may also like

Comments