org-ctags.el 20 KB

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