【问题标题】:Implementing a "Save As" using the vscode API使用 vscode API 实现“另存为”
【发布时间】:2018-04-12 03:09:35
【问题描述】:

我一直在尝试找出使用 vscode 扩展 API 实现“另存为”的最佳方式。

到目前为止,这是我所拥有的最好的:

// First turn the path we were given into an absolute path
// Relative paths are interpreted as relative to the original file
const newFileAbsolutePath = path.isAbsolute(saveFileDetails.newPath) ?
    saveFileDetails.newPath :
    path.resolve(path.dirname(saveFileDetails.filePath), saveFileDetails.newPath);  
// Create an "untitled-scheme" path so that VSCode will let us create a new file with a given path
const newFileUri = vscode.Uri.parse("untitled:" + newFileAbsolutePath); 
// Now we need to copy the content of the current file,
// then create a new file at the given path, insert the content,
// save it and open the document
return vscode.workspace.openTextDocument(saveFileDetails.filePath)
    .then((oldDoc) => {
        return vscode.workspace.openTextDocument(newFileUri)
            .then((newDoc) => {
                return vscode.window.showTextDocument(newDoc, 1, false)
                    .then((editor) => {
                        return editor.edit((editBuilder) => {
                            editBuilder.insert(new vscode.Position(0, 0), oldDoc.getText());
                        })
                        .then(() => {
                            return newDoc.save()
                                .then(() => EditorOperationResponse.Completed);
                        });
                    });
            });
    });

我们打开旧文档,然后打开一个新文档(即无标题文档),然后将旧文档的文本插入到新文档中,然后保存新文档。

然后新文档关闭(出于某种原因)。

有人有什么建议吗?

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:

    这似乎是一个已知问题,由使用untitled:// 方案引起:

    TextDocument.save() closes untitled documents (#29156)

    目前,您可以通过再次重新打开文件来解决此问题,因为您知道最终的 URI(与报告问题的人不同)。

    newDoc.save().then((completed) => {
        const finalUri = vscode.Uri.file(newFileAbsolutePath);
        vscode.workspace.openTextDocument(finalUri).then((doc) => {
            vscode.window.showTextDocument(doc, {preview: false});
        })
    });
    

    不幸的是,这确实会导致明显的“闪烁”效果。为了避免这种情况,我建议简单地绕过 VSCode API 并使用 fs 进行文件 IO,仅使用 vscode 在末尾显示文件。这也大大简化了代码:

    import * as fs from 'fs';
    
    function runCommand() {
        // obtain newFileAbsolutePath / oldFileAbsolutePath
    
        var oldDocText = fs.readFileSync(oldFileAbsolutePath);
        fs.writeFileSync(newFileAbsolutePath, oldDocText);
    
        const finalUri = vscode.Uri.file(newFileAbsolutePath);
        vscode.workspace.openTextDocument(finalUri).then((doc) => {
            vscode.window.showTextDocument(doc, {preview: false});
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 2011-10-07
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多