使用vundle在vim配置C与Golang开发环境

# 1、安装编译器及其依赖

安装Golang。

安装gcc:

1
sudo apt install gcc universal-ctags cscope vim

默认的vim不支持python3,如果想在vim中编写Python代码,可以安装vim.nox替代,它默认支持python3。

也可以重新编译vim,使其支持python3。

# 2、配置vim开发环境

# 2.1 创建目录

1
2
mkdir -p ~/.vim/bundle
mkdir -p ~/.vim/syntax

# 2.2 配置.vimrc

创建~/.vimrc文件并输入以下配置:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
" 通用配置

"打开语法高亮。自动识别代码,使用多种颜色显示
if has("syntax")
    syntax on
endif

set nu              "显示行号
"set nonu           "取消显示行号

set shiftwidth=4    "设置缩进的空格数为4
set tabstop=4       "设定tab长度为4
set autoindent      "设定自动缩进,下一行的缩进自动跟上一行的缩进保持一致
set cindent         "设置使用C/C++语言的自动缩进方式
set cursorline      "突出显示当前行

set autoread        "打开文件监视.如果在编辑过程中文件发生外部改变(比如被别的编辑器编辑了),就会发出提示

set hlsearch        "启用高亮搜索
"set nohlsearch     "关闭高亮搜索
set incsearch       "查询增量模式,自动追随要查找的内容,并就自动跳到第一个匹配的结果
"set nohl           "只取消当前的搜索高亮
set ignorecase      "搜索忽略大小写
set smartcase       " Do smart case matching

set noeb            "去掉输入错误的提示声音
set laststatus=2    "总是显示状态行

set showmode   "显示当前是处于命令模式还是插入模式
set showcmd    "显示当前输入的命令

set ruler  "在编辑过程中,在右下角显示光标位置的状态行

" 命令模式下,底部操作指令按下 Tab 键自动补全。
"  第一次按下 Tab,会显示所有匹配的操作指令的清单;
"  第二次按下 Tab,会依次选择各个指令。
set wildmenu
set wildmode=longest:list,full

" 设置在状态行显示的信息: 文件格式, 编码格式, 当前行的第几个字符, 当前行数, 文件总行数
set statusline=\ %<%F[%1*%M%*%n%R%H]%=\ %y\ %0(%{&fileformat}\ %{&encoding}\ %c:%l/%L%)\
"显示文件名:总行数,总的字符数
"set statusline=[%F]%y%r%m%*%=[Line:%l/%L,Column:%c][%p%%]

"切换文件时,如果当前文件被修改,则自动保存,不再提示
set autowriteall

"语言设置
set enc=utf-8
set fencs=utf-8,ucs-bom,shift-jis,gb18030,gbk,gb2312,cp936
set langmenu=zh_CN.UTF-8
set helplang=cn

"映射光标在窗口间移动的快捷键
nmap <C-h> <C-W>h
nmap <C-j> <C-W>j
nmap <C-k> <C-W>k
nmap <C-l> <C-W>l

"去掉当前高亮
nmap <C-n> :nohl<CR>

"刷新当前文件,重新载入当前文件
nmap <F5> :edit<CR>

"设置或取消paste模式
nmap <F6> :set paste<CR>
nmap <F7> :set nopaste<CR>

"======快捷键调用函数,当前文件头部添加注释(/* */格式)======
function UpdateTitle()
    normal m'
    execute '/* Last modified\s*:/s@:.*$@\=strftime(": %Y-%m-%d %H:%M:%S")@'
    normal "
    normal mk
    execute '/* Filename\s*:/s@:.*$@\=":      ".expand("%:t")@'
    execute "noh"
    normal 'k
    echohl WarningMsg | echo "Successful in updating the copy right." | echohl None
endfunction

function AddTitle()
    call append(0,"/**********************************************************")
    call append(1," * Filename:      ".expand("%:t"))
    call append(2," * Author:        sunxidong")
    call append(3," * Email:         sunxidong9999@gmail.com")
    call append(4," * Created:       ".strftime("%Y-%m-%d %H:%M:%S"))
    call append(5," * Last modified: ".strftime("%Y-%m-%d %H:%M:%S"))
    call append(6," * Description: ")
    call append(7," * *******************************************************/")
    echohl WarningMsg | echo "Successful in adding the copyright." | echohl None
endfunction

function AddAuthor()
    let n=1
    while n < 7
        let line = getline(n)
        if line =~'^\s*\*\s*\S*Last\s*modified\s*:\s*\S*.*$'
            call UpdateTitle()
            return
        endif
        let n = n + 1
    endwhile
    call AddTitle()
endfunction
" 设置快捷键,按F9后向当前文件头部添加注释(/* */格式)
map <F9> ms:call AddAuthor()<cr>'s

function UpdateTitle_M()
    normal m'
    execute '/# Last modified\s*:/s@:.*$@\=strftime(": %Y-%m-%d %H:%M:%S")@'
    normal "
    normal mk
    execute '/# Filename\s*:/s@:.*$@\=":      ".expand("%:t")@'
    execute "noh"
    normal 'k
    echohl WarningMsg | echo "Successful in updating the copy right." | echohl None
endfunction

function AddTitle_M()
    call append(0,"###########################################################")
    call append(1,"# Filename:      ".expand("%:t"))
    call append(2,"# Author:        sunxidong")
    call append(3,"# Email:         sunxidong9999@gmail.com")
    call append(4,"# Created:       ".strftime("%Y-%m-%d %H:%M:%S"))
    call append(5,"# Last modified: ".strftime("%Y-%m-%d %H:%M:%S"))
    call append(6,"# Description:   ")
    call append(7,"##########################################################")
    echohl WarningMsg | echo "Successful in adding the copyright." | echohl None
endfunction

function AddAuthor_M()
    let n=1
    while n < 7
        let line = getline(n)
        if line =~'^#\s*\S*Last\s*modified\s*:\s*\S*.*$'
            call UpdateTitle_M()
            return
        endif
        let n = n + 1
    endwhile
    call AddTitle_M()
endfunction
" 设置快捷键,按F10后向当前文件头部添加注释(#格式)
map <F10> ms:call AddAuthor_M()<cr>'s

"==============================================================
" 配置cscope,打开文件时自动加载cscope.out
if has("cscope") && filereadable("/usr/bin/cscope")
   set csprg=/usr/bin/cscope
   set csto=0
   set cst
   set nocsverb
   " add any database in current directory
   if filereadable("cscope.out")
      cs add cscope.out
   " else add database pointed to by environment
   elseif $CSCOPE_DB != ""
      cs add $CSCOPE_DB
   endif
   set csverb
endif
" 配置cscope快捷键
nmap <C-\>g :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-\>s :cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-\>c :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-\>t :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-\>e :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-\>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-\>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-\>d :cs find d <C-R>=expand("<cword>")<CR><CR>

# 2.3 安装vundle

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

# 2.4 通过vundle安装其他插件

~/.vimrc文件添加以下内容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
set nocompatible              " be iMproved, required
filetype off                  " required

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

" let Vundle manage Vundle, required
Plugin 'https://github.com/VundleVim/Vundle.vim'
Plugin 'https://github.com/fatih/vim-go'
Plugin 'https://github.com/majutsushi/tagbar'
Plugin 'https://github.com/scrooloose/nerdtree'
"Plugin 'https://github.com/Valloric/YouCompleteMe'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

注:安装完YouaCompleteMe插件后,打开vim提示:

1
YouCompleteMe unavailable: requires Vim compiled with Python (2.7.1+ or 3.5.1+) support

原因是YouCompleteMe需要vim支持python,在编译vim的时候指定--enable-pythoninterp=yes即可,如果是python3,则指定--enable-python3interp=yes

1
2
3
$ vim --version | grep -i python
+comments          +libcall           -python            +visual
+conceal           +linebreak         -python3           +visualextra

如果pythonpython3前的符号为+号则表示支持。

之后打开vim,通过:PluginInstall命令安装插件。

之后,通过:GoInstallBinaries命令安装vim-go

# 2.5 在.vimrc中配置NerdTree与tagbar插件快捷键

~/.vimrc中添加以下配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"============ 配置 Tagbar ===============
nmap <F2> :TagbarToggle<CR>   "设置快捷键
let g:tagbar_width = 25       "设置宽度,默认为40
autocmd VimEnter * nested :call tagbar#autoopen(1)    "打开vim时自动打开tagbar
let g:tagbar_sort = 0       "按函数在源码中出现的顺序排序(为1则按函数名称排序)
let g:tagbar_left = 1       "在左侧
"let g:tagbar_right = 1     "在右侧
let g:tagbar_type_go = {
    \ 'ctagstype' : 'go',
    \ 'kinds'     : [
        \ 'p:package',
        \ 'i:imports:1',
        \ 'c:constants',
        \ 'v:variables',
        \ 't:types',
        \ 'n:interfaces',
        \ 'w:fields',
        \ 'e:embedded',
        \ 'm:methods',
        \ 'r:constructor',
        \ 'f:functions'
    \ ],
    \ 'sro' : '.',
    \ 'kind2scope' : {
        \ 't' : 'ctype',
        \ 'n' : 'ntype'
    \ },
    \ 'scope2kind' : {
        \ 'ctype' : 't',
        \ 'ntype' : 'n'
    \ },
    \ 'ctagsbin'  : 'gotags',
    \ 'ctagsargs' : '-sort -silent'
\ }

"============== 配置 NerdTree ============
let NERDTreeWinPos='right'  "NERDTree打开后在窗口的位置:左='left', 右='right'
let NERDTreeShowLineNumbers=1   "NERDTree显示行号
let NERDTreeWinSize=25   "NERDTree列表的宽度
let NERDChristmasTree=1  "NERD添加色彩
let NERDTreeAutoCenter=1 "光标移动超过一定距离时,是否自动将焦点调整到屏中心
nnoremap <F4> :NERDTreeToggle<CR>  "打开与关闭nerdtree快捷键映射

# 2.6 在.vimrc中配置golang相关命令快捷键

在~/.vimrc中添加如下配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"================== 配置 Golang ===================
" 输入.号后弹出自动完成提示
au filetype go inoremap <buffer> . .<C-x><C-o>

" Go语法高亮
"This may overwrite syntax in "~/.vim/syntax/go.vim"
let g:go_highlight_fields = 1
let g:go_highlight_functions = 1
let g:go_highlight_function_calls = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_operators = 1

let g:go_fmt_autosave = 1
let g:go_fmt_command = "goimports"

"Status line types/signatures
let g:go_auto_type_info = 1

" 基于go文件运行:GoBuild 或:GoTestCompile
function! s:build_go_files()
  let l:file = expand('%')
  if l:file =~# '^\f\+_test\.go$'
    call go#test#Test(0, 1)
  elseif l:file =~# '^\f\+\.go$'
    call go#cmd#Build(0)
  endif
endfunction

"Map keys for most used commands.
"Ex: `\b` for building, `\r` for running and `\t` for running test.
autocmd FileType go nmap <leader>b :<C-u>call <SID>build_go_files()<CR>
autocmd FileType go nmap <leader>r  <Plug>(go-run)
autocmd FileType go nmap <leader>t  <Plug>(go-test)
autocmd FileType go nmap <leader>f  <Plug>(go-fmt)

# 2.7 支持.c/.go文件的函数名语法高亮

创建文件~/.vim/syntax/c.vim,内容如下:

1
2
3
4
"highlight Functions
syn match cFunctions "\<[a-zA-Z_][a-zA-Z_0-9]*\>[^()]*)("me=e-2
syn match cFunctions "\<[a-zA-Z_][a-zA-Z_0-9]*\>\s*("me=e-1
hi cFunctions gui=NONE cterm=bold  ctermfg=blue

# 2.8 golang代码可用的cscope

创建文件goscope,内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash

# generate cscope index files in current directory
# the generated cscope index files also include go standard packages

# check go binary exist
GOEXIST=`which go`
if [ "$GOEXIST" = "" ]; then
    echo "Golang not installed"
    exit 1
fi

# get GOROOT
GOROOT=`go env |grep "GOROOT"`
if [ "$GOROOT" = "" ] ; then
    echo "GOROOT is not set"
    exit 1
fi
GOROOT=`go env | grep "GOROOT" | cut -d "=" -f2`
GOROOT=${GOROOT#\"}
GOROOT=${GOROOT%\"}

go_pkg_src=$GOROOT/pkg

find $go_pkg_src -name "*.go" -print > cscope.files
find . -name "*.go" -print >> cscope.files

if cscope -b -k; then
    echo "Done"
else
    echo "Failed"
    exit 1
fi

之后将其放置到/usr/bin/目录:

1
2
chmod +x goscope
sudo mv goscope /usr/bin/
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-08-26 22:26 CST
网站已稳定运行 小时 分钟
使用 Hugo 构建
主题 StackJimmy 设计