]> code.delx.au - gnu-emacs-elpa/blob - ggtags.el
Fix #52: Search references and symbols in GTAGSLIBPATH
[gnu-emacs-elpa] / ggtags.el
1 ;;; ggtags.el --- emacs frontend to GNU Global source code tagging system -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
4
5 ;; Author: Leo Liu <sdl.web@gmail.com>
6 ;; Version: 0.8.4
7 ;; Keywords: tools, convenience
8 ;; Created: 2013-01-29
9 ;; URL: https://github.com/leoliu/ggtags
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; A package to integrate GNU Global source code tagging system
28 ;; (http://www.gnu.org/software/global) with Emacs.
29 ;;
30 ;; Usage:
31 ;;
32 ;; `ggtags' is similar to the standard `etags' package. These keys
33 ;; `M-.', `M-,', `M-*' and `C-M-.' should work as expected in
34 ;; `ggtags-mode'. See the README in https://github.com/leoliu/ggtags
35 ;; for more details.
36 ;;
37 ;; All commands are available from the `Ggtags' menu in `ggtags-mode'.
38
39 ;;; Code:
40
41 (eval-when-compile
42 (require 'url-parse))
43
44 (require 'cl-lib)
45 (require 'ewoc)
46 (require 'compile)
47 (require 'etags)
48 (require 'tabulated-list) ;preloaded since 24.3
49
50 (eval-when-compile
51 (unless (fboundp 'setq-local)
52 (defmacro setq-local (var val)
53 (list 'set (list 'make-local-variable (list 'quote var)) val)))
54
55 (unless (fboundp 'defvar-local)
56 (defmacro defvar-local (var val &optional docstring)
57 (declare (debug defvar) (doc-string 3))
58 (list 'progn (list 'defvar var val docstring)
59 (list 'make-variable-buffer-local (list 'quote var)))))
60
61 (defmacro ignore-errors-unless-debug (&rest body)
62 "Ignore all errors while executing BODY unless debug is on."
63 (declare (debug t) (indent 0))
64 `(condition-case-unless-debug nil (progn ,@body) (error nil)))
65
66 (defmacro with-display-buffer-no-window (&rest body)
67 (declare (debug t) (indent 0))
68 ;; See http://debbugs.gnu.org/13594
69 `(let ((display-buffer-overriding-action
70 (if (and ggtags-auto-jump-to-match
71 ;; Appeared in emacs 24.4.
72 (fboundp 'display-buffer-no-window))
73 (list #'display-buffer-no-window)
74 display-buffer-overriding-action)))
75 ,@body)))
76
77 (eval-and-compile
78 (or (fboundp 'user-error) ;24.3
79 (defalias 'user-error 'error))
80 (or (fboundp 'read-only-mode) ;24.3
81 (defalias 'read-only-mode 'toggle-read-only))
82 (or (fboundp 'register-read-with-preview) ;24.4
83 (defalias 'register-read-with-preview 'read-char)))
84
85 (defgroup ggtags nil
86 "GNU Global source code tagging system."
87 :group 'tools)
88
89 (defface ggtags-highlight '((t (:underline t)))
90 "Face used to highlight a valid tag at point."
91 :group 'ggtags)
92
93 (defface ggtags-global-line '((t (:inherit secondary-selection)))
94 "Face used to highlight matched line in Global buffer."
95 :group 'ggtags)
96
97 (defcustom ggtags-executable-directory nil
98 "If non-nil the directory to search global executables."
99 :type '(choice (const :tag "Unset" nil) directory)
100 :risky t
101 :group 'ggtags)
102
103 (defcustom ggtags-oversize-limit (* 10 1024 1024)
104 "The over size limit for the GTAGS file.
105 For large source trees, running 'global -u' can be expensive.
106 Thus when GTAGS file is larger than this limit, ggtags
107 automatically switches to 'global --single-update'."
108 :safe 'numberp
109 :type '(choice (const :tag "None" nil)
110 (const :tag "Always" t)
111 number)
112 :group 'ggtags)
113
114 (defcustom ggtags-include-pattern
115 '("^\\s-*#\\(?:include\\|import\\)\\s-*[\"<]\\(?:[./]*\\)?\\(.*?\\)[\">]" . 1)
116 "Pattern used to detect #include files.
117 Value can be (REGEXP . SUB) or a function with no arguments.
118 REGEXP should match from the beginning of line."
119 :type '(choice (const :tag "Disable" nil)
120 (cons regexp integer)
121 function)
122 :safe 'stringp
123 :group 'ggtags)
124
125 (defcustom ggtags-use-project-gtagsconf t
126 "Non-nil to use GTAGSCONF file found at project root.
127 File .globalrc and gtags.conf are checked in order."
128 :safe 'booleanp
129 :type 'boolean
130 :group 'ggtags)
131
132 (defcustom ggtags-project-duration 600
133 "Seconds to keep information of a project in memory."
134 :type 'number
135 :group 'ggtags)
136
137 (defcustom ggtags-process-environment nil
138 "Similar to `process-environment' with higher precedence.
139 Elements are run through `substitute-env-vars' before use.
140 GTAGSROOT will always be expanded to current project root
141 directory. This is intended for project-wise ggtags-specific
142 process environment settings. Note on remote hosts (e.g. tramp)
143 directory local variables is not enabled by default per
144 `enable-remote-dir-locals' (which see)."
145 :safe 'ggtags-list-of-string-p
146 :type '(repeat string)
147 :group 'ggtags)
148
149 (defcustom ggtags-auto-jump-to-match 'history
150 "Strategy on how to jump to match: nil, first or history.
151
152 nil: never automatically jump to any match;
153 first: jump to the first match;
154 history: jump to the match stored in search history."
155 :type '(choice (const :tag "First match" first)
156 (const :tag "Search History" history)
157 (const :tag "Never" nil))
158 :group 'ggtags)
159
160 (defcustom ggtags-global-window-height 8 ; ggtags-global-mode
161 "Number of lines for the *ggtags-global* popup window.
162 If nil, use Emacs default."
163 :type '(choice (const :tag "Default" nil) integer)
164 :group 'ggtags)
165
166 (defcustom ggtags-global-abbreviate-filename 40
167 "Non-nil to display file names abbreviated e.g. \"/u/b/env\".
168 If an integer abbreviate only names longer than that number."
169 :type '(choice (const :tag "No" nil)
170 (const :tag "Always" t)
171 integer)
172 :group 'ggtags)
173
174 (defcustom ggtags-split-window-function split-window-preferred-function
175 "A function to control how ggtags pops up the auxiliary window."
176 :type 'function
177 :group 'ggtags)
178
179 (defcustom ggtags-use-idutils (and (executable-find "mkid") t)
180 "Non-nil to also generate the idutils DB."
181 :type 'boolean
182 :group 'ggtags)
183
184 (defcustom ggtags-global-output-format 'grep
185 "Global output format: path, ctags, ctags-x, grep or cscope."
186 :type '(choice (const path)
187 (const ctags)
188 (const ctags-x)
189 (const grep)
190 (const cscope))
191 :group 'ggtags)
192
193 (defcustom ggtags-global-use-color t
194 "Non-nil to use color in output if supported by Global.
195 Note: processing colored output takes noticeable time
196 particularly when the output is large."
197 :type 'boolean
198 :safe 'booleanp
199 :group 'ggtags)
200
201 (defcustom ggtags-global-ignore-case nil
202 "Non-nil if Global should ignore case in the search pattern."
203 :safe 'booleanp
204 :type 'boolean
205 :group 'ggtags)
206
207 (defcustom ggtags-global-treat-text nil
208 "Non-nil if Global should include matches from text files.
209 This affects `ggtags-find-file' and `ggtags-grep'."
210 :safe 'booleanp
211 :type 'boolean
212 :group 'ggtags)
213
214 (defcustom ggtags-global-large-output 1000
215 "Number of lines in the Global buffer to indicate large output."
216 :type 'number
217 :group 'ggtags)
218
219 (defcustom ggtags-global-history-length history-length
220 "Maximum number of items to keep in `ggtags-global-search-history'."
221 :type 'integer
222 :group 'ggtags)
223
224 (defcustom ggtags-enable-navigation-keys t
225 "If non-nil key bindings in `ggtags-navigation-map' are enabled."
226 :safe 'booleanp
227 :type 'boolean
228 :group 'ggtags)
229
230 (defcustom ggtags-find-tag-hook nil
231 "Hook run immediately after finding a tag."
232 :options '(recenter reposition-window)
233 :type 'hook
234 :group 'ggtags)
235
236 (defcustom ggtags-get-definition-function #'ggtags-get-definition-default
237 "Function called by `ggtags-show-definition' to get definition.
238 It is passed a list of definition candidates of the form:
239
240 (TEXT NAME FILE LINE)
241
242 where TEXT is usually the source line of the definition.
243
244 The return value is passed to `ggtags-print-definition-function'."
245 :type 'function
246 :group 'ggtags)
247
248 (defcustom ggtags-print-definition-function
249 (lambda (s) (ggtags-echo "%s" (or s "[definition not found]")))
250 "Function used by `ggtags-show-definition' to print definition."
251 :type 'function
252 :group 'ggtags)
253
254 (defcustom ggtags-mode-sticky t
255 "If non-nil enable Ggtags Mode in files visited."
256 :safe 'booleanp
257 :type 'boolean
258 :group 'ggtags)
259
260 (defcustom ggtags-mode-prefix-key "\C-c"
261 "Key binding used for `ggtags-mode-prefix-map'.
262 Users should change the value using `customize-variable' to
263 properly update `ggtags-mode-map'."
264 :set (lambda (sym value)
265 (when (bound-and-true-p ggtags-mode-map)
266 (let ((old (and (boundp sym) (symbol-value sym))))
267 (and old (define-key ggtags-mode-map old nil)))
268 (and value
269 (bound-and-true-p ggtags-mode-prefix-map)
270 (define-key ggtags-mode-map value ggtags-mode-prefix-map)))
271 (set-default sym value))
272 :type 'key-sequence
273 :group 'ggtags)
274
275 (defcustom ggtags-highlight-tag-delay 0.25
276 "Time in seconds before highlighting tag at point."
277 :set (lambda (sym value)
278 (when (bound-and-true-p ggtags-highlight-tag-timer)
279 (timer-set-idle-time ggtags-highlight-tag-timer value t))
280 (set-default sym value))
281 :type 'number
282 :group 'ggtags)
283
284 (defcustom ggtags-bounds-of-tag-function (lambda ()
285 (bounds-of-thing-at-point 'symbol))
286 "Function to get the start and end positions of the tag at point."
287 :type 'function
288 :group 'ggtags)
289
290 ;; Used by ggtags-global-mode
291 (defvar ggtags-global-error "match"
292 "Stem of message to print when no matches are found.")
293
294 (defconst ggtags-bug-url "https://github.com/leoliu/ggtags/issues")
295
296 (defvar ggtags-global-last-buffer nil)
297
298 (defvar ggtags-global-continuation nil)
299
300 (defvar ggtags-current-tag-name nil)
301
302 (defvar ggtags-highlight-tag-overlay nil)
303
304 (defvar ggtags-highlight-tag-timer nil)
305
306 (defmacro ggtags-with-temp-message (message &rest body)
307 (declare (debug t) (indent 1))
308 (let ((init-time (make-symbol "-init-time-"))
309 (tmp-msg (make-symbol "-tmp-msg-")))
310 `(let ((,init-time (float-time))
311 (,tmp-msg ,message))
312 (with-temp-message ,tmp-msg
313 (prog1 (progn ,@body)
314 (message "%sdone (%.2fs)" ,(or tmp-msg "")
315 (- (float-time) ,init-time)))))))
316
317 (defmacro ggtags-delay-finish-functions (&rest body)
318 "Delay running `compilation-finish-functions' until after BODY."
319 (declare (indent 0) (debug t))
320 (let ((saved (make-symbol "-saved-"))
321 (exit-args (make-symbol "-exit-args-")))
322 `(let ((,saved compilation-finish-functions)
323 ,exit-args)
324 (setq-local compilation-finish-functions nil)
325 (add-hook 'compilation-finish-functions
326 (lambda (&rest args) (setq ,exit-args args))
327 nil t)
328 (unwind-protect (progn ,@body)
329 (setq-local compilation-finish-functions ,saved)
330 (and ,exit-args (apply #'run-hook-with-args
331 'compilation-finish-functions ,exit-args))))))
332
333 (defmacro ggtags-ensure-global-buffer (&rest body)
334 (declare (debug t) (indent 0))
335 `(progn
336 (or (and (buffer-live-p ggtags-global-last-buffer)
337 (with-current-buffer ggtags-global-last-buffer
338 (derived-mode-p 'ggtags-global-mode)))
339 (error "No global buffer found"))
340 (with-current-buffer ggtags-global-last-buffer ,@body)))
341
342 (defun ggtags-list-of-string-p (xs)
343 "Return non-nil if XS is a list of strings."
344 (cl-every #'stringp xs))
345
346 (defun ggtags-ensure-localname (file)
347 (and file (or (file-remote-p file 'localname) file)))
348
349 (defun ggtags-echo (format-string &rest args)
350 "Print formatted text to echo area."
351 (let (message-log-max) (apply #'message format-string args)))
352
353 (defun ggtags-forward-to-line (line)
354 "Move to line number LINE in current buffer."
355 (cl-check-type line (integer 1))
356 (save-restriction
357 (widen)
358 (goto-char (point-min))
359 (forward-line (1- line))))
360
361 (defun ggtags-program-path (name)
362 (if ggtags-executable-directory
363 (expand-file-name name ggtags-executable-directory)
364 name))
365
366 (defun ggtags-process-string (program &rest args)
367 (with-temp-buffer
368 (let ((exit (apply #'process-file
369 (ggtags-program-path program) nil t nil args))
370 (output (progn
371 (goto-char (point-max))
372 (skip-chars-backward " \t\n")
373 (buffer-substring (point-min) (point)))))
374 (or (zerop exit)
375 (error "`%s' non-zero exit: %s" program output))
376 output)))
377
378 (defun ggtags-tag-at-point ()
379 (pcase (funcall ggtags-bounds-of-tag-function)
380 (`(,beg . ,end) (buffer-substring beg end))))
381
382 ;;; Store for project info and settings
383
384 (defvar ggtags-projects (make-hash-table :size 7 :test #'equal))
385
386 (cl-defstruct (ggtags-project (:constructor ggtags-project--make)
387 (:copier nil)
388 (:type vector)
389 :named)
390 root tag-size has-refs has-path-style has-color dirty-p mtime timestamp)
391
392 (defun ggtags-make-project (root)
393 (cl-check-type root string)
394 (pcase (nthcdr 5 (file-attributes (expand-file-name "GTAGS" root)))
395 (`(,mtime ,_ ,tag-size . ,_)
396 (let* ((default-directory (file-name-as-directory root))
397 (rtags-size (nth 7 (file-attributes "GRTAGS")))
398 (has-refs
399 (when rtags-size
400 (and (or (> rtags-size (* 32 1024))
401 (with-demoted-errors
402 (not (equal "" (ggtags-process-string "global" "-crs")))))
403 'has-refs)))
404 ;; http://thread.gmane.org/gmane.comp.gnu.global.bugs/1518
405 (has-path-style
406 (with-demoted-errors ; in case `global' not found
407 (and (zerop (process-file (ggtags-program-path "global")
408 nil nil nil
409 "--path-style" "shorter" "--help"))
410 'has-path-style)))
411 ;; http://thread.gmane.org/gmane.comp.gnu.global.bugs/1542
412 (has-color
413 (with-demoted-errors
414 (and (zerop (process-file (ggtags-program-path "global")
415 nil nil nil
416 "--color" "--help"))
417 'has-color))))
418 (puthash default-directory
419 (ggtags-project--make :root default-directory
420 :tag-size tag-size
421 :has-refs has-refs
422 :has-path-style has-path-style
423 :has-color has-color
424 :mtime (float-time mtime)
425 :timestamp (float-time))
426 ggtags-projects)))))
427
428 (defun ggtags-project-expired-p (project)
429 (or (< (ggtags-project-timestamp project) 0)
430 (> (- (float-time)
431 (ggtags-project-timestamp project))
432 ggtags-project-duration)))
433
434 (defun ggtags-project-update-mtime-maybe (&optional project)
435 "Update PROJECT's modtime and if current file is newer.
436 Value is new modtime if updated."
437 (let ((project (or project (ggtags-find-project))))
438 (when (and (ggtags-project-p project)
439 (consp (visited-file-modtime))
440 (> (float-time (visited-file-modtime))
441 (ggtags-project-mtime project)))
442 (setf (ggtags-project-dirty-p project) t)
443 (setf (ggtags-project-mtime project)
444 (float-time (visited-file-modtime))))))
445
446 (defun ggtags-project-oversize-p (&optional project)
447 (pcase ggtags-oversize-limit
448 (`nil nil)
449 (`t t)
450 (size (let ((project (or project (ggtags-find-project))))
451 (and project (> (ggtags-project-tag-size project) size))))))
452
453 (defvar-local ggtags-project-root 'unset
454 "Internal variable for project root directory.")
455
456 (defun ggtags-clear-project-root ()
457 (kill-local-variable 'ggtags-project-root))
458
459 ;;;###autoload
460 (defun ggtags-find-project ()
461 ;; See https://github.com/leoliu/ggtags/issues/42
462 ;;
463 ;; It is unsafe to cache `ggtags-project-root' in non-file buffers.
464 ;; But we keep the cache for a command's duration so that multiple
465 ;; calls of `ggtags-find-project' has no performance impact.
466 (unless buffer-file-name
467 (add-hook 'pre-command-hook #'ggtags-clear-project-root nil t))
468 (let ((project (gethash ggtags-project-root ggtags-projects)))
469 (if (ggtags-project-p project)
470 (if (ggtags-project-expired-p project)
471 (progn
472 (remhash ggtags-project-root ggtags-projects)
473 (ggtags-find-project))
474 project)
475 (setq ggtags-project-root
476 (or (ignore-errors-unless-debug
477 (file-name-as-directory
478 (concat (file-remote-p default-directory)
479 ;; Resolves symbolic links
480 (ggtags-process-string "global" "-pr"))))
481 ;; 'global -pr' resolves symlinks before checking the
482 ;; GTAGS file which could cause issues such as
483 ;; https://github.com/leoliu/ggtags/issues/22, so
484 ;; let's help it out.
485 ;;
486 ;; Note: `locate-dominating-file' doesn't accept
487 ;; function for NAME before 24.3.
488 (let ((dir (locate-dominating-file default-directory "GTAGS")))
489 ;; `file-truename' may strip the trailing '/' on
490 ;; remote hosts, see http://debbugs.gnu.org/16851
491 (and dir (file-regular-p (expand-file-name "GTAGS" dir))
492 (file-name-as-directory (file-truename dir))))))
493 (when ggtags-project-root
494 (if (gethash ggtags-project-root ggtags-projects)
495 (ggtags-find-project)
496 (ggtags-make-project ggtags-project-root))))))
497
498 (defun ggtags-current-project-root ()
499 (and (ggtags-find-project)
500 (ggtags-project-root (ggtags-find-project))))
501
502 (defun ggtags-check-project ()
503 (or (ggtags-find-project) (error "File GTAGS not found")))
504
505 (defun ggtags-ensure-project ()
506 (or (ggtags-find-project)
507 (when (or (yes-or-no-p "File GTAGS not found; run gtags? ")
508 (user-error "Aborted"))
509 (call-interactively #'ggtags-create-tags)
510 ;; Need checking because `ggtags-create-tags' can create tags
511 ;; in any directory.
512 (ggtags-check-project))))
513
514 (defvar delete-trailing-lines) ;new in 24.3
515
516 (defun ggtags-save-project-settings (&optional noconfirm)
517 "Save Gnu Global's specific environment variables."
518 (interactive "P")
519 (ggtags-check-project)
520 (let* ((inhibit-read-only t) ; for `add-dir-local-variable'
521 (default-directory (ggtags-current-project-root))
522 ;; Not using `ggtags-with-current-project' to preserve
523 ;; environment variables that may be present in
524 ;; `ggtags-process-environment'.
525 (process-environment
526 (append ggtags-process-environment
527 process-environment
528 (and (not (ggtags-project-has-refs (ggtags-find-project)))
529 (list "GTAGSLABEL=ctags"))))
530 (envlist (delete-dups
531 (cl-loop for x in process-environment
532 when (string-match
533 "^\\(GTAGS[^=\n]*\\|MAKEOBJDIRPREFIX\\)=" x)
534 ;; May have duplicates thus `delete-dups'.
535 collect (concat (match-string 1 x)
536 "="
537 (getenv (match-string 1 x))))))
538 (help-form (format "y: save\nn: don't save\n=: diff\n?: help\n")))
539 (add-dir-local-variable nil 'ggtags-process-environment envlist)
540 ;; Remove trailing newlines by `add-dir-local-variable'.
541 (let ((delete-trailing-lines t)) (delete-trailing-whitespace))
542 (or noconfirm
543 (while (pcase (read-char-choice
544 (format "Save `%s'? (y/n/=/?) " buffer-file-name)
545 '(?y ?n ?= ??))
546 ;; ` required for 24.1 and 24.2
547 (`?n (user-error "Aborted"))
548 (`?y nil)
549 (`?= (diff-buffer-with-file) 'loop)
550 (`?? (help-form-show) 'loop))))
551 (save-buffer)
552 (kill-buffer)))
553
554 (defun ggtags-toggle-project-read-only ()
555 (interactive)
556 (ggtags-check-project)
557 (let ((inhibit-read-only t) ; for `add-dir-local-variable'
558 (val (not buffer-read-only))
559 (default-directory (ggtags-current-project-root)))
560 (add-dir-local-variable nil 'buffer-read-only val)
561 (save-buffer)
562 (kill-buffer)
563 (when buffer-file-name
564 (read-only-mode (if val +1 -1)))
565 (when (called-interactively-p 'interactive)
566 (message "Project read-only-mode is %s" (if val "on" "off")))
567 val))
568
569 (defun ggtags-visit-project-root ()
570 (interactive)
571 (ggtags-ensure-project)
572 (dired (ggtags-current-project-root)))
573
574 (defmacro ggtags-with-current-project (&rest body)
575 "Eval BODY in current project's `process-environment'."
576 (declare (debug t) (indent 0))
577 (let ((gtagsroot (make-symbol "-gtagsroot-"))
578 (root (make-symbol "-ggtags-project-root-")))
579 `(let* ((,root ggtags-project-root)
580 (,gtagsroot (when (ggtags-find-project)
581 (ggtags-ensure-localname
582 (directory-file-name (ggtags-current-project-root)))))
583 (process-environment
584 (append (let ((process-environment process-environment))
585 (and ,gtagsroot (setenv "GTAGSROOT" ,gtagsroot))
586 (mapcar #'substitute-env-vars ggtags-process-environment))
587 process-environment
588 (and ,gtagsroot (list (concat "GTAGSROOT=" ,gtagsroot)))
589 (and (ggtags-find-project)
590 (not (ggtags-project-has-refs (ggtags-find-project)))
591 (list "GTAGSLABEL=ctags")))))
592 (unwind-protect (save-current-buffer ,@body)
593 (setq ggtags-project-root ,root)))))
594
595 (defun ggtags-get-libpath ()
596 (let ((path (ggtags-with-current-project (getenv "GTAGSLIBPATH"))))
597 (and path (mapcar (apply-partially #'concat (file-remote-p default-directory))
598 (split-string path (regexp-quote path-separator) t)))))
599
600 (defun ggtags-project-relative-file (file)
601 "Get file name relative to current project root."
602 (ggtags-check-project)
603 (if (file-name-absolute-p file)
604 (file-relative-name file (if (string-prefix-p (ggtags-current-project-root)
605 file)
606 (ggtags-current-project-root)
607 (locate-dominating-file file "GTAGS")))
608 file))
609
610 (defun ggtags-project-file-p (file)
611 "Return non-nil if FILE is part of current project."
612 (when (ggtags-find-project)
613 (with-temp-buffer
614 (ggtags-with-current-project
615 (process-file (ggtags-program-path "global") nil t nil
616 "-vP" (concat "^" (ggtags-project-relative-file file) "$")))
617 (goto-char (point-min))
618 (not (re-search-forward "^file not found" nil t)))))
619
620 (defun ggtags-create-tags (root)
621 "Create tag files (e.g. GTAGS) in directory ROOT.
622 If file .globalrc or gtags.conf exists in ROOT, it will be used
623 as configuration file per `ggtags-use-project-gtagsconf'.
624
625 If file gtags.files exists in ROOT, it should be a list of source
626 files to index, which can be used to speed gtags up in large
627 source trees. See Info node `(global)gtags' for details."
628 (interactive "DRoot directory: ")
629 (let ((process-environment process-environment))
630 (when (zerop (length root)) (error "No root directory provided"))
631 (setenv "GTAGSROOT" (ggtags-ensure-localname
632 (expand-file-name
633 (directory-file-name (file-name-as-directory root)))))
634 (ggtags-with-current-project
635 (let ((conf (and ggtags-use-project-gtagsconf
636 (cl-loop for name in '(".globalrc" "gtags.conf")
637 for full = (expand-file-name name root)
638 thereis (and (file-exists-p full) full)))))
639 (unless (or conf (getenv "GTAGSLABEL")
640 (not (yes-or-no-p "Use `ctags' backend? ")))
641 (setenv "GTAGSLABEL" "ctags"))
642 (ggtags-with-temp-message "`gtags' in progress..."
643 (let ((default-directory (file-name-as-directory root))
644 (args (cl-remove-if #'null
645 (list (and ggtags-use-idutils "--idutils")
646 (and conf "--gtagsconf")
647 (and conf (ggtags-ensure-localname conf))))))
648 (condition-case err
649 (apply #'ggtags-process-string "gtags" args)
650 (error (if (and ggtags-use-idutils
651 (stringp (cadr err))
652 (string-match-p "mkid not found" (cadr err)))
653 ;; Retry without mkid
654 (apply #'ggtags-process-string
655 "gtags" (cl-remove "--idutils" args))
656 (signal (car err) (cdr err)))))))))
657 (message "GTAGS generated in `%s'" root)
658 root))
659
660 (defun ggtags-update-tags (&optional force)
661 "Update GNU Global tag database.
662 Do nothing if GTAGS exceeds the oversize limit unless FORCE."
663 (interactive (progn
664 (ggtags-check-project)
665 ;; Mark project info expired.
666 (setf (ggtags-project-timestamp (ggtags-find-project)) -1)
667 (list t)))
668 (when (or force (and (ggtags-find-project)
669 (not (ggtags-project-oversize-p))
670 (ggtags-project-dirty-p (ggtags-find-project))))
671 (ggtags-with-current-project
672 (ggtags-with-temp-message "`global -u' in progress..."
673 (ggtags-process-string "global" "-u")
674 (setf (ggtags-project-dirty-p (ggtags-find-project)) nil)
675 (setf (ggtags-project-mtime (ggtags-find-project)) (float-time))))))
676
677 (defun ggtags-update-tags-single (file &optional nowait)
678 (cl-check-type file string)
679 (ggtags-with-current-project
680 (process-file (ggtags-program-path "global") nil (and nowait 0) nil
681 "--single-update" (ggtags-project-relative-file file))))
682
683 (defun ggtags-delete-tags ()
684 "Delete file GTAGS, GRTAGS, GPATH, ID etc. generated by gtags."
685 (interactive (ignore (ggtags-check-project)))
686 (when (ggtags-current-project-root)
687 (let* ((re (concat "\\`" (regexp-opt '("GPATH" "GRTAGS" "GTAGS" "ID")) "\\'"))
688 (files (cl-remove-if-not
689 (lambda (file)
690 ;; Don't trust `directory-files'.
691 (let ((case-fold-search nil))
692 (string-match-p re (file-name-nondirectory file))))
693 (directory-files (ggtags-current-project-root) t re)))
694 (buffer "*GTags File List*"))
695 (or files (user-error "No tag files found"))
696 (with-output-to-temp-buffer buffer
697 (princ (mapconcat #'identity files "\n")))
698 (let ((win (get-buffer-window buffer)))
699 (unwind-protect
700 (progn
701 (fit-window-to-buffer win)
702 (when (yes-or-no-p "Remove GNU Global tag files? ")
703 (with-demoted-errors (mapc #'delete-file files))
704 (remhash (ggtags-current-project-root) ggtags-projects)
705 (and (overlayp ggtags-highlight-tag-overlay)
706 (delete-overlay ggtags-highlight-tag-overlay))))
707 (when (window-live-p win)
708 (quit-window t win)))))))
709
710 (defvar-local ggtags-completion-cache nil)
711
712 ;; See global/libutil/char.c
713 ;; (defconst ggtags-regexp-metachars "[][$()*+.?\\{}|^]")
714 (defvar ggtags-completion-flag "") ;internal use
715
716 (defvar ggtags-completion-table
717 (completion-table-dynamic
718 (lambda (prefix)
719 (let ((cache-key (concat prefix "$" ggtags-completion-flag)))
720 (unless (equal cache-key (car ggtags-completion-cache))
721 (setq ggtags-completion-cache
722 (cons cache-key
723 (ignore-errors-unless-debug
724 ;; May throw global: only name char is allowed
725 ;; with -c option.
726 (ggtags-with-current-project
727 (split-string
728 (apply #'ggtags-process-string
729 "global"
730 (append (and completion-ignore-case '("--ignore-case"))
731 ;; Note -c alone returns only definitions
732 (list (concat "-c" ggtags-completion-flag) prefix)))
733 "\n" t)))))))
734 (cdr ggtags-completion-cache))))
735
736 (defun ggtags-completion-at-point ()
737 "A function for `completion-at-point-functions'."
738 (pcase (funcall ggtags-bounds-of-tag-function)
739 (`(,beg . ,end)
740 (and (< beg end) (list beg end ggtags-completion-table)))))
741
742 (defun ggtags-read-tag (&optional type confirm prompt require-match default)
743 (ggtags-ensure-project)
744 (let ((default (or default (ggtags-tag-at-point)))
745 (prompt (or prompt (capitalize (symbol-name (or type 'tag)))))
746 (ggtags-completion-flag (pcase type
747 (`(or nil definition) "T")
748 (`symbol "s")
749 (`reference "r")
750 (`id "I")
751 (`path "P")
752 ((pred stringp) type)
753 (_ ggtags-completion-flag))))
754 (setq ggtags-current-tag-name
755 (cond (confirm
756 (ggtags-update-tags)
757 (completing-read
758 (format (if default "%s (default %s): " "%s: ") prompt default)
759 ggtags-completion-table nil require-match nil nil default))
760 (default (substring-no-properties default))
761 (t (ggtags-read-tag type t prompt require-match default))))))
762
763 (defun ggtags-global-build-command (cmd &rest args)
764 ;; CMD can be definition, reference, symbol, grep, idutils
765 (let ((xs (append (list (shell-quote-argument (ggtags-program-path "global"))
766 "-v"
767 (format "--result=%s" ggtags-global-output-format)
768 (and ggtags-global-ignore-case "--ignore-case")
769 (and ggtags-global-use-color
770 (ggtags-find-project)
771 (ggtags-project-has-color (ggtags-find-project))
772 "--color=always")
773 (and (ggtags-find-project)
774 (ggtags-project-has-path-style (ggtags-find-project))
775 "--path-style=shorter")
776 (and ggtags-global-treat-text "--other")
777 (pcase cmd
778 ((pred stringp) cmd)
779 (`definition "") ;-d not supported by Global 5.7.1
780 (`reference "-r")
781 (`symbol "-s")
782 (`path "--path")
783 (`grep "--grep")
784 (`idutils "--idutils")))
785 args)))
786 (mapconcat #'identity (delq nil xs) " ")))
787
788 ;; Can be three values: nil, t and a marker; t means start marker has
789 ;; been saved in the tag ring.
790 (defvar ggtags-global-start-marker nil)
791 (defvar ggtags-tag-ring-index nil)
792 (defvar ggtags-global-search-history nil)
793
794 (defvar ggtags-auto-jump-to-match-target nil)
795
796 (defvar-local ggtags-global-exit-info nil) ; (EXIT-STATUS COUNT DB)
797
798 (defun ggtags-global-save-start-marker ()
799 (when (markerp ggtags-global-start-marker)
800 (setq ggtags-tag-ring-index nil)
801 (ring-insert find-tag-marker-ring ggtags-global-start-marker)
802 (setq ggtags-global-start-marker t)))
803
804 (defun ggtags-global-start (command &optional directory)
805 (let* ((default-directory (or directory (ggtags-current-project-root)))
806 (split-window-preferred-function ggtags-split-window-function)
807 (env ggtags-process-environment))
808 (unless (markerp ggtags-global-start-marker)
809 (setq ggtags-global-start-marker (point-marker)))
810 (setq ggtags-auto-jump-to-match-target
811 (nth 4 (assoc (ggtags-global-search-id command default-directory)
812 ggtags-global-search-history)))
813 (ggtags-navigation-mode +1)
814 (ggtags-update-tags)
815 (ggtags-with-current-project
816 (with-current-buffer (with-display-buffer-no-window
817 (compilation-start command 'ggtags-global-mode))
818 (setq-local ggtags-process-environment env)
819 (setq ggtags-global-last-buffer (current-buffer))))))
820
821 (defun ggtags-find-tag-continue ()
822 (interactive)
823 (ggtags-ensure-global-buffer
824 (ggtags-navigation-mode +1)
825 (let ((split-window-preferred-function ggtags-split-window-function))
826 (ignore-errors (compilation-next-error 1))
827 (compile-goto-error))))
828
829 (defun ggtags-find-tag (cmd &rest args)
830 (ggtags-check-project)
831 (ggtags-global-start (apply #'ggtags-global-build-command cmd args)))
832
833 (defun ggtags-include-file ()
834 "Calculate the include file based on `ggtags-include-pattern'."
835 (pcase ggtags-include-pattern
836 (`nil nil)
837 ((pred functionp)
838 (funcall ggtags-include-pattern))
839 (`(,re . ,sub)
840 (save-excursion
841 (beginning-of-line)
842 (and (looking-at re) (match-string sub))))
843 (_ (warn "Invalid value for `ggtags-include-pattern': %s"
844 ggtags-include-pattern)
845 nil)))
846
847 ;;;###autoload
848 (defun ggtags-find-tag-dwim (name &optional what)
849 "Find NAME by context.
850 If point is at a definition tag, find references, and vice versa.
851 If point is at a line that matches `ggtags-include-pattern', find
852 the include file instead.
853
854 When called interactively with a prefix arg, always find
855 definition tags."
856 (interactive
857 (let ((include (and (not current-prefix-arg) (ggtags-include-file))))
858 (ggtags-ensure-project)
859 (if include (list include 'include)
860 (list (ggtags-read-tag 'definition current-prefix-arg)
861 (and current-prefix-arg 'definition)))))
862 (ggtags-check-project) ; For `ggtags-current-project-root' below.
863 (cond
864 ((eq what 'include)
865 (ggtags-find-file name))
866 ((or (eq what 'definition)
867 (not buffer-file-name)
868 (and (ggtags-find-project)
869 (not (ggtags-project-has-refs (ggtags-find-project))))
870 (not (ggtags-project-file-p buffer-file-name)))
871 (ggtags-find-tag 'definition (shell-quote-argument name)))
872 (t (ggtags-find-tag (format "--from-here=%d:%s"
873 (line-number-at-pos)
874 (shell-quote-argument
875 ;; Note `ggtags-global-start' binds
876 ;; default-directory to project root.
877 (ggtags-project-relative-file buffer-file-name)))
878 (shell-quote-argument name)))))
879
880 (defun ggtags-setup-libpath-search (type name)
881 (pcase (ggtags-get-libpath)
882 ((and libs (guard libs))
883 (cl-labels ((cont (buf how)
884 (pcase ggtags-global-exit-info
885 (`(0 0 ,_)
886 (with-temp-buffer
887 (setq default-directory
888 (file-name-as-directory (pop libs)))
889 (and libs (setq ggtags-global-continuation #'cont))
890 (if (ggtags-find-project)
891 (ggtags-find-tag type (shell-quote-argument name))
892 (cont buf how))))
893 (_ (ggtags-global-handle-exit buf how)))))
894 (setq ggtags-global-continuation #'cont)))))
895
896 (defun ggtags-find-reference (name)
897 (interactive (list (ggtags-read-tag 'reference current-prefix-arg)))
898 (ggtags-setup-libpath-search 'reference name)
899 (ggtags-find-tag 'reference (shell-quote-argument name)))
900
901 (defun ggtags-find-other-symbol (name)
902 "Find tag NAME that is a reference without a definition."
903 (interactive (list (ggtags-read-tag 'symbol current-prefix-arg)))
904 (ggtags-setup-libpath-search 'symbol name)
905 (ggtags-find-tag 'symbol (shell-quote-argument name)))
906
907 (defun ggtags-quote-pattern (pattern)
908 (prin1-to-string (substring-no-properties pattern)))
909
910 (defun ggtags-idutils-query (pattern)
911 (interactive (list (ggtags-read-tag 'id t)))
912 (ggtags-find-tag 'idutils "--" (ggtags-quote-pattern pattern)))
913
914 (defun ggtags-grep (pattern &optional invert-match)
915 "Grep for lines matching PATTERN.
916 Invert the match when called with a prefix arg \\[universal-argument]."
917 (interactive (list (ggtags-read-tag 'definition 'confirm
918 (if current-prefix-arg
919 "Inverted grep pattern" "Grep pattern"))
920 current-prefix-arg))
921 (ggtags-find-tag 'grep (and invert-match "--invert-match")
922 "--" (ggtags-quote-pattern pattern)))
923
924 (defun ggtags-find-file (pattern &optional invert-match)
925 (interactive (list (ggtags-read-tag 'path 'confirm (if current-prefix-arg
926 "Inverted path pattern"
927 "Path pattern")
928 nil (thing-at-point 'filename))
929 current-prefix-arg))
930 (let ((ggtags-global-output-format 'path))
931 (ggtags-find-tag 'path (and invert-match "--invert-match")
932 "--" (ggtags-quote-pattern pattern))))
933
934 ;; NOTE: Coloured output in grep requested: http://goo.gl/Y9IcX
935 (defun ggtags-find-tag-regexp (regexp directory)
936 "List tags matching REGEXP in DIRECTORY (default to project root).
937 When called interactively with a prefix, ask for the directory."
938 (interactive
939 (progn
940 (ggtags-check-project)
941 (list (ggtags-read-tag "" t "POSIX regexp")
942 (if current-prefix-arg
943 (read-directory-name "Directory: " nil nil t)
944 (ggtags-current-project-root)))))
945 (ggtags-check-project)
946 (ggtags-global-start
947 (ggtags-global-build-command nil nil "-l" "--" (ggtags-quote-pattern regexp))
948 (file-name-as-directory directory)))
949
950 (defvar ggtags-navigation-mode)
951
952 (defun ggtags-query-replace (from to &optional delimited)
953 "Query replace FROM with TO on files in the Global buffer.
954 If not in navigation mode, do a grep on FROM first.
955
956 Note: the regular expression FROM must be supported by both
957 Global and Emacs."
958 (interactive
959 ;; Note: in 24.4 query-replace-read-args returns a list of 4 elements.
960 (let ((args (query-replace-read-args "Query replace (regexp)" t t)))
961 (list (nth 0 args) (nth 1 args) (nth 2 args))))
962 (unless ggtags-navigation-mode
963 (let ((ggtags-auto-jump-to-match nil))
964 (ggtags-grep from)))
965 (let ((file-form
966 '(let ((files))
967 (ggtags-ensure-global-buffer
968 (ggtags-with-temp-message "Waiting for Grep to finish..."
969 (while (get-buffer-process (current-buffer))
970 (sit-for 0.2)))
971 (goto-char (point-min))
972 (while (ignore-errors (compilation-next-file 1) t)
973 (let ((m (get-text-property (point) 'compilation-message)))
974 (push (expand-file-name
975 (caar (compilation--loc->file-struct
976 (compilation--message->loc m))))
977 files))))
978 (ggtags-navigation-mode -1)
979 (nreverse files))))
980 (tags-query-replace from to delimited file-form)))
981
982 (defun ggtags-global-search-id (cmd directory)
983 (sha1 (concat directory (make-string 1 0) cmd)))
984
985 (defun ggtags-global-current-search ()
986 ;; CMD DIR ENV LINE TEXT
987 (ggtags-ensure-global-buffer
988 (list (car compilation-arguments)
989 default-directory
990 ggtags-process-environment
991 (line-number-at-pos)
992 (buffer-substring-no-properties
993 (line-beginning-position) (line-end-position)))))
994
995 (defun ggtags-global-rerun-search-1 (data)
996 (pcase data
997 (`(,cmd ,dir ,env ,line ,_text)
998 (with-current-buffer (let ((ggtags-auto-jump-to-match nil)
999 ;; Switch current project to DIR.
1000 (default-directory dir)
1001 (ggtags-project-root dir)
1002 (ggtags-process-environment env))
1003 (ggtags-global-start cmd dir))
1004 (add-hook 'compilation-finish-functions
1005 (lambda (buf _msg)
1006 (with-current-buffer buf
1007 (ggtags-forward-to-line line)
1008 (compile-goto-error)))
1009 nil t)))))
1010
1011 (defvar-local ggtags-global-search-ewoc nil)
1012 (defvar ggtags-global-rerun-search-last nil)
1013
1014 (defvar ggtags-global-rerun-search-map
1015 (cl-labels
1016 ((save ()
1017 (setq ggtags-global-rerun-search-last
1018 (ewoc-data (ewoc-locate ggtags-global-search-ewoc))))
1019 (next (arg)
1020 (interactive "p")
1021 (ewoc-goto-next ggtags-global-search-ewoc arg)
1022 (save))
1023 (prev (arg)
1024 (interactive "p")
1025 (ewoc-goto-prev ggtags-global-search-ewoc arg)
1026 (save))
1027 (quit ()
1028 (interactive)
1029 (quit-windows-on (ewoc-buffer ggtags-global-search-ewoc) t))
1030 (done ()
1031 (interactive)
1032 (let ((node (ewoc-locate ggtags-global-search-ewoc)))
1033 (when node
1034 (save)
1035 (quit)
1036 (ggtags-global-rerun-search-1 (cdr (ewoc-data node)))))))
1037 (let ((m (make-sparse-keymap)))
1038 (set-keymap-parent m special-mode-map)
1039 (define-key m "p" #'prev)
1040 (define-key m "\M-p" #'prev)
1041 (define-key m "n" #'next)
1042 (define-key m "\M-n" #'next)
1043 (define-key m "r" #'ggtags-save-to-register)
1044 (define-key m "q" #'quit)
1045 (define-key m "\r" #'done)
1046 m)))
1047
1048 (defvar bookmark-make-record-function)
1049
1050 (defun ggtags-global-rerun-search ()
1051 "Pop up a buffer to choose a past search to re-run.
1052
1053 \\{ggtags-global-rerun-search-map}"
1054 (interactive)
1055 (or ggtags-global-search-history (user-error "No search history"))
1056 (let ((split-window-preferred-function ggtags-split-window-function)
1057 (inhibit-read-only t))
1058 (pop-to-buffer "*Ggtags Search History*")
1059 (erase-buffer)
1060 (special-mode)
1061 (use-local-map ggtags-global-rerun-search-map)
1062 (setq-local ggtags-enable-navigation-keys nil)
1063 (setq-local bookmark-make-record-function #'ggtags-make-bookmark-record)
1064 (setq truncate-lines t)
1065 (cl-labels ((prop (s) (propertize s 'face 'minibuffer-prompt))
1066 (pp (data)
1067 (pcase data
1068 (`(,_id ,cmd ,dir ,_env ,line ,text)
1069 (insert (prop " cmd: ") cmd "\n"
1070 (prop " dir: ") dir "\n"
1071 (prop "line: ") (number-to-string line) "\n"
1072 (prop "text: ") text "\n"
1073 (propertize (make-string 32 ?-) 'face 'shadow))))))
1074 (setq ggtags-global-search-ewoc
1075 (ewoc-create #'pp "Global search history keys: n:next p:prev r:register RET:choose\n")))
1076 (dolist (data ggtags-global-search-history)
1077 (ewoc-enter-last ggtags-global-search-ewoc data))
1078 (and ggtags-global-rerun-search-last
1079 (re-search-forward (cadr ggtags-global-rerun-search-last) nil t)
1080 (ewoc-goto-node ggtags-global-search-ewoc
1081 (ewoc-locate ggtags-global-search-ewoc)))
1082 (set-buffer-modified-p nil)
1083 (fit-window-to-buffer nil (floor (frame-height) 2))))
1084
1085 (defun ggtags-save-to-register (r)
1086 "Save current search session to register R.
1087 Use \\[jump-to-register] to restore the search session."
1088 (interactive (list (register-read-with-preview "Save search to register: ")))
1089 (cl-labels ((prn (data)
1090 (pcase data
1091 (`(,command ,root ,_env ,line ,_)
1092 (princ (format "a ggtags search session `%s' in directory `%s' at line %d."
1093 command root line))))))
1094 (set-register r (registerv-make
1095 (if ggtags-global-search-ewoc
1096 (cdr (ewoc-data (ewoc-locate ggtags-global-search-ewoc)))
1097 (ggtags-global-current-search))
1098 :jump-func #'ggtags-global-rerun-search-1
1099 :print-func #'prn))))
1100
1101 (defun ggtags-make-bookmark-record ()
1102 `(,(and ggtags-current-tag-name (format "*ggtags %s*" ggtags-current-tag-name))
1103 (ggtags-search . ,(if ggtags-global-search-ewoc
1104 (cdr (ewoc-data (ewoc-locate ggtags-global-search-ewoc)))
1105 (ggtags-global-current-search)))
1106 (handler . ggtags-bookmark-jump)))
1107
1108 (declare-function bookmark-prop-get "bookmark")
1109
1110 (defun ggtags-bookmark-jump (bmk)
1111 (ggtags-global-rerun-search-1 (bookmark-prop-get bmk 'ggtags-search)))
1112
1113 (defun ggtags-browse-file-as-hypertext (file line)
1114 "Browse FILE in hypertext (HTML) form."
1115 (interactive (if (or current-prefix-arg (not buffer-file-name))
1116 (list (read-file-name "Browse file: " nil nil t)
1117 (read-number "Line: " 1))
1118 (list buffer-file-name (line-number-at-pos))))
1119 (cl-check-type line (integer 1))
1120 (or (and file (file-exists-p file)) (error "File `%s' doesn't exist" file))
1121 (ggtags-check-project)
1122 (or (file-exists-p (expand-file-name "HTML" (ggtags-current-project-root)))
1123 (if (yes-or-no-p "No hypertext form exists; run htags? ")
1124 (let ((default-directory (ggtags-current-project-root)))
1125 (ggtags-with-current-project (ggtags-process-string "htags")))
1126 (user-error "Aborted")))
1127 (let ((url (ggtags-process-string "gozilla" "-p" (format "+%d" line)
1128 (file-relative-name file))))
1129 (or (equal (file-name-extension
1130 (url-filename (url-generic-parse-url url))) "html")
1131 (user-error "No hypertext form for `%s'" file))
1132 (when (called-interactively-p 'interactive)
1133 (message "Browsing %s" url))
1134 (browse-url url)))
1135
1136 (defun ggtags-next-mark (&optional arg)
1137 "Move to the next (newer) mark in the tag marker ring."
1138 (interactive)
1139 (and (ring-empty-p find-tag-marker-ring) (user-error "Tag ring empty"))
1140 (setq ggtags-tag-ring-index
1141 ;; Note `ring-minus1' gets newer item.
1142 (funcall (if arg #'ring-plus1 #'ring-minus1)
1143 (or ggtags-tag-ring-index
1144 (progn
1145 (ring-insert find-tag-marker-ring (point-marker))
1146 0))
1147 (ring-length find-tag-marker-ring)))
1148 (let ((m (ring-ref find-tag-marker-ring ggtags-tag-ring-index))
1149 (i (- (ring-length find-tag-marker-ring) ggtags-tag-ring-index)))
1150 (ggtags-echo "%d%s marker%s" i (pcase (mod i 10)
1151 ;; ` required for 24.1 and 24.2
1152 (`1 "st")
1153 (`2 "nd")
1154 (`3 "rd")
1155 (_ "th"))
1156 (if (marker-buffer m) "" " (dead)"))
1157 (if (not (marker-buffer m))
1158 (ding)
1159 (switch-to-buffer (marker-buffer m))
1160 (goto-char m))))
1161
1162 (defun ggtags-prev-mark ()
1163 "Move to the previous (older) mark in the tag marker ring."
1164 (interactive)
1165 (ggtags-next-mark 'previous))
1166
1167 (defvar ggtags-view-tag-history-mode-map
1168 (let ((m (make-sparse-keymap)))
1169 (define-key m "\M-n" 'next-error-no-select)
1170 (define-key m "\M-p" 'previous-error-no-select)
1171 (define-key m "q" (lambda () (interactive) (quit-window t)))
1172 m))
1173
1174 (define-derived-mode ggtags-view-tag-history-mode tabulated-list-mode "TagHist"
1175 :abbrev-table nil :group 'ggtags)
1176
1177 (defun ggtags-view-tag-history ()
1178 "Pop to a buffer listing visited locations from newest to oldest.
1179 The buffer is a next error buffer and works with standard
1180 commands `next-error' and `previous-error'.
1181
1182 \\{ggtags-view-tag-history-mode-map}"
1183 (interactive)
1184 (and (ring-empty-p find-tag-marker-ring)
1185 (user-error "Tag ring empty"))
1186 (let ((split-window-preferred-function ggtags-split-window-function)
1187 (inhibit-read-only t))
1188 (pop-to-buffer "*Tag Ring*")
1189 (erase-buffer)
1190 (ggtags-view-tag-history-mode)
1191 (setq next-error-function #'ggtags-view-tag-history-next-error
1192 next-error-last-buffer (current-buffer))
1193 (setq tabulated-list-entries
1194 ;; Use a function so that revert can work properly.
1195 (lambda ()
1196 (let ((counter (ring-length find-tag-marker-ring))
1197 (elements (or (ring-elements find-tag-marker-ring)
1198 (user-error "Tag ring empty")))
1199 (action (lambda (_button) (next-error 0)))
1200 (get-line (lambda (m)
1201 (with-current-buffer (marker-buffer m)
1202 (save-excursion
1203 (goto-char m)
1204 (buffer-substring (line-beginning-position)
1205 (line-end-position)))))))
1206 (setq tabulated-list-format
1207 `[("ID" ,(max (1+ (floor (log counter 10))) 2)
1208 car-less-than-car)
1209 ("Buffer" ,(max (cl-loop for m in elements
1210 for b = (marker-buffer m)
1211 maximize
1212 (length (and b (buffer-name b))))
1213 6)
1214 t :right-align t)
1215 ("Position" ,(max (cl-loop for m in elements
1216 for p = (or (marker-position m) 1)
1217 maximize (1+ (floor (log p 10))))
1218 8)
1219 (lambda (x y)
1220 (< (string-to-number (aref (cadr x) 2))
1221 (string-to-number (aref (cadr y) 2))))
1222 :right-align t)
1223 ("Contents" 100 t)])
1224 (tabulated-list-init-header)
1225 (mapcar (lambda (x)
1226 (prog1
1227 (list counter
1228 (if (marker-buffer x)
1229 (vector (number-to-string counter)
1230 `(,(buffer-name (marker-buffer x))
1231 face link
1232 follow-link t
1233 marker ,x
1234 action ,action)
1235 (number-to-string (marker-position x))
1236 (funcall get-line x))
1237 (vector (number-to-string counter)
1238 "(dead)" "?" "?")))
1239 (cl-decf counter)))
1240 elements))))
1241 (setq tabulated-list-sort-key '("ID" . t))
1242 (tabulated-list-print)
1243 (fit-window-to-buffer nil (floor (frame-height) 2))))
1244
1245 (defun ggtags-view-tag-history-next-error (&optional arg reset)
1246 (if (not reset)
1247 (forward-button arg)
1248 (goto-char (point-min))
1249 (forward-button (if (button-at (point)) 0 1)))
1250 (when (get-buffer-window)
1251 (set-window-point (get-buffer-window) (point)))
1252 (pcase (button-get (button-at (point)) 'marker)
1253 ((and (pred markerp) m)
1254 (if (eq (get-buffer-window) (selected-window))
1255 (pop-to-buffer (marker-buffer m))
1256 (switch-to-buffer (marker-buffer m)))
1257 (goto-char (marker-position m)))
1258 (_ (error "Dead marker"))))
1259
1260 (defun ggtags-global-exit-message-1 ()
1261 "Get the total of matches and db file used."
1262 (save-excursion
1263 (goto-char (point-max))
1264 (if (re-search-backward
1265 "^\\w+ \\(not found\\)\\|^\\([0-9]+\\) \\w+ located" nil t)
1266 (cons (or (and (match-string 1) 0)
1267 (string-to-number (match-string 2)))
1268 (when (re-search-forward
1269 "using \\(?:\\(idutils\\)\\|'[^']*/\\(\\w+\\)'\\)"
1270 (line-end-position)
1271 t)
1272 (or (and (match-string 1) "ID")
1273 (match-string 2))))
1274 (cons 0 nil))))
1275
1276 (defun ggtags-global-exit-message-function (_process-status exit-status msg)
1277 "A function for `compilation-exit-message-function'."
1278 (pcase (ggtags-global-exit-message-1)
1279 (`(,count . ,db)
1280 (setq ggtags-global-exit-info (list exit-status count db))
1281 ;; Clear the start marker in case of zero matches.
1282 (and (zerop count)
1283 (markerp ggtags-global-start-marker)
1284 (not ggtags-global-continuation)
1285 (setq ggtags-global-start-marker nil))
1286 (cons (if (> exit-status 0)
1287 msg
1288 (format "found %d %s" count
1289 (funcall (if (= count 1) #'car #'cadr)
1290 (pcase db
1291 ;; ` required for 24.1 and 24.2
1292 (`"GTAGS" '("definition" "definitions"))
1293 (`"GSYMS" '("symbol" "symbols"))
1294 (`"GRTAGS" '("reference" "references"))
1295 (`"GPATH" '("file" "files"))
1296 (`"ID" '("identifier" "identifiers"))
1297 (_ '("match" "matches"))))))
1298 exit-status))))
1299
1300 (defun ggtags-global-column (start)
1301 ;; START is the beginning position of source text.
1302 (let ((mbeg (text-property-any start (line-end-position) 'global-color t)))
1303 (and mbeg (- mbeg start))))
1304
1305 ;;; NOTE: Must not match the 'Global started at Mon Jun 3 10:24:13'
1306 ;;; line or `compilation-auto-jump' will jump there and fail. See
1307 ;;; comments before the 'gnu' entry in
1308 ;;; `compilation-error-regexp-alist-alist'.
1309 (defvar ggtags-global-error-regexp-alist-alist
1310 (append
1311 `((path "^\\(?:[^\"'\n]*/\\)?[^ )\t\n]+$" 0)
1312 ;; ACTIVE_ESCAPE src/dialog.cc 172
1313 (ctags "^\\([^ \t\n]+\\)[ \t]+\\(.*?\\)[ \t]+\\([0-9]+\\)$"
1314 2 3 nil nil 2 (1 font-lock-function-name-face))
1315 ;; ACTIVE_ESCAPE 172 src/dialog.cc #undef ACTIVE_ESCAPE
1316 (ctags-x "^\\([^ \t\n]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(\\(?:[^/\n]*/\\)?[^ \t\n]+\\)"
1317 3 2 (,(lambda () (ggtags-global-column (1+ (match-end 0)))))
1318 nil 3 (1 font-lock-function-name-face))
1319 ;; src/dialog.cc:172:#undef ACTIVE_ESCAPE
1320 (grep "^\\(.+?\\):\\([0-9]+\\):\\(?:$\\|[^0-9\n]\\|[0-9][^0-9\n]\\|[0-9][0-9].\\)"
1321 1 2 (,(lambda () (ggtags-global-column (1+ (match-end 2))))) nil 1)
1322 ;; src/dialog.cc ACTIVE_ESCAPE 172 #undef ACTIVE_ESCAPE
1323 (cscope "^\\(.+?\\)[ \t]+\\([^ \t\n]+\\)[ \t]+\\([0-9]+\\).*\\(?:[^0-9\n]\\|[^0-9\n][0-9]\\|[^:\n][0-9][0-9]\\)$"
1324 1 3 nil nil 1 (2 font-lock-function-name-face)))
1325 compilation-error-regexp-alist-alist))
1326
1327 (defun ggtags-abbreviate-file (start end)
1328 (let ((inhibit-read-only t)
1329 (amount (if (numberp ggtags-global-abbreviate-filename)
1330 (- (- end start) ggtags-global-abbreviate-filename)
1331 999))
1332 (advance-word (lambda ()
1333 "Return the length of the text made invisible."
1334 (let ((wend (min end (progn (forward-word 1) (point))))
1335 (wbeg (max start (progn (backward-word 1) (point)))))
1336 (goto-char wend)
1337 (if (<= (- wend wbeg) 1)
1338 0
1339 (put-text-property (1+ wbeg) wend 'invisible t)
1340 (1- (- wend wbeg)))))))
1341 (goto-char start)
1342 (while (and (> amount 0) (> end (point)))
1343 (cl-decf amount (funcall advance-word)))))
1344
1345 (defun ggtags-abbreviate-files (start end)
1346 (goto-char start)
1347 (let* ((error-re (cdr (assq (car compilation-error-regexp-alist)
1348 ggtags-global-error-regexp-alist-alist)))
1349 (sub (cadr error-re)))
1350 (when (and ggtags-global-abbreviate-filename error-re)
1351 (while (re-search-forward (car error-re) end t)
1352 (when (and (or (not (numberp ggtags-global-abbreviate-filename))
1353 (> (length (match-string sub))
1354 ggtags-global-abbreviate-filename))
1355 ;; Ignore bogus file lines such as:
1356 ;; Global found 2 matches at Thu Jan 31 13:45:19
1357 (get-text-property (match-beginning sub) 'compilation-message))
1358 (ggtags-abbreviate-file (match-beginning sub) (match-end sub)))))))
1359
1360 (defvar-local ggtags-global-output-lines 0)
1361
1362 (defun ggtags-global--display-buffer (&optional buffer desired-point)
1363 (pcase (let ((buffer (or buffer (current-buffer)))
1364 (split-window-preferred-function ggtags-split-window-function))
1365 (and (not (get-buffer-window buffer))
1366 (display-buffer buffer '(nil (allow-no-window . t)))))
1367 ((and (pred windowp) w)
1368 (with-selected-window w
1369 (compilation-set-window-height w)
1370 (and desired-point (goto-char desired-point))))))
1371
1372 (defun ggtags-global-filter ()
1373 "Called from `compilation-filter-hook' (which see)."
1374 (let ((ansi-color-apply-face-function
1375 (lambda (beg end face)
1376 (when face
1377 (ansi-color-apply-overlay-face beg end face)
1378 (put-text-property beg end 'global-color t)))))
1379 (ansi-color-apply-on-region compilation-filter-start (point)))
1380 ;; Get rid of line "Using config file '/PATH/TO/.globalrc'." or
1381 ;; "Using default configuration."
1382 (when (re-search-backward
1383 "^ *Using \\(?:config file '.*\\|default configuration.\\)\n"
1384 compilation-filter-start t)
1385 (replace-match ""))
1386 (cl-incf ggtags-global-output-lines
1387 (count-lines compilation-filter-start (point)))
1388 ;; If the number of output lines is small
1389 ;; `ggtags-global-handle-exit' takes care of displaying the buffer.
1390 (when (and (> ggtags-global-output-lines 30) ggtags-navigation-mode)
1391 (ggtags-global--display-buffer nil (or compilation-current-error (point-min))))
1392 (when (and (eq ggtags-auto-jump-to-match 'history)
1393 (numberp ggtags-auto-jump-to-match-target)
1394 (not compilation-current-error)
1395 ;; `ggtags-global-output-lines' is imprecise but use it
1396 ;; as first approximation.
1397 (> (+ 10 ggtags-global-output-lines) ggtags-auto-jump-to-match-target)
1398 (> (line-number-at-pos (point-max))
1399 ggtags-auto-jump-to-match-target))
1400 (ggtags-forward-to-line ggtags-auto-jump-to-match-target)
1401 (setq-local ggtags-auto-jump-to-match-target nil)
1402 ;;
1403 ;; Can't call `compile-goto-error' here becuase
1404 ;; `compilation-filter' restores point and as a result commands
1405 ;; dependent on point such as `ggtags-navigation-next-file' and
1406 ;; `ggtags-navigation-previous-file' fail to work.
1407 (run-with-idle-timer 0 nil (lambda (buf pt)
1408 (and (buffer-live-p buf)
1409 (with-current-buffer buf
1410 (ggtags-delay-finish-functions
1411 (let ((compilation-auto-jump-to-first-error t))
1412 (with-display-buffer-no-window
1413 (compilation-auto-jump buf pt)))))))
1414 (current-buffer) (point)))
1415 (make-local-variable 'ggtags-global-large-output)
1416 (when (> ggtags-global-output-lines ggtags-global-large-output)
1417 (cl-incf ggtags-global-large-output 500)
1418 (ggtags-echo "Output %d lines (Type `C-c C-k' to cancel)"
1419 ggtags-global-output-lines)))
1420
1421 (defun ggtags-global-handle-exit (buf how)
1422 "A function for `compilation-finish-functions' (which see)."
1423 (cond
1424 (ggtags-global-continuation
1425 (let ((cont (prog1 ggtags-global-continuation
1426 (setq ggtags-global-continuation nil))))
1427 (funcall cont buf how)))
1428 ((string-prefix-p "exited abnormally" how)
1429 ;; If exit abnormally display the buffer for inspection.
1430 (ggtags-global--display-buffer))
1431 (ggtags-auto-jump-to-match
1432 (if (pcase (compilation-next-single-property-change
1433 (point-min) 'compilation-message)
1434 ((and pt (guard pt))
1435 (compilation-next-single-property-change
1436 (save-excursion (goto-char pt) (end-of-line) (point))
1437 'compilation-message)))
1438 ;; There are multiple matches so pop up the buffer.
1439 (ggtags-global--display-buffer)
1440 ;; For the `compilation-auto-jump' in idle timer to run.
1441 ;; See also: http://debbugs.gnu.org/13829
1442 (sit-for 0)
1443 (ggtags-navigation-mode -1)
1444 (ggtags-navigation-mode-cleanup buf 0)))))
1445
1446 (defvar ggtags-global-mode-font-lock-keywords
1447 '(("^Global \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
1448 (1 'compilation-error)
1449 (2 'compilation-error nil t))
1450 ("^Global found \\([0-9]+\\)" (1 compilation-info-face))))
1451
1452 (defvar compilation-always-kill) ;new in 24.3
1453
1454 (define-compilation-mode ggtags-global-mode "Global"
1455 "A mode for showing outputs from gnu global."
1456 ;; Note: Place `ggtags-global-output-format' as first element for
1457 ;; `ggtags-abbreviate-files'.
1458 (setq-local compilation-error-regexp-alist (list ggtags-global-output-format))
1459 (pcase ggtags-auto-jump-to-match
1460 (`history (make-local-variable 'ggtags-auto-jump-to-match-target)
1461 (setq-local compilation-auto-jump-to-first-error
1462 (not ggtags-auto-jump-to-match-target)))
1463 (`nil (setq-local compilation-auto-jump-to-first-error nil))
1464 (_ (setq-local compilation-auto-jump-to-first-error t)))
1465 (setq-local compilation-scroll-output nil)
1466 ;; See `compilation-move-to-column' for details.
1467 (setq-local compilation-first-column 0)
1468 (setq-local compilation-error-screen-columns nil)
1469 (setq-local compilation-disable-input t)
1470 (setq-local compilation-always-kill t)
1471 (setq-local compilation-error-face 'compilation-info)
1472 (setq-local compilation-exit-message-function
1473 'ggtags-global-exit-message-function)
1474 ;; See: https://github.com/leoliu/ggtags/issues/26
1475 (setq-local find-file-suppress-same-file-warnings t)
1476 (setq-local truncate-lines t)
1477 (jit-lock-register #'ggtags-abbreviate-files)
1478 (add-hook 'compilation-filter-hook 'ggtags-global-filter nil 'local)
1479 (add-hook 'compilation-finish-functions 'ggtags-global-handle-exit nil t)
1480 (setq-local bookmark-make-record-function #'ggtags-make-bookmark-record)
1481 (setq-local ggtags-enable-navigation-keys nil)
1482 (add-hook 'kill-buffer-hook (lambda () (ggtags-navigation-mode -1)) nil t))
1483
1484 ;; NOTE: Need this to avoid putting menu items in
1485 ;; `emulation-mode-map-alists', which creates double entries. See
1486 ;; http://i.imgur.com/VJJTzVc.png
1487 (defvar ggtags-navigation-map
1488 (let ((map (make-sparse-keymap)))
1489 (define-key map "\M-n" 'next-error)
1490 (define-key map "\M-p" 'previous-error)
1491 (define-key map "\M-}" 'ggtags-navigation-next-file)
1492 (define-key map "\M-{" 'ggtags-navigation-previous-file)
1493 (define-key map "\M->" 'ggtags-navigation-last-error)
1494 (define-key map "\M-<" 'first-error)
1495 ;; Note: shadows `isearch-forward-regexp' but it can be invoked
1496 ;; with C-u C-s instead.
1497 (define-key map "\C-\M-s" 'ggtags-navigation-isearch-forward)
1498 (define-key map "\C-c\C-k"
1499 (lambda () (interactive)
1500 (ggtags-ensure-global-buffer (kill-compilation))))
1501 (define-key map "\M-o" 'ggtags-navigation-visible-mode)
1502 (define-key map [return] 'ggtags-navigation-mode-done)
1503 (define-key map "\r" 'ggtags-navigation-mode-done)
1504 (define-key map [remap pop-tag-mark] 'ggtags-navigation-mode-abort)
1505 map))
1506
1507 (defvar ggtags-mode-map-alist
1508 `((ggtags-enable-navigation-keys . ,ggtags-navigation-map)))
1509
1510 (defvar ggtags-navigation-mode-map
1511 (let ((map (make-sparse-keymap))
1512 (menu (make-sparse-keymap "GG-Navigation")))
1513 ;; Menu items: (info "(elisp)Extended Menu Items")
1514 (define-key map [menu-bar ggtags-navigation] (cons "GG-Navigation" menu))
1515 ;; Ordered backwards
1516 (define-key menu [visible-mode]
1517 '(menu-item "Visible mode" ggtags-navigation-visible-mode
1518 :button (:toggle . (ignore-errors
1519 (ggtags-ensure-global-buffer
1520 visible-mode)))))
1521 (define-key menu [done]
1522 '(menu-item "Finish navigation" ggtags-navigation-mode-done))
1523 (define-key menu [abort]
1524 '(menu-item "Abort" ggtags-navigation-mode-abort))
1525 (define-key menu [last-match]
1526 '(menu-item "Last match" ggtags-navigation-last-error))
1527 (define-key menu [first-match] '(menu-item "First match" first-error))
1528 (define-key menu [previous-file]
1529 '(menu-item "Previous file" ggtags-navigation-previous-file))
1530 (define-key menu [next-file]
1531 '(menu-item "Next file" ggtags-navigation-next-file))
1532 (define-key menu [isearch-forward]
1533 '(menu-item "Find match with isearch" ggtags-navigation-isearch-forward))
1534 (define-key menu [previous]
1535 '(menu-item "Previous match" previous-error))
1536 (define-key menu [next]
1537 '(menu-item "Next match" next-error))
1538 map))
1539
1540 (defun ggtags-move-to-tag (&optional name)
1541 "Move to NAME tag in current line."
1542 (let ((tag (or name ggtags-current-tag-name)))
1543 ;; Do nothing if on the tag already i.e. by `ggtags-global-column'.
1544 (unless (or (not tag) (looking-at (concat (regexp-quote tag) "\\_>")))
1545 (let ((orig (point))
1546 (regexps (mapcar (lambda (fmtstr)
1547 (format fmtstr (regexp-quote tag)))
1548 '("\\_<%s\\_>" "%s\\_>" "%s"))))
1549 (beginning-of-line)
1550 (if (cl-loop for re in regexps
1551 ;; Note: tag might not agree with current
1552 ;; major-mode's symbol, so try harder. For
1553 ;; example, in `php-mode' $cacheBackend is a
1554 ;; symbol, but cacheBackend is a tag.
1555 thereis (re-search-forward re (line-end-position) t))
1556 (goto-char (match-beginning 0))
1557 (goto-char orig))))))
1558
1559 (defun ggtags-navigation-mode-cleanup (&optional buf time)
1560 (let ((buf (or buf ggtags-global-last-buffer)))
1561 (and (buffer-live-p buf)
1562 (with-current-buffer buf
1563 (when (get-buffer-process (current-buffer))
1564 (kill-compilation))
1565 (when (and (derived-mode-p 'ggtags-global-mode)
1566 (get-buffer-window))
1567 (quit-windows-on (current-buffer)))
1568 (and time (run-with-idle-timer time nil #'kill-buffer buf))))))
1569
1570 (defun ggtags-navigation-mode-done ()
1571 (interactive)
1572 (ggtags-navigation-mode -1)
1573 (setq tags-loop-scan t
1574 tags-loop-operate '(ggtags-find-tag-continue))
1575 (ggtags-navigation-mode-cleanup))
1576
1577 (defun ggtags-navigation-mode-abort ()
1578 "Abort navigation and return to where the search was started."
1579 (interactive)
1580 (ggtags-navigation-mode -1)
1581 (ggtags-navigation-mode-cleanup nil 0)
1582 ;; Run after (ggtags-navigation-mode -1) or
1583 ;; ggtags-global-start-marker might not have been saved.
1584 (when (and ggtags-global-start-marker
1585 (not (markerp ggtags-global-start-marker)))
1586 (setq ggtags-global-start-marker nil)
1587 (pop-tag-mark)))
1588
1589 (defun ggtags-navigation-next-file (n)
1590 (interactive "p")
1591 (ggtags-ensure-global-buffer
1592 (compilation-next-file n)
1593 (compile-goto-error)))
1594
1595 (defun ggtags-navigation-previous-file (n)
1596 (interactive "p")
1597 (ggtags-navigation-next-file (- n)))
1598
1599 (defun ggtags-navigation-last-error ()
1600 (interactive)
1601 (ggtags-ensure-global-buffer
1602 (goto-char (point-max))
1603 (compilation-previous-error 1)
1604 (compile-goto-error)))
1605
1606 (defun ggtags-navigation-isearch-forward (&optional regexp-p)
1607 (interactive "P")
1608 (ggtags-ensure-global-buffer
1609 (let ((saved (if visible-mode 1 -1)))
1610 (visible-mode 1)
1611 (with-selected-window (get-buffer-window (current-buffer))
1612 (isearch-forward regexp-p)
1613 (beginning-of-line)
1614 (visible-mode saved)
1615 (compile-goto-error)))))
1616
1617 (defun ggtags-navigation-visible-mode (&optional arg)
1618 (interactive (list (or current-prefix-arg 'toggle)))
1619 (ggtags-ensure-global-buffer
1620 (visible-mode arg)))
1621
1622 (defvar ggtags-global-line-overlay nil)
1623
1624 (defun ggtags-global-next-error-function ()
1625 (when (eq next-error-last-buffer ggtags-global-last-buffer)
1626 (ggtags-move-to-tag)
1627 (ggtags-global-save-start-marker)
1628 (and (ggtags-project-update-mtime-maybe)
1629 (message "File `%s' is newer than GTAGS"
1630 (file-name-nondirectory buffer-file-name)))
1631 (and ggtags-mode-sticky (ggtags-mode 1))
1632 (ignore-errors
1633 (ggtags-ensure-global-buffer
1634 (unless (overlayp ggtags-global-line-overlay)
1635 (setq ggtags-global-line-overlay (make-overlay (point) (point)))
1636 (overlay-put ggtags-global-line-overlay 'face 'ggtags-global-line))
1637 (move-overlay ggtags-global-line-overlay
1638 (line-beginning-position) (line-end-position)
1639 (current-buffer))
1640 ;; Update search history
1641 (let ((id (ggtags-global-search-id (car compilation-arguments)
1642 default-directory)))
1643 (setq ggtags-global-search-history
1644 (cl-remove id ggtags-global-search-history :test #'equal :key #'car))
1645 (add-to-history 'ggtags-global-search-history
1646 (cons id (ggtags-global-current-search))
1647 ggtags-global-history-length))))
1648 (run-hooks 'ggtags-find-tag-hook)))
1649
1650 (put 'ggtags-navigation-mode-lighter 'risky-local-variable t)
1651
1652 (defvar ggtags-navigation-mode-lighter
1653 '(" GG["
1654 (:eval
1655 (if (not (buffer-live-p ggtags-global-last-buffer))
1656 '(:propertize "??" face error help-echo "No Global buffer")
1657 (with-current-buffer ggtags-global-last-buffer
1658 (pcase (or ggtags-global-exit-info '(0 0 ""))
1659 (`(,exit ,count ,db)
1660 `((:propertize ,(pcase db
1661 (`"GTAGS" "D")
1662 (`"GRTAGS" "R")
1663 (`"GSYMS" "S")
1664 (`"GPATH" "F")
1665 (`"ID" "I"))
1666 face success)
1667 (:propertize
1668 ,(pcase (get-text-property (line-beginning-position)
1669 'compilation-message)
1670 (`nil "?")
1671 ;; Assume the first match appears at line 5
1672 (_ (number-to-string (- (line-number-at-pos) 4))))
1673 face success)
1674 "/"
1675 (:propertize ,(number-to-string count) face success)
1676 ,(unless (zerop exit)
1677 `(":" (:propertize ,(number-to-string exit) face error)))))))))
1678 "]")
1679 "Ligher for `ggtags-navigation-mode'; set to nil to disable it.")
1680
1681 (define-minor-mode ggtags-navigation-mode nil
1682 :lighter ggtags-navigation-mode-lighter
1683 :global t
1684 (if ggtags-navigation-mode
1685 (progn
1686 ;; Higher priority for `ggtags-navigation-mode' to avoid being
1687 ;; hijacked by modes such as `view-mode'.
1688 (add-to-list 'emulation-mode-map-alists 'ggtags-mode-map-alist)
1689 (add-hook 'next-error-hook 'ggtags-global-next-error-function)
1690 (add-hook 'minibuffer-setup-hook 'ggtags-minibuffer-setup-function))
1691 (setq emulation-mode-map-alists
1692 (delq 'ggtags-mode-map-alist emulation-mode-map-alists))
1693 (remove-hook 'next-error-hook 'ggtags-global-next-error-function)
1694 (remove-hook 'minibuffer-setup-hook 'ggtags-minibuffer-setup-function)))
1695
1696 (defun ggtags-minibuffer-setup-function ()
1697 ;; Disable ggtags-navigation-mode in minibuffer.
1698 (setq-local ggtags-enable-navigation-keys nil))
1699
1700 (defun ggtags-kill-file-buffers (&optional interactive)
1701 "Kill all buffers visiting files in current project."
1702 (interactive "p")
1703 (ggtags-check-project)
1704 (let ((directories (cons (ggtags-current-project-root) (ggtags-get-libpath)))
1705 (count 0))
1706 (dolist (buf (buffer-list))
1707 (let ((file (and (buffer-live-p buf)
1708 (not (eq buf (current-buffer)))
1709 (buffer-file-name buf))))
1710 (when (and file (cl-some (lambda (dir)
1711 ;; Don't use `file-in-directory-p'
1712 ;; to allow symbolic links.
1713 (string-prefix-p dir file))
1714 directories))
1715 (and (kill-buffer buf) (cl-incf count)))))
1716 (and interactive
1717 (message "%d %s killed" count (if (= count 1) "buffer" "buffers")))))
1718
1719 (defun ggtags-after-save-function ()
1720 (when (ggtags-find-project)
1721 (ggtags-project-update-mtime-maybe)
1722 (and buffer-file-name
1723 (ggtags-update-tags-single buffer-file-name 'nowait))))
1724
1725 (defun ggtags-global-output (buffer cmds callback &optional cutoff)
1726 "Asynchronously pipe the output of running CMDS to BUFFER.
1727 When finished invoke CALLBACK in BUFFER with process exit status."
1728 (or buffer (error "Output buffer required"))
1729 (when (get-buffer-process (get-buffer buffer))
1730 ;; Notice running multiple processes in the same buffer so that we
1731 ;; can fix the caller. See for example `ggtags-eldoc-function'.
1732 (message "Warning: detected %S already running in %S; interrupting..."
1733 (get-buffer-process buffer) buffer)
1734 (interrupt-process (get-buffer-process buffer)))
1735 (let* ((program (car cmds))
1736 (args (cdr cmds))
1737 (cutoff (and cutoff (+ cutoff (if (get-buffer buffer)
1738 (with-current-buffer buffer
1739 (line-number-at-pos (point-max)))
1740 0))))
1741 (proc (apply #'start-file-process program buffer program args))
1742 (filter (lambda (proc string)
1743 (and (buffer-live-p (process-buffer proc))
1744 (with-current-buffer (process-buffer proc)
1745 (goto-char (process-mark proc))
1746 (insert string)
1747 (when (and (> (line-number-at-pos (point-max)) cutoff)
1748 (process-live-p proc))
1749 (interrupt-process (current-buffer)))))))
1750 (sentinel (lambda (proc _msg)
1751 (when (memq (process-status proc) '(exit signal))
1752 (with-current-buffer (process-buffer proc)
1753 (set-process-buffer proc nil)
1754 (funcall callback (process-exit-status proc)))))))
1755 (set-process-query-on-exit-flag proc nil)
1756 (and cutoff (set-process-filter proc filter))
1757 (set-process-sentinel proc sentinel)
1758 proc))
1759
1760 (defun ggtags-get-definition-default (defs)
1761 (and (caar defs)
1762 (concat (caar defs) (and (cdr defs) " [guess]"))))
1763
1764 (defun ggtags-show-definition (name)
1765 (interactive (list (ggtags-read-tag 'definition current-prefix-arg)))
1766 (ggtags-check-project)
1767 (let* ((re (cadr (assq 'grep ggtags-global-error-regexp-alist-alist)))
1768 (current (current-buffer))
1769 (buffer (get-buffer-create " *ggtags-definition*"))
1770 ;; Need these bindings so that let-binding
1771 ;; `ggtags-print-definition-function' can work see
1772 ;; `ggtags-eldoc-function'.
1773 (get-fn ggtags-get-definition-function)
1774 (print-fn ggtags-print-definition-function)
1775 (show (lambda (_status)
1776 (goto-char (point-min))
1777 (let ((defs (cl-loop while (re-search-forward re nil t)
1778 collect (list (buffer-substring (1+ (match-end 2))
1779 (line-end-position))
1780 name
1781 (match-string 1)
1782 (string-to-number (match-string 2))))))
1783 (kill-buffer buffer)
1784 (with-current-buffer current
1785 (funcall print-fn (funcall get-fn defs)))))))
1786 (ggtags-with-current-project
1787 (ggtags-global-output
1788 buffer
1789 (list (ggtags-program-path "global")
1790 "--result=grep" "--path-style=absolute" name)
1791 show 100))))
1792
1793 (defvar ggtags-mode-prefix-map
1794 (let ((m (make-sparse-keymap)))
1795 ;; Globally bound to `M-g p'.
1796 ;; (define-key m "\M-'" 'previous-error)
1797 (define-key m (kbd "M-DEL") 'ggtags-delete-tags)
1798 (define-key m "\M-p" 'ggtags-prev-mark)
1799 (define-key m "\M-n" 'ggtags-next-mark)
1800 (define-key m "\M-f" 'ggtags-find-file)
1801 (define-key m "\M-o" 'ggtags-find-other-symbol)
1802 (define-key m "\M-g" 'ggtags-grep)
1803 (define-key m "\M-i" 'ggtags-idutils-query)
1804 (define-key m "\M-b" 'ggtags-browse-file-as-hypertext)
1805 (define-key m "\M-k" 'ggtags-kill-file-buffers)
1806 (define-key m "\M-h" 'ggtags-view-tag-history)
1807 (define-key m "\M-j" 'ggtags-visit-project-root)
1808 (define-key m "\M-/" 'ggtags-global-rerun-search)
1809 (define-key m (kbd "M-SPC") 'ggtags-save-to-register)
1810 (define-key m (kbd "M-%") 'ggtags-query-replace)
1811 (define-key m "\M-?" 'ggtags-show-definition)
1812 m))
1813
1814 (defvar ggtags-mode-map
1815 (let ((map (make-sparse-keymap))
1816 (menu (make-sparse-keymap "Ggtags")))
1817 (define-key map "\M-." 'ggtags-find-tag-dwim)
1818 (define-key map (kbd "M-]") 'ggtags-find-reference)
1819 (define-key map (kbd "C-M-.") 'ggtags-find-tag-regexp)
1820 (define-key map ggtags-mode-prefix-key ggtags-mode-prefix-map)
1821 ;; Menu items
1822 (define-key map [menu-bar ggtags] (cons "Ggtags" menu))
1823 ;; Ordered backwards
1824 (define-key menu [report-bugs]
1825 `(menu-item "Report bugs"
1826 (lambda () (interactive)
1827 (browse-url ggtags-bug-url)
1828 (message "Please visit %s" ggtags-bug-url))
1829 :help ,(format "Visit %s" ggtags-bug-url)))
1830 (define-key menu [custom-ggtags]
1831 '(menu-item "Customize Ggtags"
1832 (lambda () (interactive) (customize-group 'ggtags))))
1833 (define-key menu [eldoc-mode]
1834 '(menu-item "Toggle eldoc mode" eldoc-mode :button (:toggle . eldoc-mode)))
1835 (define-key menu [save-project]
1836 '(menu-item "Save project settings" ggtags-save-project-settings))
1837 (define-key menu [toggle-read-only]
1838 '(menu-item "Toggle project read-only" ggtags-toggle-project-read-only
1839 :button (:toggle . buffer-read-only)))
1840 (define-key menu [visit-project-root]
1841 '(menu-item "Visit project root" ggtags-visit-project-root))
1842 (define-key menu [sep2] menu-bar-separator)
1843 (define-key menu [browse-hypertext]
1844 '(menu-item "Browse as hypertext" ggtags-browse-file-as-hypertext
1845 :enable (ggtags-find-project)))
1846 (define-key menu [delete-tags]
1847 '(menu-item "Delete tags" ggtags-delete-tags
1848 :enable (ggtags-find-project)
1849 :help "Delete file GTAGS, GRTAGS, GPATH, ID etc."))
1850 (define-key menu [kill-buffers]
1851 '(menu-item "Kill project file buffers" ggtags-kill-file-buffers
1852 :enable (ggtags-find-project)))
1853 (define-key menu [view-tag]
1854 '(menu-item "View tag history" ggtags-view-tag-history))
1855 (define-key menu [pop-mark]
1856 '(menu-item "Pop mark" pop-tag-mark
1857 :help "Pop to previous mark and destroy it"))
1858 (define-key menu [next-mark]
1859 '(menu-item "Next mark" ggtags-next-mark))
1860 (define-key menu [prev-mark]
1861 '(menu-item "Previous mark" ggtags-prev-mark))
1862 (define-key menu [sep1] menu-bar-separator)
1863 (define-key menu [previous-error]
1864 '(menu-item "Previous match" previous-error))
1865 (define-key menu [next-error]
1866 '(menu-item "Next match" next-error))
1867 (define-key menu [rerun-search]
1868 '(menu-item "Re-run past search" ggtags-global-rerun-search))
1869 (define-key menu [save-to-register]
1870 '(menu-item "Save search to register" ggtags-save-to-register))
1871 (define-key menu [find-file]
1872 '(menu-item "Find files" ggtags-find-file))
1873 (define-key menu [query-replace]
1874 '(menu-item "Query replace" ggtags-query-replace))
1875 (define-key menu [idutils]
1876 '(menu-item "Query idutils DB" ggtags-idutils-query))
1877 (define-key menu [grep]
1878 '(menu-item "Grep" ggtags-grep))
1879 (define-key menu [find-symbol]
1880 '(menu-item "Find other symbol" ggtags-find-other-symbol
1881 :help "Find references without definition"))
1882 (define-key menu [find-tag-regexp]
1883 '(menu-item "Find tag matching regexp" ggtags-find-tag-regexp))
1884 (define-key menu [show-definition]
1885 '(menu-item "Show definition" ggtags-show-definition))
1886 (define-key menu [find-reference]
1887 '(menu-item "Find reference" ggtags-find-reference))
1888 (define-key menu [find-tag-continue]
1889 '(menu-item "Continue find tag" tags-loop-continue))
1890 (define-key menu [find-tag]
1891 '(menu-item "Find tag" ggtags-find-tag-dwim))
1892 (define-key menu [update-tags]
1893 '(menu-item "Update tag files" ggtags-update-tags
1894 :visible (ggtags-find-project)))
1895 (define-key menu [run-gtags]
1896 '(menu-item "Run gtags" ggtags-create-tags
1897 :visible (not (ggtags-find-project))))
1898 map))
1899
1900 (defvar ggtags-mode-line-project-keymap
1901 (let ((map (make-sparse-keymap)))
1902 (define-key map [mode-line mouse-1] 'ggtags-visit-project-root)
1903 map))
1904
1905 (put 'ggtags-mode-line-project-name 'risky-local-variable t)
1906 (defvar ggtags-mode-line-project-name
1907 '("[" (:eval (let ((name (if (stringp ggtags-project-root)
1908 (file-name-nondirectory
1909 (directory-file-name ggtags-project-root))
1910 "?")))
1911 (propertize
1912 name 'face compilation-info-face
1913 'help-echo (if (stringp ggtags-project-root)
1914 (concat "mouse-1 to visit " ggtags-project-root)
1915 "mouse-1 to set project")
1916 'mouse-face 'mode-line-highlight
1917 'keymap ggtags-mode-line-project-keymap)))
1918 "]")
1919 "Mode line construct for displaying current project name.
1920 The value is the name of the project root directory. Setting it
1921 to nil disables displaying this information.")
1922
1923 ;;;###autoload
1924 (define-minor-mode ggtags-mode nil
1925 :lighter (:eval (if ggtags-navigation-mode "" " GG"))
1926 (unless (timerp ggtags-highlight-tag-timer)
1927 (setq ggtags-highlight-tag-timer
1928 (run-with-idle-timer
1929 ggtags-highlight-tag-delay t #'ggtags-highlight-tag-at-point)))
1930 (if ggtags-mode
1931 (progn
1932 (add-hook 'after-save-hook 'ggtags-after-save-function nil t)
1933 ;; Append to serve as a fallback method.
1934 (add-hook 'completion-at-point-functions
1935 #'ggtags-completion-at-point t t)
1936 (unless (memq 'ggtags-mode-line-project-name
1937 mode-line-buffer-identification)
1938 (setq mode-line-buffer-identification
1939 (append mode-line-buffer-identification
1940 '(ggtags-mode-line-project-name)))))
1941 (remove-hook 'after-save-hook 'ggtags-after-save-function t)
1942 (remove-hook 'completion-at-point-functions #'ggtags-completion-at-point t)
1943 (setq mode-line-buffer-identification
1944 (delq 'ggtags-mode-line-project-name mode-line-buffer-identification))
1945 (and (overlayp ggtags-highlight-tag-overlay)
1946 (delete-overlay ggtags-highlight-tag-overlay))
1947 (setq ggtags-highlight-tag-overlay nil)))
1948
1949 (defvar ggtags-highlight-tag-map
1950 (let ((map (make-sparse-keymap)))
1951 ;; Bind down- events so that the global keymap won't ``shine
1952 ;; through''. See `mode-line-buffer-identification-keymap' for
1953 ;; similar workaround.
1954 (define-key map [S-mouse-1] 'ggtags-find-tag-dwim)
1955 (define-key map [S-down-mouse-1] 'ignore)
1956 (define-key map [S-mouse-3] 'ggtags-find-reference)
1957 (define-key map [S-down-mouse-3] 'ignore)
1958 map)
1959 "Keymap used for valid tag at point.")
1960
1961 (put 'ggtags-active-tag 'face 'ggtags-highlight)
1962 (put 'ggtags-active-tag 'keymap ggtags-highlight-tag-map)
1963 ;; (put 'ggtags-active-tag 'mouse-face 'match)
1964 (put 'ggtags-active-tag 'help-echo
1965 "S-mouse-1 for definitions\nS-mouse-3 for references")
1966
1967 (defun ggtags-highlight-tag-at-point ()
1968 (when (and ggtags-mode ggtags-project-root (ggtags-find-project))
1969 (unless (overlayp ggtags-highlight-tag-overlay)
1970 (setq ggtags-highlight-tag-overlay (make-overlay (point) (point) nil t))
1971 (overlay-put ggtags-highlight-tag-overlay 'modification-hooks
1972 (list (lambda (o after &rest _args)
1973 (and (not after) (delete-overlay o))))))
1974 (let ((bounds (funcall ggtags-bounds-of-tag-function))
1975 (o ggtags-highlight-tag-overlay))
1976 (cond
1977 ((and bounds
1978 (eq (overlay-buffer o) (current-buffer))
1979 (= (overlay-start o) (car bounds))
1980 (= (overlay-end o) (cdr bounds)))
1981 ;; Overlay matches current tag so do nothing.
1982 nil)
1983 ((and bounds (let ((completion-ignore-case nil))
1984 (test-completion
1985 (buffer-substring (car bounds) (cdr bounds))
1986 ggtags-completion-table)))
1987 (move-overlay o (car bounds) (cdr bounds) (current-buffer))
1988 (overlay-put o 'category 'ggtags-active-tag))
1989 (t (move-overlay o
1990 (or (car bounds) (point))
1991 (or (cdr bounds) (point))
1992 (current-buffer))
1993 (overlay-put o 'category nil))))))
1994
1995 ;;; eldoc
1996
1997 (defvar-local ggtags-eldoc-cache nil)
1998
1999 (declare-function eldoc-message "eldoc")
2000 (defun ggtags-eldoc-function ()
2001 "A function suitable for `eldoc-documentation-function' (which see)."
2002 (pcase (ggtags-tag-at-point)
2003 (`nil nil)
2004 (tag (if (equal tag (car ggtags-eldoc-cache))
2005 (cadr ggtags-eldoc-cache)
2006 (and ggtags-project-root (ggtags-find-project)
2007 (let* ((ggtags-print-definition-function
2008 (lambda (s)
2009 (setq ggtags-eldoc-cache (list tag s))
2010 (eldoc-message s))))
2011 ;; Prevent multiple runs of ggtags-show-definition
2012 ;; for the same tag.
2013 (setq ggtags-eldoc-cache (list tag))
2014 (ggtags-show-definition tag)
2015 nil))))))
2016
2017 ;;; imenu
2018
2019 (defun ggtags-goto-imenu-index (name line &rest _args)
2020 (ggtags-forward-to-line line)
2021 (ggtags-move-to-tag name))
2022
2023 ;;;###autoload
2024 (defun ggtags-build-imenu-index ()
2025 "A function suitable for `imenu-create-index-function'."
2026 (let ((file (and buffer-file-name (file-relative-name buffer-file-name))))
2027 (and file (with-temp-buffer
2028 (when (with-demoted-errors
2029 (zerop (ggtags-with-current-project
2030 (process-file (ggtags-program-path "global")
2031 nil t nil "-x" "-f" file))))
2032 (goto-char (point-min))
2033 (cl-loop while (re-search-forward
2034 "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)" nil t)
2035 collect (list (match-string 1)
2036 (string-to-number (match-string 2))
2037 'ggtags-goto-imenu-index)))))))
2038
2039 ;;; hippie-expand
2040
2041 ;;;###autoload
2042 (defun ggtags-try-complete-tag (old)
2043 "A function suitable for `hippie-expand-try-functions-list'."
2044 (eval-and-compile (require 'hippie-exp))
2045 (unless old
2046 (he-init-string (or (car (funcall ggtags-bounds-of-tag-function)) (point))
2047 (point))
2048 (setq he-expand-list
2049 (and (not (equal he-search-string ""))
2050 (ggtags-find-project)
2051 (sort (all-completions he-search-string
2052 ggtags-completion-table)
2053 #'string-lessp))))
2054 (if (null he-expand-list)
2055 (progn
2056 (if old (he-reset-string))
2057 nil)
2058 (he-substitute-string (car he-expand-list))
2059 (setq he-expand-list (cdr he-expand-list))
2060 t))
2061
2062 (defun ggtags-reload (&optional force)
2063 (interactive "P")
2064 (unload-feature 'ggtags force)
2065 (require 'ggtags))
2066
2067 (provide 'ggtags)
2068 ;;; ggtags.el ends here