org-contacts.el 38 KB

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