我正在尝试创建一个简单的vscode扩展,它将将一些默认文本插入到新创建的文件中。我想要的是vscode.workspace.createFileSystemWatcher调用一个获取activeTextEditor并写入新文件的函数。以下是我尝试过的:
import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand(
"default-text-generator.generate",
() => {
function _watcherChangeApplied(editor?: vscode.TextEditor) {
if (editor) {
editor.edit((editBuilder) => {
editBuilder.insert(editor.selection.active, "Hello World");
});
}
}
const editor = vscode.window.activeTextEditor;
let uri: vscode.Uri | undefined = editor?.document.uri;
if (uri) {
let watcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(
vscode.workspace.getWorkspaceFolder(uri)!,
"**/*.ts"
),
false,
false,
false
);
watcher.onDidCreate(() => _watcherChangeApplied(editor));
}
}
);
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate(): void {
//deactivate
}这是正在发生的事情。编辑器似乎插入了文本,然后立即被覆盖回空白页。我好像搞不懂为什么。
发布于 2022-11-06 22:51:46
之所以会出现这个问题,是因为您所指的editor不是您所认为的那样。在创建新的.ts文件时,您关注的不是新创建的编辑器,而是您所关注的/活动的编辑器。
FileSystemWatcher.onDidCreate事件为工作区内新创建的文件提供了一个Uri,但不一定是在VS代码中打开的。尝试通过终端创建一个文件,你就会明白我的意思。文件被创建,事件被触发,但是VS代码中没有打开任何编辑器。
因此,您将无法使用editor.edit API来操作该文件。相反,您应该使用RAW/Node函数编辑文件。但是,在这种情况下,您可能/可能会与创建.ts文件的外部工具发生冲突(如果使用FileWatcher,这可能不是VS代码)。如果只能检测到通过VS代码创建的文件,则应改为workspace.onDidCreateFiles事件。但是,它也只为您提供Uri,而不是Editor。
希望这能有所帮助
发布于 2022-11-06 23:39:09
这样做是可行的:
let disposable2 = vscode.commands.registerCommand('yourCommand.here', async (...file) => {
async function _watcherChangeApplied(uri) {
if (uri) {
const editor = await vscode.window.showTextDocument(uri);
editor.edit((editBuilder) => {
editBuilder.insert(editor.selection.active, "Hello World");
});
await editor.document.save();
}
}
const editor = vscode.window.activeTextEditor;
let uri = editor?.document.uri;
if (uri) {
let watcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(
vscode.workspace.getWorkspaceFolder(uri),
"**/*.ts"
),
false,
false,
false
);
// watcher.onDidCreate(() => _watcherChangeApplied(editor));
watcher.onDidCreate((uri) => _watcherChangeApplied(uri));
}
}关键是watcher.onDidCreate()将返回新创建的文件的uri。您可以将它传递给您的_watcherChangeApplied(uri)函数。
在_watcherChangeApplied(uri)中,您可以通过await vscode.window.showTextDocument(uri)显示创建的文件,该函数返回一个可以与其edit函数一起使用的editor。
无论是在vscode中创建文件(比如浏览器顶部的New File...图标按钮)还是通过终端(比如touch test.ts),代码都可以工作。
如果希望启用通过终端创建新文件,而不打开它们,请尝试以下_watcherChangeApplied(uri)
async function _watcherChangeApplied(uri) {
if (uri) {
const document = await vscode.workspace.openTextDocument(uri);
const strToAdd = "Hello World";
const wse = new vscode.WorkspaceEdit();
wse.insert(uri, new vscode.Position(0,0), strToAdd);
await vscode.workspace.applyEdit(wse);
await document.save();
}
}https://stackoverflow.com/questions/74339446
复制相似问题