Add 2012 to FSF copyright years for Emacs files.
[gnus] / lisp / nnmairix.el
1 ;;; nnmairix.el --- Mairix back end for Gnus, the Emacs newsreader
2
3 ;; Copyright (C) 2007-2012  Free Software Foundation, Inc.
4
5 ;; Author: David Engster <dengste@eml.cc>
6 ;; Keywords: mail searching
7 ;; Version: 0.6
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs 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.
15
16 ;; GNU Emacs 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.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This is a back end for using the mairix search engine with
27 ;; Gnus.  Mairix is a tool for searching words in locally stored
28 ;; mail.  Mairix is very fast which allows using it efficiently for
29 ;; "smart folders", e.g. folders which are associated with search
30 ;; queries.  Of course, you can also use this back end just for
31 ;; calling mairix with some search query.
32 ;;
33 ;; Mairix is written by Richard Curnow.  More information can be found at
34 ;; http://www.rpcurnow.force9.co.uk/mairix/
35
36 ;; Commentary on the code: nnmairix sits between Gnus and the "real"
37 ;; back end which handles the mail (currently nnml, nnimap and
38 ;; nnmaildir were tested). I know this is all a bit hacky, but so far
39 ;; it works for me.  This is the first back end I've written for Gnus,
40 ;; so I'd appreciate any comments, suggestions, bug reports (and, of
41 ;; course, patches) for improving nnmairix.
42
43 ;; nnmairix does not use an active file, since I wanted to contain the
44 ;; back end "inside Gnus" as much as possible without the need of an
45 ;; external file.  It stores the query/folder information in the group
46 ;; parameters instead.  This also implies that once you kill a mairix
47 ;; group, it's gone for good.  I don't think that this is really
48 ;; problematic, since I don't see the need in unsubscribing and
49 ;; re-subscribing search groups
50
51 ;; Every mairix server is "responsible" for one mairix installation,
52 ;; i.e. you can have several mairix servers for different mairix
53 ;; configurations.  Not that I think anyone will actually do this, but
54 ;; I thought it would be a "nice to have feature"...
55
56 ;; KNOWN BUGS:
57 ;; * Mairix does only support us-ascii characters.
58
59 ;; TODO/MISSING FEATURES:
60 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
61 ;; * Maybe use an active file instead of group parameters?
62 ;; * Maybe use "-a" when updating groups which are not newly created?
63
64 ;;; Changelog:
65 ;; 05/30/2008 - version 0.6
66 ;;
67 ;;    * It is now possible to propagate marks from the nnmairix groups
68 ;;      to the original messages (and for maildir also vice versa). See
69 ;;      the docs for details on this feature - it's pretty delicate
70 ;;      and currently needs a patched mairix binary to work smoothly.
71 ;;
72 ;;    * Keep messages in nnmairix groups always read/unread
73 ;;      (bound to 'G b r').
74 ;;
75 ;;    * Recreate back end folder for nnmairix groups in case you
76 ;;      somehow get wrong article counts (bound to 'G b d').
77 ;;
78 ;;    * New group parameter 'allow-fast'. Toggling of parameter bound
79 ;;      to 'G b a'. The default is nil, meaning that the group will
80 ;;      always be updated with a mairix search, even when only entered.
81 ;;
82 ;;    * More/Better use of the registry (if available). Can now also
83 ;;      deal with duplicate messages in different groups.
84 ;;
85 ;; 02/06/2008 - version 0.5
86 ;;
87 ;;    * New function: nnmairix-goto-original-article. Uses the
88 ;;      registry or the mail file path for determining original group.
89 ;;
90 ;;    * Deal with empty Xref header
91 ;;
92 ;;    * Changed summary mode keybindings since the old ones were
93 ;;      already taken
94 ;;
95 ;;   (Thanks to Tassilo Horn and Ted Zlatanov for their help)
96 ;;
97 ;; 01/07/2008 - version 0.4
98 ;;
99 ;;    * New/fixed doc strings and code cleanup.
100 ;;
101 ;; 11/18/2007 - version 0.3
102 ;;
103 ;;    * Fixed bugs when dealing with nnml and native servers
104 ;;
105 ;;    * Make variables customizable
106 ;;
107 ;; 10/10/2007 - version 0.2
108 ;;
109 ;;    * Use nnml-directory/directory server variables for nnml and
110 ;;    nnmaildir back ends as path for search folders. This way it
111 ;;    becomes independent of 'base' setting in .mairixirc (but not for
112 ;;    nnimap).
113 ;;
114 ;;    * As a result: Changed nnmairix-backend-to-server so that user
115 ;;    is asked when more than one nnmairix server exists and we do not
116 ;;    know which one is responsible for current back end.
117 ;;
118 ;;    * Rename files when using nnml back ends so that there are no
119 ;;    holes in article numbers. This should fix all problems regarding
120 ;;    wrong article counts with nnml.
121 ;;
122 ;;    * More commands for creating queries (using widgets or the
123 ;;    minibuffer).
124 ;;
125 ;;    * Fixed bug in nnmairix-create-search-group-from-message
126 ;;
127 ;;    * Changed copyright to FSF
128 ;;
129 ;;      (Thanks to Georg C. F. Greve and Bastien for suggestions and
130 ;;      ideas!)
131 ;;
132 ;; 10/03/2007 - version 0.1 - first release
133
134
135 ;;; Code:
136
137 (eval-when-compile (require 'cl))       ;For (pop (cdr ogroup)).
138
139 (require 'nnoo)
140 (require 'gnus-group)
141 (require 'gnus-sum)
142 (require 'message)
143 (require 'nnml)
144 (require 'widget)
145
146 (nnoo-declare nnmairix)
147
148 ;;; === Keymaps
149
150 (eval-when-compile
151   (when (featurep 'xemacs)
152     ;; The `kbd' macro requires that the `read-kbd-macro' macro is available.
153     (require 'edmacro)))
154
155 ;; Group mode
156 (defun nnmairix-group-mode-hook ()
157   "Nnmairix group mode keymap."
158   (define-key gnus-group-mode-map
159     (kbd "G b") (make-sparse-keymap))
160   (define-key gnus-group-mode-map
161     (kbd "G b g") 'nnmairix-create-search-group)
162   (define-key gnus-group-mode-map
163     (kbd "G b c") 'nnmairix-create-server-and-default-group)
164   (define-key gnus-group-mode-map
165     (kbd "G b q") 'nnmairix-group-change-query-this-group)
166   (define-key gnus-group-mode-map
167     (kbd "G b t") 'nnmairix-group-toggle-threads-this-group)
168   (define-key gnus-group-mode-map
169     (kbd "G b u") 'nnmairix-update-database)
170   (define-key gnus-group-mode-map
171     (kbd "G b s") 'nnmairix-search)
172   (define-key gnus-group-mode-map
173     (kbd "G b i") 'nnmairix-search-interactive)
174   (define-key gnus-group-mode-map
175     (kbd "G b m") 'nnmairix-widget-search)
176   (define-key gnus-group-mode-map
177     (kbd "G b p") 'nnmairix-group-toggle-propmarks-this-group)
178   (define-key gnus-group-mode-map
179     (kbd "G b r") 'nnmairix-group-toggle-readmarks-this-group)
180   (define-key gnus-group-mode-map
181     (kbd "G b d") 'nnmairix-group-delete-recreate-this-group)
182   (define-key gnus-group-mode-map
183     (kbd "G b a") 'nnmairix-group-toggle-allowfast-this-group)
184   (define-key gnus-group-mode-map
185     (kbd "G b o") 'nnmairix-propagate-marks))
186
187 ;; Summary mode
188 (defun nnmairix-summary-mode-hook ()
189   "Nnmairix summary mode keymap."
190   (define-key gnus-summary-mode-map
191     (kbd "G G t") 'nnmairix-search-thread-this-article)
192   (define-key gnus-summary-mode-map
193     (kbd "G G f") 'nnmairix-search-from-this-article)
194   (define-key gnus-summary-mode-map
195     (kbd "G G m") 'nnmairix-widget-search-from-this-article)
196   (define-key gnus-summary-mode-map
197     (kbd "G G g") 'nnmairix-create-search-group-from-message)
198   (define-key gnus-summary-mode-map
199     (kbd "G G o") 'nnmairix-goto-original-article)
200   (define-key gnus-summary-mode-map
201     (kbd "G G u") 'nnmairix-remove-tick-mark-original-article))
202
203 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
204 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
205
206 ;; ;;;###autoload
207 ;; (defun nnmairix-initialize (&optional force)
208 ;;   (interactive "P")
209 ;;   (if (not (or (file-readable-p "~/.mairixrc")
210 ;;             force))
211 ;;       (message "No file `~/.mairixrc', skipping nnmairix setup")
212 ;;     (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
213 ;;     (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)))
214
215 ;; Customizable stuff
216
217 (defgroup nnmairix nil
218   "Back end for the Mairix mail search engine."
219   :group 'gnus)
220
221 (defcustom nnmairix-group-prefix "zz_mairix"
222   "Prefix for mairix search groups on back end server.
223 nnmairix will create these groups automatically on the back end
224 server for each nnmairix search group.  The name on the back end
225 server will be this prefix plus a random number.  You can delete
226 unused nnmairix groups on the back end using
227 `nnmairix-purge-old-groups'."
228   :version "23.1"
229   :type 'string
230   :group 'nnmairix)
231
232 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
233   "Buffer used for mairix output."
234   :version "23.1"
235   :type 'string
236   :group 'nnmairix)
237
238 (defcustom nnmairix-customize-query-buffer "*mairix query*"
239   "Name of the buffer for customizing Mairix queries."
240   :version "23.1"
241   :type 'string
242   :group 'nnmairix)
243
244 (defcustom nnmairix-mairix-update-options '("-F" "-Q")
245   "Options when calling mairix for updating the database.
246 The default is '-F' and '-Q' for making updates faster.  You
247 should call mairix without these options from time to
248 time (e.g. via cron job)."
249   :version "23.1"
250   :type '(repeat string)
251   :group 'nnmairix)
252
253 (defcustom nnmairix-mairix-search-options '("-Q")
254   "Options when calling mairix for searching.
255 The default is '-Q' for making searching faster."
256   :version "23.1"
257   :type '(repeat string)
258   :group 'nnmairix)
259
260 (defcustom nnmairix-mairix-synchronous-update nil
261   "Set this to t if you want Emacs to wait for mairix updating the database."
262   :version "23.1"
263   :type 'boolean
264   :group 'nnmairix)
265
266 (defcustom nnmairix-rename-files-for-nnml t
267   "Rename nnml mail files so that they are consecutively numbered.
268 When using nnml as back end, mairix might produce holes in the
269 article numbers which will produce wrong article counts by
270 Gnus.  This option controls whether nnmairix should rename the
271 files consecutively."
272   :version "23.1"
273   :type 'boolean
274   :group 'nnmairix)
275
276 (defcustom nnmairix-widget-fields-list
277   '(("from" "f" "From") ("to" "t" "To") ("cc" "c" "Cc")
278     ("subject" "s" "Subject")  ("to" "tc" "To or Cc")
279     ("from" "a" "Address") (nil "b" "Body") (nil "n" "Attachment")
280     ("Message-ID" "m" "Message ID") (nil "s" "Size") (nil "d" "Date"))
281   "Fields that should be editable during interactive query customization.
282
283 Header, corresponding mairix command and description for editable
284 fields in interactive query customization.  The header specifies
285 which header contents should be inserted into the editable field
286 when creating a Mairix query based on the current message (can be
287 nil for disabling this)."
288   :version "23.1"
289   :type '(repeat (list
290                   (choice :tag "Field"
291                           (const :tag "none" nil)
292                           (const :tag "From" "from")
293                           (const :tag "To" "to")
294                           (const :tag "Cc" "cc")
295                           (const :tag "Subject" "subject")
296                           (const :tag "Message ID" "Message-ID"))
297                   (string :tag "Command")
298                   (string :tag "Description")))
299   :group 'nnmairix)
300
301 (defcustom nnmairix-widget-select-window-function
302   (lambda () (select-window (get-largest-window)))
303   "Function for selecting the window for customizing the mairix query.
304 The default chooses the largest window in the current frame."
305   :version "23.1"
306   :type 'function
307   :group 'nnmairix)
308
309 (defcustom nnmairix-propagate-marks-upon-close t
310   "Flag if marks should be propagated upon closing a group.
311 The default of this variable is t. If set to 'ask, the
312 user will be asked if the flags should be propagated when the
313 group is closed.  If set to nil, the user will have to manually
314 call 'nnmairix-propagate-marks'."
315   :version "23.1"
316   :type '(choice (const :tag "always" t)
317                  (const :tag "ask" 'ask)
318                  (const :tag "never" nil))
319   :group 'nnmairix)
320
321 (defcustom nnmairix-propagate-marks-to-nnmairix-groups nil
322   "Flag if marks from original articles should be seen in nnmairix groups.
323 The default is nil since it will only work if the articles are in
324 maildir format and NOT managed by the nnmaildir back end but
325 e.g. an IMAP server (which stores the marks in the maildir file
326 name).  You may safely set this to t for testing - the worst that
327 can happen are wrong marks in nnmairix groups."
328   :version "23.1"
329   :type 'boolean
330   :group 'nnmairix)
331
332 (defcustom nnmairix-only-use-registry nil
333   "Use only the registry for determining original group(s).
334 If set to t, nnmairix will only use the registry for determining
335 the original group(s) of an article (which is also necessary for
336 propagating marks).  If set to nil, it will also try to determine
337 the group from an additional mairix search which might be slow
338 when propagating lots of marks."
339   :version "23.1"
340   :type 'boolean
341   :group 'nnmairix)
342
343 (defcustom nnmairix-allowfast-default nil
344   "Whether fast entering should be the default for nnmairix groups.
345 You may set this to t to make entering the group faster, but note that
346 this might lead to problems, especially when used with marks propagation."
347   :version "23.1"
348   :type 'boolean
349   :group 'nnmairix)
350
351 ;; ==== Other variables
352
353 (defvar nnmairix-widget-other
354   '(threads flags)
355   "Other editable mairix commands when using customization widgets.
356 Currently there are 'threads and 'flags.")
357
358 (defvar nnmairix-interactive-query-parameters
359   '((?f "from" "f" "From") (?t "to" "t" "To") (?c "to" "tc" "To or Cc")
360     (?a "from" "a" "Address") (?s "subject" "s" "Subject") (?b nil "b" "Body")
361     (?d nil "d" "Date") (?n nil "n" "Attachment"))
362   "Things that should be editable during interactive query generation.
363 Every list element consists of the following entries: Keystroke,
364 message field (if any), mairix command and description.")
365
366 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
367   "Controls on which back ends groups should be deleted and re-created.
368 This variable is a list of back ends where the search group
369 should be completely deleted and re-created when the query or
370 thread parameter changes.  The default is to this for all
371 currently supported back ends.  It usually also corrects the
372 problem of \"holes\" in the article numbers which often lead to a
373 wrong count of total articles shown by Gnus.")
374
375 ;;; === Server variables
376
377 (defvoo nnmairix-backend  nil
378   "Back end where mairix stores its searches.")
379
380 (defvoo nnmairix-backend-server nil
381   "Name of the server where mairix stores its searches.")
382
383 (defvoo nnmairix-mairix-command "mairix"
384   "Command to call mairix for this nnmairix server.")
385
386 (defvoo nnmairix-hidden-folders nil
387   "Set this to t if the back end server uses hidden directories for
388 its maildir mail folders (e.g. the Dovecot IMAP server or mutt).")
389
390 (defvoo nnmairix-default-group nil
391   "Default search group. This is the group which is used for all
392 temporary searches, e.g. nnmairix-search.")
393
394 ;;; === Internal variables
395
396 (defconst nnmairix-group-regexp
397   (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
398   "Regexp for mairix groups on back end.")
399
400 (defconst nnmairix-valid-backends '(nnimap nnml nnmaildir)
401   "Back ends supported by nnmairix.
402 Other back ends might or might not work.")
403
404 (defvar nnmairix-last-server nil
405   "Last chosen server.")
406
407 (defvar nnmairix-current-server nil
408   "Current server.")
409
410 (defvar nnmairix-marks-cache nil
411   "Cache for marks which should be set upon closing current group.")
412
413 (defvar nnmairix-version-output nil
414   "Version string of mairix binary.")
415
416 ;;; === Gnus back end functions
417
418 (nnoo-define-basics nnmairix)
419
420 (gnus-declare-backend "nnmairix" 'mail 'address)
421
422 (deffoo nnmairix-open-server (server &optional definitions)
423   ;; just set server variables
424   (setq nnmairix-current-server server)
425   (nnoo-change-server 'nnmairix server definitions))
426
427 (deffoo nnmairix-request-group (group &optional server fast info)
428   ;; Call mairix and request group on back end server
429   (when server (nnmairix-open-server server))
430   (let* ((qualgroup (if server
431                         (gnus-group-prefixed-name group (list 'nnmairix server))
432                       group))
433          (folder (gnus-group-get-parameter qualgroup 'folder))
434          (allowfast (gnus-group-get-parameter qualgroup 'allow-fast))
435          (query (gnus-group-get-parameter qualgroup 'query t))
436          (threads (gnus-group-get-parameter qualgroup 'threads))
437          (backendmethod (gnus-server-to-method
438                          (format "%s:%s" (symbol-name nnmairix-backend)
439                                  nnmairix-backend-server)))
440          rval mfolder folderpath args)
441     (cond
442      ((not folder)
443       ;; No folder parameter -> error
444       (nnheader-report 'nnmairix "Check folder parameter for group %s" group)
445       nil)
446      ((not query)
447       ;; No query -> return empty group
448       (with-current-buffer nntp-server-buffer
449         (erase-buffer)
450         (insert (concat "211 0 1 0 " group))
451         t))
452      (t
453       ;; For maildir++ folders: create a hidden directory (prepend dot)
454       (setq mfolder (if (and nnmairix-hidden-folders
455                              (not (string-match "^\\." folder)))
456                         (concat "." folder)
457                       folder))
458       ;; For nnml and nnmaildir, precede mfolder with directory where mail
459       ;; is actually stored so that it's independent of 'base' setting
460       ;; in .mairixrc.
461       (when (eq nnmairix-backend 'nnml)
462         (setq folderpath (cadr (assoc 'nnml-directory backendmethod)))
463         ;; if nnml-directory is not explicitly set, use global value
464         (when (not folderpath)
465           (setq folderpath nnml-directory)))
466       (when (eq nnmairix-backend 'nnmaildir)
467         (setq folderpath
468               (cadr (assoc 'directory backendmethod))))
469       (when folderpath
470         (setq mfolder
471               (concat
472                (file-name-as-directory
473                 (expand-file-name
474                  folderpath))
475                mfolder)))
476       ;; If (not fast), call Mairix binary
477       ;; recreate underlying folder on the back end
478       (setq rval
479             (if (and fast allowfast)
480                 0
481               (nnmairix-call-mairix-binary
482                (split-string nnmairix-mairix-command)
483                mfolder query threads)))
484       ;; Check return value
485       (cond
486        ((zerop rval)                    ; call was successful
487         (nnmairix-call-backend
488          "open-server" nnmairix-backend-server)
489         ;; If we're dealing with nnml, rename files
490         ;; consecutively and make new active file for this
491         ;; group
492         (when (eq nnmairix-backend 'nnml)
493           (when nnmairix-rename-files-for-nnml
494             (nnmairix-rename-files-consecutively mfolder))
495           (nnml-generate-nov-databases-directory mfolder nil t))
496         (nnmairix-call-backend
497          "request-scan" folder nnmairix-backend-server)
498         (if (and fast allowfast)
499             t
500           (nnmairix-request-group-with-article-number-correction
501            folder qualgroup)))
502        ((and (= rval 1)
503              (with-current-buffer nnmairix-mairix-output-buffer
504                (goto-char (point-min))
505                (looking-at "^Matched 0 messages")))
506         ;; No messages found -> return empty group
507         (nnheader-message 5 "Mairix: No matches found.")
508         (set-buffer nntp-server-buffer)
509         (erase-buffer)
510         (insert (concat "211 0 1 0 " group))
511         t)
512        ;; Everything else is an error
513        (t
514         (nnheader-report
515          'nnmairix "Error running mairix. See buffer %s for details"
516          nnmairix-mairix-output-buffer)
517         nil))))))
518
519
520 (deffoo nnmairix-request-create-group (group &optional server args)
521   (let ((qualgroup (if server (gnus-group-prefixed-name group (list 'nnmairix server))
522                      group))
523         (exist t)
524         (count 0)
525         groupname info)
526     (when server (nnmairix-open-server server))
527     (gnus-group-add-parameter qualgroup '(query . nil))
528     (gnus-group-add-parameter qualgroup '(threads . nil))
529     (while exist
530       (setq count (1+ count))
531       (setq groupname (format "%s-%s-%s" nnmairix-group-prefix group
532                               (number-to-string count)))
533       (setq exist (nnmairix-call-backend
534                    "request-group" groupname nnmairix-backend-server)))
535     (nnmairix-call-backend
536      "request-create-group" groupname nnmairix-backend-server)
537     (gnus-group-add-parameter qualgroup '(folder . nil))
538     (when nnmairix-allowfast-default
539       (gnus-group-add-parameter qualgroup '(allow-fast . t)))
540     (gnus-group-set-parameter qualgroup 'folder groupname))
541   t)
542
543
544 (deffoo nnmairix-retrieve-headers (articles group &optional server fetch-old)
545   (when server (nnmairix-open-server server))
546   (let* ((folder (nnmairix-get-backend-folder group server))
547          (corr (nnmairix-get-numcorr group server))
548          (numcorr 0)
549          rval)
550     (when (and corr
551                (not (zerop (cadr corr)))
552                (numberp (car articles)))
553       (setq numcorr (cadr corr))
554       (setq articles
555             (mapcar
556              (lambda (arg) (- arg numcorr))
557              articles)))
558     (setq rval
559           (if (eq nnmairix-backend 'nnimap)
560               (let ((gnus-nov-is-evil t))
561                 (nnmairix-call-backend
562                  "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
563             (nnmairix-call-backend
564              "retrieve-headers" articles folder nnmairix-backend-server fetch-old)))
565     (nnmairix-replace-group-and-numbers articles folder group numcorr rval)
566     rval))
567
568 (deffoo nnmairix-request-article (article &optional group server to-buffer)
569   (when server (nnmairix-open-server server))
570   (let ((folder (nnmairix-get-backend-folder group server))
571         (corr (nnmairix-get-numcorr group server)))
572     (when (and
573            (numberp article)
574            corr
575            (not (zerop (cadr corr))))
576       (setq article (- article (cadr corr))))
577     (nnmairix-call-backend
578      "request-article" article folder nnmairix-backend-server to-buffer))
579   t)
580
581 (deffoo nnmairix-request-list (&optional server)
582   (when server (nnmairix-open-server server))
583   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
584       (let (cpoint cur qualgroup folder)
585         (with-current-buffer nntp-server-buffer
586           (goto-char (point-min))
587           (setq cpoint (point))
588           (while (re-search-forward nnmairix-group-regexp (point-max) t)
589             (setq cur (match-string 1)
590                   qualgroup (gnus-group-prefixed-name cur
591                                                       (list 'nnmairix server)))
592             (if (and (gnus-group-entry qualgroup)
593                      (string= (match-string 0)
594                               (gnus-group-get-parameter qualgroup 'folder)))
595                 (progn
596                   (replace-match cur)
597                   (delete-region cpoint (point-at-bol))
598                   (forward-line)
599                   (setq cpoint (point)))
600               (forward-line)))
601           (delete-region cpoint (point-max)))
602         t)
603     nil))
604
605 ;; Silence byte-compiler.
606 (autoload 'gnus-registry-get-id-key "gnus-registry")
607
608 (deffoo nnmairix-request-set-mark (group actions &optional server)
609   (when server
610     (nnmairix-open-server server))
611   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
612          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
613          (propto (gnus-group-get-parameter qualgroup 'propto t))
614          (corr (nnmairix-get-numcorr group server))
615          (folder (nnmairix-get-backend-folder group server)))
616     (save-excursion
617       (dolist (cur actions)
618         (let ((type (nth 1 cur))
619               (cmdmarks (nth 2 cur))
620               (range (gnus-uncompress-range (nth 0 cur)))
621               mid ogroup number method temp)
622           (when (and corr
623                      (not (zerop (cadr corr))))
624             (setq range (mapcar (lambda (arg)
625                                   (- arg (cadr corr)))
626                                 range)))
627           (when propmarks
628             (nnheader-message 7 "nnmairix: Setting marks...")
629               (dolist (article range)
630                 ;; get article (header) and extract message id
631                 ;; we try to determine as many original articles as possible
632                 (catch 'problem
633                   (nnmairix-call-backend "open-server" nnmairix-backend-server)
634                   (unless (gnus-request-head
635                            article
636                            (gnus-group-prefixed-name
637                             folder
638                             (list nnmairix-backend nnmairix-backend-server)))
639                     (nnheader-message
640                      3 "Unable to set mark: couldn't fetch article header for article number %d"
641                      article)
642                     (throw 'problem nil))
643                   (set-buffer nntp-server-buffer)
644                   (goto-char (point-min))
645                   (let ((case-fold-search t))
646                     (re-search-forward "^message-id:.*\\(<.+>\\)" nil t))
647                   (setq mid (match-string 1))
648                   (unless mid
649                     (nnheader-message
650                      3 "Unable to set mark: article number %d has no message-id header"
651                      article)
652                     (throw 'problem nil))
653                   ;; get original group. First try registry, then file path
654                   (setq ogroup
655                         (nnmairix-determine-original-group-from-registry mid))
656                   (unless (or ogroup
657                               nnmairix-only-use-registry)
658                     (setq ogroup
659                           (nnmairix-determine-original-group-from-path
660                            mid nnmairix-current-server)))
661                   (unless ogroup
662                     (nnheader-message
663                      3 "Unable to set mark: couldn't find original group for %s" mid)
664                     (throw 'problem nil))
665                   ;; store original groups with mid's. We cannot get
666                   ;; the article number immediately since this would
667                   ;; generate problems with maildir (articles might
668                   ;; get moved from /new to /cur and further marks
669                   ;; could then not be set)
670                   (dolist (cur ogroup)
671                     (setq temp (assoc cur
672                                       nnmairix-marks-cache))
673                     (if temp
674                         (nconc temp (list (list mid type cmdmarks)))
675                       (push (list cur (list mid type cmdmarks))
676                             nnmairix-marks-cache)))))
677               (nnheader-message 7 "nnmairix: Setting marks... done")))))))
678
679 (deffoo nnmairix-close-group (group &optional server)
680   (when server
681     (nnmairix-open-server server))
682   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
683          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
684          method)
685     (when (and propmarks
686                nnmairix-marks-cache)
687       (when (or (eq nnmairix-propagate-marks-upon-close t)
688                 (and (eq nnmairix-propagate-marks-upon-close 'ask)
689                      (y-or-n-p "Propagate marks to original articles? ")))
690       (with-current-buffer gnus-group-buffer
691         (nnmairix-propagate-marks)
692         ;; update mairix group
693         (gnus-group-jump-to-group qualgroup)
694         (gnus-group-get-new-news-this-group))))))
695
696 (autoload 'nnimap-request-update-info-internal "nnimap")
697
698 (deffoo nnmairix-request-marks (group info &optional server)
699 ;; propagate info from underlying IMAP folder to nnmairix group
700 ;; This is currently experimental and must be explicitly activated
701 ;; with nnmairix-propagate-marks-to-nnmairix-group
702   (when server
703     (nnmairix-open-server server))
704   (let* ((qualgroup (gnus-group-prefixed-name
705                     group
706                     (list 'nnmairix nnmairix-current-server)))
707          (readmarks (gnus-group-get-parameter qualgroup 'readmarks))
708          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
709          (folder (nnmairix-get-backend-folder group server))
710          (corr (nnmairix-get-numcorr group server))
711          (docorr (and corr (not (zerop (cadr corr)))))
712          (folderinfo `(,group 1 ((1 . 1))))
713          readrange marks)
714       (when (and propmarks
715                  nnmairix-propagate-marks-to-nnmairix-groups)
716         ;; these groups are not subscribed, so we have to ask the back end directly
717         (if (eq nnmairix-backend 'nnimap)
718             (nnimap-request-update-info-internal folder folderinfo nnmairix-backend-server)
719           (nnmairix-call-backend "request-update-info" folder folderinfo nnmairix-backend-server))
720         ;; set range of read articles
721         (gnus-info-set-read
722          info
723          (if docorr
724              (nnmairix-map-range
725               `(lambda (x) (+ x ,(cadr corr)))
726               (gnus-info-read folderinfo))
727            (gnus-info-read folderinfo)))
728         ;; set other marks
729         (gnus-info-set-marks
730          info
731          (if docorr
732              (mapcar (lambda (cur)
733                          (cons
734                           (car cur)
735                           (nnmairix-map-range
736                            `(lambda (x) (+ x ,(cadr corr)))
737                            (list (cadr cur)))))
738                      (gnus-info-marks folderinfo))
739            (gnus-info-marks folderinfo))))
740       (when (eq readmarks 'unread)
741         (gnus-info-set-read info nil))
742       (when (eq readmarks 'read)
743         (gnus-info-set-read info (gnus-active qualgroup))))
744   t)
745
746 (nnoo-define-skeleton nnmairix)
747
748
749 ;;; === Interactive functions
750
751 (defun nnmairix-create-search-group (server group query threads)
752   "Create on SERVER nnmairix search group GROUP with QUERY.
753 If THREADS is t, include whole threads from found messages.  If
754 called interactively, user will be asked for parameters."
755   (interactive
756    (list
757     (gnus-server-to-method (car (nnmairix-get-server)))
758     (read-string "Group name: ")
759     (read-string "Query: ")
760     (y-or-n-p "Include threads? ")))
761   (when (and (stringp query)
762              (string-match "\\s-" query))
763     (setq query (split-string query)))
764   (when (not (listp query))
765     (setq query (list query)))
766   (when (and server group query)
767     (save-excursion
768       (let ((groupname (gnus-group-prefixed-name group server))
769             info)
770         (set-buffer gnus-group-buffer)
771         (gnus-group-make-group group server)
772         (gnus-group-set-parameter groupname 'query  query)
773         (gnus-group-set-parameter groupname 'threads threads)
774         (nnmairix-update-and-clear-marks groupname)))))
775
776 (defun nnmairix-search-interactive ()
777   "Create mairix search interactively with the minibuffer."
778   (interactive)
779   (let ((char-header nnmairix-interactive-query-parameters)
780         header finished query achar)
781     (while (not finished)
782       (while (not achar)
783         (message "Query (%s): " (nnmairix-create-message-line-for-search))
784           (setq achar (read-char))
785           (when (not (assoc achar char-header))
786             (setq achar nil)))
787       (setq header (read-string
788                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
789         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
790         (setq finished (not (y-or-n-p "Add another search query? "))
791               achar nil))
792     (nnmairix-search
793      (mapconcat 'identity query " ")
794      (car (nnmairix-get-server))
795      (y-or-n-p "Include whole threads? "))))
796
797 (defun nnmairix-create-search-group-from-message ()
798   "Interactively create search group with query based on current message."
799   (interactive)
800   (let ((char-header nnmairix-interactive-query-parameters)
801         (server (nnmairix-backend-to-server gnus-current-select-method))
802          query achar header finished group threads cq)
803     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
804               (not (gnus-buffer-live-p gnus-summary-buffer)))
805       (error "No article or summary buffer"))
806     (when (not server)
807       (error "No nnmairix server found for back end %s:%s"
808              (symbol-name (car gnus-current-select-method))
809              (nth 1 gnus-current-select-method)))
810     (while (not finished)
811       (save-excursion
812         (gnus-summary-toggle-header 1)
813         (while (not achar)
814           (message "Query (%s): " (nnmairix-create-message-line-for-search))
815           (setq achar (read-char))