github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/misc/emacs/go-mode.el (about)

     1  ;;; go-mode.el --- Major mode for the Go programming language
     2  
     3  ;; Copyright 2013 The Go Authors. All rights reserved.
     4  ;; Use of this source code is governed by a BSD-style
     5  ;; license that can be found in the LICENSE file.
     6  
     7  (require 'cl)
     8  (require 'etags)
     9  (require 'ffap)
    10  (require 'ring)
    11  (require 'url)
    12  
    13  ;; XEmacs compatibility guidelines
    14  ;; - Minimum required version of XEmacs: 21.5.32
    15  ;;   - Feature that cannot be backported: POSIX character classes in
    16  ;;     regular expressions
    17  ;;   - Functions that could be backported but won't because 21.5.32
    18  ;;     covers them: plenty.
    19  ;;   - Features that are still partly broken:
    20  ;;     - godef will not work correctly if multibyte characters are
    21  ;;       being used
    22  ;;     - Fontification will not handle unicode correctly
    23  ;;
    24  ;; - Do not use \_< and \_> regexp delimiters directly; use
    25  ;;   go--regexp-enclose-in-symbol
    26  ;;
    27  ;; - The character `_` must not be a symbol constituent but a
    28  ;;   character constituent
    29  ;;
    30  ;; - Do not use process-lines
    31  ;;
    32  ;; - Use go--old-completion-list-style when using a plain list as the
    33  ;;   collection for completing-read
    34  ;;
    35  ;; - Use go--kill-whole-line instead of kill-whole-line (called
    36  ;;   kill-entire-line in XEmacs)
    37  ;;
    38  ;; - Use go--position-bytes instead of position-bytes
    39  (defmacro go--xemacs-p ()
    40    `(featurep 'xemacs))
    41  
    42  (defalias 'go--kill-whole-line
    43    (if (fboundp 'kill-whole-line)
    44        #'kill-whole-line
    45      #'kill-entire-line))
    46  
    47  ;; Delete the current line without putting it in the kill-ring.
    48  (defun go--delete-whole-line (&optional arg)
    49    ;; Emacs uses both kill-region and kill-new, Xemacs only uses
    50    ;; kill-region. In both cases we turn them into operations that do
    51    ;; not modify the kill ring. This solution does depend on the
    52    ;; implementation of kill-line, but it's the only viable solution
    53    ;; that does not require to write kill-line from scratch.
    54    (flet ((kill-region (beg end)
    55                        (delete-region beg end))
    56           (kill-new (s) ()))
    57      (go--kill-whole-line arg)))
    58  
    59  ;; declare-function is an empty macro that only byte-compile cares
    60  ;; about. Wrap in always false if to satisfy Emacsen without that
    61  ;; macro.
    62  (if nil
    63      (declare-function go--position-bytes "go-mode" (point)))
    64  ;; XEmacs unfortunately does not offer position-bytes. We can fall
    65  ;; back to just using (point), but it will be incorrect as soon as
    66  ;; multibyte characters are being used.
    67  (if (fboundp 'position-bytes)
    68      (defalias 'go--position-bytes #'position-bytes)
    69    (defun go--position-bytes (point) point))
    70  
    71  (defun go--old-completion-list-style (list)
    72    (mapcar (lambda (x) (cons x nil)) list))
    73  
    74  ;; GNU Emacs 24 has prog-mode, older GNU Emacs and XEmacs do not, so
    75  ;; copy its definition for those.
    76  (if (not (fboundp 'prog-mode))
    77      (define-derived-mode prog-mode fundamental-mode "Prog"
    78        "Major mode for editing source code."
    79        (set (make-local-variable 'require-final-newline) mode-require-final-newline)
    80        (set (make-local-variable 'parse-sexp-ignore-comments) t)
    81        (setq bidi-paragraph-direction 'left-to-right)))
    82  
    83  (defun go--regexp-enclose-in-symbol (s)
    84    ;; XEmacs does not support \_<, GNU Emacs does. In GNU Emacs we make
    85    ;; extensive use of \_< to support unicode in identifiers. Until we
    86    ;; come up with a better solution for XEmacs, this solution will
    87    ;; break fontification in XEmacs for identifiers such as "typeµ".
    88    ;; XEmacs will consider "type" a keyword, GNU Emacs won't.
    89  
    90    (if (go--xemacs-p)
    91        (concat "\\<" s "\\>")
    92      (concat "\\_<" s "\\_>")))
    93  
    94  ;; Move up one level of parentheses.
    95  (defun go-goto-opening-parenthesis (&optional legacy-unused)
    96    ;; The old implementation of go-goto-opening-parenthesis had an
    97    ;; optional argument to speed up the function. It didn't change the
    98    ;; function's outcome.
    99  
   100    ;; Silently fail if there's no matching opening parenthesis.
   101    (condition-case nil
   102        (backward-up-list)
   103      (scan-error nil)))
   104  
   105  
   106  (defconst go-dangling-operators-regexp "[^-]-\\|[^+]\\+\\|[/*&><.=|^]")
   107  (defconst go-identifier-regexp "[[:word:][:multibyte:]]+")
   108  (defconst go-label-regexp go-identifier-regexp)
   109  (defconst go-type-regexp "[[:word:][:multibyte:]*]+")
   110  (defconst go-func-regexp (concat (go--regexp-enclose-in-symbol "func") "\\s *\\(" go-identifier-regexp "\\)"))
   111  (defconst go-func-meth-regexp (concat
   112                                 (go--regexp-enclose-in-symbol "func") "\\s *\\(?:(\\s *"
   113                                 "\\(" go-identifier-regexp "\\s +\\)?" go-type-regexp
   114                                 "\\s *)\\s *\\)?\\("
   115                                 go-identifier-regexp
   116                                 "\\)("))
   117  (defconst go-builtins
   118    '("append" "cap"   "close"   "complex" "copy"
   119      "delete" "imag"  "len"     "make"    "new"
   120      "panic"  "print" "println" "real"    "recover")
   121    "All built-in functions in the Go language. Used for font locking.")
   122  
   123  (defconst go-mode-keywords
   124    '("break"    "default"     "func"   "interface" "select"
   125      "case"     "defer"       "go"     "map"       "struct"
   126      "chan"     "else"        "goto"   "package"   "switch"
   127      "const"    "fallthrough" "if"     "range"     "type"
   128      "continue" "for"         "import" "return"    "var")
   129    "All keywords in the Go language.  Used for font locking.")
   130  
   131  (defconst go-constants '("nil" "true" "false" "iota"))
   132  (defconst go-type-name-regexp (concat "\\(?:[*(]\\)*\\(?:" go-identifier-regexp "\\.\\)?\\(" go-identifier-regexp "\\)"))
   133  
   134  (defvar go-dangling-cache)
   135  (defvar go-godoc-history nil)
   136  (defvar go--coverage-current-file-name)
   137  
   138  (defgroup go nil
   139    "Major mode for editing Go code"
   140    :group 'languages)
   141  
   142  (defgroup go-cover nil
   143    "Options specific to `cover`"
   144    :group 'go)
   145  
   146  (defcustom go-fontify-function-calls t
   147    "Fontify function and method calls if this is non-nil."
   148    :type 'boolean
   149    :group 'go)
   150  
   151  (defcustom go-mode-hook nil
   152    "Hook called by `go-mode'."
   153    :type 'hook
   154    :group 'go)
   155  
   156  (defcustom go-command "go"
   157    "The 'go' command.  Some users have multiple Go development
   158  trees and invoke the 'go' tool via a wrapper that sets GOROOT and
   159  GOPATH based on the current directory.  Such users should
   160  customize this variable to point to the wrapper script."
   161    :type 'string
   162    :group 'go)
   163  
   164  (defcustom gofmt-command "gofmt"
   165    "The 'gofmt' command.  Some users may replace this with 'goimports'
   166  from https://github.com/bradfitz/goimports."
   167    :type 'string
   168    :group 'go)
   169  
   170  (defface go-coverage-untracked
   171    '((t (:foreground "#505050")))
   172    "Coverage color of untracked code."
   173    :group 'go-cover)
   174  
   175  (defface go-coverage-0
   176    '((t (:foreground "#c00000")))
   177    "Coverage color for uncovered code."
   178    :group 'go-cover)
   179  (defface go-coverage-1
   180    '((t (:foreground "#808080")))
   181    "Coverage color for covered code with weight 1."
   182    :group 'go-cover)
   183  (defface go-coverage-2
   184    '((t (:foreground "#748c83")))
   185    "Coverage color for covered code with weight 2."
   186    :group 'go-cover)
   187  (defface go-coverage-3
   188    '((t (:foreground "#689886")))
   189    "Coverage color for covered code with weight 3."
   190    :group 'go-cover)
   191  (defface go-coverage-4
   192    '((t (:foreground "#5ca489")))
   193    "Coverage color for covered code with weight 4."
   194    :group 'go-cover)
   195  (defface go-coverage-5
   196    '((t (:foreground "#50b08c")))
   197    "Coverage color for covered code with weight 5."
   198    :group 'go-cover)
   199  (defface go-coverage-6
   200    '((t (:foreground "#44bc8f")))
   201    "Coverage color for covered code with weight 6."
   202    :group 'go-cover)
   203  (defface go-coverage-7
   204    '((t (:foreground "#38c892")))
   205    "Coverage color for covered code with weight 7."
   206    :group 'go-cover)
   207  (defface go-coverage-8
   208    '((t (:foreground "#2cd495")))
   209    "Coverage color for covered code with weight 8.
   210  For mode=set, all covered lines will have this weight."
   211    :group 'go-cover)
   212  (defface go-coverage-9
   213    '((t (:foreground "#20e098")))
   214    "Coverage color for covered code with weight 9."
   215    :group 'go-cover)
   216  (defface go-coverage-10
   217    '((t (:foreground "#14ec9b")))
   218    "Coverage color for covered code with weight 10."
   219    :group 'go-cover)
   220  (defface go-coverage-covered
   221    '((t (:foreground "#2cd495")))
   222    "Coverage color of covered code."
   223    :group 'go-cover)
   224  
   225  (defvar go-mode-syntax-table
   226    (let ((st (make-syntax-table)))
   227      (modify-syntax-entry ?+  "." st)
   228      (modify-syntax-entry ?-  "." st)
   229      (modify-syntax-entry ?%  "." st)
   230      (modify-syntax-entry ?&  "." st)
   231      (modify-syntax-entry ?|  "." st)
   232      (modify-syntax-entry ?^  "." st)
   233      (modify-syntax-entry ?!  "." st)
   234      (modify-syntax-entry ?=  "." st)
   235      (modify-syntax-entry ?<  "." st)
   236      (modify-syntax-entry ?>  "." st)
   237      (modify-syntax-entry ?/ (if (go--xemacs-p) ". 1456" ". 124b") st)
   238      (modify-syntax-entry ?*  ". 23" st)
   239      (modify-syntax-entry ?\n "> b" st)
   240      (modify-syntax-entry ?\" "\"" st)
   241      (modify-syntax-entry ?\' "\"" st)
   242      (modify-syntax-entry ?`  "\"" st)
   243      (modify-syntax-entry ?\\ "\\" st)
   244      ;; It would be nicer to have _ as a symbol constituent, but that
   245      ;; would trip up XEmacs, which does not support the \_< anchor
   246      (modify-syntax-entry ?_  "w" st)
   247  
   248      st)
   249    "Syntax table for Go mode.")
   250  
   251  (defun go--build-font-lock-keywords ()
   252    ;; we cannot use 'symbols in regexp-opt because emacs <24 doesn't
   253    ;; understand that
   254    (append
   255     `((,(go--regexp-enclose-in-symbol (regexp-opt go-mode-keywords t)) . font-lock-keyword-face)
   256       (,(go--regexp-enclose-in-symbol (regexp-opt go-builtins t)) . font-lock-builtin-face)
   257       (,(go--regexp-enclose-in-symbol (regexp-opt go-constants t)) . font-lock-constant-face)
   258       (,go-func-regexp 1 font-lock-function-name-face)) ;; function (not method) name
   259  
   260     (if go-fontify-function-calls
   261         `((,(concat "\\(" go-identifier-regexp "\\)[[:space:]]*(") 1 font-lock-function-name-face) ;; function call/method name
   262           (,(concat "[^[:word:][:multibyte:]](\\(" go-identifier-regexp "\\))[[:space:]]*(") 1 font-lock-function-name-face)) ;; bracketed function call
   263       `((,go-func-meth-regexp 1 font-lock-function-name-face))) ;; method name
   264  
   265     `(
   266       (,(concat (go--regexp-enclose-in-symbol "type") "[[:space:]]*\\([^[:space:]]+\\)") 1 font-lock-type-face) ;; types
   267       (,(concat (go--regexp-enclose-in-symbol "type") "[[:space:]]*" go-identifier-regexp "[[:space:]]*" go-type-name-regexp) 1 font-lock-type-face) ;; types
   268       (,(concat "[^[:word:][:multibyte:]]\\[\\([[:digit:]]+\\|\\.\\.\\.\\)?\\]" go-type-name-regexp) 2 font-lock-type-face) ;; Arrays/slices
   269       (,(concat "\\(" go-identifier-regexp "\\)" "{") 1 font-lock-type-face)
   270       (,(concat (go--regexp-enclose-in-symbol "map") "\\[[^]]+\\]" go-type-name-regexp) 1 font-lock-type-face) ;; map value type
   271       (,(concat (go--regexp-enclose-in-symbol "map") "\\[" go-type-name-regexp) 1 font-lock-type-face) ;; map key type
   272       (,(concat (go--regexp-enclose-in-symbol "chan") "[[:space:]]*\\(?:<-\\)?" go-type-name-regexp) 1 font-lock-type-face) ;; channel type
   273       (,(concat (go--regexp-enclose-in-symbol "\\(?:new\\|make\\)") "\\(?:[[:space:]]\\|)\\)*(" go-type-name-regexp) 1 font-lock-type-face) ;; new/make type
   274       ;; TODO do we actually need this one or isn't it just a function call?
   275       (,(concat "\\.\\s *(" go-type-name-regexp) 1 font-lock-type-face) ;; Type conversion
   276       (,(concat (go--regexp-enclose-in-symbol "func") "[[:space:]]+(" go-identifier-regexp "[[:space:]]+" go-type-name-regexp ")") 1 font-lock-type-face) ;; Method receiver
   277       (,(concat (go--regexp-enclose-in-symbol "func") "[[:space:]]+(" go-type-name-regexp ")") 1 font-lock-type-face) ;; Method receiver without variable name
   278       ;; Like the original go-mode this also marks compound literal
   279       ;; fields. There, it was marked as to fix, but I grew quite
   280       ;; accustomed to it, so it'll stay for now.
   281       (,(concat "^[[:space:]]*\\(" go-label-regexp "\\)[[:space:]]*:\\(\\S.\\|$\\)") 1 font-lock-constant-face) ;; Labels and compound literal fields
   282       (,(concat (go--regexp-enclose-in-symbol "\\(goto\\|break\\|continue\\)") "[[:space:]]*\\(" go-label-regexp "\\)") 2 font-lock-constant-face)))) ;; labels in goto/break/continue
   283  
   284  (defvar go-mode-map
   285    (let ((m (make-sparse-keymap)))
   286      (define-key m "}" #'go-mode-insert-and-indent)
   287      (define-key m ")" #'go-mode-insert-and-indent)
   288      (define-key m "," #'go-mode-insert-and-indent)
   289      (define-key m ":" #'go-mode-insert-and-indent)
   290      (define-key m "=" #'go-mode-insert-and-indent)
   291      (define-key m (kbd "C-c C-a") #'go-import-add)
   292      (define-key m (kbd "C-c C-j") #'godef-jump)
   293      (define-key m (kbd "C-x 4 C-c C-j") #'godef-jump-other-window)
   294      (define-key m (kbd "C-c C-d") #'godef-describe)
   295      m)
   296    "Keymap used by Go mode to implement electric keys.")
   297  
   298  (defun go-mode-insert-and-indent (key)
   299    "Invoke the global binding of KEY, then reindent the line."
   300  
   301    (interactive (list (this-command-keys)))
   302    (call-interactively (lookup-key (current-global-map) key))
   303    (indent-according-to-mode))
   304  
   305  (defmacro go-paren-level ()
   306    `(car (syntax-ppss)))
   307  
   308  (defmacro go-in-string-or-comment-p ()
   309    `(nth 8 (syntax-ppss)))
   310  
   311  (defmacro go-in-string-p ()
   312    `(nth 3 (syntax-ppss)))
   313  
   314  (defmacro go-in-comment-p ()
   315    `(nth 4 (syntax-ppss)))
   316  
   317  (defmacro go-goto-beginning-of-string-or-comment ()
   318    `(goto-char (nth 8 (syntax-ppss))))
   319  
   320  (defun go--backward-irrelevant (&optional stop-at-string)
   321    "Skips backwards over any characters that are irrelevant for
   322  indentation and related tasks.
   323  
   324  It skips over whitespace, comments, cases and labels and, if
   325  STOP-AT-STRING is not true, over strings."
   326  
   327    (let (pos (start-pos (point)))
   328      (skip-chars-backward "\n\s\t")
   329      (if (and (save-excursion (beginning-of-line) (go-in-string-p)) (looking-back "`") (not stop-at-string))
   330          (backward-char))
   331      (if (and (go-in-string-p) (not stop-at-string))
   332          (go-goto-beginning-of-string-or-comment))
   333      (if (looking-back "\\*/")
   334          (backward-char))
   335      (if (go-in-comment-p)
   336          (go-goto-beginning-of-string-or-comment))
   337      (setq pos (point))
   338      (beginning-of-line)
   339      (if (or (looking-at (concat "^" go-label-regexp ":")) (looking-at "^[[:space:]]*\\(case .+\\|default\\):"))
   340          (end-of-line 0)
   341        (goto-char pos))
   342      (if (/= start-pos (point))
   343          (go--backward-irrelevant stop-at-string))
   344      (/= start-pos (point))))
   345  
   346  (defun go--buffer-narrowed-p ()
   347    "Return non-nil if the current buffer is narrowed."
   348    (/= (buffer-size)
   349        (- (point-max)
   350           (point-min))))
   351  
   352  (defun go-previous-line-has-dangling-op-p ()
   353    "Returns non-nil if the current line is a continuation line."
   354    (let* ((cur-line (line-number-at-pos))
   355           (val (gethash cur-line go-dangling-cache 'nope)))
   356      (if (or (go--buffer-narrowed-p) (equal val 'nope))
   357          (save-excursion
   358            (beginning-of-line)
   359            (go--backward-irrelevant t)
   360            (setq val (looking-back go-dangling-operators-regexp))
   361            (if (not (go--buffer-narrowed-p))
   362                (puthash cur-line val go-dangling-cache))))
   363      val))
   364  
   365  (defun go--at-function-definition ()
   366    "Return non-nil if point is on the opening curly brace of a
   367  function definition.
   368  
   369  We do this by first calling (beginning-of-defun), which will take
   370  us to the start of *some* function. We then look for the opening
   371  curly brace of that function and compare its position against the
   372  curly brace we are checking. If they match, we return non-nil."
   373    (if (= (char-after) ?\{)
   374        (save-excursion
   375          (let ((old-point (point))
   376                start-nesting)
   377            (beginning-of-defun)
   378            (when (looking-at "func ")
   379              (setq start-nesting (go-paren-level))
   380              (skip-chars-forward "^{")
   381              (while (> (go-paren-level) start-nesting)
   382                (forward-char)
   383                (skip-chars-forward "^{") 0)
   384              (if (and (= (go-paren-level) start-nesting) (= old-point (point)))
   385                  t))))))
   386  
   387  (defun go--indentation-for-opening-parenthesis ()
   388    "Return the semantic indentation for the current opening parenthesis.
   389  
   390  If point is on an opening curly brace and said curly brace
   391  belongs to a function declaration, the indentation of the func
   392  keyword will be returned. Otherwise the indentation of the
   393  current line will be returned."
   394    (save-excursion
   395      (if (go--at-function-definition)
   396          (progn
   397            (beginning-of-defun)
   398            (current-indentation))
   399        (current-indentation))))
   400  
   401  (defun go-indentation-at-point ()
   402    (save-excursion
   403      (let (start-nesting)
   404        (back-to-indentation)
   405        (setq start-nesting (go-paren-level))
   406  
   407        (cond
   408         ((go-in-string-p)
   409          (current-indentation))
   410         ((looking-at "[])}]")
   411          (go-goto-opening-parenthesis)
   412          (if (go-previous-line-has-dangling-op-p)
   413              (- (current-indentation) tab-width)
   414            (go--indentation-for-opening-parenthesis)))
   415         ((progn (go--backward-irrelevant t) (looking-back go-dangling-operators-regexp))
   416          ;; only one nesting for all dangling operators in one operation
   417          (if (go-previous-line-has-dangling-op-p)
   418              (current-indentation)
   419            (+ (current-indentation) tab-width)))
   420         ((zerop (go-paren-level))
   421          0)
   422         ((progn (go-goto-opening-parenthesis) (< (go-paren-level) start-nesting))
   423          (if (go-previous-line-has-dangling-op-p)
   424              (current-indentation)
   425            (+ (go--indentation-for-opening-parenthesis) tab-width)))
   426         (t
   427          (current-indentation))))))
   428  
   429  (defun go-mode-indent-line ()
   430    (interactive)
   431    (let (indent
   432          shift-amt
   433          (pos (- (point-max) (point)))
   434          (point (point))
   435          (beg (line-beginning-position)))
   436      (back-to-indentation)
   437      (if (go-in-string-or-comment-p)
   438          (goto-char point)
   439        (setq indent (go-indentation-at-point))
   440        (if (looking-at (concat go-label-regexp ":\\([[:space:]]*/.+\\)?$\\|case .+:\\|default:"))
   441            (decf indent tab-width))
   442        (setq shift-amt (- indent (current-column)))
   443        (if (zerop shift-amt)
   444            nil
   445          (delete-region beg (point))
   446          (indent-to indent))
   447        ;; If initial point was within line's indentation,
   448        ;; position after the indentation.  Else stay at same point in text.
   449        (if (> (- (point-max) pos) (point))
   450            (goto-char (- (point-max) pos))))))
   451  
   452  (defun go-beginning-of-defun (&optional count)
   453    (unless count (setq count 1))
   454    (let ((first t) failure)
   455      (dotimes (i (abs count))
   456        (while (and (not failure)
   457                    (or first (go-in-string-or-comment-p)))
   458          (if (>= count 0)
   459              (progn
   460                (go--backward-irrelevant)
   461                (if (not (re-search-backward go-func-meth-regexp nil t))
   462                    (setq failure t)))
   463            (if (looking-at go-func-meth-regexp)
   464                (forward-char))
   465            (if (not (re-search-forward go-func-meth-regexp nil t))
   466                (setq failure t)))
   467          (setq first nil)))
   468      (if (< count 0)
   469          (beginning-of-line))
   470      (not failure)))
   471  
   472  (defun go-end-of-defun ()
   473    (let (orig-level)
   474      ;; It can happen that we're not placed before a function by emacs
   475      (if (not (looking-at "func"))
   476          (go-beginning-of-defun -1))
   477      (skip-chars-forward "^{")
   478      (forward-char)
   479      (setq orig-level (go-paren-level))
   480      (while (>= (go-paren-level) orig-level)
   481        (skip-chars-forward "^}")
   482        (forward-char))))
   483  
   484  ;;;###autoload
   485  (define-derived-mode go-mode prog-mode "Go"
   486    "Major mode for editing Go source text.
   487  
   488  This mode provides (not just) basic editing capabilities for
   489  working with Go code. It offers almost complete syntax
   490  highlighting, indentation that is almost identical to gofmt and
   491  proper parsing of the buffer content to allow features such as
   492  navigation by function, manipulation of comments or detection of
   493  strings.
   494  
   495  In addition to these core features, it offers various features to
   496  help with writing Go code. You can directly run buffer content
   497  through gofmt, read godoc documentation from within Emacs, modify
   498  and clean up the list of package imports or interact with the
   499  Playground (uploading and downloading pastes).
   500  
   501  The following extra functions are defined:
   502  
   503  - `gofmt'
   504  - `godoc'
   505  - `go-import-add'
   506  - `go-remove-unused-imports'
   507  - `go-goto-imports'
   508  - `go-play-buffer' and `go-play-region'
   509  - `go-download-play'
   510  - `godef-describe' and `godef-jump'
   511  - `go-coverage'
   512  
   513  If you want to automatically run `gofmt' before saving a file,
   514  add the following hook to your emacs configuration:
   515  
   516  \(add-hook 'before-save-hook 'gofmt-before-save)
   517  
   518  If you want to use `godef-jump' instead of etags (or similar),
   519  consider binding godef-jump to `M-.', which is the default key
   520  for `find-tag':
   521  
   522  \(add-hook 'go-mode-hook (lambda ()
   523                            (local-set-key (kbd \"M-.\") #'godef-jump)))
   524  
   525  Please note that godef is an external dependency. You can install
   526  it with
   527  
   528  go get code.google.com/p/rog-go/exp/cmd/godef
   529  
   530  
   531  If you're looking for even more integration with Go, namely
   532  on-the-fly syntax checking, auto-completion and snippets, it is
   533  recommended that you look at goflymake
   534  \(https://github.com/dougm/goflymake), gocode
   535  \(https://github.com/nsf/gocode) and yasnippet-go
   536  \(https://github.com/dominikh/yasnippet-go)"
   537  
   538    ;; Font lock
   539    (set (make-local-variable 'font-lock-defaults)
   540         '(go--build-font-lock-keywords))
   541  
   542    ;; Indentation
   543    (set (make-local-variable 'indent-line-function) #'go-mode-indent-line)
   544  
   545    ;; Comments
   546    (set (make-local-variable 'comment-start) "// ")
   547    (set (make-local-variable 'comment-end)   "")
   548    (set (make-local-variable 'comment-use-syntax) t)
   549    (set (make-local-variable 'comment-start-skip) "\\(//+\\|/\\*+\\)\\s *")
   550  
   551    (set (make-local-variable 'beginning-of-defun-function) #'go-beginning-of-defun)
   552    (set (make-local-variable 'end-of-defun-function) #'go-end-of-defun)
   553  
   554    (set (make-local-variable 'parse-sexp-lookup-properties) t)
   555    (if (boundp 'syntax-propertize-function)
   556        (set (make-local-variable 'syntax-propertize-function) #'go-propertize-syntax))
   557  
   558    (set (make-local-variable 'go-dangling-cache) (make-hash-table :test 'eql))
   559    (add-hook 'before-change-functions (lambda (x y) (setq go-dangling-cache (make-hash-table :test 'eql))) t t)
   560  
   561  
   562    (setq imenu-generic-expression
   563          '(("type" "^type *\\([^ \t\n\r\f]*\\)" 1)
   564            ("func" "^func *\\(.*\\) {" 1)))
   565    (imenu-add-to-menubar "Index")
   566  
   567    ;; Go style
   568    (setq indent-tabs-mode t)
   569  
   570    ;; Handle unit test failure output in compilation-mode
   571    ;;
   572    ;; Note the final t argument to add-to-list for append, ie put these at the
   573    ;; *ends* of compilation-error-regexp-alist[-alist]. We want go-test to be
   574    ;; handled first, otherwise other elements will match that don't work, and
   575    ;; those alists are traversed in *reverse* order:
   576    ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2001-12/msg00674.html
   577    (when (and (boundp 'compilation-error-regexp-alist)
   578               (boundp 'compilation-error-regexp-alist-alist))
   579      (add-to-list 'compilation-error-regexp-alist 'go-test t)
   580      (add-to-list 'compilation-error-regexp-alist-alist
   581                   '(go-test . ("^\t+\\([^()\t\n]+\\):\\([0-9]+\\):? .*$" 1 2)) t)))
   582  
   583  ;;;###autoload
   584  (add-to-list 'auto-mode-alist (cons "\\.go\\'" 'go-mode))
   585  
   586  (defun go--apply-rcs-patch (patch-buffer)
   587    "Apply an RCS-formatted diff from PATCH-BUFFER to the current
   588  buffer."
   589    (let ((target-buffer (current-buffer))
   590          ;; Relative offset between buffer line numbers and line numbers
   591          ;; in patch.
   592          ;;
   593          ;; Line numbers in the patch are based on the source file, so
   594          ;; we have to keep an offset when making changes to the
   595          ;; buffer.
   596          ;;
   597          ;; Appending lines decrements the offset (possibly making it
   598          ;; negative), deleting lines increments it. This order
   599          ;; simplifies the forward-line invocations.
   600          (line-offset 0))
   601      (save-excursion
   602        (with-current-buffer patch-buffer
   603          (goto-char (point-min))
   604          (while (not (eobp))
   605            (unless (looking-at "^\\([ad]\\)\\([0-9]+\\) \\([0-9]+\\)")
   606              (error "invalid rcs patch or internal error in go--apply-rcs-patch"))
   607            (forward-line)
   608            (let ((action (match-string 1))
   609                  (from (string-to-number (match-string 2)))
   610                  (len  (string-to-number (match-string 3))))
   611              (cond
   612               ((equal action "a")
   613                (let ((start (point)))
   614                  (forward-line len)
   615                  (let ((text (buffer-substring start (point))))
   616                    (with-current-buffer target-buffer
   617                      (decf line-offset len)
   618                      (goto-char (point-min))
   619                      (forward-line (- from len line-offset))
   620                      (insert text)))))
   621               ((equal action "d")
   622                (with-current-buffer target-buffer
   623                  (go--goto-line (- from line-offset))
   624                  (incf line-offset len)
   625                  (go--delete-whole-line len)))
   626               (t
   627                (error "invalid rcs patch or internal error in go--apply-rcs-patch")))))))))
   628  
   629  (defun gofmt ()
   630    "Formats the current buffer according to the gofmt tool."
   631  
   632    (interactive)
   633    (let ((tmpfile (make-temp-file "gofmt" nil ".go"))
   634          (patchbuf (get-buffer-create "*Gofmt patch*"))
   635          (errbuf (get-buffer-create "*Gofmt Errors*"))
   636          (coding-system-for-read 'utf-8)
   637          (coding-system-for-write 'utf-8))
   638  
   639      (with-current-buffer errbuf
   640        (setq buffer-read-only nil)
   641        (erase-buffer))
   642      (with-current-buffer patchbuf
   643        (erase-buffer))
   644  
   645      (write-region nil nil tmpfile)
   646  
   647      ;; We're using errbuf for the mixed stdout and stderr output. This
   648      ;; is not an issue because gofmt -w does not produce any stdout
   649      ;; output in case of success.
   650      (if (zerop (call-process gofmt-command nil errbuf nil "-w" tmpfile))
   651          (if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile))
   652              (progn
   653                (kill-buffer errbuf)
   654                (message "Buffer is already gofmted"))
   655            (go--apply-rcs-patch patchbuf)
   656            (kill-buffer errbuf)
   657            (message "Applied gofmt"))
   658        (message "Could not apply gofmt. Check errors for details")
   659        (gofmt--process-errors (buffer-file-name) tmpfile errbuf))
   660  
   661      (kill-buffer patchbuf)
   662      (delete-file tmpfile)))
   663  
   664  
   665  (defun gofmt--process-errors (filename tmpfile errbuf)
   666    ;; Convert the gofmt stderr to something understood by the compilation mode.
   667    (with-current-buffer errbuf
   668      (goto-char (point-min))
   669      (insert "gofmt errors:\n")
   670      (while (search-forward-regexp (concat "^\\(" (regexp-quote tmpfile) "\\):") nil t)
   671        (replace-match (file-name-nondirectory filename) t t nil 1))
   672      (compilation-mode)
   673      (display-buffer errbuf)))
   674  
   675  ;;;###autoload
   676  (defun gofmt-before-save ()
   677    "Add this to .emacs to run gofmt on the current buffer when saving:
   678   (add-hook 'before-save-hook 'gofmt-before-save).
   679  
   680  Note that this will cause go-mode to get loaded the first time
   681  you save any file, kind of defeating the point of autoloading."
   682  
   683    (interactive)
   684    (when (eq major-mode 'go-mode) (gofmt)))
   685  
   686  (defun godoc--read-query ()
   687    "Read a godoc query from the minibuffer."
   688    ;; Compute the default query as the symbol under the cursor.
   689    ;; TODO: This does the wrong thing for e.g. multipart.NewReader (it only grabs
   690    ;; half) but I see no way to disambiguate that from e.g. foobar.SomeMethod.
   691    (let* ((bounds (bounds-of-thing-at-point 'symbol))
   692           (symbol (if bounds
   693                       (buffer-substring-no-properties (car bounds)
   694                                                       (cdr bounds)))))
   695      (completing-read (if symbol
   696                           (format "godoc (default %s): " symbol)
   697                         "godoc: ")
   698                       (go--old-completion-list-style (go-packages)) nil nil nil 'go-godoc-history symbol)))
   699  
   700  (defun godoc--get-buffer (query)
   701    "Get an empty buffer for a godoc query."
   702    (let* ((buffer-name (concat "*godoc " query "*"))
   703           (buffer (get-buffer buffer-name)))
   704      ;; Kill the existing buffer if it already exists.
   705      (when buffer (kill-buffer buffer))
   706      (get-buffer-create buffer-name)))
   707  
   708  (defun godoc--buffer-sentinel (proc event)
   709    "Sentinel function run when godoc command completes."
   710    (with-current-buffer (process-buffer proc)
   711      (cond ((string= event "finished\n")  ;; Successful exit.
   712             (goto-char (point-min))
   713             (view-mode 1)
   714             (display-buffer (current-buffer) t))
   715            ((/= (process-exit-status proc) 0)  ;; Error exit.
   716             (let ((output (buffer-string)))
   717               (kill-buffer (current-buffer))
   718               (message (concat "godoc: " output)))))))
   719  
   720  ;;;###autoload
   721  (defun godoc (query)
   722    "Show go documentation for a query, much like M-x man."
   723    (interactive (list (godoc--read-query)))
   724    (unless (string= query "")
   725      (set-process-sentinel
   726       (start-process-shell-command "godoc" (godoc--get-buffer query)
   727                                    (concat "godoc " query))
   728       'godoc--buffer-sentinel)
   729      nil))
   730  
   731  (defun go-goto-imports ()
   732    "Move point to the block of imports.
   733  
   734  If using
   735  
   736    import (
   737      \"foo\"
   738      \"bar\"
   739    )
   740  
   741  it will move point directly behind the last import.
   742  
   743  If using
   744  
   745    import \"foo\"
   746    import \"bar\"
   747  
   748  it will move point to the next line after the last import.
   749  
   750  If no imports can be found, point will be moved after the package
   751  declaration."
   752    (interactive)
   753    ;; FIXME if there's a block-commented import before the real
   754    ;; imports, we'll jump to that one.
   755  
   756    ;; Generally, this function isn't very forgiving. it'll bark on
   757    ;; extra whitespace. It works well for clean code.
   758    (let ((old-point (point)))
   759      (goto-char (point-min))
   760      (cond
   761       ((re-search-forward "^import ()" nil t)
   762        (backward-char 1)
   763        'block-empty)
   764       ((re-search-forward "^import ([^)]+)" nil t)
   765        (backward-char 2)
   766        'block)
   767       ((re-search-forward "\\(^import \\([^\"]+ \\)?\"[^\"]+\"\n?\\)+" nil t)
   768        'single)
   769       ((re-search-forward "^[[:space:]\n]*package .+?\n" nil t)
   770        (message "No imports found, moving point after package declaration")
   771        'none)
   772       (t
   773        (goto-char old-point)
   774        (message "No imports or package declaration found. Is this really a Go file?")
   775        'fail))))
   776  
   777  (defun go-play-buffer ()
   778    "Like `go-play-region', but acts on the entire buffer."
   779    (interactive)
   780    (go-play-region (point-min) (point-max)))
   781  
   782  (defun go-play-region (start end)
   783    "Send the region to the Playground and stores the resulting
   784  link in the kill ring."
   785    (interactive "r")
   786    (let* ((url-request-method "POST")
   787           (url-request-extra-headers
   788            '(("Content-Type" . "application/x-www-form-urlencoded")))
   789           (url-request-data
   790            (encode-coding-string
   791             (buffer-substring-no-properties start end)
   792             'utf-8))
   793           (content-buf (url-retrieve
   794                         "http://play.golang.org/share"
   795                         (lambda (arg)
   796                           (cond
   797                            ((equal :error (car arg))
   798                             (signal 'go-play-error (cdr arg)))
   799                            (t
   800                             (re-search-forward "\n\n")
   801                             (kill-new (format "http://play.golang.org/p/%s" (buffer-substring (point) (point-max))))
   802                             (message "http://play.golang.org/p/%s" (buffer-substring (point) (point-max)))))))))))
   803  
   804  ;;;###autoload
   805  (defun go-download-play (url)
   806    "Downloads a paste from the playground and inserts it in a Go
   807  buffer. Tries to look for a URL at point."
   808    (interactive (list (read-from-minibuffer "Playground URL: " (ffap-url-p (ffap-string-at-point 'url)))))
   809    (with-current-buffer
   810        (let ((url-request-method "GET") url-request-data url-request-extra-headers)
   811          (url-retrieve-synchronously (concat url ".go")))
   812      (let ((buffer (generate-new-buffer (concat (car (last (split-string url "/"))) ".go"))))
   813        (goto-char (point-min))
   814        (re-search-forward "\n\n")
   815        (copy-to-buffer buffer (point) (point-max))
   816        (kill-buffer)
   817        (with-current-buffer buffer
   818          (go-mode)
   819          (switch-to-buffer buffer)))))
   820  
   821  (defun go-propertize-syntax (start end)
   822    (save-excursion
   823      (goto-char start)
   824      (while (search-forward "\\" end t)
   825        (put-text-property (1- (point)) (point) 'syntax-table (if (= (char-after) ?`) '(1) '(9))))))
   826  
   827  (defun go-import-add (arg import)
   828    "Add a new import to the list of imports.
   829  
   830  When called with a prefix argument asks for an alternative name
   831  to import the package as.
   832  
   833  If no list exists yet, one will be created if possible.
   834  
   835  If an identical import has been commented, it will be
   836  uncommented, otherwise a new import will be added."
   837  
   838    ;; - If there's a matching `// import "foo"`, uncomment it
   839    ;; - If we're in an import() block and there's a matching `"foo"`, uncomment it
   840    ;; - Otherwise add a new import, with the appropriate syntax
   841    (interactive
   842     (list
   843      current-prefix-arg
   844      (replace-regexp-in-string "^[\"']\\|[\"']$" "" (completing-read "Package: " (go--old-completion-list-style (go-packages))))))
   845    (save-excursion
   846      (let (as line import-start)
   847        (if arg
   848            (setq as (read-from-minibuffer "Import as: ")))
   849        (if as
   850            (setq line (format "%s \"%s\"" as import))
   851          (setq line (format "\"%s\"" import)))
   852  
   853        (goto-char (point-min))
   854        (if (re-search-forward (concat "^[[:space:]]*//[[:space:]]*import " line "$") nil t)
   855            (uncomment-region (line-beginning-position) (line-end-position))
   856          (case (go-goto-imports)
   857            ('fail (message "Could not find a place to add import."))
   858            ('block-empty
   859             (insert "\n\t" line "\n"))
   860            ('block
   861                (save-excursion
   862                  (re-search-backward "^import (")
   863                  (setq import-start (point)))
   864              (if (re-search-backward (concat "^[[:space:]]*//[[:space:]]*" line "$")  import-start t)
   865                  (uncomment-region (line-beginning-position) (line-end-position))
   866                (insert "\n\t" line)))
   867            ('single (insert "import " line "\n"))
   868            ('none (insert "\nimport (\n\t" line "\n)\n")))))))
   869  
   870  (defun go-root-and-paths ()
   871    (let* ((output (split-string (shell-command-to-string (concat go-command " env GOROOT GOPATH"))
   872                                 "\n"))
   873           (root (car output))
   874           (paths (split-string (cadr output) ":")))
   875      (append (list root) paths)))
   876  
   877  (defun go--string-prefix-p (s1 s2 &optional ignore-case)
   878    "Return non-nil if S1 is a prefix of S2.
   879  If IGNORE-CASE is non-nil, the comparison is case-insensitive."
   880    (eq t (compare-strings s1 nil nil
   881                           s2 0 (length s1) ignore-case)))
   882  
   883  (defun go--directory-dirs (dir)
   884    "Recursively return all subdirectories in DIR."
   885    (if (file-directory-p dir)
   886        (let ((dir (directory-file-name dir))
   887              (dirs '())
   888              (files (directory-files dir nil nil t)))
   889          (dolist (file files)
   890            (unless (member file '("." ".."))
   891              (let ((file (concat dir "/" file)))
   892                (if (file-directory-p file)
   893                    (setq dirs (append (cons file
   894                                             (go--directory-dirs file))
   895                                       dirs))))))
   896          dirs)
   897      '()))
   898  
   899  
   900  (defun go-packages ()
   901    (sort
   902     (delete-dups
   903      (mapcan
   904       (lambda (topdir)
   905         (let ((pkgdir (concat topdir "/pkg/")))
   906           (mapcan (lambda (dir)
   907                     (mapcar (lambda (file)
   908                               (let ((sub (substring file (length pkgdir) -2)))
   909                                 (unless (or (go--string-prefix-p "obj/" sub) (go--string-prefix-p "tool/" sub))
   910                                   (mapconcat #'identity (cdr (split-string sub "/")) "/"))))
   911                             (if (file-directory-p dir)
   912                                 (directory-files dir t "\\.a$"))))
   913                   (if (file-directory-p pkgdir)
   914                       (go--directory-dirs pkgdir)))))
   915       (go-root-and-paths)))
   916     #'string<))
   917  
   918  (defun go-unused-imports-lines ()
   919    ;; FIXME Technically, -o /dev/null fails in quite some cases (on
   920    ;; Windows, when compiling from within GOPATH). Practically,
   921    ;; however, it has the same end result: There won't be a
   922    ;; compiled binary/archive, and we'll get our import errors when
   923    ;; there are any.
   924    (reverse (remove nil
   925                     (mapcar
   926                      (lambda (line)
   927                        (if (string-match "^\\(.+\\):\\([[:digit:]]+\\): imported and not used: \".+\".*$" line)
   928                            (if (string= (file-truename (match-string 1 line)) (file-truename buffer-file-name))
   929                                (string-to-number (match-string 2 line)))))
   930                      (split-string (shell-command-to-string
   931                                     (concat go-command
   932                                             (if (string-match "_test\.go$" buffer-file-truename)
   933                                                 " test -c"
   934                                               " build -o /dev/null"))) "\n")))))
   935  
   936  (defun go-remove-unused-imports (arg)
   937    "Removes all unused imports. If ARG is non-nil, unused imports
   938  will be commented, otherwise they will be removed completely."
   939    (interactive "P")
   940    (save-excursion
   941      (let ((cur-buffer (current-buffer)) flymake-state lines)
   942        (when (boundp 'flymake-mode)
   943          (setq flymake-state flymake-mode)
   944          (flymake-mode-off))
   945        (save-some-buffers nil (lambda () (equal cur-buffer (current-buffer))))
   946        (if (buffer-modified-p)
   947            (message "Cannot operate on unsaved buffer")
   948          (setq lines (go-unused-imports-lines))
   949          (dolist (import lines)
   950            (go--goto-line import)
   951            (beginning-of-line)
   952            (if arg
   953                (comment-region (line-beginning-position) (line-end-position))
   954              (go--delete-whole-line)))
   955          (message "Removed %d imports" (length lines)))
   956        (if flymake-state (flymake-mode-on)))))
   957  
   958  (defun godef--find-file-line-column (specifier other-window)
   959    "Given a file name in the format of `filename:line:column',
   960  visit FILENAME and go to line LINE and column COLUMN."
   961    (if (not (string-match "\\(.+\\):\\([0-9]+\\):\\([0-9]+\\)" specifier))
   962        ;; We've only been given a directory name
   963        (funcall (if other-window #'find-file-other-window #'find-file) specifier)
   964      (let ((filename (match-string 1 specifier))
   965            (line (string-to-number (match-string 2 specifier)))
   966            (column (string-to-number (match-string 3 specifier))))
   967        (with-current-buffer (funcall (if other-window #'find-file-other-window #'find-file) filename)
   968          (go--goto-line line)
   969          (beginning-of-line)
   970          (forward-char (1- column))
   971          (if (buffer-modified-p)
   972              (message "Buffer is modified, file position might not have been correct"))))))
   973  
   974  (defun godef--call (point)
   975    "Call godef, acquiring definition position and expression
   976  description at POINT."
   977    (if (go--xemacs-p)
   978        (error "godef does not reliably work in XEmacs, expect bad results"))
   979    (if (not (buffer-file-name (go--coverage-origin-buffer)))
   980        (error "Cannot use godef on a buffer without a file name")
   981      (let ((outbuf (get-buffer-create "*godef*")))
   982        (with-current-buffer outbuf
   983          (erase-buffer))
   984        (call-process-region (point-min)
   985                             (point-max)
   986                             "godef"
   987                             nil
   988                             outbuf
   989                             nil
   990                             "-i"
   991                             "-t"
   992                             "-f"
   993                             (file-truename (buffer-file-name (go--coverage-origin-buffer)))
   994                             "-o"
   995                             (number-to-string (go--position-bytes (point))))
   996        (with-current-buffer outbuf
   997          (split-string (buffer-substring-no-properties (point-min) (point-max)) "\n")))))
   998  
   999  (defun godef-describe (point)
  1000    "Describe the expression at POINT."
  1001    (interactive "d")
  1002    (condition-case nil
  1003        (let ((description (cdr (butlast (godef--call point) 1))))
  1004          (if (not description)
  1005              (message "No description found for expression at point")
  1006            (message "%s" (mapconcat #'identity description "\n"))))
  1007      (file-error (message "Could not run godef binary"))))
  1008  
  1009  (defun godef-jump (point &optional other-window)
  1010    "Jump to the definition of the expression at POINT."
  1011    (interactive "d")
  1012    (condition-case nil
  1013        (let ((file (car (godef--call point))))
  1014          (cond
  1015           ((string= "-" file)
  1016            (message "godef: expression is not defined anywhere"))
  1017           ((string= "godef: no identifier found" file)
  1018            (message "%s" file))
  1019           ((go--string-prefix-p "godef: no declaration found for " file)
  1020            (message "%s" file))
  1021           ((go--string-prefix-p "error finding import path for " file)
  1022            (message "%s" file))
  1023           (t
  1024            (push-mark)
  1025            (ring-insert find-tag-marker-ring (point-marker))
  1026            (godef--find-file-line-column file other-window))))
  1027      (file-error (message "Could not run godef binary"))))
  1028  
  1029  (defun godef-jump-other-window (point)
  1030    (interactive "d")
  1031    (godef-jump point t))
  1032  
  1033  (defun go--goto-line (line)
  1034    (goto-char (point-min))
  1035    (forward-line (1- line)))
  1036  
  1037  (defun go--line-column-to-point (line column)
  1038    (save-excursion
  1039      (go--goto-line line)
  1040      (forward-char (1- column))
  1041      (point)))
  1042  
  1043  (defstruct go--covered
  1044    start-line start-column end-line end-column covered count)
  1045  
  1046  (defun go--coverage-file ()
  1047    "Return the coverage file to use, either by reading it from the
  1048  current coverage buffer or by prompting for it."
  1049    (if (boundp 'go--coverage-current-file-name)
  1050        go--coverage-current-file-name
  1051      (read-file-name "Coverage file: " nil nil t)))
  1052  
  1053  (defun go--coverage-origin-buffer ()
  1054    "Return the buffer to base the coverage on."
  1055    (or (buffer-base-buffer) (current-buffer)))
  1056  
  1057  (defun go--coverage-face (count divisor)
  1058    "Return the intensity face for COUNT when using DIVISOR
  1059  to scale it to a range [0,10].
  1060  
  1061  DIVISOR scales the absolute cover count to values from 0 to 10.
  1062  For DIVISOR = 0 the count will always translate to 8."
  1063    (let* ((norm (cond
  1064                  ((= count 0)
  1065                   -0.1) ;; Uncovered code, set to -0.1 so n becomes 0.
  1066                  ((= divisor 0)
  1067                   0.8) ;; covermode=set, set to 0.8 so n becomes 8.
  1068                  (t
  1069                   (/ (log count) divisor))))
  1070           (n (1+ (floor (* norm 9))))) ;; Convert normalized count [0,1] to intensity [0,10]
  1071      (concat "go-coverage-" (number-to-string n))))
  1072  
  1073  (defun go--coverage-make-overlay (range divisor)
  1074    "Create a coverage overlay for a RANGE of covered/uncovered
  1075  code. Uses DIVISOR to scale absolute counts to a [0,10] scale."
  1076    (let* ((count (go--covered-count range))
  1077           (face (go--coverage-face count divisor))
  1078           (ov (make-overlay (go--line-column-to-point (go--covered-start-line range)
  1079                                                       (go--covered-start-column range))
  1080                             (go--line-column-to-point (go--covered-end-line range)
  1081                                                       (go--covered-end-column range)))))
  1082  
  1083      (overlay-put ov 'face face)
  1084      (overlay-put ov 'help-echo (format "Count: %d" count))))
  1085  
  1086  (defun go--coverage-clear-overlays ()
  1087    "Remove existing overlays and put a single untracked overlay
  1088  over the entire buffer."
  1089    (remove-overlays)
  1090    (overlay-put (make-overlay (point-min) (point-max))
  1091                 'face
  1092                 'go-coverage-untracked))
  1093  
  1094  (defun go--coverage-parse-file (coverage-file file-name)
  1095    "Parse COVERAGE-FILE and extract coverage information and
  1096  divisor for FILE-NAME."
  1097    (let (ranges
  1098          (max-count 0))
  1099      (with-temp-buffer
  1100        (insert-file-contents coverage-file)
  1101        (go--goto-line 2) ;; Skip over mode
  1102        (while (not (eobp))
  1103          (let* ((parts (split-string (buffer-substring (point-at-bol) (point-at-eol)) ":"))
  1104                 (file (car parts))
  1105                 (rest (split-string (nth 1 parts) "[., ]")))
  1106  
  1107            (destructuring-bind
  1108                (start-line start-column end-line end-column num count)
  1109                (mapcar #'string-to-number rest)
  1110  
  1111              (when (and (string= (file-name-nondirectory file) file-name))
  1112                (if (> count max-count)
  1113                    (setq max-count count))
  1114                (push (make-go--covered :start-line start-line
  1115                                        :start-column start-column
  1116                                        :end-line end-line
  1117                                        :end-column end-column
  1118                                        :covered (/= count 0)
  1119                                        :count count)
  1120                      ranges)))
  1121  
  1122            (forward-line)))
  1123  
  1124        (list ranges (if (> max-count 0) (log max-count) 0)))))
  1125  
  1126  (defun go-coverage (&optional coverage-file)
  1127    "Open a clone of the current buffer and overlay it with
  1128  coverage information gathered via go test -coverprofile=COVERAGE-FILE.
  1129  
  1130  If COVERAGE-FILE is nil, it will either be inferred from the
  1131  current buffer if it's already a coverage buffer, or be prompted
  1132  for."
  1133    (interactive)
  1134    (let* ((cur-buffer (current-buffer))
  1135           (origin-buffer (go--coverage-origin-buffer))
  1136           (gocov-buffer-name (concat (buffer-name origin-buffer) "<gocov>"))
  1137           (coverage-file (or coverage-file (go--coverage-file)))
  1138           (ranges-and-divisor (go--coverage-parse-file
  1139                                coverage-file
  1140                                (file-name-nondirectory (buffer-file-name origin-buffer))))
  1141           (cov-mtime (nth 5 (file-attributes coverage-file)))
  1142           (cur-mtime (nth 5 (file-attributes (buffer-file-name origin-buffer)))))
  1143  
  1144      (if (< (float-time cov-mtime) (float-time cur-mtime))
  1145          (message "Coverage file is older than the source file."))
  1146  
  1147      (with-current-buffer (or (get-buffer gocov-buffer-name)
  1148                               (make-indirect-buffer origin-buffer gocov-buffer-name t))
  1149        (set (make-local-variable 'go--coverage-current-file-name) coverage-file)
  1150  
  1151        (save-excursion
  1152          (go--coverage-clear-overlays)
  1153          (dolist (range (car ranges-and-divisor))
  1154            (go--coverage-make-overlay range (cadr ranges-and-divisor))))
  1155  
  1156        (if (not (eq cur-buffer (current-buffer)))
  1157            (display-buffer (current-buffer) #'display-buffer-reuse-window)))))
  1158  
  1159  (provide 'go-mode)