org-ctags.el 20 KB

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