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

Consider writing a JavaDoc style comment that includes indentation (when expandtaband is installed softtabstop=2):

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

Currently, after typing First line:and clicking return, Vim will insert correctly *<space>. However, when I hit tabto insert the second row, only one place will be inserted instead of two.

Can this be fixed, so the space after *will be ignored during indentation calculations?

+5
source share
1 answer

I am still new to VimScript, but I have prepared it for you. Try it 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
+1
source

All Articles