Vim key maps act weird in urxvt - vim

Recently I started to use & favor urxvt due to its vast amount of options and because of the transparency feature.
Unfortunately, some key mapping in Vim do not work in urxvt.
For example, I have mapped Ctrl + Up/Down and Shift + Up/Down to 5 respectively 10 lines up/down movement or Ctrl + Left/Right to 1 word left/right movement.
These movement commands do work without any problems in xterm, but they refuse to work in urxvt: they switch to insert mode and paste a, b, c or d as input into my vim.
Why does this happen?
I also use zsh as my shell and mapped Ctrl + Left/Right to move 1 word left/right in zsh: this also stopped working in urxvt (while still working in xterm).
How can I get urxvt to correctly map the keys?

From the description of the problem you probably overlooked the fact that key definitions in urxvt differ from xterm. Unless you specially configure urxvt, its special keys (cursor- and keypad-keys) send different escape sequences than xterm when you modify those with shift, control, alt.
You can either use the escape sequences which urxvt sends, or you could use the keysym feature to configure urxvt to send comparable escape sequences. This feature was introduced by rxvt, and extended with urxvt to allow you to specify the modifiers (shift, control, etc), which you might want to limit the keysym to apply on:
keysym.sym: string
Compile frills: Associate string with keysym sym. The intervening resource name keysym. cannot be omitted.
The format of sym is "(modifiers-)key", where modifiers can be any combination of ISOLevel3, AppKeypad, Control, NumLock, Shift, Meta, Lock, Mod1, Mod2, Mod3, Mod4, Mod5, and the abbreviated I, K, C, N, S, M, A, L, 1, 2, 3, 4, 5.
That "compile frills" is a hint that it's an optional feature. However most packagers appear to turn on all of its options (except where they conflict). So it's probably available to you.
There's an overview of the topic (of the escape sequences) in the ncurses FAQ How can I use shift- or control-modifiers? (vim incidentally doesn't use ncurses or the modifier information in the terminal database—it's a termcap application—but that's a different problem).

In vim, you can have:
set t_ku=^[OA
set t_kd=^[OB
set t_kr=^[OC
set t_kl=^[OD
(To get ^[OA you press ctrl-v then up )
I use urxvt too, because it is fast, I don't use the transparency feature. In urxvt you may want to set option keysym.sym: action read man page for more details.
suggestion
If you use vim, use vim motions, ctrl-U/D/F/B or wWeEbB... You don't need the arrow keys at all. E.g. On my keyboard, pressing arrow keys I have to press an extra Fn key.. too expensive, and my fingers have to leave the homerow.
In terminal, I suggest you getting used to emacs-binding to edit command line, your word jumping would be: alt-b (back) and alt-f(forward) There are a lot more, very common to use: ctrl-f, c-h, c-w, a-w,c-b,c-u,c-k,a-. etc ..... also man should not forget the c-xc-e

Related

In Vim, the 5-key on the numeric keypad inserts a line above the current line with "E"

While using Vim under Linux Mint 20.2 (with NumLock off), when I hit the NumPad center key (5), a line is inserted above the current line, a capital E appears, and I am left in Insert mode. I often mistakenly hit the 5 key when trying to navigate using the NumPad cursor keys, and I would love to redefine the NumPad 5 to do nothing. I've tried remapping the key in .vimrc (using noremap <Esc>[E <Esc>, for example), but it has no effect. Note, the ANSI sequence produced when I press the NumPad5 is \033[E
FYI, I have TERM=xterm-256color.
Note: this answer generally talks about the numpad in a no-numlock context. All numbers on the numpad can be mapped when numlock is on by using <k0>...<k9>. References to the mapability of keys is therefore in a no-numlock context
Note, the ANSI sequence produced when I press the NumPad5 is \033[E
Vim doesn't see it that way.
On my system (Mint 20.2 with Cinnamon under X11), no-numlock 5 produces ^[OE. That O is very important to the observed behavior. o means "go to a new line under and enter insert mode", and O means the exact same thing, but to a new line above. The next E is then interpreted as an insert mode character, because Vim.
Moreover, esc is represented as ^[, so for mapping purposes, you only need <esc>. This point is easier to demonstrate in Vim:
^[ is additionally treated as a single character. If you want to play around with this, pop into insert mode and press <C-v>. The next key(bind) you press will be printed literally to the screen
This means what you actually want is:
nnoremap <Esc>OE <nop>
Note that I'm not sure how terminal input processing applies here; this may only hold for certain terminals, or even only apply to X11.
Another trick in general here, and a way to make sure the keycode is correct for your terminal, is that you can type :nnoremap , and then press Ctrl+v+Numpad 5. This will give you the exact keycode as Vim sees it, which you then can map to whatever you have planned.
If you do this in gVim, however, you'll find that numpad 5 without numlock doesn't actually produce a keycode detectable by gVim. This presumably means it can't be mapped (unless there's some way I just don't know about - if there is, please prove me wrong). But because it doesn't spew out a terminal code, there's the added benefit of not needing to remap it for this particular purpose, because it doesn't have the problem you're trying to avoid here in the first place.
romainl mentioned :help key-notation in the comments, but there's something to keep in mind here:
gVim not producing a keycode usually means there isn't one. <C-v> followed by numpad 9 in gVim produces <kPageUp>, but followed by numpad 5, it doesn't produce anything. Secondly, if you read :h key-notation, you'll see that it only defines home, end, up, and down, as well as the various operators, enter, and the decimal point. 2, 4, 6, and 8 are all registered as normal arrow keys, meaning <Down>, <Left>, <Right>, and <Up>. There's no way to detect these on the numpad specifically, but that's not really important.
If you've been keeping track, you'll find that numpad 5 is excluded. Note: When numlock is on, <C-v> + numpad 5 doesn't output anything in Vim or gVim, because the definition is:
Insert the next non-digit literally.
See :h i_CTRL-V.
TL;DR:
<C-v> is your friend.
Use:
nnoremap <Esc>OE <nop>
Or use <C-v> to insert the keycode, that may or may not be terminal dependent.
The mapping isn't necessary in gVim, and may not be possible.
The reason why you see this behavior is that Vim uses only the termcap interface of the terminal database. If it used terminfo, it would see a wider range of information.
Typing the key on the keyboard is misleading, because Vim (like almost all terminal applications) puts the keypad into application mode, which causes the terminal to send Escape and O rather than Escape and [ as a prefix. In terminal notation, that is \EO. In XTerm Control Sequences, that is referred to as SS3 (technically a misnomer since that applies to output, while keyboard input is input — but since no standards apply to keyboard input, that's good enough).
The terminal description for xterm at one point assigned \EOE to the kbeg capability (i.e., terminfo, which termcap names #1). That was a while back, around 1996.
Terminfo names are generally 3-5 characters, while termcap names are always 2.
Standard terminfo has a limited number of special keys (such as those for the numeric keypad which you are familiar with). All of the standard termcap names correspond to these terminfo names. In the standard arrangement, there are only five keys associated with a keypad: ka1, ka3, kb2, kc1, and kc3, which correspond to termcap's K1, K2, K3, K4, and K5. (Why there are no standard k2, kb1, kb3, or kc2 is long forgotten).
Looking for ways to improve the terminal descriptions in ncurses, a few different layouts of the standard keys have been proposed. But the best solution lies in adding new keys, using extended capabilities (a feature of ncurses since 1999). Those extensions all have names, and are chosen to conform to terminfo naming conventions. So... in May 2019, the terminfo building blocks xterm+keypad and vt220+keypad were introduced. In the former (used in xterm-new and xterm-256color, that key is named kp5.
There's no kp5 in the standard names listed in the terminfo(5) manpage. It is an extended (user-definable) key. In the older scheme some other key was unavailable for applications.
An ncurses application would automatically be able to use all of the keys, because ncurses uses terminfo (and adds all of the keys in a terminal description to its special cases for timing).
Vim will not see that key's definition because it views only a fraction (about a third) of the terminal description. Since it does not see the definition, it does not add that to the special cases where it will wait (a short time) for the completion of the character-sequence sent on that key. As noted in the other answer, in that case, Vim will see the commands Escape and O to insert the third character in the sequence, "E".

remap or ignore spacebar in vi

Vim/vi shortcuts are awesome, but there is one behavior that I would be very happy if it could be configured. My machine uses Brazilian Portuguese(abnt2) keyboard map,and some accents(like caret) needs an extra spacebar to be print, obviously because they wait/expect another character, mostly vowels. Example of the "cut until you find an empty line":
d/^$
Keystrokes actually needed on br-abnt2:
d / <shift + ~ , spacebar>(to result ^) $ <enter>
I could use { d } as it is explained on this awesome thread, but i would benefit much more on other accents(backslash) where the extra backspace trick is needed, and most important, without change my keyboard mapping to "US" for example.
Edit: I also know that this is a keymap limitation, since our language expect something after the accent, and this is why i'm asking if there is a way to circunvent this limitation inside vim.
Any ideas?
The problem does not come from the editor, but your keymap. In fact, the caret is set to be a "dead key". Meaning that it should wait for other input before being printed.
What you probably need is a new keymap that has the caret as a non dead-key. As for example, uk-gb map has caret on the key as well as another dead-key ( if I remember correctly).
If you don't want/can't remap your keyboard, you can use vim mapping function do act so.
Just choose an unused key and map it like this:
imap g ^
This will insert ^ while typing g on insert mode (other mapping for other- mode exists, nmap, ...).
For example, to use the vim mapping in the vim command-line, you shall use :
cmap g ^
Then your example will be working.

How to remap keyboard keys to avoid RSI in VIM

I hope this does not come across as an attempt to spark conversation purely for the sake of doing so.
I use vim a great deal (5-10 hours a day) and I noticed my left wrist is the first to start aching. The standard keyboard layout (see image below) is almost guaranteed to give you arthritis.
Currently, I have remapped
Ctrl to Shift
Shift to Caps Lock
Caps Lock to Ctrl
This helps with common commands such as Ctrlf or Shift2 (#), but I still have to twist my wrist to get at those combinations. Is there anyway to remap the keys so as to avoid this twisting on the left wrist (maybe use the Tab key)? I just find it odd that for a text editor designed specifically for programmers, it would make heavy use of these out of the way keys. I have considered remapping to the old keyboard layout (see below image), but I don't want to learn that if it is going to have the same fundamental problems as my current remapping.
Note: I am not a doctor, just another typist that suffered from wrist pain.
In my experience, just mapping Caps to Ctrl (or swapping the two if you must have a Caps) and using Ctrl+[ instead of Esc make a big difference. Ctrl+[ does not require an additional mapping in vim as it is equivalent to Esc. If you can teach yourself this small change you reduce your movement by a great deal when you consider how often you use Esc in vim.
The Caps to Ctrl mapping can't be done inside vim and will have to be made system-wide, however, having Ctrl in the more convenient location will also help in other applications that use Ctrl combinations. There are different methods of remapping keys depending on which OS you're using. A few common options are:
xmodmap (GNU/Linux)
KeyRemap4Macbook (OSX)
KeyTweak (Windows)
While this will probably improve your situation you really should consider seeing a doctor and/or purchasing a more ergonomically designed keyboard if your pain persists. I own an older version of the Kinesis Advantage that I picked up used on Ebay for about $100 (USD) and I couldn't be happier. The keys can be programmed directly on the keyboard so no software is needed to swap keys or create your own keyboard macros for frequently used key strokes.
Edit: I see in your post you also mention combinations like Ctrl+f and Shift+2 requiring you to twist your wrist to press. It sounds to me like you're only using the Ctrl and Shift keys on the left side of your keyboard. You should really be using both sets of these keys, using whichever one is on the opposite hand of the key you're modifying. That would negate this wrist movement.
Use caps as ctrl systemwide. (How often do you cut/copy/paste?)
This also makes ctrl[ work in vim.
Alongside I use the vim 'arpeggio' plugin.
Arpeggio lets you define vim bindings that are activated when two keys are simultanously pressed.
jk pressed serves me as ESC.
Also the 'surround.vim' plugin might be interesting for you.
Eliminated all my wrist pains.
post scriptum:
Use 'vundle'!
Its the best vim plugin manager by far, and you will wonder how you could ever do without, especially if you use a customized vim on several machines. Don't be scared if you have trouble setting it up initially, take your time.
I switched to a Kinesis Advantage keyboard, and remapped Caps Lock to Esc. This effectively removed any wrist pain I felt as a vim user.Once again not a doctor, but looking at how my hands move, I don't see my wrist twisting even when I hit Shift.
You could probably do some great remappings to the thumb keys to further minimise tension, but to be honest I've never felt the need.
Not a $0 solution, I'm afraid, but it was very effective for me.
I mapped both Escape (single tap) and Ctrl (hold) to CapsLock:
xmodmap -e "remove Lock = Caps_Lock"
xmodmap -e "remove Control = Control_L"
xmodmap -e "keysym Control_L = Caps_Lock"
xmodmap -e "keysym Caps_Lock = Control_L"
xmodmap -e "add Control = Control_L"
xcape -t 1000 -e "Control_L=Escape" # Fire nothing if 1000ms hold time out
Probably I'm messing things up here, but xmodmap isn't the best option to modify mappings anyway, so I will change that to pure xkb config.
I have also swapped : with ; and ` with ~, since I use : and ~ more often:
xmodmap -e "keycode 47 = colon semicolon"
xmodmap -e "keycode 49 = asciitilde grave"
I also use Compose Key to be able to type ūmlauts et c.
In vim, the most useful change I have ever made is mapping of space to leader. All kinds of leader-key combinations will make your life easier.
I couldn't get used to H and L for _ and $, since it doesn't seem to work with surround.vim and some other tricks people advise.
Just don't use arrows!
I'd make this part a comment to Randy's answer on Esc if I could, but it demands a little more space. There's one important use case where you can't just remap Windows keys: Windows 7 without admin rights. It's common enough in an enterprise environment; at the very least, it describes me and that keyboard in the pic. keymapper's repo has decent info on this issue:
Important note for Windows 7 Users
Windows 7 does not support per-user key mappings. Until the next release of Key Mapper, you will have to manually switch to 'Boot' mappings from the Mappings menu, reboot to change the mappings, and you will need to have Administrative access to your computer to set key mappings that will work in Windows 7.
The same is true for any Microsoft tools, KeyTweak, SharpKey, etc.
So you'll have to use something like AutoHotkey. I personally prefer mapping Caps Lock directly to Esc for Vim, and I've had issues just mapping it to Ctrl:
#IfWinActive ahk_class Vim
*CapsLock::Esc
#IfWinActive
Another alternative I like is inoremap jj <Esc>. Unless you plan to write about a hajj or something it works pretty well.
More to your point
In any case, have you considered doing the above for easy escaping and then remapping some of the hard-to-reach insert mode commands to Alt (hit it with your thumb) and then using mappings to your leader?
let mapleader=","
nnoremap <leader>f <C-F>
I would suggest remapping
Caps lock to left Control
Left Control to Escape
Escape to Caps lock
. If in linux first can be done by using setxkbmap -option '...,ctrl:nocaps' or changing XkbOptions in /etc/X11/xorg.conf. Second requires using of xmodmap. After some X server update I failed to get the third working, previously used xmodmap as well.
Using dvorak layout (maybe even programming) that is optimized for touch typing and mappings like ,s->()<Left> might also help.
Note: I am not a doctor as well. I am touch typist, but unlike #Randy Morris I never suffered from the wrist pain, just moved keys to the most convenient locations.
I always press the left ctrl key by curling up my pinky and pressing with the first knuckle. I find this requires less hand movement.
Update
I don't find Shift uncomfortable, so I can't help you with
that. However Ctrl does bother me, and even with my
knuckle technique I prefer to avoid it where possible. So for
insert mode (and command-line mode) I use a leading ;
instead of Ctrl. E.g.
:map! ;w <C-W>
:map! ;a <C-A>
:map! ;r <C-R>
:ino ;t <C-T>
:ino ;d <C-D>
You get the idea.
In normal mode I use v and V instead of Ctrl+F and
Ctrl+B (I only use visual blockwise mode), though
I imagine most people would prefer to map different keys,
such as <Space> and - for paging (- isn't really
needed). Instead of F you could search forwards with f,
and then hit ,.
I've never really seen much point in Ctrl+D or Ctrl+U.
However I do find z., z<Enter>, and z- useful for
scrolling the line with the cursor to the middle, top, and
bottom of the window respectively. H, M and L are also
useful for moving the cursor around the screen. But in
general I prefer to just use / with 'incsearch' set for
navigating about.
There's no right or wrong way to do this, these are just my personal preferences, but I hope it gives you one or
two ideas. Try experimenting and see what works for you.
I've developed a vim module to do some simple remappings for exactly this issue:
https://github.com/vim-scripts/vim.ergonomic
The biggest things it does is make it easier to type bracket sets. It also makes it much easier to get into command mode (jj->ESC)
It runs on the principle that you hardly ever used the J key while editing, but it is right there in the home row... so let's abuse it!
from the documentation:
Remapping commonly used commands
key combo mapping purpose
; : removes the need to hit Shift to use commands
jj <ESC> can exit edit mode quickly and easily
Jj j can type 'j' when you need to
JJ J can type 'J' when you need to
Making it easier to insert various kinds of braces:
key combo mapping purpose
JU ()<left> easier to create parenthesis
JI []<left> easier to create square brackets
JM {}<left> eaiser to create curly braces
J< <><left> easier to create carrot braces
Make it easier to move small distances (especially useful with braces commands):
key combo mapping purpose
JL <left> move left in insert mode
JH <right> move right in insert mode
Removing any need for enter, backspace or delete:
key combo mapping purpose
JB <esc>ldbi delete the previous word
JW <esc>dwi delete the next word
JO <esc>oi insert line and go to it

Return to normal mode without leaving the home row

I've been trying out vim, and the emphasis on speed and accessibility makes sense for the veteran programmer. I've previously used emacs, and currently use a combination of nano, and stuff like gedit or geany.
I'm confused by the need to constantly switch modes, and that returning from insert mode to normal mode requires leaving the home row to press Esc. I've read that previously, this key was Tab on some systems where vim was first used, which makes a lot more sense, but not on current systems where tab is expected to participate in smart indenting when coding.
Returning to normal mode is an operation that you need to perform all the time. Is there some alternative key mapping that makes this quicker, or mappings that I simply don't know about that do this?
Ctrl+C also return you to normal mode
You can also use ^[. If you've mapped your caps lock key to control (highly recommended), this becomes a rather easy keystroke.
I personally use the Capslock key as the second Esc key, so it is very comfortable. You can do it by adding the following lines to your .xmodmap file:
remove Lock = Caps_Lock
keysym Caps_Lock = Escape
You can map whatever you like to escape:
imap kj <Esc>
I haven't yet run across a situation where I need to type kj next to each other, besides when I talk about this mapping. I've seen other people use jk or jj, but kj works best for me.
I personally use ii to get out of insert mode while staying on the home row, but it is only a matter of personal preference:
inoremap ii <Esc>
i to go in insert and ii to go out. This is easy for your finger to remember. (I tend to still use <Esc> though)
I personally use Left Control as escape and Caps Lock as Left Control. It is not vim mapping, but some xmodmap+setxkbmap magic:
! ~/.Xmodmap
! Control_R
keycode 37 = Escape
and ctrl:nocaps in X keyboard options. You may have different keycode though.
Use Alt/Meta In a Terminal
If you use Vim in a terminal, simply press alt/meta+normal_mode_key. Most terminals send an escape character followed by the normal_mode_key that you pressed, removing the need to press escape yourself.
The terminals konsole and gnome terminal send the escape by default when you press alt/meta+normal_mode_key. For Xterm you can ctrl+click and select the option "Meta sends escape" or "Alt sends escape".
Thus in insert mode pressing alt+h alt+j alt+k alt+l all take you to normal mode and move in the expected direction. You can hold down alt when moving even while in normal mode since the additional ESC that is sent does no harm.
The advantage of using this scheme is that you can use the alt/meta+key combination with any normal mode key, e.g.
Alt+o opens a new line below the one you are currently editing,
Alt+A appends to the end of the current line,
Alt+p pastes at the current insert location.
Alt+k moves up
Thus using vim via a terminal gives you these short cut powers on any stock standard system without the need to edit each systems vim mappings.

How to map Ctrl+A and Ctrl+Shift+A differently?

In a terminal, one cannot distinguish Ctrl+A and Ctrl+Shift+A as they both emit the same key code, so I can see why Vim can't do it. But gVim, being an X application, can differentiate Ctrl+A and Ctrl+Shift+A. Is there any way to map those two things differently?
For starters, I'd like to do something like the following: Make "paste from clipboard" work like Gnome terminal, while keeping Ctrl+V to the visual mode.
:nmap <C-S-V> "+gP
Gvim doesn't do it because vim cannot do it (under normal circumstances). Sorry, but that's just how it is.
However...
Some terminals (e.g., xterm and iterm2) can be configured to send an arbitrary escape sequence for any combination of keys.
For example, add the following to .Xresources for xterm to send <Esc>[65;5u for CtrlShiftA. You can then map that in Vim to <C-S-a>. (65 is the decimal Unicode value for shift-a and 5 is the bit for the ctrl modifier. The u in this case stands for "unicode".)
! .Xresources
XTerm*vt100.translations: #override Ctrl ~Meta Shift <Key>a: string(0x1b) string("[65;5u")
iTerm and [u]rxvt can also be configured to do this (examples not provided).
More info: http://www.leonerd.org.uk/hacks/fixterms/
As already pointed out, there are no ways to map <C-S-A> differently from <C-A>.
However, using tools like autokey (for linux & windows) or autohotkey (for windows), you can remap <C-S-A> to send a different key-stroke(s) for specific applications.
e.g. On my system, I have this setting in autokey:
$ cat ~/.config/autokey/data/gnome-terminal/ctrlshifta-gnome-terminal.py
#ctrl+shift+a sends '<S-F1>a'
keyboard.send_keys("<shift>+<f1>a") # Note that `f` in `f1` needs to be in lower case.
Assign it these properties:
keyboard-shortcut as ctrl+shift+a
window class: gnome-terminal-server.Gnome-terminal
Then your ~/.vimrc can create mapping for <S-F1>a to do whatever you want.
Notes:
I have used <S-F1> as kind of leader key for detecting <C-S>. This was because my terminal did not accept <F13>-<F37> etc keys. If your application supports it, (gvim does I think) using those keys is recommended.
I mainly vim in gnome-terminal. So I used window class = gnome-terminal-server.Gnome-terminal as filter. Modify it to use gvim if you want. autokey supports a button for capturing any other window's properties like class/title.
Due to the way that the keyboard input is handled internally, this unfortunately isn't generally possible today, even in GVIM. Some key combinations, like Ctrl + non-alphabetic cannot be mapped, and Ctrl + letter vs. Ctrl + Shift + letter cannot be distinguished. (Unless your terminal sends a distinct termcap code for it, which most don't.) In insert or command-line mode, try typing the key combination. If nothing happens / is inserted, you cannot use that key combination. This also applies to <Tab> / <C-I>, <CR> / <C-M> / <Esc> / <C-[> etc. (Only exception is <BS> / <C-H>.) This is a known pain point, and the subject of various discussions on vim_dev and the #vim IRC channel.
Some people (foremost Paul LeoNerd Evans) want to fix that (even for console Vim in terminals that support this), and have floated various proposals, cp. http://groups.google.com/group/vim_dev/browse_thread/thread/626e83fa4588b32a/bfbcb22f37a8a1f8
But as of today, no patches or volunteers have yet come forward, though many have expressed a desire to have this in a future Vim release.
If what bothers you is loosing existing C-V functionality, you can use C-Q instead. See, :help CTRL-V-alternative.
NeoVim now offers this functionality for both its terminal and gui clients. See :h nvim-features-new
As you've noted, you get the same keycode. So the only way to distinguish them is to check the state of the Shift key in your event handling function. Of course, if you have more than 0.5 second delay between keypress and processing, you'll miss some hits.
Most terminal emulators treat control plus shift simply as control by default. Instead, you usually map those key combinations to an escape sequence and listen to that inside the terminal application.
Step 1: Configure your terminal emulator to bind Ctrl+Shift+A to the sequence Esc,A.
Your terminal emulator is the program that shows the actual window of the terminal. When accessing a server via SSH, the terminal emulator is a program on your local machine. Binding keys works differently in different terminal emulators. For example:
For urxvt, add URxvt.keysym.Control-Shift-A: \033A to the ~/.Xresources configuration file and reload it with xrdb ~/.Xresources.
For iTerm2, open Preferences -> Keys, add an entry, and bind Ctrl+Shift+A to the action "Send Escape Sequence" and type A into the field below.
Step 2: Bind Esc,A to a command in Vim.
Add the key mapping to your ~/.vimrc configuration and reload it with :source ~/.vimrc:
nnoremap <esc>a your command here

Resources