skip to Main Content

How do I make a keybinding that works like Ctrl+F / Cmd+F, but it starts searching at the top of the file, rather than at the current cursor location? Is there a command for that?

2

Answers


  1. Chosen as BEST ANSWER

    I haven't found a built-in command to search from the beginning of the file, but you can easily do it by chaining the two commands "go to the top" and "find" using the runCommands command.

    As this requires passing args to runCommands, we can't do this in the built-in keyboard shortcuts UI. Instead, run the command "Preferences: Open Keyboard Shortcuts (JSON)", and then add the following entry to the array:

    [
      ...,
      {
        "key": "ctrl+cmd+f",
        "when": "editorTextFocus",
        "command": "runCommands",
        "args": {
          "commands": ["actions.find", "cursorTop"]
        }
      }
    ]
    

    Note that we're running "actions.find" (the "Find" command) first, and then "cursorTop". The reason is that the "Find" command seeds its search string from the word at the cursor position, so if we run "cursorTop" first, it will instead seed whichever word happens to be the first in the file.

    The only drawback to this solution is that even if you cancel your search immediately, it won't go back to your original cursor position.


  2. You have at least a couple of options. Try this keybinding:

    {
      "key": "alt+f",                // whatever keybinding you want 
      "when": "editorTextFocus",
      "command": "runCommands",
      "args": {
        "commands": [
          "actions.find", 
          "editor.action.goToMatchFindAction"
        ]
      }
    }
    

    You’ll see it preforms the find on the word or selection at the cursor and then opens a little input box at the top where you could type 1 and Enter to go to the first find match.

    Or, a little simpler but requires an extension, Find and Transform (that I wrote). Try this keybinding:

    {
      "key": "alt+f",                // whatever keybinding you want
      "command": "findInCurrentFile",
      "args": {
        "reveal": "first",     // or "last" or "next"
        "postCommands": ["actions.find", "cancelSelection"]
      },
      // "when": ""
    }
    

    It will reveal the first find match. The find will again be based on your selection or the word at the cursor.

    The "cancelSelection" postCommand is there because normally the extension selects ALL the find matches, not just the first one. Canceling the selections will result in only the first revealed match being selected.

    The "actions.find" postCommand isn’t really needed or used, but it is a convenience to show the Find Widget where you can easily go to the next or previous match.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search