org-ctags.el 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. ;;; org-ctags.el - Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2007-2017 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 <https://www.gnu.org/licenses/>.
  19. ;;
  20. ;; Synopsis
  21. ;; ========
  22. ;;
  23. ;; Allows Org mode to make use of the Emacs `etags' system. Defines
  24. ;; tag destinations in Org files as any text between <<double angled
  25. ;; brackets>>. This allows the tags-generation program `exuberant
  26. ;; ctags' to parse these files and create tag tables that record where
  27. ;; these destinations are found. Plain [[links]] in org mode files
  28. ;; which do not have <<matching destinations>> within the same file
  29. ;; will then be interpreted as links to these 'tagged' destinations,
  30. ;; allowing seamless navigation between multiple Org files. Topics
  31. ;; can be created in any org mode file and will always be found by
  32. ;; plain links from other files. Other file types recognized by ctags
  33. ;; (source code files, latex files, etc) will also be available as
  34. ;; destinations for plain links, and similarly, Org links will be
  35. ;; available as tags from source files. Finally, the function
  36. ;; `org-ctags-find-tag-interactive' lets you choose any known tag,
  37. ;; using autocompletion, and quickly jump to it.
  38. ;;
  39. ;; Installation
  40. ;; ============
  41. ;;
  42. ;; Install org mode
  43. ;; Ensure org-ctags.el is somewhere in your emacs load path.
  44. ;; Download and install Exuberant ctags -- "http://ctags.sourceforge.net/"
  45. ;; Edit your .emacs file (see next section) and load emacs.
  46. ;; To put in your init file (.emacs):
  47. ;; ==================================
  48. ;;
  49. ;; Assuming you already have org mode installed and set up:
  50. ;;
  51. ;; (setq org-ctags-path-to-ctags "/path/to/ctags/executable")
  52. ;; (add-hook 'org-mode-hook
  53. ;; (lambda ()
  54. ;; (define-key org-mode-map "\C-co" 'org-ctags-find-tag-interactive)))
  55. ;;
  56. ;; By default, with org-ctags loaded, org will first try and visit the tag
  57. ;; with the same name as the link; then, if unsuccessful, ask the user if
  58. ;; he/she wants to rebuild the 'TAGS' database and try again; then ask if
  59. ;; the user wishes to append 'tag' as a new toplevel heading at the end of
  60. ;; the buffer; and finally, defer to org's default behavior which is to
  61. ;; search the entire text of the current buffer for 'tag'.
  62. ;;
  63. ;; This behavior can be modified by changing the value of
  64. ;; ORG-CTAGS-OPEN-LINK-FUNCTIONS. For example I have the following in my
  65. ;; .emacs, which describes the same behavior as the above paragraph with
  66. ;; one difference:
  67. ;;
  68. ;; (setq org-ctags-open-link-functions
  69. ;; '(org-ctags-find-tag
  70. ;; org-ctags-ask-rebuild-tags-file-then-find-tag
  71. ;; org-ctags-ask-append-topic
  72. ;; org-ctags-fail-silently)) ; <-- prevents org default behavior
  73. ;;
  74. ;;
  75. ;; Usage
  76. ;; =====
  77. ;;
  78. ;; When you click on a link "[[foo]]" and org cannot find a matching "<<foo>>"
  79. ;; in the current buffer, the tags facility will take over. The file TAGS in
  80. ;; the active directory is examined to see if the tags facility knows about
  81. ;; "<<foo>>" in any other files. If it does, the matching file will be opened
  82. ;; and the cursor will jump to the position of "<<foo>>" in that file.
  83. ;;
  84. ;; User-visible functions:
  85. ;; - `org-ctags-find-tag-interactive': type a tag (plain link) name and visit
  86. ;; it. With autocompletion. Bound to ctrl-O in the above setup.
  87. ;; - All the etags functions should work. These include:
  88. ;;
  89. ;; M-. `find-tag' -- finds the tag at point
  90. ;;
  91. ;; C-M-. find-tag based on regular expression
  92. ;;
  93. ;; M-x tags-search RET -- like C-M-. but searches through ENTIRE TEXT
  94. ;; of ALL the files referenced in the TAGS file. A quick way to
  95. ;; search through an entire 'project'.
  96. ;;
  97. ;; M-* "go back" from a tag jump. Like `org-mark-ring-goto'.
  98. ;; You may need to bind this key yourself with (eg)
  99. ;; (global-set-key (kbd "<M-kp-multiply>") 'pop-tag-mark)
  100. ;;
  101. ;; (see etags chapter in Emacs manual for more)
  102. ;;
  103. ;;
  104. ;; Keeping the TAGS file up to date
  105. ;; ================================
  106. ;;
  107. ;; Tags mode has no way of knowing that you have created new tags by
  108. ;; typing in your Org buffer. New tags make it into the TAGS file in
  109. ;; 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-ctags-create-tags tags-table-list))
  130. ;;; Code:
  131. (require 'org)
  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 files.
  141. Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/
  142. See the ctags documentation for more information.")
  143. (defcustom org-ctags-path-to-ctags
  144. (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
  145. "Name of the ctags executable file."
  146. :group 'org-ctags
  147. :version "24.1"
  148. :type 'file)
  149. (defcustom org-ctags-open-link-functions
  150. '(org-ctags-find-tag
  151. org-ctags-ask-rebuild-tags-file-then-find-tag
  152. org-ctags-ask-append-topic)
  153. "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active."
  154. :group 'org-ctags
  155. :version "24.1"
  156. :type 'hook
  157. :options '(org-ctags-find-tag
  158. org-ctags-ask-rebuild-tags-file-then-find-tag
  159. org-ctags-rebuild-tags-file-then-find-tag
  160. org-ctags-ask-append-topic
  161. org-ctags-append-topic
  162. org-ctags-ask-visit-buffer-or-file
  163. org-ctags-visit-buffer-or-file
  164. org-ctags-fail-silently))
  165. (defvar org-ctags-tag-list nil
  166. "List of all tags in the active TAGS file.
  167. Created as a local variable in each buffer.")
  168. (defcustom org-ctags-new-topic-template
  169. "* <<%t>>\n\n\n\n\n\n"
  170. "Text to insert when creating a new org file via opening a hyperlink.
  171. The following patterns are replaced in the string:
  172. `%t' - replaced with the capitalized title of the hyperlink"
  173. :group 'org-ctags
  174. :version "24.1"
  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. (setq-local 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. ;;; Internal functions =======================================================
  243. (defun org-ctags-open-file (name &optional title)
  244. "Visit or create a file called `NAME.org', and insert a new topic.
  245. The new topic will be titled NAME (or TITLE if supplied)."
  246. (interactive "sFile name: ")
  247. (condition-case v
  248. (progn
  249. (org-open-file name t)
  250. (message "Opened file OK")
  251. (goto-char (point-max))
  252. (insert (org-ctags-string-search-and-replace
  253. "%t" (capitalize (or title name))
  254. org-ctags-new-topic-template))
  255. (message "Inserted new file text OK")
  256. (org-mode-restart))
  257. (error (error "Error %S in org-ctags-open-file" v))))
  258. ;;;; Misc interoperability with etags system =================================
  259. (defadvice xref-find-definitions
  260. (before org-ctags-set-org-mark-before-finding-tag activate compile)
  261. "Before trying to find a tag, save our current position on org mark ring."
  262. (save-excursion
  263. (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
  264. (org-mark-ring-push))))
  265. (defun org-ctags-find-tag-at-point ()
  266. "Determine default tag to search for, based on text at point.
  267. If there is no plausible default, return nil."
  268. (let (from to bound)
  269. (when (or (ignore-errors
  270. ;; Look for hyperlink around `point'.
  271. (save-excursion
  272. (search-backward "[[") (setq from (+ 2 (point))))
  273. (save-excursion
  274. (goto-char from)
  275. (search-forward "]") (setq to (- (point) 1)))
  276. (and (> to from) (>= (point) from) (<= (point) to)))
  277. (progn
  278. ;; Look at text around `point'.
  279. (save-excursion
  280. (skip-syntax-backward "w_") (setq from (point)))
  281. (save-excursion
  282. (skip-syntax-forward "w_") (setq to (point)))
  283. (> to from))
  284. ;; Look between `line-beginning-position' and `point'.
  285. (save-excursion
  286. (and (setq bound (line-beginning-position))
  287. (skip-syntax-backward "^w_" bound)
  288. (> (setq to (point)) bound)
  289. (skip-syntax-backward "w_")
  290. (setq from (point))))
  291. ;; Look between `point' and `line-end-position'.
  292. (save-excursion
  293. (and (setq bound (line-end-position))
  294. (skip-syntax-forward "^w_" bound)
  295. (< (setq from (point)) bound)
  296. (skip-syntax-forward "w_")
  297. (setq to (point)))))
  298. (buffer-substring-no-properties from to))))
  299. ;;; Functions for use with 'org-open-link-functions' hook =================
  300. (defun org-ctags-find-tag (name)
  301. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  302. Look for a tag called `NAME' in the current TAGS table. If it is found,
  303. visit the file and location where the tag is found."
  304. (interactive "sTag: ")
  305. (let ((old-buf (current-buffer))
  306. (old-pnt (point-marker))
  307. (old-mark (copy-marker (mark-marker))))
  308. (condition-case nil
  309. (progn (xref-find-definitions name)
  310. t)
  311. (error
  312. ;; only restore old location if find-tag raises error
  313. (set-buffer old-buf)
  314. (goto-char old-pnt)
  315. (set-marker (mark-marker) old-mark)
  316. nil))))
  317. (defun org-ctags-visit-buffer-or-file (name &optional create)
  318. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  319. Visit buffer named `NAME.org'. If there is no such buffer, visit the file
  320. with the same name if it exists. If the file does not exist, then behavior
  321. depends on the value of CREATE.
  322. If CREATE is nil (default), then return nil. Do not create a new file.
  323. If CREATE is t, create the new file and visit it.
  324. If CREATE is the symbol `ask', then ask the user if they wish to create
  325. the new file."
  326. (interactive)
  327. (let ((filename (concat (substitute-in-file-name
  328. (expand-file-name name))
  329. ".org")))
  330. (cond
  331. ((get-buffer (concat name ".org"))
  332. ;; Buffer is already open
  333. (pop-to-buffer-same-window (get-buffer (concat name ".org"))))
  334. ((file-exists-p filename)
  335. ;; File exists but is not open --> open it
  336. (message "Opening existing org file `%S'..."
  337. filename)
  338. (org-open-file filename t))
  339. ((or (eql create t)
  340. (and (eql create 'ask)
  341. (y-or-n-p (format-message
  342. "File `%s.org' not found; create?" name))))
  343. (org-ctags-open-file filename name))
  344. (t ;; File does not exist, and we don't want to create it.
  345. nil))))
  346. (defun org-ctags-ask-visit-buffer-or-file (name)
  347. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  348. Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
  349. asked before creating a new file."
  350. (org-ctags-visit-buffer-or-file name 'ask))
  351. (defun org-ctags-append-topic (name &optional narrowp)
  352. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  353. Append a new toplevel heading to the end of the current buffer. The
  354. heading contains NAME surrounded by <<angular brackets>>, thus making
  355. the heading a destination for the tag `NAME'."
  356. (interactive "sTopic: ")
  357. (widen)
  358. (goto-char (point-max))
  359. (newline 2)
  360. (message "Adding topic in buffer %s" (buffer-name))
  361. (insert (org-ctags-string-search-and-replace
  362. "%t" (capitalize name) org-ctags-new-topic-template))
  363. (backward-char 4)
  364. (end-of-line)
  365. (forward-line 2)
  366. (when narrowp
  367. ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
  368. (org-narrow-to-subtree))
  369. t)
  370. (defun org-ctags-ask-append-topic (name &optional narrowp)
  371. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  372. Wrapper for org-ctags-append-topic, which first asks the user if they want
  373. to append a new topic."
  374. (if (y-or-n-p (format-message
  375. "Topic `%s' not found; append to end of buffer?" name))
  376. (org-ctags-append-topic name narrowp)
  377. nil))
  378. (defun org-ctags-rebuild-tags-file-then-find-tag (name)
  379. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  380. Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
  381. to rebuild (update) the TAGS file."
  382. (unless tags-file-name
  383. (call-interactively (visit-tags-table)))
  384. (when (buffer-file-name)
  385. (org-ctags-create-tags))
  386. (org-ctags-find-tag name))
  387. (defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
  388. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  389. Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
  390. (if (and (buffer-file-name)
  391. (y-or-n-p
  392. (format-message
  393. "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
  394. name
  395. (file-name-directory (buffer-file-name)))))
  396. (org-ctags-rebuild-tags-file-then-find-tag name)
  397. nil))
  398. (defun org-ctags-fail-silently (_name)
  399. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  400. Put as the last function in the list if you want to prevent Org's
  401. default behavior of free text search."
  402. t)
  403. ;;; User-visible functions ===================================================
  404. (defun org-ctags-create-tags (&optional directory-name)
  405. "(Re)create tags file in the directory of the active buffer.
  406. The file will contain tag definitions for all the files in the
  407. directory and its subdirectories which are recognized by ctags.
  408. This will include files ending in `.org' as well as most other
  409. source files (.C, .H, .EL, .LISP, etc). All the resulting tags
  410. end up in one file, called TAGS, located in the directory. This
  411. function may take several seconds to finish if the directory or
  412. its subdirectories contain large numbers of taggable files."
  413. (interactive)
  414. (cl-assert (buffer-file-name))
  415. (let ((dir-name (or directory-name
  416. (file-name-directory (buffer-file-name))))
  417. (exitcode nil))
  418. (save-excursion
  419. (setq exitcode
  420. (shell-command
  421. (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
  422. "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
  423. org-ctags-path-to-ctags
  424. org-ctags-tag-regexp
  425. (expand-file-name (concat dir-name "/TAGS"))
  426. (expand-file-name (concat dir-name "/*")))))
  427. (cond
  428. ((eql 0 exitcode)
  429. (setq-local org-ctags-tag-list
  430. (org-ctags-all-tags-in-current-tags-table)))
  431. (t
  432. ;; This seems to behave differently on Linux, so just ignore
  433. ;; error codes for now
  434. ;;(error "Calling ctags executable resulted in error code: %s"
  435. ;; exitcode)
  436. nil)))))
  437. (defvar org-ctags-find-tag-history nil
  438. "History of tags visited by org-ctags-find-tag-interactive.")
  439. (defun org-ctags-find-tag-interactive ()
  440. "Prompt for the name of a tag, with autocompletion, then visit the named tag.
  441. Uses `ido-mode' if available.
  442. If the user enters a string that does not match an existing tag, create
  443. a new topic."
  444. (interactive)
  445. (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
  446. 'ido-completing-read
  447. 'completing-read))
  448. (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
  449. nil 'confirm nil 'org-ctags-find-tag-history)))
  450. (when tag
  451. (cond
  452. ((member tag org-ctags-tag-list)
  453. ;; Existing tag
  454. (push tag org-ctags-find-tag-history)
  455. (xref-find-definitions tag))
  456. (t
  457. ;; New tag
  458. (run-hook-with-args-until-success
  459. 'org-open-link-functions tag))))))
  460. (org-ctags-enable)
  461. (provide 'org-ctags)
  462. ;;; org-ctags.el ends here