Merge from emacs--devo--0, gnus--rel--5.10
[gnus] / lisp / nnmairix.el
1 ;;; nnmairix.el --- Mairix back end for Gnus, the Emacs newsreader
2
3 ;; Copyright (C) 2007, 2008  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 BETA SOFTWARE! This back end should not mess up or
27 ;; even delete your mails, but having a backup is always a good idea.
28
29 ;; This is a back end for using the mairix search engine with
30 ;; Gnus.  Mairix is a tool for searching words in locally stored
31 ;; mail.  Mairix is very fast which allows using it efficiently for
32 ;; "smart folders", e.g. folders which are associated with search
33 ;; queries.  Of course, you can also use this back end just for
34 ;; calling mairix with some search query.
35 ;;
36 ;; Mairix is written by Richard Curnow.  More information can be found at
37 ;; http://www.rpcurnow.force9.co.uk/mairix/
38 ;;
39 ;; For details about setting up mairix&Gnus&nnmairix.el, look at the
40 ;; emacswiki:
41 ;;
42 ;; http://www.emacswiki.org/cgi-bin/wiki/GnusMairix
43 ;;
44 ;; The newest version of nnmairix.el can be found at
45 ;;
46 ;; http://www.emacswiki.org/cgi-bin/emacs/nnmairix.el
47
48 ;; For impatient people, here's the setup in a nutshell:
49 ;;
50 ;; This back end requires an installed mairix binary which is
51 ;; configured to index your mail folder.  You don't have to specify a
52 ;; search folder (but it does no harm, either).  Visit the man page of
53 ;; mairix and mairixrc for details.
54 ;;
55 ;; Put nnmairix.el into your search path and "(require 'nnmarix)" into
56 ;; your .gnus.  Then call nnmairix-create-default-group (or 'G b
57 ;; c'). This function will ask for all necessary information to create
58 ;; a mairix server in Gnus with the default search folder.  This
59 ;; default search folder will be used for all temporary searches: call
60 ;; nnmairix-search ('G b s') and enter a mairix query (like
61 ;; f:test@example.com). To create a mairix group for one specific
62 ;; search query, use 'G b g'.  See the emacswiki or the source for more
63 ;; information.
64
65 ;; Commentary on the code: nnmairix sits between Gnus and the "real"
66 ;; back end which handles the mail (currently nnml, nnimap and
67 ;; nnmaildir were tested). I know this is all a bit hacky, but so far
68 ;; it works for me.  This is the first back end I've written for Gnus,
69 ;; so I'd appreciate any comments, suggestions, bug reports (and, of
70 ;; course, patches) for improving nnmairix.
71
72 ;; nnmairix does not use an active file, since I wanted to contain the
73 ;; back end "inside Gnus" as much as possible without the need of an
74 ;; external file.  It stores the query/folder information in the group
75 ;; parameters instead.  This also implies that once you kill a mairix
76 ;; group, it's gone for good.  I don't think that this is really
77 ;; problematic, since I don't see the need in unsubscribing and
78 ;; re-subscribing search groups
79
80 ;; Every mairix server is "responsible" for one mairix installation,
81 ;; i.e. you can have several mairix servers for different mairix
82 ;; configurations.  Not that I think anyone will actually do this, but
83 ;; I thought it would be a "nice to have feature"...
84
85 ;; KNOWN BUGS:
86 ;; * Mairix does only support us-ascii characters.
87
88 ;; TODO/MISSING FEATURES:
89 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
90 ;; * Maybe use an active file instead of group parameters?
91 ;; * Maybe use "-a" when updating groups which are not newly created?
92
93 ;;; Changelog:
94 ;; 05/30/2008 - version 0.6
95 ;;
96 ;;    * It is now possible to propagate marks from the nnmairix groups
97 ;;      to the original messages (and for maildir also vice versa). See
98 ;;      the docs for details on this feature - it's pretty delicate
99 ;;      and currently needs a patched mairix binary to work smoothly.
100 ;;
101 ;;    * Keep messages in nnmairix groups always read/unread
102 ;;      (bound to 'G b r').
103 ;;
104 ;;    * Recreate back end folder for nnmairix groups in case you
105 ;;      somehow get wrong article counts (bound to 'G b d').
106 ;;
107 ;;    * New group parameter 'allow-fast'. Toggling of parameter bound
108 ;;      to 'G b a'. The default is nil, meaning that the group will
109 ;;      always be updated with a mairix search, even when only entered.
110 ;;
111 ;;    * More/Better use of the registry (if available). Can now also
112 ;;      deal with duplicate messages in different groups.
113 ;;
114 ;; 02/06/2008 - version 0.5
115 ;;
116 ;;    * New function: nnmairix-goto-original-article. Uses the
117 ;;      registry or the mail file path for determining original group.
118 ;;
119 ;;    * Deal with empty Xref header
120 ;;
121 ;;    * Changed summary mode keybindings since the old ones were
122 ;;      already taken
123 ;;
124 ;;   (Thanks to Tassilo Horn and Ted Zlatanov for their help)
125 ;;
126 ;; 01/07/2008 - version 0.4
127 ;;
128 ;;    * New/fixed doc strings and code cleanup.
129 ;;
130 ;; 11/18/2007 - version 0.3
131 ;;
132 ;;    * Fixed bugs when dealing with nnml and native servers
133 ;;
134 ;;    * Make variables customizable
135 ;;
136 ;; 10/10/2007 - version 0.2
137 ;;
138 ;;    * Use nnml-directory/directory server variables for nnml and
139 ;;    nnmaildir back ends as path for search folders. This way it
140 ;;    becomes independent of 'base' setting in .mairixirc (but not for
141 ;;    nnimap).
142 ;;
143 ;;    * As a result: Changed nnmairix-backend-to-server so that user
144 ;;    is asked when more than one nnmairix server exists and we do not
145 ;;    know which one is responsible for current back end.
146 ;;
147 ;;    * Rename files when using nnml back ends so that there are no
148 ;;    holes in article numbers. This should fix all problems regarding
149 ;;    wrong article counts with nnml.
150 ;;
151 ;;    * More commands for creating queries (using widgets or the
152 ;;    minibuffer).
153 ;;
154 ;;    * Fixed bug in nnmairix-create-search-group-from-message
155 ;;
156 ;;    * Changed copyright to FSF
157 ;;
158 ;;      (Thanks to Georg C. F. Greve and Bastien for suggestions and
159 ;;      ideas!)
160 ;;
161 ;; 10/03/2007 - version 0.1 - first release
162
163
164 ;;; Code:
165
166 (eval-when-compile (require 'cl))       ;For (pop (cdr ogroup)).
167
168 (require 'nnoo)
169 (require 'gnus-group)
170 (require 'gnus-sum)
171 (require 'message)
172 (require 'nnml)
173 (require 'widget)
174
175 (nnoo-declare nnmairix)
176
177 ;;; === Keymaps
178
179 (eval-when-compile
180   (when (featurep 'xemacs)
181     ;; The `kbd' macro requires that the `read-kbd-macro' macro is available.
182     (require 'edmacro)))
183
184 ;; Group mode
185 (defun nnmairix-group-mode-hook ()
186   "Nnmairix group mode keymap."
187   (define-key gnus-group-mode-map
188     (kbd "G b") (make-sparse-keymap))
189   (define-key gnus-group-mode-map
190     (kbd "G b g") 'nnmairix-create-search-group)
191   (define-key gnus-group-mode-map
192     (kbd "G b c") 'nnmairix-create-server-and-default-group)
193   (define-key gnus-group-mode-map
194     (kbd "G b q") 'nnmairix-group-change-query-this-group)
195   (define-key gnus-group-mode-map
196     (kbd "G b t") 'nnmairix-group-toggle-threads-this-group)
197   (define-key gnus-group-mode-map
198     (kbd "G b u") 'nnmairix-update-database)
199   (define-key gnus-group-mode-map
200     (kbd "G b s") 'nnmairix-search)
201   (define-key gnus-group-mode-map
202     (kbd "G b i") 'nnmairix-search-interactive)
203   (define-key gnus-group-mode-map
204     (kbd "G b m") 'nnmairix-widget-search)
205   (define-key gnus-group-mode-map
206     (kbd "G b p") 'nnmairix-group-toggle-propmarks-this-group)
207   (define-key gnus-group-mode-map
208     (kbd "G b r") 'nnmairix-group-toggle-readmarks-this-group)
209   (define-key gnus-group-mode-map
210     (kbd "G b d") 'nnmairix-group-delete-recreate-this-group)
211   (define-key gnus-group-mode-map
212     (kbd "G b a") 'nnmairix-group-toggle-allowfast-this-group)
213   (define-key gnus-group-mode-map
214     (kbd "G b o") 'nnmairix-propagate-marks))
215
216 ;; Summary mode
217 (defun nnmairix-summary-mode-hook ()
218   "Nnmairix summary mode keymap."
219   (define-key gnus-summary-mode-map
220     (kbd "$ t") 'nnmairix-search-thread-this-article)
221   (define-key gnus-summary-mode-map
222     (kbd "$ f") 'nnmairix-search-from-this-article)
223   (define-key gnus-summary-mode-map
224     (kbd "$ m") 'nnmairix-widget-search-from-this-article)
225   (define-key gnus-summary-mode-map
226     (kbd "$ g") 'nnmairix-create-search-group-from-message)
227   (define-key gnus-summary-mode-map
228     (kbd "$ o") 'nnmairix-goto-original-article)
229   (define-key gnus-summary-mode-map
230     (kbd "$ u") 'nnmairix-remove-tick-mark-original-article))
231
232 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
233 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
234
235 ;; ;;;###autoload
236 ;; (defun nnmairix-initalize (&optional force)
237 ;;   (interactive "P")
238 ;;   (if (not (or (file-readable-p "~/.mairixrc")
239 ;;             force))
240 ;;       (message "No file `~/.mairixrc', skipping nnmairix setup")
241 ;;     (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
242 ;;     (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)))
243
244 ;; Customizable stuff
245
246 (defgroup nnmairix nil
247   "Back end for the Mairix mail search engine."
248   :group 'gnus)
249
250 (defcustom nnmairix-group-prefix "zz_mairix"
251   "Prefix for mairix search groups on back end server.
252 nnmairix will create these groups automatically on the back end
253 server for each nnmairix search group.  The name on the back end
254 server will be this prefix plus a random number.  You can delete
255 unused nnmairix groups on the back end using
256 `nnmairix-purge-old-groups'."
257   :version "23.1"
258   :type 'string
259   :group 'nnmairix)
260
261 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
262   "Buffer used for mairix output."
263   :version "23.1"
264   :type 'string
265   :group 'nnmairix)
266
267 (defcustom nnmairix-customize-query-buffer "*mairix query*"
268   "Name of the buffer for customizing Mairix queries."
269   :version "23.1"
270   :type 'string
271   :group 'nnmairix)
272
273 (defcustom nnmairix-mairix-update-options '("-F" "-Q")
274   "Options when calling mairix for updating the database.
275 The default is '-F' and '-Q' for making updates faster.  You
276 should call mairix without these options from time to
277 time (e.g. via cron job)."
278   :version "23.1"
279   :type '(repeat string)
280   :group 'nnmairix)
281
282 (defcustom nnmairix-mairix-search-options '("-Q")
283   "Options when calling mairix for searching.
284 The default is '-Q' for making searching faster."
285   :version "23.1"
286   :type '(repeat string)
287   :group 'nnmairix)
288
289 (defcustom nnmairix-mairix-synchronous-update nil
290   "Set this to t if you want Emacs to wait for mairix updating the database."
291   :version "23.1"
292   :type 'boolean
293   :group 'nnmairix)
294
295 (defcustom nnmairix-rename-files-for-nnml t
296   "Rename nnml mail files so that they are consecutively numbered.
297 When using nnml as back end, mairix might produce holes in the
298 article numbers which will produce wrong article counts by
299 Gnus.  This option controls whether nnmairix should rename the
300 files consecutively."
301   :version "23.1"
302   :type 'boolean
303   :group 'nnmairix)
304
305 (defcustom nnmairix-widget-fields-list
306   '(("from" "f" "From") ("to" "t" "To") ("cc" "c" "Cc")
307     ("subject" "s" "Subject")  ("to" "tc" "To or Cc")
308     ("from" "a" "Address") (nil "b" "Body") (nil "n" "Attachment")
309     ("Message-ID" "m" "Message ID") (nil "s" "Size") (nil "d" "Date"))
310   "Fields that should be editable during interactive query customization.
311
312 Header, corresponding mairix command and description for editable
313 fields in interactive query customization.  The header specifies
314 which header contents should be inserted into the editable field
315 when creating a Mairix query based on the current message (can be
316 nil for disabling this)."
317   :version "23.1"
318   :type '(repeat (list
319                   (choice :tag "Field"
320                           (const :tag "none" nil)
321                           (const :tag "From" "from")
322                           (const :tag "To" "to")
323                           (const :tag "Cc" "cc")
324                           (const :tag "Subject" "subject")
325                           (const :tag "Message ID" "Message-ID"))
326                   (string :tag "Command")
327                   (string :tag "Description")))
328   :group 'nnmairix)
329
330 (defcustom nnmairix-widget-select-window-function
331   (lambda () (select-window (get-largest-window)))
332   "Function for selecting the window for customizing the mairix query.
333 The default chooses the largest window in the current frame."
334   :version "23.1"
335   :type 'function
336   :group 'nnmairix)
337
338 (defcustom nnmairix-propagate-marks-upon-close t
339   "Flag if marks should be propagated upon closing a group.
340 The default of this variable is t. If set to 'ask, the
341 user will be asked if the flags should be propagated when the
342 group is closed.  If set to nil, the user will have to manually
343 call 'nnmairix-propagate-marks'."
344   :version "23.1"
345   :type '(choice (const :tag "always" t)
346                  (const :tag "ask" 'ask)
347                  (const :tag "never" nil))
348   :group 'nnmairix)
349
350 (defcustom nnmairix-propagate-marks-to-nnmairix-groups nil
351   "Flag if marks from original articles should be seen in nnmairix groups.
352 The default is nil since it will only work if the articles are in
353 maildir format and NOT managed by the nnmaildir back end but
354 e.g. an IMAP server (which stores the marks in the maildir file
355 name).  You may safely set this to t for testing - the worst that
356 can happen are wrong marks in nnmairix groups."
357   :version "23.1"
358   :type 'boolean
359   :group 'nnmairix)
360
361 (defcustom nnmairix-only-use-registry nil
362   "Use only the registry for determining original group(s).
363 If set to t, nnmairix will only use the registry for determining
364 the original group(s) of an article (which is also necessary for
365 propapagting marks).  If set to nil, it will also try to determine
366 the group from an additional mairix search which might be slow
367 when propagating lots of marks."
368   :version "23.1"
369   :type 'boolean
370   :group 'nnmairix)
371
372 (defcustom nnmairix-allowfast-default nil
373   "Whether fast entering should be the default for nnmairix groups.
374 You may set this to t to make entering the group faster, but note that
375 this might lead to problems, especially when used with marks propagation."
376   :version "23.1"
377   :type 'boolean
378   :group 'nnmairix)
379
380 ;; ==== Other variables
381
382 (defvar nnmairix-widget-other
383   '(threads flags)
384   "Other editable mairix commands when using customization widgets.
385 Currently there are 'threads and 'flags.")
386
387 (defvar nnmairix-interactive-query-parameters
388   '((?f "from" "f" "From") (?t "to" "t" "To") (?c "to" "tc" "To or Cc")
389     (?a "from" "a" "Address") (?s "subject" "s" "Subject") (?b nil "b" "Body")
390     (?d nil "d" "Date") (?n nil "n" "Attachment"))
391   "Things that should be editable during interactive query generation.
392 Every list element consists of the following entries: Keystroke,
393 message field (if any), mairix command and description.")
394
395 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
396   "Controls on which back ends groups should be deleted and re-created.
397 This variable is a list of back ends where the search group
398 should be completely deleted and re-created when the query or
399 thread parameter changes.  The default is to this for all
400 currently supported back ends.  It usually also corrects the
401 problem of \"holes\" in the article numbers which often lead to a
402 wrong count of total articles shown by Gnus.")
403
404 ;;; === Server variables
405
406 (defvoo nnmairix-backend  nil
407   "Back end where mairix stores its searches.")
408
409 (defvoo nnmairix-backend-server nil
410   "Name of the server where mairix stores its searches.")
411
412 (defvoo nnmairix-mairix-command "mairix"
413   "Command to call mairix for this nnmairix server.")
414
415 (defvoo nnmairix-hidden-folders nil
416   "Set this to t if the back end server uses hidden directories for
417 its maildir mail folders (e.g. the Dovecot IMAP server or mutt).")
418
419 (defvoo nnmairix-default-group nil
420   "Default search group. This is the group which is used for all
421 temporary searches, e.g. nnmairix-search.")
422
423 ;;; === Internal variables
424
425 (defconst nnmairix-group-regexp
426   (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
427   "Regexp for mairix groups on back end.")
428
429 (defconst nnmairix-valid-backends '(nnimap nnml nnmaildir)
430   "Back ends supported by nnmairix.
431 Other back ends might or might not work.")
432
433 (defvar nnmairix-last-server nil
434   "Last chosen server.")
435
436 (defvar nnmairix-current-server nil
437   "Current server.")
438
439 (defvar nnmairix-marks-cache nil
440   "Cache for marks which should be set upon closing current group.")
441
442 (defvar nnmairix-version-output nil
443   "Version string of mairix binary.")
444
445 ;;; === Gnus back end functions
446
447 (nnoo-define-basics nnmairix)
448
449 (gnus-declare-backend "nnmairix" 'mail 'address)
450
451 (deffoo nnmairix-open-server (server &optional definitions)
452   ;; just set server variables
453   (setq nnmairix-current-server server)
454   (nnoo-change-server 'nnmairix server definitions))
455
456 (deffoo nnmairix-request-group (group &optional server fast)
457   ;; Call mairix and request group on back end server
458   (when server (nnmairix-open-server server))
459   (let* ((qualgroup (if server
460                         (gnus-group-prefixed-name group (list 'nnmairix server))
461                       group))
462          (folder (gnus-group-get-parameter qualgroup 'folder))
463          (allowfast (gnus-group-get-parameter qualgroup 'allow-fast))
464          (query (gnus-group-get-parameter qualgroup 'query t))
465          (threads (gnus-group-get-parameter qualgroup 'threads))
466          (backendmethod (gnus-server-to-method
467                          (format "%s:%s" (symbol-name nnmairix-backend)
468                                  nnmairix-backend-server)))
469          rval mfolder folderpath args)
470     (cond
471      ((not folder)
472       ;; No folder parameter -> error
473       (nnheader-report 'nnmairix "Check folder parameter for group %s" group)
474       nil)
475      ((not query)
476       ;; No query -> return empty group
477       (save-excursion
478         (set-buffer nntp-server-buffer)
479         (erase-buffer)
480         (insert (concat "211 0 1 0 " group))
481         t))
482      (t
483       ;; For maildir++ folders: create a hidden directory (prepend dot)
484       (setq mfolder (if (and nnmairix-hidden-folders
485                              (not (string-match "^\\." folder)))
486                         (concat "." folder)
487                       folder))
488       ;; For nnml and nnmaildir, precede mfolder with directory where mail
489       ;; is actually stored so that it's independent of 'base' setting
490       ;; in .mairixrc.
491       (when (eq nnmairix-backend 'nnml)
492         (setq folderpath (cadr (assoc 'nnml-directory backendmethod)))
493         ;; if nnml-directory is not explicitly set, use global value
494         (when (not folderpath)
495           (setq folderpath nnml-directory)))
496       (when (eq nnmairix-backend 'nnmaildir)
497         (setq folderpath
498               (cadr (assoc 'directory backendmethod))))
499       (when folderpath
500         (setq mfolder
501               (concat
502                (file-name-as-directory
503                 (expand-file-name
504                  folderpath))
505                mfolder)))
506       ;; If (not fast), call Mairix binary
507       ;; recreate underlying folder on the back end
508       (setq rval
509             (if (and fast allowfast)
510                 0
511               (nnmairix-call-mairix-binary
512                (split-string nnmairix-mairix-command)
513                mfolder query threads)))
514       ;; Check return value
515       (cond
516        ((zerop rval)                    ; call was succesful
517         (nnmairix-call-backend
518          "open-server" nnmairix-backend-server)
519         ;; If we're dealing with nnml, rename files
520         ;; consecutively and make new active file for this
521         ;; group
522         (when (eq nnmairix-backend 'nnml)
523           (when nnmairix-rename-files-for-nnml
524             (nnmairix-rename-files-consecutively mfolder))
525           (nnml-generate-nov-databases-directory mfolder))
526         (nnmairix-call-backend
527          "request-scan" folder nnmairix-backend-server)
528         (if (and fast allowfast)
529             t
530           (nnmairix-request-group-with-article-number-correction
531            folder qualgroup)))
532        ((and (= rval 1)
533              (save-excursion (set-buffer nnmairix-mairix-output-buffer)
534                              (goto-char (point-min))
535                              (looking-at "^Matched 0 messages")))
536         ;; No messages found -> return empty group
537         (nnheader-message 5 "Mairix: No matches found.")
538         (set-buffer nntp-server-buffer)
539         (erase-buffer)
540         (insert (concat "211 0 1 0 " group))
541         t)
542        ;; Everything else is an error
543        (t
544         (nnheader-report
545          'nnmairix "Error running marix. See buffer %s for details"
546          nnmairix-mairix-output-buffer)
547         nil))))))
548
549
550 (deffoo nnmairix-request-create-group (group &optional server args)
551   (let ((qualgroup (if server (gnus-group-prefixed-name group (list 'nnmairix server))
552                      group))
553         (exist t)
554         (count 0)
555         groupname info)
556     (when server (nnmairix-open-server server))
557     (gnus-group-add-parameter qualgroup '(query . nil))
558     (gnus-group-add-parameter qualgroup '(threads . nil))
559     (while exist
560       (setq count (1+ count))
561       (setq groupname (format "%s-%s-%s" nnmairix-group-prefix group
562                               (number-to-string count)))
563       (setq exist (nnmairix-call-backend
564                    "request-group" groupname nnmairix-backend-server)))
565     (nnmairix-call-backend
566      "request-create-group" groupname nnmairix-backend-server)
567     (gnus-group-add-parameter qualgroup '(folder . nil))
568     (when nnmairix-allowfast-default
569       (gnus-group-add-parameter qualgroup '(allow-fast . t)))
570     (gnus-group-set-parameter qualgroup 'folder groupname))
571   t)
572
573
574 (deffoo nnmairix-retrieve-headers (articles group &optional server fetch-old)
575   (when server (nnmairix-open-server server))
576   (let* ((folder (nnmairix-get-backend-folder group server))
577          (corr (nnmairix-get-numcorr group server))
578          (numcorr 0)
579          rval)
580     (when (and corr
581                (not (zerop (cadr corr)))
582                (numberp (car articles)))
583       (setq numcorr (cadr corr))
584       (setq articles
585             (mapcar
586              (lambda (arg) (- arg numcorr))
587              articles)))
588     (setq rval (nnmairix-call-backend
589                 "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
590     (when (eq rval 'nov)
591       (nnmairix-replace-group-and-numbers articles folder group numcorr)
592       rval)))
593
594 (deffoo nnmairix-request-article (article &optional group server to-buffer)
595   (when server (nnmairix-open-server server))
596   (let ((folder (nnmairix-get-backend-folder group server))
597         (corr (nnmairix-get-numcorr group server)))
598     (when (and
599            (numberp article)
600            corr
601            (not (zerop (cadr corr))))
602       (setq article (- article (cadr corr))))
603     (nnmairix-call-backend
604      "request-article" article folder nnmairix-backend-server to-buffer))
605   t)
606
607 (deffoo nnmairix-request-list (&optional server)
608   (when server (nnmairix-open-server server))
609   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
610       (let (cpoint cur qualgroup folder)
611         (save-excursion
612           (set-buffer nntp-server-buffer)
613           (goto-char (point-min))
614           (setq cpoint (point))
615           (while (re-search-forward nnmairix-group-regexp (point-max) t)
616             (setq cur (match-string 1)
617                   qualgroup (gnus-group-prefixed-name cur
618                                                       (list 'nnmairix server)))
619             (if (and (gnus-group-entry qualgroup)
620                      (string= (match-string 0)
621                               (gnus-group-get-parameter qualgroup 'folder)))
622                 (progn
623                   (replace-match cur)
624                   (delete-region cpoint (point-at-bol))
625                   (forward-line)
626                   (setq cpoint (point)))
627               (forward-line)))
628           (delete-region cpoint (point-max)))
629         t)
630     nil))
631
632 ;; Silence byte-compiler.
633 (defvar gnus-registry-install)
634 (autoload 'gnus-registry-fetch-group "gnus-registry")
635 (autoload 'gnus-registry-fetch-groups "gnus-registry")
636 (autoload 'gnus-registry-add-group "gnus-registry")
637
638 (deffoo nnmairix-request-set-mark (group actions &optional server)
639   (when server
640     (nnmairix-open-server server))
641   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
642          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
643          (propto (gnus-group-get-parameter qualgroup 'propto t))
644          (corr (nnmairix-get-numcorr group server))
645          (folder (nnmairix-get-backend-folder group server)))
646     (save-excursion
647       (dolist (cur actions)
648         (let ((type (nth 1 cur))
649               (cmdmarks (nth 2 cur))
650               (range (gnus-uncompress-range (nth 0 cur)))
651               mid ogroup number method temp)
652           (when (and corr
653                      (not (zerop (cadr corr))))
654             (setq range (mapcar (lambda (arg)
655                                   (- arg (cadr corr)))
656                                 range)))
657           (when propmarks
658             (nnheader-message 7 "nnmairix: Setting marks...")
659               (dolist (article range)
660                 ;; get article (header) and extract message id
661                 ;; we try to determine as many original articles as possible
662                 (catch 'problem
663                   (nnmairix-call-backend "open-server" nnmairix-backend-server)
664                   (unless (gnus-request-head
665                            article
666                            (gnus-group-prefixed-name
667                             folder
668                             (list nnmairix-backend nnmairix-backend-server)))
669                     (nnheader-message
670                      3 "Unable to set mark: couldn't fetch article header for article number %d"
671                      article)
672                     (throw 'problem nil))
673                   (set-buffer nntp-server-buffer)
674                   (goto-char (point-min))
675                   (let ((case-fold-search t))
676                     (re-search-forward "^message-id:.*\\(<.+>\\)" nil t))
677                   (setq mid (match-string 1))
678                   (unless mid
679                     (nnheader-message
680                      3 "Unable to set mark: article number %d has no message-id header"
681                      article)
682                     (throw 'problem nil))
683                   ;; get original group. First try registry, then file path
684                   (setq ogroup
685                         (nnmairix-determine-original-group-from-registry mid))
686                   (unless (or ogroup
687                               nnmairix-only-use-registry)
688                     (setq ogroup
689                           (nnmairix-determine-original-group-from-path
690                            mid nnmairix-current-server))
691                     ;; if available and allowed, add this entry to the registry
692                     (when (and (boundp 'gnus-registry-install)
693                                gnus-registry-install)
694                       (dolist (cur ogroup)
695                         (unless (gnus-parameter-registry-ignore cur)
696                           (gnus-registry-add-group mid cur)))))
697                   (unless ogroup
698                     (nnheader-message
699                      3 "Unable to set mark: couldn't find original group for %s" mid)
700                     (throw 'problem nil))
701                   ;; store original groups with mid's. We cannot get
702                   ;; the article number immediately since this would
703                   ;; generate problems with maildir (articles might
704                   ;; get moved from /new to /cur and further marks
705                   ;; could then not be set)
706                   (dolist (cur ogroup)
707                     (setq temp (assoc cur
708                                       nnmairix-marks-cache))
709                     (if temp
710                         (nconc temp (list (list mid type cmdmarks)))
711                       (push (list cur (list mid type cmdmarks))
712                             nnmairix-marks-cache)))))
713               (nnheader-message 7 "nnmairix: Setting marks... done")))))))
714
715 (deffoo nnmairix-close-group (group &optional server)
716   (when server
717     (nnmairix-open-server server))
718   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
719          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
720          method)
721     (when (and propmarks
722                nnmairix-marks-cache)
723       (when (or (eq nnmairix-propagate-marks-upon-close t)
724                 (and (eq nnmairix-propagate-marks-upon-close 'ask)
725                      (y-or-n-p "Propagate marks to original articles? ")))
726       (save-excursion
727         (set-buffer gnus-group-buffer)
728         (nnmairix-propagate-marks)
729         ;; update mairix group
730         (gnus-group-jump-to-group qualgroup)
731         (gnus-group-get-new-news-this-group))))))
732
733 (autoload 'nnimap-request-update-info-internal "nnimap")
734
735 (deffoo nnmairix-request-update-info (group info &optional server)
736 ;; propagate info from underlying IMAP folder to nnmairix group
737 ;; This is currently experimental and must be explicitly activated
738 ;; with nnmairix-propagate-marks-to-nnmairix-group
739   (when server
740     (nnmairix-open-server server))
741   (let* ((qualgroup (gnus-group-prefixed-name
742                     group
743                     (list 'nnmairix nnmairix-current-server)))
744          (readmarks (gnus-group-get-parameter qualgroup 'readmarks))
745          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
746          (folder (nnmairix-get-backend-folder group server))
747          (corr (nnmairix-get-numcorr group server))
748          (docorr (and corr (not (zerop (cadr corr)))))
749          (folderinfo `(,group 1 ((1 . 1))))
750          readrange marks)
751       (when (and propmarks
752                  nnmairix-propagate-marks-to-nnmairix-groups)
753         ;; these groups are not subscribed, so we have to ask the back end directly
754         (if (eq nnmairix-backend 'nnimap)
755             (nnimap-request-update-info-internal folder folderinfo nnmairix-backend-server)
756           (nnmairix-call-backend "request-update-info" folder folderinfo nnmairix-backend-server))
757         ;; set range of read articles
758         (gnus-info-set-read
759          info
760          (if docorr
761              (nnmairix-map-range
762               `(lambda (x) (+ x ,(cadr corr)))
763               (gnus-info-read folderinfo))
764            (gnus-info-read folderinfo)))
765         ;; set other marks
766         (gnus-info-set-marks
767          info
768          (if docorr
769              (mapcar (lambda (cur)
770                          (cons
771                           (car cur)
772                           (nnmairix-map-range
773                            `(lambda (x) (+ x ,(cadr corr)))
774                            (list (cadr cur)))))
775                      (gnus-info-marks folderinfo))
776            (gnus-info-marks folderinfo))))
777       (when (eq readmarks 'unread)
778         (gnus-info-set-read info nil))
779       (when (eq readmarks 'read)
780         (gnus-info-set-read info (gnus-active qualgroup))))
781   t)
782
783 (nnoo-define-skeleton nnmairix)
784
785
786 ;;; === Interactive functions
787
788 (defun nnmairix-create-search-group (server group query threads)
789   "Create on SERVER nnmairix search group GROUP with QUERY.
790 If THREADS is t, include whole threads from found messages.  If
791 called interactively, user will be asked for parameters."
792   (interactive
793    (list
794     (gnus-server-to-method (car (nnmairix-get-server)))
795     (read-string "Group name: ")
796     (read-string "Query: ")
797     (y-or-n-p "Include threads? ")))
798   (when (and (stringp query)
799              (string-match "\\s-" query))
800     (setq query (split-string query)))
801   (when (not (listp query))
802     (setq query (list query)))
803   (when (and server group query)
804     (save-excursion
805       (let ((groupname (gnus-group-prefixed-name group server))
806             info)
807         (set-buffer gnus-group-buffer)
808         (gnus-group-make-group group server)
809         (gnus-group-set-parameter groupname 'query  query)
810         (gnus-group-set-parameter groupname 'threads threads)
811         (nnmairix-update-and-clear-marks groupname)))))
812
813 (defun nnmairix-search-interactive ()
814   "Create mairix search interactively with the minibuffer."
815   (interactive)
816   (let ((char-header nnmairix-interactive-query-parameters)
817         header finished query achar)
818     (while (not finished)
819       (while (not achar)
820         (message "Query (%s): " (nnmairix-create-message-line-for-search))
821           (setq achar (read-char))
822           (when (not (assoc achar char-header))
823             (setq achar nil)))
824       (setq header (read-string
825                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
826         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
827         (setq finished (not (y-or-n-p "Add another search query? "))
828               achar nil))
829     (nnmairix-search
830      (mapconcat 'identity query " ")
831      (car (nnmairix-get-server))
832      (y-or-n-p "Include whole threads? "))))
833
834 (defun nnmairix-create-search-group-from-message ()
835   "Interactively create search group with query based on current message."
836   (interactive)
837   (let ((char-header nnmairix-interactive-query-parameters)
838         (server (nnmairix-backend-to-server gnus-current-select-method))
839          query achar header finished group threads cq)
840     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
841               (not (gnus-buffer-live-p gnus-summary-buffer)))
842       (error "No article or summary buffer"))
843     (when (not server)
844       (error "No nnmairix server found for back end %s:%s"
845              (symbol-name (car gnus-current-select-method))
846              (nth 1 gnus-current-select-method)))
847     (while (not finished)
848       (save-excursion
849         (gnus-summary-toggle-header 1)
850         (while (not achar)
851           (message "Query (%s): " (nnmairix-create-message-line-for-search))
852           (setq achar (read-char))
853           (when (not (assoc achar char-header))
854             (setq achar nil)))
855         (set-buffer gnus-article-buffer)
856         (setq header nil)
857         (when (setq cq (nth 1 (assoc achar char-header)))
858           (setq header
859                 (nnmairix-replace-illegal-chars
860                  (gnus-fetch-field (nth 1 (assoc achar char-header))))))
861         (setq header (read-string
862                       (concat "Match " (nth 3 (assoc achar char-header)) " on: ")
863                       header))
864         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
865         (setq finished (not (y-or-n-p "Add another search query? "))
866               achar nil)))
867     (setq threads (y-or-n-p "Include whole threads? "))
868     (setq group (read-string "Group name: "))
869     (set-buffer gnus-summary-buffer)
870     (message "Creating group %s on server %s with query %s." group
871              (gnus-method-to-server server) (mapconcat 'identity query " "))
872     (nnmairix-create-search-group server group query threads)))
873
874 (defun nnmairix-create-server-and-default-group ()
875   "Interactively create new nnmairix server with default search group.
876 All necessary information will be queried from the user."
877   (interactive)
878   (let* ((name (read-string "Name of the mairix server: "))
879         (server (completing-read "Back end server (TAB for completion): "
880                                  (nnmairix-get-valid-servers)))
881         (mairix (read-string "Command to call mairix: " "mairix"))
882         (defaultgroup (read-string "Default search group: "))
883         (backend (symbol-name (car (gnus-server-to-method server))))
884         (servername (nth 1 (gnus-server-to-method server)))
885         (hidden (and (string-match "^nn\\(imap\\|maildir\\)$" backend)
886                      (y-or-n-p
887                       "Does the back end server work with maildir++ (i.e. hidden directories)? ")))
888         create)
889
890     (apply (intern (format "%s-%s" backend "open-server"))
891            (list servername))
892
893     (when (and hidden
894                (string-match "^\\." defaultgroup))
895       (setq defaultgroup (substring defaultgroup 1)))
896     ;; Create default search group
897     (gnus-group-make-group
898      defaultgroup (list 'nnmairix name  (list 'nnmairix-backend (intern backend))
899                         (list 'nnmairix-backend-server servername)
900                         (list 'nnmairix-mairix-command mairix)
901                         (list 'nnmairix-hidden-folders hidden)
902                         (list 'nnmairix-default-group defaultgroup)))))
903
904 (defun nnmairix-group-change-query-this-group (&optional query)
905   "Set QUERY for group under cursor."
906   (interactive)
907   (let* ((group (gnus-group-group-name))
908          (method (gnus-find-method-for-group group))
909          (oldquery (gnus-group-get-parameter group 'query t)))
910     (if (eq (car method) 'nnmairix)
911         (progn
912           (when (listp oldquery)
913             (setq oldquery (mapconcat 'identity oldquery " ")))
914           (setq query (or query
915                           (read-string "New query: " oldquery)))
916           (when (stringp query)
917             (setq query (split-string query)))
918           (when query
919             (gnus-group-set-parameter group 'query query)
920             (nnmairix-update-and-clear-marks group)))
921       (error "This is no nnmairix group"))))
922
923
924 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
925   "Toggle threads parameter for this group.
926 If THREADS is a positive number, set threads parameter to t.
927 If THREADS is a negative number, set it to nil."
928   (interactive)
929   (let ((group (gnus-group-group-name)))
930     (when (nnmairix-group-toggle-parameter
931            group 'threads "Threads" threads)
932       (nnmairix-update-and-clear-marks group))))
933
934 (defun nnmairix-group-toggle-propmarks-this-group (&optional propmarks)
935   "Toggle marks propagation for this group.
936 If PROPMARKS is a positive number, set parameter to t.
937 If PROPMARKS is a negative number, set it to nil."
938   (interactive)
939   (unless (nnmairix-check-mairix-version "maildirpatch")
940     (error "You need a mairix binary with maildir patch to use this feature.  See docs for details"))
941   (let ((group (gnus-group-group-name)))
942     (when (or (not (string= (gnus-group-short-name group)
943                             (cadr (assoc 'nnmairix-default-group
944                                         (gnus-find-method-for-group group)))))
945               (y-or-n-p "You should not activate marks propagation for the default \
946 search group.  Are you sure? "))
947       (nnmairix-group-toggle-parameter
948        group 'propmarks "Marks propagation" propmarks))))
949
950 (defun nnmairix-group-toggle-allowfast-this-group (&optional allowfast)
951   "Toggle fast entering for this group.
952 If ALLOWFAST is a positive number, set parameter to t.
953 If ALLOWFAST is a negative number, set it to nil."
954   (interactive)
955   (nnmairix-group-toggle-parameter
956    (gnus-group-group-name) 'allow-fast "Fast entering" allowfast))
957
958
959 (defun nnmairix-group-toggle-readmarks-this-group (&optional readmarks)
960   "Toggle read/unread marks for this group.
961 If READMARKS is a positive number, articles will always be read.
962 If READMARKS is a negative number, articles will always be unread.
963 If READMARKS is t or zero, marks will stay unchanged."
964   (interactive)
965   (let*  ((group (gnus-group-group-name))
966           (method (gnus-find-method-for-group group))
967           (readmarks (or readmarks
968                          (gnus-group-get-parameter group 'readmarks))))
969     (if (eq (car method) 'nnmairix)
970         (cond
971          ((or (and (numberp readmarks) (< readmarks 0))
972               (eq readmarks 'read))
973           (gnus-group-set-parameter group 'readmarks 'unread)
974           (nnheader-message 3 "Articles in %s always unread." group))
975          ((or (and (numberp readmarks) (> readmarks 0))
976               (not readmarks))
977               (gnus-group-set-parameter group 'readmarks 'read)
978               (nnheader-message 3 "Articles in %s always read." group))
979          (t
980           (gnus-group-set-parameter group 'readmarks nil)
981           (nnheader-message 3 "Read marks in %s stay unchanged." group)))
982       (error "This is no nnmairix group"))))
983
984
985 (defun nnmairix-search (query &optional server threads)
986   "Sends QUERY to nnmairix backend SERVER, using default its search group.
987
988 Default search group is automatically entered and results are shown.
989 If THREADS is t, enable threads.
990 If THREADS is a negative number, disable threads.
991 Otherwise, leave threads parameter as it is."
992   (interactive (list (read-string "Query: ")))
993   (when (not server)
994     (setq server (car (nnmairix-get-server))))
995   (if (not server)
996       (error "No opened nnmairix server found")
997     (setq server (gnus-server-to-method server)))
998   (nnmairix-open-server (nth 1 server))
999   (let* ((qualgroup (gnus-group-prefixed-name nnmairix-default-group
1000                                               (list 'nnmairix (nth 1 server)))))
1001     (set-buffer gnus-group-buffer)
1002     (when (stringp query)
1003       (setq query (split-string query)))
1004     (gnus-group-set-parameter qualgroup 'query query)
1005     (if (symbolp threads)
1006         (when (eq threads 't)
1007           (gnus-group-set-parameter qualgroup 'threads t))
1008       (when (< threads 0)
1009         (gnus-group-set-parameter qualgroup 'threads nil)))
1010     (nnmairix-update-and-clear-marks qualgroup)
1011     (unless (equal (gnus-active qualgroup) '(1 . 0))
1012       (gnus-group-read-group nil t qualgroup))))
1013
1014 (defun nnmairix-search-thread-this-article ()
1015   "Search thread for the current article.
1016 This is effectively a shortcut for calling `nnmairix-search'
1017 with m:msgid of the current article and enabled threads."
1018   (interactive)
1019   (let* ((server
1020           (nnmairix-backend-to-server gnus-current-select-method))
1021          mid)
1022     (if server
1023         (if (gnus-buffer-live-p gnus-article-buffer)
1024             (progn
1025               (save-excursion
1026                 (set-buffer gnus-article-buffer)
1027                 (gnus-summary-toggle-header 1)
1028                 (setq mid (message-fetch-field "Message-ID")))
1029               (while (string-match "[<>]" mid)
1030                 (setq mid (replace-match "" t t mid)))
1031               (nnmairix-search (concat "m:" mid) server t))
1032           (message "No article buffer."))
1033       (error "No nnmairix server found for back end %s:%s"
1034              (symbol-name (car gnus-current-select-method))
1035              (nth 1 gnus-current-select-method)))))
1036
1037 (defun nnmairix-search-from-this-article ()
1038   "Search messages from sender of the current article.
1039 This is effectively a shortcut for calling `nnmairix-search' with
1040 f:current_from."
1041   (interactive)
1042   (let* ((server
1043           (nnmairix-backend-to-server gnus-current-select-method))
1044          from)
1045     (if server
1046         (if (gnus-buffer-live-p gnus-article-buffer)
1047             (progn
1048               (save-excursion
1049                 (set-buffer gnus-article-buffer)
1050                 (gnus-summary-toggle-header 1)
1051                 (setq from (cadr (gnus-extract-address-components
1052                                   (gnus-fetch-field "From"))))
1053                 (nnmairix-search (concat "f:" from) server -1)))
1054           (message "No article buffer."))
1055       (error "No nnmairix server found for back end %s:%s"
1056              (symbol-name (car gnus-current-select-method))
1057              (nth 1 gnus-current-select-method)))))
1058
1059
1060 (defun nnmairix-purge-old-groups (&optional dontask server)
1061   "Delete mairix search groups which are no longer used.
1062
1063 You may want to call this from time to time if you are creating
1064 and deleting lots of nnmairix groups.  If DONTASK is t, do not ask
1065 before deleting a group on the back end.  SERVER specifies nnmairix server."
1066   (interactive)
1067   (let ((server (or server
1068                     (gnus-server-to-method (car (nnmairix-get-server))))))
1069     (if (nnmairix-open-server (nth 1 server))
1070         (when (nnmairix-call-backend
1071                "request-list" nnmairix-backend-server)
1072           (let (cur qualgroup folder)
1073             (save-excursion
1074               (set-buffer nntp-server-buffer)
1075               (goto-char (point-min))
1076               (while (re-search-forward nnmairix-group-regexp (point-max) t)
1077                 (setq cur (match-string 0)
1078                       qualgroup (gnus-group-prefixed-name
1079                                  (match-string 1) server))
1080                 (when (not (and (gnus-group-entry qualgroup)
1081                                 (string= cur
1082                                          (gnus-group-get-parameter
1083                                           qualgroup 'folder))))
1084                   (when (or dontask
1085                             (y-or-n-p
1086                              (concat "Delete group " cur
1087                                      " on server " nnmairix-backend-server "? ")))
1088                     (nnmairix-call-backend
1089                      "request-delete-group" cur t nnmairix-backend-server)))))))
1090       (message "Couldn't open server %s" (nth 1 server)))))
1091
1092
1093 (defun nnmairix-update-database (&optional servers)
1094   "Call mairix for updating the database for SERVERS.
1095
1096 If SERVERS is nil, do update for all nnmairix servers.  Mairix
1097 will be called asynchronously unless
1098 `nnmairix-mairix-synchronous-update' is t.  Mairix will be called
1099 with `nnmairix-mairix-update-options'."
1100   (interactive)
1101   (let ((servers (or servers
1102                      (nnmairix-get-nnmairix-servers)))
1103         args cur commandsplit)
1104     (while servers
1105       (setq cur (car (pop servers)))
1106       (nnmairix-open-server
1107        (nth 1 (gnus-server-to-method cur)))
1108       (setq commandsplit (split-string nnmairix-mairix-command))
1109       (nnheader-message 7 "Updating mairix database for %s..." cur)
1110       (if nnmairix-mairix-synchronous-update
1111           (progn
1112             (setq args (append (list (car commandsplit) nil
1113                                      (get-buffer nnmairix-mairix-output-buffer)
1114                                      nil)))
1115             (if (> (length commandsplit) 1)
1116                 (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1117               (setq args (append args nnmairix-mairix-update-options)))
1118             (apply 'call-process args)
1119             (nnheader-message 7 "Updating mairix database for %s... done" cur))
1120         (progn
1121           (setq args (append (list cur (get-buffer nnmairix-mairix-output-buffer)
1122                                    (car commandsplit))))
1123           (if (> (length commandsplit) 1)
1124               (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1125             (setq args (append args nnmairix-mairix-update-options)))
1126           (set-process-sentinel (apply 'start-process args)
1127                                 'nnmairix-sentinel-mairix-update-finished))))))
1128
1129 (defun nnmairix-group-delete-recreate-this-group ()
1130   "Deletes and recreates group on the back end.
1131 You can use this function on nnmairix groups which continously
1132 show wrong article counts."
1133   (interactive)
1134   (let* ((group (gnus-group-group-name))
1135          (method (gnus-find-method-for-group group)))
1136     (unless (eq (car method) 'nnmairix)
1137       (error "This is not a nnmairix group"))
1138     (when (y-or-n-p
1139            (format "Really recreate group %s on the back end? " group))
1140       (nnmairix-delete-recreate-group group)
1141       (gnus-group-get-new-news-this-group))))
1142
1143 (defun nnmairix-propagate-marks (&optional server)
1144   "Propagate marks from nnmairix group to original articles.
1145 Unless SERVER is explicitly specified, will use the last opened
1146 nnmairix server. Only marks from current session will be set."
1147   (interactive)
1148   (if server
1149       (nnmairix-open-server server)
1150     (unless (eq (car gnus-current-select-method) 'nnmairix)
1151       (if nnmairix-current-server
1152           (nnmairix-open-server nnmairix-current-server)
1153         (error "No opened nnmairix server"))))
1154   (if nnmairix-marks-cache
1155       (let (number ogroup number-cache method mid-marks temp)
1156         ;; first we get the article numbers
1157         (catch 'problem
1158           (while (setq ogroup (pop nnmairix-marks-cache))
1159             (while (setq mid-marks (pop (cdr ogroup)))
1160               (setq number
1161                     (cdr
1162                      (gnus-request-head (car mid-marks) (car ogroup))))
1163               (unless number
1164                 (nnheader-message
1165                  3 "Unable to set mark: couldn't determine article number for %s in %s"
1166                  (car mid-marks) (car ogroup))
1167                 (throw 'problem nil))
1168               (setq temp (assoc (car ogroup) number-cache))
1169               (if temp
1170                   (catch 'done
1171                     (dolist (cur (cdr temp))
1172                       (when (equal (cdr cur) (list (nth 1 mid-marks) (nth 2 mid-marks)))
1173                         (nconc (car cur) (list number))
1174                         (throw 'done nil)))
1175                     (nconc temp (list (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))))
1176                 (push (list (car ogroup) (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))
1177                       number-cache)))))
1178         ;; now we set the marks
1179         (save-excursion
1180           (set-buffer gnus-group-buffer)
1181           (nnheader-message 5 "nnmairix: Propagating marks...")
1182           (dolist (cur number-cache)
1183             (setq method (gnus-find-method-for-group (car cur)))
1184             (apply (intern (format "%s-%s"
1185                                    (symbol-name (car method))
1186                                    "request-set-mark"))
1187                    (gnus-group-short-name (car cur))
1188                    (cdr cur)
1189                    (list (nth 1 method)))
1190             (gnus-group-jump-to-group (car cur))
1191             (gnus-group-get-new-news-this-group)))
1192         (nnheader-message 5 "nnmairix: Propagating marks... done"))
1193     (nnheader-message 3 "No marks to propagate.")))
1194
1195 (defun nnmairix-update-groups (servername &optional skipdefault updatedb)
1196   "Update all search groups on SERVERNAME.
1197 If SKIPDEFAULT is t, the default search group will not be
1198 updated.
1199 If UPDATEDB is t, database for SERVERNAME will be updated first."
1200   (interactive (list (completing-read "Update groups on server: "
1201                                 (nnmairix-get-nnmairix-servers))))
1202   (save-excursion
1203     (when (string-match ".*:\\(.*\\)" servername)
1204       (setq servername (match-string 1 servername)))
1205     (if (not (assoc (format "nnmairix:%s" servername)
1206                     (nnmairix-get-nnmairix-servers)))
1207         (nnheader-message 3 "Server %s not opened" servername)
1208       (when updatedb
1209         (let ((nnmairix-mairix-synchronous-update t))
1210           (nnmairix-update-database
1211            (list (list (format "nnmairix:%s" servername))))))
1212       (let ((groups (nnmairix-get-groups-from-server servername))
1213             default)
1214         (when skipdefault
1215           (setq default
1216                 (format "nnmairix+%s:%s"
1217                         servername
1218                         (cadr
1219                          (assoc 'nnmairix-default-group
1220                                 (gnus-server-to-method
1221                                  (format "nnmairix:%s" servername)))))))
1222         (dolist (cur groups)
1223           (unless (and skipdefault
1224                        (string= (car cur) default))
1225             (gnus-group-jump-to-group (car cur))
1226             (gnus-group-get-new-news-this-group)))))))
1227
1228 (defun nnmairix-remove-tick-mark-original-article ()
1229   "Remove tick mark from original article.
1230 Marks propagation has to be enabled for this to work."
1231   (interactive)
1232   (unless (eq (car gnus-current-select-method) 'nnmairix)
1233     (error "Not in a nnmairix group"))
1234   (save-excursion
1235     (let ((mid (mail-header-message-id (gnus-summary-article-header)))
1236           groups cur)
1237       (when mid
1238         (setq groups (nnmairix-determine-original-group-from-registry mid))
1239         (unless (or groups
1240                     nnmairix-only-use-registry)
1241           (setq groups
1242                 (nnmairix-determine-original-group-from-path mid nnmairix-current-server)))
1243         (unless groups
1244           (error "Couldn't find original article"))
1245         (dolist (cur groups)
1246           (push `(,cur (,mid del (tick))) nnmairix-marks-cache))
1247         (nnheader-message 5 "Will remove tick mark for %s upon closing." mid)))))
1248
1249 ;;; ==== Helper functions
1250
1251 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
1252   "Request FOLDER on back end for nnmairix QUALGROUP and article number correction."
1253   (save-excursion
1254     (nnmairix-call-backend "request-group" folder nnmairix-backend-server)
1255     (set-buffer nnmairix-mairix-output-buffer)
1256     (goto-char (point-min))
1257     (re-search-forward "^Matched.*messages")
1258     (nnheader-message 7 (match-string 0))
1259     (set-buffer nntp-server-buffer)
1260     (goto-char (point-min))
1261     (let ((status (read (current-buffer)))
1262           (total (read (current-buffer)))
1263           (low (read (current-buffer)))
1264           (high (read (current-buffer)))
1265           (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1266       (if (= status 211)
1267           (progn
1268             ;; Article number correction
1269             (if (and corr
1270                      (> (+ (car (cddr corr)) high) 0))
1271                 (progn
1272                   (when (car corr) ;Group has changed
1273                     (setq corr
1274                           (list nil
1275                                 (car (cddr corr))
1276                                 (+ (car (cddr corr)) high)))
1277                     (gnus-group-set-parameter
1278                      qualgroup 'numcorr corr))
1279                   (setq low (+ low (cadr corr))
1280                         high (+ high (cadr corr))))
1281               (when (member nnmairix-backend
1282                             nnmairix-delete-and-create-on-change)
1283                 (gnus-group-set-parameter
1284                  qualgroup 'numcorr (list nil 0 high))))
1285             (erase-buffer)
1286             (insert (format "%d %d %d %d %s" status total low high
1287                             (gnus-group-real-name qualgroup)))
1288             t)
1289         (progn
1290           (nnheader-report
1291            'nnmairix "Error calling back end on group %s" folder)
1292           nil)))))
1293
1294 (defun nnmairix-call-mairix-binary (command folder searchquery threads)
1295   "Call mairix binary with COMMAND, using FOLDER and SEARCHQUERY.
1296 If THREADS is non-nil, enable full threads."
1297   (let ((args (cons (car command) '(nil t nil))))
1298     (save-excursion
1299       (set-buffer
1300        (get-buffer-create nnmairix-mairix-output-buffer))
1301       (erase-buffer)
1302       (when (> (length command) 1)
1303         (setq args (append args (cdr command))))
1304       (when nnmairix-mairix-search-options
1305         (setq args (append args nnmairix-mairix-search-options)))
1306       ;; If we have a patched mairix binary, call it with "-c"
1307       (when (nnmairix-check-mairix-version "maildirpatch")
1308         (setq args (append args '("-c"))))
1309       (when threads
1310         (setq args (append args '("-t"))))
1311       (apply 'call-process
1312              (append args (list "-o" folder) searchquery)))))
1313
1314 (defun nnmairix-call-mairix-binary-raw (command query)
1315   "Call mairix binary with COMMAND and QUERY in raw mode."
1316   (let ((args (cons (car command) '(nil t nil))))
1317     (save-excursion
1318       (set-buffer
1319        (get-buffer-create nnmairix-mairix-output-buffer))
1320       (erase-buffer)
1321       (when (> (length command) 1)
1322         (setq args (append args (cdr command))))
1323       (setq args (append args '("-r")))
1324       (apply 'call-process
1325              (append args query)))))
1326
1327 (defun nnmairix-get-server ()
1328   "If there exists just one nnmairix server, return its value.
1329 Otherwise, ask user for server."
1330   (let ((openedserver (nnmairix-get-nnmairix-servers)))
1331     (when (not openedserver)
1332       (error "No opened nnmairix server found"))
1333     (if (> (length openedserver) 1)
1334         (progn
1335           (while
1336               (equal '("")
1337                   (setq nnmairix-last-server
1338                         (list (completing-read "Server: " openedserver nil 1
1339                                                (or nnmairix-last-server
1340                                                    "nnmairix:"))))))
1341           nnmairix-last-server)
1342       (car openedserver))))
1343
1344 (defun nnmairix-get-nnmairix-servers (&optional all)
1345   "Return available nnmairix servers.
1346 If ALL is t, return also the unopened/failed ones."
1347   (let ((alist gnus-opened-servers)
1348         server openedserver)
1349     (while alist
1350       (setq server (pop alist))
1351       (when (and server
1352                  (or all
1353                      (eq (cadr server) 'ok))
1354                  (eq (caar server) 'nnmairix)
1355                  (not (member (car server) gnus-ephemeral-servers)))
1356         (setq server
1357               (concat (symbol-name (caar server)) ":" (nth 1 (car server))))
1358         (push (list server) openedserver)))
1359     openedserver))
1360
1361 (defun nnmairix-get-valid-servers ()
1362   "Return list of valid back end servers for nnmairix groups."
1363   (let ((alist gnus-opened-servers)
1364         (mairixservers (nnmairix-get-nnmairix-servers t))
1365         server mserver openedserver occ cur)
1366     ;; Get list of all nnmairix backends (i.e. backends which are
1367     ;; already occupied)
1368     (dolist (cur mairixservers)
1369       (push
1370        (concat
1371         (symbol-name
1372          (cadr (assoc 'nnmairix-backend
1373                       (gnus-server-to-method (car cur)))))
1374          ":"
1375          (cadr (assoc 'nnmairix-backend-server
1376                       (gnus-server-to-method (car cur)))))
1377         occ))
1378     (while alist
1379       (setq server (pop alist))
1380       (setq mserver (gnus-method-to-server (car server)))
1381       ;; If this is the native server, convert it to the real server
1382       ;; name to avoid confusion
1383       (when (string= mserver "native")
1384         (setq mserver (format "%s:%s"
1385                               (caar server)
1386                               (nth 1 (car server)))))
1387       (when (and server
1388                  (eq (cadr server) 'ok)
1389                  (member (caar server) nnmairix-valid-backends)
1390                  (not (member (car server) gnus-ephemeral-servers))
1391                  (not (member (gnus-method-to-server (car server)) occ)))
1392         (push
1393          (list mserver)
1394          openedserver)))
1395     openedserver))
1396
1397 (defun nnmairix-get-groups-from-server (servername)
1398   "Return all groups for nnmairix server SERVERNAME."
1399   (let ((searchstring (format "nnmairix\\+%s:" servername))
1400         groups)
1401     (dolist (cur gnus-newsrc-alist)
1402       (when (string-match searchstring
1403                           (car cur))
1404         (push (list (car cur)) groups)))
1405     groups))
1406
1407 (defun nnmairix-call-backend (func &rest args)
1408   "Call a function FUNC on backend with ARGS."
1409   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
1410
1411 (defun nnmairix-get-backend-folder (group &optional server)
1412   "Return back end GROUP from nnmairix group on SERVER."
1413   (let* ((qualgroup (if server
1414                         (gnus-group-prefixed-name group (list 'nnmairix server))
1415                       group))
1416          (folder (gnus-group-get-parameter qualgroup 'folder)))
1417     folder))
1418
1419 (defun nnmairix-get-numcorr (group &optional server)
1420   "Return values for article number correction nnmairix GROUP on SERVER."
1421   (let* ((qualgroup (if server
1422                         (gnus-group-prefixed-name group (list 'nnmairix server))
1423                       group))
1424          (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1425     corr))
1426
1427
1428 (defun nnmairix-rename-files-consecutively (path)
1429   "Rename all nnml mail files in PATH so that they have consecutive numbers.
1430 This should correct problems of wrong article counts when using
1431 nnmairix with nnml backends."
1432   (let* ((files
1433          (sort
1434           (mapcar 'string-to-number
1435                   (directory-files path nil "[0-9]+" t))
1436           '<))
1437          (lastplusone (car files))
1438          (path (file-name-as-directory path)))
1439     (dolist (cur files)
1440       (when (not (= cur lastplusone))
1441         (rename-file (concat path
1442                              (number-to-string cur))
1443                      (concat path
1444                              (number-to-string lastplusone)))
1445         (setq cur lastplusone))
1446       (setq lastplusone (1+ cur)))))
1447
1448 (defun nnmairix-replace-group-and-numbers (articles backendgroup mairixgroup numc)
1449   "Replace folder names in Xref header and correct article numbers.
1450 Do this for all ARTICLES on BACKENDGROUP.  Replace using
1451 MAIRIXGROUP.  NUMC contains values for article number correction."
1452   (let ((buf (get-buffer-create " *nnmairix buffer*"))
1453         (corr (not (zerop numc)))
1454         (name (buffer-name nntp-server-buffer))
1455         header cur xref)
1456     (save-excursion
1457       (set-buffer buf)
1458       (erase-buffer)
1459       (set-buffer nntp-server-buffer)
1460       (goto-char (point-min))
1461       (nnheader-message 7 "nnmairix: Rewriting headers...")
1462       (mapc
1463        (lambda (article)
1464          (when (or (looking-at (number-to-string article))
1465                    (nnheader-find-nov-line article))
1466            (setq cur (nnheader-parse-nov))
1467            (when corr
1468              (setq article (+ (mail-header-number cur) numc))
1469              (mail-header-set-number cur article))
1470            (setq xref (mail-header-xref cur))
1471            (when (and (stringp xref)
1472                       (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
1473              (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
1474              (mail-header-set-xref cur xref))
1475            (set-buffer buf)
1476            (nnheader-insert-nov cur)
1477            (set-buffer nntp-server-buffer)
1478            (when (not (eobp))
1479              (forward-line 1))))
1480        articles)
1481       (nnheader-message 7 "nnmairix: Rewriting headers... done")
1482       (kill-buffer nntp-server-buffer)
1483       (set-buffer buf)
1484       (rename-buffer name)
1485       (setq nntp-server-buffer buf))))
1486
1487 (defun nnmairix-backend-to-server (server)
1488   "Return nnmairix server most probably responsible for back end SERVER.
1489 User will be asked if this cannot be determined.  Result is saved in
1490 parameter 'indexed-servers of corresponding default search
1491 group."
1492   (let ((allservers (nnmairix-get-nnmairix-servers))
1493         mairixserver found defaultgroup)
1494     (if (> (length allservers) 1)
1495         (progn
1496           ;; If there is more than one nnmairix server, we go through them
1497           (while (and allservers (not found))
1498             (setq mairixserver (gnus-server-to-method (car (pop allservers))))
1499             ;; First we look if SERVER is the backend of current nnmairix server
1500             (setq found (and (eq (cadr (assoc 'nnmairix-backend mairixserver))
1501                                  (car server))
1502                              (string= (cadr (assoc 'nnmairix-backend-server mairixserver))
1503                                       (nth 1 server))))
1504             ;; If that's not the case, we look at 'indexed-servers
1505             ;; variable in default search group
1506             (when (not found)
1507               (setq defaultgroup (cadr (assoc 'nnmairix-default-group mairixserver)))
1508               (setq found (member (gnus-method-to-server server)
1509                                   (gnus-group-get-parameter
1510                                    (gnus-group-prefixed-name defaultgroup
1511                                                              mairixserver)
1512                                    'indexed-servers t)))))
1513           ;; If still not found, we ask user
1514           (when (not found)
1515             (setq mairixserver
1516                   (gnus-server-to-method
1517                    (completing-read
1518                     (format "Cannot determine which nnmairix server indexes %s. Please specify: "
1519                             (gnus-method-to-server server))
1520                     (nnmairix-get-nnmairix-servers) nil nil "nnmairix:")))
1521             ;; Save result in parameter of default search group so that
1522             ;; we don't have to ask again
1523             (setq defaultgroup (gnus-group-prefixed-name
1524                                 (cadr (assoc 'nnmairix-default-group mairixserver)) mairixserver))
1525             (gnus-group-set-parameter
1526              defaultgroup
1527              'indexed-servers
1528              (append (gnus-group-get-parameter defaultgroup 'indexed-servers t)
1529                      (list (gnus-method-to-server server)))))
1530           mairixserver)
1531       ;; If there is just one (or none) nnmairix server:
1532       (gnus-server-to-method (caar allservers)))))
1533
1534
1535 (defun nnmairix-delete-recreate-group (group)
1536   "Delete and recreate folder from GROUP on the back end."
1537   (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1538     (let ((folder (gnus-group-get-parameter group 'folder)))
1539       (if (string-match nnmairix-group-regexp folder)
1540           (progn
1541             (nnmairix-call-backend "open-server"
1542                                    nnmairix-backend-server)
1543             (nnmairix-call-backend "request-delete-group"
1544                                    folder t nnmairix-backend-server)
1545             (nnmairix-call-backend "request-create-group"
1546                                    folder nnmairix-backend-server))
1547         (error "`nnmairix-delete-recreate-group' called on \
1548 non-mairix group.  Check folder parameter")))))
1549
1550 (defun nnmairix-update-and-clear-marks (group &optional method)
1551   "Update group and clear all marks from GROUP using METHOD."
1552   (let ((method (or method
1553                     (gnus-find-method-for-group group)))
1554         (corr (gnus-group-get-parameter group 'numcorr t))
1555         info)
1556     (unless (or (gnus-group-prefixed-p group)
1557                 (not method))
1558       (setq group (gnus-group-prefixed-name group method)))
1559     (if (eq (nth 0 method) 'nnmairix)
1560         (save-excursion
1561           (nnmairix-open-server (nth 1 method))
1562           (set-buffer gnus-group-buffer)
1563           ;; (gnus-group-set-parameter group 'propmarks nil)
1564           (setq info (gnus-get-info group))
1565           ;; Clear active and info
1566           (gnus-set-active group nil)
1567           (gnus-info-clear-data info)
1568           ;; Delete and re-create group if needed
1569           (nnmairix-delete-recreate-group group)
1570           ;; set flag that group has changed for article number correction
1571           (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1572             (when corr
1573               (setcar corr t)
1574               (gnus-group-set-parameter group 'numcorr corr)))
1575           (gnus-group-jump-to-group group)
1576           (gnus-group-get-new-news-this-group))
1577       (error "`nnmairix-update-and-clear-marks' called with non-nnmairix group"))))
1578
1579 (defun nnmairix-sentinel-mairix-update-finished (proc status)
1580   "Sentinel for mairix update process PROC with STATUS."
1581   (if (equal status "finished\n")
1582       (nnheader-message 7 "Updating mairix database for %s... done" proc)
1583     (error "There was an error updating the mairix database for server %s.  \
1584 See %s for details" proc nnmairix-mairix-output-buffer)))
1585
1586 (defun nnmairix-create-message-line-for-search ()
1587   "Create message line for interactive query in minibuffer."
1588   (mapconcat
1589    (function
1590     (lambda (cur)
1591       (format "%c=%s" (car cur) (nth 3 cur))))
1592    nnmairix-interactive-query-parameters ","))
1593
1594 (defun nnmairix-replace-illegal-chars (header)
1595   "Replace illegal characters in HEADER for mairix query."
1596   (when header
1597     (if (> emacs-major-version 20)
1598         (while (string-match "[^-.@/,& [:alnum:]]" header)
1599           (setq header (replace-match "" t t header)))
1600       (while (string-match "[[]{}:<>]" header)
1601         (setq header (replace-match "" t t header))))
1602     (while (string-match "[-& ]" header)
1603       (setq header (replace-match "," t t header)))
1604   header))
1605
1606 (defun nnmairix-group-toggle-parameter (group parameter description &optional par)
1607   "Toggle on GROUP a certain PARAMETER.
1608 DESCRIPTION will be shown to the user with the activation
1609 status.  If PAR is a positive number, the group parameter will be
1610 set to t and to nil otherwise."
1611   (let* ((method (gnus-find-method-for-group group))
1612          (par (or par
1613                   (not (gnus-group-get-parameter group parameter)))))
1614     (if (eq (car method) 'nnmairix)
1615         (progn
1616           (when (numberp par)
1617             (setq par (> par 0)))
1618           (gnus-group-set-parameter group parameter par)
1619           (if par
1620               (message "%s activated for group %s" description group)
1621             (message "%s deactivated for group %s" description group))
1622           t)
1623       (error "This is no nnmairix group")
1624       nil)))
1625
1626 ;; Search for original article helper functions
1627
1628 (defun nnmairix-goto-original-article (&optional no-registry)
1629   "Jump to the original group and display article.
1630 The original group of the article is first determined with the
1631 registry (if enabled).  If the registry is not enabled or did not
1632 find the article or the prefix NO-REGISTRY is non-nil, this
1633 function will try to determine the original group form the path
1634 of the mail file.  The path is obtained through another mairix
1635 search in raw mode."
1636   (interactive "P")
1637   (when (not (eq (car gnus-current-select-method) 'nnmairix))
1638     (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
1639       (if (eq (car method) 'nnmairix)
1640           (nnmairix-open-server (nth 1 method))
1641         (error "Not in a nnmairix group"))))
1642   (when (not (gnus-buffer-live-p gnus-article-buffer))
1643     (error "No article buffer available"))
1644   (let ((server (nth 1 gnus-current-select-method))
1645         mid rval group allgroups)
1646     ;; get message id
1647     (save-excursion
1648       (set-buffer gnus-article-buffer)
1649       (gnus-summary-toggle-header 1)
1650       (setq mid (message-fetch-field "Message-ID"))
1651       ;; first check the registry (if available)
1652       (unless no-registry
1653         (setq allgroups (nnmairix-determine-original-group-from-registry mid)))
1654       (unless (or allgroups
1655                   nnmairix-only-use-registry)
1656         ;; registry was not available or did not find article
1657         ;; so we search again with mairix in raw mode to get filename
1658         (setq allgroups
1659               (nnmairix-determine-original-group-from-path mid server))
1660         ;; if available and allowed, add this entry to the registry
1661         (when (and (not no-registry)
1662                    (boundp 'gnus-registry-install)
1663                    gnus-registry-install)
1664           (dolist (cur allgroups)
1665             (unless (gnus-parameter-registry-ignore cur)
1666               (gnus-registry-add-group mid cur)))))
1667       (if (> (length allgroups) 1)
1668           (setq group
1669                 (completing-read
1670                  "Message exists in more than one group. Choose: "
1671                  allgroups nil t))
1672         (setq group (car allgroups))))
1673     (if group
1674         ;; show article in summary buffer
1675         (nnmairix-show-original-article group mid)
1676       (nnheader-message 3 "Couldn't find original article"))))
1677
1678 (defun nnmairix-determine-original-group-from-registry (mid)
1679   "Try to determinale original group for message-id MID from the registry."
1680   (when (and (boundp 'gnus-registry-install)
1681              gnus-registry-install)
1682     (unless (string-match "^<" mid)
1683       (set mid (concat "<" mid)))
1684     (unless (string-match ">$" mid)
1685       (set mid (concat mid ">")))
1686     (gnus-registry-fetch-groups mid)))
1687
1688 (defun nnmairix-determine-original-group-from-path (mid server)
1689   "Determine original group(s) for message-id MID from the file path.
1690 The file path is obtained through a mairix search for the id on
1691 SERVER."
1692   (nnmairix-open-server server)
1693   (while (string-match "[<>]" mid)
1694     (setq mid (replace-match "" t t mid)))
1695   (let (allgroups)
1696     (if (zerop (nnmairix-call-mairix-binary-raw
1697                 (split-string nnmairix-mairix-command)
1698                 (list (concat "m:" mid))))
1699         (save-excursion
1700           (set-buffer nnmairix-mairix-output-buffer)
1701           (goto-char (point-min))
1702           (while (re-search-forward "^/.*$" nil t)
1703             (push (nnmairix-get-group-from-file-path (match-string 0))
1704                   allgroups)
1705             (forward-line 1)))
1706       (error "Mairix could not find original article.  See buffer %s for details"
1707              nnmairix-mairix-output-buffer))
1708     allgroups))
1709
1710 (defun nnmairix-get-group-from-file-path (file)
1711   "Get group by parsing the message location FILE."
1712   (let (path filename serverbase group maildirflag allgroups)
1713     (string-match "^\\(.*\\)/\\(.*?\\)$" file)
1714     (setq path (expand-file-name (match-string 1 file)))
1715     (setq filename (match-string 2 file))
1716     ;; when we deal with maildir, remove cur/new/tmp from path
1717     (setq maildirflag (string-match ".+\\..+\\..+" filename))
1718     (when maildirflag
1719       (setq path
1720             (replace-regexp-in-string
1721              ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
1722     ;; we first check nnml and nnmaildir servers
1723     (setq
1724      group
1725      (catch 'found
1726        (dolist (cur gnus-opened-servers)
1727          (when (or (and (not maildirflag)
1728                         (eq (caar cur) 'nnml))
1729                    (and maildirflag
1730                         (eq (caar cur) 'nnmaildir)))
1731            ;; get base path from server
1732            (if maildirflag
1733                (setq serverbase (cadr (assoc 'directory (car cur))))
1734              (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
1735              (unless serverbase
1736                (setq serverbase nnml-directory)))
1737            (setq serverbase (file-name-as-directory
1738                              (expand-file-name serverbase)))
1739            (when (string-match (concat serverbase "\\(.*\\)") path)
1740              ;; looks good - rest of the path should be the group
1741              (setq group (match-string 1 path))
1742              (when (string-match "/$" group)
1743                (setq group (replace-match "" t t group)))
1744              (unless maildirflag
1745                ;; for nnml: convert slashes to dots
1746                (while (string-match "/" group)
1747                  (setq group (replace-match "." t t group))))
1748              (setq group (gnus-group-prefixed-name group (car cur)))
1749              ;; check whether this group actually exists
1750              (when (gnus-group-entry group)
1751                (throw 'found group)))))))
1752     (unless group
1753       ;; we haven't found it yet --> look for nnimap groups. Assume
1754       ;; last element of the path is the group. This might fail since
1755       ;; IMAP servers may present groups to the client in arbitrary
1756       ;; ways...
1757       (string-match "^.*/\\.?\\(.*\\)$" path)
1758       (setq group (match-string 1 path))
1759       ;; convert dots to slashes (nested group)
1760       (while (string-match "\\." group)
1761         (setq group (replace-match "/" t t group)))
1762       (dolist (cur gnus-opened-servers)
1763         (when (eq (caar cur) 'nnimap)
1764           (when (gnus-group-entry
1765                  (gnus-group-prefixed-name group (car cur)))
1766             (push
1767              (gnus-group-prefixed-name group (car cur))
1768              allgroups))))
1769       (if (> (length allgroups) 1)
1770           (setq group (completing-read
1771                        "Group %s exists on more than one IMAP server. Choose: "
1772                        allgroups nil t))
1773         (setq group (car allgroups))))
1774     group))
1775
1776 (defun nnmairix-show-original-article (group mid)
1777   "Switch to GROUP and display Article with message-id MID."
1778   (unless (string-match "^<" mid)
1779     (set mid (concat "<" mid)))
1780   (unless (string-match ">$" mid)
1781     (set mid (concat mid ">")))
1782   (when (string-match "Summary" (buffer-name (current-buffer)))
1783     (gnus-summary-exit))
1784   (pop-to-buffer gnus-group-buffer)
1785   (gnus-group-jump-to-group group)
1786   (gnus-summary-read-group group 1 t)
1787   (gnus-summary-refer-article mid)
1788   (gnus-summary-limit-to-headers (format "message-id: %s" mid))
1789   (gnus-summary-select-article)
1790   ;; Force redisplay
1791   (gnus-summary-show-article)
1792   (nnheader-message 5 "Switched to group %s." group))
1793
1794 (defun nnmairix-map-range (func range)
1795   "Map function FUNC on all members of RANGE."
1796   (cond
1797    ((numberp range)
1798     (funcall func range))
1799    (t
1800     (mapcar (lambda (cur)
1801               (cond
1802                ((listp cur)
1803                 (cons
1804                  (funcall func (car cur))
1805                  (funcall func (cdr cur))))
1806                ((numberp cur)
1807                 (funcall func cur))))
1808             range))))
1809
1810 (defun nnmairix-check-mairix-version (version &optional server)
1811   "Check mairix VERSION on SERVER.
1812 If VERSION is a number: specifies the minimum version.
1813 If VERSION is a string: must be contained in mairix version output."
1814   (unless server
1815     (setq server nnmairix-current-server))
1816   (let ((versionstring (cadr (assoc server nnmairix-version-output))))
1817     (unless versionstring
1818       ;; call "mairix -V" to get the version string
1819       (with-temp-buffer
1820         (setq versionstring
1821               (let* ((commandsplit (split-string nnmairix-mairix-command))
1822                      (args (append (list (car commandsplit))
1823                                   `(nil t nil) (cdr commandsplit) '("-V"))))
1824               (apply 'call-process args)
1825               (goto-char (point-min))
1826               (re-search-forward "mairix.*")
1827               (match-string 0))))
1828       ;; save version string for current session
1829       (setq nnmairix-version-output
1830             (append nnmairix-version-output
1831                     (list (list server versionstring)))))
1832     (cond
1833      ((stringp version)
1834       (string-match version versionstring))
1835      ((numberp version)
1836       (<= version (string-to-number
1837                    (progn
1838                      (string-match "mairix \\([0-9\\.]+\\)" versionstring)
1839                      (match-string 1 versionstring))))))))
1840
1841 ;; ==== Widget stuff
1842
1843 (defvar nnmairix-widgets)
1844 (defvar nnmairix-widgets-values nil)
1845
1846 (defun nnmairix-widget-search-from-this-article ()
1847   "Create mairix query based on current article using graphical widgets."
1848   (interactive)
1849   (nnmairix-widget-search
1850    (nnmairix-widget-get-values)))
1851
1852 (defun nnmairix-widget-get-values ()
1853   "Create values for editable fields from current article."
1854   (if (not (gnus-buffer-live-p gnus-article-buffer))
1855       (error "No article buffer available")
1856     (save-excursion
1857       (gnus-summary-toggle-header 1)
1858       (set-buffer gnus-article-buffer)
1859       (mapcar
1860        (function
1861         (lambda (field)
1862           (list (car (cddr field))
1863                 (if (car field)
1864                     (nnmairix-replace-illegal-chars
1865                      (gnus-fetch-field (car field)))
1866                   nil))))
1867        nnmairix-widget-fields-list))))
1868
1869
1870 (defun nnmairix-widget-search (&optional mvalues)
1871   "Create mairix query interactively using graphical widgets.
1872 MVALUES may contain values from current article."
1873   (interactive)
1874   ;; Select window for mairix customization
1875   (funcall nnmairix-widget-select-window-function)
1876   ;; generate widgets
1877   (nnmairix-widget-create-query mvalues)
1878   ;; generate Buttons
1879   (widget-create 'push-button
1880                  :notify
1881                  (if mvalues
1882                      (lambda (&rest ignore)
1883                        (nnmairix-widget-send-query nnmairix-widgets
1884                                                    t))
1885                    (lambda (&rest ignore)
1886                      (nnmairix-widget-send-query nnmairix-widgets
1887                                                  nil)))
1888                  "Send Query")
1889   (widget-insert "   ")
1890   (widget-create 'push-button
1891                  :notify
1892                  (if mvalues
1893                      (lambda (&rest ignore)
1894                        (nnmairix-widget-create-group nnmairix-widgets
1895                                                      t))
1896                    (lambda (&rest ignore)
1897                      (nnmairix-widget-create-group nnmairix-widgets
1898                                                    nil)))
1899                  "Create permanent group")
1900   (widget-insert "   ")
1901   (widget-create 'push-button
1902                  :notify (lambda (&rest ignore)
1903                            (kill-buffer nnmairix-customize-query-buffer))
1904                  "Cancel")
1905   (use-local-map widget-keymap)
1906   (widget-setup)
1907   (goto-char (point-min)))
1908
1909 (defun nnmairix-widget-send-query (widgets &optional withvalues)
1910   "Send query from WIDGETS to mairix binary.
1911 If WITHVALUES is t, query is based on current article."
1912   (nnmairix-search
1913    (nnmairix-widget-make-query-from-widgets widgets)
1914    (if withvalues
1915        (gnus-method-to-server
1916         (nnmairix-backend-to-server gnus-current-select-method))
1917      (car (nnmairix-get-server)))
1918    (if (widget-value (cadr (assoc "Threads" widgets)))
1919        t
1920      -1))
1921   (kill-buffer nnmairix-customize-query-buffer))
1922
1923 (defun nnmairix-widget-create-group (widgets &optional withvalues)
1924   "Create nnmairix group based on current widget values WIDGETS.
1925 If WITHVALUES is t, query is based on current article."
1926   (let ((group (read-string "Name of the group: ")))
1927     (when (not (zerop (length group)))
1928       (nnmairix-create-search-group
1929        (if withvalues
1930            (gnus-method-to-server
1931             (nnmairix-backend-to-server gnus-current-select-method))
1932          (car (nnmairix-get-server)))
1933        group
1934        (nnmairix-widget-make-query-from-widgets widgets)
1935        (widget-value (cadr (assoc "Threads" widgets))))))
1936   (kill-buffer nnmairix-customize-query-buffer))
1937
1938
1939 (defun nnmairix-widget-make-query-from-widgets (widgets)
1940   "Create mairix query from widget values WIDGETS."
1941   (let (query temp flag)
1942     ;; first we do the editable fields
1943     (dolist (cur nnmairix-widget-fields-list)
1944       ;; See if checkbox is checked
1945       (when (widget-value
1946              (cadr (assoc (concat "c" (car (cddr cur))) widgets)))
1947         ;; create query for the field
1948         (push
1949          (concat
1950           (nth 1 cur)
1951           ":"
1952           (nnmairix-replace-illegal-chars
1953            (widget-value
1954            (cadr (assoc (concat "e" (car (cddr cur))) widgets)))))
1955          query)))
1956     ;; Flags
1957     (when (member 'flags nnmairix-widget-other)
1958       (setq flag
1959             (mapconcat
1960              (function
1961               (lambda (flag)
1962                 (setq temp
1963                       (widget-value (cadr (assoc (car flag) nnmairix-widgets))))
1964                 (if (string= "yes" temp)
1965                     (cadr flag)
1966                   (if (string= "no" temp)
1967                       (concat "-" (cadr flag))))))
1968              '(("seen" "s") ("replied" "r") ("flagged" "f")) ""))
1969       (when (not (zerop (length flag)))
1970         (push (concat "F:" flag) query)))
1971     ;; return query string
1972     (mapconcat 'identity query " ")))
1973
1974
1975 (defun nnmairix-widget-create-query (&optional values)
1976   "Create widgets for creating mairix queries.
1977 Fill in VALUES if based on an article."
1978   (let (allwidgets)
1979     (when (get-buffer nnmairix-customize-query-buffer)
1980       (kill-buffer nnmairix-customize-query-buffer))
1981     (switch-to-buffer nnmairix-customize-query-buffer)
1982     (kill-all-local-variables)
1983     (erase-buffer)
1984     (widget-insert "Specify your query for Mairix (check boxes for activating fields):\n\n")
1985     (widget-insert "(Whitespaces will be converted to ',' (i.e. AND). Use '/' for OR.)\n\n")
1986 ;    (make-local-variable 'nnmairix-widgets)
1987     (setq nnmairix-widgets (nnmairix-widget-build-editable-fields values))
1988     (when (member 'flags nnmairix-widget-other)
1989       (widget-insert "\nFlags:\n      Seen:     ")
1990       (nnmairix-widget-add "seen"
1991                            'menu-choice
1992                            :value "ignore"
1993                            '(item "yes") '(item "no") '(item "ignore"))
1994       (widget-insert "      Replied:  ")
1995       (nnmairix-widget-add "replied"
1996                            'menu-choice
1997                            :value "ignore"
1998                            '(item "yes") '(item "no") '(item "ignore"))
1999       (widget-insert "      Ticked:   ")
2000       (nnmairix-widget-add "flagged"
2001                            'menu-choice
2002                            :value "ignore"
2003                            '(item "yes") '(item "no") '(item "ignore")))
2004     (when (member 'threads nnmairix-widget-other)
2005       (widget-insert "\n")
2006       (nnmairix-widget-add "Threads" 'checkbox nil))
2007       (widget-insert " Show full threads\n\n")))
2008
2009 (defun nnmairix-widget-build-editable-fields (values)
2010   "Build editable field widgets in `nnmairix-widget-fields-list'.
2011 VALUES may contain values for editable fields from current article."
2012   ;; how can this be done less ugly?
2013   (let ((ret))
2014     (mapc
2015      (function
2016       (lambda (field)
2017         (setq field (car (cddr field)))
2018         (setq ret
2019               (nconc
2020                (list
2021                 (list
2022                  (concat "c" field)
2023                  (widget-create 'checkbox
2024                                 :tag field
2025                                 :notify (lambda (widget &rest ignore)
2026                                           (nnmairix-widget-toggle-activate widget))
2027                                 nil)))
2028                (list
2029                 (list
2030                  (concat "e" field)
2031                  (widget-create 'editable-field
2032                                 :size 60
2033                                 :format (concat " " field ":"
2034                                                 (make-string (- 11 (length field)) ?\ )
2035                                                 "%v")
2036                                 :value (or (cadr (assoc field values)) ""))))
2037                ret))
2038         (widget-insert "\n")
2039         ;; Deactivate editable field
2040         (widget-apply (cadr (nth 1 ret)) :deactivate)))
2041      nnmairix-widget-fields-list)
2042     ret))
2043
2044 (defun nnmairix-widget-add (name &rest args)
2045   "Add a widget NAME with optional ARGS."
2046   (push
2047    (list name
2048          (apply 'widget-create args))
2049    nnmairix-widgets))
2050
2051 (defun nnmairix-widget-toggle-activate (widget)
2052   "Toggle activation status of WIDGET depending on corresponding checkbox value."
2053   (let ((field (widget-get widget :tag)))
2054     (if (widget-value widget)
2055         (widget-apply
2056          (cadr (assoc (concat "e" field) nnmairix-widgets))
2057          :activate)
2058       (widget-apply
2059        (cadr (assoc (concat "e" field) nnmairix-widgets))
2060        :deactivate)))
2061   (widget-setup))
2062
2063 (provide 'nnmairix)
2064
2065 ;; arch-tag: bb187498-b229-4a55-8c07-6d3f80713e94
2066 ;;; nnmairix.el ends here