org-id.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. ;;; org-id.el --- Global identifiers for Org entries -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2008-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; URL: https://orgmode.org
  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 <https://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file implements globally unique identifiers for Org entries.
  25. ;; Identifiers are stored in the entry as an :ID: property. Functions
  26. ;; are provided that create and retrieve such identifiers, and that find
  27. ;; entries based on the identifier.
  28. ;; Identifiers consist of a prefix (default "Org" given by the variable
  29. ;; `org-id-prefix') and a unique part that can be created by a number
  30. ;; of different methods, see the variable `org-id-method'.
  31. ;; Org has a builtin method that uses a compact encoding of the creation
  32. ;; time of the ID, with microsecond accuracy. This virtually
  33. ;; guarantees globally unique identifiers, even if several people are
  34. ;; creating IDs at the same time in files that will eventually be used
  35. ;; together.
  36. ;;
  37. ;; By default Org uses UUIDs as global unique identifiers.
  38. ;;
  39. ;; This file defines the following API:
  40. ;;
  41. ;; org-id-get-create
  42. ;; Create an ID for the entry at point if it does not yet have one.
  43. ;; Returns the ID (old or new). This function can be used
  44. ;; interactively, with prefix argument the creation of a new ID is
  45. ;; forced, even if there was an old one.
  46. ;;
  47. ;; org-id-get
  48. ;; Get the ID property of an entry. Using appropriate arguments
  49. ;; to the function, it can also create the ID for this entry.
  50. ;;
  51. ;; org-id-goto
  52. ;; Command to go to a specific ID, this command can be used
  53. ;; interactively.
  54. ;;
  55. ;; org-id-get-with-outline-path-completion
  56. ;; Retrieve the ID of an entry, using outline path completion.
  57. ;; This function can work for multiple files.
  58. ;;
  59. ;; org-id-get-with-outline-drilling
  60. ;; Retrieve the ID of an entry, using outline path completion.
  61. ;; This function only works for the current file.
  62. ;;
  63. ;; org-id-find
  64. ;; Find the location of an entry with specific id.
  65. ;;
  66. ;;; Code:
  67. (require 'org-macs)
  68. (org-assert-version)
  69. (require 'org)
  70. (require 'org-refile)
  71. (require 'ol)
  72. (declare-function message-make-fqdn "message" ())
  73. (declare-function org-goto-location "org-goto" (&optional _buf help))
  74. ;; Declared inside `org-element-with-disabled-cache' macro.
  75. (declare-function org-element--cache-active-p "org-element.el" (&optional called-from-cache-change-func-p))
  76. ;;; Customization
  77. (defgroup org-id nil
  78. "Options concerning global entry identifiers in Org mode."
  79. :tag "Org ID"
  80. :group 'org)
  81. (defcustom org-id-link-to-org-use-id nil
  82. "Non-nil means storing a link to an Org file will use entry IDs.
  83. \\<org-mode-map>
  84. The variable can have the following values:
  85. t Create an ID if needed to make a link to the current entry.
  86. create-if-interactive
  87. If `org-store-link' is called directly (interactively, as a user
  88. command), do create an ID to support the link. But when doing the
  89. job for capture, only use the ID if it already exists. The
  90. purpose of this setting is to avoid proliferation of unwanted
  91. IDs, just because you happen to be in an Org file when you
  92. call `org-capture' that automatically and preemptively creates a
  93. link. If you do want to get an ID link in a capture template to
  94. an entry not having an ID, create it first by explicitly creating
  95. a link to it, using `\\[org-store-link]' first.
  96. create-if-interactive-and-no-custom-id
  97. Like create-if-interactive, but do not create an ID if there is
  98. a CUSTOM_ID property defined in the entry.
  99. use-existing
  100. Use existing ID, do not create one.
  101. nil Never use an ID to make a link, instead link using a text search for
  102. the headline text."
  103. :group 'org-link-store
  104. :group 'org-id
  105. :version "24.3"
  106. :type '(choice
  107. (const :tag "Create ID to make link" t)
  108. (const :tag "Create if storing link interactively"
  109. create-if-interactive)
  110. (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
  111. create-if-interactive-and-no-custom-id)
  112. (const :tag "Only use existing" use-existing)
  113. (const :tag "Do not use ID to create link" nil)))
  114. (defcustom org-id-uuid-program "uuidgen"
  115. "The uuidgen program."
  116. :group 'org-id
  117. :type 'string)
  118. (defcustom org-id-ts-format "%Y%m%dT%H%M%S.%6N"
  119. "Timestamp format for IDs generated using `ts' `org-id-method'.
  120. The format should be suitable to pass as an argument to `format-time-string'.
  121. Defaults to ISO8601 timestamps without separators and without
  122. timezone, local time and precision down to 1e-6 seconds."
  123. :type 'string
  124. :package-version '(Org . "9.5"))
  125. (defcustom org-id-method 'uuid
  126. "The method that should be used to create new IDs.
  127. An ID will consist of the optional prefix specified in `org-id-prefix',
  128. and a unique part created by the method this variable specifies.
  129. Allowed values are:
  130. org Org's own internal method, using an encoding of the current time to
  131. microsecond accuracy, and optionally the current domain of the
  132. computer. See the variable `org-id-include-domain'.
  133. uuid Create random (version 4) UUIDs. If the program defined in
  134. `org-id-uuid-program' is available it is used to create the ID.
  135. Otherwise an internal functions is used.
  136. ts Create ID's based on timestamps as specified in `org-id-ts-format'."
  137. :group 'org-id
  138. :type '(choice
  139. (const :tag "Org's internal method" org)
  140. (const :tag "external: uuidgen" uuid)
  141. (const :tag "Timestamp with format `org-id-ts-format'" ts)))
  142. (defcustom org-id-prefix nil
  143. "The prefix for IDs.
  144. This may be a string, or it can be nil to indicate that no prefix is required.
  145. When a string, the string should have no space characters as IDs are expected
  146. to have no space characters in them."
  147. :group 'org-id
  148. :type '(choice
  149. (const :tag "No prefix")
  150. (string :tag "Prefix")))
  151. (defcustom org-id-include-domain nil
  152. "Non-nil means add the domain name to new IDs.
  153. This ensures global uniqueness of IDs, and is also suggested by
  154. the relevant RFCs. This is relevant only if `org-id-method' is
  155. `org' or `ts'. When uuidgen is used, the domain will never be added.
  156. The default is to not use this because we have no really good way to get
  157. the true domain, and Org entries will normally not be shared with enough
  158. people to make this necessary."
  159. :group 'org-id
  160. :type 'boolean)
  161. (defcustom org-id-track-globally t
  162. "Non-nil means track IDs through files, so that links work globally.
  163. This work by maintaining a hash table for IDs and writing this table
  164. to disk when exiting Emacs. Because of this, it works best if you use
  165. a single Emacs process, not many.
  166. When nil, IDs are not tracked. Links to IDs will still work within
  167. a buffer, but not if the entry is located in another file.
  168. IDs can still be used if the entry with the id is in the same file as
  169. the link."
  170. :group 'org-id
  171. :type 'boolean)
  172. (defcustom org-id-locations-file (locate-user-emacs-file ".org-id-locations")
  173. "The file for remembering in which file an ID was defined.
  174. This variable is only relevant when `org-id-track-globally' is set."
  175. :group 'org-id
  176. :type 'file)
  177. (defcustom org-id-locations-file-relative nil
  178. "Determine if `org-id-locations' should be stored as relative links.
  179. Non-nil means that links to locations are stored as links
  180. relative to the location of where `org-id-locations-file' is
  181. stored.
  182. Nil means to store absolute paths to files.
  183. This customization is useful when folders are shared across
  184. systems but mounted at different roots. Relative path to
  185. `org-id-locations-file' still has to be maintained across
  186. systems."
  187. :group 'org-id
  188. :type 'boolean
  189. :package-version '(Org . "9.3"))
  190. (defvar org-id-locations nil
  191. "List of files with IDs in those files.")
  192. (defvar org-id-files nil
  193. "List of files that contain IDs.")
  194. (defcustom org-id-extra-files 'org-agenda-text-search-extra-files
  195. "Files to be searched for IDs, besides the agenda files.
  196. When Org reparses files to remake the list of files and IDs it is tracking,
  197. it will normally scan the agenda files, the archives related to agenda files,
  198. any files that are listed as ID containing in the current register, and
  199. any Org file currently visited by Emacs.
  200. You can list additional files here.
  201. This variable is only relevant when `org-id-track-globally' is set."
  202. :group 'org-id
  203. :type
  204. '(choice
  205. (symbol :tag "Variable")
  206. (repeat :tag "List of files"
  207. (file))))
  208. (defcustom org-id-search-archives t
  209. "Non-nil means search also the archive files of agenda files for entries.
  210. This is a possibility to reduce overhead, but it means that entries moved
  211. to the archives can no longer be found by ID.
  212. This variable is only relevant when `org-id-track-globally' is set."
  213. :group 'org-id
  214. :type 'boolean)
  215. ;;; The API functions
  216. ;;;###autoload
  217. (defun org-id-get-create (&optional force)
  218. "Create an ID for the current entry and return it.
  219. If the entry already has an ID, just return it.
  220. With optional argument FORCE, force the creation of a new ID."
  221. (interactive "P")
  222. (when force
  223. (org-entry-put (point) "ID" nil))
  224. (org-id-get (point) 'create))
  225. ;;;###autoload
  226. (defun org-id-copy ()
  227. "Copy the ID of the entry at point to the kill ring.
  228. Create an ID if necessary."
  229. (interactive)
  230. (org-kill-new (org-id-get nil 'create)))
  231. (defvar org-id-overriding-file-name nil
  232. "Tell `org-id-get' to use this as the file name when creating an ID.
  233. This is useful when working with contents in a temporary buffer
  234. that will be copied back to the original.")
  235. ;;;###autoload
  236. (defun org-id-get (&optional pom create prefix)
  237. "Get the ID property of the entry at point-or-marker POM.
  238. If POM is nil, refer to the entry at point.
  239. If the entry does not have an ID, the function returns nil.
  240. However, when CREATE is non-nil, create an ID if none is present already.
  241. PREFIX will be passed through to `org-id-new'.
  242. In any case, the ID of the entry is returned."
  243. (org-with-point-at pom
  244. (let ((id (org-entry-get nil "ID")))
  245. (cond
  246. ((and id (stringp id) (string-match "\\S-" id))
  247. id)
  248. (create
  249. (setq id (org-id-new prefix))
  250. (org-entry-put pom "ID" id)
  251. (org-id-add-location id
  252. (or org-id-overriding-file-name
  253. (buffer-file-name (buffer-base-buffer))))
  254. id)))))
  255. ;;;###autoload
  256. (defun org-id-get-with-outline-path-completion (&optional targets)
  257. "Use `outline-path-completion' to retrieve the ID of an entry.
  258. TARGETS may be a setting for `org-refile-targets' to define
  259. eligible headlines. When omitted, all headlines in the current
  260. file are eligible. This function returns the ID of the entry.
  261. If necessary, the ID is created."
  262. (let* ((org-refile-targets (or targets '((nil . (:maxlevel . 10)))))
  263. (org-refile-use-outline-path
  264. (if (caar org-refile-targets) 'file t))
  265. (org-refile-target-verify-function nil)
  266. (spos (org-refile-get-location "Entry"))
  267. (pom (and spos (move-marker (make-marker) (or (nth 3 spos) 1)
  268. (get-file-buffer (nth 1 spos))))))
  269. (prog1 (org-id-get pom 'create)
  270. (move-marker pom nil))))
  271. ;;;###autoload
  272. (defun org-id-get-with-outline-drilling ()
  273. "Use an outline-cycling interface to retrieve the ID of an entry.
  274. This only finds entries in the current buffer, using `org-goto-location'.
  275. It returns the ID of the entry. If necessary, the ID is created."
  276. (let* ((spos (org-goto-location))
  277. (pom (and spos (move-marker (make-marker) (car spos)))))
  278. (prog1 (org-id-get pom 'create)
  279. (move-marker pom nil))))
  280. ;;;###autoload
  281. (defun org-id-goto (id)
  282. "Switch to the buffer containing the entry with id ID.
  283. Move the cursor to that entry in that buffer."
  284. (interactive "sID: ")
  285. (let ((m (org-id-find id 'marker)))
  286. (unless m
  287. (error "Cannot find entry with ID \"%s\"" id))
  288. (pop-to-buffer-same-window (marker-buffer m))
  289. (goto-char m)
  290. (move-marker m nil)
  291. (org-fold-show-context)))
  292. ;;;###autoload
  293. (defun org-id-find (id &optional markerp)
  294. "Return the location of the entry with the id ID.
  295. The return value is a cons cell (file-name . position), or nil
  296. if there is no entry with that ID.
  297. With optional argument MARKERP, return the position as a new marker."
  298. (cond
  299. ((symbolp id) (setq id (symbol-name id)))
  300. ((numberp id) (setq id (number-to-string id))))
  301. (let ((file (org-id-find-id-file id))
  302. org-agenda-new-buffers where)
  303. (when file
  304. (setq where (org-id-find-id-in-file id file markerp)))
  305. (unless where
  306. (org-id-update-id-locations nil t)
  307. (setq file (org-id-find-id-file id))
  308. (when file
  309. (setq where (org-id-find-id-in-file id file markerp))))
  310. where))
  311. ;;; Internal functions
  312. ;; Creating new IDs
  313. ;;;###autoload
  314. (defun org-id-new (&optional prefix)
  315. "Create a new globally unique ID.
  316. An ID consists of two parts separated by a colon:
  317. - a prefix
  318. - a unique part that will be created according to `org-id-method'.
  319. PREFIX can specify the prefix, the default is given by the variable
  320. `org-id-prefix'. However, if PREFIX is the symbol `none', don't use any
  321. prefix even if `org-id-prefix' specifies one.
  322. So a typical ID could look like \"Org:4nd91V40HI\"."
  323. (let* ((prefix (if (eq prefix 'none)
  324. ""
  325. (concat (or prefix org-id-prefix) ":")))
  326. unique)
  327. (if (equal prefix ":") (setq prefix ""))
  328. (cond
  329. ((memq org-id-method '(uuidgen uuid))
  330. (setq unique (org-trim (shell-command-to-string org-id-uuid-program)))
  331. (unless (org-uuidgen-p unique)
  332. (setq unique (org-id-uuid))))
  333. ((eq org-id-method 'org)
  334. (let* ((etime (org-reverse-string (org-id-time-to-b36)))
  335. (postfix (when org-id-include-domain
  336. (require 'message)
  337. (concat "@" (message-make-fqdn)))))
  338. (setq unique (concat etime postfix))))
  339. ((eq org-id-method 'ts)
  340. (let ((ts (format-time-string org-id-ts-format))
  341. (postfix (when org-id-include-domain
  342. (require 'message)
  343. (concat "@" (message-make-fqdn)))))
  344. (setq unique (concat ts postfix))))
  345. (t (error "Invalid `org-id-method'")))
  346. (concat prefix unique)))
  347. (defun org-id-uuid ()
  348. "Return string with random (version 4) UUID."
  349. (let ((rnd (md5 (format "%s%s%s%s%s%s%s"
  350. (random)
  351. (org-time-convert-to-list nil)
  352. (user-uid)
  353. (emacs-pid)
  354. (user-full-name)
  355. user-mail-address
  356. (recent-keys)))))
  357. (format "%s-%s-4%s-%s%s-%s"
  358. (substring rnd 0 8)
  359. (substring rnd 8 12)
  360. (substring rnd 13 16)
  361. (format "%x"
  362. (logior
  363. #b10000000
  364. (logand
  365. #b10111111
  366. (string-to-number
  367. (substring rnd 16 18) 16))))
  368. (substring rnd 18 20)
  369. (substring rnd 20 32))))
  370. (defun org-id-int-to-b36-one-digit (integer)
  371. "Convert INTEGER between 0 and 61 into a single character 0..9, A..Z, a..z."
  372. (cond
  373. ((< integer 10) (+ ?0 integer))
  374. ((< integer 36) (+ ?a integer -10))
  375. (t (error "Larger that 35"))))
  376. (defun org-id-b36-to-int-one-digit (i)
  377. "Convert character 0..9, A..Z, a..z into a number 0..61.
  378. The input I may be a character, or a single-letter string."
  379. (and (stringp i) (setq i (string-to-char i)))
  380. (cond
  381. ((and (>= i ?0) (<= i ?9)) (- i ?0))
  382. ((and (>= i ?a) (<= i ?z)) (+ (- i ?a) 10))
  383. (t (error "Invalid b36 letter"))))
  384. (defun org-id-int-to-b36 (integer &optional length)
  385. "Convert an INTEGER to a base-36 number represented as a string.
  386. The returned string is padded with leading zeros to LENGTH if necessary."
  387. (let ((s "")
  388. (i integer))
  389. (while (> i 0)
  390. (setq s (concat (char-to-string
  391. (org-id-int-to-b36-one-digit (mod i 36))) s)
  392. i (/ i 36)))
  393. (setq length (max 1 (or length 1)))
  394. (if (< (length s) length)
  395. (setq s (concat (make-string (- length (length s)) ?0) s)))
  396. s))
  397. (defun org-id-b36-to-int (string)
  398. "Convert a base-36 STRING into the corresponding integer."
  399. (let ((r 0))
  400. (mapc (lambda (i) (setq r (+ (* r 36) (org-id-b36-to-int-one-digit i))))
  401. string)
  402. r))
  403. (defun org-id-time-to-b36 (&optional time)
  404. "Encode TIME as a 12-digit string.
  405. This string holds the time to micro-second accuracy, and can be decoded
  406. using `org-id-decode'."
  407. ;; FIXME: If TIME represents N seconds after the epoch, then
  408. ;; this encoding assumes 0 <= N < 110075314176 = (* (expt 36 4) 65536),
  409. ;; i.e., that TIME is from 1970-01-01 00:00:00 to 5458-02-23 20:09:36 UTC.
  410. (setq time (org-time-convert-to-list nil))
  411. (concat (org-id-int-to-b36 (nth 0 time) 4)
  412. (org-id-int-to-b36 (nth 1 time) 4)
  413. (org-id-int-to-b36 (nth 2 time) 4)))
  414. (defun org-id-decode (id)
  415. "Split ID into the prefix and the time value that was used to create it.
  416. The return value is (prefix . time) where PREFIX is nil or a string,
  417. and TIME is a Lisp time value (HI LO USEC)."
  418. (let (prefix time parts)
  419. (setq parts (org-split-string id ":"))
  420. (if (= 2 (length parts))
  421. (setq prefix (car parts) time (nth 1 parts))
  422. (setq prefix nil time (nth 0 parts)))
  423. (setq time (org-reverse-string time))
  424. (setq time (list (org-id-b36-to-int (substring time 0 4))
  425. (org-id-b36-to-int (substring time 4 8))
  426. (org-id-b36-to-int (substring time 8 12))))
  427. (cons prefix time)))
  428. ;; Storing ID locations (files)
  429. ;;;###autoload
  430. (defun org-id-update-id-locations (&optional files silent)
  431. "Scan relevant files for IDs.
  432. Store the relation between files and corresponding IDs.
  433. This will scan all agenda files, all associated archives, all open Org
  434. files, and all files currently mentioned in `org-id-locations'.
  435. When FILES is given, scan also these files.
  436. If SILENT is non-nil, messages are suppressed."
  437. (interactive)
  438. (unless org-id-track-globally
  439. (error "Please turn on `org-id-track-globally' if you want to track IDs"))
  440. (setq org-id-locations nil)
  441. (let* ((files
  442. (delete-dups
  443. (mapcar #'file-truename
  444. (cl-remove-if-not
  445. ;; Default `org-id-extra-files' value contains
  446. ;; `agenda-archives' symbol.
  447. #'stringp
  448. (append
  449. ;; Agenda files and all associated archives.
  450. (org-agenda-files t org-id-search-archives)
  451. ;; Explicit extra files.
  452. (if (symbolp org-id-extra-files)
  453. (symbol-value org-id-extra-files)
  454. org-id-extra-files)
  455. ;; All files known to have IDs.
  456. org-id-files
  457. ;; All Org files open in Emacs.
  458. (mapcar #'buffer-file-name (org-buffer-list 'files t))
  459. ;; Additional files from function call.
  460. files)))))
  461. (nfiles (length files))
  462. (id-regexp
  463. (rx (seq bol (0+ (any "\t ")) ":ID:" (1+ " ") (not (any " ")))))
  464. (seen-ids nil)
  465. (ndup 0)
  466. (i 0))
  467. (with-temp-buffer
  468. (org-element-with-disabled-cache
  469. (delay-mode-hooks
  470. (org-mode)
  471. (dolist (file files)
  472. (when (file-exists-p file)
  473. (unless silent
  474. (cl-incf i)
  475. (message "Finding ID locations (%d/%d files): %s" i nfiles file))
  476. (insert-file-contents file nil nil nil 'replace)
  477. (let ((ids nil)
  478. (case-fold-search t))
  479. (org-with-point-at 1
  480. (while (re-search-forward id-regexp nil t)
  481. (when (org-at-property-p)
  482. (push (org-entry-get (point) "ID") ids)))
  483. (when ids
  484. (push (cons (abbreviate-file-name file) ids)
  485. org-id-locations)
  486. (dolist (id ids)
  487. (cond
  488. ((not (member id seen-ids)) (push id seen-ids))
  489. (silent nil)
  490. (t
  491. (message "Duplicate ID %S" id)
  492. (cl-incf ndup))))))))))))
  493. (setq org-id-files (mapcar #'car org-id-locations))
  494. (org-id-locations-save)
  495. ;; Now convert to a hash table.
  496. (setq org-id-locations (org-id-alist-to-hash org-id-locations))
  497. (when (and (not silent) (> ndup 0))
  498. (warn "WARNING: %d duplicate IDs found, check *Messages* buffer" ndup))
  499. (message "%d files scanned, %d files contains IDs, and %d IDs found."
  500. nfiles (length org-id-files) (hash-table-count org-id-locations))
  501. org-id-locations))
  502. (defun org-id-locations-save ()
  503. "Save `org-id-locations' in `org-id-locations-file'."
  504. (when (and org-id-track-globally org-id-locations)
  505. (let ((out (if (hash-table-p org-id-locations)
  506. (org-id-hash-to-alist org-id-locations)
  507. org-id-locations)))
  508. (when (and org-id-locations-file-relative out)
  509. (setq out (mapcar
  510. (lambda (item)
  511. (if (file-name-absolute-p (car item))
  512. (cons (file-relative-name
  513. (car item) (file-name-directory
  514. org-id-locations-file))
  515. (cdr item))
  516. item))
  517. out)))
  518. (with-temp-file org-id-locations-file
  519. (let ((print-level nil)
  520. (print-length nil))
  521. (print out (current-buffer)))))))
  522. (defun org-id-locations-load ()
  523. "Read the data from `org-id-locations-file'."
  524. (setq org-id-locations nil)
  525. (when org-id-track-globally
  526. (with-temp-buffer
  527. (condition-case nil
  528. (progn
  529. (insert-file-contents org-id-locations-file)
  530. (setq org-id-locations (read (current-buffer)))
  531. (let ((loc (file-name-directory org-id-locations-file)))
  532. (mapc (lambda (item)
  533. (unless (file-name-absolute-p (car item))
  534. (setf (car item) (expand-file-name (car item) loc))))
  535. org-id-locations)))
  536. (error
  537. (message "Could not read `org-id-locations' from %s, setting it to nil"
  538. org-id-locations-file))))
  539. (setq org-id-files (mapcar 'car org-id-locations))
  540. (setq org-id-locations (org-id-alist-to-hash org-id-locations))))
  541. (defun org-id-add-location (id file)
  542. "Add the ID with location FILE to the database of ID locations."
  543. ;; Only if global tracking is on, and when the buffer has a file
  544. (unless file
  545. (error "`org-id-get' expects a file-visiting buffer"))
  546. (let ((afile (abbreviate-file-name file)))
  547. (when (and org-id-track-globally id)
  548. (unless org-id-locations (org-id-locations-load))
  549. (puthash id afile org-id-locations)
  550. (unless (member afile org-id-files)
  551. (add-to-list 'org-id-files afile)))))
  552. (unless noninteractive
  553. (add-hook 'kill-emacs-hook 'org-id-locations-save))
  554. (defun org-id-hash-to-alist (hash)
  555. "Turn an org-id HASH into an alist.
  556. This is to be able to write it to a file."
  557. (let (res x)
  558. (maphash
  559. (lambda (k v)
  560. (if (setq x (assoc v res))
  561. (setcdr x (cons k (cdr x)))
  562. (push (list v k) res)))
  563. hash)
  564. res))
  565. (defun org-id-alist-to-hash (list)
  566. "Turn an org-id location LIST into a hash table."
  567. (let ((res (make-hash-table
  568. :test 'equal
  569. :size (apply '+ (mapcar 'length list))))
  570. f)
  571. (mapc
  572. (lambda (x)
  573. (setq f (car x))
  574. (mapc (lambda (i) (puthash i f res)) (cdr x)))
  575. list)
  576. res))
  577. (defun org-id-paste-tracker (txt &optional buffer-or-file)
  578. "Update any ids in TXT and assign BUFFER-OR-FILE to them."
  579. (when org-id-track-globally
  580. (save-match-data
  581. (setq buffer-or-file (or buffer-or-file (current-buffer)))
  582. (when (bufferp buffer-or-file)
  583. (setq buffer-or-file (or (buffer-base-buffer buffer-or-file)
  584. buffer-or-file))
  585. (setq buffer-or-file (buffer-file-name buffer-or-file)))
  586. (when buffer-or-file
  587. (let ((fname (abbreviate-file-name buffer-or-file))
  588. (s 0))
  589. (while (string-match "^[ \t]*:ID:[ \t]+\\([^ \t\n\r]+\\)" txt s)
  590. (setq s (match-end 0))
  591. (org-id-add-location (match-string 1 txt) fname)))))))
  592. ;; Finding entries with specified id
  593. ;;;###autoload
  594. (defun org-id-find-id-file (id)
  595. "Query the id database for the file in which ID is located."
  596. (unless org-id-locations (org-id-locations-load))
  597. (or (and org-id-locations
  598. (hash-table-p org-id-locations)
  599. (gethash id org-id-locations))
  600. ;; Fall back on current buffer
  601. (buffer-file-name (or (buffer-base-buffer (current-buffer))
  602. (current-buffer)))))
  603. (defun org-id-find-id-in-file (id file &optional markerp)
  604. "Return the position of the entry ID in FILE.
  605. If that files does not exist, or if it does not contain this ID,
  606. return nil.
  607. The position is returned as a cons cell (file-name . position). With
  608. optional argument MARKERP, return the position as a new marker."
  609. (cond
  610. ((not file) nil)
  611. ((not (file-exists-p file)) nil)
  612. (t
  613. (let* ((visiting (find-buffer-visiting file))
  614. (buffer (or visiting (find-file-noselect file))))
  615. (unwind-protect
  616. (with-current-buffer buffer
  617. (let ((pos (org-find-entry-with-id id)))
  618. (cond
  619. ((null pos) nil)
  620. (markerp (move-marker (make-marker) pos buffer))
  621. (t (cons file pos)))))
  622. ;; Remove opened buffer in the process.
  623. (unless (or visiting markerp) (kill-buffer buffer)))))))
  624. ;; id link type
  625. ;; Calling the following function is hard-coded into `org-store-link',
  626. ;; so we do have to add it to `org-store-link-functions'.
  627. ;;;###autoload
  628. (defun org-id-store-link ()
  629. "Store a link to the current entry, using its ID.
  630. If before first heading store first title-keyword as description
  631. or filename if no title."
  632. (interactive)
  633. (when (and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  634. (let* ((link (concat "id:" (org-id-get-create)))
  635. (case-fold-search nil)
  636. (desc (save-excursion
  637. (org-back-to-heading-or-point-min t)
  638. (cond ((org-before-first-heading-p)
  639. (let ((keywords (org-collect-keywords '("TITLE"))))
  640. (if keywords
  641. (cadr (assoc "TITLE" keywords))
  642. (file-name-nondirectory
  643. (buffer-file-name (buffer-base-buffer))))))
  644. ((looking-at org-complex-heading-regexp)
  645. (if (match-end 4)
  646. (match-string 4)
  647. (match-string 0)))
  648. (t link)))))
  649. (org-link-store-props :link link :description desc :type "id")
  650. link)))
  651. (defun org-id-open (id _)
  652. "Go to the entry with id ID."
  653. (org-mark-ring-push)
  654. (let ((m (org-id-find id 'marker))
  655. cmd)
  656. (unless m
  657. (error "Cannot find entry with ID \"%s\"" id))
  658. ;; Use a buffer-switching command in analogy to finding files
  659. (setq cmd
  660. (or
  661. (cdr
  662. (assq
  663. (cdr (assq 'file org-link-frame-setup))
  664. '((find-file . switch-to-buffer)
  665. (find-file-other-window . switch-to-buffer-other-window)
  666. (find-file-other-frame . switch-to-buffer-other-frame))))
  667. 'switch-to-buffer-other-window))
  668. (if (not (equal (current-buffer) (marker-buffer m)))
  669. (funcall cmd (marker-buffer m)))
  670. (goto-char m)
  671. (move-marker m nil)
  672. (org-fold-show-context)))
  673. (org-link-set-parameters "id" :follow #'org-id-open)
  674. (provide 'org-id)
  675. ;; Local variables:
  676. ;; generated-autoload-file: "org-loaddefs.el"
  677. ;; End:
  678. ;;; org-id.el ends here