开发者

Change word under cursor from inside a vim function

I want to write a function, which increases/decreases the size of a LaTeX text. E.g., when the cursor is above the word \footnotesize I want to call Tex_ChangeSize(-1) to change it to \small and Tex_ChangeSize(1) to change it to \normalsize.

What I have is the following:

function! Tex_ChangeSize(direction)
    let sizes = ["tiny", "scriptsize", "footnotesize", "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge"]
    let cursize = index(sizes,expand("<cword>"))
    if cursize != -1
        "FIXME: replace current word under cursor with the following
        echo sizes[cursize + a:direction]
    endif
endfunction
imap <C-h> <C-o>:call Tex_ChangeSize(-1)<Enter>
imap <C-g> <C-o>:call Tex_ChangeSize(1)<Enter>

What I don't know is, how to replace the word under cursor (see FIXME). To be more precise: Is there a better way than parsing开发者_开发百科 getline(line('.')) and setting it back with setline()?


getline+setline is one the neater choice as it won't mess any register (neither @" nor @/), however finding the limits of a current word is a bit tricky in an utf-8 world where tab characters (\t) can also be used. (col('.') + match() will do it ; see https://github.com/LucHermitte/lh-misc/blob/master/plugin/vim-tip-swap-word.vim for examples)

You can also have a nnoremapping that does a simple cw<c-r>=<sid>ChangeSize(1)<cr> with s:ChangeSize() that tests @" to see which symbol is next in order to return it -- not messing @" is simple though in this case.

You can also play with :exe 'normal! "_cw'.new_word from within the function if you'd rather not have it return anyting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜