Vim indentation for c++ templates?

前端 未结 2 1724
青春惊慌失措
青春惊慌失措 2021-02-04 18:48

Does anyone have or know about vim plugin/macro/function that indents nicely c++ templates?

When I highlight template definition in vim .hpp/.h file and indent it with \

2条回答
  •  难免孤独
    2021-02-04 18:59

    My solution:

    " Don't indent namespace and template
    function! CppNoNamespaceAndTemplateIndent()
        let l:cline_num = line('.')
        let l:cline = getline(l:cline_num)
        let l:pline_num = prevnonblank(l:cline_num - 1)
        let l:pline = getline(l:pline_num)
        while l:pline =~# '\(^\s*{\s*\|^\s*//\|^\s*/\*\|\*/\s*$\)'
            let l:pline_num = prevnonblank(l:pline_num - 1)
            let l:pline = getline(l:pline_num)
        endwhile
        let l:retv = cindent('.')
        let l:pindent = indent(l:pline_num)
        if l:pline =~# '^\s*template\s*\s*$'
            let l:retv = l:pindent
        elseif l:pline =~# '\s*typename\s*.*,\s*$'
            let l:retv = l:pindent
        elseif l:cline =~# '^\s*>\s*$'
            let l:retv = l:pindent - &shiftwidth
        elseif l:pline =~# '\s*typename\s*.*>\s*$'
            let l:retv = l:pindent - &shiftwidth
        elseif l:pline =~# '^\s*namespace.*'
            let l:retv = 0
        endif
        return l:retv
    endfunction
    
    if has("autocmd")
        autocmd BufEnter *.{cc,cxx,cpp,h,hh,hpp,hxx} setlocal indentexpr=CppNoNamespaceAndTemplateIndent()
    endif
    

提交回复
热议问题