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