2021年3月20日 星期六

在vim中建立clang-format功能

 目的: 

在vim中加入clang-format的附件功能,並以google當作coding sytle。

步驟:

1. 在vim加入套件管理程式Vundle

    1-1. 下載vundle模組

        git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/Vundle.vim

    1-2. 下載clang-format程式和vundle的模組

        sudo apt-get install clang-format
        git clone https://github.com/rhysd/vim-clang-format.git  ~/.vim/Vundle.vim/vim-clang-format

    1-3. 加入vimrc並改為特定的內容

        vim ~/.vimrc

       內容如下:

set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/Vundle.vim/
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
call vundle#end()            " required
filetype plugin indent on    " required


    1-4. 一般模式下輸入:PlugInstall安裝Vundle模組的部份,若是成功會在右下角暗道Done!的字樣。

2. 增加clang-format的功能和vim相關的外掛模組

    2-1. 安裝clang-format

        sudo apt-get install clang-format

    2-2.在vimrc加入clang-format模組部份:

        Plugin 'rhysd/vim-clang-format'

    2-3.一般模式下輸入:PlugInstall安裝Vundle模組的部份,若是成功會在右下角暗道Done!的字樣。


    2-4.在.vim同的同層的資料夾下使用指令

        clang-format -style=google -dump-config > ./.clang-format 

        建立google的coding style規則。

3. 為了更方便使用,將vim的clang-format加入快捷鍵(ctrl+f)的功能。為此要在vimrc裡面加入以下內容:

        let g:clang_format#command = 'clang-format'
        nmap <c-f> :ClangFormat<cr>
        autocmd FileType c ClangFormatAutoEnable
        let g:clang_format#detect_style_file = 1

4. 最終的vimrc如下:

set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/Vundle.vim/
call vundle#begin()

Plugin 'gmarik/Vundle.vim'
Plugin 'rhysd/vim-clang-format'
call vundle#end()            " required
filetype plugin indent on    " required

let g:clang_format#command = 'clang-format'
nmap <c-f> :ClangFormat<cr>
autocmd FileType c ClangFormatAutoEnable
let g:clang_format#detect_style_file = 1

5. 最後即可在自己的c語言裡面藉由ctrl+f將程式排版成符合google的coding style。


參考資料:

1. Linux下vim配置clang-format的方法

2. Vim 套件管理程式 Vundle

3. [Vim] Vim 的插件管理工具 Vundle

沒有留言:

張貼留言