Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/emmet/src/evaluateMathExpression.ts
4772 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
/* Based on @sergeche's work in his emmet plugin */
7
8
import * as vscode from 'vscode';
9
import evaluate, { extract } from '@emmetio/math-expression';
10
11
export function evaluateMathExpression(): Thenable<boolean> {
12
if (!vscode.window.activeTextEditor) {
13
vscode.window.showInformationMessage('No editor is active');
14
return Promise.resolve(false);
15
}
16
const editor = vscode.window.activeTextEditor;
17
return editor.edit(editBuilder => {
18
editor.selections.forEach(selection => {
19
// startpos always comes before endpos
20
const startpos = selection.isReversed ? selection.active : selection.anchor;
21
const endpos = selection.isReversed ? selection.anchor : selection.active;
22
const selectionText = editor.document.getText(new vscode.Range(startpos, endpos));
23
24
try {
25
if (selectionText) {
26
// respect selections
27
const result = String(evaluate(selectionText));
28
editBuilder.replace(new vscode.Range(startpos, endpos), result);
29
} else {
30
// no selection made, extract expression from line
31
const lineToSelectionEnd = editor.document.getText(new vscode.Range(new vscode.Position(selection.end.line, 0), endpos));
32
const extractedIndices = extract(lineToSelectionEnd);
33
if (!extractedIndices) {
34
throw new Error('Invalid extracted indices');
35
}
36
const result = String(evaluate(lineToSelectionEnd.substr(extractedIndices[0], extractedIndices[1])));
37
const rangeToReplace = new vscode.Range(
38
new vscode.Position(selection.end.line, extractedIndices[0]),
39
new vscode.Position(selection.end.line, extractedIndices[1])
40
);
41
editBuilder.replace(rangeToReplace, result);
42
}
43
} catch (err) {
44
vscode.window.showErrorMessage('Could not evaluate expression');
45
// Ignore error since most likely it's because of non-math expression
46
console.warn('Math evaluation error', err);
47
}
48
});
49
});
50
}
51
52