contrib/lisp/org-contacts.el: Permit to unload properly `org-contacts'
[org-mode/org-tableheadings.git] / contrib / lisp / org-contacts.el
blobd81d43bc4b0785ba0fb3de1e87d1c1e1f2613eaa
1 ;;; org-contacts.el --- Contacts management
3 ;; Copyright (C) 2010-2013 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 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 ;;; Code:
39 (eval-when-compile
40 (require 'cl))
42 (require 'org)
43 (require 'gnus-util)
44 (require 'gnus-art)
45 (require 'mail-utils)
46 (require 'org-agenda)
47 (require 'org-capture)
49 (defgroup org-contacts nil
50 "Options about contacts management."
51 :group 'org)
53 (defcustom org-contacts-files nil
54 "List of Org files to use as contacts source.
55 When set to nil, all your Org files will be used."
56 :type '(repeat file)
57 :group 'org-contacts)
59 (defcustom org-contacts-email-property "EMAIL"
60 "Name of the property for contact email address."
61 :type 'string
62 :group 'org-contacts)
64 (defcustom org-contacts-tel-property "PHONE"
65 "Name of the property for contact phone number."
66 :type 'string
67 :group 'org-contacts)
69 (defcustom org-contacts-address-property "ADDRESS"
70 "Name of the property for contact address."
71 :type 'string
72 :group 'org-contacts)
74 (defcustom org-contacts-birthday-property "BIRTHDAY"
75 "Name of the property for contact birthday date."
76 :type 'string
77 :group 'org-contacts)
79 (defcustom org-contacts-note-property "NOTE"
80 "Name of the property for contact note."
81 :type 'string
82 :group 'org-contacts)
84 (defcustom org-contacts-alias-property "ALIAS"
85 "Name of the property for contact name alias."
86 :type 'string
87 :group 'org-contacts)
90 (defcustom org-contacts-birthday-format "Birthday: %l (%Y)"
91 "Format of the anniversary agenda entry.
92 The following replacements are available:
94 %h - Heading name
95 %l - Link to the heading
96 %y - Number of year
97 %Y - Number of year (ordinal)"
98 :type 'string
99 :group 'org-contacts)
101 (defcustom org-contacts-last-read-mail-property "LAST_READ_MAIL"
102 "Name of the property for contact last read email link storage."
103 :type 'string
104 :group 'org-contacts)
106 (defcustom org-contacts-icon-property "ICON"
107 "Name of the property for contact icon."
108 :type 'string
109 :group 'org-contacts)
111 (defcustom org-contacts-nickname-property "NICKNAME"
112 "Name of the property for IRC nickname match."
113 :type 'string
114 :group 'org-contacts)
116 (defcustom org-contacts-icon-size 32
117 "Size of the contacts icons."
118 :type 'string
119 :group 'org-contacts)
121 (defcustom org-contacts-icon-use-gravatar (fboundp 'gravatar-retrieve)
122 "Whether use Gravatar to fetch contact icons."
123 :type 'boolean
124 :group 'org-contacts)
126 (defcustom org-contacts-completion-ignore-case t
127 "Ignore case when completing contacts."
128 :type 'boolean
129 :group 'org-contacts)
131 (defcustom org-contacts-group-prefix "+"
132 "Group prefix."
133 :type 'string
134 :group 'org-contacts)
136 (defcustom org-contacts-matcher
137 (mapconcat 'identity (list org-contacts-email-property
138 org-contacts-alias-property
139 org-contacts-tel-property
140 org-contacts-address-property
141 org-contacts-birthday-property)
142 "<>\"\"|")
143 "Matching rule for finding heading that are contacts.
144 This can be a tag name, or a property check."
145 :type 'string
146 :group 'org-contacts)
148 (defcustom org-contacts-email-link-description-format "%s (%d)"
149 "Format used to store links to email.
150 This overrides `org-email-link-description-format' if set."
151 :group 'org-contacts
152 :type 'string)
154 (defcustom org-contacts-vcard-file "contacts.vcf"
155 "Default file for vcard export."
156 :group 'org-contacts
157 :type 'file)
159 (defcustom org-contacts-enable-completion t
160 "Enable or not the completion in `message-mode' with `org-contacts'."
161 :group 'org-contacts
162 :type 'boolean)
164 ;; Decalre external functions and variables
165 (declare-function org-reverse-string "org")
166 (declare-function diary-ordinal-suffix "ext:diary-lib")
167 (declare-function wl-summary-message-number "ext:wl-summary")
168 (declare-function wl-address-header-extract-address "ext:wl-address")
169 (declare-function wl-address-header-extract-realname "ext:wl-address")
170 (declare-function erc-buffer-list "ext:erc")
171 (declare-function erc-get-channel-user-list "ext:erc")
172 (declare-function google-maps-static-show "ext:google-maps-static")
173 (declare-function elmo-message-field "ext:elmo-pipe")
174 (declare-function std11-narrow-to-header "ext:std11")
175 (declare-function std11-fetch-field "ext:std11")
177 (defconst org-contacts-property-values-separators "[,; \f\t\n\r\v]+"
178 "The default value of separators for `org-contacts-split-property'.
180 A regexp matching strings of whitespace, `,' and `;'.")
182 (defvar org-contacts-keymap
183 (let ((map (make-sparse-keymap)))
184 (define-key map "M" 'org-contacts-view-send-email)
185 (define-key map "i" 'org-contacts-view-switch-to-irc-buffer)
186 map)
187 "The keymap used in `org-contacts' result list.")
189 (defvar org-contacts-db nil
190 "Org Contacts database.")
192 (defvar org-contacts-last-update nil
193 "Last time the Org Contacts database has been updated.")
195 (defun org-contacts-files ()
196 "Return list of Org files to use for contact management."
197 (or org-contacts-files (org-agenda-files t 'ifmode)))
199 (defun org-contacts-db-need-update-p ()
200 "Determine whether `org-contacts-db' needs to be refreshed."
201 (or (null org-contacts-last-update)
202 (org-find-if (lambda (file)
203 (or (time-less-p org-contacts-last-update
204 (elt (file-attributes file) 5))))
205 (org-contacts-files))))
207 (defun org-contacts-db ()
208 "Return the latest Org Contacts Database."
209 (let* (todo-only
210 (contacts-matcher
211 (cdr (org-make-tags-matcher org-contacts-matcher)))
212 markers result)
213 (when (org-contacts-db-need-update-p)
214 (let ((progress-reporter
215 (make-progress-reporter "Updating Org Contacts Database..." 0 (length org-contacts-files)))
216 (i 0))
217 (dolist (file (org-contacts-files))
218 (org-check-agenda-file file)
219 (with-current-buffer (org-get-agenda-file-buffer file)
220 (unless (eq major-mode 'org-mode)
221 (error "File %s is no in `org-mode'" file))
222 (org-scan-tags
223 '(add-to-list 'markers (set-marker (make-marker) (point)))
224 contacts-matcher
225 todo-only))
226 (progress-reporter-update progress-reporter (setq i (1+ i))))
227 (dolist (marker markers result)
228 (org-with-point-at marker
229 (add-to-list 'result
230 (list (org-get-heading t) marker (org-entry-properties marker 'all)))))
231 (setf org-contacts-db result
232 org-contacts-last-update (current-time))
233 (progress-reporter-done progress-reporter)))
234 org-contacts-db))
236 (defun org-contacts-filter (&optional name-match tags-match prop-match)
237 "Search for a contact matching any of NAME-MATCH, TAGS-MATCH, PROP-MATCH.
238 If all match values are nil, return all contacts.
240 The optional PROP-MATCH argument is a single (PROP . VALUE) cons
241 cell corresponding to the contact properties.
243 (if (and (null name-match)
244 (null prop-match)
245 (null tags-match))
246 (org-contacts-db)
247 (loop for contact in (org-contacts-db)
248 if (or
249 (and name-match
250 (org-string-match-p name-match
251 (first contact)))
252 (and prop-match
253 (org-find-if (lambda (prop)
254 (and (string= (car prop-match) (car prop))
255 (org-string-match-p (cdr prop-match) (cdr prop))))
256 (caddr contact)))
257 (and tags-match
258 (org-find-if (lambda (tag)
259 (org-string-match-p tags-match tag))
260 (org-split-string
261 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
262 collect contact)))
264 (when (not (fboundp 'completion-table-case-fold))
265 ;; That function is new in Emacs 24...
266 (defun completion-table-case-fold (table &optional dont-fold)
267 (lambda (string pred action)
268 (let ((completion-ignore-case (not dont-fold)))
269 (complete-with-action action table string pred)))))
271 (defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
272 "Custom implementation of `try-completion'.
273 This version works only with list and alist and it looks at all
274 prefixes rather than just the beginning of the string."
275 (loop with regexp = (concat "\\b" (regexp-quote to-match))
276 with ret = nil
277 with ret-start = nil
278 with ret-end = nil
280 for el in collection
281 for string = (if (listp el) (car el) el)
283 for start = (when (or (null predicate) (funcall predicate string))
284 (string-match regexp string))
286 if start
287 do (let ((end (match-end 0))
288 (len (length string)))
289 (if (= end len)
290 (return t)
291 (destructuring-bind (string start end)
292 (if (null ret)
293 (values string start end)
294 (org-contacts-common-substring
295 ret ret-start ret-end
296 string start end))
297 (setf ret string
298 ret-start start
299 ret-end end))))
301 finally (return
302 (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
304 (defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
305 "Compare the contents of two strings, using `compare-strings'.
307 This function works like `compare-strings' excepted that it
308 returns a cons.
309 - The CAR is the number of characters that match at the beginning.
310 - The CDR is T is the two strings are the same and NIL otherwise."
311 (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
312 (if (eq ret t)
313 (cons (or end1 (length s1)) t)
314 (cons (1- (abs ret)) nil))))
316 (defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
317 "Extract the common substring between S1 and S2.
319 This function extracts the common substring between S1 and S2 and
320 adjust the part that remains common.
322 START1 and END1 delimit the part in S1 that we know is common
323 between the two strings. This applies to START2 and END2 for S2.
325 This function returns a list whose contains:
326 - The common substring found.
327 - The new value of the start of the known inner substring.
328 - The new value of the end of the known inner substring."
329 ;; Given two strings:
330 ;; s1: "foo bar baz"
331 ;; s2: "fooo bar baz"
332 ;; and the inner substring is "bar"
333 ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
335 ;; To find the common substring we will compare two substrings:
336 ;; " oof" and " ooof" to find the beginning of the common substring.
337 ;; " baz" and " baz" to find the end of the common substring.
338 (let* ((len1 (length s1))
339 (start1 (or start1 0))
340 (end1 (or end1 len1))
342 (len2 (length s2))
343 (start2 (or start2 0))
344 (end2 (or end2 len2))
346 (new-start (car (org-contacts-compare-strings
347 (substring (org-reverse-string s1) (- len1 start1)) nil nil
348 (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
350 (new-end (+ end1 (car (org-contacts-compare-strings
351 (substring s1 end1) nil nil
352 (substring s2 end2) nil nil)))))
353 (list (substring s1 (- start1 new-start) new-end)
354 new-start
355 (+ new-start (- end1 start1)))))
357 (defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
358 "Custom version of `all-completions'.
359 This version works only with list and alist and it looks at all
360 prefixes rather than just the beginning of the string."
361 (loop with regexp = (concat "\\b" (regexp-quote to-match))
362 for el in collection
363 for string = (if (listp el) (car el) el)
364 for match? = (when (and (or (null predicate) (funcall predicate string)))
365 (string-match regexp string))
366 if match?
367 collect (progn
368 (let ((end (match-end 0)))
369 (org-no-properties string)
370 (when (< end (length string))
371 ;; Here we add a text property that will be used
372 ;; later to highlight the character right after
373 ;; the common part between each addresses.
374 ;; See `org-contacts-display-sort-function'.
375 (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
376 string)))
378 (defun org-contacts-make-collection-prefix (collection)
379 "Make a collection function from COLLECTION which will match on prefixes."
380 (lexical-let ((collection collection))
381 (lambda (string predicate flag)
382 (cond ((eq flag nil)
383 (org-contacts-try-completion-prefix string collection predicate))
384 ((eq flag t)
385 ;; `org-contacts-all-completions-prefix' has already been
386 ;; used to compute `all-completions'.
387 collection)
388 ((eq flag 'lambda)
389 (org-contacts-test-completion-prefix string collection predicate))
390 ((and (listp flag) (eq (car flag) 'boundaries))
391 (destructuring-bind (to-ignore &rest suffix)
392 flag
393 (org-contacts-boundaries-prefix string collection predicate suffix)))
394 ((eq flag 'metadata)
395 (org-contacts-metadata-prefix string collection predicate))
396 (t nil ; operation unsupported
397 )))))
399 (defun org-contacts-display-sort-function (completions)
400 "Sort function for contacts display."
401 (mapcar (lambda (string)
402 (loop with len = (1- (length string))
403 for i upfrom 0 to len
404 if (memq 'org-contacts-prefix
405 (text-properties-at i string))
406 do (set-text-properties
407 i (1+ i)
408 (list 'font-lock-face
409 (if (char-equal (aref string i)
410 (string-to-char " "))
411 ;; Spaces can't be bold.
412 'underline
413 'bold)) string)
414 else
415 do (set-text-properties i (1+ i) nil string)
416 finally (return string)))
417 completions))
419 (defun org-contacts-test-completion-prefix (string collection predicate)
420 ;; Prevents `org-find-if' from redefining `predicate' and going into
421 ;; an infinite loop.
422 (lexical-let ((predicate predicate))
423 (org-find-if (lambda (el)
424 (and (or (null predicate) (funcall predicate el))
425 (string= string el)))
426 collection)))
428 (defun org-contacts-boundaries-prefix (string collection predicate suffix)
429 (list* 'boundaries (completion-boundaries string collection predicate suffix)))
431 (defun org-contacts-metadata-prefix (string collection predicate)
432 '(metadata .
433 ((display-sort-function . org-contacts-display-sort-function))))
435 (defun org-contacts-complete-group (start end string)
436 "Complete text at START from a group.
438 A group FOO is composed of contacts with the tag FOO."
439 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
440 (group-completion-p (org-string-match-p
441 (concat "^" org-contacts-group-prefix) string)))
442 (when group-completion-p
443 (let ((completion-list
444 (all-completions
445 string
446 (mapcar (lambda (group)
447 (propertize (concat org-contacts-group-prefix group)
448 'org-contacts-group group))
449 (org-uniquify
450 (loop for contact in (org-contacts-filter)
451 nconc (org-split-string
452 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
453 (list start end
454 (if (= (length completion-list) 1)
455 ;; We've found the correct group, returns the address
456 (lexical-let ((tag (get-text-property 0 'org-contacts-group
457 (car completion-list))))
458 (lambda (string pred &optional to-ignore)
459 (mapconcat 'identity
460 (loop for contact in (org-contacts-filter
462 tag)
463 ;; The contact name is always the car of the assoc-list
464 ;; returned by `org-contacts-filter'.
465 for contact-name = (car contact)
466 ;; Grab the first email of the contact
467 for email = (org-contacts-strip-link (car (org-contacts-split-property
469 (cdr (assoc-string org-contacts-email-property
470 (caddr contact)))
471 ""))))
472 ;; If the user has an email address, append USER <EMAIL>.
473 if email collect (org-contacts-format-email contact-name email))
474 ", ")))
475 ;; We haven't found the correct group
476 (completion-table-case-fold completion-list
477 (not org-contacts-completion-ignore-case))))))))
479 (defun org-contacts-complete-name (start end string)
480 "Complete text at START with a user name and email."
481 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
482 (completion-list
483 (loop for contact in (org-contacts-filter)
484 ;; The contact name is always the car of the assoc-list
485 ;; returned by `org-contacts-filter'.
486 for contact-name = (car contact)
487 ;; Build the list of the user email addresses.
488 for email-list = (org-contacts-split-property (or
489 (cdr (assoc-string org-contacts-email-property
490 (caddr contact))) ""))
491 ;; If the user has email addresses…
492 if email-list
493 ;; … append a list of USER <EMAIL>.
494 nconc (loop for email in email-list
495 collect (org-contacts-format-email contact-name (org-contacts-strip-link email)))))
496 (completion-list (org-contacts-all-completions-prefix
497 string
498 (org-uniquify completion-list))))
499 (when completion-list
500 (list start end
501 (org-contacts-make-collection-prefix completion-list)))))
503 (defun org-contacts-message-complete-function (&optional start)
504 "Function used in `completion-at-point-functions' in `message-mode'."
505 ;; Avoid to complete in `post-command-hook'.
506 (when completion-in-region-mode
507 (remove-hook 'post-command-hook #'completion-in-region--postch))
508 (let ((mail-abbrev-mode-regexp
509 "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
510 (when (mail-abbrev-in-expansion-header-p)
511 (lexical-let*
512 ((end (point))
513 (start (or start
514 (save-excursion
515 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
516 (goto-char (match-end 0))
517 (point))))
518 (string (buffer-substring start end)))
519 (or (org-contacts-complete-group start end string)
520 (org-contacts-complete-name start end string))))))
522 (defun org-contacts-gnus-get-name-email ()
523 "Get name and email address from Gnus message."
524 (if (gnus-alive-p)
525 (gnus-with-article-headers
526 (mail-extract-address-components
527 (or (mail-fetch-field "From") "")))))
529 (defun org-contacts-gnus-article-from-get-marker ()
530 "Return a marker for a contact based on From."
531 (let* ((address (org-contacts-gnus-get-name-email))
532 (name (car address))
533 (email (cadr address)))
534 (cadar (or (org-contacts-filter
537 (cons org-contacts-email-property (concat "\\b" (regexp-quote email) "\\b")))
538 (when name
539 (org-contacts-filter
540 (concat "^" name "$")))))))
542 (defun org-contacts-gnus-article-from-goto ()
543 "Go to contact in the From address of current Gnus message."
544 (interactive)
545 (let ((marker (org-contacts-gnus-article-from-get-marker)))
546 (when marker
547 (switch-to-buffer-other-window (marker-buffer marker))
548 (goto-char marker)
549 (when (eq major-mode 'org-mode)
550 (org-show-context 'agenda)
551 (save-excursion
552 (and (outline-next-heading)
553 ;; show the next heading
554 (org-flag-heading nil)))))))
556 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
557 (defun org-contacts-anniversaries (&optional field format)
558 "Compute FIELD anniversary for each contact, returning FORMAT.
559 Default FIELD value is \"BIRTHDAY\".
561 Format is a string matching the following format specification:
563 %h - Heading name
564 %l - Link to the heading
565 %y - Number of year
566 %Y - Number of year (ordinal)"
567 (let ((calendar-date-style 'american)
568 (entry ""))
569 (unless format (setq format org-contacts-birthday-format))
570 (loop for contact in (org-contacts-filter)
571 for anniv = (let ((anniv (cdr (assoc-string
572 (or field org-contacts-birthday-property)
573 (caddr contact)))))
574 (when anniv
575 (calendar-gregorian-from-absolute
576 (org-time-string-to-absolute anniv))))
577 ;; Use `diary-anniversary' to compute anniversary.
578 if (and anniv (apply 'diary-anniversary anniv))
579 collect (format-spec format
580 `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
581 (?h . ,(car contact))
582 (?y . ,(- (calendar-extract-year date)
583 (calendar-extract-year anniv)))
584 (?Y . ,(let ((years (- (calendar-extract-year date)
585 (calendar-extract-year anniv))))
586 (format "%d%s" years (diary-ordinal-suffix years)))))))))
588 (defun org-completing-read-date (prompt collection
589 &optional predicate require-match initial-input
590 hist def inherit-input-method)
591 "Like `completing-read' but reads a date.
592 Only PROMPT and DEF are really used."
593 (org-read-date nil nil nil prompt nil def))
595 (add-to-list 'org-property-set-functions-alist
596 `(,org-contacts-birthday-property . org-completing-read-date))
598 (defun org-contacts-template-name (&optional return-value)
599 "Try to return the contact name for a template.
600 If not found return RETURN-VALUE or something that would ask the user."
601 (or (car (org-contacts-gnus-get-name-email))
602 return-value
603 "%^{Name}"))
605 (defun org-contacts-template-email (&optional return-value)
606 "Try to return the contact email for a template.
607 If not found return RETURN-VALUE or something that would ask the user."
608 (or (cadr (org-contacts-gnus-get-name-email))
609 return-value
610 (concat "%^{" org-contacts-email-property "}p")))
612 (defun org-contacts-gnus-store-last-mail ()
613 "Store a link between mails and contacts.
615 This function should be called from `gnus-article-prepare-hook'."
616 (let ((marker (org-contacts-gnus-article-from-get-marker)))
617 (when marker
618 (with-current-buffer (marker-buffer marker)
619 (save-excursion
620 (goto-char marker)
621 (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
622 org-email-link-description-format))
623 (link (gnus-with-article-buffer (org-store-link nil))))
624 (org-set-property org-contacts-last-read-mail-property link)))))))
626 (defun org-contacts-icon-as-string ()
627 "Return the contact icon as a string."
628 (let ((image (org-contacts-get-icon)))
629 (concat
630 (propertize "-" 'display
631 (append
632 (if image
633 image
634 `'(space :width (,org-contacts-icon-size)))
635 '(:ascent center)))
636 " ")))
638 ;;;###autoload
639 (defun org-contacts (name)
640 "Create agenda view for contacts matching NAME."
641 (interactive (list (read-string "Name: ")))
642 (let ((org-agenda-files (org-contacts-files))
643 (org-agenda-skip-function
644 (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
645 (org-agenda-prefix-format (propertize
646 "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
647 'keymap org-contacts-keymap))
648 (org-agenda-overriding-header
649 (or org-agenda-overriding-header
650 (concat "List of contacts matching `" name "':"))))
651 (setq org-agenda-skip-regexp name)
652 (org-tags-view nil org-contacts-matcher)
653 (with-current-buffer org-agenda-buffer-name
654 (setq org-agenda-redo-command
655 (list 'org-contacts name)))))
657 (defun org-contacts-completing-read (prompt
658 &optional predicate
659 initial-input hist def inherit-input-method)
660 "Call `completing-read' with contacts name as collection."
661 (org-completing-read
662 prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
664 (defun org-contacts-format-name (name)
665 "Trim any local formatting to get a bare NAME."
666 ;; Remove radio targets characters
667 (replace-regexp-in-string org-radio-target-regexp "\\1" name))
669 (defun org-contacts-format-email (name email)
670 "Format an EMAIL address corresponding to NAME."
671 (unless email
672 (error "`email' cannot be nul"))
673 (if name
674 (concat (org-contacts-format-name name) " <" email ">")
675 email))
677 (defun org-contacts-check-mail-address (mail)
678 "Add MAIL address to contact at point if it does not have it."
679 (let ((mails (org-entry-get (point) org-contacts-email-property)))
680 (unless (member mail (split-string mails))
681 (when (yes-or-no-p
682 (format "Do you want to add this address to %s?" (org-get-heading t)))
683 (org-set-property org-contacts-email-property (concat mails " " mail))))))
685 (defun org-contacts-gnus-check-mail-address ()
686 "Check that contact has the current address recorded.
687 This function should be called from `gnus-article-prepare-hook'."
688 (let ((marker (org-contacts-gnus-article-from-get-marker)))
689 (when marker
690 (org-with-point-at marker
691 (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
693 (defun org-contacts-gnus-insinuate ()
694 "Add some hooks for Gnus user.
695 This adds `org-contacts-gnus-check-mail-address' and
696 `org-contacts-gnus-store-last-mail' to
697 `gnus-article-prepare-hook'. It also adds a binding on `;' in
698 `gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
699 (require 'gnus)
700 (require 'gnus-art)
701 (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
702 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
703 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
705 (defun org-contacts-setup-completion-at-point ()
706 "Add `org-contacts-message-complete-function' as a new function
707 to complete the thing at point."
708 (add-to-list 'completion-at-point-functions
709 'org-contacts-message-complete-function))
711 (defun org-contacts-unload-hook ()
712 (remove-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
714 (when (and org-contacts-enable-completion
715 (boundp 'completion-at-point-functions))
716 (add-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
718 (defun org-contacts-wl-get-from-header-content ()
719 "Retrieve the content of the `From' header of an email.
720 Works from wl-summary-mode and mime-view-mode - that is while viewing email.
721 Depends on Wanderlust been loaded."
722 (with-current-buffer (org-capture-get :original-buffer)
723 (cond
724 ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
725 wl-summary-buffer-elmo-folder)
726 (elmo-message-field
727 wl-summary-buffer-elmo-folder
728 (wl-summary-message-number)
729 'from)))
730 ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
731 (prog1
732 (std11-fetch-field "From")
733 (widen))))))
735 (defun org-contacts-wl-get-name-email ()
736 "Get name and email address from Wanderlust email.
737 See `org-contacts-wl-get-from-header-content' for limitations."
738 (let ((from (org-contacts-wl-get-from-header-content)))
739 (when from
740 (list (wl-address-header-extract-realname from)
741 (wl-address-header-extract-address from)))))
743 (defun org-contacts-template-wl-name (&optional return-value)
744 "Try to return the contact name for a template from wl.
745 If not found, return RETURN-VALUE or something that would ask the
746 user."
747 (or (car (org-contacts-wl-get-name-email))
748 return-value
749 "%^{Name}"))
751 (defun org-contacts-template-wl-email (&optional return-value)
752 "Try to return the contact email for a template from Wanderlust.
753 If not found return RETURN-VALUE or something that would ask the user."
754 (or (cadr (org-contacts-wl-get-name-email))
755 return-value
756 (concat "%^{" org-contacts-email-property "}p")))
758 (defun org-contacts-view-send-email (&optional ask)
759 "Send email to the contact at point.
760 If ASK is set, ask for the email address even if there's only one
761 address."
762 (interactive "P")
763 (let ((marker (org-get-at-bol 'org-hd-marker)))
764 (org-with-point-at marker
765 (let ((emails (org-entry-get (point) org-contacts-email-property)))
766 (if emails
767 (let ((email-list (org-contacts-split-property emails)))
768 (if (and (= (length email-list) 1) (not ask))
769 (compose-mail (org-contacts-format-email
770 (org-get-heading t) emails))
771 (let ((email (completing-read "Send mail to which address: " email-list)))
772 (setq email (org-contacts-strip-link email))
773 (org-contacts-check-mail-address email)
774 (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
775 (error (format "This contact has no mail address set (no %s property)."
776 org-contacts-email-property)))))))
778 (defun org-contacts-get-icon (&optional pom)
779 "Get icon for contact at POM."
780 (setq pom (or pom (point)))
781 (catch 'icon
782 ;; Use `org-contacts-icon-property'
783 (let ((image-data (org-entry-get pom org-contacts-icon-property)))
784 (when image-data
785 (throw 'icon
786 (if (fboundp 'gnus-rescale-image)
787 (gnus-rescale-image (create-image image-data)
788 (cons org-contacts-icon-size org-contacts-icon-size))
789 (create-image image-data)))))
790 ;; Next, try Gravatar
791 (when org-contacts-icon-use-gravatar
792 (let* ((gravatar-size org-contacts-icon-size)
793 (email-list (org-entry-get pom org-contacts-email-property))
794 (gravatar
795 (when email-list
796 (loop for email in (org-contacts-split-property email-list)
797 for gravatar = (gravatar-retrieve-synchronously (org-contacts-strip-link email))
798 if (and gravatar
799 (not (eq gravatar 'error)))
800 return gravatar))))
801 (when gravatar (throw 'icon gravatar))))))
803 (defun org-contacts-irc-buffer (&optional pom)
804 "Get the IRC buffer associated with the entry at POM."
805 (setq pom (or pom (point)))
806 (let ((nick (org-entry-get pom org-contacts-nickname-property)))
807 (when nick
808 (let ((buffer (get-buffer nick)))
809 (when buffer
810 (with-current-buffer buffer
811 (when (eq major-mode 'erc-mode)
812 buffer)))))))
814 (defun org-contacts-irc-number-of-unread-messages (&optional pom)
815 "Return the number of unread messages for contact at POM."
816 (when (boundp 'erc-modified-channels-alist)
817 (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
818 (if number
819 (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
820 (make-string 21 ? )))))
822 (defun org-contacts-view-switch-to-irc-buffer ()
823 "Switch to the IRC buffer of the current contact if it has one."
824 (interactive)
825 (let ((marker (org-get-at-bol 'org-hd-marker)))
826 (org-with-point-at marker
827 (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
829 (defun org-contacts-completing-read-nickname (prompt collection
830 &optional predicate require-match initial-input
831 hist def inherit-input-method)
832 "Like `completing-read' but reads a nickname."
833 (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
834 initial-input hist def inherit-input-method))
836 (defun erc-nicknames-list ()
837 "Return all nicknames of all ERC buffers."
838 (loop for buffer in (erc-buffer-list)
839 nconc (with-current-buffer buffer
840 (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
841 collect (elt user-entry 1)))))
843 (add-to-list 'org-property-set-functions-alist
844 `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
846 (defun org-contacts-vcard-escape (str)
847 "Escape ; , and \n in STR for the VCard format."
848 ;; Thanks to this library for the regexp:
849 ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
850 (when str
851 (replace-regexp-in-string
852 "\n" "\\\\n"
853 (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
855 (defun org-contacts-vcard-encode-name (name)
856 "Try to encode NAME as VCard's N property.
857 The N property expects
859 FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
861 Org-contacts does not specify how to encode the name. So we try
862 to do our best."
863 (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
865 (defun org-contacts-vcard-format (contact)
866 "Formats CONTACT in VCard 3.0 format."
867 (let* ((properties (caddr contact))
868 (name (org-contacts-vcard-escape (car contact)))
869 (n (org-contacts-vcard-encode-name name))
870 (email (cdr (assoc-string org-contacts-email-property properties)))
871 (tel (cdr (assoc-string org-contacts-tel-property properties)))
872 (note (cdr (assoc-string org-contacts-note-property properties)))
873 (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
874 (addr (cdr (assoc-string org-contacts-address-property properties)))
875 (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
876 (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name)))
877 (concat head
878 (when email (progn
879 (setq emails-list (org-contacts-split-property email))
880 (setq result "")
881 (while emails-list
882 (setq result (concat result "EMAIL:" (org-contacts-strip-link (car emails-list)) "\n"))
883 (setq emails-list (cdr emails-list)))
884 result))
885 (when addr
886 (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
887 (when tel (progn
888 (setq phones-list (org-contacts-split-property tel))
889 (setq result "")
890 (while phones-list
891 (setq result (concat result "TEL:" (org-contacts-strip-link (car phones-list)) "\n"))
892 (setq phones-list (cdr phones-list)))
893 result))
894 (when bday
895 (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
896 (format "BDAY:%04d-%02d-%02d\n"
897 (calendar-extract-year cal-bday)
898 (calendar-extract-month cal-bday)
899 (calendar-extract-day cal-bday))))
900 (when nick (format "NICKNAME:%s\n" nick))
901 (when note (format "NOTE:%s\n" note))
902 "END:VCARD\n\n")))
904 (defun org-contacts-export-as-vcard (&optional name file to-buffer)
905 "Export all contacts matching NAME as VCard 3.0.
906 If TO-BUFFER is nil, the content is written to FILE or
907 `org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
908 is created and the VCard is written into that buffer."
909 (interactive) ; TODO ask for name?
910 (let* ((filename (or file org-contacts-vcard-file))
911 (buffer (if to-buffer
912 (get-buffer-create to-buffer)
913 (find-file-noselect filename))))
914 (message "Exporting...")
915 (set-buffer buffer)
916 (let ((inhibit-read-only t)) (erase-buffer))
917 (fundamental-mode)
918 (when (fboundp 'set-buffer-file-coding-system)
919 (set-buffer-file-coding-system coding-system-for-write))
920 (loop for contact in (org-contacts-filter name)
921 do (insert (org-contacts-vcard-format contact)))
922 (if to-buffer
923 (current-buffer)
924 (progn (save-buffer) (kill-buffer)))))
926 (defun org-contacts-show-map (&optional name)
927 "Show contacts on a map.
928 Requires google-maps-el."
929 (interactive)
930 (unless (fboundp 'google-maps-static-show)
931 (error "`org-contacts-show-map' requires `google-maps-el'"))
932 (google-maps-static-show
933 :markers
934 (loop
935 for contact in (org-contacts-filter name)
936 for addr = (cdr (assoc-string org-contacts-address-property (caddr contact)))
937 if addr
938 collect (cons (list addr) (list :label (string-to-char (car contact)))))))
940 (defun org-contacts-strip-link (link)
941 "Remove brackets, description, link type and colon from an org
942 link string and return the pure link target."
943 (let (startpos colonpos endpos)
944 (setq startpos (string-match (regexp-opt '("[[tel:" "[[mailto:")) link))
945 (if startpos
946 (progn
947 (setq colonpos (string-match ":" link))
948 (setq endpos (string-match "\\]" link))
949 (if endpos (substring link (1+ colonpos) endpos) link))
950 (progn
951 (setq startpos (string-match "mailto:" link))
952 (setq colonpos (string-match ":" link))
953 (if startpos (substring link (1+ colonpos)) link)))))
955 (defun org-contacts-split-property (string &optional separators omit-nulls)
956 "Custom version of `split-string'.
957 Split a property STRING into sub-strings bounded by matches
958 for SEPARATORS but keep Org links intact.
960 The beginning and end of STRING, and each match for SEPARATORS, are
961 splitting points. The substrings matching SEPARATORS are removed, and
962 the substrings between the splitting points are collected as a list,
963 which is returned.
965 If SEPARATORS is non-nil, it should be a regular expression
966 matching text which separates, but is not part of, the
967 substrings. If nil it defaults to `org-contacts-property-values-separators',
968 normally \"[,; \f\t\n\r\v]+\", and OMIT-NULLS is forced to t.
970 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
971 that for the default value of SEPARATORS leading and trailing whitespace
972 are effectively trimmed). If nil, all zero-length substrings are retained."
973 (let* ((keep-nulls (or nil omit-nulls))
974 (rexp (or separators org-contacts-property-values-separators))
975 (inputlist (split-string string rexp keep-nulls))
976 (linkstring "")
977 (bufferstring "")
978 (proplist (list "")))
979 (while inputlist
980 (setq bufferstring (pop inputlist))
981 (if (string-match "\\[\\[" bufferstring)
982 (progn
983 (setq linkstring (concat bufferstring " "))
984 (while (not (string-match "\\]\\]" bufferstring))
985 (setq bufferstring (pop inputlist))
986 (setq linkstring (concat linkstring bufferstring " ")))
987 (setq proplist (cons (org-trim linkstring) proplist)))
988 (setq proplist (cons bufferstring proplist))))
989 (cdr (reverse proplist))))
991 (provide 'org-contacts)
993 ;;; org-contacts.el ends here