Vsnips icon indicating copy to clipboard operation
Vsnips copied to clipboard

VSCode编辑器会在editor更新后, 再发送一次事件

Open corvofeng opened this issue 3 years ago • 0 comments

VSCode的行为很奇怪:

针对有prefix的代码片段, 因为我们调用编辑器做了一次修改, 将原始的prefix删除了, 具体代码见:

https://github.com/corvofeng/Vsnips/blob/eb2e0d7559572d40055a9033390851ec211d8cb1/src/script_tpl.ts#L294

  if (prefix !== "") {
    const editor = vsContext.getActiveEditor();
    if (editor !== undefined) {
      const startPos = new Position(vsContext.position.line, 0);
      const endPos = vsContext.position;
      editor.edit((te) => {
        te.delete(new Range(startPos, endPos));
      });
    }

本身这次修改应该在snip插入前进行, 但是VSCode的行为有些奇怪,

在我们添加了监听器之后, 将这次修改的change又重新传给了我们的监听器, 由于这个行为的存在, 导致我们的状态需要在处理过prefix删除事件后再同步一次, 具体的代码如下,

  public initSnip(leftUpPos: vscode.Position) {
    if (this.prefix == "") {
      this.blockSynced = true;
    } else {
      this.blockSynced = false;
    }
  }

  public doChange(ch: vscode.TextDocumentContentChangeEvent): boolean {
    if (ch.range.start.line === this.leftUpPos.line &&
      (ch.range.end.character - ch.range.start.character) === this.prefix.length &&
      ch.rangeLength === this.prefix.length &&
      ch.text === ""
    ) {
      Logger.debug("Current delete the old exist prefix, just return");
      // 这里是prefix的删除事件, 处理完此事件后, 我们才会认为vscode完成了同步 #38
      this.blockSynced = true;
      return false;
    }
   // ....
  }

因为VSCode这个行为的异常, 导致了这部分代码很不优雅...

corvofeng avatar Sep 23 '21 13:09 corvofeng