Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim comment continuation at end of line

Tags:

vim

So, lets say I have a chunk of code

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

if(i == 0){
  blahblahblahblah;
}

blahblahblah;

Is it possible to tell vim that when I hit enter, I want it do result in the following:

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

if(i == 0){
  blahblahblahblah;
}

blahblahblah;

I know it will do this for a comment who is on a line all on its own, but I can't figure out this way.

like image 612
Luke Cycon Avatar asked Oct 08 '22 09:10

Luke Cycon


1 Answers

I don’t know whether there is a plugin for this (but there may be one), but the following mapping should do the trick for adding a line by pressing enter (there are much more ways to add the line though):

" 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('//')
like image 115
ZyX Avatar answered Oct 12 '22 10:10

ZyX