Renaming a variable, a method, or a class

Oftentimes, we rename things when refactoring, and these changes need to be reflected throughout the code base. However, simple search and replace often won't cut it, since you'll risk accidentally renaming unrelated things.

For example, let's try renaming our Dog class as Pitbull. Since we need to carry this out in multiple files, we'll use arglist:

:arg **/*.py

Now, move your cursor over the class name you'd like to rename (Dog), and enter the following(here, <[Ctrl + r, Ctrl + w]> signifies pressing Ctrl + r followed by Ctrl w and not typing in square brackets):

:argdo %s/<[Ctrl + r, Ctrl + w]>/Pitbull/gec | update

Once you run it, you'll be prompted for every match:

Press y to approve each change, or n to reject it.

Here's what's going on here:

  • :argdo runs the operation on every arglist entry (which we loaded with :arg)
  • %s/.../.../gec substitutes every occurrence (g) throughout the whole file (%), without raising errors if no entries were found (e), and asking the user before making changes (c)
  • <...> ensures we're looking for a whole word, and not just partial matches (otherwise we'll also rename another class called Dogfish, which we don't want to do)
  • Ctrl + r, Ctrl + w is a shortcut to insert the word under the cursor in the current command (which would insert Dog)

This approach has the disadvantage of locking you into dialog windows, without you being able to look around the file first. If you'd like more control, another alternative would be to use :vimgrep to find the matches first:

:vimgrep /<Dog>/ **/*.py

You'll be able to look at matches, and step through them with :cn or :cp (or open the quickfix window with :copen and navigate from there):

In this particular example, you could replace the word using the usual change word command (cw followed by Pitbull followed by Esc), and then replay the changes by pressing dot (.), or run a non-global :substitute command (:s/<Dog>/Pitbull).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.244.216