1 ;;; gnorb-utils.el --- Common utilities for all gnorb stuff.
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 (mailcap-parse-mimetypes)
33 "Glue code between Gnus, Org, and BBDB."
36 (make-obsolete-variable
37 'gnorb-trigger-todo-default
38 "This variable has been superseded by
39 `gnorb-org-trigger-actions'"
40 "September 8, 2014" 'set)
42 (defun gnorb-prompt-for-bbdb-record ()
43 "Prompt the user for a BBDB record."
44 (let ((recs (bbdb-records))
46 (while (> (length recs) 1)
49 (format "Filter records by regexp (%d remaining): "
51 (mapcar 'bbdb-record-name recs)))
52 (setq recs (bbdb-search recs name name name nil nil)))
55 (error "No matching records"))))
57 (defvar gnorb-tmp-dir (make-temp-file "emacs-gnorb" t)
58 "Temporary directory where attachments etc are saved.")
60 (defvar gnorb-message-org-ids nil
61 "List of Org heading IDs from the outgoing Gnus message, used
62 to mark mail TODOs as done once the message is sent."
63 ;; The send hook either populates this, or sets it to nil, depending
64 ;; on whether the message in question has an Org id header. Then
65 ;; `gnorb-org-restore-after-send' checks for it and acts
66 ;; appropriately, then sets it to nil.
69 (defvar gnorb-window-conf nil
70 "Save window configurations here, for restoration after mails
71 are sent, or Org headings triggered.")
73 (defvar gnorb-return-marker (make-marker)
74 "Return point here after various actions, to be used together
75 with `gnorb-window-conf'.")
77 (defvar gnorb-trigger-capture-location nil
78 "Marker pointing at the location where we want to place capture
79 templates, for the capture-to-child and capture-to-sibling
82 (defcustom gnorb-mail-header "X-Org-ID"
83 "Name of the mail header used to store the ID of a related Org
84 heading. Only used locally: always stripped when the mail is
89 ;;; this is just ghastly, but the value of this var is single regexp
90 ;;; group containing various header names, and we want our value
91 ;;; inside that group.
92 (eval-after-load 'message
93 `(let ((ign-headers-list
94 (split-string message-ignored-mail-headers
96 (our-val (concat gnorb-mail-header "\\")))
97 (unless (member our-val ign-headers-list)
98 (setq ign-headers-list
99 `(,@(butlast ign-headers-list 1) ,our-val
100 ,@(last ign-headers-list 1)))
101 (setq message-ignored-mail-headers
103 'identity ign-headers-list "|")))))
106 (defun gnorb-restore-layout ()
107 "Restore window layout and value of point after a Gnorb command.
109 Some Gnorb commands change the window layout (ie `gnorb-org-view'
110 or incoming email triggering). This command restores the layout
111 to what it was. Bind it to a global key, or to local keys in Org
112 and Gnus and BBDB maps."
114 (when (window-configuration-p gnorb-window-conf)
115 (select-frame-set-input-focus
116 (window-configuration-frame gnorb-window-conf))
117 (set-window-configuration gnorb-window-conf)
118 (when (buffer-live-p (marker-buffer gnorb-return-marker))
119 (goto-char gnorb-return-marker))))
121 (defun gnorb-bracket-message-id (id)
122 "Ensure message-id ID is bound by angle brackets."
123 ;; Always use a message-id with angle brackets around it.
124 ;; `gnus-summary-goto-article' can handle either, but
125 ;; `gnus-request-head' will fail without brackets IF you're
126 ;; requesting from an nntp group. Mysterious.
127 (unless (string-match "\\`<" id)
128 (setq id (concat "<" id)))
129 (unless (string-match ">\\'" id)
130 (setq id (concat id ">")))
133 (defun gnorb-unbracket-message-id (id)
134 "Ensure message-id ID is NOT bound by angle brackets."
135 ;; This shit is annoying, but Org wants an id with no brackets, and
136 ;; Gnus is safest with an id that has brackets. So here we are.
137 (replace-regexp-in-string "\\(\\`<\\|>\\'\\)" "" id))
139 (defun gnorb-reply-to-gnus-link (link)
140 "Start a reply to the linked message."
141 (let* ((link (org-link-unescape link))
142 (group (car (org-split-string link "#")))
143 (id (gnorb-bracket-message-id
144 (second (org-split-string link "#"))))
146 (car (gnus-find-method-for-group group))))
147 (gnorb-follow-gnus-link group id)
149 (if (eq backend 'nntp)
150 'gnus-summary-followup-with-original
151 'gnus-summary-wide-reply-with-original))))
153 (defun gnorb-follow-gnus-link (group id)
154 "Be a little clever about following gnus links.
156 The goal here is reuse frames and windows as much as possible, so
157 we're not opening multiple windows on the *Group* buffer, for
158 instance, and messing up people's layouts. There also seems to be
159 an issue when opening a link to a message whose *Summary* buffer
160 is already visible: somehow, after following the link, point ends
161 up on the message _after_ the one we want, and things go haywire.
163 So we try to be a little clever. The logical progression here is
166 1. If the link's target group is already open in a *Summary*
167 buffer, just switch to that buffer (if it's visible in any frame
168 then raise it and switch focus, otherwise pull it into the
169 current window) and go to the message with
170 `gnus-summary-goto-article'.
172 2. If the Gnus *Group* buffer is visible in any window or frame,
173 raise that frame/window and give it focus before following the
176 3. Otherwise just follow the link as usual, in the current
178 (let* ((sum-buffer (gnus-summary-buffer-name group))
181 ((gnus-buffer-exists-p sum-buffer)
183 ((gnus-buffer-exists-p gnus-group-buffer)
186 (target-window (when target-buffer
187 (get-buffer-window target-buffer t))))
189 ;; Our target buffer is displayed somewhere: just go there.
191 (select-frame-set-input-focus
192 (window-frame target-window))
193 (switch-to-buffer target-buffer))
194 ;; Our target buffer exists, but isn't displayed: pull it up.
196 (switch-to-buffer target-buffer)))
197 (message "Following link...")
198 (if (gnus-buffer-exists-p sum-buffer)
199 (gnus-summary-goto-article id nil t)
200 (gnorb-open-gnus-link group id))))
202 (defun gnorb-open-gnus-link (group id)
203 "Gnorb version of `org-gnus-follow-link'."
204 ;; We've probably already bracketed the id, but just in case this is
205 ;; called from elsewhere...
206 (let* ((id (gnorb-bracket-message-id id))
207 (art-no (cdr (gnus-request-head id group)))
208 (arts (gnus-group-unread group))
210 (gnus-activate-group group)
211 (setq success (gnus-group-read-group arts t group))
213 (gnus-summary-goto-article (or art-no id) nil t)
214 (signal 'error "Group could not be opened."))))
216 (defun gnorb-trigger-todo-action (arg &optional id)
217 "Do the actual restore action. Two main things here. First: if
218 we were in the agenda when this was called, then keep us in the
219 agenda. Then let the user choose an action from the value of
220 `gnorb-org-trigger-actions'."
221 (let* ((agenda-p (eq major-mode 'org-agenda-mode))
225 (org-get-at-bol 'org-hd-marker)))
226 ((derived-mode-p 'org-mode)
228 (org-back-to-heading)
233 (org-back-to-heading)
236 (org-with-point-at root-marker
237 (org-id-get-create))))
241 "Trigger action on %s: "
242 (gnorb-pretty-outline id))
243 gnorb-org-trigger-actions nil t)
244 gnorb-org-trigger-actions))))
250 (gnorb-registry-make-entry
251 (plist-get gnorb-gnus-message-info :msg-id)
252 (plist-get gnorb-gnus-message-info :from)
253 (plist-get gnorb-gnus-message-info :subject)
255 (plist-get gnorb-gnus-message-info :group))))
256 ;; Handle our action.
258 (org-with-point-at root-marker
259 (make-entry (org-id-get-create))
260 (funcall action gnorb-gnus-message-info))
263 (org-with-point-at root-marker
264 (make-entry (org-id-get-create))
265 (call-interactively 'org-add-note)))
269 (org-with-point-at root-marker
270 (make-entry (org-id-get-create)))
271 (call-interactively 'org-agenda-todo))
272 (org-with-point-at root-marker
273 (make-entry (org-id-get-create))
274 (call-interactively 'org-todo))))
278 (org-with-point-at root-marker
279 (make-entry (org-id-get-create))))
280 ;; We're going to capture a new heading
282 (org-with-point-at root-marker
283 (setq gnorb-trigger-capture-location (point-marker)))
286 (copy-sequence (org-capture-select-template))))
287 ;; Do surgery on that template so that it finds its
288 ;; location using our function.
291 ,(if (eq action 'cap-child)
292 #'gnorb-trigger-capture-child
293 #'gnorb-trigger-capture-sibling)))
294 ;; This will likely fail horribly for capture templates
295 ;; that aren't entries or list items.
296 (let ((org-capture-entry entry))
297 ;; When org-capture-entry is let-bound, the capture
298 ;; process will use that template instead of
299 ;; prompting the user. Also, `gnorb-registry-capture'
300 ;; will take care of making the registry entry for us.
301 (call-interactively 'org-capture)))))))
302 ;; Lastly, query about attaching email attachments. No matter what
303 ;; happens, clear `gnorb-gnus-capture-attachments'.
306 (if (memq action '(cap-child cap-sib))
311 (format "Attach %s to heading? "
312 (file-name-nondirectory a)))
315 (org-attach-attach a nil 'mv)))
316 gnorb-gnus-capture-attachments
317 '("file" "files" "attach")))
318 (setq gnorb-gnus-capture-attachments nil))))
320 (defun gnorb-trigger-capture-child ()
321 ;; The capture process creates a child by default
322 (org-goto-marker-or-bmk gnorb-trigger-capture-location)
323 (org-back-to-heading))
325 (defun gnorb-trigger-capture-sibling ()
326 ;; This only works if we're not trying to create a sibling for a
327 ;; top-level heading, there appears to be no way to do that. But in
328 ;; that case this trigger action isn't really necessary, just
329 ;; handle it with a regular capture.
330 (org-goto-marker-or-bmk gnorb-trigger-capture-location)
331 (org-up-heading-safe))
333 (defun gnorb-pretty-outline (id &optional kw)
334 "Return pretty outline path of the Org heading indicated by ID.
336 If the KW argument is true, add the TODO keyword into the path."
337 (org-with-point-at (org-id-find id t)
338 (let ((el (org-element-at-point)))
342 (org-element-property :todo-keyword el))
344 (org-format-outline-path
347 (file-name-nondirectory
349 (org-base-buffer (current-buffer)))))
350 (org-get-outline-path)
352 (replace-regexp-in-string
353 org-bracket-link-regexp
354 "\\3" (org-element-property :raw-value el)))))))))
356 (defun gnorb-scan-links (bound &rest types)
357 "Scan from point to BOUND looking for links of type in TYPES.
359 TYPES is a list of symbols, possible values include 'bbdb, 'mail,
361 ;; this function could be refactored somewhat -- lots of code
362 ;; repetition. It also should be a little faster for when we're
363 ;; scanning for gnus links only, that's a little slow. We should
364 ;; probably use a different regexp based on the value of TYPES.
366 ;; This function should also *not* be responsible for unescaping
367 ;; links -- we don't know what they're going to be used for, and
368 ;; unescaped is safer.
369 (unless (= (point) bound)
370 (let (addr gnus mail bbdb)
371 (while (re-search-forward org-any-link-re bound t)
372 (setq addr (or (match-string-no-properties 2)
373 (match-string-no-properties 0)))
375 ((and (memq 'gnus types)
376 (string-match "^<?gnus:" addr))
377 (push (substring addr (match-end 0)) gnus))
378 ((and (memq 'mail types)
379 (string-match "^<?mailto:" addr))
380 (push (substring addr (match-end 0)) mail))
381 ((and (memq 'bbdb types)
382 (string-match "^<?bbdb:" addr))
383 (push (substring addr (match-end 0)) bbdb))))
384 `(:gnus ,(reverse gnus) :mail ,(reverse mail) :bbdb ,(reverse bbdb)))))
386 (defun gnorb-msg-id-to-link (msg-id)
387 "Given a message id, try to create a full org link to the
389 (let ((server-group (gnorb-msg-id-to-group msg-id)))
392 (concat server-group "#"
393 (gnorb-unbracket-message-id msg-id))))))
395 (defun gnorb-msg-id-to-group (msg-id)
396 "Given a message id, try to find the group it's in.
398 So far we're checking the registry, then the groups in
399 `gnorb-gnus-sent-groups'. Use search engines? Other clever
401 (let (candidates server-group)
402 (setq msg-id (gnorb-bracket-message-id msg-id))
404 (when gnorb-tracking-enabled
405 ;; Make a big list of all the groups where this message might
408 (append (gnus-registry-get-id-key msg-id 'group)
409 gnorb-gnus-sent-groups))
410 (while (setq server-group (pop candidates))
411 (when (and (stringp server-group)
414 "\\(nnir\\|nnvirtual\\|UNKNOWN\\)"
417 (gnus-request-head msg-id server-group)))
418 (throw 'found server-group))))
421 (defun gnorb-collect-ids (&optional id)
422 "Collect all Org IDs for a subtree.
424 Starting with the heading under point (or the heading indicated
425 by the ID argument), collect its ID property, and the IDs of all
431 (org-narrow-to-subtree)
432 (org-element-map (org-element-parse-buffer)
435 (org-element-property :ID hl))))))
437 ;; Common functions for extracting references and relevant headings
438 ;; from the message under point. For use in gnorb-gnus.el functions.
440 (defun gnorb-get-real-group-name (group art-no)
441 "Find the original group name of a message in a virtual or nnir
443 (cl-case (car (gnus-find-method-for-group group))
445 (setq group (car (nnvirtual-map-article art-no))))
447 (setq group (nnir-article-group art-no))))
450 (defun gnorb-find-tracked-headings (headers &optional include-zombies)
451 "Check HEADERS for message references and return relevant heading IDs.
453 HEADERs is a message's data header, as produced by
454 \(gnus-interactive \"H\"\), or, equivalently:
456 \(gnus-data-header \(gnus-data-find \(gnus-summary-article-number\)\)\)"
457 (let ((references (mail-header-references headers))
458 (msg-id (mail-header-message-id headers)))
459 (when gnorb-tracking-enabled
460 (gnorb-find-visit-candidates
461 (concat msg-id " " references) include-zombies))))
463 (defun gnorb-choose-trigger-heading (&optional id)
464 "Given an Org heading ID, ask the user if they want to trigger it.
466 If not, prompt for another target heading. Either way, return the
468 (let ((id (if (stringp id)
475 (gnorb-pretty-outline id))))
478 (org-refile-get-location "Attach part to" nil t))
479 (save-window-excursion
480 (find-file (nth 1 refile-result))
481 (goto-char (nth 3 refile-result))
482 (org-id-get-create)))))
484 ;; Loading the registry
486 (defvar gnorb-tracking-enabled nil
487 "Internal flag indicating whether Gnorb is successfully plugged
488 into the registry or not.")
491 (defun gnorb-tracking-initialize ()
492 "Start using the Gnus registry to track correspondences between
493 Gnus messages and Org headings. This requires that the Gnus
494 registry be in use, and should be called after the call to
495 `gnus-registry-initialize'."
496 (require 'gnorb-registry)
497 (with-eval-after-load 'gnus-registry
498 (add-to-list 'gnus-registry-extra-entries-precious 'gnorb-ids)
499 (add-to-list 'gnus-registry-track-extra 'gnorb-ids))
503 (unless (gnus-registry-install-p)
504 (user-error "Gnorb tracking requires that the Gnus registry be installed."))
505 (add-hook 'org-capture-mode-hook 'gnorb-registry-capture)
506 (add-hook 'org-capture-prepare-finalize-hook 'gnorb-registry-capture-abort-cleanup)
507 (setq gnorb-tracking-enabled t))))
509 (provide 'gnorb-utils)
510 ;;; gnorb-utils.el ends here