Why I have error overlapping range is not allowed?

二次信任 提交于 2021-01-29 09:25:29

问题


I am building formatter extension. Unfortunately I cannot find a lot of examples how to tackle simple tasks.

This is my files Formatter provider and I try to capitalize some keywords. This works first time after extension refresh but not second time.

What did I do wrong?

'use strict';
import * as vscode from 'vscode';

export class STFormatterProvider implements vscode.DocumentFormattingEditProvider {

    public out: Array<vscode.TextEdit> = [];

    provideDocumentFormattingEdits(document: vscode.TextDocument) {
        this.capitalize(document);

        return this.out;
    }

    capitalize(document: vscode.TextDocument) {
        let keywords = ['true', 'false', 'exit', 'continue', 'return', 'constant', 'retain'];

        for (let line = 0; line < document.lineCount; line++) {
            const element = document.lineAt(line);
            let regEx = new RegExp(`\\b(${keywords.join('|')})\\b`, "ig");
            let result = element.text.match(regEx);
            if (result && result.length > 0) {
                let str = element.text.replace(regEx, (match, content) => {
                    return match.toUpperCase();
                });

                this.out.push(
                    vscode.TextEdit.replace(element.range, str)
                );
            }
        }
    }
}

回答1:


The main reason you have this overlap range is that you don't reset the out array.

I have also performed a few other refactors

class STFormatterProvider implements vscode.DocumentFormattingEditProvider {

  public out: Array<vscode.TextEdit> = [];

  provideDocumentFormattingEdits(document: vscode.TextDocument) {
      this.out = [];
      this.capitalize(document);
      return this.out;
  }

  capitalize(document: vscode.TextDocument) {
      let keywords = ['true', 'false', 'exit', 'continue', 'return', 'constant', 'retain'];

      let regEx = new RegExp(`\\b(${keywords.join('|')})\\b`, "ig");
      for (let lineNr = 0; lineNr < document.lineCount; ++lineNr) {
          const line = document.lineAt(lineNr);
          if (regEx.test(line.text)) {
              let str = line.text.replace(regEx, (match) => { return match.toUpperCase(); });
              this.out.push( vscode.TextEdit.replace(line.range, str) );
          }
      }
  }
}


来源:https://stackoverflow.com/questions/62618542/why-i-have-error-overlapping-range-is-not-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!