11

Is there an elisp refactoring tool that can rename local variables and function arguments? I would like to be able to turn:

(defun my-func (s r)
  ...
  (use s .. r))

into:

(defun my-func (string replacement)
  ...
  (use string .. replacement))

using a method that knows how to find variable references. I'm okay if it is not super-hygenic.

  • 4
    Multiple cursors can edit all instances of a symbol in current defun. – Malabarba Aug 8 '15 at 20:42
  • Also see iedit. – InHarmsWay Aug 8 '15 at 23:22
  • 2
    iedit: github.com/victorhge/iedit – Gracjan Polak Aug 9 '15 at 10:14
  • 4
    Not all code is ours. Some code is old. – Gracjan Polak Aug 10 '15 at 6:31
  • 2
    I usually regexp replace in region \bSYM\b … – BRPocock Mar 23 '16 at 13:56
2

TL;DR: erefactor-rename-symbol-in-buffer

You're looking for a lexically intelligent rename function - one that renames variables by their scope, not just a dumb find and replace. Packages like this exist for a lot of languages but as of writing (April 2019), there aren't actually many options for Emacs Lisp. The erefactor package is the only one I know of.

erefactor-rename-symbol-in-buffer is the function you want. It's an intelligent find-and-replace command that will replace symbols in the current scope (including docstrings). The limitation of this command is that it won't search outside the current buffer. It's smart, but not perfect. It will ask you to confirm each occurance to ensure the end result is sanitary.

The other rename function is erefactor-rename-symbol-in-package. This doesn't work the same way - it only works on global symbols. It relies on your package being set up correctly, with a grouping system and prefix, and it needs the variable to match the package's prefix. It's not very robust - it will fail if you haven't set things up the way this function expects. I think if you're renaming a global symbol, you may as well use a naive find and replace since global symbols in Elisp don't have a namespace. The benefits of lexical understanding are minimal. This command is too fragile for the tradeoff. I would suggest just using projectile-replace.

Erefactor has a number of other Elisp commands you might find useful. An (incomplete) list is available in the readme.

It's not described on the GitHub page but erefactor is available on MELPA (M-x package-install RET erefactor). The MELPA page can be found here.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.