Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change word under cursor from inside a vim function

Tags:

function

vim

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()?

like image 450
Ben Avatar asked Mar 07 '26 05:03

Ben


1 Answers

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.

like image 106
Luc Hermitte Avatar answered Mar 08 '26 23:03

Luc Hermitte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!