org-ctags.el 20 KB

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