Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-ctags.el
blob3fd4a48b8ce3d2064fc49bea5627019b37bfa0c6
1 ;;; org-ctags.el - Integrate Emacs "tags" facility with org mode.
2 ;;
3 ;; Copyright (C) 2007-2016 Free Software Foundation, Inc.
5 ;; Author: Paul Sexton <eeeickythump@gmail.com>
8 ;; Keywords: org, wp
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs 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.
17 ;; GNU Emacs 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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; Synopsis
27 ;; ========
29 ;; Allows org-mode to make use of the Emacs `etags' system. Defines tag
30 ;; destinations in org-mode files as any text between <<double angled
31 ;; brackets>>. This allows the tags-generation program `exuberant ctags' to
32 ;; parse these files and create tag tables that record where these
33 ;; destinations are found. Plain [[links]] in org mode files which do not have
34 ;; <<matching destinations>> within the same file will then be interpreted as
35 ;; links to these 'tagged' destinations, allowing seamless navigation between
36 ;; multiple org-mode files. Topics can be created in any org mode file and
37 ;; will always be found by plain links from other files. Other file types
38 ;; recognized by ctags (source code files, latex files, etc) will also be
39 ;; available as destinations for plain links, and similarly, org-mode links
40 ;; will be available as tags from source files. Finally, the function
41 ;; `org-ctags-find-tag-interactive' lets you choose any known tag, using
42 ;; autocompletion, and quickly jump to it.
44 ;; Installation
45 ;; ============
47 ;; Install org mode
48 ;; Ensure org-ctags.el is somewhere in your emacs load path.
49 ;; Download and install Exuberant ctags -- "http://ctags.sourceforge.net/"
50 ;; Edit your .emacs file (see next section) and load emacs.
52 ;; To put in your init file (.emacs):
53 ;; ==================================
55 ;; Assuming you already have org mode installed and set up:
57 ;; (setq org-ctags-path-to-ctags "/path/to/ctags/executable")
58 ;; (add-hook 'org-mode-hook
59 ;; (lambda ()
60 ;; (define-key org-mode-map "\C-co" 'org-ctags-find-tag-interactive)))
62 ;; By default, with org-ctags loaded, org will first try and visit the tag
63 ;; with the same name as the link; then, if unsuccessful, ask the user if
64 ;; he/she wants to rebuild the 'TAGS' database and try again; then ask if
65 ;; the user wishes to append 'tag' as a new toplevel heading at the end of
66 ;; the buffer; and finally, defer to org's default behavior which is to
67 ;; search the entire text of the current buffer for 'tag'.
69 ;; This behavior can be modified by changing the value of
70 ;; ORG-CTAGS-OPEN-LINK-FUNCTIONS. For example I have the following in my
71 ;; .emacs, which describes the same behavior as the above paragraph with
72 ;; one difference:
74 ;; (setq org-ctags-open-link-functions
75 ;; '(org-ctags-find-tag
76 ;; org-ctags-ask-rebuild-tags-file-then-find-tag
77 ;; org-ctags-ask-append-topic
78 ;; org-ctags-fail-silently)) ; <-- prevents org default behavior
81 ;; Usage
82 ;; =====
84 ;; When you click on a link "[[foo]]" and org cannot find a matching "<<foo>>"
85 ;; in the current buffer, the tags facility will take over. The file TAGS in
86 ;; the active directory is examined to see if the tags facility knows about
87 ;; "<<foo>>" in any other files. If it does, the matching file will be opened
88 ;; and the cursor will jump to the position of "<<foo>>" in that file.
90 ;; User-visible functions:
91 ;; - `org-ctags-find-tag-interactive': type a tag (plain link) name and visit
92 ;; it. With autocompletion. Bound to ctrl-O in the above setup.
93 ;; - All the etags functions should work. These include:
95 ;; M-. `find-tag' -- finds the tag at point
97 ;; C-M-. find-tag based on regular expression
99 ;; M-x tags-search RET -- like C-M-. but searches through ENTIRE TEXT
100 ;; of ALL the files referenced in the TAGS file. A quick way to
101 ;; search through an entire 'project'.
103 ;; M-* "go back" from a tag jump. Like `org-mark-ring-goto'.
104 ;; You may need to bind this key yourself with (eg)
105 ;; (global-set-key (kbd "<M-kp-multiply>") 'pop-tag-mark)
107 ;; (see etags chapter in Emacs manual for more)
110 ;; Keeping the TAGS file up to date
111 ;; ================================
113 ;; Tags mode has no way of knowing that you have created new tags by typing in
114 ;; your org-mode buffer. New tags make it into the TAGS file in 3 ways:
116 ;; 1. You re-run (org-ctags-create-tags "directory") to rebuild the file.
117 ;; 2. You put the function `org-ctags-ask-rebuild-tags-file-then-find-tag' in
118 ;; your `org-open-link-functions' list, as is done in the setup
119 ;; above. This will cause the TAGS file to be rebuilt whenever a link
120 ;; cannot be found. This may be slow with large file collections however.
121 ;; 3. You run the following from the command line (all 1 line):
123 ;; ctags --langdef=orgmode --langmap=orgmode:.org
124 ;; --regex-orgmode="/<<([^>]+)>>/\1/d,definition/"
125 ;; -f /your/path/TAGS -e -R /your/path/*.org
127 ;; If you are paranoid, you might want to run (org-ctags-create-tags
128 ;; "/path/to/org/files") at startup, by including the following toplevel form
129 ;; in .emacs. However this can cause a pause of several seconds if ctags has
130 ;; to scan lots of files.
132 ;; (progn
133 ;; (message "-- rebuilding tags tables...")
134 ;; (mapc 'org-ctags-create-tags tags-table-list))
136 ;;; Code:
138 (eval-when-compile (require 'cl))
140 (require 'org)
142 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
144 (defgroup org-ctags nil
145 "Options concerning use of ctags within org mode."
146 :tag "Org-Ctags"
147 :group 'org-link)
149 (defvar org-ctags-enabled-p t
150 "Activate ctags support in org mode?")
152 (defvar org-ctags-tag-regexp "/<<([^>]+)>>/\\1/d,definition/"
153 "Regexp expression used by ctags external program.
154 The regexp matches tag destinations in org-mode files.
155 Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/
156 See the ctags documentation for more information.")
158 (defcustom org-ctags-path-to-ctags
159 (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
160 "Name of the ctags executable file."
161 :group 'org-ctags
162 :version "24.1"
163 :type 'file)
165 (defcustom org-ctags-open-link-functions
166 '(org-ctags-find-tag
167 org-ctags-ask-rebuild-tags-file-then-find-tag
168 org-ctags-ask-append-topic)
169 "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active."
170 :group 'org-ctags
171 :version "24.1"
172 :type 'hook
173 :options '(org-ctags-find-tag
174 org-ctags-ask-rebuild-tags-file-then-find-tag
175 org-ctags-rebuild-tags-file-then-find-tag
176 org-ctags-ask-append-topic
177 org-ctags-append-topic
178 org-ctags-ask-visit-buffer-or-file
179 org-ctags-visit-buffer-or-file
180 org-ctags-fail-silently))
183 (defvar org-ctags-tag-list nil
184 "List of all tags in the active TAGS file.
185 Created as a local variable in each buffer.")
187 (defcustom org-ctags-new-topic-template
188 "* <<%t>>\n\n\n\n\n\n"
189 "Text to insert when creating a new org file via opening a hyperlink.
190 The following patterns are replaced in the string:
191 `%t' - replaced with the capitalized title of the hyperlink"
192 :group 'org-ctags
193 :version "24.1"
194 :type 'string)
197 (add-hook 'org-mode-hook
198 (lambda ()
199 (when (and org-ctags-enabled-p
200 (buffer-file-name))
201 ;; Make sure this file's directory is added to default
202 ;; directories in which to search for tags.
203 (let ((tags-filename
204 (expand-file-name
205 (concat (file-name-directory (buffer-file-name))
206 "/TAGS"))))
207 (when (file-exists-p tags-filename)
208 (visit-tags-table tags-filename))))))
211 (defadvice visit-tags-table (after org-ctags-load-tag-list activate compile)
212 (when (and org-ctags-enabled-p tags-file-name)
213 (setq-local org-ctags-tag-list
214 (org-ctags-all-tags-in-current-tags-table))))
217 (defun org-ctags-enable ()
218 (put 'org-mode 'find-tag-default-function 'org-ctags-find-tag-at-point)
219 (setq org-ctags-enabled-p t)
220 (dolist (fn org-ctags-open-link-functions)
221 (add-hook 'org-open-link-functions fn t)))
224 ;;; General utility functions. ===============================================
225 ;; These work outside org-ctags mode.
227 (defun org-ctags-get-filename-for-tag (tag)
228 "TAG is a string. Search the active TAGS file for a matching tag.
229 If the tag is found, return a list containing the filename, line number, and
230 buffer position where the tag is found."
231 (interactive "sTag: ")
232 (unless tags-file-name
233 (call-interactively (visit-tags-table)))
234 (save-excursion
235 (visit-tags-table-buffer 'same)
236 (when tags-file-name
237 (with-current-buffer (get-file-buffer tags-file-name)
238 (goto-char (point-min))
239 (cond
240 ((re-search-forward (format "^.*\x7f%s\x01\\([0-9]+\\),\\([0-9]+\\)$"
241 (regexp-quote tag)) nil t)
242 (let ((line (string-to-number (match-string 1)))
243 (pos (string-to-number (match-string 2))))
244 (cond
245 ((re-search-backward "\f\n\\(.*\\),[0-9]+\n")
246 (list (match-string 1) line pos))
247 (t ; can't find a file name preceding the matched
248 ; tag??
249 (error "Malformed TAGS file: %s" (buffer-name))))))
250 (t ; tag not found
251 nil))))))
254 (defun org-ctags-all-tags-in-current-tags-table ()
255 "Read all tags defined in the active TAGS file, into a list of strings.
256 Return the list."
257 (interactive)
258 (let ((taglist nil))
259 (unless tags-file-name
260 (call-interactively (visit-tags-table)))
261 (save-excursion
262 (visit-tags-table-buffer 'same)
263 (with-current-buffer (get-file-buffer tags-file-name)
264 (goto-char (point-min))
265 (while (re-search-forward "^.*\x7f\\(.*\\)\x01\\([0-9]+\\),\\([0-9]+\\)$"
266 nil t)
267 (push (substring-no-properties (match-string 1)) taglist)))
268 taglist)))
271 (defun org-ctags-string-search-and-replace (search replace string)
272 "Replace all instances of SEARCH with REPLACE in STRING."
273 (replace-regexp-in-string (regexp-quote search) replace string t t))
276 ;;; Internal functions =======================================================
279 (defun org-ctags-open-file (name &optional title)
280 "Visit or create a file called `NAME.org', and insert a new topic.
281 The new topic will be titled NAME (or TITLE if supplied)."
282 (interactive "sFile name: ")
283 (let ((filename (substitute-in-file-name (expand-file-name name))))
284 (condition-case v
285 (progn
286 (org-open-file name t)
287 (message "Opened file OK")
288 (goto-char (point-max))
289 (insert (org-ctags-string-search-and-replace
290 "%t" (capitalize (or title name))
291 org-ctags-new-topic-template))
292 (message "Inserted new file text OK")
293 (org-mode-restart))
294 (error (error "Error %S in org-ctags-open-file" v)))))
297 ;;;; Misc interoperability with etags system =================================
300 (defadvice xref-find-definitions
301 (before org-ctags-set-org-mark-before-finding-tag activate compile)
302 "Before trying to find a tag, save our current position on org mark ring."
303 (save-excursion
304 (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
305 (org-mark-ring-push))))
309 (defun org-ctags-find-tag-at-point ()
310 "Determine default tag to search for, based on text at point.
311 If there is no plausible default, return nil."
312 (let (from to bound)
313 (when (or (ignore-errors
314 ;; Look for hyperlink around `point'.
315 (save-excursion
316 (search-backward "[[") (setq from (+ 2 (point))))
317 (save-excursion
318 (goto-char from)
319 (search-forward "]") (setq to (- (point) 1)))
320 (and (> to from) (>= (point) from) (<= (point) to)))
321 (progn
322 ;; Look at text around `point'.
323 (save-excursion
324 (skip-syntax-backward "w_") (setq from (point)))
325 (save-excursion
326 (skip-syntax-forward "w_") (setq to (point)))
327 (> to from))
328 ;; Look between `line-beginning-position' and `point'.
329 (save-excursion
330 (and (setq bound (line-beginning-position))
331 (skip-syntax-backward "^w_" bound)
332 (> (setq to (point)) bound)
333 (skip-syntax-backward "w_")
334 (setq from (point))))
335 ;; Look between `point' and `line-end-position'.
336 (save-excursion
337 (and (setq bound (line-end-position))
338 (skip-syntax-forward "^w_" bound)
339 (< (setq from (point)) bound)
340 (skip-syntax-forward "w_")
341 (setq to (point)))))
342 (buffer-substring-no-properties from to))))
345 ;;; Functions for use with 'org-open-link-functions' hook =================
348 (defun org-ctags-find-tag (name)
349 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
350 Look for a tag called `NAME' in the current TAGS table. If it is found,
351 visit the file and location where the tag is found."
352 (interactive "sTag: ")
353 (let ((old-buf (current-buffer))
354 (old-pnt (point-marker))
355 (old-mark (copy-marker (mark-marker))))
356 (condition-case nil
357 (progn (xref-find-definitions name)
359 (error
360 ;; only restore old location if find-tag raises error
361 (set-buffer old-buf)
362 (goto-char old-pnt)
363 (set-marker (mark-marker) old-mark)
364 nil))))
367 (defun org-ctags-visit-buffer-or-file (name &optional create)
368 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
369 Visit buffer named `NAME.org'. If there is no such buffer, visit the file
370 with the same name if it exists. If the file does not exist, then behavior
371 depends on the value of CREATE.
373 If CREATE is nil (default), then return nil. Do not create a new file.
374 If CREATE is t, create the new file and visit it.
375 If CREATE is the symbol `ask', then ask the user if they wish to create
376 the new file."
377 (interactive)
378 (let ((filename (concat (substitute-in-file-name
379 (expand-file-name name))
380 ".org")))
381 (cond
382 ((get-buffer (concat name ".org"))
383 ;; Buffer is already open
384 (org-pop-to-buffer-same-window (get-buffer (concat name ".org"))))
385 ((file-exists-p filename)
386 ;; File exists but is not open --> open it
387 (message "Opening existing org file `%S'..."
388 filename)
389 (org-open-file filename t))
390 ((or (eql create t)
391 (and (eql create 'ask)
392 (y-or-n-p (format-message
393 "File `%s.org' not found; create?" name))))
394 (org-ctags-open-file filename name))
395 (t ;; File does not exist, and we don't want to create it.
396 nil))))
399 (defun org-ctags-ask-visit-buffer-or-file (name)
400 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
401 Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
402 asked before creating a new file."
403 (org-ctags-visit-buffer-or-file name 'ask))
406 (defun org-ctags-append-topic (name &optional narrowp)
407 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
408 Append a new toplevel heading to the end of the current buffer. The
409 heading contains NAME surrounded by <<angular brackets>>, thus making
410 the heading a destination for the tag `NAME'."
411 (interactive "sTopic: ")
412 (widen)
413 (goto-char (point-max))
414 (newline 2)
415 (message "Adding topic in buffer %s" (buffer-name))
416 (insert (org-ctags-string-search-and-replace
417 "%t" (capitalize name) org-ctags-new-topic-template))
418 (backward-char 4)
419 (org-update-radio-target-regexp)
420 (end-of-line)
421 (forward-line 2)
422 (when narrowp
423 ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
424 (org-narrow-to-subtree))
428 (defun org-ctags-ask-append-topic (name &optional narrowp)
429 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
430 Wrapper for org-ctags-append-topic, which first asks the user if they want
431 to append a new topic."
432 (if (y-or-n-p (format-message
433 "Topic `%s' not found; append to end of buffer?" name))
434 (org-ctags-append-topic name narrowp)
435 nil))
438 (defun org-ctags-rebuild-tags-file-then-find-tag (name)
439 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
440 Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
441 to rebuild (update) the TAGS file."
442 (unless tags-file-name
443 (call-interactively (visit-tags-table)))
444 (when (buffer-file-name)
445 (org-ctags-create-tags))
446 (org-ctags-find-tag name))
449 (defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
450 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
451 Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
452 (if (and (buffer-file-name)
453 (y-or-n-p
454 (format-message
455 "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
456 name
457 (file-name-directory (buffer-file-name)))))
458 (org-ctags-rebuild-tags-file-then-find-tag name)
459 nil))
462 (defun org-ctags-fail-silently (name)
463 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
464 Put as the last function in the list if you want to prevent org's default
465 behavior of free text search."
469 ;;; User-visible functions ===================================================
472 (defun org-ctags-create-tags (&optional directory-name)
473 "(Re)create tags file in the directory of the active buffer.
474 The file will contain tag definitions for all the files in the
475 directory and its subdirectories which are recognized by ctags.
476 This will include files ending in `.org' as well as most other
477 source files (.C, .H, .EL, .LISP, etc). All the resulting tags
478 end up in one file, called TAGS, located in the directory. This
479 function may take several seconds to finish if the directory or
480 its subdirectories contain large numbers of taggable files."
481 (interactive)
482 (assert (buffer-file-name))
483 (let ((dir-name (or directory-name
484 (file-name-directory (buffer-file-name))))
485 (exitcode nil))
486 (save-excursion
487 (setq exitcode
488 (shell-command
489 (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
490 "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
491 org-ctags-path-to-ctags
492 org-ctags-tag-regexp
493 (expand-file-name (concat dir-name "/TAGS"))
494 (expand-file-name (concat dir-name "/*")))))
495 (cond
496 ((eql 0 exitcode)
497 (setq-local org-ctags-tag-list
498 (org-ctags-all-tags-in-current-tags-table)))
500 ;; This seems to behave differently on Linux, so just ignore
501 ;; error codes for now
502 ;;(error "Calling ctags executable resulted in error code: %s"
503 ;; exitcode)
504 nil)))))
507 (defvar org-ctags-find-tag-history nil
508 "History of tags visited by org-ctags-find-tag-interactive.")
510 (defun org-ctags-find-tag-interactive ()
511 "Prompt for the name of a tag, with autocompletion, then visit the named tag.
512 Uses `ido-mode' if available.
513 If the user enters a string that does not match an existing tag, create
514 a new topic."
515 (interactive)
516 (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
517 'ido-completing-read
518 'completing-read))
519 (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
520 nil 'confirm nil 'org-ctags-find-tag-history)))
521 (when tag
522 (cond
523 ((member tag org-ctags-tag-list)
524 ;; Existing tag
525 (push tag org-ctags-find-tag-history)
526 (xref-find-definitions tag))
528 ;; New tag
529 (run-hook-with-args-until-success
530 'org-open-link-functions tag))))))
533 (org-ctags-enable)
535 (provide 'org-ctags)
537 ;;; org-ctags.el ends here