Vim: transitioning from mouse to movement - vim

I use MacVim (and gvim) a lot. I'm familiar with and use a lot of the basic movement commands (b, w, $, 0, G). However, for a lot of things—such as selecting particular lines on the screen or jumping to a particular column in a different line—I use the mouse (sometimes in concert with my left hand on the keyboard). It also helps that my mouse has a scroll wheel and buttons for changing tabs.
I also need to admit... I use the arrow keys on my keyboard rather than hjkl.
I think that my speed (and posture at the computer) will be improved by not having to escape from insert mode, and from keeping both hands on the main part of the keyboard.
What convinced you to abandon the mouse? What are the most helpful shortcuts for moving quickly between lines and columns, scrolling, etc.?
This question is inspired by this recent post

I think that my speed (and posture at
the computer) will be improved by not
having to escape from insert mode
No, you must escape from insert mode right after you typed what you want. It quickly becomes a reflex, so you don't really lose time (I sometimes even press escape after completing a web form...). Normal mode isn't just for moving around, it's used to perform most operations (save from typing): for instance deleting or moving sections of text. You also benefit from entering insert mode with the appropriate key: o to start a line, S to replace a line (while keeping indentation), A to move to the end of the line, c+motion to replace a few words or until a given character... All of these save keystrokes.
The mouse seems fast, but in reality it isn't precise, so you lose time (in addition to the constant back and forth with the keyboard). ViM has a long list of moving commands (see :help usr_03) which, when mastered, are faster than the mouse in most situations.
Use search the most you can (/, ?, *, #, f, t...). I personally use Ctrl+(d,u,f,b) a lot. Also, Ctrl+(o, i) and `` are really useful to go back where you were before a search or something else.
h, j, k, l are there to place your right hand near to useful commands (i, u, o...): I always have my fingers on them. The arrows force you to move your hand a lot.
Try to look at a few commands in :help, then use them a lot, and you'll get habits about what you should use to move according to the situation. Nobody uses ViM the same way.

The more I used the keyboard movement in vim, the less I wanted to use the mouse. It doesn't help that extended periods of time where I'm constantly moving from keyboard to mouse can take a toll on my wrist.
If you want to force doing things the vim way, unplug your mouse for a while! The more you use the keyboard, the more you will love it. This worked for me.
For moving between lines, I usually just use jk but I often skip to lines using :line_num. Getting to a specific column in a line, I typically use wbe^0$ and put modifiers in front of w, b, or e if I'm skipping through several words. And there is also the shifted versions, WBE which also come in handy often.

I have to admit that I often use the arrow keys for specific movement in vim.
I rarely use hjkl. However, I find that most of my navigation is done with other commands such as w (skip a word forward), b (skip a word backwards). Combine this with modifiers such as 3w (3 words forward). : skip to a specific line.
I've never really had to abandon the mouse since I never really started with it. All I can say is that attempting to use editors without all the keyboard shortcuts that vim has can feel quite painful.

I'd run vimtutor from the command line (Terminal.app in OS X). It runs vim with a tutorial document. That document was what really made me realize the power of some of the commands. You'll pick up some that are most useful to you and gain more over time. Eventually you'll find yourself using the mouse less and less.

One command that will really improve your movement speeds is f. f plus a character will jump to the first occurrence of that character on the current line. Pressing ; will jump to the next occurrence. Of course this can be used in combination with other commands. So, for example, removing all characters up to and including the first closing parenthesis is achieved by pressing d+f+).

You can seriously revolve your life around jk in hjkl.
nnoremap <c-k> ddkP "move current line up one
nnoremap <c-j> ddp "move current line down one
vnoremap <c-j> dp'[V'] "move visual block down one
vnoremap <c-k> dkP'[V'] "move visual block up one
"These may be a bit more esoteric to me"
inoremap jj <esc>o "Insert mode can move to next line (works mid line)
inoremap kk <esc>O "Insert mode new line on previous line
also for the desktop gui (ion3 and gnome)
winj - next window
wink - prev window
(This beats alttab if your editing in vim all day)
also read :he motion.txt in its entirety using j and k to scroll up and down as you do.

I learned vi so for me the mouse has never been something to use with a text editor.
I don't use hjkl except when the machine/network/keyboard/whatever-in-between is not comfortably configured.

Use the mouse where it makes sense. It often does (copy/paste to and from other gui applications).
To answer your question, though: Once you start using vim as a tool for transforming text bits with macros, the movements will all start to fall into place ;)

I think you're wondering if there's a quick way to move around while in insert mode (without using the mouse or arrow keys) but unfortunately there isn't; you have to escape out of insert mode. However I know that jumping all the way to your Esc key can be really annoying, which is why I've gotten into the habit of escaping with Ctrl+c, it's much faster.

I almost never use hjkl because it's too tedious. I usually try to jump right to where I want to go. There's a great cheat sheet out there (a Dvorak version is a available also (although it's in PDF)) that you can stare at and imagine the possibilities.
Mostly I use f, F, t, and T, and sometimes they're enhanced by typing a number up front like d2t) will delete up to the second close paren. Sometimes I use search. A lot of the time I use w, W, b, B, e, and E. They're all fantastic.
When I see vim users arrowing all over the place in visual mode just to delete text it makes me shudder, because there are so much easier ways (and hjkl only make you move your arm less, they don't change the number of button presses).
Something I did that I don't know if it's common or not is remapped my arrow keys to be <Esc><Up> and so on. For whatever reason I started out always arrowing around and assuming I'd be back in normal mode, so I just made it do that...
The biggest bummer about Vim is that now when I edit anything anywhere else I hit escape all of the time and type :w after every change...

Related

vim - navigating characters in command mode

Relatively new to VIM and having a great time using it.
One very minor annoyance I've been having is command mode character navigation when I want to revise a command. I'm used to using readline shortcuts on the regular (non-vim) command line but these shortcuts don't seem to work in : command mode.
For example, using ctrl + b to go back a character ends up sending me to the start of the line, or using alt + f to go forward a word ends up clearing the line and exiting command mode.
The only way I've found to navigate in command mode is to use the arrow keys, but I'm under the impression you should avoid the arrow keys in vim for max efficiency.
What is the standard way to navigate around in : command mode? Do vim users usually use the arrow keys here? Is there a different way to modify commands?
As a more concrete example, I've been using vimgrep a lot to search through files. I'll do a command like:
:vimgrep /font-family/j my-project/**/*.less | cope
Later, I'll want to use the same search but look for a different property, so I hit : then ctrl + p to access my previous vimgrep. Now here I have to use the arrow keys to navigate backwards to the search string and modify it. It would be much faster if I could use readline to navigate backwards by word then delete by word.
For small edits, Backspace and light use of the cursor keys should be fine. For anything larger, I would advise to use the command-line window:
In the command-line window the command line can be edited just like editing
text in any window.
So, there's no need to mentally switch to readline key mappings; just use the full editing power (including any custom mappings) of Vim!
You can switch via <C-F> from the command-line, or directly enter it (from normal mode) by pressing q: instead of :. All the details can be found at :help cmdline-window.
I like this question. Long time vim user, but new-ish here, so I can't vote it up. But indeed, perhaps unofficially, many vim fans feel that most of the time the goal is to not have your hands leave home row position (fingers move, hands relatively still).
I will admit, when it comes to command mode, I use the arrows. With P being on my pinky finger, I would miss-hit ctrl-P a lot, and it's faster to slide my right hand down (on my Natural keyboard) and find the up-arrow by quick feel, instantly, to do the same thing. Once I'm there, left-right arrows are also easy to find without looking or delay. Also Ctrl-arrows let you skip by word.
One of the great things about vim is the :help. I have easily spent tens of hours over the years reading through it, and it solves 95% of my problems if I have enough time and working-memory to push deep enough into it.
Here is what I found for :help readline:
READLINE readline.vim ft-readline-syntax
The readline library is primarily used by the BASH shell, which adds
quite a few commands and options to the ones already available. To
highlight these items as well you can add the following to your
|vimrc| or just type it in the command line before loading a file with
the readline syntax:
let readline_has_bash = 1
This will add highlighting for the commands that BASH (version 2.05a
and later, and part earlier) adds.
Give it a try! (I am using vim 7.4)
You can see a list of the default key binds with :help cmdline-history (scroll down a bit) and :help ex-edit-index.
You can remap this with cnoremap:
cnoremap <C-b> <Left>
cnoremap <C-a> <C-b>
" .. Probably more
Note that using cmap will probably get you into problems here since the right-hand side is the currently mapped action, whereas with cnoremap the right-hand side it will always use the native Vim action.

Effective way to put ; at the end of line

Sorry for a noob question, but i find it struggling to just put a ";" at the end of line after writing a function. For example, I am coding in C and many time i need to write things like:
f(a);
what i usually type is (from normal mode, using bracket autopair-like feature):
if(a<ESC><SHIFT-a>;
and it need changing mode twice! Comparing to normal editor (sublime):
f(a<right>;
does anyone have more efficient way do do those typing? thanks for any help.
I think you have some "auto-close" plugin installed.
I have that kind of plugin too, and I don't press arrow keys either, since I don't have them on my keyboard. I have this:
" moving cursor out of (right of ) autoClosed brackets
inoremap <c-l> <esc>%%a
So with your example: it would be (assume already in INSERT mode)
f(a<ctrl-l>;
Thus, your fingers never leave the home row.
If you're a vim user, you can hit Shift-a.
Shift-a takes you from normal mode to insert mode, and starts your cursor at the end of the line.
(If you want to be an efficient vim user, you should remap esc to something like caps-lock.)
Comparing to normal editor (sublime):
f(a<right>;
Well… that's exactly how you would do it in Vim if you use Delimitmate or some other "autoclosing" plugin. Why do you insist on making things more complicated than they are?

In Vim, how can I switch the functionality of 'i', 'j', 'k' and 'h'

I am 5 or so weeks into learning Vim for development, and while things are starting to sink in, I have one personal issue that is frustratingly still tripping me up.
I am constantly using 'i' to move 'up.' 'k' is down, 'j' and 'l' are left and right respectively.
I know this all comes from playing too many years of PC games where these were direction movements. Honestly, I don't want to fight it anymore, and I would rather do what is extremely natural for me. How can I remap these so the above are the direction movements and 'h' is insert?
2 issues: How can I permanently store these in my local settings for development on my own machine, and how can I also quickly switch these when I am on someone else's machine for the time I am working on it. I mean, is there a set of commands that I can invoke and then they be erased when I shut Vim down?
DON'T DO THAT MAPPING! It is even worse than using arrow keys
first of all, I would suggest you learning the vim way to move your cursor.
Back to your question, remapping h,j,k,l is easy. However, it makes no sense to do those mapping (and you shouldn't do it), it won't make you work faster, it just drives you crazy when you use your vim. You know, editing with vim doesn't mean
in NORMAL mode, just do cursor moving
entering INSERT mode, do actual text editing
back to NORMAL mode to save the file
There are a lot of vim magic you could do in NORMAL mode (that's why it was called NORMAL). with your mapping, you will really have headache when you want to apply those. Let's take an example. Say you have already set mappings for your needs. i,j,k and h. We have a line:
function foo (String arg)
when your cursor is between (and ), you could type ci( to change the stuff in brackets. However your i means k. What would happen? the current line and the line above it will be removed!! Well you could say, you will remember to type chw, dhw,ch(,dhw... So you have to remap those keys also in your mind. :)
Also when you want to "borrow" someone else's .vimrc, or use some plugins, you will have problem too.
You see the point by the simple example above. So please think it twice before you remap those basic keys.
Put this in a file called ~/.vimrc:
noremap i k
noremap k j
noremap j h
noremap h i
If you're using vim on someone else's computer, you can type the same four commands at the prompt (type : before each, and enter after each), and the settings will apply for 1 session only.
Also, no is short for noremap, so you can shorten the whole sequence to
:no i k<enter>:no k j<enter>:no j h<enter>:no h i<enter>
when you're using someone else's computer.

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

Is there a way to emulate ReSharper's "extend selection" feature in Vim?

ReSharper has a nice feature called "extend selection": by pressing CTRL+W (I think this is the default) repeatedly, you select more and more from your current caret location. First it's a word, then more and more words, a line, inner then outer block of lines (for example an if-block), then a function, etc...
Basically, by pressing the key combination repeatedly, you can end up selecting the entire file. I'm sure at least some of you will be familiar with it.
I have just started learning all the intricacies of vim and I don't have enough experience to see how something like this could be implemented in Vim (although I assume it's possible). So my question is meant for Vim gurus out there: can this be done and how?
Update: a bit of a background story. I've been talking to my ex-boss about all the benefits of Vim, and he thinks it's all great. His only question/problem was: does it have "extend selection"? My question so far has been no. So, if someone knows the answer, I'll finally win a discussion :P (and maybe create a new Vim convert:-))
I had a quick go at this problem. It doesn't work as is. Feel Free to make edits and post on the vim wiki or as a plugin if you get it refined.
chances are you'd want to make a g:resharp_list for each language (eg. one for paranthesised languages, etc.)
All that is needed is a marker for the original cursor position :he markers and a timeout autocommand that resets the index.
"resharp emulator
"TODO this needs a marker
"also c-w is bad mapping as it has a lag with all the other-
"window mappings
"
let g:resharp_index = 0
let g:resharp_select = ['iw', 'is', 'ip', 'ggVG']
func! ResharpSelect()
if g:resharp_index >= len (g:resharp_select)
let g:resharp_index = 0
endif
exe "norm \<esc>v" . g:resharp_select[g:resharp_index]
let g:resharp_index = g:resharp_index + 1
endfun
nnoremap <c-w> :call ResharpSelect()<cr>
vnoremap <c-w> :call ResharpSelect()<cr>
"Something to reset on timeout. TODO this doesn't work
au CursorHold :let g:resharp_index = 0<cr>
The answer is yes. Once in Visual mode you can use all the regular navigation methods as well as some extra ones.
Some of my favourites? First hit v while in normal mode to get to visual mode then hit:
iw - to select the inner word. Great for selecting a word while excluding surrounding braces or quotes
w - hit multiple times to keep selecting each subsequent word.
b - select wordwise backwords
^ - select all from current position to beginning of text on line
$ - select all from current position to end of line
I'm sure others here could add to this list as well. Oh and don't forget Visual Block mode C-v try it out in vim with the above commands it works in two dimensions :-)
If you're talking about Vim (and you should be :-), you can start marking text with the v command, then you have all the standard cursor movement commands (and, as you know, there are a lot of them) which will extend the selection, as well as moving the cursor.
Then you just do whatever you want with the selected text.
See here for the gory details.
One would need to write a function that would save the current selection, then try increasingly wide selections, until the new selection exceeds the saved one or selects all text. Some possible selections are:
viW - select word
vis - select sentence
vip - select paragraph
viB - select text within the innermost brackets
v2iB - select text within the next most innermost brackets
ggVG - select all text
I think Jeremy Wall's heading in the right direction. And to get a little further in that direction, you might look at the "surround.vim" script from Tim Pope. A good description is available on github. Or, if you'd rather, get it from vim.org. It'll probably help you do some of the things you'd like to do, though it doesn't seem to have a feature for say, simply selecting within a tag. Let me know if I'm wrong.
Ultimately, what you'd really like is a hierarchy of enclosing text-objects. You should read up on text-objects if you haven't. A nice overview is here. Note that you can grab multiple objects in one go using counts, or do this iteratively (try vawasap}}} from normal mode).
You can also get scripts which define other text-objects, like this one that uses indentation to define a text-object. It'll work for many languages if you're formatting according to common standards, and guaranteed for python.
One annoyance is that the cursor ends up at the end of the visual block, so, for example, you can't easily select everything between some ()'s, then get the function name that precedes them...
...BUT, I just found in this post that you can change this behavior with o. Cool!
I suspect you'll find yourself more efficient being able to skip over intermediate selections in the long run.
Anyway, I'll be curious to see if anyone else comes up with a more general solution as well!
In Rider [on a Mac with VS Mac bindings with IdeaVim], I bind:
Ctrl+= to Extend Selection
Ctrl+- to Shrink Selection
Doesn't clash with any other bindings of consequence and doesn't require a v for mode switching, and easier than Cmd+Option+-> and Cmd+Option+<-
Putting it here as I always hit this question with any Rider Vim selection searches. If I get enough harassment, I'll create a self-answered "How to use Extend Selection with Rider Vim mode".

Resources