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