]> code.delx.au - gnu-emacs/blob - lisp/org/org-ctags.el
Merge from trunk.
[gnu-emacs] / lisp / org / org-ctags.el
1 ;;; org-ctags.el - Integrate Emacs "tags" facility with org mode.
2 ;;
3 ;; Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 ;; Author: Paul Sexton <eeeickythump@gmail.com>
6 ;; Version: 7.7
7
8 ;; Keywords: org, wp
9 ;; Version: 7.7
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
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.
17
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.
22
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/>.
25
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.
52
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'.
103 ;;
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)
107 ;;
108 ;; (see etags chapter in Emacs manual for more)
109 ;;
110 ;;
111 ;; Keeping the TAGS file up to date
112 ;; ================================
113 ;;
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:
116 ;;
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):
123 ;;
124 ;; ctags --langdef=orgmode --langmap=orgmode:.org
125 ;; --regex-orgmode="/<<([^>]+)>>/\1/d,definition/"
126 ;; -f /your/path/TAGS -e -R /your/path/*.org
127 ;;
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.
132 ;;
133 ;; (progn
134 ;; (message "-- rebuilding tags tables...")
135 ;; (mapc 'org-create-tags tags-table-list))
136
137 ;;; Code:
138
139 (eval-when-compile (require 'cl))
140
141 (require 'org)
142
143 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
144
145 (defgroup org-ctags nil
146 "Options concerning use of ctags within org mode."
147 :tag "Org-Ctags"
148 :group 'org-link)
149
150 (defvar org-ctags-enabled-p t
151 "Activate ctags support in org mode?")
152
153 (defvar org-ctags-tag-regexp "/<<([^>]+)>>/\\1/d,definition/"
154 "Regexp expression used by ctags external program.
155 The regexp matches tag destinations in org-mode files.
156 Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/
157 See the ctags documentation for more information.")
158
159 (defcustom org-ctags-path-to-ctags
160 (case system-type
161 (windows-nt "ctags.exe")
162 (darwin "ctags-exuberant")
163 (t "ctags-exuberant"))
164 "Full path to the ctags executable file."
165 :group 'org-ctags
166 :type 'file)
167
168 (defcustom org-ctags-open-link-functions
169 '(org-ctags-find-tag
170 org-ctags-ask-rebuild-tags-file-then-find-tag
171 org-ctags-ask-append-topic)
172 "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active."
173 :group 'org-ctags
174 :type 'hook
175 :options '(org-ctags-find-tag
176 org-ctags-ask-rebuild-tags-file-then-find-tag
177 org-ctags-rebuild-tags-file-then-find-tag
178 org-ctags-ask-append-topic
179 org-ctags-append-topic
180 org-ctags-ask-visit-buffer-or-file
181 org-ctags-visit-buffer-or-file
182 org-ctags-fail-silently))
183
184
185 (defvar org-ctags-tag-list nil
186 "List of all tags in the active TAGS file.
187 Created as a local variable in each buffer.")
188
189 (defcustom org-ctags-new-topic-template
190 "* <<%t>>\n\n\n\n\n\n"
191 "Text to insert when creating a new org file via opening a hyperlink.
192 The following patterns are replaced in the string:
193 `%t' - replaced with the capitalized title of the hyperlink"
194 :group 'org-ctags
195 :type 'string)
196
197
198 (add-hook 'org-mode-hook
199 (lambda ()
200 (when (and org-ctags-enabled-p
201 (buffer-file-name))
202 ;; Make sure this file's directory is added to default
203 ;; directories in which to search for tags.
204 (let ((tags-filename
205 (expand-file-name
206 (concat (file-name-directory (buffer-file-name))
207 "/TAGS"))))
208 (when (file-exists-p tags-filename)
209 (visit-tags-table tags-filename))))))
210
211
212 (defadvice visit-tags-table (after org-ctags-load-tag-list activate compile)
213 (when (and org-ctags-enabled-p tags-file-name)
214 (set (make-local-variable 'org-ctags-tag-list)
215 (org-ctags-all-tags-in-current-tags-table))))
216
217
218 (defun org-ctags-enable ()
219 (put 'org-mode 'find-tag-default-function 'org-ctags-find-tag-at-point)
220 (setq org-ctags-enabled-p t)
221 (dolist (fn org-ctags-open-link-functions)
222 (add-hook 'org-open-link-functions fn t)))
223
224
225 ;;; General utility functions. ===============================================
226 ;; These work outside org-ctags mode.
227
228 (defun org-ctags-get-filename-for-tag (tag)
229 "TAG is a string. Search the active TAGS file for a matching tag.
230 If the tag is found, return a list containing the filename, line number, and
231 buffer position where the tag is found."
232 (interactive "sTag: ")
233 (unless tags-file-name
234 (call-interactively (visit-tags-table)))
235 (save-excursion
236 (visit-tags-table-buffer 'same)
237 (when tags-file-name
238 (with-current-buffer (get-file-buffer tags-file-name)
239 (goto-char (point-min))
240 (cond
241 ((re-search-forward (format "^.*\7f%s\ 1\\([0-9]+\\),\\([0-9]+\\)$"
242 (regexp-quote tag)) nil t)
243 (let ((line (string-to-number (match-string 1)))
244 (pos (string-to-number (match-string 2))))
245 (cond
246 ((re-search-backward "\f\n\\(.*\\),[0-9]+\n")
247 (list (match-string 1) line pos))
248 (t ; can't find a file name preceding the matched
249 ; tag??
250 (error "Malformed TAGS file: %s" (buffer-name))))))
251 (t ; tag not found
252 nil))))))
253
254
255 (defun org-ctags-all-tags-in-current-tags-table ()
256 "Read all tags defined in the active TAGS file, into a list of strings.
257 Return the list."
258 (interactive)
259 (let ((taglist nil))
260 (unless tags-file-name
261 (call-interactively (visit-tags-table)))
262 (save-excursion
263 (visit-tags-table-buffer 'same)
264 (with-current-buffer (get-file-buffer tags-file-name)
265 (goto-char (point-min))
266 (while (re-search-forward "^.*\7f\\(.*\\)\ 1\\([0-9]+\\),\\([0-9]+\\)$"
267 nil t)
268 (push (substring-no-properties (match-string 1)) taglist)))
269 taglist)))
270
271
272 (defun org-ctags-string-search-and-replace (search replace string)
273 "Replace all instances of SEARCH with REPLACE in STRING."
274 (replace-regexp-in-string (regexp-quote search) replace string t t))
275
276
277 (defun y-or-n-minibuffer (prompt)
278 (let ((use-dialog-box nil))
279 (y-or-n-p prompt)))
280
281
282 ;;; Internal functions =======================================================
283
284
285 (defun org-ctags-open-file (name &optional title)
286 "Visit or create a file called `NAME.org', and insert a new topic.
287 The new topic will be titled NAME (or TITLE if supplied)."
288 (interactive "sFile name: ")
289 (let ((filename (substitute-in-file-name (expand-file-name name))))
290 (condition-case v
291 (progn
292 (org-open-file name t)
293 (message "Opened file OK")
294 (goto-char (point-max))
295 (insert (org-ctags-string-search-and-replace
296 "%t" (capitalize (or title name))
297 org-ctags-new-topic-template))
298 (message "Inserted new file text OK")
299 (org-mode-restart))
300 (error (error "Error %S in org-ctags-open-file" v)))))
301
302
303 ;;;; Misc interoperability with etags system =================================
304
305
306 (defadvice find-tag (before org-ctags-set-org-mark-before-finding-tag
307 activate compile)
308 "Before trying to find a tag, save our current position on org mark ring."
309 (save-excursion
310 (if (and (org-mode-p) org-ctags-enabled-p)
311 (org-mark-ring-push))))
312
313
314
315 (defun org-ctags-find-tag-at-point ()
316 "Determine default tag to search for, based on text at point.
317 If there is no plausible default, return nil."
318 (let (from to bound)
319 (when (or (ignore-errors
320 ;; Look for hyperlink around `point'.
321 (save-excursion
322 (search-backward "[[") (setq from (+ 2 (point))))
323 (save-excursion
324 (goto-char from)
325 (search-forward "]") (setq to (- (point) 1)))
326 (and (> to from) (>= (point) from) (<= (point) to)))
327 (progn
328 ;; Look at text around `point'.
329 (save-excursion
330 (skip-syntax-backward "w_") (setq from (point)))
331 (save-excursion
332 (skip-syntax-forward "w_") (setq to (point)))
333 (> to from))
334 ;; Look between `line-beginning-position' and `point'.
335 (save-excursion
336 (and (setq bound (line-beginning-position))
337 (skip-syntax-backward "^w_" bound)
338 (> (setq to (point)) bound)
339 (skip-syntax-backward "w_")
340 (setq from (point))))
341 ;; Look between `point' and `line-end-position'.
342 (save-excursion
343 (and (setq bound (line-end-position))
344 (skip-syntax-forward "^w_" bound)
345 (< (setq from (point)) bound)
346 (skip-syntax-forward "w_")
347 (setq to (point)))))
348 (buffer-substring-no-properties from to))))
349
350
351 ;;; Functions for use with 'org-open-link-functions' hook =================
352
353
354 (defun org-ctags-find-tag (name)
355 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
356 Look for a tag called `NAME' in the current TAGS table. If it is found,
357 visit the file and location where the tag is found."
358 (interactive "sTag: ")
359 (let ((old-buf (current-buffer))
360 (old-pnt (point-marker))
361 (old-mark (copy-marker (mark-marker))))
362 (condition-case nil
363 (progn (find-tag name)
364 t)
365 (error
366 ;; only restore old location if find-tag raises error
367 (set-buffer old-buf)
368 (goto-char old-pnt)
369 (set-marker (mark-marker) old-mark)
370 nil))))
371
372
373 (defun org-ctags-visit-buffer-or-file (name &optional create)
374 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
375 Visit buffer named `NAME.org'. If there is no such buffer, visit the file
376 with the same name if it exists. If the file does not exist, then behavior
377 depends on the value of CREATE.
378
379 If CREATE is nil (default), then return nil. Do not create a new file.
380 If CREATE is t, create the new file and visit it.
381 If CREATE is the symbol `ask', then ask the user if they wish to create
382 the new file."
383 (interactive)
384 (let ((filename (concat (substitute-in-file-name
385 (expand-file-name name))
386 ".org")))
387 (cond
388 ((get-buffer (concat name ".org"))
389 ;; Buffer is already open
390 (org-pop-to-buffer-same-window (get-buffer (concat name ".org"))))
391 ((file-exists-p filename)
392 ;; File exists but is not open --> open it
393 (message "Opening existing org file `%S'..."
394 filename)
395 (org-open-file filename t))
396 ((or (eql create t)
397 (and (eql create 'ask)
398 (y-or-n-p (format "File `%s.org' not found; create?" name))))
399 (org-ctags-open-file filename name))
400 (t ;; File does not exist, and we don't want to create it.
401 nil))))
402
403
404 (defun org-ctags-ask-visit-buffer-or-file (name)
405 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
406 Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
407 asked before creating a new file."
408 (org-ctags-visit-buffer-or-file name 'ask))
409
410
411 (defun org-ctags-append-topic (name &optional narrowp)
412 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
413 Append a new toplevel heading to the end of the current buffer. The
414 heading contains NAME surrounded by <<angular brackets>>, thus making
415 the heading a destination for the tag `NAME'."
416 (interactive "sTopic: ")
417 (widen)
418 (goto-char (point-max))
419 (newline 2)
420 (message "Adding topic in buffer %s" (buffer-name))
421 (insert (org-ctags-string-search-and-replace
422 "%t" (capitalize name) org-ctags-new-topic-template))
423 (backward-char 4)
424 (org-update-radio-target-regexp)
425 (end-of-line)
426 (forward-line 2)
427 (when narrowp
428 ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
429 (org-narrow-to-subtree))
430 t)
431
432
433 (defun org-ctags-ask-append-topic (name &optional narrowp)
434 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
435 Wrapper for org-ctags-append-topic, which first asks the user if they want
436 to append a new topic."
437 (if (y-or-n-p (format "Topic `%s' not found; append to end of buffer?"
438 name))
439 (org-ctags-append-topic name narrowp)
440 nil))
441
442
443 (defun org-ctags-rebuild-tags-file-then-find-tag (name)
444 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
445 Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
446 to rebuild (update) the TAGS file."
447 (unless tags-file-name
448 (call-interactively (visit-tags-table)))
449 (when (buffer-file-name)
450 (org-ctags-create-tags))
451 (org-ctags-find-tag name))
452
453
454 (defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
455 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
456 Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
457 (if (and (buffer-file-name)
458 (y-or-n-p
459 (format
460 "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
461 name
462 (file-name-directory (buffer-file-name)))))
463 (org-ctags-rebuild-tags-file-then-find-tag name)
464 nil))
465
466
467 (defun org-ctags-fail-silently (name)
468 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
469 Put as the last function in the list if you want to prevent org's default
470 behavior of free text search."
471 t)
472
473
474 ;;; User-visible functions ===================================================
475
476
477 (defun org-ctags-create-tags (&optional directory-name)
478 "(Re)create tags file in the directory of the active buffer.
479 The file will contain tag definitions for all the files in the
480 directory and its subdirectories which are recognized by ctags.
481 This will include files ending in `.org' as well as most other
482 source files (.C, .H, .EL, .LISP, etc). All the resulting tags
483 end up in one file, called TAGS, located in the directory. This
484 function may take several seconds to finish if the directory or
485 its subdirectories contain large numbers of taggable files."
486 (interactive)
487 (assert (buffer-file-name))
488 (let ((dir-name (or directory-name
489 (file-name-directory (buffer-file-name))))
490 (exitcode nil))
491 (save-excursion
492 (setq exitcode
493 (shell-command
494 (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
495 "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
496 org-ctags-path-to-ctags
497 org-ctags-tag-regexp
498 (expand-file-name (concat dir-name "/TAGS"))
499 (expand-file-name (concat dir-name "/*")))))
500 (cond
501 ((eql 0 exitcode)
502 (set (make-local-variable 'org-ctags-tag-list)
503 (org-ctags-all-tags-in-current-tags-table)))
504 (t
505 ;; This seems to behave differently on Linux, so just ignore
506 ;; error codes for now
507 ;;(error "Calling ctags executable resulted in error code: %s"
508 ;; exitcode)
509 nil)))))
510
511
512 (defvar org-ctags-find-tag-history nil
513 "History of tags visited by org-ctags-find-tag-interactive.")
514
515 (defun org-ctags-find-tag-interactive ()
516 "Prompt for the name of a tag, with autocompletion, then visit the named tag.
517 Uses `ido-mode' if available.
518 If the user enters a string that does not match an existing tag, create
519 a new topic."
520 (interactive)
521 (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
522 'ido-completing-read
523 'completing-read))
524 (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
525 nil 'confirm nil 'org-ctags-find-tag-history)))
526 (when tag
527 (cond
528 ((member tag org-ctags-tag-list)
529 ;; Existing tag
530 (push tag org-ctags-find-tag-history)
531 (find-tag tag))
532 (t
533 ;; New tag
534 (run-hook-with-args-until-success
535 'org-open-link-functions tag))))))
536
537
538 (org-ctags-enable)
539
540 (provide 'org-ctags)
541
542
543 ;;; org-ctags.el ends here