1 ;;; gnorb-org.el --- The Org-centric functions of gnorb
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Eric Abrahamsen <eric@ericabrahamsen.net>
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
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.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
30 (require 'gnorb-utils)
33 (defgroup gnorb-org nil
34 "The Org bits of Gnorb."
38 (defcustom gnorb-org-after-message-setup-hook nil
39 "Hook run in a message buffer after setting up the message from
40 `gnorb-org-handle-mail' or `gnorb-org-email-subtree'."
44 (defcustom gnorb-org-trigger-actions
45 '(("todo state" . todo)
47 ("don't associate" . no-associate)
48 ("only associate" . associate)
49 ; ("capture to child" . cap-child)
50 ; ("capture to sibling" . cap-sib)
52 "List of potential actions that can be taken on headings.
54 When triggering an Org heading after receiving or sending a
55 message, this option lists the possible actions to take. Built-in
58 todo state: Associate the message, and change TODO state.
59 take note: Associate the message, and take a note.
60 don't associate: Do nothing at all, don't connect the message and TODO.
61 only associate: Associate the message with this heading, do nothing else.
62 capture to child: [not yet implemented] Associate this message with a new child heading.
63 capture to sibling: [not yet implemented] Associate this message with a new sibling heading.
65 You can reorder this list or remove items as suits your workflow.
66 The two \"capture\" options will use the value of
67 `gnorb-gnus-new-todo-capture-key' to find the appropriate
70 You can also add custom actions to the list. Actions should be a
71 cons of a string tag and a symbol indicating a custom function.
72 This function will be called on the heading in question, and
73 passed a plist containing information about the message from
74 which we're triggering."
78 (defcustom gnorb-org-msg-id-key "GNORB_MSG_ID"
79 "The name of the org property used to store the Message-IDs
80 from relevant messages. This is no longer used, and will be
85 (defcustom gnorb-org-mail-scan-scope 2
86 "Number of paragraphs to scan for mail-related links.
88 When handling a TODO heading with `gnorb-org-handle-mail', Gnorb
89 will typically reply to the most recent message associated with
90 this heading. If there are no such messages, or message tracking
91 is disabled entirely, or `gnorb-org-handle-mail' has been called
92 with a prefix arg, the heading and body text of the subtree under
93 point will instead be scanned for gnus:, mailto:, and bbdb:
94 links. This option controls how many paragraphs of body text to
95 scan. Set to 0 to only look in the heading.")
97 (make-obsolete-variable
98 'gnorb-org-mail-scan-strategies
99 "This variable has been superseded by `gnorb-org-trigger-actions'"
100 "September 12, 2014" 'set)
102 (make-obsolete-variable
103 'gnorb-org-mail-scan-state-changes
104 "This variable has been superseded by `gnorb-org-trigger-actions'"
105 "September 12, 2014" 'set)
107 (make-obsolete-variable
108 'gnorb-org-mail-scan-function
109 "This variable has been superseded by `gnorb-org-trigger-actions'"
110 "September 12, 2014" 'set)
112 (defcustom gnorb-org-find-candidates-match nil
113 "When scanning all org files for heading related to an incoming
114 message, this option will limit which headings will be offered as
115 target candidates. Specifically it will be used as the second
116 argument to `org-map-entries', and syntax is the same as that
117 used in an agenda tags view."
122 (defun gnorb-org-contact-link (rec)
123 "Prompt for a BBDB record and insert a link to that record at
126 There's really no reason to use this instead of regular old
127 `org-insert-link' with BBDB completion. But there might be in the
129 ;; this needs to handle an active region.
130 (interactive (list (gnorb-prompt-for-bbdb-record)))
131 (let* ((name (bbdb-record-name rec))
132 (link (concat "bbdb:" (org-link-escape name))))
133 (org-store-link-props :type "bbdb" :name name
134 :link link :description name)
135 (if (called-interactively-p 'any)
136 (insert (format "[[%s][%s]]" link name))
139 (defun gnorb-org-restore-after-send ()
140 "After an email is sent, go through all the org ids that might
141 have been in the outgoing message's headers and call
142 `gnorb-trigger-todo-action' on each one, then put us back where
144 (delete-other-windows)
145 (dolist (id gnorb-message-org-ids)
147 (gnorb-trigger-todo-action nil id))
148 ;; this is a little unnecessary, but it may save grief
149 (setq gnorb-gnus-message-info nil)
150 (setq gnorb-message-org-ids nil)
151 (gnorb-restore-layout))
153 (defun gnorb-org-extract-links (&optional arg region)
154 "See if there are viable links in the subtree under point."
155 ;; We're not currently using the arg. What could we do with it?
157 ;; If the region was active, only use the region
159 (push (buffer-substring (car region) (cdr region))
161 ;; Otherwise collect the heading text, and all the paragraph
164 (org-narrow-to-subtree)
165 (let ((head (org-element-at-point))
166 (tree (org-element-parse-buffer)))
167 (push (org-element-property
171 (org-element-map tree 'paragraph
173 (push (org-element-interpret-data p)
177 ;; Limit number of paragraphs based on
178 ;; `gnorb-org-mail-scan-scope'
180 (cond ((eq gnorb-org-mail-scan-scope 'all)
182 ((numberp gnorb-org-mail-scan-scope)
185 strings 0 (1+ gnorb-org-mail-scan-scope))))
186 ;; We could provide more options here. 'tree vs
187 ;; 'subtree, for instance.
194 (goto-char (point-min))
195 (gnorb-scan-links (point-max) 'gnus 'mail 'bbdb)))))
197 (defun gnorb-org-extract-mail-stuff (&optional arg region)
198 "Decide how to hande the Org heading under point as an email task.
200 See the docstring of `gnorb-org-handle-mail' for details."
201 (if (or (not gnorb-tracking-enabled)
203 (gnorb-org-extract-links arg region)
204 ;; Get all the messages associated with the IDS in this subtree.
209 (gnorb-registry-org-id-search id))
210 (gnorb-collect-ids)))))
211 (gnorb-org-extract-mail-tracking assoc-msg-ids arg region))))
213 (defun gnorb-org-extract-mail-tracking (assoc-msg-ids &optional arg region)
215 (let* ((all-links (gnorb-org-extract-links nil region))
216 ;; The latest (by the creation-time registry key) of all the
217 ;; tracked messages that were not sent by our user.
224 (let ((from (car (gnus-registry-get-id-key m 'sender))))
227 user-mail-address from)
229 message-alternative-emails from))))
233 (car (gnus-registry-get-id-key l 'creation-time))
234 (car (gnus-registry-get-id-key r 'creation-time))))))))
237 (gnorb-msg-id-to-link latest-msg-id))))
239 ;; If there are no tracked messages, or the user has specifically
240 ;; requested we ignore them with the prefix arg, just return the
241 ;; found links in the subtree.
245 ;; Otherwise ignore the other links in the subtree, and return
246 ;; the latest message.
248 `(:gnus ,(list msg-id-link))))))
250 (defvar message-beginning-of-line)
252 (defun gnorb-org-setup-message
253 (&optional messages mails from cc bcc attachments text ids)
254 "Common message setup routine for other gnorb-org commands.
255 MESSAGES is a list of gnus links pointing to messages -- we
256 currently only use the first of the list. MAILS is a list of
257 email address strings suitable for inserting in the To header.
258 ATTACHMENTS is a list of filenames to attach. TEXT is a string or
259 buffer, which is inserted in the message body. IDS is one or more
260 Org heading ids, associating the outgoing message with those
262 (require 'gnorb-gnus)
264 ;; Either compose new message...
266 ;; ...or follow link and start reply.
268 (gnorb-reply-to-gnus-link (car messages))
269 (error (gnorb-restore-layout)
270 (signal (car err) (cdr err)))))
271 ;; Add MAILS to message To header.
276 (insert (mapconcat 'identity mails ", ")))
277 ;; Return us after message is sent.
278 (add-to-list 'message-exit-actions
279 'gnorb-org-restore-after-send t)
280 ;; Set headers from MAIL_* properties (from, cc, and bcc).
283 (funcall (intern (format "message-goto-%s" (car h))))
284 (let ((message-beginning-of-line t)
285 (show-trailing-whitespace t))
286 (message-beginning-of-line)
290 (dolist (h `((from . ,from) (cc . ,cc) (bcc . ,bcc)))
292 ;; attach ATTACHMENTS
294 (lambda (a) (format "Attach %s to outgoing message? "
295 (file-name-nondirectory a)))
297 (mml-attach-file a (mm-default-file-encoding a)
300 '("file" "files" "attach"))
301 ;; insert text, if any
306 (insert-buffer-substring text)
308 ;; insert org ids, if any
311 (setq ids (list ids)))
314 (message-narrow-to-headers)
316 (goto-char (point-at-bol))
318 ;; this function hardly does anything
319 (message-insert-header
320 (intern gnorb-mail-header) i)))))
321 ;; put point somewhere reasonable
322 (if (or mails messages)
324 (message-goto-subject)
327 (run-hooks 'gnorb-org-after-message-setup-hook))
329 (defun gnorb-org-attachment-list (&optional id)
330 "Get a list of files (absolute filenames) attached to the
331 current heading, or the heading indicated by optional argument ID."
332 (when (featurep 'org-attach)
333 (let* ((attach-dir (save-excursion
340 (expand-file-name f attach-dir))
341 (org-attach-file-list attach-dir))))
344 (defvar message-mode-hook)
347 (defun gnorb-org-handle-mail (&optional arg text file)
348 "Handle current headline as a mail TODO.
350 How this function behaves depends on whether you're using Gnorb
351 for email tracking, also on the prefix arg, and on the active
354 If tracking is enabled and there is no prefix arg, Gnorb will
355 begin a reply to the newest associated message that wasn't sent
356 by the user -- ie, the Sender header doesn't match
357 `user-mail-address' or `message-alternative-emails'.
359 If tracking is enabled and there is a prefix arg, ignore the
360 tracked messages and instead scan the subtree for mail-related
361 links. This means links prefixed with gnus:, mailto:, or bbdb:.
362 See `gnorb-org-mail-scan-scope' to limit the scope of this scan.
363 Do something appropriate with the resulting links.
365 With a double prefix arg, ignore all tracked messages and all
366 links, and compose a blank new message.
368 If tracking is enabled and you want to reply to a
369 specific (earlier) message in the tracking history, use
370 `gnorb-org-view' to open an nnir *Summary* buffer containing all
371 the messages, and reply to the one you want. Your reply will be
372 automatically tracked, as well.
374 If tracking is not enabled and you want to use a specific link in
375 the subtree as a basis for the email action, then put the region
376 around that link before you call this message."
378 (setq gnorb-window-conf (current-window-configuration))
379 (move-marker gnorb-return-marker (point))
380 (when (eq major-mode 'org-agenda-mode)
381 ;; If this is all the different types, we could skip the check.
382 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
383 (org-agenda-check-no-diary)
384 (let* ((marker (or (org-get-at-bol 'org-hd-marker)
386 (buffer (marker-buffer marker))
387 (pos (marker-position marker)))
388 (switch-to-buffer buffer)
393 (cons (region-beginning) (region-end)))))
396 (unless (org-back-to-heading t)
397 (error "Not in an org item"))
398 (cl-flet ((mp (p) (org-entry-get (point) p t)))
399 ;; Double prefix means ignore everything and compose a blank
401 (let* ((links (unless (equal arg '(16))
402 (gnorb-org-extract-mail-stuff arg region)))
403 (attachments (gnorb-org-attachment-list))
404 (from (mp "MAIL_FROM"))
406 (bcc (mp "MAIL_BCC"))
407 (org-id (org-id-get-create))
408 (recs (plist-get links :bbdb))
409 (message-mode-hook (copy-sequence message-mode-hook))
412 (cons file attachments))
418 (car (bbdb-message-search
419 (org-link-unescape r)
424 (push (bbdb-mail-address r) mails)))
426 gnorb-bbdb-posting-styles)
427 (add-hook 'message-mode-hook
429 (gnorb-bbdb-configure-posting-styles (cdr recs))
430 (gnorb-bbdb-configure-posting-styles (list (car recs))))))
431 (gnorb-org-setup-message
432 (plist-get links :gnus)
433 (append mails (plist-get links :mail))
435 attachments text org-id))))))
439 (defcustom gnorb-org-email-subtree-text-parameters nil
440 "A plist of export parameters corresponding to the EXT-PLIST
441 argument to the export functions, for use when exporting to
446 (defcustom gnorb-org-email-subtree-file-parameters nil
447 "A plist of export parameters corresponding to the EXT-PLIST
448 argument to the export functions, for use when exporting to a
453 (defcustom gnorb-org-email-subtree-text-options '(nil t nil t)
454 "A list of ts and nils corresponding to Org's export options,
455 to be used when exporting to text. The options, in order, are
456 async, subtreep, visible-only, and body-only."
460 (defcustom gnorb-org-email-subtree-file-options '(nil t nil nil)
461 "A list of ts and nils corresponding to Org's export options,
462 to be used when exporting to a file. The options, in order, are
463 async, subtreep, visible-only, and body-only."
467 (defcustom gnorb-org-export-extensions
475 (odt ".odt") ; not really, though
478 "Correspondence between export backends and their
479 respective (usual) file extensions. Ugly way to do it, but what
483 (defvar org-export-show-temporary-export-buffer)
486 (defun gnorb-org-email-subtree (&optional arg)
487 "Call on a subtree to export it either to a text string or a file,
488 then compose a mail message either with the exported text
489 inserted into the message body, or the exported file attached to
492 Export options default to the following: When exporting to a
493 buffer: async = nil, subtreep = t, visible-only = nil, body-only
494 = t. Options are the same for files, except body-only is set to
495 nil. Customize `gnorb-org-email-subtree-text-options' and
496 `gnorb-org-email-subtree-file-options', respectively.
498 Customize `gnorb-org-email-subtree-parameters' to your preferred
499 default set of parameters."
500 ;; I sure would have liked to use the built-in dispatch ui, but it's
501 ;; got too much hard-coded stuff.
503 (org-back-to-heading t)
504 (let* ((backend-string
508 (symbol-name (org-export-backend-name b)))
509 org-export--registered-backends)
511 (backend-symbol (intern backend-string))
512 (f-or-t (org-completing-read "Export as file or text? "
513 '("file" "text") nil t))
514 (org-export-show-temporary-export-buffer nil)
515 (opts (if (equal f-or-t "text")
516 gnorb-org-email-subtree-text-options
517 gnorb-org-email-subtree-file-options))
519 (if (equal f-or-t "text")
520 (apply 'org-export-to-buffer
524 ,gnorb-org-email-subtree-text-parameters))
525 (apply 'org-export-to-file
527 ,(org-export-output-file-name
528 (second (assoc backend-symbol gnorb-org-export-extensions))
531 ,gnorb-org-email-subtree-file-parameters))))
533 (setq gnorb-window-conf (current-window-configuration))
534 (move-marker gnorb-return-marker (point))
538 (gnorb-org-handle-mail arg text file)))
540 (defcustom gnorb-org-capture-collect-link-p t
541 "Should the capture process store a link to the gnus message or
542 BBDB record under point, even if it's not part of the template?
543 You'll probably end up needing it, anyway."
546 (defun gnorb-org-capture-collect-link ()
547 (when gnorb-org-capture-collect-link-p
548 (let ((buf (org-capture-get :original-buffer)))
550 (with-current-buffer buf
551 (when (memq major-mode '(gnus-summary-mode
554 (call-interactively 'org-store-link)))))))
556 (add-hook 'org-capture-mode-hook 'gnorb-org-capture-collect-link)
558 ;;; Agenda/BBDB popup stuff
560 (defcustom gnorb-org-agenda-popup-bbdb nil
561 "Should Agenda tags search pop up a BBDB buffer with matching
564 Records are considered matching if they have an `org-tags' field
565 matching the current Agenda search. The name of that field can be
566 customized with `gnorb-bbdb-org-tag-field'."
569 (defcustom gnorb-org-bbdb-popup-layout 'pop-up-multi-line
570 "Default BBDB buffer layout for automatic Org Agenda display."
572 :type '(choice (const one-line)
574 (const full-multi-line)
578 (defun gnorb-org-popup-bbdb (&optional str)
579 "In an `org-tags-view' Agenda buffer, pop up a BBDB buffer
580 showing records whose `org-tags' field matches the current tags
582 ;; I was hoping to use `org-make-tags-matcher' directly, then snag
583 ;; the tagmatcher from the resulting value, but there doesn't seem
584 ;; to be a reliable way of only getting the tag-related returns. But
585 ;; I'd still like to use that function. So an ugly hack to first
586 ;; remove non-tag contents from the query string, and then make a
587 ;; new call to `org-make-tags-matcher'.
589 (require 'gnorb-bbdb)
592 (and (eq major-mode 'org-agenda-mode)
593 (eq org-agenda-type 'tags))
594 (or (called-interactively-p 'any)
595 gnorb-org-agenda-popup-bbdb))
596 (let ((todo-only nil)
597 (str (or str org-agenda-query-string))
598 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
599 or-terms term rest out-or acc tag-clause)
600 (setq or-terms (org-split-string str "|"))
601 (while (setq term (pop or-terms))
603 (while (string-match re term)
604 (setq rest (substring term (match-end 0)))
605 (let ((sub-term (match-string 0 term)))
606 (unless (save-match-data ; this isn't a tag, don't want it
607 (string-match "\\([<>=]\\)" sub-term))
610 (push (mapconcat 'identity (nreverse acc) "") out-or))
611 (setq str (mapconcat 'identity (nreverse out-or) "|"))
612 (setq tag-clause (cdr (org-make-tags-matcher str)))
613 (unless (equal str "")
617 (let ((rec-tags (bbdb-record-xfield
618 r gnorb-bbdb-org-tag-field)))
620 (let ((tags-list (org-split-string rec-tags ":"))
622 (org-trust-scanner-tags t))
623 (eval tag-clause)))))
625 ((eq major-mode 'org-mode)
627 (org-back-to-heading)
628 (let ((bound (org-element-property
629 :end (org-element-at-point)))
631 (while (re-search-forward
632 org-bracket-link-analytic-regexp bound t)
633 (when (string-match-p "bbdb" (match-string 2))
634 (setq desc (match-string 5)
635 rec (bbdb-search (bbdb-records) desc desc desc)
636 recs (append recs rec))))))))
638 (bbdb-display-records
639 recs gnorb-org-bbdb-popup-layout)
640 (when (get-buffer-window bbdb-buffer-name)
642 (get-buffer-window bbdb-buffer-name)))
643 (when (called-interactively-p 'any)
644 (message "No relevant BBDB records")))))
646 (if (featurep 'gnorb-bbdb)
647 (add-hook 'org-agenda-finalize-hook 'gnorb-org-popup-bbdb))
649 ;;; Groups from the gnorb gnus server backend
652 (defun gnorb-org-view ()
653 "Search the subtree at point for links to gnus messages, and
654 then show them in an ephemeral group, in gnus.
656 This won't work unless you've added a \"nngnorb\" server to
657 your gnus select methods."
658 ;; this should also work on the active region, if there is one.
660 (require 'gnorb-gnus)
661 (setq gnorb-window-conf (current-window-configuration))
662 (move-marker gnorb-return-marker (point))
663 (when (eq major-mode 'org-agenda-mode)
664 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
665 (org-agenda-check-no-diary)
666 (let* ((marker (or (org-get-at-bol 'org-hd-marker)
668 (buffer (marker-buffer marker))
669 (pos (marker-position marker)))
670 (switch-to-buffer buffer)
675 (org-back-to-heading)
676 (setq id (concat "id+" (org-id-get-create)))
677 (gnorb-gnus-search-messages
679 `(when (and (window-configuration-p gnorb-window-conf)
681 (set-window-configuration gnorb-window-conf)
682 (goto-char gnorb-return-marker))))))
685 ;;; gnorb-org.el ends here