org-contacts.el 39 KB

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