An extension to jump to lines by filtering them (like emacs-swoop)
I'm an emacs user who checked out vscode to see how easy it is to write an extension for it (result: not very difficult, but somewhat more cumbersome than in emacs).
Anyway, I created a simple extension which is similar to emacs-swoop. (I looked, but I couldn't find a similar one for vscode, but maybe I didn't look hard enough.) When you type a string then it shows the matching lines in the current file and you can jump quickly to the matches with the keyboard by moving in the menu.
Here's a demo: https://i.imgur.com/SRQxw35.gif
It was only an exercise, I don't plan to publish it or anything, but I leave its code here (pretty simple) in case somebody finds it useful and wants to make a proper extension out of it.
I used the tutorial template, so the extension is still called helloworld.
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, your extension "filter" is now active!');
// The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand('extension.helloWorld', function () { // The code you place here will be executed every time your command is executed
// Display a message box to the user //vscode.window.showInformationMessage('Hello World!'); // const quickPick = vscode.window.createQuickPick(); quickPick.items = [].map(label => ({ label })); quickPick.onDidHide(() => quickPick.dispose());
let timer = null;
quickPick.onDidChangeValue(() => { if (timer) clearTimeout(timer);
timer = setTimeout(() => { timer = null;
let query = quickPick.value.replace(/^\s+|\s+$/g, '');
if (query == '') { quickPick.items = []; return; }
const doc = vscode.window.activeTextEditor.document; let matches = [];
for (let index = 0; index < doc.lineCount; index++) { const line = doc.lineAt(index);
if (line.text.indexOf(query) != -1) { matches.push(index + ': ' + line.text); } }
quickPick.items = matches.map(label => ({ label }));
}, 500); });
quickPick.onDidChangeActive(() => { const line = parseInt(quickPick.activeItems[0].label.match(/^[0-9]+/)[0]); let editor = vscode.window.activeTextEditor; let range = editor.document.lineAt(line).range; editor.selection = new vscode.Selection(range.start, range.end); editor.revealRange(range, vscode.TextEditorRevealType.InCenter); });
quickPick.onDidAccept(() => { quickPick.hide(); });
quickPick.show();
});
context.subscriptions.push(disposable); }