Merge from emacs--devo--0
[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.5
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 ;; * When using Maildir: path and filename of a mail can change due to
87 ;; reading/replying/etc.  This can lead to dangling symlinks in
88 ;; nnmairix groups and it depends on the back end how well it deals
89 ;; with that (some IMAP servers out there may not be amused).  Update the
90 ;; database ('G b u') and the group to fix it.
91 ;; * Mairix does only support us-ascii characters.
92
93 ;; TODO/MISSING FEATURES:
94 ;; * Possibility to propagate flags like seen, replied, ticked
95 ;;   to original message
96 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
97 ;; * Maybe use an active file instead of group parameters?
98 ;; * Use "-a" when updating groups which are not newly created
99
100 ;;; Changelog:
101 ;;
102 ;; 02/06/2008 - version 0.5
103 ;;
104 ;;    * New function: nnmairix-goto-original-article. Uses the
105 ;;      registry or the mail file path for determining original group.
106 ;;
107 ;;    * Deal with empty Xref header
108 ;;
109 ;;    * Changed summary mode keybindings since the old ones were
110 ;;      already taken
111 ;;
112 ;;   (Thanks to Tassilo Horn and Ted Zlatanov for their help)
113 ;;
114 ;; 01/07/2008 - version 0.4
115 ;;
116 ;;    * New/fixed doc strings and code cleanup.
117 ;;
118 ;; 18/11/2007 - version 0.3
119 ;;
120 ;;    * Fixed bugs when dealing with nnml and native servers
121 ;;
122 ;;    * Make variables customizable
123 ;;
124 ;; 10/10/2007 - version 0.2
125 ;;
126 ;;    * Use nnml-directory/directory server variables for nnml and
127 ;;    nnmaildir backends as path for search folders. This way it
128 ;;    becomes independent of 'base' setting in .mairixirc (but not for
129 ;;    nnimap).
130 ;;
131 ;;    * As a result: Changed nnmairix-backend-to-server so that user
132 ;;    is asked when more than one nnmairix server exists and we do not
133 ;;    know which one is responsible for current backend.
134 ;;
135 ;;    * Rename files when using nnml backends so that there are no
136 ;;    holes in article numbers. This should fix all problems regarding
137 ;;    wrong article counts with nnml.
138 ;;
139 ;;    * More commands for creating queries (using widgets or the
140 ;;    minibuffer).
141 ;;
142 ;;    * Fixed bug in nnmairix-create-search-group-from-message
143 ;;
144 ;;    * Changed copyright to FSF
145 ;;
146 ;;      (Thanks to Georg C. F. Greve and Bastien for suggestions and
147 ;;      ideas!)
148 ;;
149 ;; 10/03/2007 - version 0.1 - first release
150
151
152 ;;; Code:
153
154 (require 'nnoo)
155 (require 'gnus-group)
156 (require 'gnus-sum)
157 (require 'message)
158 (require 'nnml)
159 (require 'widget)
160
161 (nnoo-declare nnmairix)
162
163 ;;; === Keymaps
164
165 ;; Group mode
166 (defun nnmairix-group-mode-hook ()
167   "Nnmairix group mode keymap."
168   (define-key gnus-group-mode-map
169     (kbd "G b") (make-sparse-keymap))
170   (define-key gnus-group-mode-map
171     (kbd "G b g") 'nnmairix-create-search-group)
172   (define-key gnus-group-mode-map
173     (kbd "G b c") 'nnmairix-create-server-and-default-group)
174   (define-key gnus-group-mode-map
175     (kbd "G b q") 'nnmairix-group-change-query-this-group)
176   (define-key gnus-group-mode-map
177     (kbd "G b t") 'nnmairix-group-toggle-threads-this-group)
178   (define-key gnus-group-mode-map
179     (kbd "G b u") 'nnmairix-update-database)
180   (define-key gnus-group-mode-map
181     (kbd "G b s") 'nnmairix-search)
182   (define-key gnus-group-mode-map
183     (kbd "G b i") 'nnmairix-search-interactive)
184   (define-key gnus-group-mode-map
185     (kbd "G b m") 'nnmairix-widget-search))
186
187 ;; Summary mode
188 (defun nnmairix-summary-mode-hook ()
189   "Nnmairix summary mode keymap."
190   (define-key gnus-summary-mode-map
191     (kbd "$ t") 'nnmairix-search-thread-this-article)
192   (define-key gnus-summary-mode-map
193     (kbd "$ f") 'nnmairix-search-from-this-article)
194   (define-key gnus-summary-mode-map
195     (kbd "$ m") 'nnmairix-widget-search-from-this-article)
196   (define-key gnus-summary-mode-map
197     (kbd "$ g") 'nnmairix-create-search-group-from-message)
198   (define-key gnus-summary-mode-map
199     (kbd "$ o") 'nnmairix-goto-original-article))
200
201 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
202 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
203
204
205 ;; Customizable stuff
206
207 (defgroup nnmairix nil
208   "Backend for the Mairix mail search engine."
209   :group 'gnus)
210
211 (defcustom nnmairix-group-prefix "zz_mairix"
212   "Prefix for mairix search groups on back end server.
213 nnmairix will create these groups automatically on the back end
214 server for each nnmairix search group.  The name on the back end
215 server will be this prefix plus a random number.  You can delete
216 unused nnmairix groups on the back end using
217 `nnmairix-purge-old-groups'."
218   :version "23.1"
219   :type 'string
220   :group 'nnmairix)
221
222 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
223   "Buffer used for mairix output."
224   :version "23.1"
225   :type 'string
226   :group 'nnmairix)
227
228 (defcustom nnmairix-customize-query-buffer "*mairix query*"
229   "Name of the buffer for customizing Mairix queries."
230   :version "23.1"
231   :type 'string
232   :group 'nnmairix)
233
234 (defcustom nnmairix-mairix-update-options '("-F" "-Q")
235   "Options when calling mairix for updating the database.
236 The default is '-F' and '-Q' for making updates faster.  You
237 should call mairix without these options from time to
238 time (e.g. via cron job)."
239   :version "23.1"
240   :type '(repeat string)
241   :group 'nnmairix)
242
243 (defcustom nnmairix-mairix-synchronous-update nil
244   "Set this to t if you want Emacs to wait for mairix updating the database."
245   :version "23.1"
246   :type 'boolean
247   :group 'nnmairix)
248
249 (defcustom nnmairix-rename-files-for-nnml t
250   "Rename nnml mail files so that they are consecutively numbered.
251 When using nnml as backend, mairix might produce holes in the
252 article numbers which will produce wrong article counts by
253 Gnus.  This option controls whether nnmairix should rename the
254 files consecutively."
255   :version "23.1"
256   :type 'boolean
257   :group 'nnmairix)
258
259 (defcustom nnmairix-widget-fields-list
260   '(("from" "f" "From") ("to" "t" "To") ("cc" "c" "Cc")
261     ("subject" "s" "Subject")  ("to" "tc" "To or Cc")
262     ("from" "a" "Address") (nil "b" "Body") (nil "n" "Attachment")
263     ("Message-ID" "m" "Message ID") (nil "s" "Size") (nil "d" "Date"))
264   "Fields that should be editable during interactive query customization.
265
266 Header, corresponding mairix command and description for editable
267 fields in interactive query customization.  The header specifies
268 which header contents should be inserted into the editable field
269 when creating a Mairix query based on the current message (can be
270 nil for disabling this)."
271   :version "23.1"
272   :type '(repeat (list
273                   (choice :tag "Field"
274                           (const :tag "none" nil)
275                           (const :tag "From" "from")
276                           (const :tag "To" "to")
277                           (const :tag "Cc" "cc")
278                           (const :tag "Subject" "subject")
279                           (const :tag "Message ID" "Message-ID"))
280                   (string :tag "Command")
281                   (string :tag "Description")))
282   :group 'nnmairix)
283
284 (defcustom nnmairix-widget-select-window-function
285   (lambda () (select-window (get-largest-window)))
286   "Function for selecting the window for customizing the mairix query.
287 The default chooses the largest window in the current frame."
288   :version "23.1"
289   :type 'function
290   :group 'nnmairix)
291
292 ;; ==== Other variables
293
294 (defvar nnmairix-widget-other
295   '(threads flags)
296   "Other editable mairix commands when using customization widgets.
297 Currently there are 'threads and 'flags.")
298
299 (defvar nnmairix-interactive-query-parameters
300   '((?f "from" "f" "From") (?t "to" "t" "To") (?c "to" "tc" "To or Cc")
301     (?a "from" "a" "Address") (?s "subject" "s" "Subject") (?b nil "b" "Body")
302     (?d nil "d" "Date") (?n nil "n" "Attachment"))
303   "Things that should be editable during interactive query generation.
304 Every list element consists of the following entries: Keystroke,
305 message field (if any), mairix command and description.")
306
307 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
308   "Controls on which backends groups should be deleted and re-created.
309 This variable is a list of back ends where the search group should
310 be completely deleted and re-created when the query or thread
311 parameter changes.  I know this is rather \"brute force\" and maybe
312 even dangerous (you have backups, right?), but it should be used at
313 least for nnimap since some IMAP servers are really not amused when
314 mailbox content changes behind their back.  It usually also corrects
315 the problem of \"holes\" in the article numbers which often lead to a
316 wrong count of total articles shown by Gnus.")
317
318 ;;; === Server variables
319
320 (defvoo nnmairix-backend  nil
321   "Backend where mairix stores its searches.")
322
323 (defvoo nnmairix-backend-server nil
324   "Name of the server where mairix stores its searches.")
325
326 (defvoo nnmairix-mairix-command "mairix"
327   "Command to call mairix for this nnmairix server.")
328
329 (defvoo nnmairix-hidden-folders nil
330   "Set this to t if the back end server uses hidden directories for
331 its maildir mail folders (e.g. the Dovecot IMAP server or mutt).")
332
333 (defvoo nnmairix-default-group nil
334   "Default search group. This is the group which is used for all
335 temporary searches, e.g. nnmairix-search.")
336
337 ;;; === Internal variables
338
339 (defconst nnmairix-group-regexp
340   (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
341   "Regexp for mairix groups on back end.")
342
343 (defconst nnmairix-valid-backends '(nnimap nnml nnmaildir)
344   "Backends supported by nnmairix.
345 Other backends might or might not work.")
346
347 (defvar nnmairix-last-server nil
348   "Last chosen server.")
349
350 (defvar nnmairix-current-server nil
351   "Current server.")
352
353 ;;; === Gnus backend functions
354
355 (nnoo-define-basics nnmairix)
356
357 (gnus-declare-backend "nnmairix" 'mail 'address)
358
359 (deffoo nnmairix-open-server (server &optional definitions)
360   ;; just set server variables
361   (setq nnmairix-current-server server)
362   (nnoo-change-server 'nnmairix server definitions))
363
364 (deffoo nnmairix-request-group (group &optional server fast)
365   ;; Call mairix and request group on back end server
366   (when server (nnmairix-open-server server))
367   (let* ((qualgroup (if server
368                         (gnus-group-prefixed-name group (list 'nnmairix server))
369                       group))
370          (query (gnus-group-get-parameter qualgroup 'query t))
371         (folder (gnus-group-get-parameter qualgroup 'folder))
372         (threads (gnus-group-get-parameter qualgroup 'threads))
373         (backendmethod (gnus-server-to-method
374                         (format "%s:%s" (symbol-name nnmairix-backend)
375                                 nnmairix-backend-server)))
376         rval mfolder folderpath)
377     (cond
378      ((not folder)
379       ;; No folder parameter -> error
380       (nnheader-report 'nnmairix "Check folder parameter for group %s" group)
381       nil)
382      ((not query)
383       ;; No query -> return empty group
384       (save-excursion
385         (set-buffer nntp-server-buffer)
386         (erase-buffer)
387         (insert (concat "211 0 1 0 " group))
388         t))
389      (t
390       ;; For maildir++ folders: create a hidden directory (prepend dot)
391       (setq mfolder (if (and nnmairix-hidden-folders
392                              (not (string-match "^\\." folder)))
393                         (concat "." folder)
394                       folder))
395       ;; For nnml and nnmaildir, precede mfolder with directory where mail
396       ;; is actually stored so that it's independent of 'base' setting
397       ;; in .mairixrc.
398       (when (eq nnmairix-backend 'nnml)
399         (setq folderpath (cadr (assoc 'nnml-directory backendmethod)))
400         ;; if nnml-directory is not explicitly set, use global value
401         (when (not folderpath)
402           (setq folderpath nnml-directory)))
403       (when (eq nnmairix-backend 'nnmaildir)
404         (setq folderpath
405               (cadr (assoc 'directory backendmethod))))
406       (when folderpath
407         (setq mfolder
408               (concat
409                (file-name-as-directory
410                 (expand-file-name
411                  folderpath))
412                mfolder)))
413       ;; If (not fast), call Mairix binary
414       (setq rval
415             (if fast 0
416               (nnmairix-call-mairix-binary
417                (split-string nnmairix-mairix-command)
418                mfolder query threads)))
419       ;; Check return value
420       (cond
421        ((zerop rval)                    ; call was succesful
422         (nnmairix-call-backend
423          "open-server" nnmairix-backend-server)
424         ;; If we're dealing with nnml, rename files
425         ;; consecutively and make new active file for this
426         ;; group
427         (when (eq nnmairix-backend 'nnml)
428           (when nnmairix-rename-files-for-nnml
429             (nnmairix-rename-files-consecutively mfolder))
430           (nnml-generate-nov-databases-directory mfolder))
431         (nnmairix-call-backend
432          "request-scan" folder nnmairix-backend-server)
433         (if fast
434             t
435           (nnmairix-request-group-with-article-number-correction
436            folder qualgroup)))
437        ((and (= rval 1)
438              (save-excursion (set-buffer nnmairix-mairix-output-buffer)
439                              (goto-char (point-min))
440                              (looking-at "^Matched 0 messages")))
441         ;; No messages found -> return empty group
442         (nnheader-message 5 "Mairix: No matches found.")
443         (set-buffer nntp-server-buffer)
444         (erase-buffer)
445         (insert (concat "211 0 1 0 " group))
446         t)
447        ;; Everything else is an error
448        (t
449         (nnheader-report
450          'nnmairix "Error running marix. See buffer %s for details"
451          nnmairix-mairix-output-buffer)
452         nil))))))
453
454
455 (deffoo nnmairix-request-create-group (group &optional server args)
456   (let ((qualgroup (if server (gnus-group-prefixed-name group (list 'nnmairix server))
457                      group))
458         (exist t)
459         (count 0)
460         groupname info)
461     (when server (nnmairix-open-server server))
462     (gnus-group-add-parameter qualgroup '(query . nil))
463     (gnus-group-add-parameter qualgroup '(threads . nil))
464     (while exist
465       (setq count (1+ count))
466       (setq groupname (format "%s-%s-%s" nnmairix-group-prefix group
467                               (number-to-string count)))
468       (setq exist (nnmairix-call-backend
469                    "request-group" groupname nnmairix-backend-server)))
470     (nnmairix-call-backend
471      "request-create-group" groupname nnmairix-backend-server)
472     (gnus-group-add-parameter qualgroup '(folder . nil))
473     (gnus-group-set-parameter qualgroup 'folder groupname))
474   t)
475
476
477 (deffoo nnmairix-retrieve-headers (articles group &optional server fetch-old)
478   (when server (nnmairix-open-server server))
479   (let* ((folder (nnmairix-get-backend-folder group server))
480          (corr (nnmairix-get-numcorr group server))
481          (numcorr 0)
482          rval)
483     (when (and corr
484                (not (zerop (cadr corr)))
485                (numberp (car articles)))
486       (setq numcorr (cadr corr))
487       (setq articles
488             (mapcar
489              (lambda (arg) (- arg numcorr))
490              articles)))
491     (setq rval (nnmairix-call-backend
492                 "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
493     (when (eq rval 'nov)
494       (nnmairix-replace-group-and-numbers articles folder group numcorr)
495       rval)))
496
497 (deffoo nnmairix-request-article (article &optional group server to-buffer)
498   (when server (nnmairix-open-server server))
499   (let ((folder (nnmairix-get-backend-folder group server))
500         (corr (nnmairix-get-numcorr group server)))
501     (when (and
502            (numberp article)
503            corr
504            (not (zerop (cadr corr))))
505       (setq article (- article (cadr corr))))
506     (nnmairix-call-backend
507      "request-article" article folder nnmairix-backend-server to-buffer))
508   t)
509
510 (deffoo nnmairix-close-group (group &optional server)
511   ;; Should we do something here?
512   nil)
513
514
515 (deffoo nnmairix-request-list (&optional server)
516   (when server (nnmairix-open-server server))
517   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
518       (let (cpoint cur qualgroup folder)
519         (save-excursion
520           (set-buffer nntp-server-buffer)
521           (goto-char (point-min))
522           (setq cpoint (point))
523           (while (re-search-forward nnmairix-group-regexp (point-max) t)
524             (setq cur (match-string 1)
525                   qualgroup (gnus-group-prefixed-name cur
526                                                       (list 'nnmairix server)))
527             (if (and (gnus-group-entry qualgroup)
528                      (string= (match-string 0)
529                               (gnus-group-get-parameter qualgroup 'folder)))
530                 (progn
531                   (replace-match cur)
532                   (delete-region cpoint (point-at-bol))
533                   (forward-line)
534                   (setq cpoint (point)))
535               (forward-line)))
536           (delete-region cpoint (point-max)))
537         t)
538     nil))
539
540
541 (nnoo-define-skeleton nnmairix)
542
543
544 ;;; === Interactive functions
545
546 (defun nnmairix-create-search-group (server group query threads)
547   "Create on SERVER nnmairix search group GROUP with QUERY.
548 If THREADS is t, include whole threads from found messages.  If
549 called interactively, user will be asked for parameters."
550   (interactive
551    (list
552     (gnus-server-to-method (car (nnmairix-get-server)))
553     (read-string "Group name: ")
554     (read-string "Query: ")
555     (y-or-n-p "Include threads? ")))
556   (when (and (stringp query)
557              (string-match "\\s-" query))
558     (setq query (split-string query)))
559   (when (not (listp query))
560     (setq query (list query)))
561   (when (and server group query)
562     (save-excursion
563       (let ((groupname (gnus-group-prefixed-name group server))
564             info)
565         (set-buffer gnus-group-buffer)
566         (gnus-group-make-group group server)
567         (gnus-group-set-parameter groupname 'query  query)
568         (gnus-group-set-parameter groupname 'threads threads)
569         (nnmairix-update-and-clear-marks groupname)))))
570
571 (defun nnmairix-search-interactive ()
572   "Create mairix search interactively with the minibuffer."
573   (interactive)
574   (let ((char-header nnmairix-interactive-query-parameters)
575         header finished query achar)
576     (while (not finished)
577       (while (not achar)
578         (message "Query (%s): " (nnmairix-create-message-line-for-search))
579           (setq achar (read-char))
580           (when (not (assoc achar char-header))
581             (setq achar nil)))
582       (setq header (read-string
583                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
584         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
585         (setq finished (not (y-or-n-p "Add another search query? "))
586               achar nil))
587     (nnmairix-search
588      (mapconcat 'identity query " ")
589      (car (nnmairix-get-server))
590      (y-or-n-p "Include whole threads? "))))
591
592 (defun nnmairix-create-search-group-from-message ()
593   "Interactively create search group with query based on current message."
594   (interactive)
595   (let ((char-header nnmairix-interactive-query-parameters)
596         (server (nnmairix-backend-to-server gnus-current-select-method))
597          query achar header finished group threads cq)
598     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
599               (not (gnus-buffer-live-p gnus-summary-buffer)))
600       (error "No article or summary buffer"))
601     (when (not server)
602       (error "No nnmairix server found for back end %s:%s"
603              (symbol-name (car gnus-current-select-method))
604              (nth 1 gnus-current-select-method)))
605     (while (not finished)
606       (save-excursion
607         (gnus-summary-toggle-header 1)
608         (while (not achar)
609           (message "Query (%s): " (nnmairix-create-message-line-for-search))
610           (setq achar (read-char))
611           (when (not (assoc achar char-header))
612             (setq achar nil)))
613         (set-buffer gnus-article-buffer)
614         (setq header nil)
615         (when (setq cq (nth 1 (assoc achar char-header)))
616           (setq header
617                 (nnmairix-replace-illegal-chars
618                  (gnus-fetch-field (nth 1 (assoc achar char-header))))))
619         (setq header (read-string
620                       (concat "Match " (nth 3 (assoc achar char-header)) " on: ")
621                       header))
622         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
623         (setq finished (not (y-or-n-p "Add another search query? "))
624               achar nil)))
625     (setq threads (y-or-n-p "Include whole threads? "))
626     (setq group (read-string "Group name: "))
627     (set-buffer gnus-summary-buffer)
628     (message "Creating group %s on server %s with query %s." group
629              (gnus-method-to-server server) (mapconcat 'identity query " "))
630     (nnmairix-create-search-group server group query threads)))
631
632 (defun nnmairix-create-server-and-default-group ()
633   "Interactively create new nnmairix server with default search group.
634 All necessary information will be queried from the user."
635   (interactive)
636   (let* ((name (read-string "Name of the mairix server: "))
637         (server (completing-read "Back end server (TAB for completion): "
638                                  (nnmairix-get-valid-servers)))
639         (mairix (read-string "Command to call mairix: " "mairix"))
640         (defaultgroup (read-string "Default search group: "))
641         (backend (symbol-name (car (gnus-server-to-method server))))
642         (servername (nth 1 (gnus-server-to-method server)))
643         (hidden (and (string-match "^nn\\(imap\\|maildir\\)$" backend)
644                      (y-or-n-p
645                       "Does the back end server work with maildir++ (i.e. hidden directories)? ")))
646         create)
647
648     (apply (intern (format "%s-%s" backend "open-server"))
649            (list servername))
650
651     (when (and hidden
652                (string-match "^\\." defaultgroup))
653       (setq defaultgroup (substring defaultgroup 1)))
654     ;; Create default search group
655     (gnus-group-make-group
656      defaultgroup (list 'nnmairix name  (list 'nnmairix-backend (intern backend))
657                         (list 'nnmairix-backend-server servername)
658                         (list 'nnmairix-mairix-command mairix)
659                         (list 'nnmairix-hidden-folders hidden)
660                         (list 'nnmairix-default-group defaultgroup)))))
661
662
663 (defun nnmairix-group-change-query-this-group (&optional query)
664   "Set QUERY for group under cursor."
665   (interactive)
666   (let* ((group (gnus-group-group-name))
667          (method (gnus-find-method-for-group group))
668          (oldquery (gnus-group-get-parameter group 'query t)))
669     (if (eq (car method) 'nnmairix)
670         (progn
671           (when (listp oldquery)
672             (setq oldquery (mapconcat 'identity oldquery " ")))
673           (setq query (or query
674                           (read-string "New query: " oldquery)))
675           (when (stringp query)
676             (setq query (split-string query)))
677           (when query
678             (gnus-group-set-parameter group 'query query)
679             (nnmairix-update-and-clear-marks group)))
680       (error "This is no nnmairix group"))))
681
682
683 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
684   "Toggle threads parameter for this group.
685 If THREADS is a positive number, set threads parameter to t.
686 If THREADS is a negative number, set it to nil."
687   (interactive)
688   (let* ((group (gnus-group-group-name))
689          (method (gnus-find-method-for-group group))
690          (getthreads (or threads
691                         (not (gnus-group-get-parameter group 'threads)))))
692     (if (eq (car method) 'nnmairix)
693         (progn
694           (when (numberp getthreads)
695             (setq getthreads (> getthreads 0)))
696           (gnus-group-set-parameter group 'threads getthreads)
697           (if getthreads
698               (message "Threads activated for group %s" group)
699             (message "Threads deacitavted for group %s" group))
700           (nnmairix-update-and-clear-marks group))
701       (error "This is no nnmairix group"))))
702
703
704 (defun nnmairix-search (query &optional server threads)
705   "Sends QUERY to nnmairix backend SERVER, using default its search group.
706
707 Default search group is automatically entered and results are shown.
708 If THREADS is t, enable threads.
709 If THREADS is a negative number, disable threads.
710 Otherwise, leave threads parameter as it is."
711   (interactive (list (read-string "Query: ")))
712   (when (not server)
713     (setq server (car (nnmairix-get-server))))
714   (if (not server)
715       (error "No opened nnmairix server found")
716     (setq server (gnus-server-to-method server)))
717   (nnmairix-open-server (nth 1 server))
718   (let* ((qualgroup (gnus-group-prefixed-name nnmairix-default-group
719                                               (list 'nnmairix (nth 1 server)))))
720     (set-buffer gnus-group-buffer)
721     (when (stringp query)
722       (setq query (split-string query)))
723     (gnus-group-set-parameter qualgroup 'query query)
724     (if (symbolp threads)
725         (when (eq threads 't)
726           (gnus-group-set-parameter qualgroup 'threads t))
727       (when (< threads 0)
728         (gnus-group-set-parameter qualgroup 'threads nil)))
729     (nnmairix-update-and-clear-marks qualgroup)
730     (when (not (zerop (gnus-group-unread qualgroup)))
731       (gnus-group-read-group nil t qualgroup))))
732
733 (defun nnmairix-search-thread-this-article ()
734   "Search thread for the current article.
735 This is effectively a shortcut for calling `nnmairix-search'
736 with m:msgid of the current article and enabled threads."
737   (interactive)
738   (let* ((server
739           (nnmairix-backend-to-server gnus-current-select-method))
740          mid)
741     (if server
742         (if (gnus-buffer-live-p gnus-article-buffer)
743             (progn
744               (save-excursion
745                 (set-buffer gnus-article-buffer)
746                 (gnus-summary-toggle-header 1)
747                 (setq mid (message-fetch-field "Message-ID")))
748               (while (string-match "[<>]" mid)
749                 (setq mid (replace-match "" t t mid)))
750               (nnmairix-search (concat "m:" mid) server t))
751           (message "No article buffer."))
752       (error "No nnmairix server found for back end %s:%s"
753              (symbol-name (car gnus-current-select-method))
754              (nth 1 gnus-current-select-method)))))
755
756 (defun nnmairix-search-from-this-article ()
757   "Search messages from sender of the current article.
758 This is effectively a shortcut for calling `nnmairix-search' with
759 f:current_from."
760   (interactive)
761   (let* ((server
762           (nnmairix-backend-to-server gnus-current-select-method))
763          from)
764     (if server
765         (if (gnus-buffer-live-p gnus-article-buffer)
766             (progn
767               (save-excursion
768                 (set-buffer gnus-article-buffer)
769                 (gnus-summary-toggle-header 1)
770                 (setq from (cadr (gnus-extract-address-components
771                                   (gnus-fetch-field "From"))))
772                 (nnmairix-search (concat "f:" from) server -1)))
773           (message "No article buffer."))
774       (error "No nnmairix server found for back end %s:%s"
775              (symbol-name (car gnus-current-select-method))
776              (nth 1 gnus-current-select-method)))))
777
778
779 (defun nnmairix-purge-old-groups (&optional dontask server)
780   "Delete mairix search groups which are no longer used.
781
782 You may want to call this from time to time if you are creating
783 and deleting lots of nnmairix groups.  If DONTASK is t, do not ask
784 before deleting a group on the back end.  SERVER specifies nnmairix server."
785   (interactive)
786   (let ((server (or server
787                     (gnus-server-to-method (car (nnmairix-get-server))))))
788     (if (nnmairix-open-server (nth 1 server))
789         (when (nnmairix-call-backend
790                "request-list" nnmairix-backend-server)
791           (let (cur qualgroup folder)
792             (save-excursion
793               (set-buffer nntp-server-buffer)
794               (goto-char (point-min))
795               (while (re-search-forward nnmairix-group-regexp (point-max) t)
796                 (setq cur (match-string 0)
797                       qualgroup (gnus-group-prefixed-name
798                                  (match-string 1) server))
799                 (when (not (and (gnus-group-entry qualgroup)
800                                 (string= cur
801                                          (gnus-group-get-parameter
802                                           qualgroup 'folder))))
803                   (when (or dontask
804                             (y-or-n-p
805                              (concat "Delete group " cur
806                                      " on server " nnmairix-backend-server "? ")))
807                     (nnmairix-call-backend
808                      "request-delete-group" cur t nnmairix-backend-server)))))))
809       (message "Couldn't open server %s" (nth 1 server)))))
810
811
812 (defun nnmairix-update-database (&optional servers)
813   "Call mairix for updating the database for SERVERS.
814
815 If SERVERS is nil, do update for all nnmairix servers.  Mairix
816 will be called asynchronously unless
817 `nnmairix-mairix-synchronous-update' is t.  Mairix will be called
818 with `nnmairix-mairix-update-options'."
819   (interactive)
820   (let ((servers (or servers
821                      (nnmairix-get-nnmairix-servers)))
822         args cur commandsplit)
823     (while servers
824       (setq cur (car (pop servers)))
825       (nnmairix-open-server
826        (nth 1 (gnus-server-to-method cur)))
827       (setq commandsplit (split-string nnmairix-mairix-command))
828       (nnheader-message 7 "Updating mairix database for %s..." cur)
829       (if nnmairix-mairix-synchronous-update
830           (progn
831             (setq args (append (list (car commandsplit) nil
832                                      (get-buffer nnmairix-mairix-output-buffer)
833                                      nil)))
834             (if (> (length commandsplit) 1)
835                 (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
836               (setq args (append args nnmairix-mairix-update-options)))
837             (apply 'call-process args)
838             (nnheader-message 7 "Updating mairix database for %s... done" cur))
839         (progn
840           (setq args (append (list cur (get-buffer nnmairix-mairix-output-buffer)
841                                    (car commandsplit))))
842           (if (> (length commandsplit) 1)
843               (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
844             (setq args (append args nnmairix-mairix-update-options)))
845           (set-process-sentinel (apply 'start-process args)
846                                 'nnmairix-sentinel-mairix-update-finished))))))
847
848 ;; Silence byte-compiler.
849 (eval-when-compile
850   (defvar gnus-registry-install)
851   (autoload 'gnus-registry-fetch-group "gnus-registry"))
852
853 (defun nnmairix-goto-original-article (&optional no-registry)
854   "Jump to the original group and display article.
855 The original group of the article is first determined with the
856 registry (if enabled). If the registry is not enabled or did not
857 find the article or the prefix NO-REGISTRY is non-nil, this
858 function will try to determine the original group form the path
859 of the mail file. The path is obtained through another mairix
860 search in raw mode."
861   (interactive "P")
862   (when (not (eq (car gnus-current-select-method) 'nnmairix))
863     (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
864       (if (eq (car method) 'nnmairix)
865           (nnmairix-open-server (nth 1 method))
866         (error "Not in a nnmairix group"))))
867   (when (not (gnus-buffer-live-p gnus-article-buffer))
868     (error "No article buffer available"))
869   (let ((server (nth 1 gnus-current-select-method))
870         mid rval group allgroups)
871     ;; get message id
872     (save-excursion
873       (set-buffer gnus-article-buffer)
874       (gnus-summary-toggle-header 1)
875       (setq mid (message-fetch-field "Message-ID"))
876       ;; first check the registry (if available)
877       (when (and (boundp 'gnus-registry-install)
878                  gnus-registry-install
879                  (not no-registry))
880         (setq group (gnus-registry-fetch-group mid)))
881       (while (string-match "[<>]" mid)
882         (setq mid (replace-match "" t t mid)))
883       (unless group
884         ;; registry was not available or did not find article
885         ;; so we search again with mairix in raw mode to get filename
886         (nnmairix-open-server server)
887         (setq rval
888               (nnmairix-call-mairix-binary-raw
889                (split-string nnmairix-mairix-command)
890                (list (concat "m:" mid))))
891         (if (zerop rval)
892             ;; determine original group(s) from filename
893             (save-excursion
894               (set-buffer nnmairix-mairix-output-buffer)
895               (goto-char (point-min))
896               (while (looking-at "/")
897                 (push (nnmairix-determine-original-group)
898                       allgroups)
899                 (forward-line 1))
900               (if (> (length allgroups) 1)
901                   (setq group
902                         (completing-read
903                          "Message exists in more than one group. Choose: "
904                          allgroups nil t))
905                 (setq group (car allgroups))))
906           (error "Mairix could not find original article. See buffer %s for details"
907                  nnmairix-mairix-output-buffer))))
908     (if group
909         ;; show article in summary buffer
910         (nnmairix-show-original-article group mid)
911       (message "Couldn't find original article"))))
912
913 (defun nnmairix-determine-original-group ()
914   "Try to determine to original group from the file path."
915   (let (path filename serverbase group maildirflag allgroups)
916     (re-search-forward "^\\(.*\\)/\\(.*?\\)$")
917     (setq path (expand-file-name (match-string 1)))
918     (setq filename (match-string 2))
919     ;; when we deal with maildir, remove cur/new/tmp from path
920     (setq maildirflag (string-match ".+\\..+\\..+" filename))
921     (when maildirflag
922       (setq path
923             (replace-regexp-in-string
924              ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
925     ;; we first check nnml and nnmaildir servers
926     (setq
927      group
928      (catch 'found
929        (dolist (cur gnus-opened-servers)
930          (when (or (and (not maildirflag)
931                         (eq (caar cur) 'nnml))
932                    (and maildirflag
933                         (eq (caar cur) 'nnmaildir)))
934            ;; get base path from server
935            (if maildirflag
936                (setq serverbase (cadr (assoc 'directory (car cur))))
937              (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
938              (when (not serverbase)
939                (setq serverbase nnml-directory)))
940            (setq serverbase (file-name-as-directory
941                              (expand-file-name serverbase)))
942            (when (string-match (concat serverbase "\\(.*\\)") path)
943              ;; looks good - rest of the path should be the group
944              (setq group (match-string 1 path))
945              (when (string-match "/$" group)
946                (setq group (replace-match "" t t group)))
947              (when (not maildirflag)
948                ;; for nnml: convert slashes to dots
949                (while (string-match "/" group)
950                  (setq group (replace-match "." t t group))))
951              (setq group (gnus-group-prefixed-name group (car cur)))
952              ;; check whether this group actually exists
953              (when (gnus-group-entry group)
954                (throw 'found group)))))))
955     (unless group
956       ;; we haven't found it yet --> look for nnimap groups
957       ;; assume last element of the path is the group
958       (string-match "^.*/\\.?\\(.*\\)$" path)
959       (setq group (match-string 1 path))
960       ;; convert dots to slashes (nested group)
961       (while (string-match "\\." group)
962         (setq group (replace-match "/" t t group)))
963       (dolist (cur gnus-opened-servers)
964         (when (eq (caar cur) 'nnimap)
965           (when (gnus-group-entry
966                  (gnus-group-prefixed-name group (car cur)))
967             (push
968              (gnus-group-prefixed-name group (car cur))
969              allgroups))))
970       (if (> (length allgroups) 1)
971           (setq group (completing-read
972                        "Group %s exists on more than one IMAP server. Choose: "
973                        allgroups nil t))
974         (setq group (car allgroups))))
975     group))
976
977
978 ;;; ==== Helper functions
979
980 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
981   "Request FOLDER on backend for nnmairix QUALGROUP and article number correction."
982   (save-excursion
983     (nnmairix-call-backend "request-group" folder nnmairix-backend-server)
984     (set-buffer nnmairix-mairix-output-buffer)
985     (goto-char (point-min))
986     (re-search-forward "^Matched.*messages")
987     (nnheader-message 7 (match-string 0))
988     (set-buffer nntp-server-buffer)
989     (goto-char (point-min))
990     (let ((status (read (current-buffer)))
991           (total (read (current-buffer)))
992           (low (read (current-buffer)))
993           (high (read (current-buffer)))
994           (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
995       (if (= status 211)
996           (progn
997             ;; Article number correction
998             (if (and corr
999                      (> (+ (car (cddr corr)) high) 0))
1000                 (progn
1001                   (when (car corr) ;Group has changed
1002                     (setq corr
1003                           (list nil
1004                                 (car (cddr corr))
1005                                 (+ (car (cddr corr)) high)))
1006                     (gnus-group-set-parameter
1007                      qualgroup 'numcorr corr))
1008                   (setq low (+ low (cadr corr))
1009                         high (+ high (cadr corr))))
1010               (when (member nnmairix-backend
1011                             nnmairix-delete-and-create-on-change)
1012                 (gnus-group-set-parameter
1013                  qualgroup 'numcorr (list nil 0 high))))
1014             (erase-buffer)
1015             (insert (format "%d %d %d %d %s" status total low high
1016                             (gnus-group-real-name qualgroup)))
1017             t)
1018         (progn
1019           (nnheader-report
1020            'nnmairix "Error calling back end on group %s" folder)
1021           nil)))))
1022
1023 (defun nnmairix-call-mairix-binary (command folder query threads)
1024   "Call mairix binary with COMMAND, using FOLDER and QUERY.
1025 If THREADS is non-nil, enable full threads."
1026   (let ((args (cons (car command) '(nil t nil))))
1027     (save-excursion
1028       (set-buffer
1029        (get-buffer-create nnmairix-mairix-output-buffer))
1030       (erase-buffer)
1031       (when (> (length command) 1)
1032         (setq args (append args (cdr command))))
1033       (when threads
1034         (setq args (append args '("-t"))))
1035       (apply 'call-process
1036              (append args (list "-o" folder) query)))))
1037
1038 (defun nnmairix-call-mairix-binary-raw (command query)
1039   "Call mairix binary with COMMAND and QUERY in raw mode."
1040   (let ((args (cons (car command) '(nil t nil))))
1041     (save-excursion
1042       (set-buffer
1043        (get-buffer-create nnmairix-mairix-output-buffer))
1044       (erase-buffer)
1045       (when (> (length command) 1)
1046         (setq args (append args (cdr command))))
1047       (setq args (append args '("-r")))
1048       (apply 'call-process
1049              (append args query)))))
1050
1051 (defun nnmairix-get-server ()
1052   "If there exists just one nnmairix server, return its value.
1053 Otherwise, ask user for server."
1054   (let ((openedserver (nnmairix-get-nnmairix-servers)))
1055     (when (not openedserver)
1056       (error "No opened nnmairix server found"))
1057     (if (> (length openedserver) 1)
1058         (progn
1059           (while
1060               (equal '("")
1061                   (setq nnmairix-last-server
1062                         (list (completing-read "Server: " openedserver nil 1
1063                                                (or nnmairix-last-server
1064                                                    "nnmairix:"))))))
1065           nnmairix-last-server)
1066       (car openedserver))))
1067
1068 (defun nnmairix-get-nnmairix-servers (&optional all)
1069   "Return available nnmairix servers.
1070 If ALL is t, return also the unopened/failed ones."
1071   (let ((alist gnus-opened-servers)
1072         server openedserver)
1073     (while alist
1074       (setq server (pop alist))
1075       (when (and server
1076                  (or all
1077                      (eq (cadr server) 'ok))
1078                  (eq (caar server) 'nnmairix)
1079                  (not (member (car server) gnus-ephemeral-servers)))
1080         (setq server
1081               (concat (symbol-name (caar server)) ":" (nth 1 (car server))))
1082         (push (list server) openedserver)))
1083     openedserver))
1084
1085
1086 (defun nnmairix-get-valid-servers ()
1087   "Return list of valid backend servers for nnmairix groups."
1088   (let ((alist gnus-opened-servers)
1089         (mairixservers (nnmairix-get-nnmairix-servers t))
1090         server mserver openedserver occ cur)
1091     ;; Get list of all nnmairix backends (i.e. backends which are
1092     ;; already occupied)
1093     (dolist (cur mairixservers)
1094       (push
1095        (concat
1096         (symbol-name
1097          (cadr (assoc 'nnmairix-backend
1098                       (gnus-server-to-method (car cur)))))
1099          ":"
1100          (cadr (assoc 'nnmairix-backend-server
1101                       (gnus-server-to-method (car cur)))))
1102         occ))
1103     (while alist
1104       (setq server (pop alist))
1105       (setq mserver (gnus-method-to-server (car server)))
1106       ;; If this is the native server, convert it to the real server
1107       ;; name to avoid confusion
1108       (when (string= mserver "native")
1109         (setq mserver (format "%s:%s"
1110                               (caar server)
1111                               (nth 1 (car server)))))
1112       (when (and server
1113                  (eq (cadr server) 'ok)
1114                  (member (caar server) nnmairix-valid-backends)
1115                  (not (member (car server) gnus-ephemeral-servers))
1116                  (not (member (gnus-method-to-server (car server)) occ)))
1117         (push
1118          (list mserver)
1119          openedserver)))
1120     openedserver))
1121
1122 (defun nnmairix-call-backend (func &rest args)
1123   "Call a function FUNC on backend with ARGS."
1124   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
1125
1126 (defun nnmairix-get-backend-folder (group &optional server)
1127   "Return back end GROUP from nnmairix group on SERVER."
1128   (let* ((qualgroup (if server
1129                         (gnus-group-prefixed-name group (list 'nnmairix server))
1130                       group))
1131          (folder (gnus-group-get-parameter qualgroup 'folder)))
1132     folder))
1133
1134 (defun nnmairix-get-numcorr (group &optional server)
1135   "Return values for article number correction nnmairix GROUP on SERVER."
1136   (let* ((qualgroup (if server
1137                         (gnus-group-prefixed-name group (list 'nnmairix server))
1138                       group))
1139          (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1140     corr))
1141
1142
1143 (defun nnmairix-rename-files-consecutively (path)
1144   "Rename all nnml mail files in PATH so that they have consecutive numbers.
1145 This should correct problems of wrong article counts when using
1146 nnmairix with nnml backends."
1147   (let* ((files
1148          (sort
1149           (mapcar 'string-to-number
1150                   (directory-files path nil "[0-9]+" t))
1151           '<))
1152          (lastplusone (car files))
1153          (path (file-name-as-directory path)))
1154     (dolist (cur files)
1155       (when (not (= cur lastplusone))
1156         (rename-file (concat path
1157                              (number-to-string cur))
1158                      (concat path
1159                              (number-to-string lastplusone)))
1160         (setq cur lastplusone))
1161       (setq lastplusone (1+ cur)))))
1162
1163 (defun nnmairix-replace-group-and-numbers (articles backendgroup mairixgroup numc)
1164   "Replace folder names in Xref header and correct article numbers.
1165 Do this for all ARTICLES on BACKENDGROUP.  Replace using
1166 MAIRIXGROUP.  NUMC contains values for article number correction."
1167   (let ((buf (get-buffer-create " *nnmairix buffer*"))
1168         (corr (not (zerop numc)))
1169         (name (buffer-name nntp-server-buffer))
1170         header cur xref)
1171     (save-excursion
1172       (set-buffer buf)
1173       (erase-buffer)
1174       (set-buffer nntp-server-buffer)
1175       (goto-char (point-min))
1176       (nnheader-message 7 "nnmairix: Rewriting headers...")
1177       (mapc
1178        (lambda (article)
1179          (when (or (looking-at (number-to-string article))
1180                    (nnheader-find-nov-line article))
1181            (setq cur (nnheader-parse-nov))
1182            (when corr
1183              (setq article (+ (mail-header-number cur) numc))
1184              (mail-header-set-number cur article))
1185            (setq xref (mail-header-xref cur))
1186            (when (and (stringp xref)
1187                       (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
1188              (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
1189              (mail-header-set-xref cur xref))
1190            (set-buffer buf)
1191            (nnheader-insert-nov cur)
1192            (set-buffer nntp-server-buffer)
1193            (when (not (eobp))
1194              (forward-line 1))))
1195        articles)
1196       (nnheader-message 7 "nnmairix: Rewriting headers... done")
1197       (kill-buffer nntp-server-buffer)
1198       (set-buffer buf)
1199       (rename-buffer name)
1200       (setq nntp-server-buffer buf))))
1201
1202 (defun nnmairix-backend-to-server (server)
1203   "Return nnmairix server most probably responsible for back end SERVER.
1204 User will be asked if this cannot be determined.  Result is saved in
1205 parameter 'indexed-servers of corresponding default search
1206 group."
1207   (let ((allservers (nnmairix-get-nnmairix-servers))
1208         mairixserver found defaultgroup)
1209     (if (> (length allservers) 1)
1210         (progn
1211           ;; If there is more than one nnmairix server, we go through them
1212           (while (and allservers (not found))
1213             (setq mairixserver (gnus-server-to-method (car (pop allservers))))
1214             ;; First we look if SERVER is the backend of current nnmairix server
1215             (setq found (and (eq (cadr (assoc 'nnmairix-backend mairixserver))
1216                                  (car server))
1217                              (string= (cadr (assoc 'nnmairix-backend-server mairixserver))
1218                                       (nth 1 server))))
1219             ;; If that's not the case, we look at 'indexed-servers
1220             ;; variable in default search group
1221             (when (not found)
1222               (setq defaultgroup (cadr (assoc 'nnmairix-default-group mairixserver)))
1223               (setq found (member (gnus-method-to-server server)
1224                                   (gnus-group-get-parameter
1225                                    (gnus-group-prefixed-name defaultgroup
1226                                                              mairixserver)
1227                                    'indexed-servers t)))))
1228           ;; If still not found, we ask user
1229           (when (not found)
1230             (setq mairixserver
1231                   (gnus-server-to-method
1232                    (completing-read
1233                     (format "Cannot determine which nnmairix server indexes %s. Please specify: "
1234                             (gnus-method-to-server server))
1235                     (nnmairix-get-nnmairix-servers) nil nil "nnmairix:")))
1236             ;; Save result in parameter of default search group so that
1237             ;; we don't have to ask again
1238             (setq defaultgroup (gnus-group-prefixed-name
1239                                 (cadr (assoc 'nnmairix-default-group mairixserver)) mairixserver))
1240             (gnus-group-set-parameter
1241              defaultgroup
1242              'indexed-servers
1243              (append (gnus-group-get-parameter defaultgroup 'indexed-servers t)
1244                      (list (gnus-method-to-server server)))))
1245           mairixserver)
1246       ;; If there is just one (or none) nnmairix server:
1247       (gnus-server-to-method (caar allservers)))))
1248
1249 (defun nnmairix-update-and-clear-marks (group &optional method)
1250   "Update group and clear all marks from GROUP using METHOD."
1251   (when method
1252     (setq group (gnus-group-prefixed-name group method)))
1253   (let ((method (or method
1254                     (gnus-find-method-for-group group)))
1255         (folder (gnus-group-get-parameter group 'folder))
1256         (corr (gnus-group-get-parameter group 'numcorr t))
1257         info)
1258     (if (eq (nth 0 method) 'nnmairix)
1259         (save-excursion
1260           (nnmairix-open-server (nth 1 method))
1261           (set-buffer gnus-group-buffer)
1262           (setq info (gnus-get-info group))
1263           ;; Clear active and info
1264           (gnus-set-active group nil)
1265           (gnus-info-clear-data info)
1266           ;; Delete and re-create group if needed
1267           (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1268             (if (string-match nnmairix-group-regexp folder)
1269                 (progn
1270                   (nnmairix-call-backend "open-server"
1271                                          nnmairix-backend-server)
1272                   (nnmairix-call-backend "request-delete-group"
1273                                          folder t nnmairix-backend-server)
1274                   (nnmairix-call-backend "request-create-group"
1275                                          folder nnmairix-backend-server)
1276                   ;; set flag that group has changed for article number correction
1277                   (when corr
1278                     (setcar corr t)
1279                     (gnus-group-set-parameter group 'numcorr corr)))
1280               (error "Nnmairix-update-and-clear-marks - delete/create with\
1281  non-mairix group!! - check folder parameter")))
1282           (when (gnus-group-jump-to-group group)
1283             (gnus-group-get-new-news-this-group)))
1284       (error "Nnmairix-update-and-clear-marks - Called with non-nnmairix group"))))
1285
1286
1287 (defun nnmairix-sentinel-mairix-update-finished (proc status)
1288   "Sentinel for mairix update process PROC with STATUS."
1289   (if (equal status "finished\n")
1290       (nnheader-message 7 "Updating mairix database for %s... done" proc)
1291     (error "There was an error updating the mairix database for server %s.  \
1292 See %s for details" proc nnmairix-mairix-output-buffer)))
1293
1294 (defun nnmairix-create-message-line-for-search ()
1295   "Create message line for interactive query in minibuffer."
1296   (mapconcat
1297    (function
1298     (lambda (cur)
1299       (format "%c=%s" (car cur) (nth 3 cur))))
1300    nnmairix-interactive-query-parameters ","))
1301
1302 (defun nnmairix-replace-illegal-chars (header)
1303   "Replace illegal characters in HEADER for mairix query."
1304   (when header
1305     (if (> emacs-major-version 20)
1306         (while (string-match "[^-.@/,& [:alnum:]]" header)
1307           (setq header (replace-match "" t t header)))
1308       (while (string-match "[[]{}:<>]" header)
1309         (setq header (replace-match "" t t header))))
1310     (while (string-match "[-& ]" header)
1311       (setq header (replace-match "," t t header)))
1312   header))
1313
1314 (defun nnmairix-show-original-article (group mid)
1315   "Switch to GROUP and display Article with message-id MID."
1316   (when (string-match "Summary" (buffer-name (current-buffer)))
1317     (gnus-summary-exit))
1318   (pop-to-buffer gnus-group-buffer)
1319   (gnus-group-jump-to-group group)
1320   (gnus-summary-read-group group 1 t)
1321   (gnus-summary-refer-article mid)
1322   (gnus-summary-limit-to-headers (format "message-id: <%s>" mid))
1323   (gnus-summary-select-article)
1324   ;; Force redisplay
1325   (gnus-summary-show-article)
1326   (nnheader-message 5 "Switched to group %s." group))
1327
1328
1329 ;; ==== Widget stuff
1330
1331 (defvar nnmairix-widgets)
1332 (defvar nnmairix-widgets-values nil)
1333
1334 (defun nnmairix-widget-search-from-this-article ()
1335   "Create mairix query based on current article using graphical widgets."
1336   (interactive)
1337   (nnmairix-widget-search
1338    (nnmairix-widget-get-values)))
1339
1340
1341 (defun nnmairix-widget-get-values ()
1342   "Create values for editable fields from current article."
1343   (if (not (gnus-buffer-live-p gnus-article-buffer))
1344       (error "No article buffer available")
1345     (save-excursion
1346       (gnus-summary-toggle-header 1)
1347       (set-buffer gnus-article-buffer)
1348       (mapcar
1349        (function
1350         (lambda (field)
1351           (list (car (cddr field))
1352                 (if (car field)
1353                     (nnmairix-replace-illegal-chars
1354                      (gnus-fetch-field (car field)))
1355                   nil))))
1356        nnmairix-widget-fields-list))))
1357
1358
1359 (defun nnmairix-widget-search (&optional mvalues)
1360   "Create mairix query interactively using graphical widgets.
1361 MVALUES may contain values from current article."
1362   (interactive)
1363   ;; Select window for mairix customization
1364   (funcall nnmairix-widget-select-window-function)
1365   ;; generate widgets
1366   (nnmairix-widget-create-query mvalues)
1367   ;; generate Buttons
1368   (widget-create 'push-button
1369                  :notify
1370                  (if mvalues
1371                      (lambda (&rest ignore)
1372                        (nnmairix-widget-send-query nnmairix-widgets
1373                                                    t))
1374                    (lambda (&rest ignore)
1375                      (nnmairix-widget-send-query nnmairix-widgets
1376                                                  nil)))
1377                  "Send Query")
1378   (widget-insert "   ")
1379   (widget-create 'push-button
1380                  :notify
1381                  (if mvalues
1382                      (lambda (&rest ignore)
1383                        (nnmairix-widget-create-group nnmairix-widgets
1384                                                      t))
1385                    (lambda (&rest ignore)
1386                      (nnmairix-widget-create-group nnmairix-widgets
1387                                                    nil)))
1388                  "Create permanent group")
1389   (widget-insert "   ")
1390   (widget-create 'push-button
1391                  :notify (lambda (&rest ignore)
1392                            (kill-buffer nnmairix-customize-query-buffer))
1393                  "Cancel")
1394   (use-local-map widget-keymap)
1395   (widget-setup)
1396   (goto-char (point-min)))
1397
1398 (defun nnmairix-widget-send-query (widgets &optional withvalues)
1399   "Send query from WIDGETS to mairix binary.
1400 If WITHVALUES is t, query is based on current article."
1401   (nnmairix-search
1402    (nnmairix-widget-make-query-from-widgets widgets)
1403    (if withvalues
1404        (gnus-method-to-server
1405         (nnmairix-backend-to-server gnus-current-select-method))
1406      (car (nnmairix-get-server)))
1407    (if (widget-value (cadr (assoc "Threads" widgets)))
1408        t
1409      -1))
1410   (kill-buffer nnmairix-customize-query-buffer))
1411
1412 (defun nnmairix-widget-create-group (widgets &optional withvalues)
1413   "Create nnmairix group based on current widget values WIDGETS.
1414 If WITHVALUES is t, query is based on current article."
1415   (let ((group (read-string "Name of the group: ")))
1416     (when (not (zerop (length group)))
1417       (nnmairix-create-search-group
1418        (if withvalues
1419            (gnus-method-to-server
1420             (nnmairix-backend-to-server gnus-current-select-method))
1421          (car (nnmairix-get-server)))
1422        group
1423        (nnmairix-widget-make-query-from-widgets widgets)
1424        (widget-value (cadr (assoc "Threads" widgets))))))
1425   (kill-buffer nnmairix-customize-query-buffer))
1426
1427
1428 (defun nnmairix-widget-make-query-from-widgets (widgets)
1429   "Create mairix query from widget values WIDGETS."
1430   (let (query temp flag)
1431     ;; first we do the editable fields
1432     (dolist (cur nnmairix-widget-fields-list)
1433       ;; See if checkbox is checked
1434       (when (widget-value
1435              (cadr (assoc (concat "c" (car (cddr cur))) widgets)))
1436         ;; create query for the field
1437         (push
1438          (concat
1439           (nth 1 cur)
1440           ":"
1441           (nnmairix-replace-illegal-chars
1442            (widget-value
1443            (cadr (assoc (concat "e" (car (cddr cur))) widgets)))))
1444          query)))
1445     ;; Flags
1446     (when (member 'flags nnmairix-widget-other)
1447       (setq flag
1448             (mapconcat
1449              (function
1450               (lambda (flag)
1451                 (setq temp
1452                       (widget-value (cadr (assoc (car flag) nnmairix-widgets))))
1453                 (if (string= "yes" temp)
1454                     (cadr flag)
1455                   (if (string= "no" temp)
1456                       (concat "-" (cadr flag))))))
1457              '(("seen" "s") ("replied" "r") ("flagged" "f")) ""))
1458       (when (not (zerop (length flag)))
1459         (push (concat "F:" flag) query)))
1460     ;; return query string
1461     (mapconcat 'identity query " ")))
1462
1463
1464 (defun nnmairix-widget-create-query (&optional values)
1465   "Create widgets for creating mairix queries.
1466 Fill in VALUES if based on an article."
1467   (let (allwidgets)
1468     (when (get-buffer nnmairix-customize-query-buffer)
1469       (kill-buffer nnmairix-customize-query-buffer))
1470     (switch-to-buffer nnmairix-customize-query-buffer)
1471     (kill-all-local-variables)
1472     (erase-buffer)
1473     (widget-insert "Specify your query for Mairix (check boxes for activating fields):\n\n")
1474     (widget-insert "(Whitespaces will be converted to ',' (i.e. AND). Use '/' for OR.)\n\n")
1475 ;    (make-local-variable 'nnmairix-widgets)
1476     (setq nnmairix-widgets (nnmairix-widget-build-editable-fields values))
1477     (when (member 'flags nnmairix-widget-other)
1478       (widget-insert "\nFlags:\n      Seen:     ")
1479       (nnmairix-widget-add "seen"
1480                            'menu-choice
1481                            :value "ignore"
1482                            '(item "yes") '(item "no") '(item "ignore"))
1483       (widget-insert "      Replied:  ")
1484       (nnmairix-widget-add "replied"
1485                            'menu-choice
1486                            :value "ignore"
1487                            '(item "yes") '(item "no") '(item "ignore"))
1488       (widget-insert "      Ticked:   ")
1489       (nnmairix-widget-add "flagged"
1490                            'menu-choice
1491                            :value "ignore"
1492                            '(item "yes") '(item "no") '(item "ignore")))
1493     (when (member 'threads nnmairix-widget-other)
1494       (widget-insert "\n")
1495       (nnmairix-widget-add "Threads" 'checkbox nil))
1496       (widget-insert " Show full threads\n\n")))
1497
1498
1499 (defun nnmairix-widget-build-editable-fields (values)
1500   "Build editable field widgets in `nnmairix-widget-fields-list'.
1501 VALUES may contain values for editable fields from current article."
1502   ;; how can this be done less ugly?
1503   (let ((ret))
1504     (mapc
1505      (function
1506       (lambda (field)
1507         (setq field (car (cddr field)))
1508         (setq ret
1509               (nconc
1510                (list
1511                 (list
1512                  (concat "c" field)
1513                  (widget-create 'checkbox
1514                                 :tag field
1515                                 :notify (lambda (widget &rest ignore)
1516                                           (nnmairix-widget-toggle-activate widget))
1517                                 nil)))
1518                (list
1519                 (list
1520                  (concat "e" field)
1521                  (widget-create 'editable-field
1522                                 :size 60
1523                                 :format (concat " " field ":"
1524                                                 (make-string (- 11 (length field)) ?\ )
1525                                                 "%v")
1526                                 :value (or (cadr (assoc field values)) ""))))
1527                ret))
1528         (widget-insert "\n")
1529         ;; Deactivate editable field
1530         (widget-apply (cadr (nth 1 ret)) :deactivate)))
1531      nnmairix-widget-fields-list)
1532     ret))
1533
1534 (defun nnmairix-widget-add (name &rest args)
1535   "Add a widget NAME with optional ARGS."
1536   (push
1537    (list name
1538          (apply 'widget-create args))
1539    nnmairix-widgets))
1540
1541 (defun nnmairix-widget-toggle-activate (widget)
1542   "Toggle activation status of WIDGET dependent on corresponding checkbox value."
1543   (let ((field (widget-get widget :tag)))
1544     (if (widget-value widget)
1545         (widget-apply
1546          (cadr (assoc (concat "e" field) nnmairix-widgets))
1547          :activate)
1548       (widget-apply
1549        (cadr (assoc (concat "e" field) nnmairix-widgets))
1550        :deactivate)))
1551   (widget-setup))
1552
1553 (provide 'nnmairix)
1554
1555 ;; arch-tag: bb187498-b229-4a55-8c07-6d3f80713e94
1556 ;;; nnmairix.el ends here