像Intellij Idea一样,Vim中的CamelCase扩展? [英] CamelCase Expansion in Vim like Intellij Idea?
问题描述
在Intellij Idea中,有一个功能。假设我在代码中的某处使用了变量 myCamelCase
。然后,如果我输入 mCC
并按 Ctrl - Enter 或某些此类组合键,它会扩展为 myCamelCase
。在Vim中有类似的东西吗?
In Intellij Idea, there's a feature. Let's say I have used a variable myCamelCase
somewhere in my code. Then if I type mCC
and press Ctrl-Enter or some such key combination, it expands to myCamelCase
. Is there something similar in Vim?
推荐答案
好的,原谅我回答两次,但是因为我的第一次尝试错过了这一点,我我会再来一次。这比我想象的要复杂得多,但可能没有我做的那么复杂(!)。
Okay, forgive me for answering twice, but since my first attempt missed the point, I'll have another go. This is more complicated than I thought, but possibly not as complicated as I have made it (!).
现在修改它以建议所有匹配的变量名称。
首先,这是一个从'myCamelCase'字符串生成'mCC'缩写的函数:
First of all, here's a function to generate the 'mCC' abbreviation from the 'myCamelCase' string:
function! Camel_Initials(camel)
let first_char = matchstr(a:camel,"^.")
let other_char = substitute(a:camel,"\\U","","g")
return first_char . other_char
endfunction
现在,这是一个带缩写('mCC')和扫描当前缓冲区(从当前行向后)查找具有此缩写的单词。 返回所有匹配项的列表:
Now, here's a function that takes an abbreviation ('mCC') and scans the current buffer (backwards from the current line) for "words" that have this abbreviation. A list of all matches is returned:
function! Expand_Camel_Initials(abbrev)
let winview=winsaveview()
let candidate=a:abbrev
let matches=[]
try
let resline = line(".")
while resline >= 1
let sstr = '\<' . matchstr(a:abbrev,"^.") . '[a-zA-Z]*\>'
keepjumps let resline=search(sstr,"bW")
let candidate=expand("<cword>")
if candidate != a:abbrev && Camel_Initials(candidate) == a:abbrev
call add( matches, candidate )
endif
endwhile
finally
call winrestview(winview)
if len(matches) == 0
echo "No expansion found"
endif
return sort(candidate)
endtry
endfunction
接下来,这是一个自定义完成函数,它读取光标下的单词并建议上述函数返回的匹配项:
Next, here's a custom-completion function that reads the word under the cursor and suggests the matches returned by the above functions:
function! Camel_Complete( findstart, base )
if a:findstart
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '[A-Za-z_]'
let start -= 1
endwhile
return start
else
return Expand_Camel_Initials( a:base )
endif
endfunction
要使用此功能,你必须定义completefunc:
setlocal completefunc=Camel_Complete
要使用插入模式完成,请键入 CTRL-X CTRL-U ,但我通常将其映射到 CTRL-L :
To use insert-mode completion, type CTRL-X CTRL-U, but I usually map this to CTRL-L:
inoremap <c-l> <c-x><c-u>
在vimrc中使用此代码,您应该会发现输入 mCC
后跟 CTRL-L 将进行预期的替换。如果没有找到匹配的扩展,则缩写不变。
With this code in your vimrc you should find that typing mCC
followed by CTRL-L will make the expected replacement. If no matching expansion is found, the abbreviation is unchanged.
代码不是防水的,但它适用于我测试过的所有简单情况。希望能帮助到你。如果有任何需要澄清,请告诉我。
The code isn't water-tight, but it works in all the simple cases I tested. Hope it helps. Let me know if anything needs elucidating.
这篇关于像Intellij Idea一样,Vim中的CamelCase扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!