Readline: a library for editing and manipulating text on command lines.
Bind key sequence to command
With the following bind command,
date
is executed when
,dt
is typed, yet, the already typed text in the command line remains.
bind -x '",dt": "date"'
Within the command, the variables READLINE_LINE
and READLINE_POINT
provide access to the content and cursor position of the text currently being edited.
If the command is a function (that executes in the same process as the shell, rather than a a script that executes as a child process), these variables can even be written to and thus the edited line can be changed.
Programmatically change current line
With bind -x
, not only an ordinary executable, but also a shell function can be called. The function can then read and write the variables READLINE_POINT
(zero based position of cursor on line) and READLINE_LINE
(text of current line).
This might be useful when doing something like cd /foo/bar/baz/xyz
and then finding out that xyz
was the wrong directory. ctrl-q
goes then back one directory.
removeLastPartOfPath() { # {
# If READLINE_LINE ends on something like $SOMETHING/foo/bar/baz
# $SOMETHING/foo/bar is assigned to READLINE_LINE.
if [[ $READLINE_LINE =~ (.*)/ ]]; then
READLINE_LINE="${BASH_REMATCH[1]}"
fi
} # }
# Trying to bind ctlr-q to removeLastPartOfPath {
#
# ctrl-q is used by the tty for flow control (xon/xoff).
# I couldn't care less (at least momentarely), so
# flow control is turned off (stty -ixon) in order to make it possible
# to bind ctrl-q to a function
#
stty -ixon
bind -x '"\C-q": removeLastPartOfPath'