Benjamin Sago / ogham / cairnrefinery / etc…

Technical notes Insert text with ‘fish_user_key_bindings’

There are a couple snippets of punctuation-heavy text I use on the command-line that are… not a pain to type, but they’re definitely more annoying than they could be:

  • 2>&1 — pipe standand error into standard output
  • >/dev/null — silence standard output, showing only standard error
  • | grep — pipe a command through grep (usually followed by arguments)

I touch-type, so my fingers stay on the home row of the keyboard the vast majority of the time; adding redirects to the command-line like this means my fingers instead have to do a little punctuation-key modifier-key dance before returning to their natural habitat.

To solve this problem, I created some custom fish keybindings that all start with Control-G, which I didn’t currently use for anything else. I have a fish function, fish_user_key_bindings, that defines them. It looks like this:

function fish_user_key_bindings -d "Configures keybindings"
    bind \cG\cG "commandline -i ' | grep '"
    bind \cG\cH "commandline -i ' | head '"
    bind \cG\cT "commandline -i ' | tail '"
    bind \cG\cE "commandline -i ' >/dev/null'"
    bind \cG\cN "commandline -i ' 2>&1'"

This function gets run upon fish startup, so you don’t need to invoke it yourself. It means:

  • If I’m typing a command and I realise I want to merge stderr and stdout, I type Control-G Control-N.
  • If I’m typing a command and I realise I’m going to need to pipe it through grep, I type Control-G Control-G.
  • If I’m typing a command and I realise I don’t want to see its output, I type Control-G Control-N.

You get the picture. The extra spaces around the quotes in the function mean I don’t need to worry about separating the text being inserted from the parameters already there.

There are a bunch of possible things you can auto-insert at the command-line like this, but these five definitions are the ones that give me the most mileage.