emacs 开发环境配置(1)——go开发环境

一、参考

emacs系列文章目录——更新ing

Becoming an emacs gopher

Emacs Golang开发环境配置指南

Stop debugging Go with Println and use Delve instead

Delve调试器

极简Emacs开发环境配置

⚠️ 最新文档 emacs 开发环境配置(1)——go 开发环境(2023更新版)

二、安装golang包

2.1 goimports

Command goimports updates your Go import lines, adding missing ones and removing unreferenced ones.

对于代码中引入的第三方模块,自动更新

goimports命令能自动格式化代码,自动添加、移除imports,而且与Emacs集成良好。可以替代官方gofmt命令。

GO111MODULE=on go get -u golang.org/x/tools/cmd/goimports

2.2 godef

Godef, given an expression or a location in a source file, prints the location of the definition of the symbol referred to.

对于代码中的函数引用,可以查看原始定义位置
godef命令能在Go源码变量、函数定义间跳转,是查看变量、函数、文件定义的好助手

GO111MODULE=on go get -u github.com/rogpeppe/godef

2.3 gocode

An autocompletion daemon for the Go programming language

自动补全代码
gocode命令能为代码自动补全提供后台支持,是EmacsGo代码补全必不可少的backend

GO111MODULE=on go get -u github.com/nsf/gocode

三、安装emacs包

包名 描述 其他
auto-Complete An Intelligent auto-completion extension for Emacs https://github.com/auto-complete/auto-complete
go-mode Emacs mode for the Go programming language https://github.com/dominikh/go-mode.el
go-complete Native Go completion for Emacs https://github.com/vibhavp/go-complete
go-autocomplete auto-complete-mode backend for go-mode https://melpa.org/#/go-autocomplete
autopair Automagically pair braces and quotes in emacs like TextMate https://github.com/joaotavora/autopair
;; Init the auto complete modules
(ac-config-default)
(global-auto-complete-mode t)
(require 'go-autocomplete)

;; Enable auto-complete
(auto-complete-mode 1)

;; Define keymaps
(define-key ac-mode-map (kbd "M-TAB") 'auto-complete)
(global-set-key (kbd"C-c C-c") 'godef-jump)

;; Set some quick config vals
(setq ac-auto-start 1)
(setq ac-auto-show-menu 0.8)

;; Just to make sure go tools are enabled
(add-to-list 'exec-path "~/go/bin")

;; Automatically format code on save
(setq gofmt-command "goimports")
(add-hook 'before-save-hook 'gofmt-before-save)
(add-hook 'go-mode-hook 'auto-complete-for-go)

四、go-mode的命令

4.1 imports区域

(1) go-goto-imports, 跳转到imports区域

image.png

(2) go-import-add, 添加新的import aaa

image.png

(3) go-remove-unused-imports, 删除不再使用的包

image.png

4.2 godef

(1) go-jump,跳转到表达式的定义

image.png

(2) godef-jump-other-window,新建窗口,并跳转到表达式定义

image.png

4.3 function

(1) go-goto-arguments, 跳转到函数的参数

image.png

(2) go-goto-docstring 跳转到函数的说明文档,如果没有说明文档,会创建

image.png

(3) go-goto-function, 跳转到函数func关键字,一般用于在函数文档中,跳转到函数代码

image.png

(4) go-goto-function-name, 跳转到函数名称处

image.png

(5) go-goto-return-values, 跳转到函数定义中的返回值处

image.png

(6) go-goto-method-receiver, 跳转到函数的调用者处

image.png

4.4 其他

(1) pop-tag-mark, 回退到前一个光标位置

image.png

(2) beginning-of-defun, 跳转到函数的初始位置(适合函数之间的跳转)

image.png

(3) end-of-defun, 跳转到函数的结束位置

image.png

五、快捷键绑定

5.1 函数跳转和回退

;; Godef jump key binding                                                                   
(global-set-key (kbd "M-,") 'godef-jump)                                                  
(global-set-key (kbd "M-.") 'pop-tag-mark)

5.2 代码块的跳转

C-M-a 跳转到上一个函数

C-M-e 跳转到下一个函数

5.3 代码注释

M-;可以实现多行注释与解注释

image.png

六、debug

6.1 安装

GO111MODULE=on go get -u github.com/go-delve/delve/cmd/dlv

➜  ~ dlv version
Delve Debugger
Version: 1.6.0
Build: $Id: 8cc9751909843dd55a46e8ea2a561544f70db34d $

6.2 基本命令

➜  ~ dlv -h
Delve is a source level debugger for Go programs.

Delve enables you to interact with your program by controlling the execution of the process,
evaluating variables, and providing information of thread / goroutine state, CPU register state and more.

The goal of this tool is to provide a simple yet powerful interface for debugging Go programs.

Pass flags to the program you are debugging using `--`, for example:

`dlv exec ./hello -- server --config conf/config.toml`

Usage:
  dlv [command]

Available Commands:
  attach      Attach to running process and begin debugging.
  connect     Connect to a headless debug server.
  core        Examine a core dump.
  dap         [EXPERIMENTAL] Starts a TCP server communicating via Debug Adaptor Protocol (DAP).
  debug       Compile and begin debugging main package in current directory, or the package specified.
  exec        Execute a precompiled binary, and begin a debug session.
  help        Help about any command
  run         Deprecated command. Use 'debug' instead.
  test        Compile test binary and begin debugging program.
  trace       Compile and begin tracing program.
  version     Prints version.

Flags:
      --accept-multiclient               Allows a headless server to accept multiple client connections.
      --allow-non-terminal-interactive   Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr
      --api-version int                  Selects API version when headless. New clients should use v2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 1)
      --backend string                   Backend selection (see 'dlv help backend'). (default "default")
      --build-flags string               Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v"
      --check-go-version                 Checks that the version of Go in use is compatible with Delve. (default true)
      --disable-aslr                     Disables address space randomization
      --headless                         Run debug server only, in headless mode.
  -h, --help                             help for dlv
      --init string                      Init file, executed by the terminal client.
  -l, --listen string                    Debugging server listen address. (default "127.0.0.1:0")
      --log                              Enable debugging server logging.
      --log-dest string                  Writes logs to the specified file or file descriptor (see 'dlv help log').
      --log-output string                Comma separated list of components that should produce debug output (see 'dlv help log')
      --only-same-user                   Only connections from the same user that started this instance of Delve are allowed to connect. (default true)
  -r, --redirect stringArray             Specifies redirect rules for target process (see 'dlv help redirect')
      --wd string                        Working directory for running the program.

Additional help topics:
  dlv backend  Help about the --backend flag.
  dlv log      Help about logging flags.
  dlv redirect Help about file redirection.

Use "dlv [command] --help" for more information about a command.

6.3 dlv子命令

命令 说明
dlv attach Attach to running process and begin debugging 调试正在运行的进程
dlv connect Connect to a headless debug server 连接到远端的debug服务器
dlv core Examine a core dump
dlv dap [EXPERIMENTAL] Starts a TCP server communicating via Debug Adaptor Protocol (DAP)
dlv debug Compile and begin debugging main package in current directory, or the package specified
dlv exec Execute a precompiled binary, and begin a debug session
dlv help Deprecated command. Use 'debug' instead
dlv test Compile test binary and begin debugging program
dlv trace Compile and begin tracing program
dlv version Prints version

6.4 dlv debug子命令

(dlv) help
The following commands are available:

Running the program:
    call ------------------------ Resumes process, injecting a function call (EXPERIMENTAL!!!)
    continue (alias: c) --------- Run until breakpoint or program termination.
    next (alias: n) ------------- Step over to next source line.
    rebuild --------------------- Rebuild the target executable and restarts it. It does not work if the executable was not built by delve.
    restart (alias: r) ---------- Restart process.
    step (alias: s) ------------- Single step through program.
    step-instruction (alias: si)  Single step a single cpu instruction.
    stepout (alias: so) --------- Step out of the current function.

Manipulating breakpoints:
    break (alias: b) ------- Sets a breakpoint.
    breakpoints (alias: bp)  Print out info for active breakpoints.
    clear ------------------ Deletes breakpoint.
    clearall --------------- Deletes multiple breakpoints.
    condition (alias: cond)  Set breakpoint condition.
    on --------------------- Executes a command when a breakpoint is hit.
    trace (alias: t) ------- Set tracepoint.

Viewing program variables and memory:
    args ----------------- Print function arguments.
    display -------------- Print value of an expression every time the program stops.
    examinemem (alias: x)  Examine memory:
    locals --------------- Print local variables.
    print (alias: p) ----- Evaluate an expression.
    regs ----------------- Print contents of CPU registers.
    set ------------------ Changes the value of a variable.
    vars ----------------- Print package variables.
    whatis --------------- Prints type of an expression.

Listing and switching between threads and goroutines:
    goroutine (alias: gr) -- Shows or changes current goroutine
    goroutines (alias: grs)  List program goroutines.
    thread (alias: tr) ----- Switch to the specified thread.
    threads ---------------- Print out info for every traced thread.

Viewing the call stack and selecting frames:
    deferred --------- Executes command in the context of a deferred call.
    down ------------- Move the current frame down.
    frame ------------ Set the current frame, or execute command on a different frame.
    stack (alias: bt)  Print stack trace.
    up --------------- Move the current frame up.

Other commands:
    config --------------------- Changes configuration parameters.
    disassemble (alias: disass)  Disassembler.
    edit (alias: ed) ----------- Open where you are in $DELVE_EDITOR or $EDITOR
    exit (alias: quit | q) ----- Exit the debugger.
    funcs ---------------------- Print list of functions.
    help (alias: h) ------------ Prints the help message.
    libraries ------------------ List loaded dynamic libraries
    list (alias: ls | l) ------- Show source code.
    source --------------------- Executes a file containing a list of delve commands
    sources -------------------- Print list of source files.
    types ---------------------- Print list of types

Type help followed by a command for full documentation.

断点相关命令:

命令 描述
break (alias: b) 创建新的断点
breakpoints (alias: bp) 输出当前断点信息
clear 取消断点
clearall 取消多个断点
condition (alias: cond) 设置断点条件
on 在断点中执行命令
trace (alias: t) 设置追踪点

程序执行相关命令:

命令 说明
call 恢复进程,注入函数调用
continue (alias: c) 继续执行,一直到程序结束或者下一个断点
next (alias: n) 继续执行下一行代码
rebuild 重新编译源代码,并且重新运行,如果不是用dlv构建,无法重新运行
restart (alias: r) 重新运行
step (alias: s)) 单步执行
step-instruction (alias: si) 单步,一条CPU指令
stepout (alias: so) 退出当前函数

七、dlv使用

7.1 源码查看

示例 说明
list TestPrint 查看函数TestPrint的源代码
list print_test.go:8 查看文件print_test.go第8行的代码
funcs TestPrint 查看函数TestPrint的具体位置

7.2 dlv test

(1) 进入dlv test

示例 说明
dlv test -- -test.run ^TestPrint1$ 只测试具体函数,需要注意:此时需要先进入对应的目录中, emacs 开发环境配置(1)——go开发环境_第1张图片
dlv test ./test emacs 开发环境配置(1)——go开发环境_第2张图片

(2) 断点的设置与撤销

示例 说明
break print1_test.go:8 断点通过设置具体的文件+行号 emacs 开发环境配置(1)——go开发环境_第3张图片
breakpoints emacs 开发环境配置(1)——go开发环境_第4张图片
clear 1 emacs 开发环境配置(1)——go开发环境_第5张图片
clearall emacs 开发环境配置(1)——go开发环境_第6张图片

7.3 实际debug

(1) 进入测试

# 进入测试目录
cd projectDir/test

# 测试具体的函数
dlv test -- -test.run TestESParse

(2) 设置断点

Type 'help' for list of commands.
(dlv) b esql.go:318
Breakpoint 1 set at 0x182c398 for  ./esql.go:318
(dlv) b esqlCheck.go:138
Breakpoint 2 set at 0x1839cd2 for ./esqlCheck.go:138

(3) 执行程序

continue

(4) 查看当前的执行状态

命令 说明
args 查看当前的所有参数
args arg1 查看参数arg1
print arg1 打印参数arg1

你可能感兴趣的:(emacsgo)