org-id.el 25 KB

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