org-contacts.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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)
  196. "Search for a contact matching NAME-MATCH and TAGS-MATCH.
  197. If both match values are nil, return all contacts."
  198. (if (and (null name-match)
  199. (null tags-match))
  200. (org-contacts-db)
  201. (loop for contact in (org-contacts-db)
  202. if (or
  203. (and name-match
  204. (org-string-match-p name-match
  205. (first contact)))
  206. (and tags-match
  207. (org-find-if (lambda (tag)
  208. (org-string-match-p tags-match tag))
  209. (org-split-string
  210. (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
  211. collect contact)))
  212. (when (not (fboundp 'completion-table-case-fold))
  213. ;; That function is new in Emacs 24...
  214. (defun completion-table-case-fold (table &optional dont-fold)
  215. (lambda (string pred action)
  216. (let ((completion-ignore-case (not dont-fold)))
  217. (complete-with-action action table string pred)))))
  218. (defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
  219. "Custom implementation of `try-completion'.
  220. This version works only with list and alist and it looks at all
  221. prefixes rather than just the beginning of the string."
  222. (loop with regexp = (concat "\\b" (regexp-quote to-match))
  223. with ret = nil
  224. with ret-start = nil
  225. with ret-end = nil
  226. for el in collection
  227. for string = (if (listp el) (car el) el)
  228. for start = (when (or (null predicate) (funcall predicate string))
  229. (string-match regexp string))
  230. if start
  231. do (let ((end (match-end 0))
  232. (len (length string)))
  233. (if (= end len)
  234. (return t)
  235. (destructuring-bind (string start end)
  236. (if (null ret)
  237. (values string start end)
  238. (org-contacts-common-substring
  239. ret ret-start ret-end
  240. string start end))
  241. (setf ret string
  242. ret-start start
  243. ret-end end))))
  244. finally (return
  245. (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
  246. (defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
  247. "Compare the contents of two strings, using `compare-strings'.
  248. This function works like `compare-strings' excepted that it
  249. returns a cons.
  250. - The CAR is the number of characters that match at the beginning.
  251. - The CDR is T is the two strings are the same and NIL otherwise."
  252. (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
  253. (if (eq ret t)
  254. (cons (or end1 (length s1)) t)
  255. (cons (1- (abs ret)) nil))))
  256. (defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
  257. "Extract the common substring between S1 and S2.
  258. This function extracts the common substring between S1 and S2 and
  259. adjust the part that remains common.
  260. START1 and END1 delimit the part in S1 that we know is common
  261. between the two strings. This applies to START2 and END2 for S2.
  262. This function returns a list whose contains:
  263. - The common substring found.
  264. - The new value of the start of the known inner substring.
  265. - The new value of the end of the known inner substring."
  266. ;; Given two strings:
  267. ;; s1: "foo bar baz"
  268. ;; s2: "fooo bar baz"
  269. ;; and the inner substring is "bar"
  270. ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
  271. ;;
  272. ;; To find the common substring we will compare two substrings:
  273. ;; " oof" and " ooof" to find the beginning of the common substring.
  274. ;; " baz" and " baz" to find the end of the common substring.
  275. (let* ((len1 (length s1))
  276. (start1 (or start1 0))
  277. (end1 (or end1 len1))
  278. (len2 (length s2))
  279. (start2 (or start2 0))
  280. (end2 (or end2 len2))
  281. (new-start (car (org-contacts-compare-strings
  282. (substring (org-reverse-string s1) (- len1 start1)) nil nil
  283. (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
  284. (new-end (+ end1 (car (org-contacts-compare-strings
  285. (substring s1 end1) nil nil
  286. (substring s2 end2) nil nil)))))
  287. (list (substring s1 (- start1 new-start) new-end)
  288. new-start
  289. (+ new-start (- end1 start1)))))
  290. (defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
  291. "Custom version of `all-completions'.
  292. This version works only with list and alist and it looks at all
  293. prefixes rather than just the beginning of the string."
  294. (loop with regexp = (concat "\\b" (regexp-quote to-match))
  295. for el in collection
  296. for string = (if (listp el) (car el) el)
  297. for match? = (when (and (or (null predicate) (funcall predicate string)))
  298. (string-match regexp string))
  299. if match?
  300. collect (progn
  301. (let ((end (match-end 0)))
  302. (org-no-properties string)
  303. (when (< end (length string))
  304. ;; Here we add a text property that will be used
  305. ;; later to highlight the character right after
  306. ;; the common part between each addresses.
  307. ;; See `org-contacts-display-sort-function'.
  308. (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
  309. string)))
  310. (defun org-contacts-make-collection-prefix (collection)
  311. "Make a collection function from COLLECTION which will match on prefixes."
  312. (lexical-let ((collection collection))
  313. (lambda (string predicate flag)
  314. (cond ((eq flag nil)
  315. (org-contacts-try-completion-prefix string collection predicate))
  316. ((eq flag t)
  317. ;; `org-contacts-all-completions-prefix' has already been
  318. ;; used to compute `all-completions'.
  319. collection)
  320. ((eq flag 'lambda)
  321. (org-contacts-test-completion-prefix string collection predicate))
  322. ((and (listp flag) (eq (car flag) 'boundaries))
  323. (destructuring-bind (to-ignore &rest suffix)
  324. flag
  325. (org-contacts-boundaries-prefix string collection predicate suffix)))
  326. ((eq flag 'metadata)
  327. (org-contacts-metadata-prefix string collection predicate))
  328. (t nil ; operation unsupported
  329. )))))
  330. (defun org-contacts-display-sort-function (completions)
  331. "Sort function for contacts display."
  332. (mapcar (lambda (string)
  333. (loop with len = (1- (length string))
  334. for i upfrom 0 to len
  335. if (memq 'org-contacts-prefix
  336. (text-properties-at i string))
  337. do (set-text-properties
  338. i (1+ i)
  339. (list 'font-lock-face
  340. (if (char-equal (aref string i)
  341. (string-to-char " "))
  342. ;; Spaces can't be bold.
  343. 'underline
  344. 'bold)) string)
  345. else
  346. do (set-text-properties i (1+ i) nil string)
  347. finally (return string)))
  348. completions))
  349. (defun org-contacts-test-completion-prefix (string collection predicate)
  350. ;; Prevents `org-find-if' from redefining `predicate' and going into
  351. ;; an infinite loop.
  352. (lexical-let ((predicate predicate))
  353. (org-find-if (lambda (el)
  354. (and (or (null predicate) (funcall predicate el))
  355. (string= string el)))
  356. collection)))
  357. (defun org-contacts-boundaries-prefix (string collection predicate suffix)
  358. (list* 'boundaries (completion-boundaries string collection predicate suffix)))
  359. (defun org-contacts-metadata-prefix (string collection predicate)
  360. '(metadata .
  361. ((display-sort-function . org-contacts-display-sort-function))))
  362. (defun org-contacts-complete-group (start end string)
  363. "Complete text at START from a group.
  364. A group FOO is composed of contacts with the tag FOO."
  365. (let* ((completion-ignore-case org-contacts-completion-ignore-case)
  366. (group-completion-p (org-string-match-p
  367. (concat "^" org-contacts-group-prefix) string)))
  368. (when group-completion-p
  369. (let ((completion-list
  370. (all-completions
  371. string
  372. (mapcar (lambda (group)
  373. (propertize (concat org-contacts-group-prefix group)
  374. 'org-contacts-group group))
  375. (org-uniquify
  376. (loop for contact in (org-contacts-filter)
  377. nconc (org-split-string
  378. (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
  379. (list start end
  380. (if (= (length completion-list) 1)
  381. ;; We've found the correct group, returns the address
  382. (lexical-let ((tag (get-text-property 0 'org-contacts-group
  383. (car completion-list))))
  384. (lambda (string pred &optional to-ignore)
  385. (mapconcat 'identity
  386. (loop for contact in (org-contacts-filter
  387. nil
  388. tag)
  389. ;; The contact name is always the car of the assoc-list
  390. ;; returned by `org-contacts-filter'.
  391. for contact-name = (car contact)
  392. ;; Grab the first email of the contact
  393. for email = (org-contacts-strip-link (car (org-contacts-split-property
  394. (or
  395. (cdr (assoc-string org-contacts-email-property
  396. (caddr contact)))
  397. ""))))
  398. ;; If the user has an email address, append USER <EMAIL>.
  399. if email collect (org-contacts-format-email contact-name email))
  400. ", ")))
  401. ;; We haven't found the correct group
  402. (completion-table-case-fold completion-list
  403. (not org-contacts-completion-ignore-case))))))))
  404. (defun org-contacts-complete-name (start end string)
  405. "Complete text at START with a user name and email."
  406. (let* ((completion-ignore-case org-contacts-completion-ignore-case)
  407. (completion-list
  408. (loop for contact in (org-contacts-filter)
  409. ;; The contact name is always the car of the assoc-list
  410. ;; returned by `org-contacts-filter'.
  411. for contact-name = (car contact)
  412. ;; Build the list of the user email addresses.
  413. for email-list = (org-contacts-split-property (or
  414. (cdr (assoc-string org-contacts-email-property
  415. (caddr contact))) ""))
  416. ;; If the user has email addresses…
  417. if email-list
  418. ;; … append a list of USER <EMAIL>.
  419. nconc (loop for email in email-list
  420. collect (org-contacts-format-email contact-name (org-contacts-strip-link email)))))
  421. (completion-list (org-contacts-all-completions-prefix
  422. string
  423. (org-uniquify completion-list))))
  424. (when completion-list
  425. (list start end
  426. (org-contacts-make-collection-prefix completion-list)))))
  427. (defun org-contacts-message-complete-function (&optional start)
  428. "Function used in `completion-at-point-functions' in `message-mode'."
  429. ;; Avoid to complete in `post-command-hook'.
  430. (when completion-in-region-mode
  431. (remove-hook 'post-command-hook #'completion-in-region--postch))
  432. (let ((mail-abbrev-mode-regexp
  433. "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
  434. (when (mail-abbrev-in-expansion-header-p)
  435. (lexical-let*
  436. ((end (point))
  437. (start (or start
  438. (save-excursion
  439. (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
  440. (goto-char (match-end 0))
  441. (point))))
  442. (string (buffer-substring start end)))
  443. (or (org-contacts-complete-group start end string)
  444. (org-contacts-complete-name start end string))))))
  445. (defun org-contacts-gnus-get-name-email ()
  446. "Get name and email address from Gnus message."
  447. (if (gnus-alive-p)
  448. (gnus-with-article-headers
  449. (mail-extract-address-components
  450. (or (mail-fetch-field "From") "")))))
  451. (defun org-contacts-gnus-article-from-get-marker ()
  452. "Return a marker for a contact based on From."
  453. (let* ((address (org-contacts-gnus-get-name-email))
  454. (name (car address))
  455. (email (cadr address)))
  456. (cadar (or (org-contacts-filter
  457. nil
  458. (concat org-contacts-email-property "={\\b" (regexp-quote email) "\\b}"))
  459. (when name
  460. (org-contacts-filter
  461. (concat "^" name "$")))))))
  462. (defun org-contacts-gnus-article-from-goto ()
  463. "Go to contact in the From address of current Gnus message."
  464. (interactive)
  465. (let ((marker (org-contacts-gnus-article-from-get-marker)))
  466. (when marker
  467. (switch-to-buffer-other-window (marker-buffer marker))
  468. (goto-char marker)
  469. (when (eq major-mode 'org-mode)
  470. (org-show-context 'agenda)
  471. (save-excursion
  472. (and (outline-next-heading)
  473. ;; show the next heading
  474. (org-flag-heading nil)))))))
  475. (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
  476. (defun org-contacts-anniversaries (&optional field format)
  477. "Compute FIELD anniversary for each contact, returning FORMAT.
  478. Default FIELD value is \"BIRTHDAY\".
  479. Format is a string matching the following format specification:
  480. %h - Heading name
  481. %l - Link to the heading
  482. %y - Number of year
  483. %Y - Number of year (ordinal)"
  484. (let ((calendar-date-style 'american)
  485. (entry ""))
  486. (unless format (setq format org-contacts-birthday-format))
  487. (loop for contact in (org-contacts-filter)
  488. for anniv = (let ((anniv (cdr (assoc-string
  489. (or field org-contacts-birthday-property)
  490. (caddr contact)))))
  491. (when anniv
  492. (calendar-gregorian-from-absolute
  493. (org-time-string-to-absolute anniv))))
  494. ;; Use `diary-anniversary' to compute anniversary.
  495. if (and anniv (apply 'diary-anniversary anniv))
  496. collect (format-spec format
  497. `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
  498. (?h . ,(car contact))
  499. (?y . ,(- (calendar-extract-year date)
  500. (calendar-extract-year anniv)))
  501. (?Y . ,(let ((years (- (calendar-extract-year date)
  502. (calendar-extract-year anniv))))
  503. (format "%d%s" years (diary-ordinal-suffix years)))))))))
  504. (defun org-completing-read-date (prompt collection
  505. &optional predicate require-match initial-input
  506. hist def inherit-input-method)
  507. "Like `completing-read' but reads a date.
  508. Only PROMPT and DEF are really used."
  509. (org-read-date nil nil nil prompt nil def))
  510. (add-to-list 'org-property-set-functions-alist
  511. `(,org-contacts-birthday-property . org-completing-read-date))
  512. (defun org-contacts-template-name (&optional return-value)
  513. "Try to return the contact name for a template.
  514. If not found return RETURN-VALUE or something that would ask the user."
  515. (or (car (org-contacts-gnus-get-name-email))
  516. return-value
  517. "%^{Name}"))
  518. (defun org-contacts-template-email (&optional return-value)
  519. "Try to return the contact email for a template.
  520. If not found return RETURN-VALUE or something that would ask the user."
  521. (or (cadr (org-contacts-gnus-get-name-email))
  522. return-value
  523. (concat "%^{" org-contacts-email-property "}p")))
  524. (defun org-contacts-gnus-store-last-mail ()
  525. "Store a link between mails and contacts.
  526. This function should be called from `gnus-article-prepare-hook'."
  527. (let ((marker (org-contacts-gnus-article-from-get-marker)))
  528. (when marker
  529. (with-current-buffer (marker-buffer marker)
  530. (save-excursion
  531. (goto-char marker)
  532. (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
  533. org-email-link-description-format))
  534. (link (gnus-with-article-buffer (org-store-link nil))))
  535. (org-set-property org-contacts-last-read-mail-property link)))))))
  536. (defun org-contacts-icon-as-string ()
  537. "Return the contact icon as a string."
  538. (let ((image (org-contacts-get-icon)))
  539. (concat
  540. (propertize "-" 'display
  541. (append
  542. (if image
  543. image
  544. `'(space :width (,org-contacts-icon-size)))
  545. '(:ascent center)))
  546. " ")))
  547. ;;;###autoload
  548. (defun org-contacts (name)
  549. "Create agenda view for contacts matching NAME."
  550. (interactive (list (read-string "Name: ")))
  551. (let ((org-agenda-files (org-contacts-files))
  552. (org-agenda-skip-function
  553. (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
  554. (org-agenda-prefix-format (propertize
  555. "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
  556. 'keymap org-contacts-keymap))
  557. (org-agenda-overriding-header
  558. (or org-agenda-overriding-header
  559. (concat "List of contacts matching `" name "':"))))
  560. (setq org-agenda-skip-regexp name)
  561. (org-tags-view nil org-contacts-matcher)
  562. (with-current-buffer org-agenda-buffer-name
  563. (setq org-agenda-redo-command
  564. (list 'org-contacts name)))))
  565. (defun org-contacts-completing-read (prompt
  566. &optional predicate
  567. initial-input hist def inherit-input-method)
  568. "Call `completing-read' with contacts name as collection."
  569. (org-completing-read
  570. prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
  571. (defun org-contacts-format-name (name)
  572. "Trim any local formatting to get a bare NAME."
  573. ;; Remove radio targets characters
  574. (replace-regexp-in-string org-radio-target-regexp "\\1" name))
  575. (defun org-contacts-format-email (name email)
  576. "Format an EMAIL address corresponding to NAME."
  577. (unless email
  578. (error "`email' cannot be nul"))
  579. (if name
  580. (concat (org-contacts-format-name name) " <" email ">")
  581. email))
  582. (defun org-contacts-check-mail-address (mail)
  583. "Add MAIL address to contact at point if it does not have it."
  584. (let ((mails (org-entry-get (point) org-contacts-email-property)))
  585. (unless (member mail (split-string mails))
  586. (when (yes-or-no-p
  587. (format "Do you want to add this address to %s?" (org-get-heading t)))
  588. (org-set-property org-contacts-email-property (concat mails " " mail))))))
  589. (defun org-contacts-gnus-check-mail-address ()
  590. "Check that contact has the current address recorded.
  591. This function should be called from `gnus-article-prepare-hook'."
  592. (let ((marker (org-contacts-gnus-article-from-get-marker)))
  593. (when marker
  594. (org-with-point-at marker
  595. (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
  596. (defun org-contacts-gnus-insinuate ()
  597. "Add some hooks for Gnus user.
  598. This adds `org-contacts-gnus-check-mail-address' and
  599. `org-contacts-gnus-store-last-mail' to
  600. `gnus-article-prepare-hook'. It also adds a binding on `;' in
  601. `gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
  602. (require 'gnus)
  603. (require 'gnus-art)
  604. (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
  605. (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
  606. (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
  607. (when (and org-contacts-enable-completion
  608. (boundp 'completion-at-point-functions))
  609. (add-hook 'message-mode-hook
  610. (lambda ()
  611. (add-to-list 'completion-at-point-functions
  612. 'org-contacts-message-complete-function))))
  613. (defun org-contacts-wl-get-from-header-content ()
  614. "Retrieve the content of the `From' header of an email.
  615. Works from wl-summary-mode and mime-view-mode - that is while viewing email.
  616. Depends on Wanderlust been loaded."
  617. (with-current-buffer (org-capture-get :original-buffer)
  618. (cond
  619. ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
  620. wl-summary-buffer-elmo-folder)
  621. (elmo-message-field
  622. wl-summary-buffer-elmo-folder
  623. (wl-summary-message-number)
  624. 'from)))
  625. ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
  626. (prog1
  627. (std11-fetch-field "From")
  628. (widen))))))
  629. (defun org-contacts-wl-get-name-email ()
  630. "Get name and email address from Wanderlust email.
  631. See `org-contacts-wl-get-from-header-content' for limitations."
  632. (let ((from (org-contacts-wl-get-from-header-content)))
  633. (when from
  634. (list (wl-address-header-extract-realname from)
  635. (wl-address-header-extract-address from)))))
  636. (defun org-contacts-template-wl-name (&optional return-value)
  637. "Try to return the contact name for a template from wl.
  638. If not found, return RETURN-VALUE or something that would ask the
  639. user."
  640. (or (car (org-contacts-wl-get-name-email))
  641. return-value
  642. "%^{Name}"))
  643. (defun org-contacts-template-wl-email (&optional return-value)
  644. "Try to return the contact email for a template from Wanderlust.
  645. If not found return RETURN-VALUE or something that would ask the user."
  646. (or (cadr (org-contacts-wl-get-name-email))
  647. return-value
  648. (concat "%^{" org-contacts-email-property "}p")))
  649. (defun org-contacts-view-send-email (&optional ask)
  650. "Send email to the contact at point.
  651. If ASK is set, ask for the email address even if there's only one
  652. address."
  653. (interactive "P")
  654. (let ((marker (org-get-at-bol 'org-hd-marker)))
  655. (org-with-point-at marker
  656. (let ((emails (org-entry-get (point) org-contacts-email-property)))
  657. (if emails
  658. (let ((email-list (org-contacts-split-property emails)))
  659. (if (and (= (length email-list) 1) (not ask))
  660. (compose-mail (org-contacts-format-email
  661. (org-get-heading t) emails))
  662. (let ((email (completing-read "Send mail to which address: " email-list)))
  663. (setq email (org-contacts-strip-link email))
  664. (org-contacts-check-mail-address email)
  665. (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
  666. (error (format "This contact has no mail address set (no %s property)."
  667. org-contacts-email-property)))))))
  668. (defun org-contacts-get-icon (&optional pom)
  669. "Get icon for contact at POM."
  670. (setq pom (or pom (point)))
  671. (catch 'icon
  672. ;; Use `org-contacts-icon-property'
  673. (let ((image-data (org-entry-get pom org-contacts-icon-property)))
  674. (when image-data
  675. (throw 'icon
  676. (if (fboundp 'gnus-rescale-image)
  677. (gnus-rescale-image (create-image image-data)
  678. (cons org-contacts-icon-size org-contacts-icon-size))
  679. (create-image image-data)))))
  680. ;; Next, try Gravatar
  681. (when org-contacts-icon-use-gravatar
  682. (let* ((gravatar-size org-contacts-icon-size)
  683. (email-list (org-entry-get pom org-contacts-email-property))
  684. (gravatar
  685. (when email-list
  686. (loop for email in (org-contacts-split-property email-list)
  687. for gravatar = (gravatar-retrieve-synchronously (org-contacts-strip-link email))
  688. if (and gravatar
  689. (not (eq gravatar 'error)))
  690. return gravatar))))
  691. (when gravatar (throw 'icon gravatar))))))
  692. (defun org-contacts-irc-buffer (&optional pom)
  693. "Get the IRC buffer associated with the entry at POM."
  694. (setq pom (or pom (point)))
  695. (let ((nick (org-entry-get pom org-contacts-nickname-property)))
  696. (when nick
  697. (let ((buffer (get-buffer nick)))
  698. (when buffer
  699. (with-current-buffer buffer
  700. (when (eq major-mode 'erc-mode)
  701. buffer)))))))
  702. (defun org-contacts-irc-number-of-unread-messages (&optional pom)
  703. "Return the number of unread messages for contact at POM."
  704. (when (boundp 'erc-modified-channels-alist)
  705. (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
  706. (if number
  707. (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
  708. (make-string 21 ? )))))
  709. (defun org-contacts-view-switch-to-irc-buffer ()
  710. "Switch to the IRC buffer of the current contact if it has one."
  711. (interactive)
  712. (let ((marker (org-get-at-bol 'org-hd-marker)))
  713. (org-with-point-at marker
  714. (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
  715. (defun org-contacts-completing-read-nickname (prompt collection
  716. &optional predicate require-match initial-input
  717. hist def inherit-input-method)
  718. "Like `completing-read' but reads a nickname."
  719. (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
  720. initial-input hist def inherit-input-method))
  721. (defun erc-nicknames-list ()
  722. "Return all nicknames of all ERC buffers."
  723. (loop for buffer in (erc-buffer-list)
  724. nconc (with-current-buffer buffer
  725. (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
  726. collect (elt user-entry 1)))))
  727. (add-to-list 'org-property-set-functions-alist
  728. `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
  729. (defun org-contacts-vcard-escape (str)
  730. "Escape ; , and \n in STR for the VCard format."
  731. ;; Thanks to this library for the regexp:
  732. ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
  733. (when str
  734. (replace-regexp-in-string
  735. "\n" "\\\\n"
  736. (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
  737. (defun org-contacts-vcard-encode-name (name)
  738. "Try to encode NAME as VCard's N property.
  739. The N property expects
  740. FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
  741. Org-contacts does not specify how to encode the name. So we try
  742. to do our best."
  743. (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
  744. (defun org-contacts-vcard-format (contact)
  745. "Formats CONTACT in VCard 3.0 format."
  746. (let* ((properties (caddr contact))
  747. (name (org-contacts-vcard-escape (car contact)))
  748. (n (org-contacts-vcard-encode-name name))
  749. (email (cdr (assoc-string org-contacts-email-property properties)))
  750. (tel (cdr (assoc-string org-contacts-tel-property properties)))
  751. (note (cdr (assoc-string org-contacts-note-property properties)))
  752. (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
  753. (addr (cdr (assoc-string org-contacts-address-property properties)))
  754. (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
  755. (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name)))
  756. (concat head
  757. (when email (progn
  758. (setq emails-list (org-contacts-split-property email))
  759. (setq result "")
  760. (while emails-list
  761. (setq result (concat result "EMAIL:" (org-contacts-strip-link (car emails-list)) "\n"))
  762. (setq emails-list (cdr emails-list)))
  763. result))
  764. (when addr
  765. (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
  766. (when tel (progn
  767. (setq phones-list (org-contacts-split-property tel))
  768. (setq result "")
  769. (while phones-list
  770. (setq result (concat result "TEL:" (org-contacts-strip-link (car phones-list)) "\n"))
  771. (setq phones-list (cdr phones-list)))
  772. result))
  773. (when bday
  774. (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
  775. (format "BDAY:%04d-%02d-%02d\n"
  776. (calendar-extract-year cal-bday)
  777. (calendar-extract-month cal-bday)
  778. (calendar-extract-day cal-bday))))
  779. (when nick (format "NICKNAME:%s\n" nick))
  780. (when note (format "NOTE:%s\n" note))
  781. "END:VCARD\n\n")))
  782. (defun org-contacts-export-as-vcard (&optional name file to-buffer)
  783. "Export all contacts matching NAME as VCard 3.0.
  784. If TO-BUFFER is nil, the content is written to FILE or
  785. `org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
  786. is created and the VCard is written into that buffer."
  787. (interactive) ; TODO ask for name?
  788. (let* ((filename (or file org-contacts-vcard-file))
  789. (buffer (if to-buffer
  790. (get-buffer-create to-buffer)
  791. (find-file-noselect filename))))
  792. (message "Exporting...")
  793. (set-buffer buffer)
  794. (let ((inhibit-read-only t)) (erase-buffer))
  795. (fundamental-mode)
  796. (when (fboundp 'set-buffer-file-coding-system)
  797. (set-buffer-file-coding-system coding-system-for-write))
  798. (loop for contact in (org-contacts-filter name)
  799. do (insert (org-contacts-vcard-format contact)))
  800. (if to-buffer
  801. (current-buffer)
  802. (progn (save-buffer) (kill-buffer)))))
  803. (defun org-contacts-show-map (&optional name)
  804. "Show contacts on a map.
  805. Requires google-maps-el."
  806. (interactive)
  807. (unless (fboundp 'google-maps-static-show)
  808. (error "`org-contacts-show-map' requires `google-maps-el'"))
  809. (google-maps-static-show
  810. :markers
  811. (loop
  812. for contact in (org-contacts-filter name)
  813. for addr = (cdr (assoc-string org-contacts-address-property (caddr contact)))
  814. if addr
  815. collect (cons (list addr) (list :label (string-to-char (car contact)))))))
  816. (defun org-contacts-strip-link (link)
  817. "Remove brackets, description, link type and colon from an org
  818. link string and return the pure link target."
  819. (let (startpos colonpos endpos)
  820. (setq startpos (string-match (regexp-opt '("[[tel:" "[[mailto:")) link))
  821. (if startpos
  822. (progn
  823. (setq colonpos (string-match ":" link))
  824. (setq endpos (string-match "\\]" link))
  825. (if endpos (substring link (1+ colonpos) endpos) link))
  826. (progn
  827. (setq startpos (string-match "mailto:" link))
  828. (setq colonpos (string-match ":" link))
  829. (if startpos (substring link (1+ colonpos)) link)))))
  830. (defun org-contacts-split-property (string &optional separators omit-nulls)
  831. "Custom version of `split-string'.
  832. Split a property STRING into sub-strings bounded by matches
  833. for SEPARATORS but keep Org links intact.
  834. The beginning and end of STRING, and each match for SEPARATORS, are
  835. splitting points. The substrings matching SEPARATORS are removed, and
  836. the substrings between the splitting points are collected as a list,
  837. which is returned.
  838. If SEPARATORS is non-nil, it should be a regular expression
  839. matching text which separates, but is not part of, the
  840. substrings. If nil it defaults to `org-contacts-property-values-separators',
  841. normally \"[,; \f\t\n\r\v]+\", and OMIT-NULLS is forced to t.
  842. If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
  843. that for the default value of SEPARATORS leading and trailing whitespace
  844. are effectively trimmed). If nil, all zero-length substrings are retained."
  845. (let* ((keep-nulls (or nil omit-nulls))
  846. (rexp (or separators org-contacts-property-values-separators))
  847. (inputlist (split-string string rexp keep-nulls))
  848. (linkstring "")
  849. (bufferstring "")
  850. (proplist (list "")))
  851. (while inputlist
  852. (setq bufferstring (pop inputlist))
  853. (if (string-match "\\[\\[" bufferstring)
  854. (progn
  855. (setq linkstring (concat bufferstring " "))
  856. (while (not (string-match "\\]\\]" bufferstring))
  857. (setq bufferstring (pop inputlist))
  858. (setq linkstring (concat linkstring bufferstring " ")))
  859. (setq proplist (cons (org-trim linkstring) proplist)))
  860. (setq proplist (cons bufferstring proplist))))
  861. (cdr (reverse proplist))))
  862. (provide 'org-contacts)
  863. ;;; org-contacts.el ends here