org-contacts.el 47 KB

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