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