Vim行末注释续行

5

假设我有一段代码:

int i = 0; // Do some junk here<cursor is here>

if(i == 0){
  blahblahblahblah;
}

blahblahblah;

我想知道是否可以告诉vim,当我按下回车键时,它会产生以下结果:

int i = 0; // Do some junk here
           // <cursor is here>

if(i == 0){
  blahblahblahblah;
}

blahblahblah;

我知道这个功能可以用于将单独一行的注释转换为这种格式,但是我无法找出其他的方法。


你安装了那种代码的插件吗?它只是Java、C、C++等吗? - mliebelt
主要是C语言。没有插件进行任何特殊处理。 - Luke Cycon
1个回答

4

我不确定是否有适用于此的插件(但可能会有一个),但是按下回车键添加行的以下映射应该能起到作用(虽然还有更多添加行的方法):

" Function that adds new line starting with comment symbol if line does not 
" start with comment, but contains it.
function! s:NewLine(comsymb)
    let line=getline('.')
    " Check whether we are in comment. Assumes syntax highlighting is working 
    " correctly. Remove these lines if you never write “//” in a string literal
    if empty(filter(synstack(line('.'), min([col('.'), col('$')-1])),
                \   'stridx(tolower(synIDattr(v:val, "name")), "comment")!=-1'))
        return "\n"
    endif
    let cidx=stridx(line, a:comsymb)
    if cidx==-1
        " No comments
        return "\n"
    elseif cidx==0 || line[:(cidx-1)]!~#'\S'
        " This assumes that vim own continuation works correctly: do not do work 
        " that can be done by something else
        return "\n"
    endif
    " Preserve tab indentation if any, correctly replace non-indent tabs with 
    " spaces
    let nextline=substitute(line[:(cidx-1)], '\v^(\s*)(\S.*)$',
                \           '\=submatch(1).'.
                \             'repeat(" ", strdisplaywidth(submatch(2), '.
                \                                          indent('.').'))',
                \           'g').a:comsymb
    " Preserve presence of a space after comment start mark
    if line[cidx+len(a:comsymb)] is# ' '
        let nextline.=' '
    endif
    return "\n".((col('.')<col('$'))?("\e\"_c0"):("\<C-\>\<C-o>\"_d0")).nextline
endfunction

inoremap <expr> <CR> <SID>NewLine('//')

这真是太棒了。谢谢!对于回复延迟我很抱歉,最近非常忙。 - Luke Cycon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接