问题
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