forked from whtouche/vscode-js-console-utils
-
Notifications
You must be signed in to change notification settings - Fork 2
/
extension.js
90 lines (69 loc) · 2.8 KB
/
extension.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const vscode = require('vscode');
const insertText = (val) => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('Can\'t insert log because no document is open');
return;
}
const selection = editor.selection;
const range = new vscode.Range(selection.start, selection.end);
editor.edit((editBuilder) => {
editBuilder.replace(range, val);
});
}
function getAllLogStatements(document, documentText) {
let logStatements = [];
const logRegex = /console.(log|debug|info|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*)\);?/g;
let match;
while (match = logRegex.exec(documentText)) {
let matchRange =
new vscode.Range(
document.positionAt(match.index),
document.positionAt(match.index + match[0].length)
);
if (!matchRange.isEmpty)
logStatements.push(matchRange);
}
return logStatements;
}
function deleteFoundLogStatements(workspaceEdit, docUri, logs) {
logs.forEach((log) => {
workspaceEdit.delete(docUri, log);
});
vscode.workspace.applyEdit(workspaceEdit).then(() => {
logs.length > 1
? vscode.window.showInformationMessage(`${logs.length} console.logs deleted`)
: vscode.window.showInformationMessage(`${logs.length} console.log deleted`);
});
}
function activate(context) {
console.log('console-log-utils is now active');
const insertLogStatement = vscode.commands.registerCommand('extension.insertLogStatement', () => {
const editor = vscode.window.activeTextEditor;
if (!editor) { return; }
const selection = editor.selection;
const text = editor.document.getText(selection);
text
? vscode.commands.executeCommand('editor.action.insertLineAfter')
.then(() => {
const logToInsert = `console.log('${text}: ', ${text});`;
insertText(logToInsert);
})
: insertText('console.log();');
});
context.subscriptions.push(insertLogStatement);
const deleteAllLogStatements = vscode.commands.registerCommand('extension.deleteAllLogStatements', () => {
const editor = vscode.window.activeTextEditor;
if (!editor) { return; }
const document = editor.document;
const documentText = editor.document.getText();
let workspaceEdit = new vscode.WorkspaceEdit();
const logStatements = getAllLogStatements(document, documentText);
deleteFoundLogStatements(workspaceEdit, document.uri, logStatements);
});
context.subscriptions.push(deleteAllLogStatements);
}
exports.activate = activate;
function deactivate() {
}
exports.deactivate = deactivate;