How to initiate "findInFiles" with VSCode extension API?

Viewed 651

I'm trying to write an extension that will automatically select the word under the cursor, open the find in files dialog, and initiate a search with that selection. So far, I've been able to get the extension to do everything except actually initiating the search. I still have to press enter in the find in files dialog to actually do the search. Here's the extension code I have so far:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('extension.searchUnderCursor', () => {
        // Get the current editor
        let editor = vscode.window.activeTextEditor;
        if (!editor) {
            console.log('No active editor!');
            return;
        }

        // Get word under cursor position
        let wordRange = editor.document.getWordRangeAtPosition(editor.selection.start);
        if (!wordRange) {
            console.log('No word under the cursor!');
            return;
        }

        // Select the word
        editor.selection = new vscode.Selection(wordRange.start, wordRange.end);

        // Initiate search
        vscode.commands.executeCommand('workbench.action.findInFiles').then(() => {
            vscode.commands.executeCommand('default:type', {text: '\n'});
        });
    });

    context.subscriptions.push(disposable);
}

export function deactivate() {}

You can see I was trying to find a way to press enter in the find in files dialog to begin the search. Of course, that doesn't work. How can I get the functionality I'm going for here?

1 Answers

Actually, I figured it out. Here's my solution:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('extension.searchUnderCursor', () => {
        // Get the current editor
        let editor = vscode.window.activeTextEditor;
        if (!editor) {
            console.log('No active editor!');
            return;
        }

        // Get word under cursor position
        let wordRange = editor.document.getWordRangeAtPosition(editor.selection.start);
        if (!wordRange) {
            console.log('No word under the cursor!');
            return;
        }

        // Get word text
        let wordText = editor.document.getText(wordRange);

        // Initiate search
        vscode.commands.executeCommand('workbench.action.findInFiles', {
            query: wordText,
            triggerSearch: true,
            matchWholeWord: true,
            isCaseSensitive: true,
        });
    });

    context.subscriptions.push(disposable);
}

export function deactivate() {}

As it turns out, the findInFiles action has a number of useful args that it accepts: https://github.com/microsoft/vscode/blob/9a987a1cd0d3413ffda4ed41268d9f9ee8b7565f/src/vs/workbench/contrib/search/browser/searchActions.ts#L163-L172

Related