org-contacts.el: Let the users decide if they want to use `org-contacts' to complete...
[org-mode.git] / contrib / lisp / org-contacts.el
blob867453390cfc7faf79a658fb1dc6cc91839b3115
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 ;; GNU Emacs 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 ;; GNU Emacs 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 (eval-and-compile
43 (require 'org))
44 (require 'gnus-util)
45 (require 'org-agenda)
46 (require 'org-capture)
48 (defgroup org-contacts nil
49 "Options about contacts management."
50 :group 'org)
52 (defcustom org-contacts-files nil
53 "List of Org files to use as contacts source.
54 When set to nil, all your Org files will be used."
55 :type '(repeat file)
56 :group 'org-contacts)
58 (defcustom org-contacts-email-property "EMAIL"
59 "Name of the property for contact email address."
60 :type 'string
61 :group 'org-contacts)
63 (defcustom org-contacts-address-property "ADDRESS"
64 "Name of the property for contact address."
65 :type 'string
66 :group 'org-contacts)
68 (defcustom org-contacts-birthday-property "BIRTHDAY"
69 "Name of the property for contact birthday date."
70 :type 'string
71 :group 'org-contacts)
73 (defcustom org-contacts-birthday-format "Birthday: %l (%Y)"
74 "Format of the anniversary agenda entry.
75 The following replacements are available:
77 %h - Heading name
78 %l - Link to the heading
79 %y - Number of year
80 %Y - Number of year (ordinal)"
81 :type 'string
82 :group 'org-contacts)
84 (defcustom org-contacts-last-read-mail-property "LAST_READ_MAIL"
85 "Name of the property for contact last read email link storage."
86 :type 'string
87 :group 'org-contacts)
89 (defcustom org-contacts-icon-property "ICON"
90 "Name of the property for contact icon."
91 :type 'string
92 :group 'org-contacts)
94 (defcustom org-contacts-nickname-property "NICKNAME"
95 "Name of the property for IRC nickname match."
96 :type 'string
97 :group 'org-contacts)
99 (defcustom org-contacts-icon-size 32
100 "Size of the contacts icons."
101 :type 'string
102 :group 'org-contacts)
104 (defcustom org-contacts-icon-use-gravatar (fboundp 'gravatar-retrieve)
105 "Whether use Gravatar to fetch contact icons."
106 :type 'boolean
107 :group 'org-contacts)
109 (defcustom org-contacts-completion-ignore-case t
110 "Ignore case when completing contacts."
111 :type 'boolean
112 :group 'org-contacts)
114 (defcustom org-contacts-group-prefix "+"
115 "Group prefix."
116 :type 'string
117 :group 'org-contacts)
119 (defcustom org-contacts-matcher (concat org-contacts-email-property "<>\"\"")
120 "Matching rule for finding heading that are contacts.
121 This can be a tag name, or a property check."
122 :type 'string
123 :group 'org-contacts)
125 (defcustom org-contacts-email-link-description-format "%s (%d)"
126 "Format used to store links to email.
127 This overrides `org-email-link-description-format' if set."
128 :group 'org-contacts
129 :type 'string)
131 (defcustom org-contacts-vcard-file "contacts.vcf"
132 "Default file for vcard export."
133 :group 'org-contacts
134 :type 'file)
136 (defcustom org-contacts-enable-completion t
137 "Enable or not the completion in `message-mode' with `org-contacts'."
138 :group 'org-contacts
139 :type 'boolean)
141 ;; Decalre external functions and variables
142 (declare-function wl-summary-message-number "ext:wl-summary" ())
143 (declare-function wl-address-header-extract-address "ext:wl-address")
144 (declare-function wl-address-header-extract-realname "ext:wl-address")
146 (defvar org-contacts-keymap
147 (let ((map (make-sparse-keymap)))
148 (define-key map "M" 'org-contacts-view-send-email)
149 (define-key map "i" 'org-contacts-view-switch-to-irc-buffer)
150 map)
151 "The keymap used in `org-contacts' result list.")
153 (defvar org-contacts-db nil
154 "Org Contacts database.")
156 (defvar org-contacts-last-update nil
157 "Last time the Org Contacts database has been updated.")
159 (defun org-contacts-files ()
160 "Return list of Org files to use for contact management."
161 (or org-contacts-files (org-agenda-files t 'ifmode)))
163 (defun org-contacts-db-need-update? ()
164 "Determine whether `org-contacts-db' needs to be refreshed."
165 (or (null org-contacts-last-update)
166 (some (lambda (file)
167 (or (time-less-p org-contacts-last-update
168 (elt (file-attributes file) 5))))
169 (org-contacts-files))))
171 (defun org-contacts-db ()
172 "Return the latest Org Contacts Database"
173 (let* (todo-only
174 (contacts-matcher
175 (cdr (org-make-tags-matcher org-contacts-matcher)))
176 markers result)
177 (when (org-contacts-db-need-update?)
178 (message "Update Org Contacts Database")
179 (dolist (file (org-contacts-files))
180 (org-check-agenda-file file)
181 (with-current-buffer (org-get-agenda-file-buffer file)
182 (unless (eq major-mode 'org-mode)
183 (error "File %s is no in `org-mode'" file))
184 (org-scan-tags
185 '(add-to-list 'markers (set-marker (make-marker) (point)))
186 contacts-matcher
187 todo-only)))
188 (dolist (marker markers result)
189 (org-with-point-at marker
190 (add-to-list 'result
191 (list (org-get-heading t) marker (org-entry-properties marker 'all)))))
192 (setf org-contacts-db result
193 org-contacts-last-update (current-time)))
194 org-contacts-db))
196 (defun org-contacts-filter (&optional name-match tags-match)
197 "Search for a contact maching NAME-MATCH and TAGS-MATCH.
198 If both match values are nil, return all contacts."
199 (if (and (null name-match)
200 (null tags-match))
201 (org-contacts-db)
202 (loop for contact in (org-contacts-db)
203 if (or
204 (and name-match
205 (org-string-match-p name-match
206 (first contact)))
207 (and tags-match
208 (some (lambda (tag)
209 (org-string-match-p tags-match tag))
210 (org-split-string
211 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
212 collect contact)))
214 (when (not (fboundp 'completion-table-case-fold))
215 ;; That function is new in Emacs 24...
216 (defun completion-table-case-fold (table &optional dont-fold)
217 (lambda (string pred action)
218 (let ((completion-ignore-case (not dont-fold)))
219 (complete-with-action action table string pred)))))
221 (defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
222 "Like `try-completion' but:
223 - works only with list and alist;
224 - looks at all prefixes rather than just the beginning of the string;"
225 (loop with regexp = (concat "\\b" (regexp-quote to-match))
226 with ret = nil
227 with ret-start = nil
228 with ret-end = nil
230 for el in collection
231 for string = (if (listp el) (car el) el)
233 for start = (when (or (null predicate) (funcall predicate string))
234 (string-match regexp string))
236 if start
237 do (let ((end (match-end 0))
238 (len (length string)))
239 (if (= end len)
240 (return t)
241 (destructuring-bind (string start end)
242 (if (null ret)
243 (values string start end)
244 (org-contacts-common-substring
245 ret ret-start ret-end
246 string start end))
247 (setf ret string
248 ret-start start
249 ret-end end))))
251 finally (return
252 (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
254 (defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
255 "Compare the contents of two strings, using `compare-strings'.
257 This function works like `compare-strings' excepted that it
258 returns a cons.
259 - The CAR is the number of characters that match at the beginning.
260 - The CDR is T is the two strings are the same and NIL otherwise."
261 (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
262 (if (eq ret t)
263 (cons (or end1 (length s1)) t)
264 (cons (1- (abs ret)) nil))))
266 (defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
267 "Extract the common substring between S1 and S2.
269 This function extracts the common substring between S1 and S2 and
270 adjust the part that remains common.
272 START1 and END1 delimit the part in S1 that we know is common
273 between the two strings. This applies to START2 and END2 for S2.
275 This function returns a list whose contains:
276 - The common substring found.
277 - The new value of the start of the known inner substring.
278 - The new value of the end of the known inner substring."
279 ;; Given two strings:
280 ;; s1: "foo bar baz"
281 ;; s2: "fooo bar baz"
282 ;; and the inner substring is "bar"
283 ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
285 ;; To find the common substring we will compare two substrings:
286 ;; " oof" and " ooof" to find the beginning of the common substring.
287 ;; " baz" and " baz" to find the end of the common substring.
288 (let* ((len1 (length s1))
289 (start1 (or start1 0))
290 (end1 (or end1 len1))
292 (len2 (length s2))
293 (start2 (or start2 0))
294 (end2 (or end2 len2))
296 (new-start (car (org-contacts-compare-strings
297 (substring (org-reverse-string s1) (- len1 start1)) nil nil
298 (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
300 (new-end (+ end1 (car (org-contacts-compare-strings
301 (substring s1 end1) nil nil
302 (substring s2 end2) nil nil)))))
303 (list (substring s1 (- start1 new-start) new-end)
304 new-start
305 (+ new-start (- end1 start1)))))
307 (defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
308 "Like `all-completions' but:
309 - works only with list and alist;
310 - looks at all prefixes rather than just the beginning of the string;"
311 (loop with regexp = (concat "\\b" (regexp-quote to-match))
312 for el in collection
313 for string = (if (listp el) (car el) el)
314 for match? = (when (and (or (null predicate) (funcall predicate string)))
315 (string-match regexp string))
316 if match?
317 collect (progn
318 (let ((end (match-end 0)))
319 (org-no-properties string)
320 (when (< end (length string))
321 ;; Here we add a text property that will be used
322 ;; later to highlight the character right after
323 ;; the common part between each addresses.
324 ;; See `org-contacts-display-sort-function'.
325 (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
326 string)))
328 (defun org-contacts-make-collection-prefix (collection)
329 "Makes a collection function from COLLECTION which will match
330 on prefixes."
331 (lexical-let ((collection collection))
332 (lambda (string predicate flag)
333 (cond ((eq flag nil)
334 (org-contacts-try-completion-prefix string collection predicate))
335 ((eq flag t)
336 ;; `org-contacts-all-completions-prefix' has already been
337 ;; used to compute `all-completions'.
338 collection)
339 ((eq flag 'lambda)
340 (org-contacts-test-completion-prefix string collection predicate))
341 ((and (listp flag) (eq (car flag) 'boundaries))
342 (destructuring-bind (to-ignore &rest suffix)
343 flag
344 (org-contacts-boundaries-prefix string collection predicate suffix)))
345 ((eq flag 'metadata)
346 (org-contacts-metadata-prefix string collection predicate))
347 (t nil ; operation unsupported
348 )))))
350 (defun org-contacts-display-sort-function (completions)
351 (mapcar (lambda (string)
352 (loop with len = (1- (length string))
353 for i upfrom 0 to len
354 if (memq 'org-contacts-prefix
355 (text-properties-at i string))
356 do (set-text-properties
357 i (1+ i)
358 (list 'font-lock-face
359 (if (char-equal (aref string i)
360 (string-to-char " "))
361 ;; Spaces can't be bold.
362 'underline
363 'bold)) string)
364 else
365 do (set-text-properties i (1+ i) nil string)
366 finally (return string)))
367 completions))
369 (defun org-contacts-test-completion-prefix (string collection predicate)
370 (find-if (lambda (el)
371 (and (or (null predicate) (funcall predicate el))
372 (string= string el)))
373 collection))
375 (defun org-contacts-boundaries-prefix (string collection predicate suffix)
376 (list* 'boundaries (completion-boundaries string collection predicate suffix)))
378 (defun org-contacts-metadata-prefix (string collection predicate)
379 '(metadata .
380 ((display-sort-function . org-contacts-display-sort-function))))
382 (defun org-contacts-complete-group (start end string)
383 "Complete text at START from a group.
385 A group FOO is composed of contacts with the tag FOO."
386 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
387 (group-completion-p (org-string-match-p
388 (concat "^" org-contacts-group-prefix) string)))
389 (when group-completion-p
390 (let ((completion-list
391 (all-completions
392 string
393 (mapcar (lambda (group)
394 (propertize (concat org-contacts-group-prefix group)
395 'org-contacts-group group))
396 (org-uniquify
397 (loop for contact in (org-contacts-filter)
398 nconc (org-split-string
399 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
400 (list start end
401 (if (= (length completion-list) 1)
402 ;; We've foudn the correct group, returns the address
403 (lexical-let ((tag (get-text-property 0 'org-contacts-group
404 (car completion-list))))
405 (lambda (string pred &optional to-ignore)
406 (mapconcat 'identity
407 (loop for contact in (org-contacts-filter
409 tag)
410 ;; The contact name is always the car of the assoc-list
411 ;; returned by `org-contacts-filter'.
412 for contact-name = (car contact)
413 ;; Grab the first email of the contact
414 for email = (car (split-string
416 (cdr (assoc-string org-contacts-email-property
417 (caddr contact)))
418 "")))
419 ;; If the user has an email address, append USER <EMAIL>.
420 if email collect (org-contacts-format-email contact-name email))
421 ", ")))
422 ;; We haven't found the correct group
423 (completion-table-case-fold completion-list
424 (not org-contacts-completion-ignore-case))))))))
426 (defun org-contacts-complete-name (start end string)
427 "Complete text at START with a user name and email."
428 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
429 (completion-list
430 (loop for contact in (org-contacts-filter)
431 ;; The contact name is always the car of the assoc-list
432 ;; returned by `org-contacts-filter'.
433 for contact-name = (car contact)
434 ;; Build the list of the user email addresses.
435 for email-list = (split-string (or
436 (cdr (assoc-string org-contacts-email-property
437 (caddr contact))) ""))
438 ;; If the user has email addresses…
439 if email-list
440 ;; … append a list of USER <EMAIL>.
441 nconc (loop for email in email-list
442 collect (org-contacts-format-email contact-name email)))))
443 (when completion-list
444 (list start end
445 (org-contacts-make-collection-prefix
446 (org-contacts-all-completions-prefix
447 string
448 (remove-duplicates completion-list :test #'equalp)))))))
450 (defun org-contacts-message-complete-function (&optional start)
451 "Function used in `completion-at-point-functions' in `message-mode'."
452 ;; Avoid to complete in `post-command-hook'.
453 (when completion-in-region-mode
454 (remove-hook 'post-command-hook #'completion-in-region--postch))
455 (let ((mail-abbrev-mode-regexp
456 "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
457 (when (mail-abbrev-in-expansion-header-p)
458 (lexical-let*
459 ((end (point))
460 (start (or start
461 (save-excursion
462 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
463 (goto-char (match-end 0))
464 (point))))
465 (string (buffer-substring start end)))
466 (or (org-contacts-complete-group start end string)
467 (org-contacts-complete-name start end string))))))
469 (defun org-contacts-gnus-get-name-email ()
470 "Get name and email address from Gnus message."
471 (if (gnus-alive-p)
472 (gnus-with-article-headers
473 (mail-extract-address-components
474 (or (mail-fetch-field "From") "")))))
476 (defun org-contacts-gnus-article-from-get-marker ()
477 "Return a marker for a contact based on From."
478 (let* ((address (org-contacts-gnus-get-name-email))
479 (name (car address))
480 (email (cadr address)))
481 (cadar (or (org-contacts-filter
483 (concat org-contacts-email-property "={\\b" (regexp-quote email) "\\b}"))
484 (when name
485 (org-contacts-filter
486 (concat "^" name "$")))))))
488 (defun org-contacts-gnus-article-from-goto ()
489 "Go to contact in the From address of current Gnus message."
490 (interactive)
491 (let ((marker (org-contacts-gnus-article-from-get-marker)))
492 (when marker
493 (switch-to-buffer-other-window (marker-buffer marker))
494 (goto-char marker)
495 (when (eq major-mode 'org-mode)
496 (org-show-context 'agenda)
497 (save-excursion
498 (and (outline-next-heading)
499 ;; show the next heading
500 (org-flag-heading nil)))))))
502 (defun org-contacts-anniversaries (&optional field format)
503 "Compute FIELD anniversary for each contact, returning FORMAT.
504 Default FIELD value is \"BIRTHDAY\".
506 Format is a string matching the following format specification:
508 %h - Heading name
509 %l - Link to the heading
510 %y - Number of year
511 %Y - Number of year (ordinal)"
512 (let ((calendar-date-style 'american)
513 (entry ""))
514 (unless format (setq format org-contacts-birthday-format))
515 (loop with date = nil ; FIXME: prevent a warning
516 for contact in (org-contacts-filter)
517 for anniv = (let ((anniv (cdr (assoc-string
518 (or field org-contacts-birthday-property)
519 (caddr contact)))))
520 (when anniv
521 (calendar-gregorian-from-absolute
522 (org-time-string-to-absolute anniv))))
523 ;; Use `diary-anniversary' to compute anniversary.
524 if (and anniv (apply 'diary-anniversary anniv))
525 collect (format-spec format
526 `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
527 (?h . ,(car contact))
528 (?y . ,(- (calendar-extract-year date)
529 (calendar-extract-year anniv)))
530 (?Y . ,(let ((years (- (calendar-extract-year date)
531 (calendar-extract-year anniv))))
532 (format "%d%s" years (diary-ordinal-suffix years)))))))))
534 (defun org-completing-read-date (prompt collection
535 &optional predicate require-match initial-input
536 hist def inherit-input-method)
537 "Like `completing-read' but reads a date.
538 Only PROMPT and DEF are really used."
539 (org-read-date nil nil nil prompt nil def))
541 (add-to-list 'org-property-set-functions-alist
542 `(,org-contacts-birthday-property . org-completing-read-date))
544 (defun org-contacts-template-name (&optional return-value)
545 "Try to return the contact name for a template.
546 If not found return RETURN-VALUE or something that would ask the user."
547 (or (car (org-contacts-gnus-get-name-email))
548 return-value
549 "%^{Name}"))
551 (defun org-contacts-template-email (&optional return-value)
552 "Try to return the contact email for a template.
553 If not found return RETURN-VALUE or something that would ask the user."
554 (or (cadr (org-contacts-gnus-get-name-email))
555 return-value
556 (concat "%^{" org-contacts-email-property "}p")))
558 (defun org-contacts-gnus-store-last-mail ()
559 "Store a link between mails and contacts.
561 This function should be called from `gnus-article-prepare-hook'."
562 (let ((marker (org-contacts-gnus-article-from-get-marker)))
563 (when marker
564 (with-current-buffer (marker-buffer marker)
565 (save-excursion
566 (goto-char marker)
567 (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
568 org-email-link-description-format))
569 (link (gnus-with-article-buffer (org-store-link nil))))
570 (org-set-property org-contacts-last-read-mail-property link)))))))
572 (defun org-contacts-icon-as-string ()
573 (let ((image (org-contacts-get-icon)))
574 (concat
575 (propertize "-" 'display
576 (append
577 (if image
578 image
579 `'(space :width (,org-contacts-icon-size)))
580 '(:ascent center)))
581 " ")))
583 ;;;###autoload
584 (defun org-contacts (name)
585 "Create agenda view for contacts matching NAME."
586 (interactive (list (read-string "Name: ")))
587 (let ((org-agenda-files (org-contacts-files))
588 (org-agenda-skip-function
589 (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
590 (org-agenda-prefix-format (propertize
591 "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
592 'keymap org-contacts-keymap))
593 (org-agenda-overriding-header
594 (or org-agenda-overriding-header
595 (concat "List of contacts matching `" name "':"))))
596 (setq org-agenda-skip-regexp name)
597 (org-tags-view nil org-contacts-matcher)
598 (with-current-buffer org-agenda-buffer-name
599 (setq org-agenda-redo-command
600 (list 'org-contacts name)))))
602 (defun org-contacts-completing-read (prompt
603 &optional predicate
604 initial-input hist def inherit-input-method)
605 "Call `completing-read' with contacts name as collection."
606 (org-completing-read
607 prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
609 (defun org-contacts-format-name (name)
610 "Trim any local formatting to get a bare name."
611 ;; Remove radio targets characters
612 (replace-regexp-in-string org-radio-target-regexp "\\1" name))
614 (defun org-contacts-format-email (name email)
615 "Format a mail address."
616 (unless email
617 (error "`email' cannot be nul"))
618 (if name
619 (concat (org-contacts-format-name name) " <" email ">")
620 email))
622 (defun org-contacts-check-mail-address (mail)
623 "Add MAIL address to contact at point if it does not have it."
624 (let ((mails (org-entry-get (point) org-contacts-email-property)))
625 (unless (member mail (split-string mails))
626 (when (yes-or-no-p
627 (format "Do you want to add this address to %s?" (org-get-heading t)))
628 (org-set-property org-contacts-email-property (concat mails " " mail))))))
630 (defun org-contacts-gnus-check-mail-address ()
631 "Check that contact has the current address recorded.
632 This function should be called from `gnus-article-prepare-hook'."
633 (let ((marker (org-contacts-gnus-article-from-get-marker)))
634 (when marker
635 (org-with-point-at marker
636 (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
638 (defun org-contacts-gnus-insinuate ()
639 "Add some hooks for Gnus user.
640 This adds `org-contacts-gnus-check-mail-address' and
641 `org-contacts-gnus-store-last-mail' to
642 `gnus-article-prepare-hook'. It also adds a binding on `;' in
643 `gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
644 (require 'gnus)
645 (require 'gnus-art)
646 (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
647 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
648 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
650 (when (and org-contacts-enable-completion
651 (boundp 'completion-at-point-functions))
652 (add-hook 'message-mode-hook
653 (lambda ()
654 (add-to-list 'completion-at-point-functions
655 'org-contacts-message-complete-function))))
657 (defun org-contacts-wl-get-from-header-content ()
658 "Retrieve the content of the `From' header of an email.
659 Works from wl-summary-mode and mime-view-mode - that is while viewing email.
660 Depends on Wanderlust been loaded."
661 (with-current-buffer (org-capture-get :original-buffer)
662 (cond
663 ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
664 wl-summary-buffer-elmo-folder)
665 (elmo-message-field
666 wl-summary-buffer-elmo-folder
667 (wl-summary-message-number)
668 'from)))
669 ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
670 (prog1
671 (std11-fetch-field "From")
672 (widen))))))
674 (defun org-contacts-wl-get-name-email ()
675 "Get name and email address from Wanderlust email.
676 See `org-contacts-wl-get-from-header-content' for limitations."
677 (let ((from (org-contacts-wl-get-from-header-content)))
678 (when from
679 (list (wl-address-header-extract-realname from)
680 (wl-address-header-extract-address from)))))
682 (defun org-contacts-template-wl-name (&optional return-value)
683 "Try to return the contact name for a template from wl.
684 If not found, return RETURN-VALUE or something that would ask the
685 user."
686 (or (car (org-contacts-wl-get-name-email))
687 return-value
688 "%^{Name}"))
690 (defun org-contacts-template-wl-email (&optional return-value)
691 "Try to return the contact email for a template from Wanderlust.
692 If not found return RETURN-VALUE or something that would ask the user."
693 (or (cadr (org-contacts-wl-get-name-email))
694 return-value
695 (concat "%^{" org-contacts-email-property "}p")))
697 (defun org-contacts-view-send-email (&optional ask)
698 "Send email to the contact at point.
699 If ASK is set, ask for the email address even if there's only one
700 address."
701 (interactive "P")
702 (let ((marker (org-get-at-bol 'org-hd-marker)))
703 (org-with-point-at marker
704 (let ((emails (org-entry-get (point) org-contacts-email-property)))
705 (if emails
706 (let ((email-list (split-string emails)))
707 (if (and (= (length email-list) 1) (not ask))
708 (compose-mail (org-contacts-format-email
709 (org-get-heading t) emails))
710 (let ((email (completing-read "Send mail to which address: " email-list)))
711 (org-contacts-check-mail-address email)
712 (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
713 (error (format "This contact has no mail address set (no %s property)."
714 org-contacts-email-property)))))))
716 (defun org-contacts-get-icon (&optional pom)
717 "Get icon for contact at POM."
718 (setq pom (or pom (point)))
719 (catch 'icon
720 ;; Use `org-contacts-icon-property'
721 (let ((image-data (org-entry-get pom org-contacts-icon-property)))
722 (when image-data
723 (throw 'icon
724 (if (fboundp 'gnus-rescale-image)
725 (gnus-rescale-image (create-image image-data)
726 (cons org-contacts-icon-size org-contacts-icon-size))
727 (create-image image-data)))))
728 ;; Next, try Gravatar
729 (when org-contacts-icon-use-gravatar
730 (let* ((gravatar-size org-contacts-icon-size)
731 (email-list (org-entry-get pom org-contacts-email-property))
732 (gravatar
733 (when email-list
734 (loop for email in (split-string email-list)
735 for gravatar = (gravatar-retrieve-synchronously email)
736 if (and gravatar
737 (not (eq gravatar 'error)))
738 return gravatar))))
739 (when gravatar (throw 'icon gravatar))))))
741 (defun org-contacts-irc-buffer (&optional pom)
742 "Get the IRC buffer associated with the entry at POM."
743 (setq pom (or pom (point)))
744 (let ((nick (org-entry-get pom org-contacts-nickname-property)))
745 (when nick
746 (let ((buffer (get-buffer nick)))
747 (when buffer
748 (with-current-buffer buffer
749 (when (eq major-mode 'erc-mode)
750 buffer)))))))
752 (defun org-contacts-irc-number-of-unread-messages (&optional pom)
753 "Return the number of unread messages for contact at POM."
754 (when (boundp 'erc-modified-channels-alist)
755 (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
756 (if number
757 (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
758 (make-string 21 ? )))))
760 (defun org-contacts-view-switch-to-irc-buffer ()
761 "Switch to the IRC buffer of the current contact if it has one."
762 (interactive)
763 (let ((marker (org-get-at-bol 'org-hd-marker)))
764 (org-with-point-at marker
765 (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
767 (defun org-contacts-completing-read-nickname (prompt collection
768 &optional predicate require-match initial-input
769 hist def inherit-input-method)
770 "Like `completing-read' but reads a nickname."
771 (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
772 initial-input hist def inherit-input-method))
774 (defun erc-nicknames-list ()
775 "Return all nicknames of all ERC buffers."
776 (if (fboundp 'erc-buffer-list)
777 (loop for buffer in (erc-buffer-list)
778 nconc (with-current-buffer buffer
779 (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
780 collect (elt user-entry 1))))))
782 (add-to-list 'org-property-set-functions-alist
783 `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
785 (defun org-contacts-vcard-escape (str)
786 "Escape ; , and \n in STR for the VCard format."
787 ;; Thanks to this library for the regexp:
788 ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
789 (when str
790 (replace-regexp-in-string
791 "\n" "\\\\n"
792 (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
794 (defun org-contacts-vcard-encode-name (name)
795 "Try to encode NAME as VCard's N property.
796 The N property expects
798 FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
800 Org-contacts does not specify how to encode the name. So we try
801 to do our best."
802 (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
804 (defun org-contacts-vcard-format (contact)
805 "Formats CONTACT in VCard 3.0 format."
806 (let* ((properties (caddr contact))
807 (name (org-contacts-vcard-escape (car contact)))
808 (n (org-contacts-vcard-encode-name name))
809 (email (org-contacts-vcard-escape (cdr (assoc-string org-contacts-email-property properties))))
810 (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
811 (addr (cdr (assoc-string org-contacts-address-property properties)))
812 (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
813 (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name)))
814 (concat head
815 (when email (format "EMAIL:%s\n" email))
816 (when addr
817 (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
818 (when bday
819 (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
820 (format "BDAY:%04d-%02d-%02d\n"
821 (calendar-extract-year cal-bday)
822 (calendar-extract-month cal-bday)
823 (calendar-extract-day cal-bday))))
824 (when nick (format "NICKNAME:%s\n" nick))
825 "END:VCARD\n\n")))
827 (defun org-contacts-export-as-vcard (&optional name file to-buffer)
828 "Export all contacts matching NAME as VCard 3.0.
829 If TO-BUFFER is nil, the content is written to FILE or
830 `org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
831 is created and the VCard is written into that buffer."
832 (interactive) ; TODO ask for name?
833 (let* ((filename (or file org-contacts-vcard-file))
834 (buffer (if to-buffer
835 (get-buffer-create to-buffer)
836 (find-file-noselect filename))))
838 (message "Exporting...")
840 (set-buffer buffer)
841 (let ((inhibit-read-only t)) (erase-buffer))
842 (fundamental-mode)
843 (org-install-letbind)
845 (when (fboundp 'set-buffer-file-coding-system)
846 (set-buffer-file-coding-system coding-system-for-write))
848 (loop for contact in (org-contacts-filter name)
849 do (insert (org-contacts-vcard-format contact)))
851 (if to-buffer
852 (current-buffer)
853 (progn (save-buffer) (kill-buffer)))))
855 (defun org-contacts-show-map (&optional name)
856 "Show contacts on a map.
857 Requires google-maps-el."
858 (interactive)
859 (unless (fboundp 'google-maps-static-show)
860 (error "`org-contacts-show-map' requires `google-maps-el'"))
861 (google-maps-static-show
862 :markers
863 (loop
864 for contact in (org-contacts-filter name)
865 for addr = (cdr (assoc-string org-contacts-address-property (caddr contact)))
866 if addr
867 collect (cons (list addr) (list :label (string-to-char (car contact)))))))
869 (provide 'org-contacts)