Jérôme Belleman
Home  •  Tools  •  Posts  •  Talks  •  Travels  •  Graphics  •  About Me

Visual Selection à la Vim with Zsh

13 Nov 2016

Those Z shell – zsh – nifty tricks that change your productivity life. Who would have thought, for instance, that zsh offers visual selection à la Vim?

I was coding along that day and started shuffling files as I normally do with Zsh. It's the relatively new zsh 5.1.1 that came bundled with that new Linux distribution I'd installed not so long ago. Carried away by my enthusiasm, my fingers started taking over from my brain, a consequence of which being that my keyboard became overcome by my Vim reflexes.

I had bindkey -v pretty much forever in my ~/.zshrc and zsh probably does the best imitation there is of vi – even Vim – bindings. But there's limits in what it can do. Or is there? I was stunned that day when I fired up Visual mode for selecting ranges of characters. And it just worked.

Imagine you've got a rather long command line from which you need to edit a fairly long portion, typically first by removing it. In the olden days, I would have used f and t to perform motions jointly with d to cut the portion I wanted to get rid of. For instance, suppose I want to just remove bar/baz/boo/corge/gazonk from this command line (watch where the cursor is):

ls foo/bar/baz/boo/corge/gazonk/grault

I would probably press d f k, which will result in

ls foo//grault

... from which point I can insert something else between the 2 forward strokes. This took a bit of time for me to find a character that I could use f on but it worked, although only because I was lucky enough that k was a fairly unique character in this line. If it had been gazono instead of gazonk I would have used the o character instead and needed to repeat the operations 3 times with .:

ls foo/bar/baz/boo/corge/gazono/grault
ls foo/bar/baz/boo/corge/gazono/grault
ls foo/o/corge/gazono/grault
ls foo/rge/gazono/grault
ls foo/no/grault
ls foo//grault

In short, it'll cost you time to choose a useful character to use f against and it may not even work in one go. You can achieve the same effect in a much more interactive, hassle-free way, just by pressing v which will take you to Visual mode. Then just select the portion you want to remove with any motion you fancy:

ls foo/bar/baz/boo/corge/gazono/grault

... press x and get on with your life.