在 vim 中保留 C++ 注释中的缩进

Preserve indentation in C++ comments in vim

是否可以配置 vim 和 cindent 在重新缩进文件 (gg=G) 时不改变 c++ 注释中的缩进?

我在注释中有一些格式化列表与 4 个空格对齐,但 vim 将其解释为缩进错误并重新对齐所有内容。

例如:

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

变成:

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

我想要一种方法来告诉 vim:"Don't touch to comments content but indent everything else."

这很重要,因为我们的项目使用带有降价解析器的 doxygen 来生成文档,并且列表级别使用缩进。

这样写怎么样,这样评论中的缩进独立于评论缩进:

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

根据评论的建议,我重新post 一个答案,其中 vi stackexchange community 的答案在这里:

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:

我跳过了第一个我不使用的解决方案,因此不是答案。原来的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>

我个人定义了一个 command 调用此函数并将其与我经常应用于此项目文件的另一个重新格式化相结合 (:%s/\s*$//g)。

感谢Rich on https://vi.stackexchange.com

原文post:https://vi.stackexchange.com/a/13962/13084