【发布时间】:2018-04-24 00:41:52
【问题描述】:
是否可以在 VSCode 中以编程方式将 TextDocument 设置为脏?类似的东西
openedDocument.setDirty()
【问题讨论】:
-
这真的很棒 - 特别是当缓冲区没有实际文件支持时
标签: visual-studio-code vscode-extensions
是否可以在 VSCode 中以编程方式将 TextDocument 设置为脏?类似的东西
openedDocument.setDirty()
【问题讨论】:
标签: visual-studio-code vscode-extensions
没有直接的方法可以做到这一点; TextDocument.isDirty 是只读属性。
但是,我通过进行无效的编辑(使用 VSCode 1.37.1 测试)来设置 isDirty 的解决方法:
// Set the dirty bit on 'textEditor'. This is meant to be called as a
// text editor command.
async function setDirty(textEditor: TextEditor, editBuilder: TextEditorEdit)
: Promise<void>
{
// The strategy here is to make a change that has no effect. If the
// document has text in it, we can replace some text with itself
// (simply inserting an empty string does not work). We prefer to
// edit text at the end of the file in order to minimize spurious
// recomputation by analyzers.
// Try to replace the last line.
if (textEditor.document.lineCount >= 2) {
const lineNumber = textEditor.document.lineCount-2;
const lastLineRange = new Range(
new Position(lineNumber, 0),
new Position(lineNumber+1, 0));
const lastLineText = textEditor.document.getText(lastLineRange);
editBuilder.replace(lastLineRange, lastLineText);
return;
}
// Try to replace the first character.
const range = new Range(new Position(0, 0), new Position(0, 1));
const text = textEditor.document.getText(range);
if (text.length > 0) {
editBuilder.replace(range, text);
return;
}
// With an empty file, we first add a character and then remove it.
// This has to be done as two edits, which can cause the cursor to
// visibly move and then return, but we can at least combine them
// into a single undo step.
await textEditor.edit(
(innerEditBuilder: TextEditorEdit) => {
innerEditBuilder.replace(range, " ");
},
{ undoStopBefore: true, undoStopAfter: false });
await textEditor.edit(
(innerEditBuilder: TextEditorEdit) => {
innerEditBuilder.replace(range, "");
},
{ undoStopBefore: false, undoStopAfter: true });
}
在您的 activate 函数中,将其与以下内容挂钩:
context.subscriptions.push(
commands.registerTextEditorCommand("extension.setDirty", setDirty));
【讨论】: