(nnimap-group-overview-filename): Create directory for
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;;         Jim Radford <radford@robby.caltech.edu>
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessery?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57 ;;   o Duplicate suppression
58
59 ;;; Code:
60
61 (eval-and-compile
62   (require 'cl)
63   (require 'imap))
64
65 (require 'nnoo)
66 (require 'nnmail)
67 (require 'nnheader)
68 (require 'mm-util)
69 (require 'gnus)
70 (require 'gnus-range)
71 (require 'gnus-start)
72 (require 'gnus-int)
73
74 (nnoo-declare nnimap)
75
76 (defconst nnimap-version "nnimap 0.131")
77
78 (defvoo nnimap-address nil
79   "Address of physical IMAP server.  If nil, use the virtual server's name.")
80
81 (defvoo nnimap-server-port nil
82   "Port number on physical IMAP server.
83 If nil, defaults to 993 for SSL connections and 143 otherwise.")
84
85 ;; Splitting variables
86
87 (defvar nnimap-split-crosspost t
88   "If non-nil, do crossposting if several split methods match the mail.
89 If nil, the first match found will be used.")
90
91 (defvar nnimap-split-inbox nil
92   "*Name of mailbox to split mail from.
93
94 Mail is read from this mailbox and split according to rules in
95 `nnimap-split-rules'.
96
97 This can be a string or a list of strings.")
98
99 (defvar nnimap-split-rule nil
100   "*Mail will be split according to theese rules.
101
102 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
103
104 If you'd like, for instance, one mail group for mail from the
105 \"gnus-imap\" mailing list, one group for junk mail and leave
106 everything else in the incoming mailbox, you could do something like
107 this:
108
109 (setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
110                           (\"INBOX.junk\"        \"Subject:.*buy\")))
111
112 As you can see, `nnimap-split-rule' is a list of lists, where the first
113 element in each \"rule\" is the name of the IMAP mailbox, and the
114 second is a regexp that nnimap will try to match on the header to find
115 a fit.
116
117 The second element can also be a function.  In that case, it will be
118 called narrowed to the headers with the first element of the rule as
119 the argument.  It should return a non-nil value if it thinks that the
120 mail belongs in that group.
121
122 This variable can also have a function as its value, the function will
123 be called with the headers narrowed and should return a group where it
124 thinks the article should be splitted to.  See `nnimap-split-fancy'.
125
126 To allow for different split rules on different virtual servers, and
127 even different split rules in different inboxes on the same server,
128 the syntax of this variable have been extended along the lines of:
129
130 (setq nnimap-split-rule
131       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
132                                   (\"junk\"    \"From:.*Simon\")))
133         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
134         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
135                                   (\"junk\"    my-junk-func)))))
136
137 The virtual server name is in fact a regexp, so that the same rules
138 may apply to several servers.  In the example, the servers
139 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
140 the inbox string is also a regexp.  The actual splitting rules are as
141 before, either a function, or a list with group/regexp or
142 group/function elements.")
143
144 (defvar nnimap-split-predicate "UNSEEN UNDELETED"
145   "The predicate used to find articles to split.
146 If you use another IMAP client to peek on articles but always would
147 like nnimap to split them once it's started, you could change this to
148 \"UNDELETED\". Other available predicates are available in
149 RFC2060 section 6.4.4.")
150
151 (defvar nnimap-split-fancy nil
152   "Like `nnmail-split-fancy', which see.")
153
154 ;; Authorization / Privacy variables
155
156 (defvoo nnimap-auth-method nil
157   "Obsolete.")
158
159 (defvoo nnimap-stream nil
160   "How nnimap will connect to the server.
161
162 The default, nil, will try to use the \"best\" method the server can
163 handle.
164
165 Change this if
166
167 1) you want to connect with SSL.  The SSL integration with IMAP is
168    brain-dead so you'll have to tell it specifically.
169
170 2) your server is more capable than your environment -- i.e. your
171    server accept Kerberos login's but you haven't installed the
172    `imtest' program or your machine isn't configured for Kerberos.
173
174 Possible choices: kerberos4, ssl, network")
175
176 (defvoo nnimap-authenticator nil
177   "How nnimap authenticate itself to the server.
178
179 The default, nil, will try to use the \"best\" method the server can
180 handle.
181
182 There is only one reason for fiddling with this variable, and that is
183 if your server is more capable than your environment -- i.e. you
184 connect to a server that accept Kerberos login's but you haven't
185 installed the `imtest' program or your machine isn't configured for
186 Kerberos.
187
188 Possible choices: kerberos4, cram-md5, login, anonymous.")
189
190 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
191   "Directory to keep NOV cache files for nnimap groups.
192 See also `nnimap-nov-file-name'.")
193
194 (defvoo nnimap-nov-file-name "nnimap."
195   "NOV cache base filename.
196 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
197 typical complete file name would be
198 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
199 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
200 `nnmail-use-long-file-names' is nil")
201
202 (defvoo nnimap-nov-file-name-suffix ".novcache"
203   "Suffix for NOV cache base filename.")
204
205 (defvoo nnimap-nov-is-evil nil
206   "If non-nil, nnimap will never generate or use a local nov database for this backend.
207 Using nov databases will speed up header fetching considerably.
208 Unlike other backends, you do not need to take special care if you
209 flip this variable.")
210
211 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
212   "Whether to expunge a group when it is closed.
213 When a IMAP group with articles marked for deletion is closed, this
214 variable determine if nnimap should actually remove the articles or
215 not.
216
217 If always, nnimap always perform a expunge when closing the group.
218 If never, nnimap never expunges articles marked for deletion.
219 If ask, nnimap will ask you if you wish to expunge marked articles.
220
221 When setting this variable to `never', you can only expunge articles
222 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
223
224 (defvoo nnimap-list-pattern "*"
225   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
226 See below for available wildcards.
227
228 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
229 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
230 semantics of this are server specific, on the University of Washington
231 server you can specify a directory.
232
233 Example:
234  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
235
236 There are two wildcards * and %. * matches everything, % matches
237 everything in the current hierarchy.")
238
239 (defvoo nnimap-news-groups nil
240   "IMAP support a news-like mode, also known as bulletin board mode, where replies is sent via IMAP instead of SMTP.
241
242 This variable should contain a regexp matching groups where you wish
243 replies to be stored to the mailbox directly.
244
245 Example:
246   '(\"^[^I][^N][^B][^O][^X].*$\")
247
248 This will match all groups not beginning with \"INBOX\".
249
250 Note that there is nothing technically different between mail-like and
251 news-like mailboxes.  If you wish to have a group with todo items or
252 similar which you wouldn't want to set up a mailing list for, you can
253 use this to make replies go directly to the group.")
254
255 (defvoo nnimap-server-address nil
256   "Obsolete.  Use `nnimap-address'.")
257
258 (defcustom nnimap-authinfo-file "~/.authinfo"
259   "Authorization information for IMAP servers.  In .netrc format."
260   :type
261   '(choice file
262            (repeat :tag "Entries"
263                    :menu-tag "Inline"
264                    (list :format "%v"
265                          :value ("" ("login" . "") ("password" . ""))
266                          (string :tag "Host")
267                          (checklist :inline t
268                                     (cons :format "%v"
269                                           (const :format "" "login")
270                                           (string :format "Login: %v"))
271                                     (cons :format "%v"
272                                           (const :format "" "password")
273                                           (string :format "Password: %v")))))))
274
275 (defcustom nnimap-prune-cache t
276   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
277   :type 'boolean)
278
279 (defvar nnimap-request-list-method 'imap-mailbox-list
280   "Method to use to request a list of all folders from the server.
281 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
282 restrict visible folders.")
283
284 ;; Internal variables:
285
286 (defvar nnimap-debug nil
287   "Name of buffer to record debugging info.
288 For example: (setq nnimap-debug \"*nnimap-debug*\")")
289 (defvar nnimap-current-move-server nil)
290 (defvar nnimap-current-move-group nil)
291 (defvar nnimap-current-move-article nil)
292 (defvar nnimap-length)
293 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
294 (defvar nnimap-progress-how-often 20)
295 (defvar nnimap-counter)
296 (defvar nnimap-callback-callback-function nil
297   "Gnus callback the nnimap asynchronous callback should call.")
298 (defvar nnimap-callback-buffer nil
299   "Which buffer the asynchronous article prefetch callback should work in.")
300 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
301 (defvar nnimap-current-server nil)      ;; Current server
302 (defvar nnimap-server-buffer nil)       ;; Current servers' buffer
303
304 \f
305
306 (nnoo-define-basics nnimap)
307
308 ;; Utility functions:
309
310 (defsubst nnimap-get-server-buffer (server)
311   "Return buffer for SERVER, if nil use current server."
312   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
313
314 (defun nnimap-possibly-change-server (server)
315   "Return buffer for SERVER, changing the current server as a side-effect.
316 If SERVER is nil, uses the current server."
317   (setq nnimap-current-server (or server nnimap-current-server)
318         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
319
320 (defun nnimap-verify-uidvalidity (group server)
321   "Verify stored uidvalidity match current one in GROUP on SERVER."
322   (let* ((gnusgroup (gnus-group-prefixed-name
323                      group (gnus-server-to-method
324                             (format "nnimap:%s" server))))
325          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
326          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity))
327          (dir (file-name-as-directory (expand-file-name nnimap-directory)))
328          (nameuid (nnheader-translate-file-chars
329                    (concat nnimap-nov-file-name
330                            (if (equal server "")
331                                "unnamed"
332                              server) "." group "." old-uidvalidity
333                              nnimap-nov-file-name-suffix) t))
334          (file (if (or nnmail-use-long-file-names
335                        (file-exists-p (expand-file-name nameuid dir)))
336                    (expand-file-name nameuid dir)
337                  (expand-file-name
338                   (mm-encode-coding-string
339                    (nnheader-replace-chars-in-string nameuid ?. ?/)
340                    nnmail-pathname-coding-system)
341                   dir))))
342     (if old-uidvalidity
343         (if (not (equal old-uidvalidity new-uidvalidity))
344             ;; uidvalidity clash
345             (gnus-delete-file file)
346           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
347           t)
348       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
349       t)))
350
351 (defun nnimap-before-find-minmax-bugworkaround ()
352   "Function called before iterating through mailboxes with
353 `nnimap-find-minmax-uid'."
354   ;; XXX this is for UoW imapd problem, it doesn't notice new mail in
355   ;; currently selected mailbox without a re-select/examine.
356   (or (null (imap-current-mailbox nnimap-server-buffer))
357       (imap-mailbox-unselect nnimap-server-buffer)))
358
359 (defun nnimap-find-minmax-uid (group &optional examine)
360   "Find lowest and highest active article nummber in GROUP.
361 If EXAMINE is non-nil the group is selected read-only."
362   (with-current-buffer nnimap-server-buffer
363     (when (imap-mailbox-select group examine)
364       (let (minuid maxuid)
365         (when (> (imap-mailbox-get 'exists) 0)
366           (imap-fetch "1,*" "UID" nil 'nouidfetch)
367           (imap-message-map (lambda (uid Uid)
368                               (setq minuid (if minuid (min minuid uid) uid)
369                                     maxuid (if maxuid (max maxuid uid) uid)))
370                             'UID))
371         (list (imap-mailbox-get 'exists) minuid maxuid)))))
372   
373 (defun nnimap-possibly-change-group (group &optional server)
374   "Make GROUP the current group, and SERVER the current server."
375   (when (nnimap-possibly-change-server server)
376     (with-current-buffer nnimap-server-buffer
377       (if (or (null group) (imap-current-mailbox-p group))
378           imap-current-mailbox
379         (if (imap-mailbox-select group)
380             (if (or (nnimap-verify-uidvalidity
381                      group (or server nnimap-current-server))
382                     (zerop (imap-mailbox-get 'exists group))
383                     (yes-or-no-p
384                      (format
385                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
386                 imap-current-mailbox
387               (imap-mailbox-unselect)
388               (error "nnimap: Group %s is not uid-valid." group))
389           (nnheader-report 'nnimap (imap-error-text)))))))
390
391 (defun nnimap-replace-whitespace (string)
392   "Return STRING with all whitespace replaced with space."
393   (when string
394     (while (string-match "[\r\n\t]+" string)
395       (setq string (replace-match " " t t string)))
396     string))
397
398 ;; Required backend functions
399
400 (defun nnimap-retrieve-headers-progress ()
401   "Hook to insert NOV line for current article into `nntp-server-buffer'."
402   (and (numberp nnmail-large-newsgroup)
403        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
404        (> nnimap-length nnmail-large-newsgroup)
405        (nnheader-message 6 "nnimap: Retrieving headers... %c"
406                          (nth (/ (% nnimap-counter
407                                     (* (length nnimap-progress-chars)
408                                        nnimap-progress-how-often))
409                                  nnimap-progress-how-often)
410                               nnimap-progress-chars)))
411   (with-current-buffer nntp-server-buffer
412     (let (headers lines chars uid mbx)
413       (with-current-buffer nnimap-server-buffer
414         (setq uid imap-current-message
415               mbx imap-current-mailbox
416               headers (nnimap-demule
417                        (if (imap-capability 'IMAP4rev1)
418                            ;; xxx don't just use car? alist doesn't contain
419                            ;; anything else now, but it might...
420                            (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
421                          (imap-message-get uid 'RFC822.HEADER)))
422               lines (imap-body-lines (imap-message-body imap-current-message))
423               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
424       (nnheader-insert-nov
425        (with-temp-buffer
426          (buffer-disable-undo)
427          (insert headers)
428          (nnheader-ms-strip-cr)
429          (nnheader-fold-continuation-lines)
430          (subst-char-in-region (point-min) (point-max) ?\t ? )
431          (let ((head (nnheader-parse-head 'naked)))
432            (mail-header-set-number head uid)
433            (mail-header-set-chars head chars)
434            (mail-header-set-lines head lines)
435            (mail-header-set-xref
436             head (format "%s %s:%d" (system-name) mbx uid))
437            head))))))
438
439 (defun nnimap-retrieve-which-headers (articles fetch-old)
440   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
441   (with-current-buffer nnimap-server-buffer
442     (if (numberp (car-safe articles))
443         (imap-search
444          (concat "UID "
445                  (imap-range-to-message-set
446                   (gnus-compress-sequence
447                    (append (gnus-uncompress-sequence
448                             (and fetch-old
449                                  (cons (if (numberp fetch-old)
450                                            (max 1 (- (car articles) fetch-old))
451                                          1)
452                                        (1- (car articles)))))
453                            articles)))))
454       (mapcar (lambda (msgid)
455                 (imap-search
456                  (format "HEADER Message-Id %s" msgid)))
457               articles))))
458
459 (defun nnimap-group-overview-filename (group server)
460   "Make pathname for GROUP on SERVER."
461   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
462          (uidvalidity (gnus-group-get-parameter
463                        (gnus-group-prefixed-name
464                         group (gnus-server-to-method
465                                (format "nnimap:%s" server)))
466                        'uidvalidity))
467          (name (nnheader-translate-file-chars
468                 (concat nnimap-nov-file-name
469                         (if (equal server "")
470                             "unnamed"
471                           server) "." group nnimap-nov-file-name-suffix) t))
472          (nameuid (nnheader-translate-file-chars
473                    (concat nnimap-nov-file-name
474                            (if (equal server "")
475                                "unnamed"
476                              server) "." group "." uidvalidity
477                              nnimap-nov-file-name-suffix) t))
478          (oldfile (if (or nnmail-use-long-file-names
479                           (file-exists-p (expand-file-name name dir)))
480                       (expand-file-name name dir)
481                     (expand-file-name
482                      (mm-encode-coding-string
483                       (nnheader-replace-chars-in-string name ?. ?/)
484                       nnmail-pathname-coding-system)
485                      dir)))
486          (newfile (if (or nnmail-use-long-file-names
487                           (file-exists-p (expand-file-name nameuid dir)))
488                       (expand-file-name nameuid dir)
489                     (expand-file-name
490                      (mm-encode-coding-string
491                       (nnheader-replace-chars-in-string nameuid ?. ?/)
492                       nnmail-pathname-coding-system)
493                      dir))))
494     (if (and (file-exists-p oldfile)
495              (not (file-exists-p newfile)))
496         (progn
497           (message "nnimap: Upgrading novcache filename...")
498           (sit-for 1)
499           (gnus-make-directory (file-name-directory newfile))
500           (unless (rename-file oldfile newfile)
501             (when (copy-file oldfile newfile)
502               (delete-file oldfile)))
503           newfile)
504       newfile)))
505
506 (defun nnimap-retrieve-headers-from-file (group server)
507   (with-current-buffer nntp-server-buffer
508     (let ((nov (nnimap-group-overview-filename group server)))
509       (when (file-exists-p nov)
510         (mm-insert-file-contents nov)
511         (set-buffer-modified-p nil)
512         (let ((min (ignore-errors (goto-char (point-min))
513                                   (read (current-buffer))))
514               (max (ignore-errors (goto-char (point-max))
515                                   (forward-line -1)
516                                   (read (current-buffer)))))
517           (if (and (numberp min) (numberp max))
518               (cons min max)
519             ;; junk, remove it, it's saved later
520             (erase-buffer)
521             nil))))))
522
523 (defun nnimap-retrieve-headers-from-server (articles group server)
524   (with-current-buffer nnimap-server-buffer
525     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
526           (nnimap-length (gnus-range-length articles))
527           (nnimap-counter 0))
528       (imap-fetch (imap-range-to-message-set articles)
529                   (concat "(UID RFC822.SIZE BODY "
530                           (let ((headers
531                                  (append '(Subject From Date Message-Id
532                                                    References In-Reply-To Xref)
533                                          (copy-sequence
534                                           nnmail-extra-headers))))
535                             (if (imap-capability 'IMAP4rev1)
536                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
537                               (format "RFC822.HEADER.LINES %s)" headers)))))
538       (and (numberp nnmail-large-newsgroup)
539            (> nnimap-length nnmail-large-newsgroup)
540            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
541
542 (defun nnimap-use-nov-p (group server)
543   (or gnus-nov-is-evil nnimap-nov-is-evil
544       (unless (and (gnus-make-directory
545                     (file-name-directory
546                      (nnimap-group-overview-filename group server)))
547                    (file-writable-p
548                     (nnimap-group-overview-filename group server)))
549         (message "nnimap: Nov cache not writable, %s"
550                  (nnimap-group-overview-filename group server)))))
551
552 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
553   (when (nnimap-possibly-change-group group server)
554     (with-current-buffer nntp-server-buffer
555       (erase-buffer)
556       (if (nnimap-use-nov-p group server)
557           (nnimap-retrieve-headers-from-server
558            (gnus-compress-sequence articles) group server)
559         (let (uids cached low high)
560           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
561                       low (car uids)
562                       high (car (last uids)))
563             (if (setq cached (nnimap-retrieve-headers-from-file group server))
564                 (progn
565                   ;; fetch articles with uids before cache block
566                   (when (< low (car cached))
567                     (goto-char (point-min))
568                     (nnimap-retrieve-headers-from-server
569                      (cons low (1- (car cached))) group server))
570                   ;; fetch articles with uids after cache block
571                   (when (> high (cdr cached))
572                     (goto-char (point-max))
573                     (nnimap-retrieve-headers-from-server
574                      (cons (1+ (cdr cached)) high) group server))
575                   (when nnimap-prune-cache
576                     ;; remove nov's for articles which has expired on server
577                     (goto-char (point-min))
578                     (dolist (uid (gnus-set-difference articles uids))
579                       (when (re-search-forward (format "^%d\t" uid) nil t)
580                         (gnus-delete-line)))))
581               ;; nothing cached, fetch whole range from server
582               (nnimap-retrieve-headers-from-server
583                (cons low high) group server))
584             (when (buffer-modified-p)
585               (nnmail-write-region
586                1 (point-max) (nnimap-group-overview-filename group server)
587                nil 'nomesg))
588             (nnheader-nov-delete-outside-range low high))))
589       'nov)))
590
591 (defun nnimap-open-connection (server)
592   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
593                       nnimap-authenticator nnimap-server-buffer))
594       (nnheader-report 'nnimap "Can't open connection to server %s" server)
595     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
596                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
597       (imap-close nnimap-server-buffer)
598       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
599     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
600            (port (if nnimap-server-port
601                      (int-to-string nnimap-server-port)
602                    "imap"))
603            (alist (gnus-netrc-machine list (or nnimap-server-address 
604                                                nnimap-address server)
605                                       port "imap"))
606            (user (gnus-netrc-get alist "login"))
607            (passwd (gnus-netrc-get alist "password")))
608       (if (imap-authenticate user passwd nnimap-server-buffer)
609           (prog1
610               (push (list server nnimap-server-buffer)
611                     nnimap-server-buffer-alist)
612             (nnimap-possibly-change-server server))
613         (imap-close nnimap-server-buffer)
614         (kill-buffer nnimap-server-buffer)
615         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
616
617 (deffoo nnimap-open-server (server &optional defs)
618   (nnheader-init-server-buffer)
619   (if (nnimap-server-opened server)
620       t
621     (unless (assq 'nnimap-server-buffer defs)
622       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
623     ;; translate `nnimap-server-address' to `nnimap-address' in defs
624     ;; for people that configured nnimap with a very old version
625     (unless (assq 'nnimap-address defs)
626       (if (assq 'nnimap-server-address defs)
627           (push (list 'nnimap-address
628                       (cadr (assq 'nnimap-server-address defs))) defs)
629         (push (list 'nnimap-address server) defs)))
630     (nnoo-change-server 'nnimap server defs)
631     (with-current-buffer (get-buffer-create nnimap-server-buffer)
632       (nnoo-change-server 'nnimap server defs))
633     (or (and nnimap-server-buffer
634              (imap-opened nnimap-server-buffer))
635         (nnimap-open-connection server))))
636
637 (deffoo nnimap-server-opened (&optional server)
638   "Whether SERVER is opened.
639 If SERVER is the current virtual server, and the connection to the
640 physical server is alive, this function return a non-nil value.  If
641 SERVER is nil, it is treated as the current server."
642   ;; clean up autologouts??
643   (and (or server nnimap-current-server)
644        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
645        (imap-opened (nnimap-get-server-buffer server))))
646
647 (deffoo nnimap-close-server (&optional server)
648   "Close connection to server and free all resources connected to it.
649 Return nil if the server couldn't be closed for some reason."
650   (let ((server (or server nnimap-current-server)))
651     (when (or (nnimap-server-opened server)
652               (imap-opened (nnimap-get-server-buffer server)))
653       (imap-close (nnimap-get-server-buffer server))
654       (kill-buffer (nnimap-get-server-buffer server))
655       (setq nnimap-server-buffer nil
656             nnimap-current-server nil
657             nnimap-server-buffer-alist
658             (delq server nnimap-server-buffer-alist)))
659     (nnoo-close-server 'nnimap server)))
660
661 (deffoo nnimap-request-close ()
662   "Close connection to all servers and free all resources that the backend have reserved.
663 All buffers that have been created by that
664 backend should be killed.  (Not the nntp-server-buffer, though.) This
665 function is generally only called when Gnus is shutting down."
666   (mapcar (lambda (server) (nnimap-close-server (car server)))
667           nnimap-server-buffer-alist)
668   (setq nnimap-server-buffer-alist nil))
669
670 (deffoo nnimap-status-message (&optional server)
671   "This function returns the last error message from server."
672   (when (nnimap-possibly-change-server server)
673     (nnoo-status-message 'nnimap server)))
674
675 (defun nnimap-demule (string)
676   (funcall (if (and (fboundp 'string-as-multibyte)
677                     (subrp (symbol-function 'string-as-multibyte)))
678                'string-as-multibyte
679              'identity)
680            (or string "")))
681
682 (defun nnimap-callback ()
683   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
684   (with-current-buffer nnimap-callback-buffer
685     (insert
686      (with-current-buffer nnimap-server-buffer
687        (nnimap-demule
688         (if (imap-capability 'IMAP4rev1) 
689             ;; xxx don't just use car? alist doesn't contain
690             ;; anything else now, but it might...
691             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
692           (imap-message-get (imap-current-message) 'RFC822)))))
693     (nnheader-ms-strip-cr)
694     (funcall nnimap-callback-callback-function t)))
695
696 (defun nnimap-request-article-part (article part prop &optional
697                                             group server to-buffer detail)
698   (when (nnimap-possibly-change-group group server)
699     (let ((article (if (stringp article)
700                        (car-safe (imap-search
701                                   (format "HEADER Message-Id %s" article)
702                                   nnimap-server-buffer))
703                      article)))
704       (when article
705         (gnus-message 10 "nnimap: Fetching (part of) article %d..." article)
706         (if (not nnheader-callback-function)
707             (with-current-buffer (or to-buffer nntp-server-buffer)
708               (erase-buffer)
709               (let ((data (imap-fetch article part prop nil
710                                       nnimap-server-buffer)))
711                 (insert (nnimap-demule (if detail
712                                            (nth 2 (car data))
713                                          data))))
714               (nnheader-ms-strip-cr)
715               (gnus-message 10 "nnimap: Fetching (part of) article %d...done"
716                             article)
717               (if (bobp)
718                   (nnheader-report 'nnimap "No such article: %s"
719                                    (imap-error-text nnimap-server-buffer))
720                 (cons group article)))
721           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
722           (setq nnimap-callback-callback-function nnheader-callback-function
723                 nnimap-callback-buffer nntp-server-buffer)
724           (imap-fetch-asynch article part nil nnimap-server-buffer)
725           (cons group article))))))
726
727 (deffoo nnimap-asynchronous-p ()
728   t)
729
730 (deffoo nnimap-request-article (article &optional group server to-buffer)
731   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
732       (nnimap-request-article-part
733        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
734     (nnimap-request-article-part
735      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
736
737 (deffoo nnimap-request-head (article &optional group server to-buffer)
738   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
739       (nnimap-request-article-part
740        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
741     (nnimap-request-article-part
742      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
743
744 (deffoo nnimap-request-body (article &optional group server to-buffer)
745   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
746       (nnimap-request-article-part
747        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
748     (nnimap-request-article-part
749      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
750
751 (deffoo nnimap-request-group (group &optional server fast)
752   (nnimap-request-update-info-internal
753    group
754    (gnus-get-info (gnus-group-prefixed-name
755                    group (gnus-server-to-method (format "nnimap:%s" server))))
756    server)
757   (when (nnimap-possibly-change-group group server)
758     (nnimap-before-find-minmax-bugworkaround)
759     (let (info)
760       (cond (fast group)
761             ((null (setq info (nnimap-find-minmax-uid group t)))
762              (nnheader-report 'nnimap "Could not get active info for %s"
763                               group))
764             (t
765              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
766                               (max 1 (or (nth 1 info) 1))
767                               (or (nth 2 info) 0) group)
768              (nnheader-report 'nnimap "Group %s selected" group)
769              t)))))
770
771 (defun nnimap-close-group (group &optional server)
772   (with-current-buffer nnimap-server-buffer
773     (when (and (imap-opened)
774                (nnimap-possibly-change-group group server))
775       (case nnimap-expunge-on-close
776         ('always (imap-mailbox-expunge)
777                  (imap-mailbox-close))
778         ('ask (if (and (imap-search "DELETED")
779                        (gnus-y-or-n-p (format
780                                        "Expunge articles in group `%s'? "
781                                        imap-current-mailbox)))
782                   (progn (imap-mailbox-expunge)
783                          (imap-mailbox-close))
784                 (imap-mailbox-unselect)))
785         (t (imap-mailbox-unselect)))
786       (not imap-current-mailbox))))
787
788 (defun nnimap-pattern-to-list-arguments (pattern)
789   (mapcar (lambda (p)
790             (cons (car-safe p) (or (cdr-safe p) p)))
791           (if (and (listp pattern)
792                    (listp (cdr pattern)))
793               pattern
794             (list pattern))))
795
796 (deffoo nnimap-request-list (&optional server)
797   (when (nnimap-possibly-change-server server)
798     (with-current-buffer nntp-server-buffer
799       (erase-buffer))
800     (gnus-message 5 "nnimap: Generating active list%s..."
801                   (if (> (length server) 0) (concat " for " server) ""))
802     (nnimap-before-find-minmax-bugworkaround)
803     (with-current-buffer nnimap-server-buffer
804       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
805         (dolist (mbx (funcall nnimap-request-list-method
806                               (cdr pattern) (car pattern)))
807           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
808               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
809                 (when info
810                   (with-current-buffer nntp-server-buffer
811                    (insert (format "\"%s\" %d %d y\n"
812                                    mbx (or (nth 2 info) 0)
813                                    (max 1 (or (nth 1 info) 1)))))))))))
814     (gnus-message 5 "nnimap: Generating active list%s...done"
815                   (if (> (length server) 0) (concat " for " server) ""))
816     t))
817
818 (deffoo nnimap-request-post (&optional server)
819   (let ((success t))
820     (dolist (mbx (message-unquote-tokens
821                   (message-tokenize-header
822                    (message-fetch-field "Newsgroups") ", ")) success)
823       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
824         (or (gnus-active to-newsgroup)
825             (gnus-activate-group to-newsgroup)
826             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
827                                        to-newsgroup))
828                 (or (and (gnus-request-create-group
829                           to-newsgroup gnus-command-method)
830                          (gnus-activate-group to-newsgroup nil nil
831                                               gnus-command-method))
832                     (error "Couldn't create group %s" to-newsgroup)))
833             (error "No such group: %s" to-newsgroup))
834         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
835           (setq success nil))))))
836
837 ;; Optional backend functions
838
839 (deffoo nnimap-retrieve-groups (groups &optional server)
840   (when (nnimap-possibly-change-server server)
841     (gnus-message 5 "nnimap: Checking mailboxes...")
842     (with-current-buffer nntp-server-buffer
843       (erase-buffer)
844       (nnimap-before-find-minmax-bugworkaround)
845       (dolist (group groups)
846         (gnus-message 7 "nnimap: Checking mailbox %s" group)
847         (or (member "\\NoSelect"
848                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
849             (let ((info (nnimap-find-minmax-uid group 'examine)))
850               (insert (format "\"%s\" %d %d y\n" group
851                               (or (nth 2 info) 0)
852                               (max 1 (or (nth 1 info) 1))))))))
853     (gnus-message 5 "nnimap: Checking mailboxes...done")
854     'active))
855
856 (deffoo nnimap-request-update-info-internal (group info &optional server)
857   (when (nnimap-possibly-change-group group server)
858     (when info;; xxx what does this mean? should we create a info?
859       (with-current-buffer nnimap-server-buffer
860         (gnus-message 5 "nnimap: Updating info for %s..."
861                       (gnus-info-group info))
862         
863         (when (nnimap-mark-permanent-p 'read)
864           (let (seen unseen)
865             ;; read info could contain articles marked unread by other
866             ;; imap clients!  we correct this
867             (setq seen (gnus-uncompress-range (gnus-info-read info))
868                   unseen (imap-search "UNSEEN UNDELETED")
869                   seen (gnus-set-difference seen unseen)
870                   ;; seen might lack articles marked as read by other
871                   ;; imap clients! we correct this
872                   seen (append seen (imap-search "SEEN"))
873                   ;; remove dupes
874                   seen (sort seen '<)
875                   seen (gnus-compress-sequence seen t)
876                   ;; we can't return '(1) since this isn't a "list of ranges",
877                   ;; and we can't return '((1)) since g-list-of-unread-articles
878                   ;; is buggy so we return '((1 . 1)).
879                   seen (if (and (integerp (car seen))
880                                 (null (cdr seen)))
881                            (list (cons (car seen) (car seen)))
882                          seen))
883             (gnus-info-set-read info seen)))
884
885         (mapcar (lambda (pred)
886                   (when (and (nnimap-mark-permanent-p (cdr pred))
887                              (member (nnimap-mark-to-flag (cdr pred))
888                                      (imap-mailbox-get 'flags)))
889                     (gnus-info-set-marks
890                      info
891                      (nnimap-update-alist-soft
892                       (cdr pred)
893                       (gnus-compress-sequence
894                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
895                       (gnus-info-marks info))
896                      t)))
897                 gnus-article-mark-lists)
898
899         ;; nnimap mark dormant article as ticked too (for other clients)
900         ;; so we remove that mark for gnus since we support dormant
901         (gnus-info-set-marks
902          info 
903          (nnimap-update-alist-soft
904           'tick
905           (gnus-remove-from-range
906            (cdr-safe (assoc 'tick (gnus-info-marks info)))
907            (cdr-safe (assoc 'dormant (gnus-info-marks info))))
908           (gnus-info-marks info))
909          t)
910         
911         (gnus-message 5 "nnimap: Updating info for %s...done"
912                       (gnus-info-group info))
913
914         info))))
915
916 (deffoo nnimap-request-type (group &optional article)
917   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
918       'news
919     'mail))
920
921 (deffoo nnimap-request-set-mark (group actions &optional server)
922   (when (nnimap-possibly-change-group group server)
923     (with-current-buffer nnimap-server-buffer
924       (let (action)
925         (gnus-message 7 "nnimap: Setting marks in %s..." group)
926         (while (setq action (pop actions))
927           (let ((range (nth 0 action))
928                 (what  (nth 1 action))
929                 (cmdmarks (nth 2 action))
930                 marks)
931             ;; cache flags are pointless on the server
932             (setq cmdmarks (delq 'cache cmdmarks))
933             ;; flag dormant articles as ticked
934             (if (memq 'dormant cmdmarks)
935                 (setq cmdmarks (cons 'tick cmdmarks)))
936             ;; remove stuff we are forbidden to store
937             (mapcar (lambda (mark)
938                       (if (imap-message-flag-permanent-p
939                            (nnimap-mark-to-flag mark))
940                           (setq marks (cons mark marks))))
941                     cmdmarks)
942             (when (and range marks)
943               (cond ((eq what 'del)
944                      (imap-message-flags-del
945                       (imap-range-to-message-set range)
946                       (nnimap-mark-to-flag marks nil t)))
947                     ((eq what 'add)
948                      (imap-message-flags-add
949                       (imap-range-to-message-set range)
950                       (nnimap-mark-to-flag marks nil t)))
951                     ((eq what 'set)
952                      (imap-message-flags-set
953                       (imap-range-to-message-set range)
954                       (nnimap-mark-to-flag marks nil t)))))))
955         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
956   nil)
957
958 (defun nnimap-split-fancy ()
959   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
960   (let ((nnmail-split-fancy nnimap-split-fancy))
961     (nnmail-split-fancy)))
962
963 (defun nnimap-split-to-groups (rules)
964   ;; tries to match all rules in nnimap-split-rule against content of
965   ;; nntp-server-buffer, returns a list of groups that matched.
966   (with-current-buffer nntp-server-buffer
967     ;; Fold continuation lines.
968     (goto-char (point-min))
969     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
970       (replace-match " " t t))
971     (if (functionp rules)
972         (funcall rules)
973       (let (to-groups regrepp)
974         (catch 'split-done
975           (dolist (rule rules to-groups)
976             (let ((group (car rule))
977                   (regexp (cadr rule)))
978               (goto-char (point-min))
979               (when (and (if (stringp regexp)
980                              (progn
981                                (setq regrepp (string-match "\\\\[0-9&]" group))
982                                (re-search-forward regexp nil t))
983                            (funcall regexp group))
984                          ;; Don't enter the article into the same group twice.
985                          (not (assoc group to-groups)))
986                 (push (if regrepp
987                           (nnmail-expand-newtext group)
988                         group)
989                       to-groups)
990                 (or nnimap-split-crosspost
991                     (throw 'split-done to-groups))))))))))
992   
993 (defun nnimap-assoc-match (key alist)
994   (let (element)
995     (while (and alist (not element))
996       (if (string-match (car (car alist)) key)
997           (setq element (car alist)))
998       (setq alist (cdr alist)))
999     element))
1000
1001 (defun nnimap-split-find-rule (server inbox)
1002   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1003            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1004       ;; extended format
1005       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
1006                                             server nnimap-split-rule))))
1007     nnimap-split-rule))
1008
1009 (defun nnimap-split-find-inbox (server)
1010   (if (listp nnimap-split-inbox)
1011       nnimap-split-inbox
1012     (list nnimap-split-inbox)))
1013
1014 (defun nnimap-split-articles (&optional group server)
1015   (when (nnimap-possibly-change-server server)
1016     (with-current-buffer nnimap-server-buffer
1017       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1018         ;; iterate over inboxes
1019         (while (and (setq inbox (pop inboxes))
1020                     (nnimap-possibly-change-group inbox));; SELECT
1021           ;; find split rule for this server / inbox
1022           (when (setq rule (nnimap-split-find-rule server inbox))
1023             ;; iterate over articles
1024             (dolist (article (imap-search nnimap-split-predicate))
1025               (when (nnimap-request-head article)
1026                 ;; copy article to right group(s)
1027                 (setq removeorig nil)
1028                 (dolist (to-group (nnimap-split-to-groups rule))
1029                   (if (imap-message-copy (number-to-string article)
1030                                          to-group nil 'nocopyuid)
1031                       (progn
1032                         (message "IMAP split moved %s:%s:%d to %s" server inbox
1033                                  article to-group)
1034                         (setq removeorig t)
1035                         ;; Add the group-art list to the history list.
1036                         (push (list (cons to-group 0)) nnmail-split-history))
1037                     (message "IMAP split failed to move %s:%s:%d to %s" server
1038                              inbox article to-group)))
1039                 ;; remove article if it was successfully copied somewhere
1040                 (and removeorig
1041                      (imap-message-flags-add (format "%d" article)
1042                                              "\\Seen \\Deleted")))))
1043           (when (imap-mailbox-select inbox);; just in case
1044             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1045             (imap-mailbox-expunge)
1046             (imap-mailbox-close)))
1047         t))))
1048
1049 (deffoo nnimap-request-scan (&optional group server)
1050   (nnimap-split-articles group server))
1051
1052 (deffoo nnimap-request-newgroups (date &optional server)
1053   (when (nnimap-possibly-change-server server)
1054     (with-current-buffer nntp-server-buffer
1055       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1056                     (if (> (length server) 0) " on " "") server)
1057       (erase-buffer)
1058       (nnimap-before-find-minmax-bugworkaround)
1059       (dolist (pattern (nnimap-pattern-to-list-arguments
1060                         nnimap-list-pattern))
1061         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
1062                                         nnimap-server-buffer))
1063           (or (catch 'found
1064                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1065                                                    nnimap-server-buffer))
1066                   (if (string= (downcase mailbox) "\\noselect")
1067                       (throw 'found t)))
1068                 nil)
1069               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1070                 (when info
1071                  (insert (format "\"%s\" %d %d y\n"
1072                                  mbx (or (nth 2 info) 0)
1073                                  (max 1 (or (nth 1 info) 1)))))))))
1074       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1075                     (if (> (length server) 0) " on " "") server))
1076     t))
1077       
1078 (deffoo nnimap-request-create-group (group &optional server args)
1079   (when (nnimap-possibly-change-server server)
1080     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1081         (imap-mailbox-create group nnimap-server-buffer))))
1082
1083 (defun nnimap-time-substract (time1 time2)
1084   "Return TIME for TIME1 - TIME2."
1085   (let* ((ms (- (car time1) (car time2)))
1086          (ls (- (nth 1 time1) (nth 1 time2))))
1087     (if (< ls 0)
1088         (list (- ms 1) (+ (expt 2 16) ls))
1089       (list ms ls))))
1090
1091 (defun nnimap-date-days-ago (daysago)
1092   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1093   (let ((date (format-time-string "%d-%b-%Y"
1094                                   (nnimap-time-substract
1095                                    (current-time)
1096                                    (days-to-time daysago)))))
1097     (if (eq ?0 (string-to-char date))
1098         (substring date 1)
1099       date)))
1100
1101 (defun nnimap-request-expire-articles-progress ()
1102   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1103                 imap-current-message))
1104
1105 ;; Notice that we don't actually delete anything, we just mark them deleted.
1106 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1107   (let ((artseq (gnus-compress-sequence articles)))
1108     (when (and artseq (nnimap-possibly-change-group group server))
1109       (with-current-buffer nnimap-server-buffer
1110         (if force
1111             (and (imap-message-flags-add
1112                   (imap-range-to-message-set artseq) "\\Deleted")
1113                  (setq articles nil))
1114           (let ((days (or (and nnmail-expiry-wait-function
1115                                (funcall nnmail-expiry-wait-function group))
1116                           nnmail-expiry-wait)))
1117             (cond ((eq days 'immediate)
1118                    (and (imap-message-flags-add
1119                          (imap-range-to-message-set artseq) "\\Deleted")
1120                         (setq articles nil)))
1121                   ((numberp days)
1122                    (let ((oldarts (imap-search
1123                                    (format "UID %s NOT SINCE %s"
1124                                            (imap-range-to-message-set artseq)
1125                                            (nnimap-date-days-ago days))))
1126                          (imap-fetch-data-hook
1127                           '(nnimap-request-expire-articles-progress)))
1128                      (and oldarts
1129                           (imap-message-flags-add
1130                            (imap-range-to-message-set
1131                             (gnus-compress-sequence oldarts))
1132                            "\\Deleted")
1133                           (setq articles (gnus-set-difference
1134                                           articles oldarts)))))))))))
1135   ;; return articles not deleted
1136   articles)
1137
1138 (deffoo nnimap-request-move-article (article group server
1139                                              accept-form &optional last)
1140   (when (nnimap-possibly-change-server server)
1141     (save-excursion
1142       (let ((buf (get-buffer-create " *nnimap move*"))
1143             (nnimap-current-move-article article)
1144             (nnimap-current-move-group group)
1145             (nnimap-current-move-server nnimap-current-server)
1146             result)
1147         (and (nnimap-request-article article group server)
1148              (save-excursion
1149                (set-buffer buf)
1150                (buffer-disable-undo (current-buffer))
1151                (insert-buffer-substring nntp-server-buffer)
1152                (setq result (eval accept-form))
1153                (kill-buffer buf)
1154                result)
1155              (nnimap-request-expire-articles (list article) group server t))
1156         result))))
1157   
1158 (deffoo nnimap-request-accept-article (group &optional server last)
1159   (when (nnimap-possibly-change-server server)
1160     (let (uid)
1161       (if (setq uid
1162                 (if (string= nnimap-current-server nnimap-current-move-server)
1163                     ;; moving article within same server, speed it up...
1164                     (and (nnimap-possibly-change-group
1165                           nnimap-current-move-group)
1166                          (imap-message-copy (number-to-string
1167                                              nnimap-current-move-article)
1168                                             group 'dontcreate nil
1169                                             nnimap-server-buffer))
1170                   (with-current-buffer (current-buffer)
1171                     (goto-char (point-min))
1172                     ;; remove any 'From blabla' lines, some IMAP servers
1173                     ;; reject the entire message otherwise.
1174                     (when (looking-at "^From[^:]")
1175                       (kill-region (point) (progn (forward-line) (point))))
1176                     ;; turn into rfc822 format (\r\n eol's)
1177                     (while (search-forward "\n" nil t)
1178                       (replace-match "\r\n")))
1179                   ;; this 'or' is for Cyrus server bug
1180                   (or (null (imap-current-mailbox nnimap-server-buffer))
1181                       (imap-mailbox-unselect nnimap-server-buffer))
1182                   (imap-message-append group (current-buffer) nil nil
1183                                        nnimap-server-buffer)))
1184           (cons group (nth 1 uid))
1185         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1186
1187 (deffoo nnimap-request-delete-group (group force &optional server)
1188   (when (nnimap-possibly-change-server server)
1189     (with-current-buffer nnimap-server-buffer
1190       (if force
1191           (or (null (imap-mailbox-status group 'uidvalidity))
1192               (imap-mailbox-delete group))
1193         ;; UNSUBSCRIBE?
1194         t))))
1195
1196 (deffoo nnimap-request-rename-group (group new-name &optional server)
1197   (when (nnimap-possibly-change-server server)
1198     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1199
1200 (defun nnimap-expunge (mailbox server)
1201   (when (nnimap-possibly-change-group mailbox server)
1202     (imap-mailbox-expunge nnimap-server-buffer)))
1203
1204 (defun nnimap-acl-get (mailbox server)
1205   (when (nnimap-possibly-change-server server)
1206     (and (imap-capability 'ACL nnimap-server-buffer)
1207          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1208
1209 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1210   (when (nnimap-possibly-change-server (cadr method))
1211     (unless (imap-capability 'ACL nnimap-server-buffer)
1212       (error "Your server does not support ACL editing"))
1213     (with-current-buffer nnimap-server-buffer
1214       ;; delete all removed identifiers
1215       (mapcar (lambda (old-acl)
1216                 (unless (assoc (car old-acl) new-acls)
1217                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1218                       (error "Can't delete ACL for %s" (car old-acl)))))
1219               old-acls)
1220       ;; set all changed acl's
1221       (mapcar (lambda (new-acl)
1222                 (let ((new-rights (cdr new-acl))
1223                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1224                   (unless (and old-rights new-rights
1225                                (string= old-rights new-rights))
1226                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1227                         (error "Can't set ACL for %s to %s" (car new-acl)
1228                                new-rights)))))
1229               new-acls)
1230       t)))
1231
1232 \f
1233 ;;; Internal functions
1234
1235 ;;
1236 ;; This is confusing.
1237 ;;
1238 ;; mark      => read, tick, draft, reply etc
1239 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1240 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1241 ;;
1242 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1243 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1244 ;;
1245
1246 (defconst nnimap-mark-to-predicate-alist
1247   (mapcar
1248    (lambda (pair)                       ; cdr is the mark
1249      (or (assoc (cdr pair)
1250                 '((read . "SEEN")
1251                   (tick . "FLAGGED")
1252                   (draft . "DRAFT")
1253                   (reply . "ANSWERED")))
1254          (cons (cdr pair)
1255                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1256    (cons '(read . read) gnus-article-mark-lists)))
1257
1258 (defun nnimap-mark-to-predicate (pred)
1259   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1260 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1261 to be used within a IMAP SEARCH query."
1262   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1263
1264 (defconst nnimap-mark-to-flag-alist
1265   (mapcar
1266    (lambda (pair)
1267      (or (assoc (cdr pair)
1268                 '((read . "\\Seen")
1269                   (tick . "\\Flagged")
1270                   (draft . "\\Draft")
1271                   (reply . "\\Answered")))
1272          (cons (cdr pair)
1273                (format "gnus-%s" (symbol-name (cdr pair))))))
1274    (cons '(read . read) gnus-article-mark-lists)))
1275
1276 (defun nnimap-mark-to-flag-1 (preds)
1277   (if (and (not (null preds)) (listp preds))
1278       (cons (nnimap-mark-to-flag (car preds))
1279             (nnimap-mark-to-flag (cdr preds)))
1280     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1281
1282 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1283   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1284 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1285 be used in a STORE FLAGS command."
1286   (let ((result (nnimap-mark-to-flag-1 preds)))
1287     (setq result (if (and (or make-string always-list)
1288                           (not (listp result)))
1289                      (list result)
1290                    result))
1291     (if make-string
1292         (mapconcat (lambda (flag)
1293                      (if (listp flag)
1294                          (mapconcat 'identity flag " ")
1295                        flag))
1296                    result " ")
1297       result)))
1298
1299 (defun nnimap-mark-permanent-p (mark &optional group)
1300   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1301   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1302
1303 (defun nnimap-remassoc (key alist)
1304   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1305 The modified LIST is returned.  If the first member
1306 of LIST has a car that is `equal' to KEY, there is no way to remove it
1307 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1308 sure of changing the value of `foo'."
1309   (when alist
1310     (if (equal key (caar alist))
1311         (cdr alist)
1312       (setcdr alist (nnimap-remassoc key (cdr alist)))
1313       alist)))
1314   
1315 (defun nnimap-update-alist-soft (key value alist)
1316   (if value
1317       (cons (cons key value) (nnimap-remassoc key alist))
1318     (nnimap-remassoc key alist)))
1319
1320 (when nnimap-debug
1321   (require 'trace)
1322   (buffer-disable-undo (get-buffer-create nnimap-debug))
1323   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1324         '(
1325           nnimap-possibly-change-server
1326           nnimap-verify-uidvalidity
1327           nnimap-find-minmax-uid
1328           nnimap-before-find-minmax-bugworkaround
1329           nnimap-possibly-change-group
1330           ;;nnimap-replace-whitespace
1331           nnimap-retrieve-headers-progress
1332           nnimap-retrieve-which-headers
1333           nnimap-group-overview-filename
1334           nnimap-retrieve-headers-from-file
1335           nnimap-retrieve-headers-from-server
1336           nnimap-retrieve-headers
1337           nnimap-open-connection
1338           nnimap-open-server
1339           nnimap-server-opened
1340           nnimap-close-server
1341           nnimap-request-close
1342           nnimap-status-message
1343           ;;nnimap-demule
1344           nnimap-request-article-part
1345           nnimap-request-article
1346           nnimap-request-head
1347           nnimap-request-body
1348           nnimap-request-group
1349           nnimap-close-group
1350           nnimap-pattern-to-list-arguments
1351           nnimap-request-list
1352           nnimap-request-post
1353           nnimap-retrieve-groups
1354           nnimap-request-update-info-internal
1355           nnimap-request-type
1356           nnimap-request-set-mark
1357           nnimap-split-to-groups
1358           nnimap-split-find-rule
1359           nnimap-split-find-inbox
1360           nnimap-split-articles
1361           nnimap-request-scan
1362           nnimap-request-newgroups
1363           nnimap-request-create-group
1364           nnimap-time-substract
1365           nnimap-date-days-ago
1366           nnimap-request-expire-articles-progress
1367           nnimap-request-expire-articles
1368           nnimap-request-move-article
1369           nnimap-request-accept-article
1370           nnimap-request-delete-group
1371           nnimap-request-rename-group
1372           gnus-group-nnimap-expunge
1373           gnus-group-nnimap-edit-acl
1374           gnus-group-nnimap-edit-acl-done
1375           nnimap-group-mode-hook
1376           nnimap-mark-to-predicate
1377           nnimap-mark-to-flag-1
1378           nnimap-mark-to-flag
1379           nnimap-mark-permanent-p
1380           nnimap-remassoc
1381           nnimap-update-alist-soft
1382           )))
1383
1384 (provide 'nnimap)
1385
1386 ;;; nnimap.el ends here