Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-bbdb.el
blob1a82ea847c2cd58178089b06397b0b3fb36f9ab1
1 ;;; org-bbdb.el --- Support for links to BBDB entries -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2016 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-mode.
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-mode 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 (org-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)
198 ;; Install the link type
199 (org-add-link-type "bbdb" 'org-bbdb-open 'org-bbdb-export)
200 (add-hook 'org-store-link-functions 'org-bbdb-store-link)
202 ;; Implementation
203 (defun org-bbdb-store-link ()
204 "Store a link to a BBDB database entry."
205 (when (eq major-mode 'bbdb-mode)
206 ;; This is BBDB, we make this link!
207 (let* ((rec (bbdb-current-record))
208 (name (bbdb-record-name rec))
209 (company (if (fboundp 'bbdb-record-getprop)
210 (bbdb-record-getprop rec 'company)
211 (car (bbdb-record-field rec 'organization))))
212 (link (concat "bbdb:" name)))
213 (org-store-link-props :type "bbdb" :name name :company company
214 :link link :description name)
215 link)))
217 (defun org-bbdb-export (path desc format)
218 "Create the export version of a BBDB link specified by PATH or DESC.
219 If exporting to either HTML or LaTeX FORMAT the link will be
220 italicized, in all other cases it is left unchanged."
221 (when (string= desc (format "bbdb:%s" path))
222 (setq desc path))
223 (cond
224 ((eq format 'html) (format "<i>%s</i>" desc))
225 ((eq format 'latex) (format "\\textit{%s}" desc))
226 ((eq format 'odt)
227 (format "<text:span text:style-name=\"Emphasis\">%s</text:span>" desc))
228 (t desc)))
230 (defun org-bbdb-open (name)
231 "Follow a BBDB link to NAME."
232 (require 'bbdb-com)
233 (let ((inhibit-redisplay (not debug-on-error)))
234 (if (fboundp 'bbdb-name)
235 (org-bbdb-open-old name)
236 (org-bbdb-open-new name))))
238 (defun org-bbdb-open-old (name)
239 (catch 'exit
240 ;; Exact match on name
241 (bbdb-name (concat "\\`" name "\\'") nil)
242 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
243 ;; Exact match on name
244 (bbdb-company (concat "\\`" name "\\'") nil)
245 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
246 ;; Partial match on name
247 (bbdb-name name nil)
248 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
249 ;; Partial match on company
250 (bbdb-company name nil)
251 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
252 ;; General match including network address and notes
253 (bbdb name nil)
254 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
255 (delete-window (get-buffer-window "*BBDB*"))
256 (error "No matching BBDB record"))))
258 (defun org-bbdb-open-new (name)
259 (catch 'exit
260 ;; Exact match on name
261 (bbdb-search-name (concat "\\`" name "\\'") nil)
262 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
263 ;; Exact match on name
264 (bbdb-search-organization (concat "\\`" name "\\'") nil)
265 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
266 ;; Partial match on name
267 (bbdb-search-name name nil)
268 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
269 ;; Partial match on company
270 (bbdb-search-organization name nil)
271 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
272 ;; General match including network address and notes
273 (bbdb name nil)
274 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
275 (delete-window (get-buffer-window "*BBDB*"))
276 (error "No matching BBDB record"))))
278 (defun org-bbdb-anniv-extract-date (time-str)
279 "Convert YYYY-MM-DD to (month date year).
280 Argument TIME-STR is the value retrieved from BBDB. If YYYY- is omitted
281 it will be considered unknown."
282 (multiple-value-bind (a b c) (values-list (org-split-string time-str "-"))
283 (if (eq c nil)
284 (list (string-to-number a)
285 (string-to-number b)
286 nil)
287 (list (string-to-number b)
288 (string-to-number c)
289 (string-to-number a)))))
291 (defun org-bbdb-anniv-split (str)
292 "Split multiple entries in the BBDB anniversary field.
293 Argument STR is the anniversary field in BBDB."
294 (let ((pos (string-match "[ \t]" str)))
295 (if pos (list (substring str 0 pos)
296 (bbdb-string-trim (substring str pos)))
297 (list str nil))))
299 (defvar org-bbdb-anniv-hash nil
300 "A hash holding anniversaries extracted from BBDB.
301 The hash table is created on first use.")
303 (defvar org-bbdb-updated-p t
304 "This is non-nil if BBDB has been updated since we last built the hash.")
306 (defun org-bbdb-make-anniv-hash ()
307 "Create a hash with anniversaries extracted from BBDB, for fast access.
308 The anniversaries are assumed to be stored `org-bbdb-anniversary-field'."
309 (let ((old-bbdb (fboundp 'bbdb-record-getprop))
310 (record-func (if (fboundp 'bbdb-record-xfield)
311 'bbdb-record-xfield
312 'bbdb-record-note))
313 split tmp annivs)
314 (clrhash org-bbdb-anniv-hash)
315 (dolist (rec (bbdb-records))
316 (when (setq annivs (if old-bbdb
317 (bbdb-record-getprop
318 rec org-bbdb-anniversary-field)
319 (funcall record-func
320 rec org-bbdb-anniversary-field)))
321 (setq annivs (if old-bbdb
322 (bbdb-split annivs "\n")
323 ;; parameter order is reversed in new bbdb
324 (bbdb-split "\n" annivs)))
325 (while annivs
326 (setq split (org-bbdb-anniv-split (pop annivs)))
327 (multiple-value-bind (m d y)
328 (values-list (funcall org-bbdb-extract-date-fun (car split)))
329 (setq tmp (gethash (list m d) org-bbdb-anniv-hash))
330 (puthash (list m d) (cons (list y
331 (bbdb-record-name rec)
332 (cadr split))
333 tmp)
334 org-bbdb-anniv-hash))))))
335 (setq org-bbdb-updated-p nil))
337 (defun org-bbdb-updated (_rec)
338 "Record the fact that BBDB has been updated.
339 This is used by Org to re-create the anniversary hash table."
340 (setq org-bbdb-updated-p t))
342 (add-hook 'bbdb-after-change-hook 'org-bbdb-updated)
344 ;;;###autoload
345 (defun org-bbdb-anniversaries ()
346 "Extract anniversaries from BBDB for display in the agenda."
347 (require 'bbdb)
348 (require 'diary-lib)
349 (unless (hash-table-p org-bbdb-anniv-hash)
350 (setq org-bbdb-anniv-hash
351 (make-hash-table :test 'equal :size 366)))
353 (when (or org-bbdb-updated-p
354 (= 0 (hash-table-count org-bbdb-anniv-hash)))
355 (org-bbdb-make-anniv-hash))
357 (let* ((m (car date)) ; month
358 (d (nth 1 date)) ; day
359 (y (nth 2 date)) ; year
360 (annivs (gethash (list m d) org-bbdb-anniv-hash))
361 (text ())
362 rec recs)
364 ;; we don't want to miss people born on Feb. 29th
365 (when (and (= m 3) (= d 1)
366 (not (null (gethash (list 2 29) org-bbdb-anniv-hash)))
367 (not (calendar-leap-year-p y)))
368 (setq recs (gethash (list 2 29) org-bbdb-anniv-hash))
369 (while (setq rec (pop recs))
370 (push rec annivs)))
372 (when annivs
373 (while (setq rec (pop annivs))
374 (when rec
375 (let* ((class (or (nth 2 rec)
376 org-bbdb-default-anniversary-format))
377 (form (or (cdr (assoc-string
378 class org-bbdb-anniversary-format-alist t))
379 class)) ; (as format string)
380 (name (nth 1 rec))
381 (years (if (eq (car rec) nil)
382 "unknown"
383 (- y (car rec))))
384 (suffix (if (eq (car rec) nil)
386 (diary-ordinal-suffix years)))
387 (tmp (cond
388 ((functionp form)
389 (funcall form name years suffix))
390 ((listp form) (eval form))
391 (t (format form name years suffix)))))
392 (org-add-props tmp nil 'org-bbdb-name name)
393 (if text
394 (setq text (append text (list tmp)))
395 (setq text (list tmp)))))
397 text))
399 ;;; Return list of anniversaries for today and the next n-1 (default: n=7) days.
400 ;;; This is meant to be used in an org file instead of org-bbdb-anniversaries:
402 ;;; %%(org-bbdb-anniversaries-future)
404 ;;; or
406 ;;; %%(org-bbdb-anniversaries-future 3)
408 ;;; to override the 7-day default.
410 (defun org-bbdb-date-list (d n)
411 "Return a list of dates in (m d y) format from the given date D to n-1 days hence."
412 (let ((abs (calendar-absolute-from-gregorian d)))
413 (mapcar (lambda (i) (calendar-gregorian-from-absolute (+ abs i)))
414 (number-sequence 0 (1- n)))))
416 ;;;###autoload
417 (defun org-bbdb-anniversaries-future (&optional n)
418 "Return list of anniversaries for today and the next n-1 days (default n=7)."
419 (let ((n (or n 7)))
420 (when (<= n 0)
421 (error "The (optional) argument of `org-bbdb-anniversaries-future' 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 anniversary date d.
426 (annotate-descriptions
427 (lambda (d l)
428 (mapcar (lambda (x)
429 ;; The assumption here is that x is a bbdb link of the form
430 ;; [[bbdb:name][description]].
431 ;; This function rather arbitrarily modifies the description
432 ;; by adding the date to it in a fixed format.
433 (string-match "]]" x)
434 (replace-match (format " -- %d-%02d-%02d\\&" (third d) (first d) (second d))
435 nil nil x))
436 l))))
437 ;; Map a function that generates anniversaries for each date over the dates
438 ;; and nconc the results into a single list. When it is no longer necessary
439 ;; to support older versions of emacs, this can be done with a cl-mapcan;
440 ;; for now, we use the (apply #'nconc ...) method for compatibility.
441 (apply #'nconc
442 (mapcar
443 (lambda (d)
444 (let ((date d))
445 ;; Rebind 'date' so that org-bbdb-anniversaries will be
446 ;; fooled into giving us the list for the given date
447 ;; and then annotate the descriptions for that date.
448 (funcall annotate-descriptions d (org-bbdb-anniversaries))))
449 dates)))))
451 (defun org-bbdb-complete-link ()
452 "Read a bbdb link with name completion."
453 (require 'bbdb-com)
454 (let ((rec (bbdb-completing-read-record "Name: ")))
455 (concat "bbdb:"
456 (bbdb-record-name (if (listp rec)
457 (car rec)
458 rec)))))
460 (defun org-bbdb-anniv-export-ical ()
461 "Extract anniversaries from BBDB and convert them to icalendar format."
462 (require 'bbdb)
463 (require 'diary-lib)
464 (unless (hash-table-p org-bbdb-anniv-hash)
465 (setq org-bbdb-anniv-hash
466 (make-hash-table :test 'equal :size 366)))
467 (when (or org-bbdb-updated-p
468 (= 0 (hash-table-count org-bbdb-anniv-hash)))
469 (org-bbdb-make-anniv-hash))
470 (maphash 'org-bbdb-format-vevent org-bbdb-anniv-hash))
472 (defun org-bbdb-format-vevent (key recs)
473 (let (rec categ)
474 (while (setq rec (pop recs))
475 (setq categ (or (nth 2 rec) org-bbdb-default-anniversary-format))
476 (princ (format "BEGIN:VEVENT
477 UID: ANNIV-%4i%02i%02i-%s
478 DTSTART:%4i%02i%02i
479 SUMMARY:%s
480 DESCRIPTION:%s
481 CATEGORIES:%s
482 RRULE:FREQ=YEARLY
483 END:VEVENT\n"
484 (nth 0 rec) (nth 0 key) (nth 1 key)
485 (mapconcat 'identity
486 (org-split-string (nth 1 rec) "[^a-zA-Z0-90]+")
487 "-")
488 (nth 0 rec) (nth 0 key) (nth 1 key)
489 (nth 1 rec)
490 (concat (capitalize categ) " " (nth 1 rec))
491 categ)))))
493 (provide 'org-bbdb)
495 ;; Local variables:
496 ;; generated-autoload-file: "org-loaddefs.el"
497 ;; End:
499 ;;; org-bbdb.el ends here