Revert "ox-latex.el: Resurrect `org-latex-with-hyperref'"
[org-mode.git] / contrib / lisp / org-contacts.el
blobedc09feb8ff7955561d8839506824299e0ba5181
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 (if (catch 'nextfile
265 ;; if file doesn't exist and the user agrees to removing it
266 ;; from org-agendas-list, 'nextfile is thrown. Catch it here
267 ;; and skip processing the file.
269 ;; TODO: suppose that the user has set an org-contacts-files
270 ;; list that contains an element that doesn't exist in the
271 ;; file system: in that case, the org-agenda-files list could
272 ;; be updated (and saved to the customizations of the user) if
273 ;; it contained the same file even though the org-agenda-files
274 ;; list wasn't actually used. I don't think it is normal that
275 ;; org-contacts updates org-agenda-files in this case, but
276 ;; short of duplicating org-check-agenda-files and
277 ;; org-remove-files, I don't know how to avoid it.
279 ;; A side effect of the TODO is that the faulty
280 ;; org-contacts-files list never gets updated and thus the
281 ;; user is always queried about the missing files when
282 ;; org-contacts-db-need-update-p returns true.
283 (org-check-agenda-file file))
284 (message "Skipped %s removed from org-agenda-files list."
285 (abbreviate-file-name file))
286 (with-current-buffer (org-get-agenda-file-buffer file)
287 (unless (eq major-mode 'org-mode)
288 (error "File %s is not in `org-mode'" file))
289 (setf result
290 (append result
291 (org-scan-tags
292 'org-contacts-at-point
293 contacts-matcher
294 todo-only)))))
295 (progress-reporter-update progress-reporter (setq i (1+ i))))
296 (setf org-contacts-db result
297 org-contacts-last-update (current-time))
298 (progress-reporter-done progress-reporter)))
299 org-contacts-db))
301 (defun org-contacts-at-point (&optional pom)
302 "Return the contacts at point-or-marker POM or current position
303 if nil."
304 (setq pom (or pom (point)))
305 (org-with-point-at pom
306 (list (org-get-heading t) (set-marker (make-marker) pom) (org-entry-properties pom 'all))))
308 (defun org-contacts-filter (&optional name-match tags-match prop-match)
309 "Search for a contact matching any of NAME-MATCH, TAGS-MATCH, PROP-MATCH.
310 If all match values are nil, return all contacts.
312 The optional PROP-MATCH argument is a single (PROP . VALUE) cons
313 cell corresponding to the contact properties.
315 (if (and (null name-match)
316 (null prop-match)
317 (null tags-match))
318 (org-contacts-db)
319 (loop for contact in (org-contacts-db)
320 if (or
321 (and name-match
322 (org-string-match-p name-match
323 (first contact)))
324 (and prop-match
325 (org-find-if (lambda (prop)
326 (and (string= (car prop-match) (car prop))
327 (org-string-match-p (cdr prop-match) (cdr prop))))
328 (caddr contact)))
329 (and tags-match
330 (org-find-if (lambda (tag)
331 (org-string-match-p tags-match tag))
332 (org-split-string
333 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
334 collect contact)))
336 (when (not (fboundp 'completion-table-case-fold))
337 ;; That function is new in Emacs 24...
338 (defun completion-table-case-fold (table &optional dont-fold)
339 (lambda (string pred action)
340 (let ((completion-ignore-case (not dont-fold)))
341 (complete-with-action action table string pred)))))
343 (defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
344 "Custom implementation of `try-completion'.
345 This version works only with list and alist and it looks at all
346 prefixes rather than just the beginning of the string."
347 (loop with regexp = (concat "\\b" (regexp-quote to-match))
348 with ret = nil
349 with ret-start = nil
350 with ret-end = nil
352 for el in collection
353 for string = (if (listp el) (car el) el)
355 for start = (when (or (null predicate) (funcall predicate string))
356 (string-match regexp string))
358 if start
359 do (let ((end (match-end 0))
360 (len (length string)))
361 (if (= end len)
362 (return t)
363 (destructuring-bind (string start end)
364 (if (null ret)
365 (values string start end)
366 (org-contacts-common-substring
367 ret ret-start ret-end
368 string start end))
369 (setf ret string
370 ret-start start
371 ret-end end))))
373 finally (return
374 (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
376 (defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
377 "Compare the contents of two strings, using `compare-strings'.
379 This function works like `compare-strings' excepted that it
380 returns a cons.
381 - The CAR is the number of characters that match at the beginning.
382 - The CDR is T is the two strings are the same and NIL otherwise."
383 (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
384 (if (eq ret t)
385 (cons (or end1 (length s1)) t)
386 (cons (1- (abs ret)) nil))))
388 (defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
389 "Extract the common substring between S1 and S2.
391 This function extracts the common substring between S1 and S2 and
392 adjust the part that remains common.
394 START1 and END1 delimit the part in S1 that we know is common
395 between the two strings. This applies to START2 and END2 for S2.
397 This function returns a list whose contains:
398 - The common substring found.
399 - The new value of the start of the known inner substring.
400 - The new value of the end of the known inner substring."
401 ;; Given two strings:
402 ;; s1: "foo bar baz"
403 ;; s2: "fooo bar baz"
404 ;; and the inner substring is "bar"
405 ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
407 ;; To find the common substring we will compare two substrings:
408 ;; " oof" and " ooof" to find the beginning of the common substring.
409 ;; " baz" and " baz" to find the end of the common substring.
410 (let* ((len1 (length s1))
411 (start1 (or start1 0))
412 (end1 (or end1 len1))
414 (len2 (length s2))
415 (start2 (or start2 0))
416 (end2 (or end2 len2))
418 (new-start (car (org-contacts-compare-strings
419 (substring (org-reverse-string s1) (- len1 start1)) nil nil
420 (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
422 (new-end (+ end1 (car (org-contacts-compare-strings
423 (substring s1 end1) nil nil
424 (substring s2 end2) nil nil)))))
425 (list (substring s1 (- start1 new-start) new-end)
426 new-start
427 (+ new-start (- end1 start1)))))
429 (defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
430 "Custom version of `all-completions'.
431 This version works only with list and alist and it looks at all
432 prefixes rather than just the beginning of the string."
433 (loop with regexp = (concat "\\b" (regexp-quote to-match))
434 for el in collection
435 for string = (if (listp el) (car el) el)
436 for match? = (when (and (or (null predicate) (funcall predicate string)))
437 (string-match regexp string))
438 if match?
439 collect (progn
440 (let ((end (match-end 0)))
441 (org-no-properties string)
442 (when (< end (length string))
443 ;; Here we add a text property that will be used
444 ;; later to highlight the character right after
445 ;; the common part between each addresses.
446 ;; See `org-contacts-display-sort-function'.
447 (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
448 string)))
450 (defun org-contacts-make-collection-prefix (collection)
451 "Make a collection function from COLLECTION which will match on prefixes."
452 (lexical-let ((collection collection))
453 (lambda (string predicate flag)
454 (cond ((eq flag nil)
455 (org-contacts-try-completion-prefix string collection predicate))
456 ((eq flag t)
457 ;; `org-contacts-all-completions-prefix' has already been
458 ;; used to compute `all-completions'.
459 collection)
460 ((eq flag 'lambda)
461 (org-contacts-test-completion-prefix string collection predicate))
462 ((and (listp flag) (eq (car flag) 'boundaries))
463 (destructuring-bind (to-ignore &rest suffix)
464 flag
465 (org-contacts-boundaries-prefix string collection predicate suffix)))
466 ((eq flag 'metadata)
467 (org-contacts-metadata-prefix string collection predicate))
468 (t nil ; operation unsupported
469 )))))
471 (defun org-contacts-display-sort-function (completions)
472 "Sort function for contacts display."
473 (mapcar (lambda (string)
474 (loop with len = (1- (length string))
475 for i upfrom 0 to len
476 if (memq 'org-contacts-prefix
477 (text-properties-at i string))
478 do (set-text-properties
479 i (1+ i)
480 (list 'font-lock-face
481 (if (char-equal (aref string i)
482 (string-to-char " "))
483 ;; Spaces can't be bold.
484 'underline
485 'bold)) string)
486 else
487 do (set-text-properties i (1+ i) nil string)
488 finally (return string)))
489 completions))
491 (defun org-contacts-test-completion-prefix (string collection predicate)
492 ;; Prevents `org-find-if' from redefining `predicate' and going into
493 ;; an infinite loop.
494 (lexical-let ((predicate predicate))
495 (org-find-if (lambda (el)
496 (and (or (null predicate) (funcall predicate el))
497 (string= string el)))
498 collection)))
500 (defun org-contacts-boundaries-prefix (string collection predicate suffix)
501 (list* 'boundaries (completion-boundaries string collection predicate suffix)))
503 (defun org-contacts-metadata-prefix (string collection predicate)
504 '(metadata .
505 ((cycle-sort-function . org-contacts-display-sort-function)
506 (display-sort-function . org-contacts-display-sort-function))))
508 (defun org-contacts-complete-group (start end string)
509 "Complete text at START from a group.
511 A group FOO is composed of contacts with the tag FOO."
512 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
513 (group-completion-p (org-string-match-p
514 (concat "^" org-contacts-group-prefix) string)))
515 (when group-completion-p
516 (let ((completion-list
517 (all-completions
518 string
519 (mapcar (lambda (group)
520 (propertize (concat org-contacts-group-prefix group)
521 'org-contacts-group group))
522 (org-uniquify
523 (loop for contact in (org-contacts-filter)
524 nconc (org-split-string
525 (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
526 (list start end
527 (if (= (length completion-list) 1)
528 ;; We've found the correct group, returns the address
529 (lexical-let ((tag (get-text-property 0 'org-contacts-group
530 (car completion-list))))
531 (lambda (string pred &optional to-ignore)
532 (mapconcat 'identity
533 (loop for contact in (org-contacts-filter
535 tag)
536 ;; The contact name is always the car of the assoc-list
537 ;; returned by `org-contacts-filter'.
538 for contact-name = (car contact)
539 ;; Grab the first email of the contact
540 for email = (org-contacts-strip-link
541 (or (car (org-contacts-split-property
543 (cdr (assoc-string org-contacts-email-property
544 (caddr contact)))
545 ""))) ""))
546 ;; If the user has an email address, append USER <EMAIL>.
547 if email collect (org-contacts-format-email contact-name email))
548 ", ")))
549 ;; We haven't found the correct group
550 (completion-table-case-fold completion-list
551 (not org-contacts-completion-ignore-case))))))))
553 (defun org-contacts-complete-tags-props (start end string)
554 "Insert emails that match the tags expression.
556 For example: FOO-BAR will match entries tagged with FOO but not
557 with BAR.
559 See (org) Matching tags and properties for a complete
560 description."
561 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
562 (completion-p (org-string-match-p
563 (concat "^" org-contacts-tags-props-prefix) string)))
564 (when completion-p
565 (let ((result
566 (mapconcat
567 'identity
568 (loop for contact in (org-contacts-db)
569 for contact-name = (car contact)
570 for email = (org-contacts-strip-link (or (car (org-contacts-split-property
572 (cdr (assoc-string org-contacts-email-property
573 (caddr contact)))
574 ""))) ""))
575 for tags = (cdr (assoc "TAGS" (nth 2 contact)))
576 for tags-list = (if tags
577 (split-string (substring (cdr (assoc "TAGS" (nth 2 contact))) 1 -1) ":")
578 '())
579 for marker = (second contact)
580 if (with-current-buffer (marker-buffer marker)
581 (save-excursion
582 (goto-char marker)
583 (let (todo-only)
584 (eval (cdr (org-make-tags-matcher (subseq string 1)))))))
585 collect (org-contacts-format-email contact-name email))
586 ",")))
587 (when (not (string= "" result))
588 ;; return (start end function)
589 (lexical-let* ((to-return result))
590 (list start end
591 (lambda (string pred &optional to-ignore) to-return))))))))
593 (defun org-contacts-remove-ignored-property-values (ignore-list list)
594 "Remove all ignore-list's elements from list and you can use
595 regular expressions in the ignore list."
596 (org-remove-if (lambda (el)
597 (org-find-if (lambda (x)
598 (string-match-p x el))
599 ignore-list))
600 list))
602 (defun org-contacts-complete-name (start end string)
603 "Complete text at START with a user name and email."
604 (let* ((completion-ignore-case org-contacts-completion-ignore-case)
605 (completion-list
606 (loop for contact in (org-contacts-filter)
607 ;; The contact name is always the car of the assoc-list
608 ;; returned by `org-contacts-filter'.
609 for contact-name = (car contact)
611 ;; Build the list of the email addresses which has
612 ;; been expired
613 for ignore-list = (org-contacts-split-property
614 (or (cdr (assoc-string org-contacts-ignore-property
615 (caddr contact))) ""))
616 ;; Build the list of the user email addresses.
617 for email-list = (org-contacts-remove-ignored-property-values
618 ignore-list
619 (org-contacts-split-property
620 (or (cdr (assoc-string org-contacts-email-property
621 (caddr contact))) "")))
622 ;; If the user has email addresses…
623 if email-list
624 ;; … append a list of USER <EMAIL>.
625 nconc (loop for email in email-list
626 collect (org-contacts-format-email contact-name (org-contacts-strip-link email)))))
627 (completion-list (org-contacts-all-completions-prefix
628 string
629 (org-uniquify completion-list))))
630 (when completion-list
631 (list start end
632 (org-contacts-make-collection-prefix completion-list)))))
634 (defun org-contacts-message-complete-function (&optional start)
635 "Function used in `completion-at-point-functions' in `message-mode'."
636 ;; Avoid to complete in `post-command-hook'.
637 (when completion-in-region-mode
638 (remove-hook 'post-command-hook #'completion-in-region--postch))
639 (let ((mail-abbrev-mode-regexp
640 "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
641 (when (mail-abbrev-in-expansion-header-p)
642 (lexical-let*
643 ((end (point))
644 (start (or start
645 (save-excursion
646 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
647 (goto-char (match-end 0))
648 (point))))
649 (string (buffer-substring start end)))
650 (run-hook-with-args-until-success
651 'org-contacts-complete-functions start end string)))))
653 (defun org-contacts-gnus-get-name-email ()
654 "Get name and email address from Gnus message."
655 (if (gnus-alive-p)
656 (gnus-with-article-headers
657 (mail-extract-address-components
658 (or (mail-fetch-field "From") "")))))
660 (defun org-contacts-gnus-article-from-get-marker ()
661 "Return a marker for a contact based on From."
662 (let* ((address (org-contacts-gnus-get-name-email))
663 (name (car address))
664 (email (cadr address)))
665 (cadar (or (org-contacts-filter
668 (cons org-contacts-email-property (concat "\\b" (regexp-quote email) "\\b")))
669 (when name
670 (org-contacts-filter
671 (concat "^" name "$")))))))
673 (defun org-contacts-gnus-article-from-goto ()
674 "Go to contact in the From address of current Gnus message."
675 (interactive)
676 (let ((marker (org-contacts-gnus-article-from-get-marker)))
677 (when marker
678 (switch-to-buffer-other-window (marker-buffer marker))
679 (goto-char marker)
680 (when (eq major-mode 'org-mode)
681 (org-show-context 'agenda)
682 (save-excursion
683 (and (outline-next-heading)
684 ;; show the next heading
685 (org-flag-heading nil)))))))
687 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
688 (defun org-contacts-anniversaries (&optional field format)
689 "Compute FIELD anniversary for each contact, returning FORMAT.
690 Default FIELD value is \"BIRTHDAY\".
692 Format is a string matching the following format specification:
694 %h - Heading name
695 %l - Link to the heading
696 %y - Number of year
697 %Y - Number of year (ordinal)"
698 (let ((calendar-date-style 'american)
699 (entry ""))
700 (unless format (setq format org-contacts-birthday-format))
701 (loop for contact in (org-contacts-filter)
702 for anniv = (let ((anniv (cdr (assoc-string
703 (or field org-contacts-birthday-property)
704 (caddr contact)))))
705 (when anniv
706 (calendar-gregorian-from-absolute
707 (org-time-string-to-absolute anniv))))
708 ;; Use `diary-anniversary' to compute anniversary.
709 if (and anniv (apply 'diary-anniversary anniv))
710 collect (format-spec format
711 `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
712 (?h . ,(car contact))
713 (?y . ,(- (calendar-extract-year date)
714 (calendar-extract-year anniv)))
715 (?Y . ,(let ((years (- (calendar-extract-year date)
716 (calendar-extract-year anniv))))
717 (format "%d%s" years (diary-ordinal-suffix years)))))))))
719 (defun org-completing-read-date (prompt collection
720 &optional predicate require-match initial-input
721 hist def inherit-input-method)
722 "Like `completing-read' but reads a date.
723 Only PROMPT and DEF are really used."
724 (org-read-date nil nil nil prompt nil def))
726 (add-to-list 'org-property-set-functions-alist
727 `(,org-contacts-birthday-property . org-completing-read-date))
729 (defun org-contacts-template-name (&optional return-value)
730 "Try to return the contact name for a template.
731 If not found return RETURN-VALUE or something that would ask the user."
732 (or (car (org-contacts-gnus-get-name-email))
733 return-value
734 "%^{Name}"))
736 (defun org-contacts-template-email (&optional return-value)
737 "Try to return the contact email for a template.
738 If not found return RETURN-VALUE or something that would ask the user."
739 (or (cadr (org-contacts-gnus-get-name-email))
740 return-value
741 (concat "%^{" org-contacts-email-property "}p")))
743 (defun org-contacts-gnus-store-last-mail ()
744 "Store a link between mails and contacts.
746 This function should be called from `gnus-article-prepare-hook'."
747 (let ((marker (org-contacts-gnus-article-from-get-marker)))
748 (when marker
749 (with-current-buffer (marker-buffer marker)
750 (save-excursion
751 (goto-char marker)
752 (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
753 org-email-link-description-format))
754 (link (gnus-with-article-buffer (org-store-link nil))))
755 (org-set-property org-contacts-last-read-mail-property link)))))))
757 (defun org-contacts-icon-as-string ()
758 "Return the contact icon as a string."
759 (let ((image (org-contacts-get-icon)))
760 (concat
761 (propertize "-" 'display
762 (append
763 (if image
764 image
765 `'(space :width (,org-contacts-icon-size)))
766 '(:ascent center)))
767 " ")))
769 ;;;###autoload
770 (defun org-contacts (name)
771 "Create agenda view for contacts matching NAME."
772 (interactive (list (read-string "Name: ")))
773 (let ((org-agenda-files (org-contacts-files))
774 (org-agenda-skip-function
775 (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
776 (org-agenda-prefix-format (propertize
777 "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
778 'keymap org-contacts-keymap))
779 (org-agenda-overriding-header
780 (or org-agenda-overriding-header
781 (concat "List of contacts matching `" name "':"))))
782 (setq org-agenda-skip-regexp name)
783 (org-tags-view nil org-contacts-matcher)
784 (with-current-buffer org-agenda-buffer-name
785 (setq org-agenda-redo-command
786 (list 'org-contacts name)))))
788 (defun org-contacts-completing-read (prompt
789 &optional predicate
790 initial-input hist def inherit-input-method)
791 "Call `completing-read' with contacts name as collection."
792 (org-completing-read
793 prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
795 (defun org-contacts-format-name (name)
796 "Trim any local formatting to get a bare NAME."
797 ;; Remove radio targets characters
798 (replace-regexp-in-string org-radio-target-regexp "\\1" name))
800 (defun org-contacts-format-email (name email)
801 "Format an EMAIL address corresponding to NAME."
802 (unless email
803 (error "`email' cannot be nul"))
804 (if name
805 (concat (org-contacts-format-name name) " <" email ">")
806 email))
808 (defun org-contacts-check-mail-address (mail)
809 "Add MAIL address to contact at point if it does not have it."
810 (let ((mails (org-entry-get (point) org-contacts-email-property)))
811 (unless (member mail (split-string mails))
812 (when (yes-or-no-p
813 (format "Do you want to add this address to %s?" (org-get-heading t)))
814 (org-set-property org-contacts-email-property (concat mails " " mail))))))
816 (defun org-contacts-gnus-check-mail-address ()
817 "Check that contact has the current address recorded.
818 This function should be called from `gnus-article-prepare-hook'."
819 (let ((marker (org-contacts-gnus-article-from-get-marker)))
820 (when marker
821 (org-with-point-at marker
822 (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
824 (defun org-contacts-gnus-insinuate ()
825 "Add some hooks for Gnus user.
826 This adds `org-contacts-gnus-check-mail-address' and
827 `org-contacts-gnus-store-last-mail' to
828 `gnus-article-prepare-hook'. It also adds a binding on `;' in
829 `gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
830 (require 'gnus)
831 (require 'gnus-art)
832 (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
833 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
834 (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
836 (defun org-contacts-setup-completion-at-point ()
837 "Add `org-contacts-message-complete-function' as a new function
838 to complete the thing at point."
839 (add-to-list 'completion-at-point-functions
840 'org-contacts-message-complete-function))
842 (defun org-contacts-unload-hook ()
843 (remove-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
845 (when (and org-contacts-enable-completion
846 (boundp 'completion-at-point-functions))
847 (add-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
849 (defun org-contacts-wl-get-from-header-content ()
850 "Retrieve the content of the `From' header of an email.
851 Works from wl-summary-mode and mime-view-mode - that is while viewing email.
852 Depends on Wanderlust been loaded."
853 (with-current-buffer (org-capture-get :original-buffer)
854 (cond
855 ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
856 wl-summary-buffer-elmo-folder)
857 (elmo-message-field
858 wl-summary-buffer-elmo-folder
859 (wl-summary-message-number)
860 'from)))
861 ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
862 (prog1
863 (std11-fetch-field "From")
864 (widen))))))
866 (defun org-contacts-wl-get-name-email ()
867 "Get name and email address from Wanderlust email.
868 See `org-contacts-wl-get-from-header-content' for limitations."
869 (let ((from (org-contacts-wl-get-from-header-content)))
870 (when from
871 (list (wl-address-header-extract-realname from)
872 (wl-address-header-extract-address from)))))
874 (defun org-contacts-template-wl-name (&optional return-value)
875 "Try to return the contact name for a template from wl.
876 If not found, return RETURN-VALUE or something that would ask the
877 user."
878 (or (car (org-contacts-wl-get-name-email))
879 return-value
880 "%^{Name}"))
882 (defun org-contacts-template-wl-email (&optional return-value)
883 "Try to return the contact email for a template from Wanderlust.
884 If not found return RETURN-VALUE or something that would ask the user."
885 (or (cadr (org-contacts-wl-get-name-email))
886 return-value
887 (concat "%^{" org-contacts-email-property "}p")))
889 (defun org-contacts-view-send-email (&optional ask)
890 "Send email to the contact at point.
891 If ASK is set, ask for the email address even if there's only one
892 address."
893 (interactive "P")
894 (let ((marker (org-get-at-bol 'org-hd-marker)))
895 (org-with-point-at marker
896 (let ((emails (org-entry-get (point) org-contacts-email-property)))
897 (if emails
898 (let ((email-list (org-contacts-split-property emails)))
899 (if (and (= (length email-list) 1) (not ask))
900 (compose-mail (org-contacts-format-email
901 (org-get-heading t) emails))
902 (let ((email (completing-read "Send mail to which address: " email-list)))
903 (setq email (org-contacts-strip-link email))
904 (org-contacts-check-mail-address email)
905 (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
906 (error (format "This contact has no mail address set (no %s property)"
907 org-contacts-email-property)))))))
909 (defun org-contacts-get-icon (&optional pom)
910 "Get icon for contact at POM."
911 (setq pom (or pom (point)))
912 (catch 'icon
913 ;; Use `org-contacts-icon-property'
914 (let ((image-data (org-entry-get pom org-contacts-icon-property)))
915 (when image-data
916 (throw 'icon
917 (if (fboundp 'gnus-rescale-image)
918 (gnus-rescale-image (create-image image-data)
919 (cons org-contacts-icon-size org-contacts-icon-size))
920 (create-image image-data)))))
921 ;; Next, try Gravatar
922 (when org-contacts-icon-use-gravatar
923 (let* ((gravatar-size org-contacts-icon-size)
924 (email-list (org-entry-get pom org-contacts-email-property))
925 (gravatar
926 (when email-list
927 (loop for email in (org-contacts-split-property email-list)
928 for gravatar = (gravatar-retrieve-synchronously (org-contacts-strip-link email))
929 if (and gravatar
930 (not (eq gravatar 'error)))
931 return gravatar))))
932 (when gravatar (throw 'icon gravatar))))))
934 (defun org-contacts-irc-buffer (&optional pom)
935 "Get the IRC buffer associated with the entry at POM."
936 (setq pom (or pom (point)))
937 (let ((nick (org-entry-get pom org-contacts-nickname-property)))
938 (when nick
939 (let ((buffer (get-buffer nick)))
940 (when buffer
941 (with-current-buffer buffer
942 (when (eq major-mode 'erc-mode)
943 buffer)))))))
945 (defun org-contacts-irc-number-of-unread-messages (&optional pom)
946 "Return the number of unread messages for contact at POM."
947 (when (boundp 'erc-modified-channels-alist)
948 (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
949 (if number
950 (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
951 (make-string 21 ? )))))
953 (defun org-contacts-view-switch-to-irc-buffer ()
954 "Switch to the IRC buffer of the current contact if it has one."
955 (interactive)
956 (let ((marker (org-get-at-bol 'org-hd-marker)))
957 (org-with-point-at marker
958 (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
960 (defun org-contacts-completing-read-nickname (prompt collection
961 &optional predicate require-match initial-input
962 hist def inherit-input-method)
963 "Like `completing-read' but reads a nickname."
964 (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
965 initial-input hist def inherit-input-method))
967 (defun erc-nicknames-list ()
968 "Return all nicknames of all ERC buffers."
969 (loop for buffer in (erc-buffer-list)
970 nconc (with-current-buffer buffer
971 (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
972 collect (elt user-entry 1)))))
974 (add-to-list 'org-property-set-functions-alist
975 `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
977 (defun org-contacts-vcard-escape (str)
978 "Escape ; , and \n in STR for the VCard format."
979 ;; Thanks to this library for the regexp:
980 ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
981 (when str
982 (replace-regexp-in-string
983 "\n" "\\\\n"
984 (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
986 (defun org-contacts-vcard-encode-name (name)
987 "Try to encode NAME as VCard's N property.
988 The N property expects
990 FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
992 Org-contacts does not specify how to encode the name. So we try
993 to do our best."
994 (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
996 (defun org-contacts-vcard-format (contact)
997 "Formats CONTACT in VCard 3.0 format."
998 (let* ((properties (caddr contact))
999 (name (org-contacts-vcard-escape (car contact)))
1000 (n (org-contacts-vcard-encode-name name))
1001 (email (cdr (assoc-string org-contacts-email-property properties)))
1002 (tel (cdr (assoc-string org-contacts-tel-property properties)))
1003 (ignore-list (cdr (assoc-string org-contacts-ignore-property properties)))
1004 (ignore-list (when ignore-list
1005 (org-contacts-split-property ignore-list)))
1006 (note (cdr (assoc-string org-contacts-note-property properties)))
1007 (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
1008 (addr (cdr (assoc-string org-contacts-address-property properties)))
1009 (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
1010 (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name))
1011 emails-list result phones-list)
1012 (concat head
1013 (when email (progn
1014 (setq emails-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property email)))
1015 (setq result "")
1016 (while emails-list
1017 (setq result (concat result "EMAIL:" (org-contacts-strip-link (car emails-list)) "\n"))
1018 (setq emails-list (cdr emails-list)))
1019 result))
1020 (when addr
1021 (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
1022 (when tel (progn
1023 (setq phones-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property tel)))
1024 (setq result "")
1025 (while phones-list
1026 (setq result (concat result "TEL:" (org-link-unescape (org-contacts-strip-link (car phones-list))) "\n"))
1027 (setq phones-list (cdr phones-list)))
1028 result))
1029 (when bday
1030 (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
1031 (format "BDAY:%04d-%02d-%02d\n"
1032 (calendar-extract-year cal-bday)
1033 (calendar-extract-month cal-bday)
1034 (calendar-extract-day cal-bday))))
1035 (when nick (format "NICKNAME:%s\n" nick))
1036 (when note (format "NOTE:%s\n" note))
1037 "END:VCARD\n\n")))
1039 (defun org-contacts-export-as-vcard (&optional name file to-buffer)
1040 "Export org contacts to V-Card 3.0.
1042 By default, all contacts are exported to `org-contacts-vcard-file'.
1044 When NAME is \\[universal-argument], prompts for a contact name.
1046 When NAME is \\[universal-argument] \\[universal-argument],
1047 prompts for a contact name and a file name where to export.
1049 When NAME is \\[universal-argument] \\[universal-argument]
1050 \\[universal-argument], prompts for a contact name and a buffer where to export.
1052 If the function is not called interactively, all parameters are
1053 passed to `org-contacts-export-as-vcard-internal'."
1054 (interactive "P")
1055 (when (called-interactively-p 'any)
1056 (cl-psetf name
1057 (when name
1058 (read-string "Contact name: "
1059 (first (org-contacts-at-point))))
1060 file
1061 (when (equal name '(16))
1062 (read-file-name "File: " nil org-contacts-vcard-file))
1063 to-buffer
1064 (when (equal name '(64))
1065 (read-buffer "Buffer: "))))
1066 (org-contacts-export-as-vcard-internal name file to-buffer))
1068 (defun org-contacts-export-as-vcard-internal (&optional name file to-buffer)
1069 "Export all contacts matching NAME as VCard 3.0.
1070 If TO-BUFFER is nil, the content is written to FILE or
1071 `org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
1072 is created and the VCard is written into that buffer."
1073 (let* ((filename (or file org-contacts-vcard-file))
1074 (buffer (if to-buffer
1075 (get-buffer-create to-buffer)
1076 (find-file-noselect filename))))
1077 (message "Exporting...")
1078 (set-buffer buffer)
1079 (let ((inhibit-read-only t)) (erase-buffer))
1080 (fundamental-mode)
1081 (when (fboundp 'set-buffer-file-coding-system)
1082 (set-buffer-file-coding-system coding-system-for-write))
1083 (loop for contact in (org-contacts-filter name)
1084 do (insert (org-contacts-vcard-format contact)))
1085 (if to-buffer
1086 (current-buffer)
1087 (progn (save-buffer) (kill-buffer)))))
1089 (defun org-contacts-show-map (&optional name)
1090 "Show contacts on a map.
1091 Requires google-maps-el."
1092 (interactive)
1093 (unless (fboundp 'google-maps-static-show)
1094 (error "`org-contacts-show-map' requires `google-maps-el'"))
1095 (google-maps-static-show
1096 :markers
1097 (loop
1098 for contact in (org-contacts-filter name)
1099 for addr = (cdr (assoc-string org-contacts-address-property (caddr contact)))
1100 if addr
1101 collect (cons (list addr) (list :label (string-to-char (car contact)))))))
1103 (defun org-contacts-strip-link (link)
1104 "Remove brackets, description, link type and colon from an org
1105 link string and return the pure link target."
1106 (let (startpos colonpos endpos)
1107 (setq startpos (string-match (regexp-opt '("[[tel:" "[[mailto:")) link))
1108 (if startpos
1109 (progn
1110 (setq colonpos (string-match ":" link))
1111 (setq endpos (string-match "\\]" link))
1112 (if endpos (substring link (1+ colonpos) endpos) link))
1113 (progn
1114 (setq startpos (string-match "mailto:" link))
1115 (setq colonpos (string-match ":" link))
1116 (if startpos (substring link (1+ colonpos)) link)))))
1118 (defun org-contacts-split-property (string &optional separators omit-nulls)
1119 "Custom version of `split-string'.
1120 Split a property STRING into sub-strings bounded by matches
1121 for SEPARATORS but keep Org links intact.
1123 The beginning and end of STRING, and each match for SEPARATORS, are
1124 splitting points. The substrings matching SEPARATORS are removed, and
1125 the substrings between the splitting points are collected as a list,
1126 which is returned.
1128 If SEPARATORS is non-nil, it should be a regular expression
1129 matching text which separates, but is not part of, the
1130 substrings. If nil it defaults to `org-contacts-property-values-separators',
1131 normally \"[,; \f\t\n\r\v]+\", and OMIT-NULLS is forced to t.
1133 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
1134 that for the default value of SEPARATORS leading and trailing whitespace
1135 are effectively trimmed). If nil, all zero-length substrings are retained."
1136 (let* ((omit-nulls (if separators omit-nulls t))
1137 (rexp (or separators org-contacts-property-values-separators))
1138 (inputlist (split-string string rexp omit-nulls))
1139 (linkstring "")
1140 (bufferstring "")
1141 (proplist (list "")))
1142 (while inputlist
1143 (setq bufferstring (pop inputlist))
1144 (if (string-match "\\[\\[" bufferstring)
1145 (progn
1146 (setq linkstring (concat bufferstring " "))
1147 (while (not (string-match "\\]\\]" bufferstring))
1148 (setq bufferstring (pop inputlist))
1149 (setq linkstring (concat linkstring bufferstring " ")))
1150 (setq proplist (cons (org-trim linkstring) proplist)))
1151 (setq proplist (cons bufferstring proplist))))
1152 (cdr (reverse proplist))))
1154 (provide 'org-contacts)
1156 ;;; org-contacts.el ends here