View changes after search and replace on Vim?

Viewed 167

I there a way to view the changes generated by search and replace in vim?

E.g. the following example deletes trailing whitespaces

:%s/\s\+$//g

but say, I am not sure of the regex and I am afraid it changed something that I did not want to be changed. But I also do not want to use gc instead of g, because confirming too many changes is confusing and takes a while, instead I would like to see the changes in a new buffer, as some sort of list. Is this possible?

2 Answers

There's an old trick that you can use to see the diff between the saved file, and your latest changes. You can see it with :help :DiffOrig.

It boils down to this command:

 command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
    \ | wincmd p | diffthis

Once you've put this in your .vimrc, you can save the file, make the substitution (or any other change you like), and run :DiffOrig to see the changes. You can then press u to undo, if you're not happy with the results, or you can save the file.

This does mean you have to save the file before running the substution, but based on your comments, I think it'll be good enough for you as a tool?

You might also want to take a look at this page in the vim wiki for some alternative proposals: http://vim.wikia.com/wiki/Diff_current_buffer_and_the_original_file

Neovim has a nice feature that highlights the substitution on the fly

"As you type a substitution  the results will immediately be
"visible in the edit window. This feature is best highlighted
"in this video: http://www.youtube.com/watch?v=sA3z6gsqOuw
if has("nvim")
    set inccommand=nosplit
endif

Another cool option is the plugin NarrowRegion. It takes a selection and uses a temporary window to apply your changes, after saving it, the result is put back into your original text.

Related