* ob-vbnet.el: Org-babel functions for VB.Net evaluation
[org-mode/org-tableheadings.git] / lisp / org-ctags.el
blob51b56634bd37b5d3fa500083ac5075afbf14e7bc
1 ;;; org-ctags.el - Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*-
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 (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.
150 The regexp matches 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 (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
156 "Name of the ctags executable file."
157 :group 'org-ctags
158 :version "24.1"
159 :type 'file)
161 (defcustom org-ctags-open-link-functions
162 '(org-ctags-find-tag
163 org-ctags-ask-rebuild-tags-file-then-find-tag
164 org-ctags-ask-append-topic)
165 "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active."
166 :group 'org-ctags
167 :version "24.1"
168 :type 'hook
169 :options '(org-ctags-find-tag
170 org-ctags-ask-rebuild-tags-file-then-find-tag
171 org-ctags-rebuild-tags-file-then-find-tag
172 org-ctags-ask-append-topic
173 org-ctags-append-topic
174 org-ctags-ask-visit-buffer-or-file
175 org-ctags-visit-buffer-or-file
176 org-ctags-fail-silently))
179 (defvar org-ctags-tag-list nil
180 "List of all tags in the active TAGS file.
181 Created as a local variable in each buffer.")
183 (defcustom org-ctags-new-topic-template
184 "* <<%t>>\n\n\n\n\n\n"
185 "Text to insert when creating a new org file via opening a hyperlink.
186 The following patterns are replaced in the string:
187 `%t' - replaced with the capitalized title of the hyperlink"
188 :group 'org-ctags
189 :version "24.1"
190 :type 'string)
193 (add-hook 'org-mode-hook
194 (lambda ()
195 (when (and org-ctags-enabled-p
196 (buffer-file-name))
197 ;; Make sure this file's directory is added to default
198 ;; directories in which to search for tags.
199 (let ((tags-filename
200 (expand-file-name
201 (concat (file-name-directory (buffer-file-name))
202 "/TAGS"))))
203 (when (file-exists-p tags-filename)
204 (visit-tags-table tags-filename))))))
207 (defadvice visit-tags-table (after org-ctags-load-tag-list activate compile)
208 (when (and org-ctags-enabled-p tags-file-name)
209 (setq-local org-ctags-tag-list
210 (org-ctags-all-tags-in-current-tags-table))))
213 (defun org-ctags-enable ()
214 (put 'org-mode 'find-tag-default-function 'org-ctags-find-tag-at-point)
215 (setq org-ctags-enabled-p t)
216 (dolist (fn org-ctags-open-link-functions)
217 (add-hook 'org-open-link-functions fn t)))
220 ;;; General utility functions. ===============================================
221 ;; These work outside org-ctags mode.
223 (defun org-ctags-get-filename-for-tag (tag)
224 "TAG is a string. Search the active TAGS file for a matching tag.
225 If the tag is found, return a list containing the filename, line number, and
226 buffer position where the tag is found."
227 (interactive "sTag: ")
228 (unless tags-file-name
229 (call-interactively (visit-tags-table)))
230 (save-excursion
231 (visit-tags-table-buffer 'same)
232 (when tags-file-name
233 (with-current-buffer (get-file-buffer tags-file-name)
234 (goto-char (point-min))
235 (cond
236 ((re-search-forward (format "^.*\x7f%s\x01\\([0-9]+\\),\\([0-9]+\\)$"
237 (regexp-quote tag)) nil t)
238 (let ((line (string-to-number (match-string 1)))
239 (pos (string-to-number (match-string 2))))
240 (cond
241 ((re-search-backward "\f\n\\(.*\\),[0-9]+\n")
242 (list (match-string 1) line pos))
243 (t ; can't find a file name preceding the matched
244 ; tag??
245 (error "Malformed TAGS file: %s" (buffer-name))))))
246 (t ; tag not found
247 nil))))))
250 (defun org-ctags-all-tags-in-current-tags-table ()
251 "Read all tags defined in the active TAGS file, into a list of strings.
252 Return the list."
253 (interactive)
254 (let ((taglist nil))
255 (unless tags-file-name
256 (call-interactively (visit-tags-table)))
257 (save-excursion
258 (visit-tags-table-buffer 'same)
259 (with-current-buffer (get-file-buffer tags-file-name)
260 (goto-char (point-min))
261 (while (re-search-forward "^.*\x7f\\(.*\\)\x01\\([0-9]+\\),\\([0-9]+\\)$"
262 nil t)
263 (push (substring-no-properties (match-string 1)) taglist)))
264 taglist)))
267 (defun org-ctags-string-search-and-replace (search replace string)
268 "Replace all instances of SEARCH with REPLACE in STRING."
269 (replace-regexp-in-string (regexp-quote search) replace string t t))
272 ;;; Internal functions =======================================================
275 (defun org-ctags-open-file (name &optional title)
276 "Visit or create a file called `NAME.org', and insert a new topic.
277 The new topic will be titled NAME (or TITLE if supplied)."
278 (interactive "sFile name: ")
279 (condition-case v
280 (progn
281 (org-open-file name t)
282 (message "Opened file OK")
283 (goto-char (point-max))
284 (insert (org-ctags-string-search-and-replace
285 "%t" (capitalize (or title name))
286 org-ctags-new-topic-template))
287 (message "Inserted new file text OK")
288 (org-mode-restart))
289 (error (error "Error %S in org-ctags-open-file" v))))
292 ;;;; Misc interoperability with etags system =================================
295 (defadvice xref-find-definitions
296 (before org-ctags-set-org-mark-before-finding-tag activate compile)
297 "Before trying to find a tag, save our current position on org mark ring."
298 (save-excursion
299 (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
300 (org-mark-ring-push))))
304 (defun org-ctags-find-tag-at-point ()
305 "Determine default tag to search for, based on text at point.
306 If there is no plausible default, return nil."
307 (let (from to bound)
308 (when (or (ignore-errors
309 ;; Look for hyperlink around `point'.
310 (save-excursion
311 (search-backward "[[") (setq from (+ 2 (point))))
312 (save-excursion
313 (goto-char from)
314 (search-forward "]") (setq to (- (point) 1)))
315 (and (> to from) (>= (point) from) (<= (point) to)))
316 (progn
317 ;; Look at text around `point'.
318 (save-excursion
319 (skip-syntax-backward "w_") (setq from (point)))
320 (save-excursion
321 (skip-syntax-forward "w_") (setq to (point)))
322 (> to from))
323 ;; Look between `line-beginning-position' and `point'.
324 (save-excursion
325 (and (setq bound (line-beginning-position))
326 (skip-syntax-backward "^w_" bound)
327 (> (setq to (point)) bound)
328 (skip-syntax-backward "w_")
329 (setq from (point))))
330 ;; Look between `point' and `line-end-position'.
331 (save-excursion
332 (and (setq bound (line-end-position))
333 (skip-syntax-forward "^w_" bound)
334 (< (setq from (point)) bound)
335 (skip-syntax-forward "w_")
336 (setq to (point)))))
337 (buffer-substring-no-properties from to))))
340 ;;; Functions for use with 'org-open-link-functions' hook =================
343 (defun org-ctags-find-tag (name)
344 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
345 Look for a tag called `NAME' in the current TAGS table. If it is found,
346 visit the file and location where the tag is found."
347 (interactive "sTag: ")
348 (let ((old-buf (current-buffer))
349 (old-pnt (point-marker))
350 (old-mark (copy-marker (mark-marker))))
351 (condition-case nil
352 (progn (xref-find-definitions name)
354 (error
355 ;; only restore old location if find-tag raises error
356 (set-buffer old-buf)
357 (goto-char old-pnt)
358 (set-marker (mark-marker) old-mark)
359 nil))))
362 (defun org-ctags-visit-buffer-or-file (name &optional create)
363 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
364 Visit buffer named `NAME.org'. If there is no such buffer, visit the file
365 with the same name if it exists. If the file does not exist, then behavior
366 depends on the value of CREATE.
368 If CREATE is nil (default), then return nil. Do not create a new file.
369 If CREATE is t, create the new file and visit it.
370 If CREATE is the symbol `ask', then ask the user if they wish to create
371 the new file."
372 (interactive)
373 (let ((filename (concat (substitute-in-file-name
374 (expand-file-name name))
375 ".org")))
376 (cond
377 ((get-buffer (concat name ".org"))
378 ;; Buffer is already open
379 (pop-to-buffer-same-window (get-buffer (concat name ".org"))))
380 ((file-exists-p filename)
381 ;; File exists but is not open --> open it
382 (message "Opening existing org file `%S'..."
383 filename)
384 (org-open-file filename t))
385 ((or (eql create t)
386 (and (eql create 'ask)
387 (y-or-n-p (format-message
388 "File `%s.org' not found; create?" name))))
389 (org-ctags-open-file filename name))
390 (t ;; File does not exist, and we don't want to create it.
391 nil))))
394 (defun org-ctags-ask-visit-buffer-or-file (name)
395 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
396 Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
397 asked before creating a new file."
398 (org-ctags-visit-buffer-or-file name 'ask))
401 (defun org-ctags-append-topic (name &optional narrowp)
402 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
403 Append a new toplevel heading to the end of the current buffer. The
404 heading contains NAME surrounded by <<angular brackets>>, thus making
405 the heading a destination for the tag `NAME'."
406 (interactive "sTopic: ")
407 (widen)
408 (goto-char (point-max))
409 (newline 2)
410 (message "Adding topic in buffer %s" (buffer-name))
411 (insert (org-ctags-string-search-and-replace
412 "%t" (capitalize name) org-ctags-new-topic-template))
413 (backward-char 4)
414 (org-update-radio-target-regexp)
415 (end-of-line)
416 (forward-line 2)
417 (when narrowp
418 ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
419 (org-narrow-to-subtree))
423 (defun org-ctags-ask-append-topic (name &optional narrowp)
424 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
425 Wrapper for org-ctags-append-topic, which first asks the user if they want
426 to append a new topic."
427 (if (y-or-n-p (format-message
428 "Topic `%s' not found; append to end of buffer?" name))
429 (org-ctags-append-topic name narrowp)
430 nil))
433 (defun org-ctags-rebuild-tags-file-then-find-tag (name)
434 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
435 Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
436 to rebuild (update) the TAGS file."
437 (unless tags-file-name
438 (call-interactively (visit-tags-table)))
439 (when (buffer-file-name)
440 (org-ctags-create-tags))
441 (org-ctags-find-tag name))
444 (defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
445 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
446 Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
447 (if (and (buffer-file-name)
448 (y-or-n-p
449 (format-message
450 "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
451 name
452 (file-name-directory (buffer-file-name)))))
453 (org-ctags-rebuild-tags-file-then-find-tag name)
454 nil))
457 (defun org-ctags-fail-silently (_name)
458 "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
459 Put as the last function in the list if you want to prevent Org's
460 default behavior of free text search."
464 ;;; User-visible functions ===================================================
467 (defun org-ctags-create-tags (&optional directory-name)
468 "(Re)create tags file in the directory of the active buffer.
469 The file will contain tag definitions for all the files in the
470 directory and its subdirectories which are recognized by ctags.
471 This will include files ending in `.org' as well as most other
472 source files (.C, .H, .EL, .LISP, etc). All the resulting tags
473 end up in one file, called TAGS, located in the directory. This
474 function may take several seconds to finish if the directory or
475 its subdirectories contain large numbers of taggable files."
476 (interactive)
477 (assert (buffer-file-name))
478 (let ((dir-name (or directory-name
479 (file-name-directory (buffer-file-name))))
480 (exitcode nil))
481 (save-excursion
482 (setq exitcode
483 (shell-command
484 (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
485 "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
486 org-ctags-path-to-ctags
487 org-ctags-tag-regexp
488 (expand-file-name (concat dir-name "/TAGS"))
489 (expand-file-name (concat dir-name "/*")))))
490 (cond
491 ((eql 0 exitcode)
492 (setq-local org-ctags-tag-list
493 (org-ctags-all-tags-in-current-tags-table)))
495 ;; This seems to behave differently on Linux, so just ignore
496 ;; error codes for now
497 ;;(error "Calling ctags executable resulted in error code: %s"
498 ;; exitcode)
499 nil)))))
502 (defvar org-ctags-find-tag-history nil
503 "History of tags visited by org-ctags-find-tag-interactive.")
505 (defun org-ctags-find-tag-interactive ()
506 "Prompt for the name of a tag, with autocompletion, then visit the named tag.
507 Uses `ido-mode' if available.
508 If the user enters a string that does not match an existing tag, create
509 a new topic."
510 (interactive)
511 (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
512 'ido-completing-read
513 'completing-read))
514 (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
515 nil 'confirm nil 'org-ctags-find-tag-history)))
516 (when tag
517 (cond
518 ((member tag org-ctags-tag-list)
519 ;; Existing tag
520 (push tag org-ctags-find-tag-history)
521 (xref-find-definitions tag))
523 ;; New tag
524 (run-hook-with-args-until-success
525 'org-open-link-functions tag))))))
528 (org-ctags-enable)
530 (provide 'org-ctags)
532 ;;; org-ctags.el ends here