org-ctags.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. ;;; org-ctags.el --- Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2007-2022 Free Software Foundation, Inc.
  3. ;; Author: Paul Sexton <eeeickythump@gmail.com>
  4. ;; Keywords: org, wp
  5. ;; This file is part of GNU Emacs.
  6. ;;
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;;
  19. ;; Synopsis
  20. ;; ========
  21. ;;
  22. ;; Allows Org mode to make use of the Emacs `etags' system. Defines
  23. ;; tag destinations in Org files as any text between <<double angled
  24. ;; brackets>>. This allows the tags-generation program `exuberant
  25. ;; ctags' to parse these files and create tag tables that record where
  26. ;; these destinations are found. Plain [[links]] in org mode files
  27. ;; which do not have <<matching destinations>> within the same file
  28. ;; will then be interpreted as links to these 'tagged' destinations,
  29. ;; allowing seamless navigation between multiple Org files. Topics
  30. ;; can be created in any org mode file and will always be found by
  31. ;; plain links from other files. Other file types recognized by ctags
  32. ;; (source code files, latex files, etc) will also be available as
  33. ;; destinations for plain links, and similarly, Org links will be
  34. ;; available as tags from source files. Finally, the function
  35. ;; `org-ctags-find-tag-interactive' lets you choose any known tag,
  36. ;; using 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 -- "https://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 behavior which is to
  60. ;; search the entire text of the current buffer for 'tag'.
  61. ;;
  62. ;; This behavior 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 behavior 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 behavior
  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
  107. ;; typing in your Org buffer. New tags make it into the TAGS file in
  108. ;; 3 ways:
  109. ;;
  110. ;; 1. You re-run (org-ctags-create-tags "directory") to rebuild the file.
  111. ;; 2. You put the function `org-ctags-ask-rebuild-tags-file-then-find-tag' in
  112. ;; your `org-open-link-functions' list, as is done in the setup
  113. ;; above. This will cause the TAGS file to be rebuilt whenever a link
  114. ;; cannot be found. This may be slow with large file collections however.
  115. ;; 3. You run the following from the command line (all 1 line):
  116. ;;
  117. ;; ctags --langdef=orgmode --langmap=orgmode:.org
  118. ;; --regex-orgmode="/<<([^>]+)>>/\1/d,definition/"
  119. ;; -f /your/path/TAGS -e -R /your/path/*.org
  120. ;;
  121. ;; If you are paranoid, you might want to run (org-ctags-create-tags
  122. ;; "/path/to/org/files") at startup, by including the following toplevel form
  123. ;; in .emacs. However this can cause a pause of several seconds if ctags has
  124. ;; to scan lots of files.
  125. ;;
  126. ;; (progn
  127. ;; (message "-- rebuilding tags tables...")
  128. ;; (mapc 'org-ctags-create-tags tags-table-list))
  129. ;;; Code:
  130. (require 'org-macs)
  131. (org-assert-version)
  132. (eval-when-compile (require 'cl-lib))
  133. (require 'org)
  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 files.
  143. Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/
  144. See the ctags documentation for more information.")
  145. (defcustom org-ctags-path-to-ctags
  146. (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
  147. "Name of the ctags executable file."
  148. :version "24.1"
  149. :type 'file)
  150. (defcustom org-ctags-open-link-functions
  151. '(org-ctags-find-tag
  152. org-ctags-ask-rebuild-tags-file-then-find-tag
  153. org-ctags-ask-append-topic)
  154. "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS by 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. :version "24.1"
  174. :type 'string)
  175. (add-hook 'org-mode-hook
  176. (lambda ()
  177. (when (and org-ctags-enabled-p
  178. (buffer-file-name))
  179. ;; Make sure this file's directory is added to default
  180. ;; directories in which to search for tags.
  181. (let ((tags-filename
  182. (expand-file-name
  183. (concat (file-name-directory (buffer-file-name))
  184. "/TAGS"))))
  185. (when (file-exists-p tags-filename)
  186. (visit-tags-table tags-filename))))))
  187. (advice-add 'visit-tags-table :after #'org--ctags-load-tag-list)
  188. (defun org--ctags-load-tag-list (&rest _)
  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\^A\\([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 "^.*\^?\\(.*\\)\^A\\([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. (advice-add 'xref-find-definitions :before
  260. #'org--ctags-set-org-mark-before-finding-tag)
  261. (defun org--ctags-set-org-mark-before-finding-tag (&rest _)
  262. "Before trying to find a tag, save our current position on org mark ring."
  263. (save-excursion
  264. (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
  265. (org-mark-ring-push))))
  266. (defun org-ctags-find-tag-at-point ()
  267. "Determine default tag to search for, based on text at point.
  268. If there is no plausible default, return nil."
  269. (let (from to bound)
  270. (when (or (ignore-errors
  271. ;; Look for hyperlink around `point'.
  272. (save-excursion
  273. (search-backward "[[") (setq from (+ 2 (point))))
  274. (save-excursion
  275. (goto-char from)
  276. (search-forward "]") (setq to (- (point) 1)))
  277. (and (> to from) (>= (point) from) (<= (point) to)))
  278. (progn
  279. ;; Look at text around `point'.
  280. (save-excursion
  281. (skip-syntax-backward "w_") (setq from (point)))
  282. (save-excursion
  283. (skip-syntax-forward "w_") (setq to (point)))
  284. (> to from))
  285. ;; Look between `line-beginning-position' and `point'.
  286. (save-excursion
  287. (and (setq bound (line-beginning-position))
  288. (skip-syntax-backward "^w_" bound)
  289. (> (setq to (point)) bound)
  290. (skip-syntax-backward "w_")
  291. (setq from (point))))
  292. ;; Look between `point' and `line-end-position'.
  293. (save-excursion
  294. (and (setq bound (line-end-position))
  295. (skip-syntax-forward "^w_" bound)
  296. (< (setq from (point)) bound)
  297. (skip-syntax-forward "w_")
  298. (setq to (point)))))
  299. (buffer-substring-no-properties from to))))
  300. ;;; Functions for use with 'org-open-link-functions' hook =================
  301. (defun org-ctags-find-tag (name)
  302. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  303. Look for a tag called `NAME' in the current TAGS table. If it is found,
  304. visit the file and location where the tag is found."
  305. (interactive "sTag: ")
  306. (let ((old-buf (current-buffer))
  307. (old-pnt (point-marker))
  308. (old-mark (copy-marker (mark-marker))))
  309. (condition-case nil
  310. (progn (xref-find-definitions name)
  311. t)
  312. (error
  313. ;; only restore old location if find-tag raises error
  314. (set-buffer old-buf)
  315. (goto-char old-pnt)
  316. (set-marker (mark-marker) old-mark)
  317. nil))))
  318. (defun org-ctags-visit-buffer-or-file (name &optional create)
  319. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  320. Visit buffer named `NAME.org'. If there is no such buffer, visit the file
  321. with the same name if it exists. If the file does not exist, then behavior
  322. depends on the value of CREATE.
  323. If CREATE is nil (default), then return nil. Do not create a new file.
  324. If CREATE is t, create the new file and visit it.
  325. If CREATE is the symbol `ask', then ask the user if they wish to create
  326. the new file."
  327. (interactive)
  328. (let ((filename (concat (substitute-in-file-name
  329. (expand-file-name name))
  330. ".org")))
  331. (cond
  332. ((get-buffer (concat name ".org"))
  333. ;; Buffer is already open
  334. (pop-to-buffer-same-window (get-buffer (concat name ".org"))))
  335. ((file-exists-p filename)
  336. ;; File exists but is not open --> open it
  337. (message "Opening existing org file `%S'..."
  338. filename)
  339. (org-open-file filename t))
  340. ((or (eql create t)
  341. (and (eql create 'ask)
  342. (y-or-n-p (format-message
  343. "File `%s.org' not found; create?" name))))
  344. (org-ctags-open-file filename name))
  345. (t ;; File does not exist, and we don't want to create it.
  346. nil))))
  347. (defun org-ctags-ask-visit-buffer-or-file (name)
  348. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  349. Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
  350. asked before creating a new file."
  351. (org-ctags-visit-buffer-or-file name 'ask))
  352. (defun org-ctags-append-topic (name &optional narrowp)
  353. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  354. Append a new toplevel heading to the end of the current buffer. The
  355. heading contains NAME surrounded by <<angular brackets>>, thus making
  356. the heading a destination for the tag `NAME'."
  357. (interactive "sTopic: ")
  358. (widen)
  359. (goto-char (point-max))
  360. (newline 2)
  361. (message "Adding topic in buffer %s" (buffer-name))
  362. (insert (org-ctags-string-search-and-replace
  363. "%t" (capitalize name) org-ctags-new-topic-template))
  364. (backward-char 4)
  365. (end-of-line)
  366. (forward-line 2)
  367. (when narrowp
  368. ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
  369. (org-narrow-to-subtree))
  370. t)
  371. (defun org-ctags-ask-append-topic (name &optional narrowp)
  372. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  373. Wrapper for org-ctags-append-topic, which first asks the user if they want
  374. to append a new topic."
  375. (if (y-or-n-p (format-message
  376. "Topic `%s' not found; append to end of buffer?" name))
  377. (org-ctags-append-topic name narrowp)
  378. nil))
  379. (defun org-ctags-rebuild-tags-file-then-find-tag (name)
  380. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  381. Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
  382. to rebuild (update) the TAGS file."
  383. (unless tags-file-name
  384. (call-interactively (visit-tags-table)))
  385. (when (buffer-file-name)
  386. (org-ctags-create-tags))
  387. (org-ctags-find-tag name))
  388. (defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
  389. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  390. Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
  391. (if (and (buffer-file-name)
  392. (y-or-n-p
  393. (format-message
  394. "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
  395. name
  396. (file-name-directory (buffer-file-name)))))
  397. (org-ctags-rebuild-tags-file-then-find-tag name)
  398. nil))
  399. (defun org-ctags-fail-silently (_name)
  400. "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
  401. Put as the last function in the list if you want to prevent Org's
  402. default behavior of free text search."
  403. t)
  404. ;;; User-visible functions ===================================================
  405. (defun org-ctags-create-tags (&optional directory-name)
  406. "(Re)create tags file in the directory of the active buffer.
  407. The file will contain tag definitions for all the files in the
  408. directory and its subdirectories which are recognized by ctags.
  409. This will include files ending in `.org' as well as most other
  410. source files (.C, .H, .EL, .LISP, etc). All the resulting tags
  411. end up in one file, called TAGS, located in the directory. This
  412. function may take several seconds to finish if the directory or
  413. its subdirectories contain large numbers of taggable files."
  414. (interactive)
  415. (cl-assert (buffer-file-name))
  416. (let ((dir-name (or directory-name
  417. (file-name-directory (buffer-file-name))))
  418. (exitcode nil))
  419. (save-excursion
  420. (setq exitcode
  421. (shell-command
  422. (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
  423. "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
  424. org-ctags-path-to-ctags
  425. org-ctags-tag-regexp
  426. (expand-file-name (concat dir-name "/TAGS"))
  427. (expand-file-name (concat dir-name "/*")))))
  428. (cond
  429. ((eql 0 exitcode)
  430. (setq-local org-ctags-tag-list
  431. (org-ctags-all-tags-in-current-tags-table)))
  432. (t
  433. ;; This seems to behave differently on Linux, so just ignore
  434. ;; error codes for now
  435. ;;(error "Calling ctags executable resulted in error code: %s"
  436. ;; exitcode)
  437. nil)))))
  438. (defvar org-ctags-find-tag-history nil
  439. "History of tags visited by org-ctags-find-tag-interactive.")
  440. (defun org-ctags-find-tag-interactive ()
  441. "Prompt for the name of a tag, with autocompletion, then visit the named tag.
  442. Uses `ido-mode' if available.
  443. If the user enters a string that does not match an existing tag, create
  444. a new topic."
  445. (interactive)
  446. (let* ((tag (ido-completing-read "Topic: " org-ctags-tag-list
  447. nil 'confirm nil 'org-ctags-find-tag-history)))
  448. (when tag
  449. (cond
  450. ((member tag org-ctags-tag-list)
  451. ;; Existing tag
  452. (push tag org-ctags-find-tag-history)
  453. (xref-find-definitions tag))
  454. (t
  455. ;; New tag
  456. (run-hook-with-args-until-success
  457. 'org-open-link-functions tag))))))
  458. (org-ctags-enable)
  459. (provide 'org-ctags)
  460. ;;; org-ctags.el ends here