I have a file that uses 4-space indentation. By default, when I move horizontally, Vim moves over those spaces one by one.
How can I configure Vim so that it moves 4 spaces horizontally when moving over indentation whitespace?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
Maybe you can add the following functions to your
.vimrc. They compare the current position of the cursor to the position of the first character and if necessary they skip the non printed characters before the first non blank one.
function! MyLMotion() let cursorPosition=getpos(".") normal ^ let firstChar=getpos(".") if cursorPosition < firstChar normal ^ else call setpos('.', cursorPosition) normal! l endif endfunction
This one goes on the right: if the cursor is before the first non blank character, then we use
normal ^ to skip the whitespaces. If we are already on the line we use
normal! l to move on the right. Note the use of
!which allows to use the original
l motion even if we remap the key (this will be necessary otherwise we create a recursive function).
function! MyHMotion() let cursorPosition=getpos(".") normal ^ let firstChar=getpos(".") if cursorPosition <= firstChar normal 0 else call setpos('.', cursorPosition) normal! h endif endfunction
This one goes on the left, this time if the cursor is on the first non blank character we use
normal 0 to go on the beginning of the line and skip the white spaces.
You then have to create these mappings:
nnoremap <silent> h :call MyHMotion()<CR> nnoremap <silent> l :call MyLMotion()<CR>
Note the use of silent to prevent the messages
call MyXMotion to be output in the status line each time you press
And you can use your
l keyslike before but they'll skip the unwanted space at the beginning of your line.
Note that the advantage of this solution is that the functions should work whatever your configuration is (tabs of whitespaces).