折腾readline和inputrc文件

折腾 readline 时发现了几个问题。

当使用到上下左右箭头、PageUp/PageDown 等特殊键时,只能考虑用其 key sequence。怎么知道这个 sequence 呢?有两种方式,一是先按 Ctrl-v,然后按下未知sequence的键或键组合,如 Ctrl+UpArrow,这时对应的 sequence 会显示出来,

这其实是调用 bash readline 的 quote-insert 功能/命令。另一种方式是使用 read 命令(shell built-in),然后输入位置的键组合,然后其 sequence 也会打印出来。之后就可以写到 ~/.inputrc 里面了。这个要感谢这里的介绍

Ctrl-u 不能被可靠地重新绑定。因为它是底层 TTY 的编辑字符,bash 会将其绑定到对应的 readline 操作 unix-line-discard 上。参考 这个缓存。当初想重新绑定它是因为 bash 的手册页里示例将其绑定到了 universal-argument 自己也想这样做。后来想曲线救国,绑定到 Ctrl-i 上,然而 Ctrl-i 即 TAB,容易引起干扰。后面又试了 Ctrl-Meta-u,还是不行,于是作罢,安安心心用 Alt+数字的方式给 readline 命令输数字参数得了。

折腾下来的自定义 ~/.inputrc 文件,于是乎也没多少内容:

$ cat .inputrc
# Prev PageUp
"e[5~": history-search-backward
# Next PageDown
"e[6~": history-search-forward
# Write the string.
"C-o": "> output"

# SEE ALSO
# http://code.google.com/p/iterm2/wiki/Keybindings#Escape_sequence_exploration
# You will learn that to get the key sequences of particular key stroke,
# use Ctrl+V (quoted insert) or read shell built-in.
# <Ctrl>+<Left arrow>
"e[1;5D": backward-word
# <Ctrl>+<Right arrow>
"e[1;5C": forward-word

# kill backward to the beginning
"C-j": unix-line-discard

其实,有一些(许多?) readline 内置的键绑定也挺有趣,可能还很有用。例如 C-t, M-t 用来转置(翻转)两个字符或单词的前后位置。不过能否记住且熟练,实在不好说。