简体   繁体   English

从vim函数内部更改光标下的单词

[英]Change word under cursor from inside a vim function

I want to write a function, which increases/decreases the size of a LaTeX text. 我想编写一个函数,该函数增加/减小LaTeX文本的大小。 Eg, 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 . 例如,当光标在\\ footnotesize单词上方时,我想调用Tex_ChangeSize(-1)将其更改为\\ small,Tex_ChangeSize(1)将其更改为\\ 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). 我不知道的是,如何替换光标下的单词(请参阅FIXME)。 To be more precise: Is there a better way than parsing getline(line('.')) and setting it back with setline() ? 更精确地说:有没有比解析getline(line('.'))并用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) getline + setline是更整洁的选择之一,因为它不会弄乱任何寄存器( @"@/ ),但是在utf-8世界中,使用制表符(\\ t)来查找当前单词的限制有些棘手也可以使用。( col('.') + match()可以做到;见https://github.com/LucHermitte/lh-misc/blob/master/plugin/vim-tip-swap-word.vim举些例子)

You can also have a nnoremapping that does a simple cw<cr>=<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. 您也可以使用nnoremapping进行简单的cw<cr>=<sid>ChangeSize(1)<cr>s:ChangeSize() ,以测试@"来查看下一个符号以返回它-不会弄乱@"很简单,但在这种情况下。

You can also play with :exe 'normal! "_cw'.new_word 您也可以使用:exe 'normal! "_cw'.new_word :exe 'normal! "_cw'.new_word from within the function if you'd rather not have it return anyting. 函数中的:exe 'normal! "_cw'.new_word如果您不希望它返回任何内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM