@Malabarba mentioned the use of wgrep
package for editing grep/ack/ag results.
I would like to write a detailed walk-through of how I use the ag
package and wgrep-ag
packages to achieve editing of 'ag'ged results using multiple-cursors
package.
These packages are available through Melpa. You also need to have ag
aka the_silver_searcher installed on your system.
This walk-through applies to cases where you are looking for a way to do single line edits at all/selected locations that ag
found.
Install ag
on your system and the above mentioned emacs packages.
ag
supports searching files with contents that match your specified regex. The simplest way to tell ag
where the project root is to put an empty .git
folder there. Then do the search using M-x ag-project-regexp
.
The results buffer of ag search is not editable by default. To make it editable, do M-x wgrep-change-to-wgrep-mode
or use the wgrep
-default binding C-c C-p
.
Now if you needed to change 'abcdef' to 'ghijkl' in all your files, you'd search for 'abcdef' and the ag results buffer will display all lines containing that string. Then you make that buffer editable and change those strings manually and those changes will reflect in the actual file buffers on doing M-x wgrep-finish-edit
or using the default binding C-c C-e
. You can also use query-replace-regexp
to do that search replace.
I prefer using multiple-cursors
for fast refactoring so that I can see a real time feedback of where my multiple edits are happening simultaneously. Highlight the string you want to replace in that ag results buffer and call M-x mc/mark-all-like-this
and then edit away in awe as you see stuff getting edited at multiple points at the same time.
Once you are happy with the edits, as I mentioned above, do C-c C-e
to "reflect" the changes in the actual buffers. The buffers are not saved yet.
To save all the buffers, I usually do that in one go, using the emacs default C-x s !
binding.
Here is an example use case with screenshots:
It shows the process of replacing all the instances of bind-to-modi-map
to bind-to-my-map
in my ~/.emacs.d/
.
When I search for bind-to-modi-map
in my emacs setup folder, I get the below 'ag'ged result:
This buffer is read-only.
After M-x wgrep-change-to-wgrep-mode
, I highlight, -modi-map
, select all instances of that selection using M-x mc/mark-all-like-this
and after editing those selections to -my-map
, it looks as below:
The blue highlight shows which lines will be modified when I press C-c C-e
.
On hitting C-c C-e
, you can see the change reflected in the actual file in this screenshot:
I would then save all the modified files using C-x s !
.