Search code examples
bashterminalzshiterm

How to keymap reverse-search (Ctrl+R) in iTerm to a different key combination


I am trying to map the reverse-search-history (Ctrl+R) command to a different command combination in iTerm but not sure how? Any help would be appreciated.


Solution

  • The person who mentioned readline is correct.

    You can edit your bindings using the bind command (try help bind).

    For this particular question, let's see what's bound to Control-R:

    $ bind -P |grep C-r
    re-read-init-file can be found on "\C-x\C-r".
    reverse-search-history can be found on "\C-r".
    revert-line can be found on "\M-\C-r".
    

    Ok. One of those is just \C-r which means Control-R. Let's double-check:

    $ bind -q reverse-search-history
    reverse-search-history can be invoked via "\C-r".
    

    man readline includes:

    reverse-search-history (C-r) Search backward starting at the current line and moving `up' through the history as necessary. This is an incremental search.

    That looks right. How do we change it? Let's assume you want to use ⌘-B instead. That's Meta-b (aka \M-b) in readline-speak.

    Let's try it out:

    $ bind '\M-b:reverse-search-history'
    $ bind -q reverse-search-history
    reverse-search-history can be invoked via "\C-r", "\M-b".
    

    Pressing ⌘-b now triggers reverse search just like Control-R. Control-R is still bound though. We can fix that:

    $ bind -r '\C-r'
    $ bind -q reverse-search-history
    reverse-search-history can be invoked via "\M-b".
    

    This change will hold for the current shell session, but will vanish the next time a shell is invoked. To make the change persistent, do the following:

    $ echo '"\M-b": reverse-search-history' >> ~/.inputrc
    

    Now ~/.inputrc contains the desired binding. Any program that uses it for readline configuration (including your shell) will now use the binding you specified.