fievel
fievel

Reputation: 480

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.

Upvotes: 4

Views: 340

Answers (2)

fievel
fievel

Reputation: 480

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. e.g.:

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

Upvotes: 1

user7860670
user7860670

Reputation: 37549

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

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

Upvotes: 3

Related Questions