Create A New File At A Specific Location In VS Code With An Extension
This is what I want to do most of the time:
extension.ts
import * as vscode from 'vscode';
import path from 'path';
import os from 'os';
export function activate(context: vscode.ExtensionContext) {
const desktopDir = path.join(os.homedir(), "Desktop");
const tmpFilePath = path.join(desktopDir, "example.py");
const cmd: string = 'vs-code-auto-typer.autoTypeScript';
const disposable = vscode.commands.registerCommand(cmd, async () => {
const uri = vscode.Uri.parse(`untitled:${tmpFilePath}`);
const doc = await vscode.workspace.openTextDocument(uri);
await vscode.window.showTextDocument(doc, { preview: false });
const editor = await vscode.window.activeTextEditor;
const pos = new vscode.Position(0, 0);
if (editor) {
await editor.edit((editBuilder) => {
editBuilder.insert(
pos, `print("hello, new python file")`
);
});
}
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
-
This is for the
extension.ts
file that's created when you run:npx --package yo --package generator-code -- yo code
-
You'll need to update the
cmd
to match what you have in yourpackage.json file. -
You'll need to update the
path
to point to wherever you want the file to be prepped for saving on your machine.
-- end of line --
References
-
-
-
-
-
This is where I finally figured out that you can open an untitled file but just skipping the
uri
when calling openTextDocument -
Search for openTextDocument() to see the specifics for it.
-
The issue that led me to figuring out openTextDocument was the way to go.
-
-
-
-
-
-
-
-