Don’t search, swipe

We looked before at basic searches using isearch. However, for some time now I have been using a very nice alternative called swiper. The project page has some good information and a link to a video, so I’ll just summarise what I like about it here.

Swiper acts like isearch, in that you type a string and you get an updating list of matches, but the matching lines are shown in a list in an expanded minibuffer, which you can move through with arrows or C-n and C-p.

One of the best things is that swiper supports regular expressions in a simple way. The main thing you need to know is that spaces are interpreted as a wildcard .* so the query "don swi" would match the title of this post, for example.

The best way to understand it is to try it out yourself. Install swiper and then run it with M-x swiper. I like it so much I have bound it to C-s to replace isearch altogether:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; swiper                                                                 ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(global-set-key (kbd "C-s") 'swiper)
(setq ivy-display-style 'fancy)

The second line in the above code sets the colours of the swiper results display to be a bit more, well, fancy! Apparently this option only works well for emacs versions 24.5 and higher, so get updated.

The other tweak I have made is to get swiper to recenter the display when it exits – I found it a little unpredictable where the point was going to be after I finished swiper. This is done with a little bit of advice:

;;advise swiper to recenter on exit
(defun bjm-swiper-recenter (&rest args)
  "recenter display after swiper"
  (recenter)
  )
(advice-add 'swiper :after #'bjm-swiper-recenter)