You could try to add this to your .vimrc
I didn't tested it extensively but it looks like it is working.
function! MyHMotion()
" Get the position of the cursor and of the first non white character
let cursorPosition=getpos(".")
normal! ^
let firstChar=getpos(".")
if cursorPosition[2] == 1
" Cursor on first column : go to the end of line
normal! $
elseif cursorPosition[2] <= firstChar[2]
" Cursor before/on first non-whitespace character: go to first column
normal! 0
elseif cursorPosition[2] <= firstChar[2]+5
" cursor less than five columns after the first non-whitespace character: go to first non-white character
normal! ^
else
" Move normally
call setpos('.', cursorPosition)
normal! h
endif
endfunction
nnoremap <silent> h :call MyHMotion()<CR>
The function is commented and its behavior should be pretty clear. Here are some additional information:
- The
!
following normal
is here so that the command will not use user-defined mappings. More info at :h normal
- The last line
nnoremap <silent> h :call MyHMotion()<CR>
is here to map h so that the function MyHMotion()
is called each time you press the key.
- The
<silent>
argument is here so that nothing is echoed on the command line when the function is called. See :h :map-silent
I used these functions of mine as inspiration. They override h and l to skip the whitespaces at the beginning of a line:
" make h and l skip indentation white spaces {{{
function! MyLMotion()
let cursorPosition=getpos(".")
normal! ^
let firstChar=getpos(".")
if cursorPosition[2] < firstChar[2]
normal! ^
else
call setpos('.', cursorPosition)
normal! l
endif
endfunction
function! MyHMotion()
let cursorPosition=getpos(".")
normal! ^
let firstChar=getpos(".")
if cursorPosition[2] <= firstChar[2]
normal! 0
else
call setpos('.', cursorPosition)
normal! h
endif
endfunction
nnoremap <silent> h :call MyHMotion()<CR>
nnoremap <silent> l :call MyLMotion()<CR>
"}}}
H
one makes h go to the beginning of the line when the cursor is on the first non white character and go one character to the left if the cursor is anywhere else.