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