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