How to override the copy-mode behavior of the Home and End keys in GNU Screen

gnu-screenkeyboard shortcuts

I use screen a fair amount and would like the Home and End keys to simply go to the beginning or end of the current line, rather than the default, which is to go to the global beginning or global end of screen's whole history for the current window.

Doing bindkey -m -k "kh" stuff 0 and bindkey -m -k "kH" stuff $ has the desired effect while in copy mode, but since -m bindings also affect command-input mode, this effectively disables use of of Home and End while typing commands, since it causes literal '0' and '$' to be inserted while the cursor is in the command-bar.

Is there a way to tame these keys without simultaneously breaking them for command-entry?

Best Answer

Yes, there is. Although there is not (currently) a bindkey flag that affects only copy-mode (not command-mode also) there is still a way to get similar results, though it means learning a new syntax for doing so.

The fix

The markkeys command affects copy-mode only, and will not affect command-mode behaviors. It's pickier about what characters it will accept, but it's better than nothing, and gets the job done in this situation:

markkeys "$=\205"
markkeys "\^=\201"

The above tells screen to alias the start-of-line and end-of-line and signals (which are sent by Home and End) to the ^ and $ movement keys respectively. ^ is written escaped as \^ in the string because it's normally used to set off escaped sequences but we mean the literal thing.

Note that if you would prefer Home to go all the way to the beginning/left instead of just to the first visible character, then replace markkeys "\^=\201" with markkeys "0=\201".

Note also that you can still use g and G to get to the global beginning or end of a window's history while in copy mode.

How I found the fix

Although I still don't know of a complete reference that lays out all of the useful hex-escapes for such things, I was able to find the two relevant ones by running bindkey -m within screen and then overriding the mappings there until I broke the behavior I was interested in. The relevant lines were:

kh          -> stuff \201
kH          -> stuff \205

With some help from the folks in irc://irc.freenode.net/screen I learned the lefthand codes can be looked up from the shell via man terminfo, which has them listed in the Tcap column as

Variable        Capname       TCap Code          Description
string
---------------------------------------------------------------------------
key_home        khome         kh                 home key
...
key_ll          kll           kH                 lower-left key (home down)

Putting two and two together and doing a bit of guesswork to get the binding right lead to the above fix.

Related Question