-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
diagnostics.ts
67 lines (53 loc) · 2.46 KB
/
diagnostics.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
57
58
59
60
61
62
63
64
65
66
67
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/** To demonstrate code actions associated with Diagnostics problems, this file provides a mock diagnostics entries. */
import * as vscode from 'vscode';
/** Code that is used to associate diagnostic entries with code actions. */
export const EMOJI_MENTION = 'emoji_mention';
/** String to detect in the text document. */
const EMOJI = 'emoji';
/**
* Analyzes the text document for problems.
* This demo diagnostic problem provider finds all mentions of 'emoji'.
* @param doc text document to analyze
* @param emojiDiagnostics diagnostic collection
*/
export function refreshDiagnostics(doc: vscode.TextDocument, emojiDiagnostics: vscode.DiagnosticCollection): void {
const diagnostics: vscode.Diagnostic[] = [];
for (let lineIndex = 0; lineIndex < doc.lineCount; lineIndex++) {
const lineOfText = doc.lineAt(lineIndex);
if (lineOfText.text.includes(EMOJI)) {
diagnostics.push(createDiagnostic(doc, lineOfText, lineIndex));
}
}
emojiDiagnostics.set(doc.uri, diagnostics);
}
function createDiagnostic(doc: vscode.TextDocument, lineOfText: vscode.TextLine, lineIndex: number): vscode.Diagnostic {
// find where in the line of that the 'emoji' is mentioned
const index = lineOfText.text.indexOf(EMOJI);
// create range that represents, where in the document the word is
const range = new vscode.Range(lineIndex, index, lineIndex, index + EMOJI.length);
const diagnostic = new vscode.Diagnostic(range, "When you say 'emoji', do you want to find out more?",
vscode.DiagnosticSeverity.Information);
diagnostic.code = EMOJI_MENTION;
return diagnostic;
}
export function subscribeToDocumentChanges(context: vscode.ExtensionContext, emojiDiagnostics: vscode.DiagnosticCollection): void {
if (vscode.window.activeTextEditor) {
refreshDiagnostics(vscode.window.activeTextEditor.document, emojiDiagnostics);
}
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
refreshDiagnostics(editor.document, emojiDiagnostics);
}
})
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, emojiDiagnostics))
);
context.subscriptions.push(
vscode.workspace.onDidCloseTextDocument(doc => emojiDiagnostics.delete(doc.uri))
);
}