-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathextension.js
54 lines (48 loc) · 1.57 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
//Strings
const CFG_SECTION = "googleSearch";
const CFG_QUERY = "QueryTemplate";
const CMD_ID = "extension.googleSearch";
const vscode = require("vscode");
//Activating Function
function activate(context) {
const disposable = vscode.commands.registerTextEditorCommand(
CMD_ID,
webSearch
);
context.subscriptions.push(disposable);
}
exports.activate = activate;
//Empty Deactivate Function
function deactivate() {}
exports.deactivate = deactivate;
//Function to launch the Search URL in default browser
function webSearch() {
const selectedText = getSelectedText();
if (!selectedText) {
return;
}
const uriText = encodeURI(selectedText);
const googleSearchCfg = vscode.workspace.getConfiguration(CFG_SECTION);
const queryTemplate = googleSearchCfg.get(CFG_QUERY);
const query = queryTemplate.replace("%SELECTION%", uriText);
vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(query));
}
//getSelectedText creates a URL for search based on the selection
function getSelectedText() {
const documentText = vscode.window.activeTextEditor.document.getText();
if (!documentText) {
return "";
}
const activeSelection = vscode.window.activeTextEditor.selection;
if (activeSelection.isEmpty) {
return "";
}
const selStartoffset = vscode.window.activeTextEditor.document.offsetAt(
activeSelection.start
);
const selEndOffset = vscode.window.activeTextEditor.document.offsetAt(
activeSelection.end
);
let selectedText = documentText.slice(selStartoffset, selEndOffset).trim();
return selectedText.replace(/\s\s+/g, " ");
}