Saturday, January 21, 2012

Re: Question about command-line mode mapping

Benoit Thomas <benoit.thomas@gameloft.com> a écrit:
>
> Hi,
>
> I'm trying to add some shortcuts in the command-line mode, mainly I want
>
> <C-B> to jump backward by word

Don't ask me how the following works exactly, I'm not sure I really
understand what's going on. I'm a bit confused with g/setcmdpos()
starting counting at 1, while other string functions start counting at
0. Anyway it seems to work (I've added <C-W> to go forward, I supposed
you'll need it):

function! Backword ()
let l:cmd = getcmdline()
let l:pos = getcmdpos()

" Position of the last character if the cursor was in the last
" (empty) column.
if strlen(l:cmd) < l:pos
let l:pos -= 1
endif

" If the current position is immediately preceded by blanks, go to
" the beginning of them.
let l:pos = match(strpart(l:cmd, 0, l:pos-1), '\zs\s*$')

" Check the type of the character on the left of the current
" position, and move left as long as there are characters of the
" same type.
if match(l:cmd, '^[[:alnum:]]', l:pos-1) > 0
let l:pos = match(strpart(l:cmd, 0, l:pos), '[[:alnum:]]\+$')
else
let l:pos = match(strpart(l:cmd, 0, l:pos), '[^[:alnum:]]\+$')
endif

call setcmdpos(l:pos+1)
return l:cmd
endfunction

function! Forword ()
let l:cmd = getcmdline()
let l:pos = getcmdpos()-1

" Go to the first character of a different type than the one under the
" cursor.
if match(l:cmd, '^[[:alnum:]]', l:pos) >= 0
let l:pos = match(l:cmd, '[^[:alnum:]]', l:pos)
else
let l:pos = match(l:cmd , '[[:alnum:][:blank:]]', l:pos)
endif

" Move to the first non-blank.
let l:pos = match(l:cmd, '\S', l:pos)

" The previous operation might have returned -1 if the cursor was in
" the last column; this restore it there.
call setcmdpos(l:pos > 0 ? setcmdpos(l:pos+1) : len(l:cmd)+1)
return getcmdline()
endfunction

cnoremap <C-B> <C-\>eBackword()<CR>
cnoremap <C-W> <C-\>eForword()<CR>

It does seem a bit convoluted, though, so hopefully somebody will find
something simpler.

Best,
Paul

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: