While working on a certain project, I needed to check the differences between two text fragments. We all know and love diff , but it operates on files, and what I had was two fragments of two files (or sometimes even of one file) which I wanted to compare.

There are a few solutions to this problem, but they seemed too complicated for me. I know Ediff is powerful, but it always seemed to complex for me to learn. There is the little-known compare-windows command, which is nice, but less sophisticated then a usual diff, and has a major drawback of not displaying any “report” showing the differences – it is well-suited to interactive use, but sometimes I’d like to have something more “tangible” to look at after doing the comparison.

Well, the main problem of diffing two regions is the user interface. The commands ediff-regions-linewise and ediff-regions-wordwise do a good job of being quite intuitive, but only up to the moment when Ediff is launched .

A few days ago it struck me that I could reuse a very basic and well-known UI for that: the kill ring. How about a command which would diff the last two kills? Then, using it would be as simple as marking the first region, pressing M-w , marking the second one, pressing M-w again, and invoking the command.

And the coolest thing about it was that it only took me a few minutes to code this command! It is extremely simplistic, and uses temporary files in a not-so-elegant way, but it does its job well enough for me. I’ve been using it for some time now and I really like it.

(defun diff-last-two-kills () "Write the last two kills to temporary files and diff them." (interactive) (let ((old "/tmp/old-kill") (new "/tmp/new-kill")) (with-temp-file new (insert (current-kill 0 t))) (with-temp-file old (insert (current-kill 1 t))) (diff old new "-u" t)))

As usual, Emacs’ shows one of its main strengths: extensibility. I have no idea if you could do this in Vim (probably yes) or in Sublime Text or VSCode or what-have-you, but I suspect that even if it was possible, it might take more time to write.

CategoryEnglish, CategoryBlog, CategoryEmacs