Go002 Use Vim as IDE for Golang

Use Vim as Ide for Golang

Go002 Use Vim as IDE for Golang
Page content

使用vim作为golang开发环境

1. vim-plug

~# curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

2. vim-go

https://github.com/fatih/vim-go

  1. 编辑.vimrc
~# mkdir ~/.vim/plugged

~# vim ~/.vimrc
call plug#begin('~/.vim/plugged')
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' }
call plug#end()

~# source ~/.vimrc
  1. vim中执行命令::PlugInstall

3. .vimrc

" A sensible vimrc for Go development
"
" Please note that the following settings are some default that I used
" for years. However it might be not the case for you (and your
" environment). I highly encourage to change/adapt the vimrc to your own
" needs. Think of a vimrc as a garden that needs to be maintained and fostered
" throughout years. Keep it clean and useful - Fatih Arslan

call plug#begin('~/.vim/plugged')
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' }
Plug 'vim-airline/vim-airline'
Plug 'fatih/molokai'
Plug 'SirVer/ultisnips'
Plug 'neoclide/coc.nvim', {'do': 'yarn install --frozen-lockfile'}
Plug 'ternjs/tern_for_vim', { 'do' : 'npm install' } "js completion
call plug#end()

""""""""""""""""""""""
"      Settings      "
""""""""""""""""""""""
set relativenumber                      " Show line numbers
set number
set path+=**
set wildmenu
set nocompatible                " Enables us Vim specific features
filetype off                    " Reset filetype detection first ...
filetype plugin indent on       " ... and enable filetype detection
set ttyfast                     " Indicate fast terminal conn for faster redraw
set ttymouse=xterm2             " Indicate terminal type for mouse codes
set ttyscroll=3                 " Speedup scrolling
set laststatus=2                " Show status line always
set encoding=utf-8              " Set default encoding to UTF-8
set autoread                    " Automatically read changed files
set tabstop=4
set softtabstop=4
set shiftwidth=4
set expandtab
set autoindent                  " Enabile Autoindent
set backspace=indent,eol,start  " Makes backspace key more powerful.
set incsearch                   " Shows the match while typing
set hlsearch                    " Highlight found searches
set noerrorbells                " No beeps
set showcmd                     " Show me what I'm typing
set noswapfile                  " Don't use swapfile
set nobackup                    " Don't create annoying backup files
set splitright                  " Vertical windows should be split to right
set splitbelow                  " Horizontal windows should split to bottom
set autowrite                   " Automatically save before :next, :make etc.
set hidden                      " Buffer should still exist if window is closed
set fileformats=unix,dos,mac    " Prefer Unix over Windows over OS 9 formats
set noshowmatch                 " Do not show matching brackets by flickering
set noshowmode                  " We show the mode with airline or lightline
set ignorecase                  " Search case insensitive...
set smartcase                   " ... but not it begins with upper case
set completeopt=menu,menuone    " Show popup menu, even if there is one entry
set pumheight=10                " Completion window max size
set nocursorcolumn              " Do not highlight column (speeds up highlighting)
set nocursorline                " Do not highlight cursor (speeds up highlighting)
set lazyredraw                  " Wait to redraw
set updatetime=100

" Enable to copy to clipboard for operations like yank, delete, change and put
" http://stackoverflow.com/questions/20186975/vim-mac-how-to-copy-to-clipboard-without-pbcopy
if has('unnamedplus')
  set clipboard^=unnamed
  set clipboard^=unnamedplus
endif

" This enables us to undo files even if you exit Vim.
if has('persistent_undo')
  set undodir=~/.vim/undodir
  set undofile
endif

" Colorscheme
syntax enable
set t_Co=256
let g:rehash256 = 1
let g:molokai_original = 1
colorscheme molokai

" Enable 24-bit true colors if your terminal supports it.
if (has("termguicolors"))
  " https://github.com/vim/vim/issues/993#issuecomment-255651605
  let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
  let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"

  set termguicolors
endif

""""""""""""""""""""""
"      Mappings      "
""""""""""""""""""""""

" Set leader shortcut to a comma ','. By default it's the backslash
let mapleader = ","

" Jump to next error with Ctrl-n and previous error with Ctrl-m. Close the
" quickfix window with <leader>a
map <C-n> :cnext<CR>
map <C-m> :cprevious<CR>
nnoremap <leader>a :cclose<CR>

" Visual linewise up and down by default (and use gj gk to go quicker)
noremap <Up> gk
noremap <Down> gj
noremap j gj
noremap k gk

" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
nnoremap n nzzzv
nnoremap N Nzzzv

" Act like D and C
nnoremap Y y$

" Enter automatically into the files directory
autocmd BufEnter * silent! lcd %:p:h

" Toggle visually showing all whitespace characters.
noremap <F7> :set list!<CR>
inoremap <F7> <C-o>:set list!<CR>
cnoremap <F7> <C-c>:set list!<CR>

"""""""""""""""""""""
"      Plugins      "
"""""""""""""""""""""

" vim-go
let g:go_fmt_command = "goimports"
let g:go_autodetect_gopath = 1
let g:go_list_type = "quickfix"

let g:go_highlight_types = 1
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_generate_tags = 1
let g:go_highlight_operators = 1

let g:go_auto_type_info = 1
let g:go_auto_sameids = 1

" Open :GoDeclsDir with ctrl-g
nmap <C-g> :GoDeclsDir<cr>
imap <C-g> <esc>:<C-u>GoDeclsDir<cr>


augroup go
  autocmd!

  " Show by default 4 spaces for a tab
  autocmd BufNewFile,BufRead *.go setlocal expandtab tabstop=4 shiftwidth=4

  " :GoBuild and :GoTestCompile
  autocmd FileType go nmap <leader>b :<C-u>call <SID>build_go_files()<CR>

  " :GoTest
  autocmd FileType go nmap <leader>t  <Plug>(go-test)

  " :GoRun
  autocmd FileType go nmap <leader>r  <Plug>(go-run)

  " :GoDoc
  autocmd FileType go nmap <Leader>d <Plug>(go-doc)

  " :GoCoverageToggle
  autocmd FileType go nmap <Leader>c <Plug>(go-coverage-toggle)

  " :GoInfo
  autocmd FileType go nmap <Leader>i <Plug>(go-info)

  " :GoMetaLinter
  autocmd FileType go nmap <Leader>l <Plug>(go-metalinter)

  " :GoDef but opens in a vertical split
  autocmd FileType go nmap <Leader>v <Plug>(go-def-vertical)
  " :GoDef but opens in a horizontal split
  autocmd FileType go nmap <Leader>s <Plug>(go-def-split)

  " :GoAlternate  commands :A, :AV, :AS and :AT
  autocmd Filetype go command! -bang A call go#alternate#Switch(<bang>0, 'edit')
  autocmd Filetype go command! -bang AV call go#alternate#Switch(<bang>0, 'vsplit')
  autocmd Filetype go command! -bang AS call go#alternate#Switch(<bang>0, 'split')
  autocmd Filetype go command! -bang AT call go#alternate#Switch(<bang>0, 'tabe')
augroup END


" build_go_files is a custom function that builds or compiles the test file.
" It calls :GoBuild if its a Go file, or :GoTestCompile if it's a test file
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

" gen shell stuff
 autocmd BufNewFile *.sh exec ":call SetTitle()"
 func SetTitle()
     if expand("%:e") == 'sh'
         call setline(1,"#!/usr/bin/env bash")
         call setline(2,"#")
         call setline(3,"#*******************************************************************************")
         call setline(4,"# Data:              ".strftime("%Y-%m-%d"))
         call setline(5,"# URL:               suosuoli.cn")
         call setline(6,"# Copyright (C):     ".strftime("%Y")." All rights reserved")
         call setline(7,"#*******************************************************************************")
         call setline(8,"#")
         call setline(9,"")
         endif
 endfunc
 autocmd BufNewFile * normal G

" gen html stuff
autocmd BufNewFile *.html exec ":call GenHTML()"
  func GenHTML()
      if expand("%:e") == 'html'
     call setline(1,"<!DOCTYPE html>")
     call setline(2,"<html>")
     call setline(3,"    <head>")
     call setline(4,"        <meta charset=\"utf-8\"/>")
     call setline(5,"        <title> TITLE </title>")
     call setline(6,"        <link href=\"http://suosuoli.cn/css/reset.css\" rel=\"stylesheet\" type=\"text/css\">")
     call setline(7,"    </head>")
     call setline(8,"    <body>")
     call setline(9,"        <h3> This is body </h3>")
     call setline(10,"        <p> This is a phrase gen by vimrc... </p>")
     call setline(11,"       <div>")
     call setline(12,"           this is a div")
     call setline(13,"       </div>")
     call setline(14,"    </body>")
     call setline(15,"</html>")
     endif
  endfunc
  autocmd BufNewFile * normal G

" gen .md stuff
autocmd BufNewFile *.md exec ":call GenMD()"
  func GenMD()
      if expand("%:e") == 'md'
     call setline(1,"title")
     call setline(2,"===")
     call setline(3,"")
     call setline(4,"## level one title one")
     call setline(5,"- list one")
     call setline(6,"- list two")
     call setline(7,"## level one title two")
     call setline(8,"## bash")
     call setline(9,"```bash")
     call setline(10,"#!/usr/bin/env bash")
     call setline(11,"")
     call setline(12,"```")
     endif
  endfunc
  autocmd BufNewFile * normal G

  " gen .js stuff
autocmd BufNewFile *.js exec ":call GenJS()"
  func GenJS()
      if expand("%:e") == 'js'
     call setline(1,"use strict;")
     endif
  endfunc
  autocmd BufNewFile * normal G


  " gen .css stuff
autocmd BufNewFile *.css exec ":call GenCSS()"
  func GenCSS()
      if expand("%:e") == 'css'
     call setline(1,"p {")
     call setline(2, "color: #00ef00")
     call setline(3, "}")
     endif
  endfunc
  autocmd BufNewFile * normal G

主要使用了vim-go插件,具体教程可以看作者fatih的项目地址: