org-clone-subtree-with-time-shift: Fix SHIFT check
[org-mode.git] / lisp / org-bbdb.el
blobf851668157807c1af98dbaa207443b3b51e1217b
1 ;;; org-bbdb.el --- Support for links to BBDB entries -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Authors: Carsten Dominik <carsten at orgmode dot org>
6 ;; Thomas Baumann <thomas dot baumann at ch dot tum dot de>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
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 links to BBDB database entries from within Org.
29 ;; Org mode loads this module by default - if this is not what you want,
30 ;; configure the variable `org-modules'.
32 ;; It also implements an interface (based on Ivar Rummelhoff's
33 ;; bbdb-anniv.el) for those Org users, who do not use the diary
34 ;; but who do want to include the anniversaries stored in the BBDB
35 ;; into the org-agenda. If you already include the `diary' into the
36 ;; agenda, you might want to prefer to include the anniversaries in
37 ;; the diary using bbdb-anniv.el.
39 ;; Put the following in /somewhere/at/home/diary.org and make sure
40 ;; that this file is in `org-agenda-files'.
42 ;; %%(org-bbdb-anniversaries)
44 ;; For example my diary.org looks like:
45 ;; * Anniversaries
46 ;; #+CATEGORY: Anniv
47 ;; %%(org-bbdb-anniversaries)
50 ;; To add an anniversary to a BBDB record, press `C-o' in the record.
51 ;; You will be prompted for the field name, in this case it must be
52 ;; "anniversary". If this is the first time you are using this field,
53 ;; you need to confirm that it should be created.
55 ;; The format of an anniversary field stored in BBDB is the following
56 ;; (items in {} are optional):
58 ;; YYYY-MM-DD{ CLASS-OR-FORMAT-STRING}
59 ;; {\nYYYY-MM-DD CLASS-OR-FORMAT-STRING}...
61 ;; CLASS-OR-FORMAT-STRING is one of two things:
63 ;; - an identifier for a class of anniversaries (eg. birthday or
64 ;; wedding) from `org-bbdb-anniversary-format-alist' which then
65 ;; defines the format string for this class
66 ;; - the (format) string displayed in the diary.
68 ;; You can enter multiple anniversaries for a single BBDB record by
69 ;; separating them with a newline character. At the BBDB prompt for
70 ;; the field value, type `C-q C-j' to enter a newline between two
71 ;; anniversaries.
73 ;; If you omit the CLASS-OR-FORMAT-STRING entirely, it defaults to the
74 ;; value of `org-bbdb-default-anniversary-format' ("birthday" by
75 ;; default).
77 ;; The substitutions in the format string are (in order):
78 ;; - the name of the record containing this anniversary
79 ;; - the number of years
80 ;; - an ordinal suffix (st, nd, rd, th) for the year
82 ;; See the documentation of `org-bbdb-anniversary-format-alist' for
83 ;; further options.
85 ;; Example
87 ;; 1973-06-22
88 ;; 20??-??-?? wedding
89 ;; 1998-03-12 %s created bbdb-anniv.el %d years ago
91 ;; From Org's agenda, you can use `C-c C-o' to jump to the BBDB
92 ;; link from which the entry at point originates.
94 ;;; Code:
96 (require 'org)
97 (require 'cl-lib)
99 ;; Declare external functions and variables
101 (declare-function bbdb "ext:bbdb-com" (string elidep))
102 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
103 (declare-function bbdb-current-record "ext:bbdb-com"
104 (&optional planning-on-modifying))
105 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
106 (declare-function bbdb-completing-read-record "ext:bbdb-com"
107 (prompt &optional omit-records))
108 (declare-function bbdb-record-field "ext:bbdb" (recond field))
109 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
110 (declare-function bbdb-record-name "ext:bbdb" (record))
111 (declare-function bbdb-records "ext:bbdb"
112 (&optional dont-check-disk already-in-db-buffer))
113 (declare-function bbdb-split "ext:bbdb" (string separators))
114 (declare-function bbdb-string-trim "ext:bbdb" (string))
115 (declare-function bbdb-record-get-field "ext:bbdb" (record field))
116 (declare-function bbdb-search-name "ext:bbdb-com" (regexp &optional layout))
117 (declare-function bbdb-search-organization "ext:bbdb-com" (regexp &optional layout))
119 ;; `bbdb-record-note' was part of BBDB v3.x
120 (declare-function bbdb-record-note "ext:bbdb" (record label))
121 ;; `bbdb-record-xfield' replaces it in recent BBDB v3.x+
122 (declare-function bbdb-record-xfield "ext:bbdb" (record label))
124 (declare-function calendar-leap-year-p "calendar" (year))
125 (declare-function diary-ordinal-suffix "diary-lib" (n))
127 (with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
129 ;; Customization
131 (defgroup org-bbdb-anniversaries nil
132 "Customizations for including anniversaries from BBDB into Agenda."
133 :group 'org-bbdb)
135 (defcustom org-bbdb-default-anniversary-format "birthday"
136 "Default anniversary class."
137 :type 'string
138 :group 'org-bbdb-anniversaries
139 :require 'bbdb)
141 (defcustom org-bbdb-anniversary-format-alist
142 '(("birthday" .
143 (lambda (name years suffix)
144 (concat "Birthday: [[bbdb:" name "][" name " ("
145 (format "%s" years) ; handles numbers as well as strings
146 suffix ")]]")))
147 ("wedding" .
148 (lambda (name years suffix)
149 (concat "[[bbdb:" name "][" name "'s "
150 (format "%s" years)
151 suffix " wedding anniversary]]"))))
152 "How different types of anniversaries should be formatted.
153 An alist of elements (STRING . FORMAT) where STRING is the name of an
154 anniversary class and format is either:
155 1) A format string with the following substitutions (in order):
156 - the name of the record containing this anniversary
157 - the number of years
158 - an ordinal suffix (st, nd, rd, th) for the year
160 2) A function to be called with three arguments: NAME YEARS SUFFIX
161 (string int string) returning a string for the diary or nil.
163 3) An Emacs Lisp form that should evaluate to a string (or nil) in the
164 scope of variables NAME, YEARS and SUFFIX (among others)."
165 :type '(alist :key-type (string :tag "Class")
166 :value-type (function :tag "Function"))
167 :group 'org-bbdb-anniversaries
168 :require 'bbdb)
170 (defcustom org-bbdb-anniversary-field 'anniversary
171 "The BBDB field which contains anniversaries.
172 The anniversaries are stored in the following format
174 YYYY-MM-DD Class-or-Format-String
176 where class is one of the customized classes for anniversaries;
177 birthday and wedding are predefined. Format-String can take three
178 substitutions 1) the name of the record containing this
179 anniversary, 2) the number of years, and 3) an ordinal suffix for
180 the year.
182 Multiple anniversaries can be separated by \\n."
183 :type 'symbol
184 :group 'org-bbdb-anniversaries
185 :require 'bbdb)
187 (defcustom org-bbdb-extract-date-fun 'org-bbdb-anniv-extract-date
188 "How to retrieve `month date year' from the anniversary field.
190 Customize if you have already filled your BBDB with dates
191 different from YYYY-MM-DD. The function must return a list (month
192 date year)."
193 :type 'function
194 :group 'org-bbdb-anniversaries
195 :require 'bbdb)
197 ;; Install the link type
198 (org-link-set-parameters "bbdb"
199 :follow #'org-bbdb-open
200 :export #'org-bbdb-export
201 :complete #'org-bbdb-complete-link
202 :store #'org-bbdb-store-link)
204 ;; Implementation
205 (defun org-bbdb-store-link ()
206 "Store a link to a BBDB database entry."
207 (when (eq major-mode 'bbdb-mode)
208 ;; This is BBDB, we make this link!
209 (let* ((rec (bbdb-current-record))
210 (name (bbdb-record-name rec))
211 (company (if (fboundp 'bbdb-record-getprop)
212 (bbdb-record-getprop rec 'company)
213 (car (bbdb-record-field rec 'organization))))
214 (link (concat "bbdb:" name)))
215 (org-store-link-props :type "bbdb" :name name :company company
216 :link link :description name)
217 link)))
219 (defun org-bbdb-export (path desc format)
220 "Create the export version of a BBDB link specified by PATH or DESC.
221 If exporting to either HTML or LaTeX FORMAT the link will be
222 italicized, in all other cases it is left unchanged."
223 (when (string= desc (format "bbdb:%s" path))
224 (setq desc path))
225 (cond
226 ((eq format 'html) (format "<i>%s</i>" desc))
227 ((eq format 'latex) (format "\\textit{%s}" desc))
228 ((eq format 'odt)
229 (format "<text:span text:style-name=\"Emphasis\">%s</text:span>" desc))
230 (t desc)))
232 (defun org-bbdb-open (name)
233 "Follow a BBDB link to NAME."
234 (require 'bbdb-com)
235 (let ((inhibit-redisplay (not debug-on-error)))
236 (if (fboundp 'bbdb-name)
237 (org-bbdb-open-old name)
238 (org-bbdb-open-new name))))
240 (defun org-bbdb-open-old (name)
241 (catch 'exit
242 ;; Exact match on name
243 (bbdb-name (concat "\\`" name "\\'") nil)
244 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
245 ;; Exact match on name
246 (bbdb-company (concat "\\`" name "\\'") nil)
247 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
248 ;; Partial match on name
249 (bbdb-name name nil)
250 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
251 ;; Partial match on company
252 (bbdb-company name nil)
253 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
254 ;; General match including network address and notes
255 (bbdb name nil)
256 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
257 (delete-window (get-buffer-window "*BBDB*"))
258 (error "No matching BBDB record"))))
260 (defun org-bbdb-open-new (name)
261 (catch 'exit
262 ;; Exact match on name
263 (bbdb-search-name (concat "\\`" name "\\'") nil)
264 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
265 ;; Exact match on name
266 (bbdb-search-organization (concat "\\`" name "\\'") nil)
267 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
268 ;; Partial match on name
269 (bbdb-search-name name nil)
270 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
271 ;; Partial match on company
272 (bbdb-search-organization name nil)
273 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
274 ;; General match including network address and notes
275 (bbdb name nil)
276 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
277 (delete-window (get-buffer-window "*BBDB*"))
278 (error "No matching BBDB record"))))
280 (defun org-bbdb-anniv-extract-date (time-str)
281 "Convert YYYY-MM-DD to (month date year).
282 Argument TIME-STR is the value retrieved from BBDB. If YYYY- is omitted
283 it will be considered unknown."
284 (pcase (org-split-string time-str "-")
285 (`(,a ,b nil) (list (string-to-number a) (string-to-number b) nil))
286 (`(,a ,b ,c) (list (string-to-number b)
287 (string-to-number c)
288 (string-to-number a)))))
290 (defun org-bbdb-anniv-split (str)
291 "Split multiple entries in the BBDB anniversary field.
292 Argument STR is the anniversary field in BBDB."
293 (let ((pos (string-match "[ \t]" str)))
294 (if pos (list (substring str 0 pos)
295 (bbdb-string-trim (substring str pos)))
296 (list str nil))))
298 (defvar org-bbdb-anniv-hash nil
299 "A hash holding anniversaries extracted from BBDB.
300 The hash table is created on first use.")
302 (defvar org-bbdb-updated-p t
303 "This is non-nil if BBDB has been updated since we last built the hash.")
305 (defun org-bbdb-make-anniv-hash ()
306 "Create a hash with anniversaries extracted from BBDB, for fast access.
307 The anniversaries are assumed to be stored `org-bbdb-anniversary-field'."
308 (let ((old-bbdb (fboundp 'bbdb-record-getprop))
309 (record-func (if (fboundp 'bbdb-record-xfield)
310 'bbdb-record-xfield
311 'bbdb-record-note))
312 split tmp annivs)
313 (clrhash org-bbdb-anniv-hash)
314 (dolist (rec (bbdb-records))
315 (when (setq annivs (if old-bbdb
316 (bbdb-record-getprop
317 rec org-bbdb-anniversary-field)
318 (funcall record-func
319 rec org-bbdb-anniversary-field)))
320 (setq annivs (if old-bbdb
321 (bbdb-split annivs "\n")
322 ;; parameter order is reversed in new bbdb
323 (bbdb-split "\n" annivs)))
324 (while annivs
325 (setq split (org-bbdb-anniv-split (pop annivs)))
326 (pcase-let ((`(,m ,d ,y) (funcall org-bbdb-extract-date-fun
327 (car split))))
328 (setq tmp (gethash (list m d) org-bbdb-anniv-hash))
329 (puthash (list m d) (cons (list y
330 (bbdb-record-name rec)
331 (cadr split))
332 tmp)
333 org-bbdb-anniv-hash))))))
334 (setq org-bbdb-updated-p nil))
336 (defun org-bbdb-updated (_rec)
337 "Record the fact that BBDB has been updated.
338 This is used by Org to re-create the anniversary hash table."
339 (setq org-bbdb-updated-p t))
341 (add-hook 'bbdb-after-change-hook 'org-bbdb-updated)
343 ;;;###autoload
344 (defun org-bbdb-anniversaries ()
345 "Extract anniversaries from BBDB for display in the agenda."
346 (require 'bbdb)
347 (require 'diary-lib)
348 (unless (hash-table-p org-bbdb-anniv-hash)
349 (setq org-bbdb-anniv-hash
350 (make-hash-table :test 'equal :size 366)))
352 (when (or org-bbdb-updated-p
353 (= 0 (hash-table-count org-bbdb-anniv-hash)))
354 (org-bbdb-make-anniv-hash))
356 (let* ((m (car date)) ; month
357 (d (nth 1 date)) ; day
358 (y (nth 2 date)) ; year
359 (annivs (gethash (list m d) org-bbdb-anniv-hash))
360 (text ())
361 rec recs)
363 ;; we don't want to miss people born on Feb. 29th
364 (when (and (= m 3) (= d 1)
365 (not (null (gethash (list 2 29) org-bbdb-anniv-hash)))
366 (not (calendar-leap-year-p y)))
367 (setq recs (gethash (list 2 29) org-bbdb-anniv-hash))
368 (while (setq rec (pop recs))
369 (push rec annivs)))
371 (when annivs
372 (while (setq rec (pop annivs))
373 (when rec
374 (let* ((class (or (nth 2 rec)
375 org-bbdb-default-anniversary-format))
376 (form (or (cdr (assoc-string
377 class org-bbdb-anniversary-format-alist t))
378 class)) ; (as format string)
379 (name (nth 1 rec))
380 (years (if (eq (car rec) nil)
381 "unknown"
382 (- y (car rec))))
383 (suffix (if (eq (car rec) nil)
385 (diary-ordinal-suffix years)))
386 (tmp (cond
387 ((functionp form)
388 (funcall form name years suffix))
389 ((listp form) (eval form))
390 (t (format form name years suffix)))))
391 (org-add-props tmp nil 'org-bbdb-name name)
392 (if text
393 (setq text (append text (list tmp)))
394 (setq text (list tmp)))))
396 text))
398 ;;; Return list of anniversaries for today and the next n-1 (default: n=7) days.
399 ;;; This is meant to be used in an org file instead of org-bbdb-anniversaries:
401 ;;; %%(org-bbdb-anniversaries-future)
403 ;;; or
405 ;;; %%(org-bbdb-anniversaries-future 3)
407 ;;; to override the 7-day default.
409 (defun org-bbdb-date-list (d n)
410 "Return a list of dates in (m d y) format from the given date D to n-1 days hence."
411 (let ((abs (calendar-absolute-from-gregorian d)))
412 (mapcar (lambda (i) (calendar-gregorian-from-absolute (+ abs i)))
413 (number-sequence 0 (1- n)))))
415 ;;;###autoload
416 (defun org-bbdb-anniversaries-future (&optional n)
417 "Return list of anniversaries for today and the next n-1 days (default n=7)."
418 (let ((n (or n 7)))
419 (when (<= n 0)
420 (error "The (optional) argument of `org-bbdb-anniversaries-future' \
421 must be positive"))
422 (let (
423 ;; List of relevant dates.
424 (dates (org-bbdb-date-list date n))
425 ;; Function to annotate text of each element of l with the
426 ;; anniversary date d.
427 (annotate-descriptions
428 (lambda (d l)
429 (mapcar (lambda (x)
430 ;; The assumption here is that x is a bbdb link
431 ;; of the form [[bbdb:name][description]].
432 ;; This function rather arbitrarily modifies
433 ;; the description by adding the date to it in
434 ;; a fixed format.
435 (string-match "]]" x)
436 (replace-match (format " -- %d-%02d-%02d\\&"
437 (nth 2 d)
438 (nth 0 d)
439 (nth 1 d))
440 nil nil x))
441 l))))
442 ;; Map a function that generates anniversaries for each date
443 ;; over the dates and nconc the results into a single list. When
444 ;; it is no longer necessary to support older versions of Emacs,
445 ;; this can be done with a cl-mapcan; for now, we use the (apply
446 ;; #'nconc ...) method for compatibility.
447 (apply #'nconc
448 (mapcar
449 (lambda (d)
450 (let ((date d))
451 ;; Rebind 'date' so that org-bbdb-anniversaries will
452 ;; be fooled into giving us the list for the given
453 ;; date and then annotate the descriptions for that
454 ;; date.
455 (funcall annotate-descriptions d (org-bbdb-anniversaries))))
456 dates)))))
458 (defun org-bbdb-complete-link ()
459 "Read a bbdb link with name completion."
460 (require 'bbdb-com)
461 (let ((rec (bbdb-completing-read-record "Name: ")))
462 (concat "bbdb:"
463 (bbdb-record-name (if (listp rec)
464 (car rec)
465 rec)))))
467 (defun org-bbdb-anniv-export-ical ()
468 "Extract anniversaries from BBDB and convert them to icalendar format."
469 (require 'bbdb)
470 (require 'diary-lib)
471 (unless (hash-table-p org-bbdb-anniv-hash)
472 (setq org-bbdb-anniv-hash
473 (make-hash-table :test 'equal :size 366)))
474 (when (or org-bbdb-updated-p
475 (= 0 (hash-table-count org-bbdb-anniv-hash)))
476 (org-bbdb-make-anniv-hash))
477 (maphash 'org-bbdb-format-vevent org-bbdb-anniv-hash))
479 (defun org-bbdb-format-vevent (key recs)
480 (let (rec categ)
481 (while (setq rec (pop recs))
482 (setq categ (or (nth 2 rec) org-bbdb-default-anniversary-format))
483 (princ (format "BEGIN:VEVENT
484 UID: ANNIV-%4i%02i%02i-%s
485 DTSTART:%4i%02i%02i
486 SUMMARY:%s
487 DESCRIPTION:%s
488 CATEGORIES:%s
489 RRULE:FREQ=YEARLY
490 END:VEVENT\n"
491 (nth 0 rec) (nth 0 key) (nth 1 key)
492 (mapconcat 'identity
493 (org-split-string (nth 1 rec) "[^a-zA-Z0-90]+")
494 "-")
495 (nth 0 rec) (nth 0 key) (nth 1 key)
496 (nth 1 rec)
497 (concat (capitalize categ) " " (nth 1 rec))
498 categ)))))
500 (provide 'org-bbdb)
502 ;; Local variables:
503 ;; generated-autoload-file: "org-loaddefs.el"
504 ;; End:
506 ;;; org-bbdb.el ends here