23

How can I open a new read-only text file in tab and insert some formatted text in that file using the Visual Studio Code API?

I didnt find any example regarding this to add simple text

Following is my code that opens some untitled file.

var setting: vscode.Uri = vscode.Uri.parse("untitled:" + "C:\summary.txt");
vscode.workspace.openTextDocument(setting).then((a: vscode.TextDocument) => {
    vscode.window.showTextDocument(a, 1, false);
}, (error: any) => {
    console.error(error);
    debugger;
});

Please give the simple example that can be added to these lines to add the text. As the official examples are little complex.

Gama11
  • 31,714
  • 9
  • 78
  • 100
Shan Khan
  • 9,667
  • 17
  • 61
  • 111
  • 1
    do not use `Uri.parse` for files. Use `Uri.file`. File name/path might contain `#` character – rioV8 Feb 20 '20 at 16:16

2 Answers2

40

The following should give you the idea

...
var setting: vscode.Uri = vscode.Uri.parse("untitled:" + "C:\summary.txt");
vscode.workspace.openTextDocument(setting).then((a: vscode.TextDocument) => {
    vscode.window.showTextDocument(a, 1, false).then(e => {
        e.edit(edit => {
            edit.insert(new vscode.Position(0, 0), "Your advertisement here");
        });
    });
}, (error: any) => {
    console.error(error);
    debugger;
});
...
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
5

In adition to DAXaholic's answer, If you want to insert text to the active editor, vscode.window.activeTextEditor can be used.

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

In my example text is inserted to the currunt curser position.

Nishan
  • 3,644
  • 1
  • 32
  • 41