user14772481
user14772481

Reputation:

How to insert text in a file for a VSCode Extension

I am developing a VSCode extension.

I want to know how I can find a file by name and add text to it. I am not adding any code since there is nothing in it that would be useful ;).

The VSCode API Documentation is so confusing that I almost decided on making a tutorial after I learn it.

Upvotes: 3

Views: 2137

Answers (1)

Nishan
Nishan

Reputation: 4421

Little late but I'm gonna leave this here for somebody else in need. To enter text to active editor you can use TextEditorEdit.insert() method. [doc]

function enterText(text: string) {
    const editor = vscode.window.activeTextEditor;
    if (editor) {
        editor.edit(editBuilder => {
            editBuilder.insert(editor.selection.active, text);
        });
    }
}

insert() takes two arguments,

  • location: Position - The position where the new text should be inserted.
  • value: string - The new text this operation should insert.

In my example text is inserted to the currunt curser position. But if you want to add text to the beginning of the file, you can do,

editBuilder.insert(new vscode.Position(0, 0), text);

Upvotes: 7

Related Questions