VSCode 扩展 - 如何更改文件的文本 [英] VSCode extension - how to alter file's text

查看:44
本文介绍了VSCode 扩展 - 如何更改文件的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展程序,可以获取打开文件的文本并对其进行更改.更改文本后,如何将其放回 VSCode 中显示的文件中?

I have an extension that grabs the open file's text and alters it. Once the text is altered, how do I put it back into the file that is displayed in 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 "myExtension" is now active!');
  console.log(process.versions);

  // 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.myExtension', () => {
    // The code you place here will be executed every time your command is executed

    let activeEditor = vscode.window.activeTextEditor;
    if (!activeEditor) {
      return;
    }
    let text = activeEditor.document.getText();

    getAsyncApi(text).then((textToInsertIntoDoc) => {

      let finaldoc = insertTextIntoDoc(text, textToInsertIntoDoc);

      // not what I want - just used to see new text
      vscode.window.showInformationMessage(textToInsertIntoDoc);
    });

  });

  context.subscriptions.push(disposable);
}

推荐答案

这是 Rebornix 扩展示例(包含在一组 Microsoft 扩展示例中)中主要功能的修订版,用于处理您提出的选择问题.它反转选择的内容(留下选择),或者如果选择为空,它将反转该选择处光标下的单词而不保留任何选择.离开选择通常是有意义的,但您可以添加代码来删除选择.

This is a revision of the main function in Rebornix's extension sample (included with the set of Microsoft extension samples) that handles the selection issues you raised. It reverses the content of the selection(s) (leaving the selections) or if a selection is empty it will reverse the word under the cursor at that selection without leaving anything selected. It often makes sense to leave a selection, but you can add code to remove selection.

    let disposable = vscode.commands.registerCommand('extension.reverseWord', function () {
        // Get the active text editor
        const editor = vscode.window.activeTextEditor;

        if (editor) {
            const document = editor.document;
            editor.edit(editBuilder => {
                editor.selections.forEach(sel => {
                    const range = sel.isEmpty ? document.getWordRangeAtPosition(sel.start) || sel : sel;
                    let word = document.getText(range);
                    let reversed = word.split('').reverse().join('');
                    editBuilder.replace(range, reversed);
                })
            }) // apply the (accumulated) replacement(s) (if multiple cursors/selections)
        }
    });

诚然,虽然我可以通过将 .selection 设置为一个新的空选择来删除单个选择,该选择似乎不适用于 .selections[i].但是您可以在没有选择的情况下进行多项更改.

Admittedly, while I could remove a single selection by setting .selection to a new empty selection that doesn't seem to work with .selections[i]. But you can make multiple changes without having selections in the first place.

您不想做的是通过代码进行选择只是为了通过代码更改文本.用户进行选择,而您不进行选择(除非该功能的最终目的是进行选择).

What you don't want to do is make a selection through code just to alter text through code. Users make selections, you don't (unless the end purpose of the function is to make a selection).

我来到这个问题是想寻找一种方法来应用 textEdit[] 数组(通常由 provideDocumentRangeFormattingEdits 回调函数返回).如果您在数组中构建更改,您可以在您自己的函数中将它们应用到您的文档:

I came to this question looking for a way to apply a textEdit[] array (which is normally returned by a provideDocumentRangeFormattingEdits callback function). If you build changes in the array you can apply them to your document in your own function:

        const { activeTextEditor } = vscode.window;

        if (activeTextEditor) {
            const { document } = activeTextEditor;
            if (document) {
                /*
                  build your textEdits similarly to the above with insert, delete, replace 
                  but not within an editBuilder arrow function
                const textEdits: vscode.TextEdit[] = [];
                textEdits.push(vscode.TextEdit.replace(...));
                textEdits.push(vscode.TextEdit.insert(...));
                */

                const workEdits = new vscode.WorkspaceEdit();
                workEdits.set(document.uri, textEdits); // give the edits
                vscode.workspace.applyEdit(workEdits); // apply the edits
            }
        }

这是将编辑应用到文档的另一种方式.即使我在没有选择文本的情况下让 editBuilder 示例正常工作,我在其他情况下也遇到了选择问题.WorkspaceEdit 不会选择更改.

So that's another way to apply edits to a document. Even though I got the editBuilder sample to work correctly without selecting text, I have had problems with selections in other cases. WorkspaceEdit doesn't select the changes.

这篇关于VSCode 扩展 - 如何更改文件的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆