Skip to content

Instantly share code, notes, and snippets.

@exceedsystem
Last active July 3, 2022 23:06
Show Gist options
  • Select an option

  • Save exceedsystem/de26501d040cbb89de9b9b0f651bb5a9 to your computer and use it in GitHub Desktop.

Select an option

Save exceedsystem/de26501d040cbb89de9b9b0f651bb5a9 to your computer and use it in GitHub Desktop.
An example of 'Search on Google' macro for VSCodeMacros extension
// [VSCode Macros] extension
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros
// License:MIT
const vscode = require('vscode');
const process = require('process');
const cp = require('child_process');
module.exports.macroCommands = {
SearchOnGoogle: {
no: 1,
func: searchOnGoogle,
},
};
async function searchOnGoogle() {
const text = await getSearchWords();
if (text?.length) launchDefaultBrowser(text);
}
function launchDefaultBrowser(keywords) {
let launcher;
switch (process.platform) {
case 'linux':
launcher = 'xdg-open';
break;
case 'darwin': // *Unverified
launcher = 'open';
break;
case 'win32':
launcher = 'start "" ';
break;
}
// Open a url in default web browser
if (launcher?.length) cp.exec(`${launcher} "https://www.google.com/search?q=${encodeURI(keywords)}"`);
}
async function getSearchWords() {
const editor = vscode.window.activeTextEditor;
let searchWords;
if (editor) {
const document = editor.document;
const selection = editor.selection;
searchWords = document.getText(selection);
}
if (!searchWords?.length) {
// Get search words from input box
searchWords = await vscode.window.showInputBox({ prompt: 'Enter search words' });
}
return searchWords;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment