Merge branch 'maint'
[org-mode.git] / contrib / lisp / org-contacts.el
blob88aef9d201361e97acefe25228c29983bdf29eff
1 ;;; org-contacts.el --- Contacts management
3 ;; Copyright (C) 2010-2014 Julien Danjou <julien@danjou.info>
5 ;; Author: Julien Danjou <julien@danjou.info>
6 ;; Keywords: outlines, hypermedia, calendar
7 ;;
8 ;; This file is NOT part of GNU Emacs.
9 ;;
10 ;; This program is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; This program 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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
24 ;;; Commentary:
26 ;; This file contains the code for managing your contacts into Org-mode.
28 ;; To enter new contacts, you can use `org-capture' and a minimal template just like
29 ;; this:
31 ;; ("c" "Contacts" entry (file "~/Org/contacts.org")
32 ;; "* %(org-contacts-template-name)
33 ;; :PROPERTIES:
34 ;; :EMAIL: %(org-contacts-template-email)
35 ;; :END:")))
37 ;; You can also use a complex template, for example:
39 ;; ("c" "Contacts" entry (file "~/Org/contacts.org")
40 ;; "* %(org-contacts-template-name)
41 ;; :PROPERTIES:
42 ;; :EMAIL: %(org-contacts-template-email)
43 ;; :PHONE:
44 ;; :ALIAS:
45 ;; :NICKNAME:
46 ;; :IGNORE:
47 ;; :ICON:
48 ;; :NOTE:
49 ;; :ADDRESS:
50 ;; :BIRTHDAY:
51 ;; :END:")))
53 ;;; Code:
55 (eval-when-compile
56 (require 'cl))
58 (require 'org)
59 (require 'gnus-util)
60 (require 'gnus-art)
61 (require 'mail-utils)
62 (require 'org-agenda)
63 (require 'org-capture)
65 (defgroup org-contacts nil
66 "Options about contacts management."
67 :group 'org)
69 (defcustom org-contacts-files nil
70 "List of Org files to use as contacts source.
71 When set to nil, all your Org files will be used."
72 :type '(repeat file)
73 :group 'org-contacts)
75 (defcustom org-contacts-email-property "EMAIL"
76 "Name of the property for contact email address."
77 :type 'string
78 :group 'org-contacts)
80 (defcustom org-contacts-tel-property "PHONE"
81 "Name of the property for contact phone number."
82 :type 'string
83 :group 'org-contacts)
85 (defcustom org-contacts-address-property "ADDRESS"
86 "Name of the property for contact address."
87 :type 'string
88 :group 'org-contacts)
90 (defcustom org-contacts-birthday-property "BIRTHDAY"
91 "Name of the property for contact birthday date."
92 :type 'string
93 :group 'org-contacts)
95 (defcustom org-contacts-note-property "NOTE"
96 "Name of the property for contact note."
97 :type 'string
98 :group 'org-contacts)
100 (defcustom org-contacts-alias-property "ALIAS"
101 "Name of the property for contact name alias."
102 :type 'string
103 :group 'org-contacts)
105 (defcustom org-contacts-ignore-property "IGNORE"
106 "Name of the property, which values will be ignored when
107 completing or exporting to vcard."
108 :type 'string
109 :group 'org-contacts)
112 (defcustom org-contacts-birthday-format "Birthday: %l (%Y)"
113 "Format of the anniversary agenda entry.
114 The following replacements are available:
116 %h - Heading name
117 %l - Link to the heading
118 %y - Number of year
119 %Y - Number of year (ordinal)"
120 :type 'string
121 :group 'org-contacts)
123 (defcustom org-contacts-last-read-mail-property "LAST_READ_MAIL"
124 "Name of the property for contact last read email link storage."
125 :type 'string
126 :group 'org-contacts)
128 (defcustom org-contacts-icon-property "ICON"
129 "Name of the property for contact icon."
130 :type 'string
131 :group 'org-contacts)
133 (defcustom org-contacts-nickname-property "NICKNAME"
134 "Name of the property for IRC nickname match."
135 :type 'string
136 :group 'org-contacts)
138 (defcustom org-contacts-icon-size 32
139 "Size of the contacts icons."
140 :type 'string
141 :group 'org-contacts)
143 (defcustom org-contacts-icon-use-gravatar (fboundp 'gravatar-retrieve)
144 "Whether use Gravatar to fetch contact icons."
145 :type 'boolean
146 :group 'org-contacts)
148 (defcustom org-contacts-completion-ignore-case t
149 "Ignore case when completing contacts."
150 :type 'boolean
151 :group 'org-contacts)
153 (defcustom org-contacts-group-prefix "+"
154 "Group prefix."
155 :type 'string
156 :group 'org-contacts)
158 (defcustom org-contacts-tags-props-prefix "#"
159 "Tags and properties prefix."
160 :type 'string
161 :group 'org-contacts)
163 (defcustom org-contacts-matcher
164 (mapconcat 'identity (list org-contacts-email-property
165 org-contacts-alias-property
166 org-contacts-tel-property
167 org-contacts-address-property
168 org-contacts-birthday-property)
169 "<>\"\"|")
170 "Matching rule for finding heading that are contacts.
171 This can be a tag name, or a property check."
172 :type 'string
173 :group 'org-contacts)
175 (defcustom org-contacts-email-link-description-format "%s (%d)"
176 "Format used to store links to email.
177 This overrides `org-email-link-description-format' if set."
178 :group 'org-contacts
179 :type 'string)
181 (defcustom org-contacts-vcard-file "contacts.vcf"
182 "Default file for vcard export."
183 :group 'org-contacts
184 :type 'file)
186 (defcustom org-contacts-enable-completion t
187 "Enable or not the completion in `message-mode' with `org-contacts'."
188 :group 'org-contacts
189 :type 'boolean)
191 (defcustom org-contacts-complete-functions
192 '(org-contacts-complete-group org-contacts-complete-tags-props org-contacts-complete-name)
193 "List of functions used to complete contacts in `message-mode'."
194 :group 'org-contacts
195 :type 'hook)
197 ;; Decalre external functions and variables
198 (declare-function org-reverse-string "org")
199 (declare-function diary-ordinal-suffix "ext:diary-lib")
200 (declare-function wl-summary-message-number "ext:wl-summary")
201 (declare-function wl-address-header-extract-address "ext:wl-address")
202 (declare-function wl-address-header-extract-realname "ext:wl-address")
203 (declare-function erc-buffer-list "ext:erc")
204 (declare-function erc-get-channel-user-list "ext:erc")
205 (declare-function google-maps-static-show "ext:google-maps-static")
206 (declare-function elmo-message-field "ext:elmo-pipe")
207 (declare-function std11-narrow-to-header "ext:std11")
208 (declare-function std11-fetch-field "ext:std11")
210 (defconst org-contacts-property-values-separators "[,; \f\t\n\r\v]+"
211 "The default value of separators for `org-contacts-split-property'.
213 A regexp matching strings of whitespace, `,' and `;'.")
215 (defvar org-contacts-keymap
216 (let ((map (make-sparse-keymap)))
217 (define-key map "M" 'org-contacts-view-send-email)
218 (define-key map "i" 'org-contacts-view-switch-to-irc-buffer)
219 map)
220 "The keymap used in `org-contacts' result list.")
222 (defvar org-contacts-db nil
223 "Org Contacts database.")
225 (defvar org-contacts-last-update nil
226 "Last time the Org Contacts database has been updated.")
228 (defun org-contacts-files ()
229 "Return list of Org files to use for contact management."
230 (or org-contacts-files (org-agenda-files t 'ifmode)))
232 (defun org-contacts-db-need-update-p ()
233 "Determine whether `org-contacts-db' needs to be refreshed."
234 (or (null org-contacts-last-update)
235 (org-find-if (lambda (file)
236 (or (time-less-p org-contacts-last-update
237 (elt (file-attributes file) 5))))
238 (org-contacts-files))
239 (org-contacts-db-has-dead-markers-p org-contacts-db)))
241 (defun org-contacts-db-has-dead-markers-p (org-contacts-db)
242 "Returns t if at least one dead marker is found in
243 ORG-CONTACTS-DB. A dead marker in this case is a marker pointing
244 to dead or no buffer."
245 ;; Scan contacts list looking for dead markers, and return t at first found.
246 (catch 'dead-marker-found
247 (while org-contacts-db
248 (unless (marker-buffer (nth 1 (car org-contacts-db)))
249 (throw 'dead-marker-found t))
250 (setq org-contacts-db (cdr org-contacts-db)))
251 nil))
253 (defun org-contacts-db ()
254 "Return the latest Org Contacts Database."
255 (let* (todo-only
256 (contacts-matcher
257 (cdr (org-make-tags-matcher org-contacts-matcher)))
258 result)
259 (when (org-contacts-db-need-update-p)
260 (let ((progress-reporter
261 (make-progress-reporter "Updating Org Contacts Database..." 0 (length org-contacts-files)))
262 (i 0))
263 (dolist (file (org-contacts-files))
264 (org-check-agenda-file file)
265 (with-current-buffer (org-get-agenda-file-buffer file)
266 (unless (eq major-mode 'org-mode)
267 (error "File %s is not in `org-mode'" file))
268 (setf result
269 (append result
270 (org-scan-tags
271 'org-contacts-at-point
272 contacts-matcher
273 todo-only))))
274 (progress-reporter-update progress-reporter (setq i (1+ i))))
275 (setf org-contacts-db result
276 org-contacts-last-update (current-time))
277 (progress-reporter-done progress-reporter)))
278 org-contacts-db))
280 (defun org-contacts-at-point (&optional pom)
281 "Return the contacts at point-or-marker POM or current position
282 if nil."
283 (setq pom (or pom (point)))
284 (org-with-point-at pom
285 (list (org-get-heading t) (set-marker (make-marker) pom) (org-entry-properties pom 'all))))
287 (defun org-contacts-filter (&optional name-match tags-match prop-match)
288 "Search for a contact matching any of NAME-MATCH, TAGS-MATCH, PROP-MATCH.
289 If all match values are nil, return all contacts.
291 The optional PROP-MATCH argument is a single (PROP . VALUE) cons
292 cell corresponding to the contact properties.
294 (if (and (null name-match)
295 (null prop-match)
296 (null tags-match))
297 (org-contacts-db)
298 (loop for contact in (org-contacts-db)
299 if (or
300 (and name-match
301 (org-string-match-p name-match
302 (first contact)))
303 (and prop-match
304 (org-find-if (lambda (prop)
305 (and (string= (car prop-match) (car prop))
306 (org-string-match-p (cdr prop-match) (cdr prop))))
307 (caddr contact)))
308 (and tags-match
309 (org-find-if (lambda (tag)
310 (org-string-match-p tags-match tag))
311 (org-split-string
312 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
313 collect contact)))
315 (when (not (fboundp 'completion-table-case-fold))
316 ;; That function is new in Emacs 24...
317 (defun completion-table-case-fold (table &optional dont-fold)
318 (lambda (string pred action)
319 (let ((completion-ignore-case (not dont-fold)))
320 (complete-with-action action table string pred)))))
322 (defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
323 "Custom implementation of `try-completion'.
324 This version works only with list and alist and it looks at all
325 prefixes rather than just the beginning of the string."
326 (loop with regexp = (concat "\\b" (regexp-quote to-match))
327 with ret = nil
328 with ret-start = nil
329 with ret-end = nil
331 for el in collection
332 for string = (if (listp el) (car el) el)
334 for start = (when (or (null predicate) (funcall predicate string))
335 (string-match regexp string))
337 if start
338 do (let ((end (match-end 0))
339 (len (length string)))
340 (if (= end len)
341 (return t)
342 (destructuring-bind (string start end)
343 (if (null ret)
344 (values string start end)
345 (org-contacts-common-substring
346 ret ret-start ret-end
347 string start end))
348 (setf ret string
349 ret-start start
350 ret-end end))))
352 finally (return
353 (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
355 (defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
356 "Compare the contents of two strings, using `compare-strings'.
358 This function works like `compare-strings' excepted that it
359 returns a cons.
360 - The CAR is the number of characters that match at the beginning.
361 - The CDR is T is the two strings are the same and NIL otherwise."
362 (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
363 (if (eq ret t)
364 (cons (or end1 (length s1)) t)
365 (cons (1- (abs ret)) nil))))
367 (defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
368 "Extract the common substring between S1 and S2.
370 This function extracts the common substring between S1 and S2 and
371 adjust the part that remains common.
373 START1 and END1 delimit the part in S1 that we know is common
374 between the two strings. This applies to START2 and END2 for S2.
376 This function returns a list whose contains:
377 - The common substring found.
378 - The new value of the start of the known inner substring.
379 - The new value of the end of the known inner substring."
380 ;; Given two strings:
381 ;; s1: "foo bar baz"
382 ;; s2: "fooo bar baz"
383 ;; and the inner substring is "bar"
384 ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
386 ;; To find the common substring we will compare two substrings:
387 ;; " oof" and " ooof" to find the beginning of the common substring.
388 ;; " baz" and " baz" to find the end of the common substring.
389 (let* ((len1 (length s1))
390 (start1 (or start1 0))
391 (end1 (or end1 len1))
393 (len2 (length s2))
394 (start2 (or start2 0))
395 (end2 (or end2 len2))
397 (new-start (car (org-contacts-compare-strings
398 (substring (org-reverse-string s1) (- len1 start1)) nil nil
399 (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
401 (new-end (+ end1 (car (org-contacts-compare-strings
402 (substring s1 end1) nil nil
403 (substring s2 end2) nil nil)))))
404 (list (substring s1 (- start1 new-start) new-end)
405 new-start
406 (+ new-start (- end1 start1)))))
408 (defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
409 "Custom version of `all-completions'.
410 This version works only with list and alist and it looks at all
411 prefixes rather than just the beginning of the string."
412 (loop with regexp = (concat "\\b" (regexp-quote to-match))
413 for el in collection
414 for string = (if (listp el) (car el) el)
415 for match? = (when (and (or (null predicate) (funcall predicate string)))
416 (string-match regexp string))
417 if match?
418 collect (progn
419 (let ((end (match-end 0)))
420 (org-no-properties string)
421 (when (< end (length string))
422 ;; Here we add a text property that will be used
423 ;; later to highlight the character right after
424 ;; the common part between each addresses.
425 ;; See `org-contacts-display-sort-function'.
426 (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
427 string)))
429 (defun org-contacts-make-collection-prefix (collection)
430 "Make a collection function from COLLECTION which will match on prefixes."
431 (lexical-let ((collection collection))
432 (lambda (string predicate flag)
433 (cond ((eq flag nil)
434 (org-contacts-try-completion-prefix string collection predicate))
435 ((eq flag t)
436 ;; `org-contacts-all-completions-prefix' has already been
437 ;; used to compute `all-completions'.
438 collection)
439 ((eq flag 'lambda)
440 (org-contacts-test-completion-prefix string collection predicate))
441 ((and (listp flag) (eq (car flag) 'boundaries))
442 (destructuring-bind (to-ignore &rest suffix)
443 flag
444 (org-contacts-boundaries-prefix string collection predicate suffix)))
445 ((eq flag 'metadata)
446 (org-contacts-metadata-prefix string collection predicate))
447 (t nil ; operation unsupported
448 )))))
450 (defun org-contacts-display-sort-function (completions)
451 "Sort function for contacts display."
452 (mapcar (lambda (string)
453 (loop with len = (1- (length string))
454 for i upfrom 0 to len
455 if (memq 'org-contacts-prefix
456 (text-properties-at i string))
457 do (set-text-properties
458 i (1+ i)
459 (list 'font-lock-face
460 (if (char-equal (aref string i)
461 (string-to-char " "))
462 ;; Spaces can't be bold.
463 'underline
464 'bold)) string)
465 else
466 do (set-text-properties i (1+ i) nil string)
467 finally (return string)))
468 completions))
470 (defun org-contacts-test-completion-prefix (string collection predicate)
471 ;; Prevents `org-find-if' from redefining `predicate' and going into
472 ;; an infinite loop.
473 (lexical-let ((predicate predicate))
474 (org-find-if (lambda (el)
475 (and (or (null predicate) (funcall predicate el))
476 (string= string el)))
477 collection)))
479 (defun org-contacts-boundaries-prefix (string collection predicate suffix)
480 (list* 'boundaries (completion-boundaries string collection predicate suffix)))
482 (defun org-contacts-metadata-prefix (string collection predicate)
483 '(metadata .
484 ((cycle-sort-function . org-contacts-display-sort-function)
485 (display-sort-function . org-contacts-display-sort-function))))
487 (defun org-contacts-complete-group (start end string)
488 "Complete text at START from a group.
490 A group FOO is composed of contacts with the tag FOO."
491 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
492 (group-completion-p (org-string-match-p
493 (concat "^" org-contacts-group-prefix) string)))
494 (when group-completion-p
495 (let ((completion-list
496 (all-completions
497 string
498 (mapcar (lambda (group)
499 (propertize (concat org-contacts-group-prefix group)
500 'org-contacts-group group))
501 (org-uniquify
502 (loop for contact in (org-contacts-filter)
503 nconc (org-split-string
504 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
505 (list start end
506 (if (= (length completion-list) 1)
507 ;; We've found the correct group, returns the address
508 (lexical-let ((tag (get-text-property 0 'org-contacts-group
509 (car completion-list))))
510 (lambda (string pred &optional to-ignore)
511 (mapconcat 'identity
512 (loop for contact in (org-contacts-filter
514 tag)
515 ;; The contact name is always the car of the assoc-list
516 ;; returned by `org-contacts-filter'.
517 for contact-name = (car contact)
518 ;; Grab the first email of the contact
519 for email = (org-contacts-strip-link
520 (or (car (org-contacts-split-property
522 (cdr (assoc-string org-contacts-email-property
523 (caddr contact)))
524 ""))) ""))
525 ;; If the user has an email address, append USER <EMAIL>.
526 if email collect (org-contacts-format-email contact-name email))
527 ", ")))
528 ;; We haven't found the correct group
529 (completion-table-case-fold completion-list
530 (not org-contacts-completion-ignore-case))))))))
532 (defun org-contacts-complete-tags-props (start end string)
533 "Insert emails that match the tags expression.
535 For example: FOO-BAR will match entries tagged with FOO but not
536 with BAR.
538 See (org) Matching tags and properties for a complete
539 description."
540 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
541 (completion-p (org-string-match-p
542 (concat "^" org-contacts-tags-props-prefix) string)))
543 (when completion-p
544 (let ((result
545 (mapconcat
546 'identity
547 (loop for contact in (org-contacts-db)
548 for contact-name = (car contact)
549 for email = (org-contacts-strip-link (or (car (org-contacts-split-property
551 (cdr (assoc-string org-contacts-email-property
552 (caddr contact)))
553 ""))) ""))
554 for tags = (cdr (assoc "TAGS" (nth 2 contact)))
555 for tags-list = (if tags
556 (split-string (substring (cdr (assoc "TAGS" (nth 2 contact))) 1 -1) ":")
557 '())
558 for marker = (second contact)
559 if (with-current-buffer (marker-buffer marker)
560 (save-excursion
561 (goto-char marker)
562 (let (todo-only)
563 (eval (cdr (org-make-tags-matcher (subseq string 1)))))))
564 collect (org-contacts-format-email contact-name email))
565 ",")))
566 (when (not (string= "" result))
567 ;; return (start end function)
568 (lexical-let* ((to-return result))
569 (list start end
570 (lambda (string pred &optional to-ignore) to-return))))))))
572 (defun org-contacts-remove-ignored-property-values (ignore-list list)
573 "Remove all ignore-list's elements from list and you can use
574 regular expressions in the ignore list."
575 (org-remove-if (lambda (el)
576 (org-find-if (lambda (x)
577 (string-match-p x el))
578 ignore-list))
579 list))
581 (defun org-contacts-complete-name (start end string)
582 "Complete text at START with a user name and email."
583 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
584 (completion-list
585 (loop for contact in (org-contacts-filter)
586 ;; The contact name is always the car of the assoc-list
587 ;; returned by `org-contacts-filter'.
588 for contact-name = (car contact)
590 ;; Build the list of the email addresses which has
591 ;; been expired
592 for ignore-list = (org-contacts-split-property
593 (or (cdr (assoc-string org-contacts-ignore-property
594 (caddr contact))) ""))
595 ;; Build the list of the user email addresses.
596 for email-list = (org-contacts-remove-ignored-property-values
597 ignore-list
598 (org-contacts-split-property
599 (or (cdr (assoc-string org-contacts-email-property
600 (caddr contact))) "")))
601 ;; If the user has email addresses…
602 if email-list
603 ;; … append a list of USER <EMAIL>.
604 nconc (loop for email in email-list
605 collect (org-contacts-format-email contact-name (org-contacts-strip-link email)))))
606 (completion-list (org-contacts-all-completions-prefix
607 string
608 (org-uniquify completion-list))))
609 (when completion-list
610 (list start end
611 (org-contacts-make-collection-prefix completion-list)))))
613 (defun org-contacts-message-complete-function (&optional start)
614 "Function used in `completion-at-point-functions' in `message-mode'."
615 ;; Avoid to complete in `post-command-hook'.
616 (when completion-in-region-mode
617 (remove-hook 'post-command-hook #'completion-in-region--postch))
618 (let ((mail-abbrev-mode-regexp
619 "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
620 (when (mail-abbrev-in-expansion-header-p)
621 (lexical-let*
622 ((end (point))
623 (start (or start
624 (save-excursion
625 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
626 (goto-char (match-end 0))
627 (point))))
628 (string (buffer-substring start end)))
629 (run-hook-with-args-until-success
630 'org-contacts-complete-functions start end string)))))
632 (defun org-contacts-gnus-get-name-email ()
633 "Get name and email address from Gnus message."
634 (if (gnus-alive-p)
635 (gnus-with-article-headers
636 (mail-extract-address-components
637 (or (mail-fetch-field "From") "")))))
639 (defun org-contacts-gnus-article-from-get-marker ()
640 "Return a marker for a contact based on From."
641 (let* ((address (org-contacts-gnus-get-name-email))
642 (name (car address))
643 (email (cadr address)))
644 (cadar (or (org-contacts-filter
647 (cons org-contacts-email-property (concat "\\b" (regexp-quote email) "\\b")))
648 (when name
649 (org-contacts-filter
650 (concat "^" name "$")))))))
652 (defun org-contacts-gnus-article-from-goto ()
653 "Go to contact in the From address of current Gnus message."
654 (interactive)
655 (let ((marker (org-contacts-gnus-article-from-get-marker)))
656 (when marker
657 (switch-to-buffer-other-window (marker-buffer marker))
658 (goto-char marker)
659 (when (eq major-mode 'org-mode)
660 (org-show-context 'agenda)
661 (save-excursion
662 (and (outline-next-heading)
663 ;; show the next heading
664 (org-flag-heading nil)))))))
666 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
667 (defun org-contacts-anniversaries (&optional field format)
668 "Compute FIELD anniversary for each contact, returning FORMAT.
669 Default FIELD value is \"BIRTHDAY\".
671 Format is a string matching the following format specification:
673 %h - Heading name
674 %l - Link to the heading
675 %y - Number of year
676 %Y - Number of year (ordinal)"
677 (let ((calendar-date-style 'american)
678 (entry ""))
679 (unless format (setq format org-contacts-birthday-format))
680 (loop for contact in (org-contacts-filter)
681 for anniv = (let ((anniv (cdr (assoc-string
682 (or field org-contacts-birthday-property)
683 (caddr contact)))))
684 (when anniv
685 (calendar-gregorian-from-absolute
686 (org-time-string-to-absolute anniv))))
687 ;; Use `diary-anniversary' to compute anniversary.
688 if (and anniv (apply 'diary-anniversary anniv))
689 collect (format-spec format
690 `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
691 (?h . ,(car contact))
692 (?y . ,(- (calendar-extract-year date)
693 (calendar-extract-year anniv)))
694 (?Y . ,(let ((years (- (calendar-extract-year date)
695 (calendar-extract-year anniv))))
696 (format "%d%s" years (diary-ordinal-suffix years)))))))))
698 (defun org-completing-read-date (prompt collection
699 &optional predicate require-match initial-input
700 hist def inherit-input-method)
701 "Like `completing-read' but reads a date.
702 Only PROMPT and DEF are really used."
703 (org-read-date nil nil nil prompt nil def))
705 (add-to-list 'org-property-set-functions-alist
706 `(,org-contacts-birthday-property . org-completing-read-date))
708 (defun org-contacts-template-name (&optional return-value)
709 "Try to return the contact name for a template.
710 If not found return RETURN-VALUE or something that would ask the user."
711 (or (car (org-contacts-gnus-get-name-email))
712 return-value
713 "%^{Name}"))
715 (defun org-contacts-template-email (&optional return-value)
716 "Try to return the contact email for a template.
717 If not found return RETURN-VALUE or something that would ask the user."
718 (or (cadr (org-contacts-gnus-get-name-email))
719 return-value
720 (concat "%^{" org-contacts-email-property "}p")))
722 (defun org-contacts-gnus-store-last-mail ()
723 "Store a link between mails and contacts.
725 This function should be called from `gnus-article-prepare-hook'."
726 (let ((marker (org-contacts-gnus-article-from-get-marker)))
727 (when marker
728 (with-current-buffer (marker-buffer marker)
729 (save-excursion
730 (goto-char marker)
731 (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
732 org-email-link-description-format))
733 (link (gnus-with-article-buffer (org-store-link nil))))
734 (org-set-property org-contacts-last-read-mail-property link)))))))
736 (defun org-contacts-icon-as-string ()
737 "Return the contact icon as a string."
738 (let ((image (org-contacts-get-icon)))
739 (concat
740 (propertize "-" 'display
741 (append
742 (if image
743 image
744 `'(space :width (,org-contacts-icon-size)))
745 '(:ascent center)))
746 " ")))
748 ;;;###autoload
749 (defun org-contacts (name)
750 "Create agenda view for contacts matching NAME."
751 (interactive (list (read-string "Name: ")))
752 (let ((org-agenda-files (org-contacts-files))
753 (org-agenda-skip-function
754 (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
755 (org-agenda-prefix-format (propertize
756 "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
757 'keymap org-contacts-keymap))
758 (org-agenda-overriding-header
759 (or org-agenda-overriding-header
760 (concat "List of contacts matching `" name "':"))))
761 (setq org-agenda-skip-regexp name)
762 (org-tags-view nil org-contacts-matcher)
763 (with-current-buffer org-agenda-buffer-name
764 (setq org-agenda-redo-command
765 (list 'org-contacts name)))))
767 (defun org-contacts-completing-read (prompt
768 &optional predicate
769 initial-input hist def inherit-input-method)
770 "Call `completing-read' with contacts name as collection."
771 (org-completing-read
772 prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
774 (defun org-contacts-format-name (name)
775 "Trim any local formatting to get a bare NAME."
776 ;; Remove radio targets characters
777 (replace-regexp-in-string org-radio-target-regexp "\\1" name))
779 (defun org-contacts-format-email (name email)
780 "Format an EMAIL address corresponding to NAME."
781 (unless email
782 (error "`email' cannot be nul"))
783 (if name
784 (concat (org-contacts-format-name name) " <" email ">")
785 email))
787 (defun org-contacts-check-mail-address (mail)
788 "Add MAIL address to contact at point if it does not have it."
789 (let ((mails (org-entry-get (point) org-contacts-email-property)))
790 (unless (member mail (split-string mails))
791 (when (yes-or-no-p
792 (format "Do you want to add this address to %s?" (org-get-heading t)))
793 (org-set-property org-contacts-email-property (concat mails " " mail))))))
795 (defun org-contacts-gnus-check-mail-address ()
796 "Check that contact has the current address recorded.
797 This function should be called from `gnus-article-prepare-hook'."
798 (let ((marker (org-contacts-gnus-article-from-get-marker)))
799 (when marker
800 (org-with-point-at marker
801 (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
803 (defun org-contacts-gnus-insinuate ()
804 "Add some hooks for Gnus user.
805 This adds `org-contacts-gnus-check-mail-address' and
806 `org-contacts-gnus-store-last-mail' to
807 `gnus-article-prepare-hook'. It also adds a binding on `;' in
808 `gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
809 (require 'gnus)
810 (require 'gnus-art)
811 (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
812 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
813 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
815 (defun org-contacts-setup-completion-at-point ()
816 "Add `org-contacts-message-complete-function' as a new function
817 to complete the thing at point."
818 (add-to-list 'completion-at-point-functions
819 'org-contacts-message-complete-function))
821 (defun org-contacts-unload-hook ()
822 (remove-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
824 (when (and org-contacts-enable-completion
825 (boundp 'completion-at-point-functions))
826 (add-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
828 (defun org-contacts-wl-get-from-header-content ()
829 "Retrieve the content of the `From' header of an email.
830 Works from wl-summary-mode and mime-view-mode - that is while viewing email.
831 Depends on Wanderlust been loaded."
832 (with-current-buffer (org-capture-get :original-buffer)
833 (cond
834 ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
835 wl-summary-buffer-elmo-folder)
836 (elmo-message-field
837 wl-summary-buffer-elmo-folder
838 (wl-summary-message-number)
839 'from)))
840 ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
841 (prog1
842 (std11-fetch-field "From")
843 (widen))))))
845 (defun org-contacts-wl-get-name-email ()
846 "Get name and email address from Wanderlust email.
847 See `org-contacts-wl-get-from-header-content' for limitations."
848 (let ((from (org-contacts-wl-get-from-header-content)))
849 (when from
850 (list (wl-address-header-extract-realname from)
851 (wl-address-header-extract-address from)))))
853 (defun org-contacts-template-wl-name (&optional return-value)
854 "Try to return the contact name for a template from wl.
855 If not found, return RETURN-VALUE or something that would ask the
856 user."
857 (or (car (org-contacts-wl-get-name-email))
858 return-value
859 "%^{Name}"))
861 (defun org-contacts-template-wl-email (&optional return-value)
862 "Try to return the contact email for a template from Wanderlust.
863 If not found return RETURN-VALUE or something that would ask the user."
864 (or (cadr (org-contacts-wl-get-name-email))
865 return-value
866 (concat "%^{" org-contacts-email-property "}p")))
868 (defun org-contacts-view-send-email (&optional ask)
869 "Send email to the contact at point.
870 If ASK is set, ask for the email address even if there's only one
871 address."
872 (interactive "P")
873 (let ((marker (org-get-at-bol 'org-hd-marker)))
874 (org-with-point-at marker
875 (let ((emails (org-entry-get (point) org-contacts-email-property)))
876 (if emails
877 (let ((email-list (org-contacts-split-property emails)))
878 (if (and (= (length email-list) 1) (not ask))
879 (compose-mail (org-contacts-format-email
880 (org-get-heading t) emails))
881 (let ((email (completing-read "Send mail to which address: " email-list)))
882 (setq email (org-contacts-strip-link email))
883 (org-contacts-check-mail-address email)
884 (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
885 (error (format "This contact has no mail address set (no %s property)."
886 org-contacts-email-property)))))))
888 (defun org-contacts-get-icon (&optional pom)
889 "Get icon for contact at POM."
890 (setq pom (or pom (point)))
891 (catch 'icon
892 ;; Use `org-contacts-icon-property'
893 (let ((image-data (org-entry-get pom org-contacts-icon-property)))
894 (when image-data
895 (throw 'icon
896 (if (fboundp 'gnus-rescale-image)
897 (gnus-rescale-image (create-image image-data)
898 (cons org-contacts-icon-size org-contacts-icon-size))
899 (create-image image-data)))))
900 ;; Next, try Gravatar
901 (when org-contacts-icon-use-gravatar
902 (let* ((gravatar-size org-contacts-icon-size)
903 (email-list (org-entry-get pom org-contacts-email-property))
904 (gravatar
905 (when email-list
906 (loop for email in (org-contacts-split-property email-list)
907 for gravatar = (gravatar-retrieve-synchronously (org-contacts-strip-link email))
908 if (and gravatar
909 (not (eq gravatar 'error)))
910 return gravatar))))
911 (when gravatar (throw 'icon gravatar))))))
913 (defun org-contacts-irc-buffer (&optional pom)
914 "Get the IRC buffer associated with the entry at POM."
915 (setq pom (or pom (point)))
916 (let ((nick (org-entry-get pom org-contacts-nickname-property)))
917 (when nick
918 (let ((buffer (get-buffer nick)))
919 (when buffer
920 (with-current-buffer buffer
921 (when (eq major-mode 'erc-mode)
922 buffer)))))))
924 (defun org-contacts-irc-number-of-unread-messages (&optional pom)
925 "Return the number of unread messages for contact at POM."
926 (when (boundp 'erc-modified-channels-alist)
927 (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
928 (if number
929 (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
930 (make-string 21 ? )))))
932 (defun org-contacts-view-switch-to-irc-buffer ()
933 "Switch to the IRC buffer of the current contact if it has one."
934 (interactive)
935 (let ((marker (org-get-at-bol 'org-hd-marker)))
936 (org-with-point-at marker
937 (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
939 (defun org-contacts-completing-read-nickname (prompt collection
940 &optional predicate require-match initial-input
941 hist def inherit-input-method)
942 "Like `completing-read' but reads a nickname."
943 (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
944 initial-input hist def inherit-input-method))
946 (defun erc-nicknames-list ()
947 "Return all nicknames of all ERC buffers."
948 (loop for buffer in (erc-buffer-list)
949 nconc (with-current-buffer buffer
950 (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
951 collect (elt user-entry 1)))))
953 (add-to-list 'org-property-set-functions-alist
954 `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
956 (defun org-contacts-vcard-escape (str)
957 "Escape ; , and \n in STR for the VCard format."
958 ;; Thanks to this library for the regexp:
959 ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
960 (when str
961 (replace-regexp-in-string
962 "\n" "\\\\n"
963 (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
965 (defun org-contacts-vcard-encode-name (name)
966 "Try to encode NAME as VCard's N property.
967 The N property expects
969 FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
971 Org-contacts does not specify how to encode the name. So we try
972 to do our best."
973 (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
975 (defun org-contacts-vcard-format (contact)
976 "Formats CONTACT in VCard 3.0 format."
977 (let* ((properties (caddr contact))
978 (name (org-contacts-vcard-escape (car contact)))
979 (n (org-contacts-vcard-encode-name name))
980 (email (cdr (assoc-string org-contacts-email-property properties)))
981 (tel (cdr (assoc-string org-contacts-tel-property properties)))
982 (ignore-list (cdr (assoc-string org-contacts-ignore-property properties)))
983 (ignore-list (when ignore-list
984 (org-contacts-split-property ignore-list)))
985 (note (cdr (assoc-string org-contacts-note-property properties)))
986 (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
987 (addr (cdr (assoc-string org-contacts-address-property properties)))
988 (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
989 (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name))
990 emails-list result phones-list)
991 (concat head
992 (when email (progn
993 (setq emails-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property email)))
994 (setq result "")
995 (while emails-list
996 (setq result (concat result "EMAIL:" (org-contacts-strip-link (car emails-list)) "\n"))
997 (setq emails-list (cdr emails-list)))
998 result))
999 (when addr
1000 (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
1001 (when tel (progn
1002 (setq phones-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property tel)))
1003 (setq result "")
1004 (while phones-list
1005 (setq result (concat result "TEL:" (org-link-unescape (org-contacts-strip-link (car phones-list))) "\n"))
1006 (setq phones-list (cdr phones-list)))
1007 result))
1008 (when bday
1009 (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
1010 (format "BDAY:%04d-%02d-%02d\n"
1011 (calendar-extract-year cal-bday)
1012 (calendar-extract-month cal-bday)
1013 (calendar-extract-day cal-bday))))
1014 (when nick (format "NICKNAME:%s\n" nick))
1015 (when note (format "NOTE:%s\n" note))
1016 "END:VCARD\n\n")))
1018 (defun org-contacts-export-as-vcard (&optional name file to-buffer)
1019 "Export org contacts to V-Card 3.0.
1021 By default, all contacts are exported to `org-contacts-vcard-file'.
1023 When NAME is \\[universal-argument], prompts for a contact name.
1025 When NAME is \\[universal-argument] \\[universal-argument],
1026 prompts for a contact name and a file name where to export.
1028 When NAME is \\[universal-argument] \\[universal-argument]
1029 \\[universal-argument], prompts for a contact name and a buffer where to export.
1031 If the function is not called interactively, all parameters are
1032 passed to `org-contacts-export-as-vcard-internal'."
1033 (interactive "P")
1034 (when (called-interactively-p 'any)
1035 (cl-psetf name
1036 (when name
1037 (read-string "Contact name: "
1038 (first (org-contacts-at-point))))
1039 file
1040 (when (equal name '(16))
1041 (read-file-name "File: " nil org-contacts-vcard-file))
1042 to-buffer
1043 (when (equal name '(64))
1044 (read-buffer "Buffer: "))))
1045 (org-contacts-export-as-vcard-internal name file to-buffer))
1047 (defun org-contacts-export-as-vcard-internal (&optional name file to-buffer)
1048 "Export all contacts matching NAME as VCard 3.0.
1049 If TO-BUFFER is nil, the content is written to FILE or
1050 `org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
1051 is created and the VCard is written into that buffer."
1052 (let* ((filename (or file org-contacts-vcard-file))
1053 (buffer (if to-buffer
1054 (get-buffer-create to-buffer)
1055 (find-file-noselect filename))))
1056 (message "Exporting...")
1057 (set-buffer buffer)
1058 (let ((inhibit-read-only t)) (erase-buffer))
1059 (fundamental-mode)
1060 (when (fboundp 'set-buffer-file-coding-system)
1061 (set-buffer-file-coding-system coding-system-for-write))
1062 (loop for contact in (org-contacts-filter name)
1063 do (insert (org-contacts-vcard-format contact)))
1064 (if to-buffer
1065 (current-buffer)
1066 (progn (save-buffer) (kill-buffer)))))
1068 (defun org-contacts-show-map (&optional name)
1069 "Show contacts on a map.
1070 Requires google-maps-el."
1071 (interactive)
1072 (unless (fboundp 'google-maps-static-show)
1073 (error "`org-contacts-show-map' requires `google-maps-el'"))
1074 (google-maps-static-show
1075 :markers
1076 (loop
1077 for contact in (org-contacts-filter name)
1078 for addr = (cdr (assoc-string org-contacts-address-property (caddr contact)))
1079 if addr
1080 collect (cons (list addr) (list :label (string-to-char (car contact)))))))
1082 (defun org-contacts-strip-link (link)
1083 "Remove brackets, description, link type and colon from an org
1084 link string and return the pure link target."
1085 (let (startpos colonpos endpos)
1086 (setq startpos (string-match (regexp-opt '("[[tel:" "[[mailto:")) link))
1087 (if startpos
1088 (progn
1089 (setq colonpos (string-match ":" link))
1090 (setq endpos (string-match "\\]" link))
1091 (if endpos (substring link (1+ colonpos) endpos) link))
1092 (progn
1093 (setq startpos (string-match "mailto:" link))
1094 (setq colonpos (string-match ":" link))
1095 (if startpos (substring link (1+ colonpos)) link)))))
1097 (defun org-contacts-split-property (string &optional separators omit-nulls)
1098 "Custom version of `split-string'.
1099 Split a property STRING into sub-strings bounded by matches
1100 for SEPARATORS but keep Org links intact.
1102 The beginning and end of STRING, and each match for SEPARATORS, are
1103 splitting points. The substrings matching SEPARATORS are removed, and
1104 the substrings between the splitting points are collected as a list,
1105 which is returned.
1107 If SEPARATORS is non-nil, it should be a regular expression
1108 matching text which separates, but is not part of, the
1109 substrings. If nil it defaults to `org-contacts-property-values-separators',
1110 normally \"[,; \f\t\n\r\v]+\", and OMIT-NULLS is forced to t.
1112 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
1113 that for the default value of SEPARATORS leading and trailing whitespace
1114 are effectively trimmed). If nil, all zero-length substrings are retained."
1115 (let* ((omit-nulls (if separators omit-nulls t))
1116 (rexp (or separators org-contacts-property-values-separators))
1117 (inputlist (split-string string rexp omit-nulls))
1118 (linkstring "")
1119 (bufferstring "")
1120 (proplist (list "")))
1121 (while inputlist
1122 (setq bufferstring (pop inputlist))
1123 (if (string-match "\\[\\[" bufferstring)
1124 (progn
1125 (setq linkstring (concat bufferstring " "))
1126 (while (not (string-match "\\]\\]" bufferstring))
1127 (setq bufferstring (pop inputlist))
1128 (setq linkstring (concat linkstring bufferstring " ")))
1129 (setq proplist (cons (org-trim linkstring) proplist)))
1130 (setq proplist (cons bufferstring proplist))))
1131 (cdr (reverse proplist))))
1133 (provide 'org-contacts)
1135 ;;; org-contacts.el ends here