简体   繁体   中英

Preserve indentation in C++ comments in vim

Is it possible to configure vim and cindent to not alter indentation in c++ comments when reindenting the file (gg=G) ?

I have some formated lists in comments aligned with 4 spaces but vim interpret this as bad indent and realign everything.

For example:

/**
    my list:
         * item 1
         * item 2
 */

becomes:

/**
    my list:
    * item 1
    * item 2
*/

I want a way to tell vim: "Don't touch to comments content but indent everything else."

It is important because our project use doxygen with a markdown like parser to generate documentation and indentation is used by list levels.

How about writing like this so in-comment indentation is independent of comment indentation:

/**
*    my list:
*        * item 1
*        * item 2
*/

As suggested by review, I repost an answer with answer from vi stackexchange community here:

I don't believe it's possible to achieve this with 'cinoptions' .

The correct solution is probably to write a new indentexpr that applies C-indenting (accessible via the cindent() function) only to lines that aren't within comments.

However, here's a couple of quick and dirty solutions:

I skipped first solution which I don't use and is therefore not the answer. You can still see it on the original post.

Using a Function

 function! IndentIgnoringComments() let in_comment = 0 for i in range(1, line('$')) if !in_comment " Check if this line starts a comment if getline(i) =~# '^\\s*/\\*\\*' let in_comment = 1 else " Indent line 'i' execute i . "normal ==" endif else " Check if this line ends the comment if getline(i) =~# '\\*\\/\\s*$' let in_comment = 0 endif endif endfor endfunction 

You can run this with :call IndentIgnoringComments() or you could set up a command or a mapping. eg:

 nnoremap <leader>= :call IndentIgnoringComments()<CR> 

I personaly defined a command which call this function and combine it with another reformating I apply often on files in this project ( :%s/\\s*$//g ).

Thank to Rich on https://vi.stackexchange.com

Original post: https://vi.stackexchange.com/a/13962/13084

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM