【问题标题】:Insert predefined text at cursor position在光标位置插入预定义文本
【发布时间】:2021-01-08 07:55:03
【问题描述】:

我想在光标的位置插入一些文本,但在 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-code vscode-extensions


    【解决方案1】:

    虽然rioV8 的代码有效,但如果选择了任何文本,它将覆盖该文本。如果要确保插入操作不会删除任何文本,请改用edit.insert。对于 rioV8 的第二个示例,这意味着这样做:

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

    【讨论】:

    • 在编辑中注意我为获得 javavscript 语法着色所做的工作。
    【解决方案2】:

    使用不同的命令注册函数,它会给你一个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)
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 2010-11-07
      相关资源
      最近更新 更多