Недавно я рассказывал о своем Консольном журнале VS Code Extension.

Вот как я это сделал.

Установка HelloWorld

Сначала я настроил их HelloWorld https://code.visualstudio.com/docs/extensions/example-hello-world

$ cd ~/.vscode/extensions
$ npm install -g yo generator-code
$ yo code 

? What type of extension do you want to create? New Extension (JavaScript)
? What's the name of your extension? Console Log
? What's the identifier of your extension? console-log
? What's the description of your extension? it console logs
? What's your publisher name (more info: https://code.visualstudio.com/docs/tools/vscecli#_publishing-ext
ensions)? Kevin
? Enable JavaScript type checking in 'jsconfig.json'? No
? Initialize a git repository? (Y/n)n

Затем на какое-то время запустится npm install.

$ cd console-log
$ code .

Теперь в VS Code

откройте ‘extension.js’ ›нажмите Shift + Cmd + P› выберите Hello World

Теперь вы видите Hello World внизу экрана в информационном сообщении. Расширение работает.

Внесение изменений по крупицам

Моя цель состояла в том, чтобы выделить какой-то текст и сохранить этот текст в console.log.

Однако на данный момент все, что происходит, это то, что отображается Hello World.

Вот шаги, которые мы предпримем, чтобы добраться от того места, где мы сейчас находимся к приведенной выше гифке.

  1. Измените сообщение, отображаемое в информационном сообщении
  2. Показывать выделенный текст в информационном сообщении
  3. Показывать последнее выражение console.log («highlightedText», highlightedText) в информационном сообщении
  4. замените выделенный текст последним выражением console.log («highlightedText», highlightedText)
  5. Обновите имя выражения с Hello World до журнала консоли

Шаг 1. Измените сообщение, отображаемое в информационном сообщении

//extension.js
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// 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 "console-log" 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 = vscode.commands.registerCommand('extension.sayHello', function () {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;

обновить выделенную строку, чтобы она была

vscode.window.showInformationMessage('Hello Betty!');

Теперь, прежде чем снова запустить Hello World, нам нужно перезагрузить окно. Мы должны делать это каждый раз

Cmd + Shift + p ›Обновить окно

Cmd + Shift + p ›Привет, мир!

Переходим к шагу 2!

Шаг 2. Показать выделенный текст в информационном сообщении

Итак, чтобы получить доступ к текущему текстовому редактору, нам нужно добавить следующие строки (выделенные жирным шрифтом) в

//extension.js
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// 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 "console-log" 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 = vscode.commands.registerCommand('extension.sayHello', function () {
// The code you place here will be executed every time your command is executed
const editor = vscode.window.activeTextEditor
const selection = editor.selection
const text = editor.document.getText(selection)
// Display a message box to the user
vscode.window.showInformationMessage(text);
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;

Давайте немного распакуем этот раздел

const editor = vscode.window.activeTextEditor
const selection = editor.selection
const text = editor.document.getText(selection)

editor - текущий редактор, в котором находится пользователь.



selection - тогда выделенный текст в этом редакторе.



и, наконец, это выделение является объектом, и чтобы получить из него текст, нам нужно использовать getText



Все это я получил, просмотрев другие примеры и погрузившись в вышеупомянутый API, с которым я довольно много боролся (почему они не приводят примеры использования ???). Но в конце концов я попал туда. Итак, давайте запустим это сейчас.

Выделите в тексте слово «редактор».

Cmd + Shift + p ›Обновить окно

Cmd + Shift + p ›Привет, мир!

Шаг 3. Покажите последнее выражение console.log («highlightedText», highlightedText) в информационном сообщении

//extension.js
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// 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 "console-log" 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 = vscode.commands.registerCommand('extension.sayHello', function () {
// The code you place here will be executed every time your command is executed
const editor = vscode.window.activeTextEditor
const selection = editor.selection
const text = editor.document.getText(selection)
const newText = `console.log('${text}', ${text})
// Display a message box to the user
vscode.window.showInformationMessage(newText);
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
let wonderfulShow = 'The Young Offenders'
wonderfulShow

так что наше добавленное заявление здесь

const newText = `console.log('${text}', ${text})`

Это строковый шаблон ES6



Старый способ сделать это было бы

"console.log('" + text + "', " + text + ")"

Теперь мы ищем актуальные вещи для публикации, давайте добавим кое-что в конец документа.

let wonderfulShow = 'The Young Offenders'
wonderfulShow

Давай проверим это

выделить замечательноПоказать

Cmd + Shift + p ›Обновить окно

Cmd + Shift + p ›Привет, мир!

Шаг 4. Замените выделенный текст последним выражением console.log («highlightedText», highlightedText)

Теперь у нас есть текст, нам просто нужно вернуть его в редактор.

//extension.js
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// 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 "console-log" 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 = vscode.commands.registerCommand('extension.sayHello', function () {
// The code you place here will be executed every time your command is executed
const editor = vscode.window.activeTextEditor
const selection = editor.selection
const text = editor.document.getText(selection)
const newText = `console.log('${text}', ${text})
editor.edit(builder => builder.replace(selection, newText))
// Display a message box to the user

vscode.window.showInformationMessage(newText);
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
let wonderfulShow = 'The Young Offenders'
wonderfulShow

Код для редактирования кода в редакторе:

editor.edit(builder => builder.replace(selection, newText))

Эту функцию редактирования я нашел в этом выпуске на github.



edit принимает функцию в качестве аргумента, builder.replace принимает два аргумента, первый аргумент - текст для замены, а второй аргумент - текст замены.

Давай проверим это

выделить замечательноПоказать

Cmd + Shift + p ›Обновить окно

Cmd + Shift + p ›Привет, мир!

Успех. Теперь мы можем закомментировать

// vscode.window.showInformationMessage(newText);

Шаг 5. Обновите имя выражения с Hello World до журнала консоли (последний шаг !!!)

Имя функции расширения по умолчанию - sayHello, а Hello World отображается как ее имя.

Последний шаг

Cmd + Shift + F

Найти: sayHello

Заменить: consoleLog

Заменить все (значок справа от consoleLog на изображении ниже)

Находка: Привет, мир

Заменить: журнал консоли

Заменить все

Готово! Поздравляю.