POC for python code manipulation with a Full Syntax Tree. That’s better than regexps.
This library is based on RedBaron:
pip install redbaron
hydra.el (in Melpa, that’s optionnal but real handy) and
For the moment, clone this repository and load
so will set the path to the python code that lives alongside it (see
The one command to know to see all options:
Another example, renaming an argument and its occurences inside the method body:
Add an argument
Inside a function, call
M-x red4e-add-arg RET whatever RET. It
replaces the method definition with a new one.
It respects args on many lines (well it isn’t that clever, it’s all in one line or each on its line).
Add *args and **kwargs
There is a shortcut to add those two special args quickly:
* on the
hydra and otherwise
Rename an argument
Renaming an argument will ask you to search and replace it inside the method body.
Current method: rename (in project), kill, comment, copy
The actions for the current method are grouped under the hydra
red4e-hydra-method/body, accessible from the main hydra.
We can rename the current methode, just once or in the current project (using projectile), and kill, comment or copy it.
The second choice will ask you to search and replace this method in
the current project (based on projectile’s
Write args in one line or in multiple lines
l on the hydra (“lines”).
Move around defs with imenu
The hydra has the
i binding to call
imenu, so you can jump to
another def and carry on using red4e.
As an imenu frontend, you can stick with the default and very basic
completing-read), or choose between helm and ivy:
(setq red4e-selection-ivy) (setq red4e-selection-helm)
Rename a symbol inside the current defun
S in the hydra. It’s a simple search and replace inside the method body.
Add and remove a decorator
You can add a decorator to the current method:
@ with the hydra.
It will suggest a list of decorators used in the current buffer. As
usual, you can bypass the ido prompt with
C-f and type another
one. In that case, you can omit the “@”.
If we choose “@staticmethod”, then it removes “self” from the method signature.
This function doesn’t use the redbaron python library.
Thus the remove (
D with the hydra) only works with one-line decorators.
take the string
def foo(first, **kwargs, second=foo): pass, where
the arguments are in a bad order, and sort them:
def foo(first, second=foo, **kwargs): pass
Call that from within emacs, use with my snippet to add an argument to
a function, and it becomes a bit simpler (no more movements around the
code) and smarter (we manipulate
code, not text with clunky regexps)
to add an argument to a method.
- emacs-traad for real refactoring (using Rope) and straightforward installation.