org-id.el 26 KB

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