是否可以在VSCode中以编程方式将TextDocument设置为脏? [英] Is it possible to set TextDocument as dirty programatically in VSCode?

查看:0
本文介绍了是否可以在VSCode中以编程方式将TextDocument设置为脏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

openedDocument.setDirty()

推荐答案

没有直接的方法;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));

这篇关于是否可以在VSCode中以编程方式将TextDocument设置为脏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆