6

Does anyone know how to bind key combinations with Alt in inputrc?

I want to map a key combination Alt+Backspace to backward-kill-word, but when I press Ctrl+V and Alt+Backspace to see what characters it represents, it shows ^[ for a brief moment before getting deleted or doesn't show anything at all.

I know that in order to bind Ctrl+Left Arrow to something I can press Ctrl+V, which will type ^[[1;5C and then replace ^[ with \e and finally write add this line to .inputrc:

"\e[1;5C": forward-word

But this method doesn't work for me with Alt+(literally anything).

AdminBee
  • 22,803
a_girl
  • 185
  • 6

1 Answers1

7

For keys that normally send a single character, Alt+key normally sends the escape character followed by this character. In particular, Alt+Backspace sends \e\177 where \e is the escape character (represented visually as ^[) and \177 is the backspace character (represented visually as ^? — more properly this is the delete character, but I'll use the name “backspace” in this answer). (Depending on your configuration, the backspace character may be \b instead, represented visually as ^H.)

When you press Ctrl+V Alt+Backspace, the Ctrl+V character tells the terminal (or the application, depending on the terminal mode) to interpret the next character literally, so this inserts an escape character, which is represented visually as ^[. Then the terminal has one more character to read, which is a backspace, which erases the escape character that you just entered.

To see the complete character string sent by a key, you can use this command, and type the key within 2 seconds:

stty raw; sleep 2; echo; stty cooked

stty raw switches the terminal to raw mode where control characters are just inserted as-is, and stty cooked switches it back. In practice Alt+Backspace is one of the very few cases where this is necessary though: most key chords only send either a single control character, or an escape character followed by printable characters.

In .inputrc, to cover both common cases (with the delete or backspace character):

"\e\177": backward-kill-word
"\e\b": backward-kill-word

Note that the escape sequence depends on your terminal. Some terminals don't send an escape sequence for some key chords, or send non-standard escape sequences, possibly the same for multiple key chords. But if you see ^[ briefly when you press Ctrl+V Alt+Backspace, it shows that your terminal does the standard thing for this particular key chord.

fra-san
  • 10,205
  • 2
  • 22
  • 43