是否可以在VSCode中以编程方式将TextDocument设置为脏?

时间:2018-04-24 00:41:52

标签: visual-studio-code vscode-extensions

是否可以在VSCode中以编程方式将TextDocument设置为脏?像

这样的东西
openedDocument.setDirty()

1 个答案:

答案 0 :(得分:0)

没有直接的方法可以做到; TextDocument.isDirty是只读属性。

但是,我整理了一种变通方法,该设置通过进行无效的设置来设置isDirty(已通过VSCode 1.37.1测试):

// 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));