Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore space after comments when calculating indent level in Vim

Consider writing a JavaDoc-style comment which includes an indented list (when expandtab is set and softtabstop=2):

/**
 * First line:
 *   - Indented text
 */

Currently, after typing First line: and hitting return, Vim will correctly insert *<space>. However, when I hit tab to indent the second line, only one space will be inserted instead of two.

Is it possible to fix this, so the space after * will be ignored during indent calculations?

like image 463
David Wolever Avatar asked Nov 14 '22 08:11

David Wolever


1 Answers

I am still a beginner at VimScript, but I cooked this up for you. Give it a try and let me know what you think.

function AdjustSoftTabStop()
    " Only act if we are in a /* */ comment region
    if match(getline('.'), '\s*\*') == 0
        " Compensate for switching out of insert mode sometimes removing lone
        " final space
        if match(getline('.'), '\*$') != -1
            " Put back in the space that was removed
            substitute/\*$/\* /
            " Adjust position of the cursor accordingly
            normal l
        endif
        " Temporary new value for softtabstop; use the currect column like a
        " base to extend off of the normal distance
        let &softtabstop+=col('.')
    endif
endfunction

function ResetSoftTabStop()
    " Note that you will want to change this if you do not like your tabstop
    " and softtabstop equal.
    let &softtabstop=&tabstop
endfunction

" Create mapping to call the function when <TAB> is pressed. Note that because
" this is mapped with inoremap (mapping in insert mode disallowing remapping of
" character on the RHS), it does not result in infinite recursion.
inoremap <TAB> <ESC>:call AdjustSoftTabStop()<CR>a<TAB><ESC>:call ResetSoftTabStop()<CR>a
like image 110
Keith Pinson Avatar answered Dec 10 '22 23:12

Keith Pinson