Simple image host.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

go-mode.el 45KB

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