像Intellij Idea一样在Vim中进行CamelCase扩展?

dha*_*0us 5 vim camelcasing intellij-idea

在Intellij Idea中,有一个功能.假设我myCamelCase在代码中的某处使用过变量.然后,如果我键入mCC并按Ctrl- Enter或某些此类组合键,它会扩展为myCamelCase.Vim有类似的东西吗?

Pri*_*ash 8

好的,请原谅我两次回答,但是由于我的第一次尝试错过了这一点,我还会再来一次.这比我想象的要复杂得多,但可能不像我做的那么复杂(!).

现在修改它以建议所有匹配的变量名称.

首先,这是一个从'myCamelCase'字符串生成'mCC'缩写的函数:

function! Camel_Initials(camel)
    let first_char = matchstr(a:camel,"^.")
    let other_char = substitute(a:camel,"\\U","","g")
    return first_char . other_char
endfunction
Run Code Online (Sandbox Code Playgroud)

现在,这是一个函数,它采用缩写('mCC')并扫描当前缓冲区(从当前行向后)查找具有此缩写的"单词".返回所有匹配的列表:

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
Run Code Online (Sandbox Code Playgroud)

接下来,这是一个自定义完成函数,它读取光标下的单词并建议上述函数返回的匹配项:

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
Run Code Online (Sandbox Code Playgroud)

要使用它,您必须定义"completefunc":

setlocal completefunc=Camel_Complete
Run Code Online (Sandbox Code Playgroud)

要使用插入模式完成,请键入CTRL-X CTRL-U,但我通常将其映射到CTRL-L:

inoremap <c-l> <c-x><c-u>
Run Code Online (Sandbox Code Playgroud)

在vimrc中使用此代码,您应该会发现mCC后面的输入CTRL-L将进行预期的替换.如果未找到匹配的扩展,则缩写不变.

代码不是防水的,但它适用于我测试过的所有简单案例.希望能帮助到你.如果有任何需要澄清,请告诉我.