This seems to work quite well, and does fairly sane things when using <C-a>
on
a 9 (95 becomes 105), or using <C-x>
on a 0 (105 becomes 95):
nnoremap g<C-a> :call search('\d', 'c')<CR>a <Esc>h<C-a>lxh
nnoremap g<C-x> :call search('\d', 'c')<CR>a <Esc>h<C-x>lxh
- First, we search for any digit,
search()
has the advantage of not resetting @/
.
a <Esc>h
- Go to insert mode, add a space after the digit, and go to the left so that the cursor is on top of the digit.
- We can now use
<C-a>
or <C-x>
.
- We use
lxh
to remove the space we added.
I've mapped this to g<C-a>
and g<C-x>
, so you can still call the original.
A slightly different version which will only search for numbers on the current
line (but will leave a dangling space if there's no number on the current line):
nnoremap g<C-a> :call search('\d', 'c', line('.'))<CR>a <Esc>h<C-a>lxh
nnoremap g<C-x> :call search('\d', 'c', line('.'))<CR>a <Esc>h<C-x>lxh
And here's another version which uses the same concept as before, but also adds
a space before the digit. This will make g<C-a>
ignore any munis sign before
the number (by default, <C-a>
on -42
will 'increment' it to -41
.
It also accepts a count, so that 5g<C-a>
will increment the number by 5:
fun! Increment(dir, count)
" No number on the current line
if !search('\d', 'c', getline('.'))
return
endif
" Store cursor position
let l:save_pos = getpos('.')
" Add spaces around the number
s/\%#\d/ \0 /
call setpos('.', l:save_pos)
normal! l
" Increment or decrement the number
if a:dir == 'prev'
execute "normal! " . repeat("\<C-x>"), a:count
else
execute "normal! " . repeat("\<C-a>", a:count)
endif
" Remove the spaces
s/\v (\d{-})%#(\d) /\1\2/
" Restore cursor position
call setpos('.', l:save_pos)
endfun
nnoremap <silent> g<C-a> :<C-u>call Increment('next', v:count1)<CR>
nnoremap <silent> g<C-x> :<C-u>call Increment('prev', v:count1)<CR>
10<C-a>
to add 10 orr2
to replace the 1 with a 2. – jamessan Apr 14 '15 at 1:32