首页 > 解决方案 > 在光标位置插入预定义文本

问题描述

我想在光标位置插入一些文本,但在 API 文档中没有找到所需的代码。是否有任何函数可以将参数放入其中,从而解决我的问题?这只是为了测试。

import * as vscode from 'vscode';
var fs = require('fs');
var flow = require('xml-flow');
var inFile = fs.createReadStream('./your-xml-file.xml');
var xmlStream = flow(inFile);

// 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 "intrexx-js-lib" 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('intrexx-js-lib.start', () => {

        const editor = vscode.window.activeTextEditor;
        if(!editor){
            vscode.window.showErrorMessage("Editor does not exist!");
            return;
        }

        if (editor.selection.isEmpty) {
            const position:vscode.Position = editor.selection.active;
            //vscode.window.showInformationMessage(`line: ${position.line} character: ${position.character}`);

        }

    });


    context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {}

标签: visual-studio-codevscode-extensions

解决方案


使用不同的命令寄存器功能,它为您提供TextEditorEdit

vscode.commands.registerTextEditorCommand('intrexx-js-lib.start', (editor, edit) => {
    let text = "FooBar";
    edit.replace(editor.selection, text);
});

要与多个游标一起使用,您必须遍历editor.selections

vscode.commands.registerTextEditorCommand('intrexx-js-lib.start', (editor, edit) => {
    editor.selections.forEach((selection, i) => {
        let text = "FooBar " + i
        edit.replace(selection, text)
    })
});

推荐阅读