Home Backend Development Golang Detailed explanation of vim configuration of go language environment

Detailed explanation of vim configuration of go language environment

Dec 31, 2019 pm 05:17 PM
go

Detailed explanation of vim configuration of go language environment

1. Environment preparation:

System environment description:

[root@docker golang]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[root@docker golang]# uname -a
Linux docker 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[root@docker golang]#
Copy after login

Prepare a go file for observing the configuration plug-in Changes in the process:

//hellogolang.go
package main
import "fmt"
func main() {
        fmt.Println("Hello Golang!")
}
Copy after login

2. Plug-in configuration path:

1. Vundle.vim:

#mkdir ~/.vim/bundle
#git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
Copy after login

Configure vimrc: create~/ .vimrc file (if you do not have this file), add the configuration of Vundle.vim at the top of the file:

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 'gmarik/Vundle.vim'

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

At this time, Vim only has the Vundle.vim plug-in installed. Editing hellogolang.go is no different from editing an ordinary text file. Everything is still Vim’s default attributes

2. vim-go

Vim-go is currently the most widely used tool for building Golang. The vim plug-in for the development environment. Here I also use vim-go as the core and foundation to build the environment. vim-go is installed using the open source Vim plug-in manager. gmarik/Vundle.vim is currently the most recommended Vim plug-in manager, surpassing pathogen.

Here we use vundle as Vim’s plug-in management tool.

Edit ~/.vimrc, add a line between vundle#begin and vundle#end:

Plugin 'fatih/vim-go'
Copy after login

Execute in Vim: PluginInstall,

Vundle.vim A Vundle Installer Preview sub-window will open on the left, and a prompt will appear at the bottom of the window: "Processing 'fatih/vim-go'". After the installation is completed, the prompt message will change to "Done!".

At this time, we can see that there is an additional vim-go folder under .vim/bundle:

$ ls .vim/bundle/
vim-go/  Vundle.vim/
Copy after login

At this time, edit hellogolang.go again, the syntax Highlighting is now available, as is automatic format when saving (using $GOBIN/gofmt), but other advanced features, such as automatic import of missing packages and automatic completion, are still not available. We still need to continue to install some stuff.

3. Install go.tools Binaries

The vim-go installation instructions mention that all necessary binaries need to be installed first , such as gocode, godef, goimports, etc.

Through:GoInstallBinaries, these vim-go dependent binary tools will be automatically downloaded and installed under $GOBIN or $GOPATH/bin. (This tool requires git or hg and needs to be installed in your OS in advance.)

: The execution of GoInstallBinaries is interactive, you need to press Enter to confirm:

vim-go: gocode not found. Installing github.com/nsf/gocode to folder /home/tonybai/go/bin
vim-go: goimports not found. Installing code.google.com/p/go.tools/cmd/goimports to folder /home/tonybai/go/bin/
vim-go: godef not found. Installing code.google.com/p/rog-go/exp/cmd/godef to folder /home/tonybai/go/bin/
vim-go: oracle not found. Installing code.google.com/p/go.tools/cmd/oracle to folder /home/tonybai/go/bin/
vim-go: gorename not found. Installing code.google.com/p/go.tools/cmd/gorename to folder /home/tonybai/go/bin/
vim-go: golint not found. Installing github.com/golang/lint/golint to folder /home/tonybai/go/bin/
vim-go: errcheck not found. Installing github.com/kisielk/errcheck to folder /home/tonybai/go/bin/
Copy after login

But these codes Most of them are hosted on code.google.com, so due to well-known reasons, the automatic installation of vim-go is likely to fail. This requires you to download and install locally according to the source code address of each tool mentioned in the log above. . If you are unable to build a ladder, you can download the relevant package through http://gopm.io.

After installation, the new Binaries under $GOBIN are as follows:

-rwxr-xr-x  1 tonybai tonybai  5735552 11??  7 11:03 errcheck*
-rwxr-xr-x  1 tonybai tonybai  9951008 11??  7 10:33 gocode*
-rwxr-xr-x  1 tonybai tonybai  5742800 11??  7 11:07 godef*
-rwxr-xr-x  1 tonybai tonybai  4994120 11??  7 11:00 goimports*
-rwxr-xr-x  1 tonybai tonybai  5750152 11??  7 11:03 golint*
-rwxr-xr-x  1 tonybai tonybai  6381832 11??  7 11:01 gorename*
-rwxr-xr-x  1 tonybai tonybai  2954392 11??  7 10:38 gotags*
-rwxr-xr-x  1 tonybai tonybai  9222856 11??  7 11:01 oracle*
Copy after login

After installing these Binaries, let’s see which features are supported.

Edit hellogolang.go again:

- Start a new line and enter fmt., then ctrl x, ctrl o. Vim will pop up the completion prompt drop-down box, but it is not the kind of completion that follows in real time. Qi, this completion is provided by gocode.

– Enter a line of code: time.Sleep(time.Second), execute: GoImports, Vim will automatically import the time package.

– Move the cursor to the Sleep function, execute: GoDef or type gd in command mode, Vim will open the definition of the Sleep function in $GOROOT/src/time/sleep.go. Execution: b 1 returns to hellogolang.go.

– Execution: GoLint, run golint on the current Go source file.

– Execute: GoDoc to open the Go document corresponding to the symbol under the current cursor.

– Execute: GoVet, run go vet in the current directory on the current Go source file.

– Execute: GoRun, compile and run the current main package.

– Execute: GoBuild, compile the current package, which depends on your source files, GoBuild does not produce the result file.

– Execute: GoInstall to install the current package.

– Execute: GoTest, test the _test.go file under your current path.

– Execute: GoCoverage, create a test coverage result file, and open the browser to display the current package situation.

– Execute: GoErrCheck to check possible uncaught errors in the current package.

– Execute: GoFiles, display the list of source files corresponding to the current package.

– Execute: GoDeps, display the list of dependent packages of the current package.

– Execution: GoImplements, displays the interface list implemented by the current type.

– Execute: GoRename [to], replace the symbol under the current cursor with [to].

3. Other plug-ins

So far, we still have several features that have not been implemented, the key points are:

-Real-time following code supplement Qi
– Code Snippet support

1. Install YCM (Your Complete Me)

Add a line in ~/.vimrc:

Plugin 'Valloric /YouCompleteMe'

After saving and exiting, open ~/.vimrc and execute: PluginInstall

After installation, the following prompt bar prompts:

ycm_client_support.[so|pyd|dll] and ycm_core.[so|pyd|dll] not detected; you need to compile YCM before using it. Read the docs!

YCM is Modules written in C are used to optimize performance, so YCM's support library needs to be manually compiled. The steps are as follows:

sudo yum install build-essential cmake python-dev
cd ~/.vim/bundle/YouCompleteMe
./install.sh
Copy after login

Build (Compiling C is very slow, you need to wait patiently for a while) After OK, open hellogolang.go, and the real-time completion function will be available! Cool!

2. Install UltiSnips

Vim-go默认是用ultisnips引擎插件,但这个插件需要单独安装。同样,我们利用vundle来安装它,在~/.vimrc中添加一行:

Plugin 'SirVer/ultisnips'
Copy after login

保存,退出vim

打开vim,执行:PluginInstall

编辑hellogolang.go,按照go.snip中的说明,我们输入func后敲击tab键,我们发现期待的:

func name(params) type {
 }
Copy after login

并没有出现。反倒是YCM的下拉提示显示在那里让你选择。似乎是ultisnips和YCM的键组合冲突了。ultisnips官方说明也的确如 此。ultisnips默认是用Tab展开snippet的,而YCM中的Tab用来选择补齐项,我们可以通过设置来避免这些。

我们在.vimrc中添加如下setting:

" YCM settings
let g:ycm_key_list_select_completion = ['', '']
let g:ycm_key_list_previous_completion = ['']
let g:ycm_key_invoke_completion = &#39;<C-Space>&#39;

" UltiSnips setting
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
Copy after login

这样让YCM通过回车和向下的箭头来做list item正向选择,通过向上箭头做反向选择。通过ctrl+space来原地触发补齐提示。

而ultisnips则是用tab做snippet展开,ctrl+b正向切换占位符,ctrl+z反向切换占位符。

四、.vimrc

前面讲到了vim-go有许多命令,在:xx模式下执行多显不便,于是你可以定义一些Mappings,比如:

 " set mapleader
  let mapleader = ","

  " vim-go custom mappings
  au FileType go nmap <Leader>s <Plug>(go-implements)
  au FileType go nmap <Leader>i <Plug>(go-info)
  au FileType go nmap <Leader>gd <Plug>(go-doc)
  au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
  au FileType go nmap <leader>r <Plug>(go-run)
  au FileType go nmap <leader>b <Plug>(go-build)
  au FileType go nmap <leader>t <Plug>(go-test)
  au FileType go nmap <leader>c <Plug>(go-coverage)
  au FileType go nmap <Leader>ds <Plug>(go-def-split)
  au FileType go nmap <Leader>dv <Plug>(go-def-vertical)
  au FileType go nmap <Leader>dt <Plug>(go-def-tab)
  au FileType go nmap <Leader>e <Plug>(go-rename)  
Copy after login

这样我们在命令模式下,输入<,>+就是运行 当前main包,以此类推。

另外下面这个配置使得我们在save file时既可以格式化代码,又可以自动插入包导入语句(或删除不用的包导入语句)。

 " vim-go settings
let g:go_fmt_command = "goimports"
Copy after login

到这里,我们的Vim Golang开发环境就基本搭建好了。snippet+实时补齐让你Coding如飞!

五、.vimrc文件

下面是截至目前为止全量.vimrc文件的内容:

set nocompatible              " be iMproved, required
filetype off                  " required
colorscheme molokai

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

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
Plugin &#39;fatih/vim-go&#39;
Plugin 'Valloric/YouCompleteMe'

Plugin &#39;SirVer/ultisnips&#39;

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

" set mapleader
let mapleader = ","

" vim-go custom mappings
au FileType go nmap s (go-implements)
au FileType go nmap i (go-info)
au FileType go nmap gd (go-doc)
au FileType go nmap gv (go-doc-vertical)
au FileType go nmap r (go-run)
au FileType go nmap b (go-build)
au FileType go nmap t (go-test)
au FileType go nmap c (go-coverage)
au FileType go nmap ds (go-def-split)
au FileType go nmap dv (go-def-vertical)
au FileType go nmap dt (go-def-tab)
au FileType go nmap e (go-rename)

" vim-go settings
let g:go_fmt_command = "goimports"

" YCM settings
let g:ycm_key_list_select_completion = ['', '']
let g:ycm_key_list_previous_completion = ['', '']
let g:ycm_key_invoke_completion = ''

" UltiSnips settings
let g:UltiSnipsExpandTrigger=""
let g:UltiSnipsJumpForwardTrigger=""
let g:UltiSnipsJumpBackwardTrigger=""
Copy after login

更多golang知识请关注golang教程栏目。

The above is the detailed content of Detailed explanation of vim configuration of go language environment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send Go WebSocket messages? How to send Go WebSocket messages? Jun 03, 2024 pm 04:53 PM

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

In-depth understanding of Golang function life cycle and variable scope In-depth understanding of Golang function life cycle and variable scope Apr 19, 2024 am 11:42 AM

In Go, the function life cycle includes definition, loading, linking, initialization, calling and returning; variable scope is divided into function level and block level. Variables within a function are visible internally, while variables within a block are only visible within the block.

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

The difference between Golang and Go language The difference between Golang and Go language May 31, 2024 pm 08:10 PM

Go and the Go language are different entities with different characteristics. Go (also known as Golang) is known for its concurrency, fast compilation speed, memory management, and cross-platform advantages. Disadvantages of the Go language include a less rich ecosystem than other languages, a stricter syntax, and a lack of dynamic typing.

How to view Golang function documentation in the IDE? How to view Golang function documentation in the IDE? Apr 18, 2024 pm 03:06 PM

View Go function documentation using the IDE: Hover the cursor over the function name. Press the hotkey (GoLand: Ctrl+Q; VSCode: After installing GoExtensionPack, F1 and select "Go:ShowDocumentation").

How to use Golang's error wrapper? How to use Golang's error wrapper? Jun 03, 2024 pm 04:08 PM

In Golang, error wrappers allow you to create new errors by appending contextual information to the original error. This can be used to unify the types of errors thrown by different libraries or components, simplifying debugging and error handling. The steps are as follows: Use the errors.Wrap function to wrap the original errors into new errors. The new error contains contextual information from the original error. Use fmt.Printf to output wrapped errors, providing more context and actionability. When handling different types of errors, use the errors.Wrap function to unify the error types.

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

See all articles