Is it possible to format C++ code with VIM?

后端 未结 9 1623
野的像风
野的像风 2020-12-07 14:58

I am rather new to VIM. I got some source code and this is a mess. At a first sight I would like at least to get a clear and organised view of the code, so I like to get it

相关标签:
9条回答
  • 2020-12-07 15:19

    you can do the following:

    gg=G
    
    0 讨论(0)
  • 2020-12-07 15:21

    I don't write C++ code, but I write some Java code.

    Instead, Vim supports the formatting of some common languages. I have set up a short cut for me to format the whole code in the buffer. It will return to the line I just edited :)

    " format the file
    map <leader>fm gg=G'. 
    
    0 讨论(0)
  • 2020-12-07 15:23

    There is a vim plugin that enables formatting on your code from within vim. It's called vim-autoformat and you can download it here:

    https://github.com/Chiel92/vim-autoformat

    It integrates external code-formatting programs into vim. For example, if you want to format C, C++, C# or Java code, you need to install the program astyle, and vim sets it as the format program automatically.

    0 讨论(0)
  • 2020-12-07 15:25

    Vim will definitely do this, although the results may not be perfect:

    1. First, select the entire file in visual mode: ggVG
    2. Then hit = to reindent everything.

    You can learn more about the equal command with: :help =

    0 讨论(0)
  • 2020-12-07 15:34

    I would highly recommend clang-format nowadays. It allows simple integration of clang-format into Vim, once you have clang-format installed:

    http://clang.llvm.org/docs/ClangFormat.html#vim-integration

    It is the only code beautifier that really understands your C++ code, and it is really intelligent to beautify the code more like a human being than a machine. E.g.:

    void TestFunction(int argument1, int argument2,
                      int argument3);
    void TestFunctionVeryLongName(int argument1,
                                  int argument2,
                                  int argument3);
    void TestFunctionWithRidiculouslyLongName(
        int argument1, int argument2, int argument3);
    
    0 讨论(0)
  • 2020-12-07 15:35

    There is also a Vim plugin relying on clang-format: vim-clang-format

    Then you can simply map the formatting command to whatever suits you.

    0 讨论(0)
提交回复
热议问题