VSCode extension - how to alter file's text

后端 未结 4 1652
天涯浪人
天涯浪人 2021-02-20 12:56

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?



        
4条回答
  •  执笔经年
    2021-02-20 13:32

    Due to the issues I commented about in the above answer, I ended up writing a quick function that does multi-cursor friendly insert, and if the selection was empty, then it does not leave the inserted text selected afterwards (i.e. it has the same intuitive behavior as if you had pressed CTRL + V, or typed text on the keyboard, etc.)

    Invoking it is simple:

    // x is the cursor index, it can be safely ignored if you don't need it.
    InsertText(x => 'Hello World'); 
    

    Implementation:

    function InsertText(getText: (i:number) => string, i: number = 0, wasEmpty: boolean = false) {
    
        let activeEditor = vscode.window.activeTextEditor;
        if (!activeEditor) { return; }
    
        let sels = activeEditor.selections;
    
        if (i > 0 && wasEmpty)
        {
            sels[i - 1] = new vscode.Selection(sels[i - 1].end, sels[i - 1].end);
            activeEditor.selections = sels; // required or the selection updates will be ignored! 

提交回复
热议问题