Create A New File At A Specific Location In VS Code With An Extension
October 2024
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() {}Notes
-
This is for the
extension.tsfile that's created when you run: -
You'll need to update the
cmdto match what you have in yourpackage.jsonfile. -
You'll need to update the
pathto 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.