Visual Studio Code Authoring Extension - Highlighted Text to File
06/19/2024, WedWrite Selected Text to the Contents of a File
A common operation that a vscode extension might encounter is the need to write to an external file. The following example will show how this is performed using
the vscode.workspace.fs.writeFile
method.
After one generates a sample starter vscode extension as is described in the official vscode authoring start guide, one would have the code similar to the following if the TypeScript option is used.
// 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';
// 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 "test" 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('test.helloWorld', () => {
// 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 from test!');
});
context.subscriptions.push(disposable);
}
// This method is called when your extension is deactivated
export function deactivate() {}
To create the 'write to file' functionality, we start by checking if a workspace editor is active first. This ensures that there might be a working document to get highlighted text from in order to write to a new file.
// 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';
// 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 "test" 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('test.helloWorld', () => {
// Check the current editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const workspace = vscode.window;
if (!workspace.activeTextEditor) {
vscode.window.showErrorMessage('A workspace must be opened.');
}
});
context.subscriptions.push(disposable);
};
// This method is called when your extension is deactivated
export function deactivate() {}
After the editor is verified, one can get the highlighted text and save it to a new file.
// 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';
// 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 "test" 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('test.helloWorld', () => {
// Check the current editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const workspace = vscode.window;
if (!workspace.activeTextEditor) {
vscode.window.showErrorMessage('A workspace must be opened.');
}
const selection = editor.selection;
// Get the current highlighted selection
const selectionRange = new vscode.Range(selection.start, selection.end);
const highlightedText = editor.document.getText(selectionRange);
// Filename
const fileName = 'test.md';
// Write the contents and save the file
const filePath = vscode.Uri
.file(`${context.extensionPath}/tmp/${fileName}`);
vscode.workspace.fs.writeFile(filePath, Buffer
.from(highlightedText)).then(() => {
console.log(`New file ${filePath} created successfully.`);
});
});
context.subscriptions.push(disposable);
}
// This method is called when your extension is deactivated
export function deactivate() {}
Assuming the vscode dev extension, Extension Test Runner is installed running, press F5 to activate the development window.
Create a new document tab and add some text to that window. Highlight some text in that window and press Ctrl + Shift + p
and type in the command that was defined in the contributes > commands
key within
the package.json file to look for the extension's command.
Press enter to run the command and then the file will save to a "tmp" folder within the vscode extension folder.