pax_global_header00006660000000000000000000000064130601077270014515gustar00rootroot0000000000000052 comment=35f6826e435c3004dabf134d0f2ae2f31ea7b6a2 go-mode.el-1.5.0/000077500000000000000000000000001306010772700134465ustar00rootroot00000000000000go-mode.el-1.5.0/.gitignore000066400000000000000000000000061306010772700154320ustar00rootroot00000000000000*.elc go-mode.el-1.5.0/.mailmap000066400000000000000000000000741306010772700150700ustar00rootroot00000000000000Dominik Honnef go-mode.el-1.5.0/AUTHORS000066400000000000000000000034351306010772700145230ustar00rootroot00000000000000Aaron France Alan Donovan Alan Donovan Andrew Gerrand Austin Clements Ben Fried Bobby Powers Charles Lee Daniel Morsing Dominik Honnef Dominik Honnef Eric Eisner Erin Keenan Evan Martin Felix Lange Florian Weimer Istvan Marko Iwasaki Yudai James Aguilar Jan Newmarch Jean-Marc Eurin Jeff Hodges Juergen Hoetzel Kevin Ballard Konstantin Shaposhnikov Lowe Thiderman Mark Petrovic Mats Lidell Matt Armstrong Peter Kleiweg Philipp Stephani Quan Yong Zhai Robert Zaremba Rui Ueyama Russ Cox Ryan Barrett Rüdiger Sonderfeld Sameer Ajmani Scott Lawrence Steven Elliot Harris Syohei YOSHIDA Taiki Sugawara Viacheslav Chimishuk Will Yasuyuki Oka Yutian Li Zac Bergquist kostya-sh nverno nwidger go-mode.el-1.5.0/AUTHORS.old000066400000000000000000000022101306010772700152660ustar00rootroot00000000000000# This file contains all the authors that contributed to go-mode while # it was still part of the Go distribution. Most of these authors are # not tracked in this repository's history. For a complete list of # authors, see the AUTHORS file instead. Aaron France Alan Donovan Austin Clements Ben Fried Bobby Powers Charles Lee Dominik Honnef Eric Eisner Evan Martin Florian Weimer Istvan Marko James Aguilar Jan Newmarch Jean-Marc Eurin Kevin Ballard Mats Lidell Peter Kleiweg Quan Yong Zhai Robert Zaremba Rui Ueyama Russ Cox Ryan Barrett Sameer Ajmani Scott Lawrence Steven Elliot Harris Yasuyuki Oka go-mode.el-1.5.0/LICENSE000066400000000000000000000027251306010772700144610ustar00rootroot00000000000000Copyright (c) 2014 The go-mode Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. go-mode.el-1.5.0/NEWS000066400000000000000000000114071306010772700141500ustar00rootroot00000000000000go-mode-1.4.0 (2016/05/12) * Fix minor bugs in fontification. * Use unwind-protect in gofmt, ensuring that temporary files will be removed in all cases. * Improve go-remove-unused-imports: don't fail to remove unused imports because of compilation errors in other files. * Add new commands for jumping to various parts of function declarations: - go-goto-arguments (C-c C-f a) - go-goto-docstring (C-c C-f d) - go-goto-function (C-c C-f f) - go-goto-function-name (C-c C-f n) - go-goto-return-values (C-c C-f r) - go-goto-method-receiver (C-c C-f m) Thanks to Lowe Thiderman for contributing these commands. * Add new customizable variable go-packages-function, which allows choosing between different ways of finding installed packages. Currently, go-packages-native (the default) and go-packages-go-list are provided. * Automatically detect if goimports is used instead of gofmt and pass the -srcdir flag, enabling support for vendoring. * Add new customizable variable gofmt-args, a list of strings that will be passed to gofmt as additional arguments. Primarily this allows using the -s flag with gofmt. * Add detection of GOPATH, Godep, wgo and gb. A new non-interactive function go-guess-gopath will try a list of functions (the customizable variable go-guess-gopath-functions) to detect a suitable value for GOPATH. A new interactive command go-set-project uses the result of go-guess-gopath to actually set GOPATH. This interactive function could be used from inside a projectile-switch-project-hook, directory variables or some other way of invoking per-project code. * Add new command go-reset-gopath, which resets GOPATH to the value it had when Emacs started. * Add customizable variable godoc-command, which allows choosing between using godoc and go doc, and generally specifying alternative paths to those tools. It defaults to go doc, which differs from prior versions which always used godoc. * Add customizable variable godoc-use-completing-read, which allows turning on or off the completion of import paths in the godoc command. This is only really useful when using godoc instead of go doc, and thus defaults to off. * Fix parsing of test output in compilation-mode for new versions of Emacs. It's probably broken in older versions now. * Add support for electric-indent-mode and only reindent for closing parens, not colons, commas or equal signs. * Avoid warnings by the byte compiler -- Use cl-lib instead of cl, and utilize a macro to conditionally compile fallback code. * Use null-device instead of /dev/null to work better on Windows. * Add new customizable variable godoc-at-point-function, which allows choosing between strategies for finding an identifier's documentation. * Add new function godoc-and-godef, which is the default function used for godoc-at-point and matches the previous behaviour. * Add new customizable variable godoc-and-godef-command, which allows specifying the path to the godoc binary. * Add the function godoc-gogetdoc, which provides godoc-at-point functionality by using the third party tool gogetdoc. * The godoc command no longer defaults to the symbol under point. It rarely defaulted to a useful value. If you're interested in documentation for the identifier at point, use godoc-at-point instead. * Set compilation-error-screen-columns to nil in go-mode buffers. Go uses tabs for indentation, and go/parser-based tools emit column numbers in terms of characters, where a tab is one character wide. Emacs defaults to interpreting columns as screen columns, where a tab is tab-width columns wide. This breaks jumping to the right columns from compilation-mode * Use HTTPS when talking to the Go Playground. Not only is it safer, it is required nowadays. go-mode-1.3.1 (2015-07-03) * The 1.3.0 release forgot to update the version in the package metadata. This version fixes that. go-mode-1.3.0 (2015-05-03) * Add a new minor mode godoc-mode, used instead of view-mode when displaying godoc output. go-mode-1.2.1 (2015-04-10) * After using godef-jump, don't temporarily mark old buffer as active. go-mode-1.2.0 (2015/03/22): * Add a menu for go-mode. * Add a new variable go-play-browsw-function that controls the behaviour of go-play-region and go-play-buffer. * Fix minor bug in fontification. * Fix minor bug in go-remove-unused-imports that sometimes prevented it from removing unused imports. go-mode-1.1.0 (2015-02-25): * Add a new variable godef-command, allowing customization of the godef command. * Automatically hide the gofmt error window after fixing errors. go-mode-1.0.0 (2014-11-28): * First release since go-mode was removed from the Go distribution. go-mode.el-1.5.0/README.md000066400000000000000000000150001306010772700147210ustar00rootroot00000000000000This is go-mode, the Emacs mode for editing Go code. It is a complete rewrite of the go-mode that shipped with Go 1.0.3 and before, and was part of Go 1.1 until Go 1.3. Beginning with Go 1.4, editor integration will not be part of the Go distribution anymore, making this repository the canonical place for go-mode. # Features In addition to normal features, such as fontification and indentation, and close integration with familiar Emacs functionality (for example syntax-based navigation like `beginning-of-defun`), go-mode comes with the following extra features to provide an improved experience: - Integration with `gofmt` by providing a command of the same name, and `gofmt-before-save`, which can be used in a hook to format Go buffers before saving them. - Setting the `gofmt-command` variable also allows using `goimports`. - Integration with `godoc` via the functions `godoc` and `godoc-at-point`. - Integration with the Playground - `go-play-buffer` and `go-play-region` to send code to the Playground - `go-download-play` to download a Playground entry into a new buffer - Managing imports - A function for jumping to the file's imports (`go-goto-imports` - `C-c C-f i`) - A function for adding imports, including tab completion (`go-import-add`, bound to `C-c C-a`) - A function for removing or commenting unused imports (`go-remove-unused-imports`) - Integration with godef - `godef-describe` (`C-c C-d`) to describe expressions - `godef-jump` (`C-c C-j`) and `godef-jump-other-window` (`C-x 4 C-c C-j`) to jump to declarations - This requires you to install godef via `go get github.com/rogpeppe/godef`. - Basic support for imenu (functions and variables) - Built-in support for displaying code coverage as calculated by `go test` (`go-coverage`) - Several functions for jumping to and manipulating the individual parts of function signatures. These functions support anonymous functions, but are smart enough to skip them when required (e.g. when jumping to a method receiver or docstring.) - Jump to the argument list (`go-goto-arguments` - `C-c C-f a`) - Jump to the docstring, create it if it does not exist yet (`go-goto-docstring` - `C-c C-f d`). - Jump to the function keyword (`go-goto-function` - `C-c C-f f`) - Jump to the function name (`go-goto-function-name` - `C-c C-f n`) - Jump to the return values (`go-goto-return-values` - `C-c C-f r`) - Jump to the method receiver, adding a pair of parentheses if no method receiver exists (`go-goto-method-receiver` - `C-c C-f m`). All of these functions accept a prefix argument (`C-u`), causing them to skip anonymous functions. - GOPATH detection – the function `go-guess-gopath` will guess a suitable value for GOPATH, based on gb or wgo projects, Godeps and src folders for plain GOPATH workspaces. The command `go-set-project` uses the return value of `go-guess-gopath` to set the GOPATH environment variable. You can either call `go-set-project` manually, or integrate it with Projectile's project switching hooks, or any other means of switching projects you may employ. # Installation ## MELPA The recommended way of installing go-mode is via [ELPA](http://www.emacswiki.org/emacs/ELPA), the Emacs package manager, and the [MELPA Stable repository](http://emacsredux.com/blog/2014/05/16/melpa-stable/), which provides an up-to-date version of go-mode. If you're not familiar with ELPA yet, consider reading [this guide](http://ergoemacs.org/emacs/emacs_package_system.html). ## Manual To install go-mode manually, place `go-mode.el` and `go-mode-autoloads.el` in a directory of your choice, add it to your load path and require `'go-mode-autoloads`: (add-to-list 'load-path "/place/where/you/put/it/") (require 'go-mode-autoloads) Either evaluate both statements with `C-x C-e`, or restart Emacs. As a side note, normally the autoloads file shouldn't be part of the package, as it's supposed to be automatically generated by ELPA, or manually by the user with `update-file-autoloads`. go-mode includes said file because it used to when it was part of the Go distribution and this makes upgrading easier for some people. # Other extensions There are several third party extensions that can enhance the Go experience in Emacs. ## Syntax/error checking There are two ways of using flymake with Go: 1. [goflymake](https://github.com/dougm/goflymake), which internally uses `go build` to capture all errors that a regular compilation would also produce 2. [flymake-go](http://marmalade-repo.org/packages/flymake-go) for a more lightweight solution that only uses `gofmt` and as such is only able to catch syntax errors. Unlike goflymake, however, it does not require an additional executable. Additionally, there is [flycheck](https://github.com/flycheck/flycheck), a modern replacement for flymake, which comes with built-in support for Go. In addition to using `go build` or `gofmt`, it also has support for `go vet`, `golint` and `errcheck`. ## Auto completion For auto completion, take a look at [gocode](https://github.com/nsf/gocode). ## eldoc https://github.com/syohex/emacs-go-eldoc provides eldoc functionality for go-mode. ## Snippets I maintain a set of YASnippet snippets for go-mode at https://github.com/dominikh/yasnippet-go ## Integration with errcheck https://github.com/dominikh/go-errcheck.el provides integration with [errcheck](https://github.com/kisielk/errcheck). # Stability go-mode.el has regular, tagged releases and is part of the MELPA Stable repository. These tagged releases are intended to provide a stable experience. APIs added in tagged releases will usually not be removed or changed in future releases. Changes made on the master branch, which is tracked by the normal MELPA repository, however, are under active development. New APIs are experimental and may be changed or removed before the next release. Furthermore, there is a higher chance for bugs. If you want a stable experience, use MELPA Stable. If you want cutting edge features, or "beta-test" future releases, use MELPA or the master branch. # Donations I am accepting donations for go-mode, but it has to be said that even though I am its primary developer, there are several third party contributions with varying complexity. Donations would be towards me, Dominik Honnef, and not go-mode as a whole. Click here to lend your support to: go-mode.el and make a donation at www.pledgie.com ! go-mode.el-1.5.0/generate_authors.sh000077500000000000000000000001651306010772700173460ustar00rootroot00000000000000#!/bin/sh export LC_ALL=C ( grep -v "^#" AUTHORS.old | grep -v '^$' git log --format='%aN <%aE>' ) | sort -u go-mode.el-1.5.0/go-guru.el000066400000000000000000000452731306010772700153700ustar00rootroot00000000000000;;; go-guru.el --- Integration of the Go 'guru' analysis tool into Emacs. ;; Copyright 2016 The Go Authors. All rights reserved. ;; Use of this source code is governed by a BSD-style ;; license that can be found in the LICENSE file. ;; Version: 0.1 ;; Package-Requires: ((go-mode "1.3.1") (cl-lib "0.5")) ;; Keywords: tools ;;; Commentary: ;; To enable the Go guru in Emacs, use this command to download, ;; build, and install the tool in $GOROOT/bin: ;; ;; $ go get golang.org/x/tools/cmd/guru ;; ;; Verify that the tool is on your $PATH: ;; ;; $ guru -help ;; Go source code guru. ;; Usage: guru [flags] ;; ... ;; ;; Then copy this file to a directory on your `load-path', ;; and add this to your ~/.emacs: ;; ;; (require 'go-guru) ;; ;; Inside a buffer of Go source code, select an expression of ;; interest, and type `C-c C-o d' (for "describe") or run one of the ;; other go-guru-xxx commands. If you use `menu-bar-mode', these ;; commands are available from the Guru menu. ;; ;; To enable identifier highlighting mode in a Go source buffer, use: ;; ;; (go-guru-hl-identifier-mode) ;; ;; To enable it automatically in all Go source buffers, ;; add this to your ~/.emacs: ;; ;; (add-hook 'go-mode-hook #'go-guru-hl-identifier-mode) ;; ;; See http://golang.org/s/using-guru for more information about guru. ;;; Code: (require 'compile) (require 'easymenu) (require 'go-mode) (require 'json) (require 'simple) (require 'cl-lib) (defgroup go-guru nil "Options specific to the Go guru." :group 'go) (defcustom go-guru-command "guru" "The Go guru command." :type 'string :group 'go-guru) (defcustom go-guru-scope "" "The scope of the analysis. See `go-guru-set-scope'." :type 'string :group 'go-guru) (defvar go-guru--scope-history nil "History of values supplied to `go-guru-set-scope'.") (defcustom go-guru-build-tags '() "Build tags passed to guru." :type '(repeat string) :group 'go-guru) (defface go-guru-hl-identifier-face '((t (:inherit highlight))) "Face used for highlighting identifiers in `go-guru-hl-identifier'." :group 'go-guru) (defcustom go-guru-debug nil "Print debug messages when running guru." :type 'boolean :group 'go-guru) (defcustom go-guru-hl-identifier-idle-time 0.5 "How long to wait after user input before highlighting the current identifier." :type 'float :group 'go-guru) (defvar go-guru--current-hl-identifier-idle-time 0 "The current delay for hl-identifier-mode.") (defvar go-guru--hl-identifier-timer nil "The global timer used for highlighting identifiers.") (defvar go-guru--last-enclosing nil "The remaining enclosing regions of the previous go-expand-region invocation.") ;; Extend go-mode-map. (let ((m (define-prefix-command 'go-guru-map))) (define-key m "d" #'go-guru-describe) (define-key m "f" #'go-guru-freevars) (define-key m "i" #'go-guru-implements) (define-key m "c" #'go-guru-peers) ; c for channel (define-key m "r" #'go-guru-referrers) (define-key m "j" #'go-guru-definition) ; j for jump (define-key m "p" #'go-guru-pointsto) (define-key m "s" #'go-guru-callstack) ; s for stack (define-key m "e" #'go-guru-whicherrs) ; e for error (define-key m "<" #'go-guru-callers) (define-key m ">" #'go-guru-callees) (define-key m "x" #'go-guru-expand-region)) ;; x for expand (define-key go-mode-map (kbd "C-c C-o") #'go-guru-map) (easy-menu-define go-guru-mode-menu go-mode-map "Menu for Go Guru." '("Guru" ["Jump to Definition" go-guru-definition t] ["Show Referrers" go-guru-referrers t] ["Show Free Names" go-guru-freevars t] ["Describe Expression" go-guru-describe t] ["Show Implements" go-guru-implements t] "---" ["Show Callers" go-guru-callers t] ["Show Callees" go-guru-callees t] ["Show Callstack" go-guru-callstack t] "---" ["Show Points-To" go-guru-pointsto t] ["Show Which Errors" go-guru-whicherrs t] ["Show Channel Peers" go-guru-peers t] "---" ["Set pointer analysis scope..." go-guru-set-scope t])) ;;;###autoload (defun go-guru-set-scope () "Set the scope for the Go guru, prompting the user to edit the previous scope. The scope restricts analysis to the specified packages. Its value is a comma-separated list of patterns of these forms: golang.org/x/tools/cmd/guru # a single package golang.org/x/tools/... # all packages beneath dir ... # the entire workspace. A pattern preceded by '-' is negative, so the scope encoding/...,-encoding/xml matches all encoding packages except encoding/xml." (interactive) (let ((scope (read-from-minibuffer "Go guru scope: " go-guru-scope nil nil 'go-guru--scope-history))) (if (string-equal "" scope) (error "You must specify a non-empty scope for the Go guru")) (setq go-guru-scope scope))) (defun go-guru--set-scope-if-empty () (if (string-equal "" go-guru-scope) (go-guru-set-scope))) (defun go-guru--json (mode) "Execute the Go guru in the specified MODE, passing it the selected region of the current buffer, requesting JSON output. Parse and return the resulting JSON object." ;; A "what" query works even in a buffer without a file name. (let* ((filename (file-truename (or buffer-file-name "synthetic.go"))) (cmd (go-guru--command mode filename '("-json"))) (buf (current-buffer)) ;; Use temporary buffers to avoid conflict with go-guru--start. (json-buffer (generate-new-buffer "*go-guru-json-output*")) (input-buffer (generate-new-buffer "*go-guru-json-input*"))) (unwind-protect ;; Run guru, feeding it the input buffer (modified files). (with-current-buffer input-buffer (go-guru--insert-modified-files) (unless (buffer-file-name buf) (go-guru--insert-modified-file filename buf)) (let ((exitcode (apply #'call-process-region (append (list (point-min) (point-max) (car cmd) ; guru nil ; delete json-buffer ; output nil) ; display (cdr cmd))))) ; args (with-current-buffer json-buffer (unless (zerop exitcode) ;; Failed: use buffer contents (sans final \n) as an error. (error "%s" (buffer-substring (point-min) (1- (point-max))))) ;; Success: parse JSON. (goto-char (point-min)) (json-read)))) ;; Clean up temporary buffers. (kill-buffer json-buffer) (kill-buffer input-buffer)))) (define-compilation-mode go-guru-output-mode "Go guru" "Go guru output mode is a variant of `compilation-mode' for the output of the Go guru tool." (set (make-local-variable 'compilation-error-screen-columns) nil) (set (make-local-variable 'compilation-filter-hook) #'go-guru--compilation-filter-hook) (set (make-local-variable 'compilation-start-hook) #'go-guru--compilation-start-hook)) (defun go-guru--compilation-filter-hook () "Post-process a blob of input to the go-guru-output buffer." ;; For readability, truncate each "file:line:col:" prefix to a fixed width. ;; If the prefix is longer than 20, show "…/last/19chars.go". ;; This usually includes the last segment of the package name. ;; Hide the line and column numbers. (let ((start compilation-filter-start) (end (point))) (goto-char start) (unless (bolp) ;; TODO(adonovan): not quite right: the filter may be called ;; with chunks of output containing incomplete lines. Moving to ;; beginning-of-line may cause duplicate post-processing. (beginning-of-line)) (setq start (point)) (while (< start end) (let ((p (search-forward ": " end t))) (if (null p) (setq start end) ; break out of loop (setq p (1- p)) ; exclude final space (let* ((posn (buffer-substring-no-properties start p)) (flen (cl-search ":" posn)) ; length of filename (filename (if (< flen 19) (substring posn 0 flen) (concat "…" (substring posn (- flen 19) flen))))) (put-text-property start p 'display filename) (forward-line 1) (setq start (point)))))))) (defun go-guru--compilation-start-hook (proc) "Erase default output header inserted by `compilation-mode'." (with-current-buffer (process-buffer proc) (let ((inhibit-read-only t)) (goto-char (point-min)) (delete-region (point) (point-max))))) (defun go-guru--start (mode) "Start an asynchronous Go guru process for the specified query MODE, passing it the selected region of the current buffer, and feeding its standard input with the contents of all modified Go buffers. Its output is handled by `go-guru-output-mode', a variant of `compilation-mode'." (or buffer-file-name (error "Cannot use guru on a buffer without a file name")) (let* ((filename (file-truename buffer-file-name)) (cmd (mapconcat #'shell-quote-argument (go-guru--command mode filename) " ")) (process-connection-type nil) ; use pipe (not pty) so EOF closes stdin (procbuf (compilation-start cmd 'go-guru-output-mode))) (with-current-buffer procbuf (setq truncate-lines t)) ; the output is neater without line wrapping (with-current-buffer (get-buffer-create "*go-guru-input*") (erase-buffer) (go-guru--insert-modified-files) (process-send-region procbuf (point-min) (point-max)) (process-send-eof procbuf)) procbuf)) (defun go-guru--command (mode filename &optional flags) "Return a command and argument list for a Go guru query of MODE, passing it the selected region of the current buffer. FILENAME is the effective name of the current buffer." (let* ((posn (if (use-region-p) (format "%s:#%d,#%d" filename (1- (position-bytes (region-beginning))) (1- (position-bytes (region-end)))) (format "%s:#%d" filename (1- (position-bytes (point)))))) (cmd (append (list go-guru-command "-modified" "-scope" go-guru-scope (format "-tags=%s" (mapconcat 'identity go-guru-build-tags ","))) flags (list mode posn)))) ;; Log the command to *Messages*, for debugging. (when go-guru-debug (message "go-guru--command: %s" cmd) (message nil)) ; clear/shrink minibuffer cmd)) (defun go-guru--insert-modified-files () "Insert the contents of each modified Go buffer into the current buffer in the format specified by guru's -modified flag." (mapc #'(lambda (b) (and (buffer-modified-p b) (buffer-file-name b) (string= (file-name-extension (buffer-file-name b)) "go") (go-guru--insert-modified-file (buffer-file-name b) b))) (buffer-list))) (defun go-guru--insert-modified-file (name buffer) (insert (format "%s\n%d\n" name (go-guru--buffer-size-bytes buffer))) (insert-buffer-substring buffer)) (defun go-guru--buffer-size-bytes (&optional buffer) "Return the number of bytes in the current buffer. If BUFFER, return the number of characters in that buffer instead." (with-current-buffer (or buffer (current-buffer)) (string-bytes (buffer-substring (point-min) (point-max))))) (defun go-guru--goto-byte (offset) "Go to the OFFSETth byte in the buffer." (goto-char (byte-to-position offset))) (defun go-guru--goto-byte-column (offset) "Go to the OFFSETth byte in the current line." (goto-char (byte-to-position (+ (position-bytes (point-at-bol)) (1- offset))))) (defun go-guru--goto-pos (posn) "Find the file containing the position POSN (of the form `file:line:col') set the point to it, switching the current buffer." (let ((file-line-pos (split-string posn ":"))) (find-file (car file-line-pos)) (goto-char (point-min)) (forward-line (1- (string-to-number (cadr file-line-pos)))) (go-guru--goto-byte-column (string-to-number (cl-caddr file-line-pos))))) (defun go-guru--goto-pos-no-file (posn) "Given `file:line:col', go to the line and column. The file component will be ignored." (let ((file-line-pos (split-string posn ":"))) (goto-char (point-min)) (forward-line (1- (string-to-number (cadr file-line-pos)))) (go-guru--goto-byte-column (string-to-number (cl-caddr file-line-pos))))) ;;;###autoload (defun go-guru-callees () "Show possible callees of the function call at the current point." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "callees")) ;;;###autoload (defun go-guru-callers () "Show the set of callers of the function containing the current point." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "callers")) ;;;###autoload (defun go-guru-callstack () "Show an arbitrary path from a root of the call graph to the function containing the current point." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "callstack")) ;;;###autoload (defun go-guru-definition () "Jump to the definition of the selected identifier." (interactive) (or buffer-file-name (error "Cannot use guru on a buffer without a file name")) (let* ((res (go-guru--json "definition")) (desc (cdr (assoc 'desc res)))) (push-mark) (ring-insert find-tag-marker-ring (point-marker)) (go-guru--goto-pos (cdr (assoc 'objpos res))) (message "%s" desc))) ;;;###autoload (defun go-guru-describe () "Describe the selected syntax, its kind, type and methods." (interactive) (go-guru--start "describe")) ;;;###autoload (defun go-guru-pointsto () "Show what the selected expression points to." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "pointsto")) ;;;###autoload (defun go-guru-implements () "Describe the 'implements' relation for types in the package containing the current point." (interactive) (go-guru--start "implements")) ;;;###autoload (defun go-guru-freevars () "Enumerate the free variables of the current selection." (interactive) (go-guru--start "freevars")) ;;;###autoload (defun go-guru-peers () "Enumerate the set of possible corresponding sends/receives for this channel receive/send operation." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "peers")) ;;;###autoload (defun go-guru-referrers () "Enumerate all references to the object denoted by the selected identifier." (interactive) (go-guru--start "referrers")) ;;;###autoload (defun go-guru-whicherrs () "Show globals, constants and types to which the selected expression (of type 'error') may refer." (interactive) (go-guru--set-scope-if-empty) (go-guru--start "whicherrs")) (defun go-guru-what () "Run a 'what' query and return the parsed JSON response as an association list." (go-guru--json "what")) (defun go-guru--hl-symbols (posn face id) "Highlight the symbols at the positions POSN by creating overlays with face FACE. The attribute 'go-guru-overlay on the overlays will be set to ID." (save-excursion (mapc (lambda (pos) (go-guru--goto-pos-no-file pos) (let ((x (make-overlay (point) (+ (point) (length (current-word)))))) (overlay-put x 'go-guru-overlay id) (overlay-put x 'face face))) posn))) ;;;###autoload (defun go-guru-unhighlight-identifiers () "Remove highlights from previously highlighted identifier." (remove-overlays nil nil 'go-guru-overlay 'sameid)) ;;;###autoload (defun go-guru-hl-identifier () "Highlight all instances of the identifier under point. Removes highlights from previously highlighted identifier." (interactive) (go-guru-unhighlight-identifiers) (go-guru--hl-identifier)) (defun go-guru--hl-identifier () "Highlight all instances of the identifier under point." (let ((posn (cdr (assoc 'sameids (go-guru-what))))) (go-guru--hl-symbols posn 'go-guru-hl-identifier-face 'sameid))) (defun go-guru--hl-identifiers-function () "Function run after an idle timeout, highlighting the identifier at point, if necessary." (when go-guru-hl-identifier-mode (unless (go-guru--on-overlay-p 'sameid) ;; Ignore guru errors. Otherwise, we might end up with an error ;; every time the timer runs, e.g. because of a malformed ;; buffer. (condition-case nil (go-guru-hl-identifier) (error nil))) (unless (eq go-guru--current-hl-identifier-idle-time go-guru-hl-identifier-idle-time) (go-guru--hl-set-timer)))) (defun go-guru--hl-set-timer () (if go-guru--hl-identifier-timer (cancel-timer go-guru--hl-identifier-timer)) (setq go-guru--current-hl-identifier-idle-time go-guru-hl-identifier-idle-time) (setq go-guru--hl-identifier-timer (run-with-idle-timer go-guru-hl-identifier-idle-time t #'go-guru--hl-identifiers-function))) ;;;###autoload (define-minor-mode go-guru-hl-identifier-mode "Highlight instances of the identifier at point after a short timeout." :group 'go-guru (if go-guru-hl-identifier-mode (progn (go-guru--hl-set-timer) ;; Unhighlight if point moves off identifier (add-hook 'post-command-hook #'go-guru--hl-identifiers-post-command-hook nil t) ;; Unhighlight any time the buffer changes (add-hook 'before-change-functions #'go-guru--hl-identifiers-before-change-function nil t)) (remove-hook 'post-command-hook #'go-guru--hl-identifiers-post-command-hook t) (remove-hook 'before-change-functions #'go-guru--hl-identifiers-before-change-function t) (go-guru-unhighlight-identifiers))) (defun go-guru--on-overlay-p (id) "Return whether point is on a guru overlay of type ID." (cl-find-if (lambda (el) (eq (overlay-get el 'go-guru-overlay) id)) (overlays-at (point)))) (defun go-guru--hl-identifiers-post-command-hook () (if (and go-guru-hl-identifier-mode (not (go-guru--on-overlay-p 'sameid))) (go-guru-unhighlight-identifiers))) (defun go-guru--hl-identifiers-before-change-function (_beg _end) (go-guru-unhighlight-identifiers)) ;; TODO(dominikh): a future feature may be to cycle through all uses ;; of an identifier. (defun go-guru--enclosing () "Return a list of enclosing regions." (cdr (assoc 'enclosing (go-guru-what)))) (defun go-guru--enclosing-unique () "Return a list of enclosing regions, with duplicates removed. Two regions are considered equal if they have the same start and end point." (let ((enclosing (go-guru--enclosing))) (cl-remove-duplicates enclosing :from-end t :test (lambda (a b) (and (= (cdr (assoc 'start a)) (cdr (assoc 'start b))) (= (cdr (assoc 'end a)) (cdr (assoc 'end b)))))))) (defun go-guru-expand-region () "Expand region to the next enclosing syntactic unit." (interactive) (let* ((enclosing (if (eq last-command #'go-guru-expand-region) go-guru--last-enclosing (go-guru--enclosing-unique))) (block (if (> (length enclosing) 0) (elt enclosing 0)))) (when block (go-guru--goto-byte (1+ (cdr (assoc 'start block)))) (set-mark (byte-to-position (1+ (cdr (assoc 'end block))))) (setq go-guru--last-enclosing (cl-subseq enclosing 1)) (message "Region: %s" (cdr (assoc 'desc block))) (setq deactivate-mark nil)))) (provide 'go-guru) ;; Local variables: ;; indent-tabs-mode: t ;; tab-width: 8 ;; End ;;; go-guru.el ends here go-mode.el-1.5.0/go-mode-autoloads.el000066400000000000000000000057311306010772700173160ustar00rootroot00000000000000;;; go-mode-autoloads.el --- automatically extracted autoloads ;; ;;; Code: ;;;### (autoloads (go-download-play godoc gofmt-before-save go-mode) ;;;;;; "go-mode" "go-mode.el" (21514 38760 682820 85000)) ;;; Generated autoloads from go-mode.el (autoload 'go-mode "go-mode" "\ Major mode for editing Go source text. This mode provides (not just) basic editing capabilities for working with Go code. It offers almost complete syntax highlighting, indentation that is almost identical to gofmt and proper parsing of the buffer content to allow features such as navigation by function, manipulation of comments or detection of strings. In addition to these core features, it offers various features to help with writing Go code. You can directly run buffer content through gofmt, read godoc documentation from within Emacs, modify and clean up the list of package imports or interact with the Playground (uploading and downloading pastes). The following extra functions are defined: - `gofmt' - `godoc' - `go-import-add' - `go-remove-unused-imports' - `go-goto-imports' - `go-play-buffer' and `go-play-region' - `go-download-play' - `godef-describe' and `godef-jump' - `go-coverage' If you want to automatically run `gofmt' before saving a file, add the following hook to your emacs configuration: \(add-hook 'before-save-hook #'gofmt-before-save) If you want to use `godef-jump' instead of etags (or similar), consider binding godef-jump to `M-.', which is the default key for `find-tag': \(add-hook 'go-mode-hook (lambda () (local-set-key (kbd \"M-.\") #'godef-jump))) Please note that godef is an external dependency. You can install it with go get github.com/rogpeppe/godef If you're looking for even more integration with Go, namely on-the-fly syntax checking, auto-completion and snippets, it is recommended that you look at flycheck \(see URL `https://github.com/flycheck/flycheck') or flymake in combination with goflymake (see URL `https://github.com/dougm/goflymake'), gocode \(see URL `https://github.com/nsf/gocode'), go-eldoc \(see URL `github.com/syohex/emacs-go-eldoc') and yasnippet-go \(see URL `https://github.com/dominikh/yasnippet-go') \(fn)" t nil) (add-to-list 'auto-mode-alist (cons "\\.go\\'" 'go-mode)) (autoload 'gofmt-before-save "go-mode" "\ Add this to .emacs to run gofmt on the current buffer when saving: (add-hook 'before-save-hook 'gofmt-before-save). Note that this will cause go-mode to get loaded the first time you save any file, kind of defeating the point of autoloading. \(fn)" t nil) (autoload 'godoc "go-mode" "\ Show Go documentation for a query, much like M-x man. \(fn QUERY)" t nil) (autoload 'go-download-play "go-mode" "\ Downloads a paste from the playground and inserts it in a Go buffer. Tries to look for a URL at point. \(fn URL)" t nil) ;;;*** (provide 'go-mode-autoloads) ;; Local Variables: ;; version-control: never ;; no-byte-compile: t ;; no-update-autoloads: t ;; coding: utf-8 ;; End: ;;; go-mode-autoloads.el ends here go-mode.el-1.5.0/go-mode.el000066400000000000000000002252561306010772700153330ustar00rootroot00000000000000;;; go-mode.el --- Major mode for the Go programming language ;;; Commentary: ;; Copyright 2013 The go-mode Authors. All rights reserved. ;; Use of this source code is governed by a BSD-style ;; license that can be found in the LICENSE file. ;; Author: The go-mode Authors ;; Version: 1.5.0 ;; Keywords: languages go ;; URL: https://github.com/dominikh/go-mode.el ;; ;; This file is not part of GNU Emacs. ;;; Code: (require 'cl-lib) (require 'compile) (require 'etags) (require 'ffap) (require 'find-file) (require 'ring) (require 'url) (require 'xref nil :noerror) ; xref is new in Emacs 25.1 (eval-when-compile (defmacro go--forward-word (&optional arg) (if (fboundp 'forward-word-strictly) `(forward-word-strictly ,arg) `(forward-word ,arg)))) (defun go--delete-whole-line (&optional arg) "Delete the current line without putting it in the `kill-ring'. Derived from function `kill-whole-line'. ARG is defined as for that function." (setq arg (or arg 1)) (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp))) (signal 'end-of-buffer nil)) (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp))) (signal 'beginning-of-buffer nil)) (cond ((zerop arg) (delete-region (progn (forward-visible-line 0) (point)) (progn (end-of-visible-line) (point)))) ((< arg 0) (delete-region (progn (end-of-visible-line) (point)) (progn (forward-visible-line (1+ arg)) (unless (bobp) (backward-char)) (point)))) (t (delete-region (progn (forward-visible-line 0) (point)) (progn (forward-visible-line arg) (point)))))) (defun go-goto-opening-parenthesis (&optional _legacy-unused) "Move up one level of parentheses." ;; The old implementation of go-goto-opening-parenthesis had an ;; optional argument to speed up the function. It didn't change the ;; function's outcome. ;; Silently fail if there's no matching opening parenthesis. (condition-case nil (backward-up-list) (scan-error nil))) (defconst go-dangling-operators-regexp "[^-]-\\|[^+]\\+\\|[/*&><.=|^]") (defconst go--max-dangling-operator-length 2 "The maximum length of dangling operators. This must be at least the length of the longest string matched by ‘go-dangling-operators-regexp.’, and must be updated whenever that constant is changed.") (defconst go-identifier-regexp "[[:word:][:multibyte:]]+") (defconst go-type-name-no-prefix-regexp "\\(?:[[:word:][:multibyte:]]+\\.\\)?[[:word:][:multibyte:]]+") (defconst go-qualified-identifier-regexp (concat go-identifier-regexp "\\." go-identifier-regexp)) (defconst go-label-regexp go-identifier-regexp) (defconst go-type-regexp "[[:word:][:multibyte:]*]+") (defconst go-func-regexp (concat "\\_\\s *\\(" go-identifier-regexp "\\)")) (defconst go-func-meth-regexp (concat "\\_\\s *\\(?:(\\s *" "\\(" go-identifier-regexp "\\s +\\)?" go-type-regexp "\\s *)\\s *\\)?\\(" go-identifier-regexp "\\)(")) (defconst go-builtins '("append" "cap" "close" "complex" "copy" "delete" "imag" "len" "make" "new" "panic" "print" "println" "real" "recover") "All built-in functions in the Go language. Used for font locking.") (defconst go-mode-keywords '("break" "default" "func" "interface" "select" "case" "defer" "go" "map" "struct" "chan" "else" "goto" "package" "switch" "const" "fallthrough" "if" "range" "type" "continue" "for" "import" "return" "var") "All keywords in the Go language. Used for font locking.") (defconst go-constants '("nil" "true" "false" "iota")) (defconst go-type-name-regexp (concat "\\(?:[*(]\\)*\\(\\(?:" go-identifier-regexp "\\.\\)?" go-identifier-regexp "\\)")) ;; Maximum number of identifiers that can be highlighted as type names ;; in one function type/declaration. (defconst go--font-lock-func-param-num-groups 16) (defvar go-dangling-cache) (defvar go-godoc-history nil) (defvar go--coverage-current-file-name) (defgroup go nil "Major mode for editing Go code." :link '(url-link "https://github.com/dominikh/go-mode.el") :group 'languages) (defgroup go-cover nil "Options specific to `cover`." :group 'go) (defgroup godoc nil "Options specific to `godoc'." :group 'go) (defcustom go-fontify-function-calls t "Fontify function and method calls if this is non-nil." :type 'boolean :group 'go) (defcustom go-mode-hook nil "Hook called by `go-mode'." :type 'hook :group 'go) (defcustom go-command "go" "The 'go' command. Some users have multiple Go development trees and invoke the 'go' tool via a wrapper that sets GOROOT and GOPATH based on the current directory. Such users should customize this variable to point to the wrapper script." :type 'string :group 'go) (defcustom gofmt-command "gofmt" "The 'gofmt' command. Some users may replace this with 'goimports' from https://golang.org/x/tools/cmd/goimports." :type 'string :group 'go) (defcustom gofmt-args nil "Additional arguments to pass to gofmt." :type '(repeat string) :group 'go) (defcustom gofmt-show-errors 'buffer "Where to display gofmt error output. It can either be displayed in its own buffer, in the echo area, or not at all. Please note that Emacs outputs to the echo area when writing files and will overwrite gofmt's echo output if used from inside a `before-save-hook'." :type '(choice (const :tag "Own buffer" buffer) (const :tag "Echo area" echo) (const :tag "None" nil)) :group 'go) (defcustom godef-command "godef" "The 'godef' command." :type 'string :group 'go) (defcustom go-other-file-alist '(("_test\\.go\\'" (".go")) ("\\.go\\'" ("_test.go"))) "See the documentation of `ff-other-file-alist' for details." :type '(repeat (list regexp (choice (repeat string) function))) :group 'go) (defcustom go-packages-function 'go-packages-native "Function called by `go-packages' to determine the list of available packages. This is used in e.g. tab completion in `go-import-add'. This package provides two functions: `go-packages-native' uses elisp to find all .a files in all /pkg/ directories. `go-packages-go-list' uses 'go list all' to determine all Go packages. `go-packages-go-list' generally produces more accurate results, but can be slower than `go-packages-native'." :type 'function :package-version '(go-mode . 1.4.0) :group 'go) (defcustom go-guess-gopath-functions (list #'go-godep-gopath #'go-wgo-gopath #'go-gb-gopath #'go-plain-gopath) "Functions to call in sequence to detect a project's GOPATH. The functions in this list will be called one after another, until a function returns non-nil. The order of the functions in this list is important, as some project layouts may superficially look like others. For example, a subset of wgo projects look like gb projects. That's why we need to detect wgo first, to avoid mis-identifying them as gb projects." :type '(repeat function) :group 'go) (defcustom godoc-command "go doc" "Which executable to use for `godoc'. This can either be 'godoc' or 'go doc', both as an absolute path or an executable in PATH." :type 'string :group 'go) (defcustom godoc-and-godef-command "godoc" "Which executable to use for `godoc' in `godoc-and-godef-command'. Must be 'godoc' and not 'go doc' and can be an absolute path or an executable in PATH." :type 'string :group 'go) (defcustom godoc-use-completing-read nil "Provide auto-completion for godoc. Only really desirable when using `godoc' instead of `go doc'." :type 'boolean :group 'godoc) (defcustom godoc-at-point-function #'godoc-and-godef "Function to call to display the documentation for an identifier at a given position. This package provides two functions: `godoc-and-godef' uses a combination of godef and godoc to find the documentation. This approach has several caveats. See its documentation for more information. The second function, `godoc-gogetdoc' uses an additional tool that correctly determines the documentation for any identifier. It provides better results than `godoc-and-godef'." :type 'function :group 'godoc) (defun godoc-and-godef (point) "Use a combination of godef and godoc to guess the documentation at POINT. Due to a limitation in godoc, it is not possible to differentiate between functions and methods, which may cause `godoc-at-point' to display more documentation than desired. Furthermore, it doesn't work on package names or variables. Consider using ‘godoc-gogetdoc’ instead for more accurate results." (condition-case nil (let* ((output (godef--call point)) (file (car output)) (name-parts (split-string (cadr output) " ")) (first (car name-parts))) (if (not (godef--successful-p file)) (message "%s" (godef--error file)) (go--godoc (format "%s %s" (file-name-directory file) (if (or (string= first "type") (string= first "const")) (cadr name-parts) (car name-parts))) godoc-and-godef-command))) (file-error (message "Could not run godef binary")))) (defun godoc-gogetdoc (point) "Use the gogetdoc tool to find the documentation for an identifier at POINT. You can install gogetdoc with 'go get -u github.com/zmb3/gogetdoc'." (if (not (buffer-file-name (go--coverage-origin-buffer))) ;; TODO: gogetdoc supports unsaved files, but not introducing ;; new artifical files, so this limitation will stay for now. (error "Cannot use gogetdoc on a buffer without a file name")) (let ((posn (format "%s:#%d" (shell-quote-argument (file-truename buffer-file-name)) (1- (position-bytes point)))) (out (godoc--get-buffer ""))) (with-current-buffer (get-buffer-create "*go-gogetdoc-input*") (setq buffer-read-only nil) (erase-buffer) (go--insert-modified-files) (call-process-region (point-min) (point-max) "gogetdoc" nil out nil "-modified" (format "-pos=%s" posn))) (with-current-buffer out (goto-char (point-min)) (godoc-mode) (display-buffer (current-buffer) t)))) (defun go--kill-new-message (url) "Make URL the latest kill and print a message." (kill-new url) (message "%s" url)) (defcustom go-play-browse-function 'go--kill-new-message "Function to call with the Playground URL. See `go-play-region' for more details." :type '(choice (const :tag "Nothing" nil) (const :tag "Kill + Message" go--kill-new-message) (const :tag "Browse URL" browse-url) (function :tag "Call function")) :group 'go) (defcustom go-coverage-display-buffer-func 'display-buffer-reuse-window "How `go-coverage' should display the coverage buffer. See `display-buffer' for a list of possible functions." :type 'function :group 'go-cover) (defface go-coverage-untracked '((t (:foreground "#505050"))) "Coverage color of untracked code." :group 'go-cover) (defface go-coverage-0 '((t (:foreground "#c00000"))) "Coverage color for uncovered code." :group 'go-cover) (defface go-coverage-1 '((t (:foreground "#808080"))) "Coverage color for covered code with weight 1." :group 'go-cover) (defface go-coverage-2 '((t (:foreground "#748c83"))) "Coverage color for covered code with weight 2." :group 'go-cover) (defface go-coverage-3 '((t (:foreground "#689886"))) "Coverage color for covered code with weight 3." :group 'go-cover) (defface go-coverage-4 '((t (:foreground "#5ca489"))) "Coverage color for covered code with weight 4." :group 'go-cover) (defface go-coverage-5 '((t (:foreground "#50b08c"))) "Coverage color for covered code with weight 5." :group 'go-cover) (defface go-coverage-6 '((t (:foreground "#44bc8f"))) "Coverage color for covered code with weight 6." :group 'go-cover) (defface go-coverage-7 '((t (:foreground "#38c892"))) "Coverage color for covered code with weight 7." :group 'go-cover) (defface go-coverage-8 '((t (:foreground "#2cd495"))) "Coverage color for covered code with weight 8. For mode=set, all covered lines will have this weight." :group 'go-cover) (defface go-coverage-9 '((t (:foreground "#20e098"))) "Coverage color for covered code with weight 9." :group 'go-cover) (defface go-coverage-10 '((t (:foreground "#14ec9b"))) "Coverage color for covered code with weight 10." :group 'go-cover) (defface go-coverage-covered '((t (:foreground "#2cd495"))) "Coverage color of covered code." :group 'go-cover) (defvar go-mode-syntax-table (let ((st (make-syntax-table))) (modify-syntax-entry ?+ "." st) (modify-syntax-entry ?- "." st) (modify-syntax-entry ?% "." st) (modify-syntax-entry ?& "." st) (modify-syntax-entry ?| "." st) (modify-syntax-entry ?^ "." st) (modify-syntax-entry ?! "." st) (modify-syntax-entry ?= "." st) (modify-syntax-entry ?< "." st) (modify-syntax-entry ?> "." st) (modify-syntax-entry ?/ ". 124b" st) (modify-syntax-entry ?* ". 23" st) (modify-syntax-entry ?\n "> b" st) (modify-syntax-entry ?\" "\"" st) (modify-syntax-entry ?\' "\"" st) (modify-syntax-entry ?` "\"" st) (modify-syntax-entry ?\\ "\\" st) ;; TODO make _ a symbol constituent now that xemacs is gone (modify-syntax-entry ?_ "w" st) st) "Syntax table for Go mode.") (defun go--build-font-lock-keywords () ;; we cannot use 'symbols in regexp-opt because GNU Emacs <24 ;; doesn't understand that (append `((go--match-func ,@(mapcar (lambda (x) `(,x font-lock-type-face)) (number-sequence 1 go--font-lock-func-param-num-groups))) (,(concat "\\_<" (regexp-opt go-mode-keywords t) "\\_>") . font-lock-keyword-face) (,(concat "\\(\\_<" (regexp-opt go-builtins t) "\\_>\\)[[:space:]]*(") 1 font-lock-builtin-face) (,(concat "\\_<" (regexp-opt go-constants t) "\\_>") . font-lock-constant-face) (,go-func-regexp 1 font-lock-function-name-face)) ;; function (not method) name (if go-fontify-function-calls `((,(concat "\\(" go-identifier-regexp "\\)[[:space:]]*(") 1 font-lock-function-name-face) ;; function call/method name (,(concat "[^[:word:][:multibyte:]](\\(" go-identifier-regexp "\\))[[:space:]]*(") 1 font-lock-function-name-face)) ;; bracketed function call `((,go-func-meth-regexp 2 font-lock-function-name-face))) ;; method name `( ("\\(`[^`]*`\\)" 1 font-lock-multiline) ;; raw string literal, needed for font-lock-syntactic-keywords (,(concat "\\_[[:space:]]+\\([^[:space:](]+\\)") 1 font-lock-type-face) ;; types (,(concat "\\_[[:space:]]+" go-identifier-regexp "[[:space:]]*" go-type-name-regexp) 1 font-lock-type-face) ;; types (,(concat "[^[:word:][:multibyte:]]\\[\\([[:digit:]]+\\|\\.\\.\\.\\)?\\]" go-type-name-regexp) 2 font-lock-type-face) ;; Arrays/slices (,(concat "\\(" go-identifier-regexp "\\)" "{") 1 font-lock-type-face) (,(concat "\\_\\[[^]]+\\]" go-type-name-regexp) 1 font-lock-type-face) ;; map value type (,(concat "\\_\\[" go-type-name-regexp) 1 font-lock-type-face) ;; map key type (,(concat "\\_[[:space:]]*\\(?:<-[[:space:]]*\\)?" go-type-name-regexp) 1 font-lock-type-face) ;; channel type (,(concat "\\_<\\(?:new\\|make\\)\\_>\\(?:[[:space:]]\\|)\\)*(" go-type-name-regexp) 1 font-lock-type-face) ;; new/make type ;; TODO do we actually need this one or isn't it just a function call? (,(concat "\\.\\s *(" go-type-name-regexp) 1 font-lock-type-face) ;; Type conversion ;; Like the original go-mode this also marks compound literal ;; fields. There, it was marked as to fix, but I grew quite ;; accustomed to it, so it'll stay for now. (,(concat "^[[:space:]]*\\(" go-label-regexp "\\)[[:space:]]*:\\(\\S.\\|$\\)") 1 font-lock-constant-face) ;; Labels and compound literal fields (,(concat "\\_<\\(goto\\|break\\|continue\\)\\_>[[:space:]]*\\(" go-label-regexp "\\)") 2 font-lock-constant-face)))) ;; labels in goto/break/continue (let ((m (define-prefix-command 'go-goto-map))) (define-key m "a" #'go-goto-arguments) (define-key m "d" #'go-goto-docstring) (define-key m "f" #'go-goto-function) (define-key m "i" #'go-goto-imports) (define-key m "m" #'go-goto-method-receiver) (define-key m "n" #'go-goto-function-name) (define-key m "r" #'go-goto-return-values)) (defvar go-mode-map (let ((m (make-sparse-keymap))) (unless (boundp 'electric-indent-chars) (define-key m "}" #'go-mode-insert-and-indent) (define-key m ")" #'go-mode-insert-and-indent)) (define-key m (kbd "C-c C-a") #'go-import-add) (define-key m (kbd "C-c C-j") #'godef-jump) (define-key m (kbd "C-x 4 C-c C-j") #'godef-jump-other-window) (define-key m (kbd "C-c C-d") #'godef-describe) (define-key m (kbd "C-c C-f") 'go-goto-map) m) "Keymap used by ‘go-mode’.") (easy-menu-define go-mode-menu go-mode-map "Menu for Go mode." '("Go" ["Describe Expression" godef-describe t] ["Jump to Definition" godef-jump t] "---" ["Add Import" go-import-add t] ["Remove Unused Imports" go-remove-unused-imports t] ["Go to Imports" go-goto-imports t] "---" ("Playground" ["Send Buffer" go-play-buffer t] ["Send Region" go-play-region t] ["Download" go-download-play t]) "---" ["Coverage" go-coverage t] ["Gofmt" gofmt t] ["Godoc" godoc t] "---" ["Customize Mode" (customize-group 'go) t])) (defun go-mode-insert-and-indent (key) "Invoke the global binding of KEY, then reindent the line." (interactive (list (this-command-keys))) (call-interactively (lookup-key (current-global-map) key)) (indent-according-to-mode)) (defmacro go-paren-level () `(car (syntax-ppss))) (defmacro go-in-string-or-comment-p () `(nth 8 (syntax-ppss))) (defmacro go-in-string-p () `(nth 3 (syntax-ppss))) (defmacro go-in-comment-p () `(nth 4 (syntax-ppss))) (defmacro go-goto-beginning-of-string-or-comment () `(goto-char (nth 8 (syntax-ppss)))) (defun go--backward-irrelevant (&optional stop-at-string) "Skip backwards over any characters that are irrelevant for indentation and related tasks. It skips over whitespace, comments, cases and labels and, if STOP-AT-STRING is not true, over strings." (let (pos (start-pos (point))) (skip-chars-backward "\n\s\t") (if (and (save-excursion (beginning-of-line) (go-in-string-p)) (= (char-before) ?`) (not stop-at-string)) (backward-char)) (if (and (go-in-string-p) (not stop-at-string)) (go-goto-beginning-of-string-or-comment)) (if (looking-back "\\*/" (line-beginning-position)) (backward-char)) (if (go-in-comment-p) (go-goto-beginning-of-string-or-comment)) (setq pos (point)) (beginning-of-line) (if (or (looking-at (concat "^" go-label-regexp ":")) (looking-at "^[[:space:]]*\\(case .+\\|default\\):")) (end-of-line 0) (goto-char pos)) (if (/= start-pos (point)) (go--backward-irrelevant stop-at-string)) (/= start-pos (point)))) (defun go--buffer-narrowed-p () "Return non-nil if the current buffer is narrowed." (/= (buffer-size) (- (point-max) (point-min)))) (defun go-previous-line-has-dangling-op-p () "Return non-nil if the current line is a continuation line." (let* ((cur-line (line-number-at-pos)) (val (gethash cur-line go-dangling-cache 'nope))) (if (or (go--buffer-narrowed-p) (equal val 'nope)) (save-excursion (beginning-of-line) (go--backward-irrelevant t) (setq val (looking-back go-dangling-operators-regexp (- (point) go--max-dangling-operator-length))) (if (not (go--buffer-narrowed-p)) (puthash cur-line val go-dangling-cache)))) val)) (defun go--at-function-definition () "Return non-nil if point is on the opening curly brace of a function definition. We do this by first calling (beginning-of-defun), which will take us to the start of *some* function. We then look for the opening curly brace of that function and compare its position against the curly brace we are checking. If they match, we return non-nil." (if (= (char-after) ?\{) (save-excursion (let ((old-point (point)) start-nesting) (beginning-of-defun) (when (looking-at "func ") (setq start-nesting (go-paren-level)) (skip-chars-forward "^{") (while (> (go-paren-level) start-nesting) (forward-char) (skip-chars-forward "^{") 0) (if (and (= (go-paren-level) start-nesting) (= old-point (point))) t)))))) (defun go--indentation-for-opening-parenthesis () "Return the semantic indentation for the current opening parenthesis. If point is on an opening curly brace and said curly brace belongs to a function declaration, the indentation of the func keyword will be returned. Otherwise the indentation of the current line will be returned." (save-excursion (if (go--at-function-definition) (progn (beginning-of-defun) (current-indentation)) (current-indentation)))) (defun go-indentation-at-point () (save-excursion (let (start-nesting) (back-to-indentation) (setq start-nesting (go-paren-level)) (cond ((go-in-string-p) (current-indentation)) ((looking-at "[])}]") (go-goto-opening-parenthesis) (if (go-previous-line-has-dangling-op-p) (- (current-indentation) tab-width) (go--indentation-for-opening-parenthesis))) ((progn (go--backward-irrelevant t) (looking-back go-dangling-operators-regexp (- (point) go--max-dangling-operator-length))) ;; only one nesting for all dangling operators in one operation (if (go-previous-line-has-dangling-op-p) (current-indentation) (+ (current-indentation) tab-width))) ((zerop (go-paren-level)) 0) ((progn (go-goto-opening-parenthesis) (< (go-paren-level) start-nesting)) (if (go-previous-line-has-dangling-op-p) (current-indentation) (+ (go--indentation-for-opening-parenthesis) tab-width))) (t (current-indentation)))))) (defun go-mode-indent-line () (interactive) (let (indent shift-amt (pos (- (point-max) (point))) (point (point)) (beg (line-beginning-position))) (back-to-indentation) (if (go-in-string-or-comment-p) (goto-char point) (setq indent (go-indentation-at-point)) (if (looking-at (concat go-label-regexp ":\\([[:space:]]*/.+\\)?$\\|case .+:\\|default:")) (cl-decf indent tab-width)) (setq shift-amt (- indent (current-column))) (if (zerop shift-amt) nil (delete-region beg (point)) (indent-to indent)) ;; If initial point was within line's indentation, ;; position after the indentation. Else stay at same point in text. (if (> (- (point-max) pos) (point)) (goto-char (- (point-max) pos)))))) (defun go-beginning-of-defun (&optional count) (unless (bolp) (end-of-line)) (setq count (or count 1)) (let (first failure) (dotimes (i (abs count)) (setq first t) (while (and (not failure) (or first (go-in-string-or-comment-p))) (if (>= count 0) (progn (go--backward-irrelevant) (if (not (re-search-backward go-func-meth-regexp nil t)) (setq failure t))) (if (looking-at go-func-meth-regexp) (forward-char)) (if (not (re-search-forward go-func-meth-regexp nil t)) (setq failure t))) (setq first nil))) (if (< count 0) (beginning-of-line)) (not failure))) (defun go-end-of-defun () (let (orig-level) ;; It can happen that we're not placed before a function by emacs (if (not (looking-at "func")) (go-beginning-of-defun -1)) ;; Find the { that starts the function, i.e., the next { that isn't ;; preceded by struct or interface, or a comment or struct tag. BUG: ;; breaks if there's a comment between the struct/interface keyword and ;; bracket, like this: ;; ;; struct /* why? */ { (while (progn (skip-chars-forward "^{") (forward-char) (or (go-in-string-or-comment-p) (looking-back "\\(struct\\|interface\\)\\s-*{" (line-beginning-position))))) (setq orig-level (go-paren-level)) (while (>= (go-paren-level) orig-level) (skip-chars-forward "^}") (forward-char)))) (defun go--find-enclosing-parentheses (position) "Return points of outermost '(' and ')' surrounding POSITION if such parentheses exist. If outermost '(' exists but ')' does not, it returns the next blank line or end-of-buffer position instead of the position of the closing parenthesis. If the starting parenthesis is not found, it returns (POSITION POSITION)." (save-excursion (let (beg end) (goto-char position) (while (> (go-paren-level) 0) (re-search-backward "[(\\[{]" nil t) (when (looking-at "(") (setq beg (point)))) (if (null beg) (list position position) (goto-char position) (while (and (> (go-paren-level) 0) (search-forward ")" nil t))) (when (> (go-paren-level) 0) (unless (re-search-forward "^[[:space:]]*$" nil t) (goto-char (point-max)))) (list beg (point)))))) (defun go--search-next-comma (end) "Search forward from point for a comma whose nesting level is the same as point. If it reaches the end of line or a closing parenthesis before a comma, it stops at it." (let ((orig-level (go-paren-level))) (while (and (< (point) end) (or (looking-at "[^,)\n]") (> (go-paren-level) orig-level))) (forward-char)) (when (and (looking-at ",") (< (point) (1- end))) (forward-char)))) (defun go--looking-at-keyword () (and (looking-at (concat "\\(" go-identifier-regexp "\\)")) (member (match-string 1) go-mode-keywords))) (defun go--match-func (end) "Search for identifiers used as type names from a function parameter list, and set the identifier positions as the results of last search. Return t if search succeeded." (when (re-search-forward "\\_" end t) (let ((regions (go--match-func-type-names end))) (if (null regions) ;; Nothing to highlight. This can happen if the current func ;; is "func()". Try next one. (go--match-func end) ;; There are something to highlight. Set those positions as ;; last search results. (setq regions (go--filter-match-data regions end)) (when regions (set-match-data (go--make-match-data regions)) t))))) (defun go--match-func-type-names (end) (cond ;; Function declaration (e.g. "func foo(") ((looking-at (concat "[[:space:]\n]*" go-identifier-regexp "[[:space:]\n]*(")) (goto-char (match-end 0)) (nconc (go--match-parameter-list end) (go--match-function-result end))) ;; Method declaration, function literal, or function type ((looking-at "[[:space:]]*(") (goto-char (match-end 0)) (let ((regions (go--match-parameter-list end))) ;; Method declaration (e.g. "func (x y) foo(") (when (looking-at (concat "[[:space:]]*" go-identifier-regexp "[[:space:]\n]*(")) (goto-char (match-end 0)) (setq regions (nconc regions (go--match-parameter-list end)))) (nconc regions (go--match-function-result end)))))) (defun go--parameter-list-type (end) "Return `present' if the parameter list has names, or `absent' if not. Assumes point is at the beginning of a parameter list, just after '('." (save-excursion (skip-chars-forward "[:space:]\n" end) (cond ((> (point) end) nil) ((looking-at (concat go-identifier-regexp "[[:space:]\n]*,")) (goto-char (match-end 0)) (go--parameter-list-type end)) ((or (looking-at go-qualified-identifier-regexp) (looking-at (concat go-type-name-no-prefix-regexp "[[:space:]\n]*\\(?:)\\|\\'\\)")) (go--looking-at-keyword) (looking-at "[*\\[]\\|\\.\\.\\.\\|\\'")) 'absent) (t 'present)))) (defconst go--opt-dotdotdot-regexp "\\(?:\\.\\.\\.\\)?") (defconst go--parameter-type-regexp (concat go--opt-dotdotdot-regexp "[[:space:]*\n]*\\(" go-type-name-no-prefix-regexp "\\)[[:space:]\n]*\\([,)]\\|\\'\\)")) (defconst go--func-type-in-parameter-list-regexp (concat go--opt-dotdotdot-regexp "[[:space:]*\n]*\\(\\_" "\\)")) (defun go--match-parameters-common (identifier-regexp end) (let ((acc ()) (start -1)) (while (progn (skip-chars-forward "[:space:]\n" end) (and (not (looking-at "\\(?:)\\|\\'\\)")) (< start (point)) (<= (point) end))) (setq start (point)) (cond ((looking-at (concat identifier-regexp go--parameter-type-regexp)) (setq acc (nconc acc (list (match-beginning 1) (match-end 1)))) (goto-char (match-beginning 2))) ((looking-at (concat identifier-regexp go--func-type-in-parameter-list-regexp)) (goto-char (match-beginning 1)) (setq acc (nconc acc (go--match-func-type-names end))) (go--search-next-comma end)) (t (go--search-next-comma end)))) (when (and (looking-at ")") (< (point) end)) (forward-char)) acc)) (defun go--match-parameters-with-identifier-list (end) (go--match-parameters-common (concat go-identifier-regexp "[[:space:]\n]+") end)) (defun go--match-parameters-without-identifier-list (end) (go--match-parameters-common "" end)) (defun go--filter-match-data (regions end) "Remove points from REGIONS if they are beyond END. REGIONS are a list whose size is multiple of 2. Element 2n is beginning of a region and 2n+1 is end of it. This function is used to make sure we don't override end point that `font-lock-mode' gave to us." (when regions (let* ((vec (vconcat regions)) (i 0) (len (length vec))) (while (and (< i len) (<= (nth i regions) end) (<= (nth (1+ i) regions) end)) (setq i (+ i 2))) (cond ((= i len) regions) ((zerop i) nil) (t (butlast regions (- (length regions) i))))))) (defun go--make-match-data (regions) (let ((deficit (- (* 2 go--font-lock-func-param-num-groups) (length regions)))) (when (> deficit 0) (let ((last (car (last regions)))) (setq regions (nconc regions (make-list deficit last)))))) `(,(car regions) ,@(last regions) ,@regions)) (defun go--match-parameter-list (end) "Return a list of identifier positions that are used as type names in a function parameter list, assuming point is at the beginning of a parameter list. Return nil if the text after point does not look like a parameter list. Set point to end of closing parenthesis on success. In Go, the names must either all be present or all be absent within a list of parameters. Parsing a parameter list is a little bit complicated because we have to scan through the parameter list to determine whether or not the list has names. Until a type name is found or reaching end of a parameter list, we are not sure which form the parameter list is. For example, X and Y are type names in a parameter list \"(X, Y)\" but are parameter names in \"(X, Y int)\". We cannot say if X is a type name until we see int after Y. Note that even \"(int, float T)\" is a valid parameter list. Builtin type names are not reserved words. In this example, int and float are parameter names and only T is a type name. In this function, we first scan the parameter list to see if the list has names, and then handle it accordingly." (let ((name (go--parameter-list-type end))) (cond ((eq name 'present) (go--match-parameters-with-identifier-list end)) ((eq name 'absent) (go--match-parameters-without-identifier-list end)) (t nil)))) (defun go--match-function-result (end) "Return a list of identifier positions that are used as type names in a function result, assuming point is at the beginning of a result. Function result is a unparenthesized type or a parameter list." (cond ((and (looking-at (concat "[[:space:]*]*\\(" go-type-name-no-prefix-regexp "\\)")) (not (member (match-string 1) go-mode-keywords))) (list (match-beginning 1) (match-end 1))) ((looking-at "[[:space:]]*(") (goto-char (match-end 0)) (go--match-parameter-list end)) (t nil))) (defun go--reset-dangling-cache-before-change (&optional _beg _end) "Reset `go-dangling-cache'. This is intended to be called from `before-change-functions'." (setq go-dangling-cache (make-hash-table :test 'eql))) ;;;###autoload (define-derived-mode go-mode prog-mode "Go" "Major mode for editing Go source text. This mode provides (not just) basic editing capabilities for working with Go code. It offers almost complete syntax highlighting, indentation that is almost identical to gofmt and proper parsing of the buffer content to allow features such as navigation by function, manipulation of comments or detection of strings. In addition to these core features, it offers various features to help with writing Go code. You can directly run buffer content through gofmt, read godoc documentation from within Emacs, modify and clean up the list of package imports or interact with the Playground (uploading and downloading pastes). The following extra functions are defined: - `gofmt' - `godoc' and `godoc-at-point' - `go-import-add' - `go-remove-unused-imports' - `go-goto-arguments' - `go-goto-docstring' - `go-goto-function' - `go-goto-function-name' - `go-goto-imports' - `go-goto-return-values' - `go-goto-method-receiver' - `go-play-buffer' and `go-play-region' - `go-download-play' - `godef-describe' and `godef-jump' - `go-coverage' - `go-set-project' - `go-reset-gopath' If you want to automatically run `gofmt' before saving a file, add the following hook to your emacs configuration: \(add-hook 'before-save-hook #'gofmt-before-save) If you want to use `godef-jump' instead of etags (or similar), consider binding godef-jump to `M-.', which is the default key for `find-tag': \(add-hook 'go-mode-hook (lambda () (local-set-key (kbd \"M-.\") #'godef-jump))) Please note that godef is an external dependency. You can install it with go get github.com/rogpeppe/godef If you're looking for even more integration with Go, namely on-the-fly syntax checking, auto-completion and snippets, it is recommended that you look at flycheck \(see URL `https://github.com/flycheck/flycheck') or flymake in combination with goflymake \(see URL `https://github.com/dougm/goflymake'), gocode \(see URL `https://github.com/nsf/gocode'), go-eldoc \(see URL `github.com/syohex/emacs-go-eldoc') and yasnippet-go \(see URL `https://github.com/dominikh/yasnippet-go')" ;; Font lock (set (make-local-variable 'font-lock-defaults) '(go--build-font-lock-keywords)) ;; Indentation (set (make-local-variable 'indent-line-function) #'go-mode-indent-line) ;; Comments (set (make-local-variable 'comment-start) "// ") (set (make-local-variable 'comment-end) "") (set (make-local-variable 'comment-use-syntax) t) (set (make-local-variable 'comment-start-skip) "\\(//+\\|/\\*+\\)\\s *") (set (make-local-variable 'beginning-of-defun-function) #'go-beginning-of-defun) (set (make-local-variable 'end-of-defun-function) #'go-end-of-defun) (set (make-local-variable 'parse-sexp-lookup-properties) t) (set (make-local-variable 'syntax-propertize-function) #'go-propertize-syntax) (if (boundp 'electric-indent-chars) (set (make-local-variable 'electric-indent-chars) '(?\n ?} ?\)))) (set (make-local-variable 'compilation-error-screen-columns) nil) (set (make-local-variable 'go-dangling-cache) (make-hash-table :test 'eql)) (add-hook 'before-change-functions #'go--reset-dangling-cache-before-change t t) ;; ff-find-other-file (setq ff-other-file-alist 'go-other-file-alist) (setq imenu-generic-expression '(("type" "^type *\\([^ \t\n\r\f]*\\)" 1) ("func" "^func *\\(.*\\) {" 1))) (imenu-add-to-menubar "Index") ;; Go style (setq indent-tabs-mode t) ;; Handle unit test failure output in compilation-mode ;; ;; Note that we add our entry to the beginning of ;; compilation-error-regexp-alist. In older versions of Emacs, the ;; list was processed from the end, and we would've wanted to add ;; ours last. But at some point this changed, and now the list is ;; processed from the beginning. It's important that our entry comes ;; before gnu, because gnu matches go test output, but includes the ;; leading whitespace in the file name. ;; ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2001-12/msg00674.html ;; documents the old, reverseed order. (when (and (boundp 'compilation-error-regexp-alist) (boundp 'compilation-error-regexp-alist-alist)) (add-to-list 'compilation-error-regexp-alist 'go-test) (add-to-list 'compilation-error-regexp-alist-alist '(go-test . ("^\t+\\([^()\t\n]+\\):\\([0-9]+\\):? .*$" 1 2)) t))) ;;;###autoload (add-to-list 'auto-mode-alist (cons "\\.go\\'" 'go-mode)) (defun go--apply-rcs-patch (patch-buffer) "Apply an RCS-formatted diff from PATCH-BUFFER to the current buffer." (let ((target-buffer (current-buffer)) ;; Relative offset between buffer line numbers and line numbers ;; in patch. ;; ;; Line numbers in the patch are based on the source file, so ;; we have to keep an offset when making changes to the ;; buffer. ;; ;; Appending lines decrements the offset (possibly making it ;; negative), deleting lines increments it. This order ;; simplifies the forward-line invocations. (line-offset 0)) (save-excursion (with-current-buffer patch-buffer (goto-char (point-min)) (while (not (eobp)) (unless (looking-at "^\\([ad]\\)\\([0-9]+\\) \\([0-9]+\\)") (error "Invalid rcs patch or internal error in go--apply-rcs-patch")) (forward-line) (let ((action (match-string 1)) (from (string-to-number (match-string 2))) (len (string-to-number (match-string 3)))) (cond ((equal action "a") (let ((start (point))) (forward-line len) (let ((text (buffer-substring start (point)))) (with-current-buffer target-buffer (cl-decf line-offset len) (goto-char (point-min)) (forward-line (- from len line-offset)) (insert text))))) ((equal action "d") (with-current-buffer target-buffer (go--goto-line (- from line-offset)) (cl-incf line-offset len) (go--delete-whole-line len))) (t (error "Invalid rcs patch or internal error in go--apply-rcs-patch"))))))))) (defun gofmt--is-goimports-p () (string-equal (file-name-base gofmt-command) "goimports")) (defun gofmt () "Format the current buffer according to the gofmt tool." (interactive) (let ((tmpfile (make-temp-file "gofmt" nil ".go")) (patchbuf (get-buffer-create "*Gofmt patch*")) (errbuf (if gofmt-show-errors (get-buffer-create "*Gofmt Errors*"))) (coding-system-for-read 'utf-8) (coding-system-for-write 'utf-8) our-gofmt-args) (unwind-protect (save-restriction (widen) (if errbuf (with-current-buffer errbuf (setq buffer-read-only nil) (erase-buffer))) (with-current-buffer patchbuf (erase-buffer)) (write-region nil nil tmpfile) (when (and (gofmt--is-goimports-p) buffer-file-name) (setq our-gofmt-args (append our-gofmt-args ;; srcdir, despite its name, supports ;; accepting a full path, and some features ;; of goimports rely on knowing the full ;; name. (list "-srcdir" (file-truename buffer-file-name))))) (setq our-gofmt-args (append our-gofmt-args gofmt-args (list "-w" tmpfile))) (message "Calling gofmt: %s %s" gofmt-command our-gofmt-args) ;; We're using errbuf for the mixed stdout and stderr output. This ;; is not an issue because gofmt -w does not produce any stdout ;; output in case of success. (if (zerop (apply #'call-process gofmt-command nil errbuf nil our-gofmt-args)) (progn (if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile)) (message "Buffer is already gofmted") (go--apply-rcs-patch patchbuf) (message "Applied gofmt")) (if errbuf (gofmt--kill-error-buffer errbuf))) (message "Could not apply gofmt") (if errbuf (gofmt--process-errors (buffer-file-name) tmpfile errbuf)))) (kill-buffer patchbuf) (delete-file tmpfile)))) (defun gofmt--process-errors (filename tmpfile errbuf) (with-current-buffer errbuf (if (eq gofmt-show-errors 'echo) (progn (message "%s" (buffer-string)) (gofmt--kill-error-buffer errbuf)) ;; Convert the gofmt stderr to something understood by the compilation mode. (goto-char (point-min)) (if (save-excursion (save-match-data (search-forward "flag provided but not defined: -srcdir" nil t))) (insert "Your version of goimports is too old and doesn't support vendoring. Please update goimports!\n\n")) (insert "gofmt errors:\n") (let ((truefile (if (gofmt--is-goimports-p) (concat (file-name-directory filename) (file-name-nondirectory tmpfile)) tmpfile))) (while (search-forward-regexp (concat "^\\(" (regexp-quote truefile) "\\):") nil t) (replace-match (file-name-nondirectory filename) t t nil 1))) (compilation-mode) (display-buffer errbuf)))) (defun gofmt--kill-error-buffer (errbuf) (let ((win (get-buffer-window errbuf))) (if win (quit-window t win) (kill-buffer errbuf)))) ;;;###autoload (defun gofmt-before-save () "Add this to .emacs to run gofmt on the current buffer when saving: \(add-hook 'before-save-hook 'gofmt-before-save). Note that this will cause ‘go-mode’ to get loaded the first time you save any file, kind of defeating the point of autoloading." (interactive) (when (eq major-mode 'go-mode) (gofmt))) (defun godoc--read-query () "Read a godoc query from the minibuffer." (if godoc-use-completing-read (completing-read "godoc; " (go-packages) nil nil nil 'go-godoc-history) (read-from-minibuffer "godoc: " nil nil nil 'go-godoc-history))) (defun godoc--get-buffer (query) "Get an empty buffer for a godoc QUERY." (let* ((buffer-name (concat "*godoc " query "*")) (buffer (get-buffer buffer-name))) ;; Kill the existing buffer if it already exists. (when buffer (kill-buffer buffer)) (get-buffer-create buffer-name))) (defun godoc--buffer-sentinel (proc event) "Sentinel function run when godoc command completes." (with-current-buffer (process-buffer proc) (cond ((string= event "finished\n") ;; Successful exit. (goto-char (point-min)) (godoc-mode) (display-buffer (current-buffer) t)) ((/= (process-exit-status proc) 0) ;; Error exit. (let ((output (buffer-string))) (kill-buffer (current-buffer)) (message (concat "godoc: " output))))))) (define-derived-mode godoc-mode special-mode "Godoc" "Major mode for showing Go documentation." (view-mode-enter)) ;;;###autoload (defun godoc (query) "Show Go documentation for QUERY, much like \\\\[man]." (interactive (list (godoc--read-query))) (go--godoc query godoc-command)) (defun go--godoc (query command) (unless (string= query "") (set-process-sentinel (start-process-shell-command "godoc" (godoc--get-buffer query) (concat command " " query)) 'godoc--buffer-sentinel) nil)) (defun godoc-at-point (point) "Show Go documentation for the identifier at POINT. It uses `godoc-at-point-function' to look up the documentation." (interactive "d") (funcall godoc-at-point-function point)) (defun go-goto-imports () "Move point to the block of imports. If using import ( \"foo\" \"bar\" ) it will move point directly behind the last import. If using import \"foo\" import \"bar\" it will move point to the next line after the last import. If no imports can be found, point will be moved after the package declaration." (interactive) ;; FIXME if there's a block-commented import before the real ;; imports, we'll jump to that one. ;; Generally, this function isn't very forgiving. it'll bark on ;; extra whitespace. It works well for clean code. (let ((old-point (point))) (goto-char (point-min)) (cond ((re-search-forward "^import ()" nil t) (backward-char 1) 'block-empty) ((re-search-forward "^import ([^)]+)" nil t) (backward-char 2) 'block) ((re-search-forward "\\(^import \\([^\"]+ \\)?\"[^\"]+\"\n?\\)+" nil t) 'single) ((re-search-forward "^[[:space:]\n]*package .+?\n" nil t) (message "No imports found, moving point after package declaration") 'none) (t (goto-char old-point) (message "No imports or package declaration found. Is this really a Go file?") 'fail)))) (defun go-play-buffer () "Like `go-play-region', but acts on the entire buffer." (interactive) (go-play-region (point-min) (point-max))) (defun go-play-region (start end) "Send the region between START and END to the Playground. If non-nil `go-play-browse-function' is called with the Playground URL." (interactive "r") (let* ((url-request-method "POST") (url-request-extra-headers '(("Content-Type" . "application/x-www-form-urlencoded"))) (url-request-data (encode-coding-string (buffer-substring-no-properties start end) 'utf-8)) (content-buf (url-retrieve "https://play.golang.org/share" (lambda (arg) (cond ((equal :error (car arg)) (signal 'go-play-error (cdr arg))) (t (re-search-forward "\n\n") (let ((url (format "https://play.golang.org/p/%s" (buffer-substring (point) (point-max))))) (when go-play-browse-function (funcall go-play-browse-function url))))))))))) ;;;###autoload (defun go-download-play (url) "Download a paste from the playground and insert it in a Go buffer. Tries to look for a URL at point." (interactive (list (read-from-minibuffer "Playground URL: " (ffap-url-p (ffap-string-at-point 'url))))) (with-current-buffer (let ((url-request-method "GET") url-request-data url-request-extra-headers) (url-retrieve-synchronously (concat url ".go"))) (let ((buffer (generate-new-buffer (concat (car (last (split-string url "/"))) ".go")))) (goto-char (point-min)) (re-search-forward "\n\n") (copy-to-buffer buffer (point) (point-max)) (kill-buffer) (with-current-buffer buffer (go-mode) (switch-to-buffer buffer))))) (defun go-propertize-syntax (start end) (save-excursion (goto-char start) (while (search-forward "\\" end t) (put-text-property (1- (point)) (point) 'syntax-table (if (= (char-after) ?`) '(1) '(9)))))) (defun go-import-add (arg import) "Add a new IMPORT to the list of imports. When called with a prefix ARG asks for an alternative name to import the package as. If no list exists yet, one will be created if possible. If an identical import has been commented, it will be uncommented, otherwise a new import will be added." ;; - If there's a matching `// import "foo"`, uncomment it ;; - If we're in an import() block and there's a matching `"foo"`, uncomment it ;; - Otherwise add a new import, with the appropriate syntax (interactive (list current-prefix-arg (replace-regexp-in-string "^[\"']\\|[\"']$" "" (completing-read "Package: " (go-packages))))) (save-excursion (let (as line import-start) (if arg (setq as (read-from-minibuffer "Import as: "))) (if as (setq line (format "%s \"%s\"" as import)) (setq line (format "\"%s\"" import))) (goto-char (point-min)) (if (re-search-forward (concat "^[[:space:]]*//[[:space:]]*import " line "$") nil t) (uncomment-region (line-beginning-position) (line-end-position)) (cl-case (go-goto-imports) ('fail (message "Could not find a place to add import.")) ('block-empty (insert "\n\t" line "\n")) ('block (save-excursion (re-search-backward "^import (") (setq import-start (point))) (if (re-search-backward (concat "^[[:space:]]*//[[:space:]]*" line "$") import-start t) (uncomment-region (line-beginning-position) (line-end-position)) (insert "\n\t" line))) ('single (insert "import " line "\n")) ('none (insert "\nimport (\n\t" line "\n)\n"))))))) (defun go-root-and-paths () (let* ((output (process-lines go-command "env" "GOROOT" "GOPATH")) (root (car output)) (paths (split-string (cadr output) path-separator))) (cons root paths))) (defun go--string-prefix-p (s1 s2 &optional ignore-case) "Return non-nil if S1 is a prefix of S2. If IGNORE-CASE is non-nil, the comparison is case-insensitive." (eq t (compare-strings s1 nil nil s2 0 (length s1) ignore-case))) (defun go--directory-dirs (dir) "Recursively return all subdirectories in DIR." (if (file-directory-p dir) (let ((dir (directory-file-name dir)) (dirs '()) (files (directory-files dir nil nil t))) (dolist (file files) (unless (member file '("." "..")) (let ((file (concat dir "/" file))) (if (file-directory-p file) (setq dirs (append (cons file (go--directory-dirs file)) dirs)))))) dirs) '())) (defun go-packages () (funcall go-packages-function)) (defun go-packages-native () "Return a list of all installed Go packages. It looks for archive files in /pkg/." (sort (delete-dups (cl-mapcan (lambda (topdir) (let ((pkgdir (concat topdir "/pkg/"))) (cl-mapcan (lambda (dir) (mapcar (lambda (file) (let ((sub (substring file (length pkgdir) -2))) (unless (or (go--string-prefix-p "obj/" sub) (go--string-prefix-p "tool/" sub)) (mapconcat #'identity (cdr (split-string sub "/")) "/")))) (if (file-directory-p dir) (directory-files dir t "\\.a$")))) (if (file-directory-p pkgdir) (go--directory-dirs pkgdir))))) (go-root-and-paths))) #'string<)) (defun go-packages-go-list () "Return a list of all Go packages, using `go list'." (process-lines go-command "list" "-e" "all")) (defun go-unused-imports-lines () (reverse (remove nil (mapcar (lambda (line) (when (string-match "^\\(.+\\):\\([[:digit:]]+\\): imported and not used: \".+\".*$" line) (let ((error-file-name (match-string 1 line)) (error-line-num (match-string 2 line))) (if (string= (file-truename error-file-name) (file-truename buffer-file-name)) (string-to-number error-line-num))))) (split-string (shell-command-to-string (concat go-command (if (string-match "_test\\.go$" buffer-file-truename) " test -c" (concat " build -o " null-device)) " -gcflags=-e" " " (shell-quote-argument (file-truename buffer-file-name)))) "\n"))))) (defun go-remove-unused-imports (arg) "Remove all unused imports. If ARG is non-nil, unused imports will be commented, otherwise they will be removed completely." (interactive "P") (save-excursion (let ((cur-buffer (current-buffer)) flymake-state lines) (when (boundp 'flymake-mode) (setq flymake-state flymake-mode) (flymake-mode-off)) (save-some-buffers nil (lambda () (equal cur-buffer (current-buffer)))) (if (buffer-modified-p) (message "Cannot operate on unsaved buffer") (setq lines (go-unused-imports-lines)) (dolist (import lines) (go--goto-line import) (beginning-of-line) (if arg (comment-region (line-beginning-position) (line-end-position)) (go--delete-whole-line))) (message "Removed %d imports" (length lines))) (if flymake-state (flymake-mode-on))))) (defun godef--find-file-line-column (specifier other-window) "Given a file name in the format of `filename:line:column', visit FILENAME and go to line LINE and column COLUMN." (if (not (string-match "\\(.+\\):\\([0-9]+\\):\\([0-9]+\\)" specifier)) ;; We've only been given a directory name (funcall (if other-window #'find-file-other-window #'find-file) specifier) (let ((filename (match-string 1 specifier)) (line (string-to-number (match-string 2 specifier))) (column (string-to-number (match-string 3 specifier)))) (funcall (if other-window #'find-file-other-window #'find-file) filename) (go--goto-line line) (beginning-of-line) (forward-char (1- column)) (if (buffer-modified-p) (message "Buffer is modified, file position might not have been correct"))))) (defun godef--call (point) "Call godef, acquiring definition position and expression description at POINT." (if (not (buffer-file-name (go--coverage-origin-buffer))) (error "Cannot use godef on a buffer without a file name") (let ((outbuf (generate-new-buffer "*godef*")) (coding-system-for-read 'utf-8) (coding-system-for-write 'utf-8)) (prog2 (call-process-region (point-min) (point-max) godef-command nil outbuf nil "-i" "-t" "-f" (file-truename (buffer-file-name (go--coverage-origin-buffer))) "-o" (number-to-string (position-bytes point))) (with-current-buffer outbuf (split-string (buffer-substring-no-properties (point-min) (point-max)) "\n")) (kill-buffer outbuf))))) (defun godef--successful-p (output) (not (or (string= "-" output) (string= "godef: no identifier found" output) (go--string-prefix-p "godef: no declaration found for " output) (go--string-prefix-p "error finding import path for " output)))) (defun godef--error (output) (cond ((godef--successful-p output) nil) ((string= "-" output) "godef: expression is not defined anywhere") (t output))) (defun godef-describe (point) "Describe the expression at POINT." (interactive "d") (condition-case nil (let ((description (cdr (butlast (godef--call point) 1)))) (if (not description) (message "No description found for expression at point") (message "%s" (mapconcat #'identity description "\n")))) (file-error (message "Could not run godef binary")))) (defun godef-jump (point &optional other-window) "Jump to the definition of the expression at POINT." (interactive "d") (condition-case nil (let ((file (car (godef--call point)))) (if (not (godef--successful-p file)) (message "%s" (godef--error file)) (push-mark) (if (eval-when-compile (fboundp 'xref-push-marker-stack)) ;; TODO: Integrate this facility with XRef. (xref-push-marker-stack) (ring-insert find-tag-marker-ring (point-marker))) (godef--find-file-line-column file other-window))) (file-error (message "Could not run godef binary")))) (defun godef-jump-other-window (point) (interactive "d") (godef-jump point t)) (defun go--goto-line (line) (goto-char (point-min)) (forward-line (1- line))) (defun go--line-column-to-point (line column) (save-excursion (go--goto-line line) (forward-char (1- column)) (point))) (cl-defstruct go--covered start-line start-column end-line end-column covered count) (defun go--coverage-file () "Return the coverage file to use, either by reading it from the current coverage buffer or by prompting for it." (if (boundp 'go--coverage-current-file-name) go--coverage-current-file-name (read-file-name "Coverage file: " nil nil t))) (defun go--coverage-origin-buffer () "Return the buffer to base the coverage on." (or (buffer-base-buffer) (current-buffer))) (defun go--coverage-face (count divisor) "Return the intensity face for COUNT when using DIVISOR to scale it to a range [0,10]. DIVISOR scales the absolute cover count to values from 0 to 10. For DIVISOR = 0 the count will always translate to 8." (let* ((norm (cond ((= count 0) -0.1) ;; Uncovered code, set to -0.1 so n becomes 0. ((= divisor 0) 0.8) ;; covermode=set, set to 0.8 so n becomes 8. (t (/ (log count) divisor)))) (n (1+ (floor (* norm 9))))) ;; Convert normalized count [0,1] to intensity [0,10] (concat "go-coverage-" (number-to-string n)))) (defun go--coverage-make-overlay (range divisor) "Create a coverage overlay for a RANGE of covered/uncovered code. Use DIVISOR to scale absolute counts to a [0,10] scale." (let* ((count (go--covered-count range)) (face (go--coverage-face count divisor)) (ov (make-overlay (go--line-column-to-point (go--covered-start-line range) (go--covered-start-column range)) (go--line-column-to-point (go--covered-end-line range) (go--covered-end-column range))))) (overlay-put ov 'face face) (overlay-put ov 'help-echo (format "Count: %d" count)))) (defun go--coverage-clear-overlays () "Remove existing overlays and put a single untracked overlay over the entire buffer." (remove-overlays) (overlay-put (make-overlay (point-min) (point-max)) 'face 'go-coverage-untracked)) (defun go--coverage-parse-file (coverage-file file-name) "Parse COVERAGE-FILE and extract coverage information and divisor for FILE-NAME." (let (ranges (max-count 0)) (with-temp-buffer (insert-file-contents coverage-file) (go--goto-line 2) ;; Skip over mode (while (not (eobp)) (let* ((parts (split-string (buffer-substring (point-at-bol) (point-at-eol)) ":")) (file (car parts)) (rest (split-string (nth 1 parts) "[., ]"))) (cl-destructuring-bind (start-line start-column end-line end-column num count) (mapcar #'string-to-number rest) (when (string= (file-name-nondirectory file) file-name) (if (> count max-count) (setq max-count count)) (push (make-go--covered :start-line start-line :start-column start-column :end-line end-line :end-column end-column :covered (/= count 0) :count count) ranges))) (forward-line))) (list ranges (if (> max-count 0) (log max-count) 0))))) (defun go-coverage (&optional coverage-file) "Open a clone of the current buffer and overlay it with coverage information gathered via go test -coverprofile=COVERAGE-FILE. If COVERAGE-FILE is nil, it will either be inferred from the current buffer if it's already a coverage buffer, or be prompted for." (interactive) (let* ((cur-buffer (current-buffer)) (origin-buffer (go--coverage-origin-buffer)) (gocov-buffer-name (concat (buffer-name origin-buffer) "")) (coverage-file (or coverage-file (go--coverage-file))) (ranges-and-divisor (go--coverage-parse-file coverage-file (file-name-nondirectory (buffer-file-name origin-buffer)))) (cov-mtime (nth 5 (file-attributes coverage-file))) (cur-mtime (nth 5 (file-attributes (buffer-file-name origin-buffer))))) (if (< (float-time cov-mtime) (float-time cur-mtime)) (message "Coverage file is older than the source file.")) (with-current-buffer (or (get-buffer gocov-buffer-name) (make-indirect-buffer origin-buffer gocov-buffer-name t)) (set (make-local-variable 'go--coverage-current-file-name) coverage-file) (save-excursion (go--coverage-clear-overlays) (dolist (range (car ranges-and-divisor)) (go--coverage-make-overlay range (cadr ranges-and-divisor)))) (if (not (eq cur-buffer (current-buffer))) (display-buffer (current-buffer) `(,go-coverage-display-buffer-func)))))) (defun go-goto-function (&optional arg) "Go to the function defintion (named or anonymous) surrounding point. If we are on a docstring, follow the docstring down. If no function is found, assume that we are at the top of a file and search forward instead. If point is looking at the func keyword of an anonymous function, go to the surrounding function. If ARG is non-nil, anonymous functions are ignored." (interactive "P") (let ((p (point))) (cond ((save-excursion (beginning-of-line) (looking-at "^//")) ;; In case we are looking at the docstring, move on forward until we are ;; not anymore (beginning-of-line) (while (looking-at "^//") (forward-line 1)) ;; If we are still not looking at a function, retry by calling self again. (when (not (looking-at "\\")) (go-goto-function arg))) ;; If we're already looking at an anonymous func, look for the ;; surrounding function. ((and (looking-at "\\") (not (looking-at "^func\\>"))) (re-search-backward "\\" nil t)) ((not (looking-at "\\")) ;; If point is on the "func" keyword, step back a word and retry (if (string= (symbol-name (symbol-at-point)) "func") (backward-word) ;; If we are not looking at the beginning of a function line, do a regexp ;; search backwards (re-search-backward "\\" nil t)) ;; If nothing is found, assume that we are at the top of the file and ;; should search forward instead. (when (not (looking-at "\\")) (re-search-forward "\\" nil t) (go--forward-word -1)) ;; If we have landed at an anonymous function, it is possible that we ;; were not inside it but below it. If we were not inside it, we should ;; go to the containing function. (while (and (not (go--in-function-p p)) (not (looking-at "^func\\>"))) (go-goto-function arg))))) (cond ((go-in-comment-p) ;; If we are still in a comment, redo the call so that we get out of it. (go-goto-function arg)) ((and (looking-at "\\")) (go-goto-function)) (let ((start (point))) (go--goto-opening-curly-brace) (unless (looking-at "{") (error "Expected to be looking at opening curly brace")) (forward-list 1) (and (>= compare-point start) (<= compare-point (point)))))) (defun go-goto-function-name (&optional arg) "Go to the name of the current function. If the function is a test, place point after 'Test'. If the function is anonymous, place point on the 'func' keyword. If ARG is non-nil, anonymous functions are skipped." (interactive "P") (when (not (looking-at "\\")) (go-goto-function arg)) ;; If we are looking at func( we are on an anonymous function and ;; nothing else should be done. (when (not (looking-at "\\