Keybinding


trap action
KEYBD
Ksh93 provides a KEYBD trap that gets executed whenever a key
is entered from the keyboard. Using this trap and the associateive array feature
of Ksh93, a keybind function can be written to map any entered key sequence to
another.
Here is an example. Create a file in your home directory,
.keybindings, containing two columns. The first column contains a single
character followed by a tab. The second column contains a command you want
executed. We’ll trap all keys. When you press the ESC key the escape
state will be set. The next key will determine what command if any will be
executed. If you have a command associated with the “a” key, then
pressing <ESC><a> will cause a scan of the .keybindings file to
locate the “a” line. The remainder of the line will become a
command evaluated by the shell.
Note, to create the escape value, in the vi
editor, press <CTRL>v<ESC>, the escape value will be entered, and
will show as ^[. The value to –d in the cut command is a tab enclosed in
quotes.
#!/bin/ksh
typeset
-A KeyTable
_InESC=false
function
_eval_esc
{
if [[ "$1" == “^[" ]] # the ^[ is escape – see above
then
_InESC=true
else
if [[ $_InESC == true ]]
then
# Previous key was an escape
grep ^${1} ~/.keybindings > /dev/null
if [[ $? == 0 ]]
then
eval $(/usr/bin/grep ^${1} ~/.keybindings | cut -d" " -f2 )
fi
fi
_InESC=false
fi
}
trap
'_eval_esc ${.sh.edchar}' KEYBD
A sample .keybindings file:
$
cat ~/.keybindings
l
ls -l
v
vi ${HOME}/.profile
p
ps -ef | grep ${LOGNAME}
In practical
applications,
keybinding’s
uses are going to need to be very specifically tailored to your individual
program requirements.
|
Special
KeyBoard Variable
|
Description
|
|
.sh.edchar
|
This
variable contains the value of the keyboard character (or sequence of characters
if the first character is an ESC, ascii 033) that has been entered when
processing a KEYBD trap. If the value is changed as part of the trap action,
then the new value replaces the key (or key sequence) that caused the trap.
|
|
.sh.edcol
|
The
character position of the cursor at the time of the most recent KEYBD trap.
|
|
.sh.edmode
|
The
value is set to ESC when processing a KEYBD trap while in vi insert mode. (See
“Vi
Editing
Mode”).
Otherwise, .sh.edmode is null when processing a KEYBD trap.
|
|
.sh.edtext
|
The
characters in the input buffer at the time of the most recent KEYBD trap. The
value is null when not processing a KEYBD trap.
|