forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluateMathExpression.ts
More file actions
50 lines (46 loc) · 2.17 KB
/
evaluateMathExpression.ts
File metadata and controls
50 lines (46 loc) · 2.17 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* Based on @sergeche's work in his emmet plugin */
import * as vscode from 'vscode';
import evaluate, { extract } from '@emmetio/math-expression';
export function evaluateMathExpression(): Thenable<boolean> {
if (!vscode.window.activeTextEditor) {
vscode.window.showInformationMessage('No editor is active');
return Promise.resolve(false);
}
const editor = vscode.window.activeTextEditor;
return editor.edit(editBuilder => {
editor.selections.forEach(selection => {
// startpos always comes before endpos
const startpos = selection.isReversed ? selection.active : selection.anchor;
const endpos = selection.isReversed ? selection.anchor : selection.active;
const selectionText = editor.document.getText(new vscode.Range(startpos, endpos));
try {
if (selectionText) {
// respect selections
const result = String(evaluate(selectionText));
editBuilder.replace(new vscode.Range(startpos, endpos), result);
} else {
// no selection made, extract expression from line
const lineToSelectionEnd = editor.document.getText(new vscode.Range(new vscode.Position(selection.end.line, 0), endpos));
const extractedIndices = extract(lineToSelectionEnd);
if (!extractedIndices) {
throw new Error('Invalid extracted indices');
}
const result = String(evaluate(lineToSelectionEnd.substr(extractedIndices[0], extractedIndices[1])));
const rangeToReplace = new vscode.Range(
new vscode.Position(selection.end.line, extractedIndices[0]),
new vscode.Position(selection.end.line, extractedIndices[1])
);
editBuilder.replace(rangeToReplace, result);
}
} catch (err) {
vscode.window.showErrorMessage('Could not evaluate expression');
// Ignore error since most likely it's because of non-math expression
console.warn('Math evaluation error', err);
}
});
});
}