FE.BASE-vscode使用、原理、插件開發筆記

使用

命令行使用

  • 幫助:code --help
  • 使用已經打開的窗口來打開文件:code -r
  • 打開文件並滾動到特定行:code -r -g package.json:128
  • 比較兩個文件:code -r -d a.txt b.txt
  • 接受管道符數據:ls | code -

圖形界面、快捷鍵使用

  • 光標移動至javascript

    • 單詞開頭/末尾 Ctrl + Left/Right,
    • 代碼塊開頭/末尾 Cmd + Shift + \
    • 文檔首行/末行 Ctrl + Home/End
  • 文本html

    • 全選/剪切/複製/黏貼/保存 Ctrl A/X/C/V/S
    • 文本選擇= Shift + 上述光標操做
    • 格式化 Alt + Shift + F
    • 格式化部分:選中,Ctrl + K + Ctrl + F
  • java

    • 刪除 Ctrl + Shift + K
    • 剪切/複製/黏貼 Ctrl + X/C/V
    • 在當前行的下(上)面新開始一行 Ctrl ( + Shift) + Enter
    • 上/下移動 Alt + 上/下
  • 文檔node

    • 查找/替換/符號跳轉 Ctrl + F/H/T
    • 轉到行 Ctrl + G
    • 轉到文件 Ctrl + P
    • 轉到符號 Ctrl + Shift + O
    • 打開命令面板 Ctrl + Shift + P
  • 窗體linux

    • 關閉Ctrl + W
    • 打開關閉側邊欄 Ctrl + B
    • 側邊欄位置 命令面板toggle side bar pos
    • markdown預覽 Ctrl + K V
    • 1/2/3列 Ctrl + 1/2/3
    • 行列切換 Shift + Alt + 0
    • 2x2佈局 命令面板2x2
    • Tab切換 Ctrl + Pagedown/Pageup
    • 縮放 Ctrl + /- (reset zoom 恢復)
  • 自定義快捷鍵 Ctrl + K + Ctrl + S
  • 鼠標操做git

    • 選中單詞 雙擊
    • 選中行 三擊/單擊行號
    • 多光標: Alt + 單擊
    • 代碼跳轉: Ctrl + 單擊
  • 編碼github

    • 代碼補全 Ctrl + 空格
    • 代碼摺疊/展開 Ctrl + Shift + [/]
    • 參數預覽 Ctrl + Shift + Space
    • 自動修復建議 Ctrl + .
    • 打開終端 Ctrl + Shift + `
    • 隱藏/顯示面板 Ctrl + J
    • 轉到上次編輯位置 命令面板go to last edit
    • 調出最近打開的工做區 Ctrl + R
  • 用戶設置chrome

    • 麪包屑: breadcrumbs
    • 小地圖: minimap
    • 自動格式化:formatOnSave、formatOnType
    • 自動保存:autoSave
    • 默認語言:default language
  • 其餘用戶設置shell

    • editor cursor, 光標渲染和多光標
    • editor find, 編輯器內搜索
    • editor font, 字體npm

      • 連字字體

        "editor.fontFamily": "Fira Code",
        "editor.fontLigatures": true
    • editor format, 代碼格式化
    • editor suggest, 自動補全、建議窗口

emment

https://docs.emmet.io/abbrevi...

編輯執行任務 tasks

命令面板輸入conf task

shell

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "echo Hello"
        }
    ]
}
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "echo",
            "args": [
                {
                    "value": "Hello World",
                    "quoting": "escape"
                }
            ]
        }
    ]
}

process

{
 "version": "2.0.0",
 "tasks": [
  {
   "label": "chrome",
   "type": "process",
   "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
   "windows": {
    "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
      },
      "linux": {
          "command": "/usr/bin/google-chrome"
      }
  }
 ]
}

group

{
 "version": "2.0.0",
 "tasks": [
  {
   "label": "test shell",
   "type": "shell",
   "command": "./scripts/test.sh",
   "windows": {
    "command": ".\\scripts\\test.cmd"
   },
   "group": "test",
   "presentation": {
    "reveal": "always",
    "panel": "new"
   },
   "options": {
    "cwd": "",
    "env": {},
    "shell": {
     "executable": "bash"
    }
   }
  }
 ]
}

安裝 quick task插件便於可視化

自定義問題分析器

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "echo",
            "args": [
                {
                    "value": "index.js:5:3: warning: unused variable",
                    "quoting": "escape"
                }
            ],
            "problemMatcher": {
                "owner": "echo",
                "fileLocation": ["relative", "${workspaceFolder}"],
                "pattern": {
                    "regexp": "^(.*):(\\d + ):(\\d + ):\\s + (warning|error):\\s + (.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

多任務

{
 "taskName": "compile",
 "dependsOn": [
  "frontend",
  "backend"
 ],
 "group": {
  "kind": "build",
  "isDefault": true
 }
}

更多資料

https://code.visualstudio.com...

調試

VS Code 爲插件做者提供了一套統一的接口,叫作Debug Adapter Protocol(DAP),插件最終實現調試功能。

自帶node調試插件Node Debug
需安裝chrome調試插件Debugger for Chrome

vscode 架構

圖片描述

Visual Studio Code / Egret Wing 技術架構

基於Electron(Chromium + node) electron應用結構

vscode源碼結構
VSCode 源碼閱讀

vscode 插件架構

圖片描述

  • 3個主要進程:

    • 第一次被啓動時會建立一個主進程(main process)
    • 每一個窗口都會建立一個渲染進程( Renderer Process)
    • 每一個窗口都會建立一個執行插件宿主進程(Extension Host)

還有兩種特殊的進程:

- 調試進程(Debug Adapter),渲染進程會經過 VS Code Debug Protocol 跟 Debug Adapter 進程通信。
- 語言支持(Language Server)

開發插件

VSCode插件開發急速入門

準備工做

確保安裝了Node.js和Git
而後安裝Yeoman和VS Code Extension Generator和VSCE:

npm install -g yo@latest generator-code vsce

註冊帳號 https://aka.ms/SignupAzureDevOps
登陸後User settings選擇Security,添加token,注意備份,以後要用

yo code myextension建立一個 VS Code 的插件模板,選擇類型
cd myextension && code .開始編輯

重要文件

- package.json 記錄了node應用和插件的信息
- extension.js 當前插件的所有代碼
- .vscode 官方提供的調試配置、任務配置等

編寫js/ts代碼插件(New Extension)

extension.js

const vscode = require('vscode');
//激活擴展程序時會調用此方法
//您的擴展程序在第一次執行命令時被激活 
function activate(context) {
    //使用控制檯輸出診斷信息(console.log)和錯誤(console.error)
    //此代碼行僅在激活擴展程序時執行一次 
    console.log('Congratulations, your extension "mdf" is now active!');
    //該命令已在package.json文件中定義
    //如今使用registerCommand提供命令的實現
    //commandId參數必須與package.json中的命令字段匹配 
    let disposable = vscode.commands.registerCommand('extension.helloWorld', function () {
        //每次執行命令時,都會執行此處放置的代碼
        vscode.window.showInformationMessage('Hello World!');//向用戶顯示消息框 
    });
    context.subscriptions.push(disposable);
}
exports.activate = activate;
//停用擴展程序時會調用此方法 
function deactivate() {}
module.exports = {
    activate,
    deactivate
}

package.json

  • engines 指定了運行這個插件須要的 VS Code 版本

    "vscode": "^1.29.0"
  • activationEvents 指定了什麼狀況下這個插件應該被加載而且激活

    "activationEvents": [
        "onCommand:extension.sayHello"
    ]
  • contributes VS Code 會把這個command命令註冊到命令面板中

    "contributes": {
        "commands": [
            {
                "command": "extension.sayHello",
                "title": "Hello World"
            }
        ]
    },

調試 F5(會再開一個vscode,請確保電腦內存充足)
查詢 API vscode.languages定義文件 vscode.d.ts

編寫快捷鍵插件 (Keymap)

只需編寫package.json

"contributes": {
    "commands": [
        {
            "command": "extension.sayHello",
            "title": "Hello World"
        }
    ],
   "keybindings": [
        {
            "key": "ctrl + t",
            "command": "extension.sayHello",
            "when": "editorTextFocus"
        }
    ]
},

示例:Notepad + + 源碼
注意事項:"activationEvents": ["*"]永遠激活插件可能影響性能,慎用。

編寫代碼片斷 (Code Snippets)

只需編寫 snippets/snippets.json(若不分享插件則本地命令面板輸入snippets便可編寫)
snippets.json

{
    "Print to console": {
        "prefix": "log",
        "body": [
            "console.log(${1:i});",
            "console.log(${1:i} + 1); // ${1:i} + 1",
            "$2"
        ],
        "description": "Log output to console"
    }
}

package.json

"contributes": {
    "snippets": [
        {
            "language": "javascript",
            "path": "./snippets/snippets.json"
        }
    ]
}

snippet-官網資料

編寫主題插件(New Color Theme)

編寫themes/mytheme-color-theme.json
以及package.json

"contributes": {
    "themes": [
        {
            "label": "mytheme",
            "uiTheme": "vs-dark",
            "path": "./themes/mytheme-color-theme.json"
        }
    ]
}

編寫語言支持(New Language Support)

  • tmLanguage:語言語法定義文件(正則搜索代碼並標註類型)參考文檔
  • Language id:語言惟一標識
  • Language name:語言名字
  • File extensions 文件後綴

package.json

  • configurations:./ language-configuration.json 語言的配置信息所在文件的相對地址
  • language-configuration.json 語言相關信息的模板
{
    "comments": {
        "lineComment": "//",// 單行註釋
        "blockComment": [ "/*", "*/" ]//多行註釋
    },
    "brackets": [// 支持的括號類型
        ["{", "}"],
        ["[", "]"],
        ["(", ")"]
    ],
    "autoClosingPairs": [// 鍵入時自動關閉的符號
        ["{", "}"],
        ["[", "]"],
        ["(", ")"],
        ["\"", "\""],
        ["'", "'"]
    ],
    "surroundingPairs": [// 可用於包圍選區的符號 
        ["{", "}"],
        ["[", "]"],
        ["(", ")"],
        ["\"", "\""],
        ["'", "'"]
    ],
    "folding": {//可被摺疊的代碼段的開頭和結尾
        "markers": {
            "start": "^\\s*//#region",
            "end": "^\\s*//#endregion"
        }
    },
    "wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\ + \\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\s] + )",//一個單詞
    "indentationRules": {//如何根據一行的內容來控制縮進
        "increaseIndentPattern": "^\\s*((begin|class|(private|protected)\\s + def|def|else|elsif|ensure|for|if|module|rescue|unless|until|when|while|case)|([^#]*\\sdo\\b)|([^#]*=\\s*(case|if|unless)))\\b([^#\\{;]|(\"|'|\/).*\\4)*(#.*)?$",
        "decreaseIndentPattern": "^\\s*(}\\]]?\\s*(#|$)|\\.[a-zA-Z_]\\w*\\b)|(end|rescue|ensure|else|elsif|when)\\b)"
    }
}

插件發佈

插件市場
使用vsce工具命令建立發佈帳號vsce create-publisher your-publisher-name
登陸帳號vsce login your-publisher-name
發佈vsce publish
發佈-官方文檔

官方demo

https://github.com/Microsoft/...

其餘教程

VSCode插件開發全攻略

API使用

工做臺API

  1. Information、Warning、Error消息
vscode.window.showInformationMessage('Hello World', 'Yes', 'No').then(value => {
    value=='Yes'&&vscode.window.showWarningMessage('User press ' + value);
    value=='No'&&vscode.window.showErrorMessage('User press ' + value);
})
  1. QuickPick

給用戶提供了一系列選項,而後根據用戶選擇的選項進行下一步的操做。

vscode.window.showQuickPick(['first', 'second', 'third']).then(value => {
   vscode.window.showInformationMessage('User choose ' + value);
})
vscode.commands.registerCommand('extension.sayHello', () => {
    vscode.window.showQuickPick([{
        label: 'first',
        description: 'first item',
        detail: 'first item details'
    }, {
        label: 'second',
        description: 'second item',
        detail: 'second item details'
    }]).then(value => {
        vscode.window.showInformationMessage('User choose ' + value.label);
    })
});

面板(Panel) API

  1. 問題面板
let collection = vscode.languages.createDiagnosticCollection('myextension');
    let uri = vscode.window.activeTextEditor.document.uri;
    collection.set(uri, [
        {
            range: new vscode.Range(0, 0, 0, 1),
            message: 'We found an error'
        }
    ]);
  1. 輸出面板
let channel =vscode.window.createOutputChannel('MyExtension');
channel.appendLine('Hello World');

調試面板
終端面板

視圖(TreeView) API

vscode.window.registerTreeDataProvider('myextension', {
    getChildren: (element) => {
        if (element) {
            return null;
        }

        return ['first', 'second', 'third'];
    },
    getTreeItem: (element) => {
        return {
            label: element,
            tooltip: 'my ' + element + ' item'
        }
    }
})

package.json的contributes

"contributes": {
        "views": {
   "explorer": [
    {
     "id": "myextension",
     "name": "My Extension"
                }
            ]
        }
    }

WebView API 來生成任意的編輯器內容
FileSystemProvider 或者 TextDocumentContentProvider 來爲 VS Code 提供相似於本地文件的文本內容

裝飾器(Decorations) API

let decorationType = vscode.window.createTextEditorDecorationType({
    backgroundColor: '#fff',
    border: '1px solid red;',
    fontStyle: 'italic',
    letterSpacing: '3px'
});
let editor = vscode.window.activeTextEditor;
editor.setDecorations(decorationType, [new vscode.Range(0, 0, 0, 1)]);

createTextEditorDecorationType(DecorationRenderOptions)

DecorationRenderOptions={
    //顏色和背景相關
    backgroundColor?: string | ThemeColor;
    color?: string | ThemeColor;
    overviewRulerColor?: string | ThemeColor;
    //邊框
    border?: string;
    borderColor?: string | ThemeColor;
    borderRadius?: string;
    borderSpacing?: string;
    borderStyle?: string;
    borderWidth?: string;
    //輪廓
    outline?: string;
    outlineColor?: string | ThemeColor;
    outlineStyle?: string;
    outlineWidth?: string;
    //字體
    fontStyle?: string;
    fontWeight?: string;
    opacity?: string;
    letterSpacing?: string;
    //其餘
    gutterIconPath?: string | Uri;
    gutterIconSize?: string;
    before?: ThemableDecorationAttachmentRenderOptions;
    after?: ThemableDecorationAttachmentRenderOptions;
}

ThemeColor

new vscode.ThemeColor('editorWarning.foreground')

插件參考:Rainbow Brackets 和 Indent Rainbow

插件 API 設計模式

發佈流程:

  • 提議(Proposal),API 在 vscode.proposed.d.ts文件中,
  • 維護團隊review,要點:

    • 插件 API 不會將 UI 直接暴露給插件。插件提供內容,VS Code 負責渲染。增量更新,儘量地減小 VS Code 從新渲染
    • 長時間運行的任務應該支持 Promise,並能夠取消
    • 插件 API 可以正確地處理對象的生命週期。VS Code 使用了 Dispose 模式,運行dispose能夠將這個對象銷燬。
  • 穩定版本(Stable), API 則是在 vscode.d.ts 裏

Node.js 模塊使用:

  • 使用模塊要剋制
  • treeshaking
  • Native Module:不用擔憂 Electron 升級的問題;不一樣的平臺要分別編譯
  • Web Assembly:沒法訪問系統 API

參考

極客時間-玩轉vscode

your-first-extension

相關文章
相關標籤/搜索