-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
validator.ts
57 lines (51 loc) · 2.16 KB
/
validator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
TextDocument, Diagnostic, DiagnosticSeverity,
} from 'vscode-languageserver';
import { Observable, from } from 'rxjs';
import { map, filter, flatMap, toArray } from 'rxjs/operators';
import { validateText } from 'cspell';
export const diagnosticCollectionName = 'cSpell';
export const diagSource = diagnosticCollectionName;
export {validateText} from 'cspell';
import { CSpellUserSettings } from './cspellConfig';
import * as cspell from 'cspell';
export const defaultCheckLimit = 500;
const diagSeverityMap = new Map<string, DiagnosticSeverity>([
['error', DiagnosticSeverity.Error],
['warning', DiagnosticSeverity.Warning],
['information', DiagnosticSeverity.Information],
['hint', DiagnosticSeverity.Hint],
]);
export function validateTextDocument(textDocument: TextDocument, options: CSpellUserSettings): Promise<Diagnostic[]> {
return validateTextDocumentAsync(textDocument, options)
.pipe(toArray())
.toPromise();
}
export function validateTextDocumentAsync(textDocument: TextDocument, options: CSpellUserSettings): Observable<Diagnostic> {
const { diagnosticLevel = DiagnosticSeverity.Information.toString() } = options;
const severity = diagSeverityMap.get(diagnosticLevel.toLowerCase()) || DiagnosticSeverity.Information;
const limit = (options.checkLimit || defaultCheckLimit) * 1024;
const text = textDocument.getText().slice(0, limit);
return from<cspell.TextOffset[]>(validateText(text, options)).pipe(
flatMap(a => a),
filter(a => !!a),
map(a => a!),
// Convert the offset into a position
map(offsetWord => ({...offsetWord, position: textDocument.positionAt(offsetWord.offset) })),
// Calculate the range
map(word => ({
...word,
range: {
start: word.position,
end: ({...word.position, character: word.position.character + word.text.length })
}
})),
// Convert it to a Diagnostic
map(({text, range}) => ({
severity,
range: range,
message: `"${text}": Unknown word.`,
source: diagSource
})),
);
}