Release 6.17b
[org-mode.git] / lisp / org-id.el
blobbb832151b734d3746de03d2d354bb3cedddd152a
1 ;;; org-id.el --- Global identifiers for Org-mode entries
2 ;; Copyright (C) 2008 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Carsten Dominik <carsten at orgmode dot org>
5 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: http://orgmode.org
7 ;; Version: 6.17b
8 ;;
9 ;; This file is part of GNU Emacs.
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.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file implements globally unique identifiers for Org-mode entries.
28 ;; Identifiers are stored in the entry as an :ID: property. Functions
29 ;; are provided that create and retrieve such identifiers, and that find
30 ;; entries based on the identifier.
32 ;; Identifiers consist of a prefix (default "Org" given by the variable
33 ;; `org-id-prefix') and a unique part that can be created by a number
34 ;; of different methods, see the variable `org-id-method'.
35 ;; Org has a builtin method that uses a compact encoding of the creation
36 ;; time of the ID, with microsecond accuracy. This virtually
37 ;; guarantees globally unique identifiers, even if several people are
38 ;; creating IDs at the same time in files that will eventually be used
39 ;; together. As an external method `uuidgen' is supported, if installed
40 ;; on the system.
42 ;; This file defines the following API:
44 ;; org-id-get-create
45 ;; Create an ID for the entry at point if it does not yet have one.
46 ;; Returns the ID (old or new). This function can be used
47 ;; interactively, with prefix argument the creation of a new ID is
48 ;; forced, even if there was an old one.
50 ;; org-id-get
51 ;; Get the ID property of an entry. Using appropriate arguments
52 ;; to the function, it can also create the ID for this entry.
54 ;; org-id-goto
55 ;; Command to go to a specific ID, this command can be used
56 ;; interactively.
58 ;; org-id-get-with-outline-path-completion
59 ;; Retrieve the ID of an entry, using outline path completion.
60 ;; This function can work for multiple files.
62 ;; org-id-get-with-outline-drilling
63 ;; Retrieve the ID of an entry, using outline path completion.
64 ;; This function only works for the current file.
66 ;; org-id-find
67 ;; Find the location of an entry with specific id.
70 (require 'org)
72 (declare-function message-make-fqdn "message" ())
74 ;;; Customization
76 (defgroup org-id nil
77 "Options concerning global entry identifiers in Org-mode."
78 :tag "Org ID"
79 :group 'org)
82 (defcustom org-id-method
83 (condition-case nil
84 (if (string-match "\\`[-0-9a-fA-F]\\{36\\}\\'"
85 (org-trim (shell-command-to-string "uuidgen")))
86 'uuidgen
87 'org)
88 (error 'org))
89 "The method that should be used to create new IDs.
91 If `uuidgen' is available on the system, it will be used as the default method.
92 if not, the method `org' is used.
93 An ID will consist of the optional prefix specified in `org-id-prefix',
94 and a unique part created by the method this variable specifies.
96 Allowed values are:
98 org Org's own internal method, using an encoding of the current time to
99 microsecond accuracy, and optionally the current domain of the
100 computer. See the variable `org-id-include-domain'.
102 uuidgen Call the external command uuidgen."
103 :group 'org-id
104 :type '(choice
105 (const :tag "Org's internal method" org)
106 (const :tag "external: uuidgen" uuidgen)))
108 (defcustom org-id-prefix nil
109 "The prefix for IDs.
111 This may be a string, or it can be nil to indicate that no prefix is required.
112 When a string, the string should have no space characters as IDs are expected
113 to have no space characters in them."
114 :group 'org-id
115 :type '(choice
116 (const :tag "No prefix")
117 (string :tag "Prefix")))
119 (defcustom org-id-include-domain nil
120 "Non-nil means, add the domain name to new IDs.
121 This ensures global uniqueness of IDs, and is also suggested by
122 RFC 2445 in combination with RFC 822. This is only relevant if
123 `org-id-method' is `org'. When uuidgen is used, the domain will never
124 be added.
125 The default is to not use this because we have no really good way to get
126 the true domain, and Org entries will normally not be shared with enough
127 people to make this necessary."
128 :group 'org-id
129 :type 'boolean)
131 (defcustom org-id-track-globally t
132 "Non-nil means, track IDs through files, so that links work globally.
133 This work by maintaining a hash table for IDs and writing this table
134 to disk when exiting Emacs. Because of this, it works best if you use
135 a single Emacs process, not many.
137 When nil, IDs are not tracked. Links to IDs will still work within
138 a buffer, but not if the entry is located in another file.
139 IDs can still be used if the entry with the id is in the same file as
140 the link."
141 :group 'org-id
142 :type 'boolean)
144 (defcustom org-id-locations-file (convert-standard-filename
145 "~/.emacs.d/.org-id-locations")
146 "The file for remembering in which file an ID was defined.
147 This variable is only relevant when `org-id-track-globally' is set."
148 :group 'org-id
149 :type 'file)
151 (defvar org-id-locations nil
152 "List of files with IDs in those files.
153 Depending on `org-id-use-hash' this can also be a hash table mapping IDs
154 to files.")
156 (defvar org-id-files nil
157 "List of files that contain IDs.")
159 (defcustom org-id-extra-files 'org-agenda-text-search-extra-files
160 "Files to be searched for IDs, besides the agenda files.
161 When Org reparses files to remake the list of files and IDs it is tracking,
162 it will normally scan the agenda files, the archives related to agenda files,
163 any files that are listed as ID containing in the current register, and
164 any Org-mode files currently visited by Emacs.
165 You can list additional files here.
166 This variable is only relevant when `org-id-track-globally' is set."
167 :group 'org-id
168 :type
169 '(choice
170 (symbol :tag "Variable")
171 (repeat :tag "List of files"
172 (file))))
174 (defcustom org-id-search-archives t
175 "Non-nil means, search also the archive files of agenda files for entries.
176 This is a possibility to reduce overhead, but it means that entries moved
177 to the archives can no longer be found by ID.
178 This variable is only relevant when `org-id-track-globally' is set."
179 :group 'org-id
180 :type 'boolean)
182 ;;; The API functions
184 ;;;###autoload
185 (defun org-id-get-create (&optional force)
186 "Create an ID for the current entry and return it.
187 If the entry already has an ID, just return it.
188 With optional argument FORCE, force the creation of a new ID."
189 (interactive "P")
190 (when force
191 (org-entry-put (point) "ID" nil))
192 (org-id-get (point) 'create))
194 ;;;###autoload
195 (defun org-id-copy ()
196 "Copy the ID of the entry at point to the kill ring.
197 Create an ID if necessary."
198 (interactive)
199 (kill-new (org-id-get nil 'create)))
201 ;;;###autoload
202 (defun org-id-get (&optional pom create prefix)
203 "Get the ID property of the entry at point-or-marker POM.
204 If POM is nil, refer to the entry at point.
205 If the entry does not have an ID, the function returns nil.
206 However, when CREATE is non nil, create an ID if none is present already.
207 PREFIX will be passed through to `org-id-new'.
208 In any case, the ID of the entry is returned."
209 (let ((id (org-entry-get pom "ID")))
210 (cond
211 ((and id (stringp id) (string-match "\\S-" id))
213 (create
214 (setq id (org-id-new prefix))
215 (org-entry-put pom "ID" id)
216 (org-id-add-location id (buffer-file-name (buffer-base-buffer)))
218 (t nil))))
220 ;;;###autoload
221 (defun org-id-get-with-outline-path-completion (&optional targets)
222 "Use outline-path-completion to retrieve the ID of an entry.
223 TARGETS may be a setting for `org-refile-targets' to define the eligible
224 headlines. When omitted, all headlines in all agenda files are
225 eligible.
226 It returns the ID of the entry. If necessary, the ID is created."
227 (let* ((org-refile-targets (or targets '((nil . (:maxlevel . 10)))))
228 (org-refile-use-outline-path
229 (if (caar org-refile-targets) 'file t))
230 (spos (org-refile-get-location "Entry: "))
231 (pom (and spos (move-marker (make-marker) (nth 3 spos)
232 (get-file-buffer (nth 1 spos))))))
233 (prog1 (org-id-get pom 'create)
234 (move-marker pom nil))))
236 ;;;###autoload
237 (defun org-id-get-with-outline-drilling (&optional targets)
238 "Use an outline-cycling interface to retrieve the ID of an entry.
239 This only finds entries in the current buffer, using `org-get-location'.
240 It returns the ID of the entry. If necessary, the ID is created."
241 (let* ((spos (org-get-location (current-buffer) org-goto-help))
242 (pom (and spos (move-marker (make-marker) (car spos)))))
243 (prog1 (org-id-get pom 'create)
244 (move-marker pom nil))))
246 ;;;###autoload
247 (defun org-id-goto (id)
248 "Switch to the buffer containing the entry with id ID.
249 Move the cursor to that entry in that buffer."
250 (interactive "sID: ")
251 (let ((m (org-id-find id 'marker)))
252 (unless m
253 (error "Cannot find entry with ID \"%s\"" id))
254 (switch-to-buffer (marker-buffer m))
255 (goto-char m)
256 (move-marker m nil)
257 (org-show-context)))
259 ;;;###autoload
260 (defun org-id-find (id &optional markerp)
261 "Return the location of the entry with the id ID.
262 The return value is a cons cell (file-name . position), or nil
263 if there is no entry with that ID.
264 With optional argument MARKERP, return the position as a new marker."
265 (cond
266 ((symbolp id) (setq id (symbol-name id)))
267 ((numberp id) (setq id (number-to-string id))))
268 (let ((file (org-id-find-id-file id))
269 org-agenda-new-buffers where)
270 (when file
271 (setq where (org-id-find-id-in-file id file markerp)))
272 (unless where
273 (org-id-update-id-locations)
274 (setq file (org-id-find-id-file id))
275 (when file
276 (setq where (org-id-find-id-in-file id file markerp))))
277 where))
279 ;;; Internal functions
281 ;; Creating new IDs
283 (defun org-id-new (&optional prefix)
284 "Create a new globally unique ID.
286 An ID consists of two parts separated by a colon:
287 - a prefix
288 - a unique part that will be created according to `org-id-method'.
290 PREFIX can specify the prefix, the default is given by the variable
291 `org-id-prefix'. However, if PREFIX is the symbol `none', don't use any
292 prefix even if `org-id-prefix' specifies one.
294 So a typical ID could look like \"Org:4nd91V40HI\"."
295 (let* ((prefix (if (eq prefix 'none)
297 (concat (or prefix org-id-prefix) ":")))
298 unique)
299 (if (equal prefix ":") (setq prefix ""))
300 (cond
301 ((eq org-id-method 'uuidgen)
302 (setq unique (org-trim (shell-command-to-string "uuidgen"))))
303 ((eq org-id-method 'org)
304 (let* ((etime (org-id-reverse-string (org-id-time-to-b36)))
305 (postfix (if org-id-include-domain
306 (progn
307 (require 'message)
308 (concat "@" (message-make-fqdn))))))
309 (setq unique (concat etime postfix))))
310 (t (error "Invalid `org-id-method'")))
311 (concat prefix unique)))
313 (defun org-id-reverse-string (s)
314 (mapconcat 'char-to-string (nreverse (string-to-list s)) ""))
316 (defun org-id-int-to-b36-one-digit (i)
317 "Turn an integer between 0 and 61 into a single character 0..9, A..Z, a..z."
318 (cond
319 ((< i 10) (+ ?0 i))
320 ((< i 36) (+ ?a i -10))
321 (t (error "Larger that 35"))))
323 (defun org-id-b36-to-int-one-digit (i)
324 "Turn a character 0..9, A..Z, a..z into a number 0..61.
325 The input I may be a character, or a single-letter string."
326 (and (stringp i) (setq i (string-to-char i)))
327 (cond
328 ((and (>= i ?0) (<= i ?9)) (- i ?0))
329 ((and (>= i ?a) (<= i ?z)) (+ (- i ?a) 10))
330 (t (error "Invalid b36 letter"))))
332 (defun org-id-int-to-b36 (i &optional length)
333 "Convert an integer to a base-36 number represented as a string."
334 (let ((s ""))
335 (while (> i 0)
336 (setq s (concat (char-to-string
337 (org-id-int-to-b36-one-digit (mod i 36))) s)
338 i (/ i 36)))
339 (setq length (max 1 (or length 1)))
340 (if (< (length s) length)
341 (setq s (concat (make-string (- length (length s)) ?0) s)))
344 (defun org-id-b36-to-int (s)
345 "Convert a base-36 string into the corresponding integer."
346 (let ((r 0))
347 (mapc (lambda (i) (setq r (+ (* r 36) (org-id-b36-to-int-one-digit i))))
351 (defun org-id-time-to-b36 (&optional time)
352 "Encode TIME as a 10-digit string.
353 This string holds the time to micro-second accuracy, and can be decoded
354 using `org-id-decode'."
355 (setq time (or time (current-time)))
356 (concat (org-id-int-to-b36 (nth 0 time) 4)
357 (org-id-int-to-b36 (nth 1 time) 4)
358 (org-id-int-to-b36 (or (nth 2 time) 0) 4)))
360 (defun org-id-decode (id)
361 "Split ID into the prefix and the time value that was used to create it.
362 The return value is (prefix . time) where PREFIX is nil or a string,
363 and time is the usual three-integer representation of time."
364 (let (prefix time parts)
365 (setq parts (org-split-string id ":"))
366 (if (= 2 (length parts))
367 (setq prefix (car parts) time (nth 1 parts))
368 (setq prefix nil time (nth 0 parts)))
369 (setq time (org-id-reverse-string time))
370 (setq time (list (org-id-b36-to-int (substring time 0 4))
371 (org-id-b36-to-int (substring time 4 8))
372 (org-id-b36-to-int (substring time 8 12))))
373 (cons prefix time)))
375 ;; Storing ID locations (files)
377 (defun org-id-update-id-locations (&optional files)
378 "Scan relevant files for IDs.
379 Store the relation between files and corresponding IDs.
380 This will scan all agenda files, all associated archives, and all
381 files currently mentioned in `org-id-locations'.
382 When FILES is given, scan these files instead.
383 When CHECK is given, prepare detailed information about duplicate IDs."
384 (interactive)
385 (if (not org-id-track-globally)
386 (error "Please turn on `org-id-track-globally' if you want to track IDs.")
387 (let ((files
388 (or files
389 (append
390 ;; Agenda files and all associated archives
391 (org-agenda-files t org-id-search-archives)
392 ;; Explicit extra files
393 (if (symbolp org-id-extra-files)
394 (symbol-value org-id-extra-files)
395 org-id-extra-files)
396 ;; Files associated with live org-mode buffers
397 (delq nil
398 (mapcar (lambda (b)
399 (with-current-buffer b
400 (and (org-mode-p) (buffer-file-name))))
401 (buffer-list)))
402 ;; All files known to have IDs
403 org-id-files)))
404 org-agenda-new-buffers
405 file nfiles tfile ids reg found id seen (ndup 0))
406 (setq nfiles (length files))
407 (while (setq file (pop files))
408 (message "Finding ID locations (%d/%d files): %s"
409 (- nfiles (length files)) nfiles file)
410 (setq tfile (file-truename file))
411 (when (and (file-exists-p file) (not (member tfile seen)))
412 (push tfile seen)
413 (setq ids nil)
414 (with-current-buffer (org-get-agenda-file-buffer file)
415 (save-excursion
416 (save-restriction
417 (widen)
418 (goto-char (point-min))
419 (while (re-search-forward "^[ \t]*:ID:[ \t]+\\(\\S-+\\)[ \t]*$"
420 nil t)
421 (setq id (org-match-string-no-properties 1))
422 (if (member id found)
423 (progn
424 (message "Duplicate ID \"%s\", also in file %s"
425 id (car (delq
427 (mapcar
428 (lambda (x)
429 (if (member id (cdr x)) (car x)))
430 reg))))
431 (when (= ndup 0)
432 (ding)
433 (sit-for 2))
434 (setq ndup (1+ ndup)))
435 (push id found)
436 (push id ids)))
437 (push (cons (abbreviate-file-name file) ids) reg))))))
438 (org-release-buffers org-agenda-new-buffers)
439 (setq org-agenda-new-buffers nil)
440 (setq org-id-locations reg)
441 (setq org-id-files (mapcar 'car org-id-locations))
442 (org-id-locations-save) ;; this function can also handle the alist form
443 ;; now convert to a hash
444 (setq org-id-locations (org-id-alist-to-hash org-id-locations))
445 (if (> ndup 0)
446 (message "WARNING: %d duplicate IDs found, check *Messages* buffer" ndup)
447 (message "%d unique files scanned for IDs" (length org-id-files)))
448 org-id-locations)))
450 (defun org-id-locations-save ()
451 "Save `org-id-locations' in `org-id-locations-file'."
452 (when org-id-track-globally
453 (let ((out (if (hash-table-p org-id-locations)
454 (org-id-hash-to-alist org-id-locations)
455 org-id-locations)))
456 (with-temp-file org-id-locations-file
457 (print out (current-buffer))))))
459 (defun org-id-locations-load ()
460 "Read the data from `org-id-locations-file'."
461 (setq org-id-locations nil)
462 (when org-id-track-globally
463 (with-temp-buffer
464 (condition-case nil
465 (progn
466 (insert-file-contents-literally org-id-locations-file)
467 (goto-char (point-min))
468 (setq org-id-locations (read (current-buffer))))
469 (error
470 (message "Could not read org-id-values from %s. Setting it to nil."
471 org-id-locations-file))))
472 (setq org-id-files (mapcar 'car org-id-locations))
473 (setq org-id-locations (org-id-alist-to-hash org-id-locations))))
475 (defun org-id-add-location (id file)
476 "Add the ID with location FILE to the database of ID locations."
477 ;; Only if global tracking is on, and when the buffer has a file
478 (when (and org-id-track-globally id file)
479 (unless org-id-locations (org-id-locations-load))
480 (puthash id (abbreviate-file-name file) org-id-locations)
481 (add-to-list 'org-id-files (abbreviate-file-name file))))
483 (add-hook 'kill-emacs-hook 'org-id-locations-save)
485 (defun org-id-hash-to-alist (hash)
486 "Turn an org-id hash into an alist, so that it can be written to a file."
487 (let (res x)
488 (maphash
489 (lambda (k v)
490 (if (setq x (member v res))
491 (setcdr x (cons k (cdr x)))
492 (push (list v k) res)))
493 hash)
494 res))
496 (defun org-id-alist-to-hash (list)
497 "Turn an org-id location list into a hash table."
498 (let ((res (make-hash-table
499 :test 'equal
500 :size (apply '+ (mapcar 'length list))))
501 f i)
502 (mapc
503 (lambda (x)
504 (setq f (car x))
505 (mapc (lambda (i) (puthash i f res)) (cdr x)))
506 list)
507 res))
509 (defun org-id-paste-tracker (txt &optional buffer-or-file)
510 "Update any IDs in TXT and assign BUFFER-OR-FILE to them."
511 (when org-id-track-globally
512 (save-match-data
513 (setq buffer-or-file (or buffer-or-file (current-buffer)))
514 (when (bufferp buffer-or-file)
515 (setq buffer-or-file (or (buffer-base-buffer buffer-or-file)
516 buffer-or-file))
517 (setq buffer-or-file (buffer-file-name buffer-or-file)))
518 (when buffer-or-file
519 (let ((fname (abbreviate-file-name buffer-or-file))
520 (s 0))
521 (while (string-match "^[ \t]*:ID:[ \t]+\\([^ \t\n\r]+\\)" txt s)
522 (setq s (match-end 0))
523 (org-id-add-location (match-string 1 txt) fname)))))))
525 ;; Finding entries with specified id
527 (defun org-id-find-id-file (id)
528 "Query the id database for the file in which this ID is located."
529 (unless org-id-locations (org-id-locations-load))
530 (or (gethash id org-id-locations)
531 ;; ball back on current buffer
532 (buffer-file-name (or (buffer-base-buffer (current-buffer))
533 (current-buffer)))))
535 (defun org-id-find-id-in-file (id file &optional markerp)
536 "Return the position of the entry ID in FILE.
537 If that files does not exist, or if it does not contain this ID,
538 return nil.
539 The position is returned as a cons cell (file-name . position). With
540 optional argument MARKERP, return the position as a new marker."
541 (let (org-agenda-new-buffers m buf pos)
542 (cond
543 ((not file) nil)
544 ((not (file-exists-p file)) nil)
545 (t (with-current-buffer (setq buf (org-get-agenda-file-buffer file))
546 (setq pos (org-find-entry-with-id id))
547 (when pos
548 (if markerp
549 (move-marker (make-marker) pos buf)
550 (cons file pos))))))))
552 ;; id link type
554 ;; Calling the following function is hard-coded into `org-store-link',
555 ;; so we do have to add it to `org-store-link-functions'.
557 (defun org-id-store-link ()
558 "Store a link to the current entry, using it's ID."
559 (interactive)
560 (let* ((link (org-make-link "id:" (org-id-get-create)))
561 (desc (save-excursion
562 (org-back-to-heading t)
563 (or (and (looking-at org-complex-heading-regexp)
564 (if (match-end 4) (match-string 4) (match-string 0)))
565 link))))
566 (org-store-link-props :link link :description desc :type "id")
567 link))
569 (defun org-id-open (id)
570 "Go to the entry with id ID."
571 (org-mark-ring-push)
572 (let ((m (org-id-find id 'marker)))
573 (unless m
574 (error "Cannot find entry with ID \"%s\"" id))
575 (if (not (equal (current-buffer) (marker-buffer m)))
576 (switch-to-buffer-other-window (marker-buffer m)))
577 (goto-char m)
578 (move-marker m nil)
579 (org-show-context)))
581 (org-add-link-type "id" 'org-id-open)
583 (provide 'org-id)
585 ;;; org-id.el ends here
587 ;; arch-tag: e5abaca4-e16f-4b25-832a-540cfb63a712