VS Code: Skipping current selection when using cmd/ctrl+d

Posted: 12/10/2022
Categories: vs code

One of my favorite features in VS Code is being able to select the next occurrence of the selected word by pressing cmd+d (ctrl+d for Windows). This then allows me to quickly modify each instance of that word.

The Problem

For a long time though I frequently encountered the same problem: it would select an instance of the word that I didn't wish to alter. Often this is because the word would feature in a different variable or function.


The Solution

You can deselect the selected word by using cmd + k (ctrl + k).



Bare with, this one isn't easy to demonstrate in a blog post.

For the sake of this contrived demo, let us ignore the fact F2 functionality exists to rename a variable...

Assume we have the following code:

const initialize = () => {
const config = getConfig();

Our goal is to rename the config variable.

Failed Attempt

On our first attempt we perform the following. It doesn't go well:


Successful Attempt

We undo our changes and make another attempt, this time using cmd + k:



We select the first instance of config and press cmd + d with the aim of also selecting the config being passed into applyConfig().

Rather than that config being selected, the "Config" in getConfig is selected.

We can bypass that by pressing cmd + k.

One issue we encounter here is the visual state of VS Code doesn't change at this point. It's not clear that it's been bypassed.

We press cmd + d again. This time the "Config" inside applyConfig is selected.

Again, press cmd + k to bypass it.

For the final time, we press cmd + d, which selects the "config" being passed into applyConfig. We are after this one.

You are now in a position where you can type and only replace the two instances of "config".