【问题标题】:TextEditorEdit.replace is async, how to execute code when it is finished?TextEditorEdit.replace 是异步的,完成后如何执行代码?
【发布时间】:2017-07-12 00:44:13
【问题描述】:

在开发this VS Code extension 时,我不得不将光标移动到我使用vscode.window.activeTextEditor.edit 方法创建的一行,但后来我意识到当我尝试移动光标时该行不存在,所以我必须输入setTimeout 才能尝试移动光标:

let editor: TextEditor = vscode.window.activeTextEditor;
let selections: Selection[] = editor.selections;
let doc: TextDocument = editor.document;

editor.edit(function (edit: TextEditorEdit): void {
    selections.forEach((selection: Selection, index: number) => {
        for (let i = selection.start.line; i <= selection.end.line; i++) {
            let selLine: TextLine = doc.lineAt(i);
            let insertPos: Range = selLine.range;
            let insertLineText: string = selLine.text;

            // This is async :(
            edit.replace(insertPos, insertSemicolon(insertLineText, newLine));
        }
    });

    if (newLine) {
        // Move cursor to the next line
        setTimeout(() => {
            vscode.commands.executeCommand("cursorMove", {
                to: "down",
                by: "wrappedLine",
                select: false,
                value: 1
            }).then(() => {
                vscode.commands.executeCommand("cursorMove", {
                    to: "wrappedLineEnd",
                    by: "wrappedLine",
                    select: false
                })
            });
        }, 50);
    }
});

我知道这不是一个好习惯,因为我不能确定代码执行时该行是否存在,我试图找到一种方法来仅在编辑完成时执行此代码替换一切。

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:

    您需要将光标操作移到编辑块之外。 TextEditor.edit 中的回调建立了一组编辑,然后异步应用这些编辑。 edit 返回一个Thenable&lt;boolean&gt; 以指示编辑是否成功完成。

    尝试类似:

    let editor: TextEditor = vscode.window.activeTextEditor;
    let selections: Selection[] = editor.selections;
    let doc: TextDocument = editor.document;
    
    editor.edit(function (edit: TextEditorEdit): void {
        selections.forEach((selection: Selection, index: number) => {
            for (let i = selection.start.line; i <= selection.end.line; i++) {
                let selLine: TextLine = doc.lineAt(i);
                let insertPos: Range = selLine.range;
                let insertLineText: string = selLine.text;
    
                edit.replace(insertPos, insertSemicolon(insertLineText, newLine));
            }
        });
    }).then(success => {
        if (!success) {
            return
        }
         if (newLine) {
            // Move cursor to the next line
            ...
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      相关资源
      最近更新 更多