(nnimap-process-quirk): Renamed function to avoid collision.
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2011 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
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 3 of the License, or
13 ;; (at your option) 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.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (eval-and-compile
34   (require 'nnheader))
35
36 (eval-when-compile
37   (require 'cl))
38
39 (require 'nnheader)
40 (require 'gnus-util)
41 (require 'gnus)
42 (require 'nnoo)
43 (require 'netrc)
44 (require 'utf7)
45 (require 'tls)
46 (require 'parse-time)
47 (require 'nnmail)
48 (require 'proto-stream)
49
50 (autoload 'auth-source-forget-user-or-password "auth-source")
51 (autoload 'auth-source-user-or-password "auth-source")
52
53 (nnoo-declare nnimap)
54
55 (defvoo nnimap-address nil
56   "The address of the IMAP server.")
57
58 (defvoo nnimap-server-port nil
59   "The IMAP port used.
60 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
61 it will default to `imap'.")
62
63 (defvoo nnimap-stream 'undecided
64   "How nnimap will talk to the IMAP server.
65 Values are `ssl', `network', `starttls' or `shell'.
66 The default is to try `ssl' first, and then `network'.")
67
68 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
69                                  (if (listp imap-shell-program)
70                                      (car imap-shell-program)
71                                    imap-shell-program)
72                                "ssh %s imapd"))
73
74 (defvoo nnimap-inbox nil
75   "The mail box where incoming mail arrives and should be split out of.")
76
77 (defvoo nnimap-split-methods nil
78   "How mail is split.
79 Uses the same syntax as nnmail-split-methods")
80
81 (defvoo nnimap-split-fancy nil
82   "Uses the same syntax as nnmail-split-fancy.")
83
84 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
85   "Articles with the flags in the list will not be considered when splitting.")
86
87 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
88                         "Emacs 24.1")
89
90 (defvoo nnimap-authenticator nil
91   "How nnimap authenticate itself to the server.
92 Possible choices are nil (use default methods) or `anonymous'.")
93
94 (defvoo nnimap-expunge t
95   "If non-nil, expunge articles after deleting them.
96 This is always done if the server supports UID EXPUNGE, but it's
97 not done by default on servers that doesn't support that command.")
98
99 (defvoo nnimap-streaming t
100   "If non-nil, try to use streaming commands with IMAP servers.
101 Switching this off will make nnimap slower, but it helps with
102 some servers.")
103
104 (defvoo nnimap-connection-alist nil)
105
106 (defvoo nnimap-current-infos nil)
107
108 (defvoo nnimap-fetch-partial-articles nil
109   "If non-nil, Gnus will fetch partial articles.
110 If t, nnimap will fetch only the first part.  If a string, it
111 will fetch all parts that have types that match that string.  A
112 likely value would be \"text/\" to automatically fetch all
113 textual parts.")
114
115 (defvar nnimap-process nil)
116
117 (defvar nnimap-status-string "")
118
119 (defvar nnimap-split-download-body-default nil
120   "Internal variable with default value for `nnimap-split-download-body'.")
121
122 (defvar nnimap-keepalive-timer nil)
123 (defvar nnimap-process-buffers nil)
124
125 (defstruct nnimap
126   group process commands capabilities select-result newlinep server
127   last-command-time greeting examined stream-type)
128
129 (defvar nnimap-object nil)
130
131 (defvar nnimap-mark-alist
132   '((read "\\Seen" %Seen)
133     (tick "\\Flagged" %Flagged)
134     (reply "\\Answered" %Answered)
135     (expire "gnus-expire")
136     (dormant "gnus-dormant")
137     (score "gnus-score")
138     (save "gnus-save")
139     (download "gnus-download")
140     (forward "gnus-forward")))
141
142 (defvar nnimap-quirks
143   '(("QRESYNC" "Zimbra" "QRESYNC ")))
144
145 (defun nnimap-buffer ()
146   (nnimap-find-process-buffer nntp-server-buffer))
147
148 (defun nnimap-header-parameters ()
149   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
150           (format
151            (if (nnimap-ver4-p)
152                "BODY.PEEK[HEADER.FIELDS %s]"
153              "RFC822.HEADER.LINES %s")
154            (append '(Subject From Date Message-Id
155                              References In-Reply-To Xref)
156                    nnmail-extra-headers))))
157
158 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
159   (with-current-buffer nntp-server-buffer
160     (erase-buffer)
161     (when (nnimap-possibly-change-group group server)
162       (with-current-buffer (nnimap-buffer)
163         (erase-buffer)
164         (nnimap-wait-for-response
165          (nnimap-send-command
166           "UID FETCH %s %s"
167           (nnimap-article-ranges (gnus-compress-sequence articles))
168           (nnimap-header-parameters))
169          t)
170         (nnimap-transform-headers)
171         (nnheader-remove-cr-followed-by-lf))
172       (insert-buffer-substring
173        (nnimap-find-process-buffer (current-buffer))))
174     'headers))
175
176 (defun nnimap-transform-headers ()
177   (goto-char (point-min))
178   (let (article bytes lines size string)
179     (block nil
180       (while (not (eobp))
181         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
182           (delete-region (point) (progn (forward-line 1) (point)))
183           (when (eobp)
184             (return)))
185         (setq article (match-string 1))
186         ;; Unfold quoted {number} strings.
187         (while (re-search-forward "[^]][ (]{\\([0-9]+\\)}\r?\n"
188                                   (1+ (line-end-position)) t)
189           (setq size (string-to-number (match-string 1)))
190           (delete-region (+ (match-beginning 0) 2) (point))
191           (setq string (buffer-substring (point) (+ (point) size)))
192           (delete-region (point) (+ (point) size))
193           (insert (format "%S" string)))
194         (setq bytes (nnimap-get-length)
195               lines nil)
196         (beginning-of-line)
197         (setq size
198               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
199                                       (line-end-position)
200                                       t)
201                    (match-string 1)))
202         (beginning-of-line)
203         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
204           (let ((structure (ignore-errors
205                              (read (current-buffer)))))
206             (while (and (consp structure)
207                         (not (stringp (car structure))))
208               (setq structure (car structure)))
209             (setq lines (nth 7 structure))))
210         (delete-region (line-beginning-position) (line-end-position))
211         (insert (format "211 %s Article retrieved." article))
212         (forward-line 1)
213         (when size
214           (insert (format "Chars: %s\n" size)))
215         (when lines
216           (insert (format "Lines: %s\n" lines)))
217         (unless (re-search-forward "^\r$" nil t)
218           (goto-char (point-max)))
219         (delete-region (line-beginning-position) (line-end-position))
220         (insert ".")
221         (forward-line 1)))))
222
223 (defun nnimap-unfold-quoted-lines ()
224   ;; Unfold quoted {number} strings.
225   (let (size string)
226     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
227       (setq size (string-to-number (match-string 1)))
228       (delete-region (1+ (match-beginning 0)) (point))
229       (setq string (buffer-substring (point) (+ (point) size)))
230       (delete-region (point) (+ (point) size))
231       (insert (format "%S" string)))))
232
233 (defun nnimap-get-length ()
234   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
235        (string-to-number (match-string 1))))
236
237 (defun nnimap-article-ranges (ranges)
238   (let (result)
239     (cond
240      ((numberp ranges)
241       (number-to-string ranges))
242      ((numberp (cdr ranges))
243       (format "%d:%d" (car ranges) (cdr ranges)))
244      (t
245       (dolist (elem ranges)
246         (push
247          (if (consp elem)
248              (format "%d:%d" (car elem) (cdr elem))
249            (number-to-string elem))
250          result))
251       (mapconcat #'identity (nreverse result) ",")))))
252
253 (deffoo nnimap-open-server (server &optional defs)
254   (if (nnimap-server-opened server)
255       t
256     (unless (assq 'nnimap-address defs)
257       (setq defs (append defs (list (list 'nnimap-address server)))))
258     (nnoo-change-server 'nnimap server defs)
259     (or (nnimap-find-connection nntp-server-buffer)
260         (nnimap-open-connection nntp-server-buffer))))
261
262 (defun nnimap-make-process-buffer (buffer)
263   (with-current-buffer
264       (generate-new-buffer (format "*nnimap %s %s %s*"
265                                    nnimap-address nnimap-server-port
266                                    (gnus-buffer-exists-p buffer)))
267     (mm-disable-multibyte)
268     (buffer-disable-undo)
269     (gnus-add-buffer)
270     (set (make-local-variable 'after-change-functions) nil)
271     (set (make-local-variable 'nnimap-object)
272          (make-nnimap :server (nnoo-current-server 'nnimap)))
273     (push (list buffer (current-buffer)) nnimap-connection-alist)
274     (push (current-buffer) nnimap-process-buffers)
275     (current-buffer)))
276
277 (defun nnimap-credentials (address ports &optional inhibit-create)
278   (let (port credentials)
279     ;; Request the credentials from all ports, but only query on the
280     ;; last port if all the previous ones have failed.
281     (while (and (null credentials)
282                 (setq port (pop ports)))
283       (setq credentials
284             (auth-source-user-or-password
285              '("login" "password") address port nil
286              (if inhibit-create
287                  nil
288                (null ports)))))
289     credentials))
290
291 (defun nnimap-keepalive ()
292   (let ((now (current-time)))
293     (dolist (buffer nnimap-process-buffers)
294       (when (buffer-name buffer)
295         (with-current-buffer buffer
296           (when (and nnimap-object
297                      (nnimap-last-command-time nnimap-object)
298                      (> (gnus-float-time
299                          (time-subtract
300                           now
301                           (nnimap-last-command-time nnimap-object)))
302                         ;; More than five minutes since the last command.
303                         (* 5 60)))
304             (nnimap-send-command "NOOP")))))))
305
306 (defun nnimap-open-connection (buffer)
307   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
308   ;; `ssl' when nnimap-server-port was nil.  Sort of.
309   (when (and nnimap-server-port
310              (eq nnimap-stream 'undecided))
311     (setq nnimap-stream 'ssl))
312   (let ((stream
313          (if (eq nnimap-stream 'undecided)
314              (loop for type in '(ssl network)
315                    for stream = (let ((nnimap-stream type))
316                                   (nnimap-open-connection-1 buffer))
317                    while (eq stream 'no-connect)
318                    finally (return stream))
319            (nnimap-open-connection-1 buffer))))
320     (if (eq stream 'no-connect)
321         nil
322       stream)))
323
324 (defun nnimap-open-connection-1 (buffer)
325   (unless nnimap-keepalive-timer
326     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
327                                               'nnimap-keepalive)))
328   (with-current-buffer (nnimap-make-process-buffer buffer)
329     (let* ((coding-system-for-read 'binary)
330            (coding-system-for-write 'binary)
331            (port nil)
332            (ports
333             (cond
334              ((or (eq nnimap-stream 'network)
335                   (eq nnimap-stream 'starttls))
336               (nnheader-message 7 "Opening connection to %s..."
337                                 nnimap-address)
338               '("143" "imap"))
339              ((eq nnimap-stream 'shell)
340               (nnheader-message 7 "Opening connection to %s via shell..."
341                                 nnimap-address)
342               '("imap"))
343              ((memq nnimap-stream '(ssl tls))
344               (nnheader-message 7 "Opening connection to %s via tls..."
345                                 nnimap-address)
346               '("143" "993" "imap" "imaps"))
347              (t
348               (error "Unknown stream type: %s" nnimap-stream))))
349            (proto-stream-always-use-starttls t)
350            login-result credentials)
351       (when nnimap-server-port
352         (setq ports (append ports (list nnimap-server-port))))
353       (destructuring-bind (stream greeting capabilities stream-type)
354           (open-protocol-stream
355            "*nnimap*" (current-buffer) nnimap-address (car (last ports))
356            :type nnimap-stream
357            :shell-command nnimap-shell-program
358            :capability-command "1 CAPABILITY\r\n"
359            :success " OK "
360            :starttls-function
361            (lambda (capabilities)
362              (when (gnus-string-match-p "STARTTLS" capabilities)
363                "1 STARTTLS\r\n")))
364         (setf (nnimap-process nnimap-object) stream)
365         (setf (nnimap-stream-type nnimap-object) stream-type)
366         (if (not stream)
367             (progn
368               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
369                                nnimap-address port nnimap-stream)
370               'no-connect)
371           (gnus-set-process-query-on-exit-flag stream nil)
372           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
373               (nnheader-report 'nnimap "%s" greeting)
374             ;; Store the greeting (for debugging purposes).
375             (setf (nnimap-greeting nnimap-object) greeting)
376             (setf (nnimap-capabilities nnimap-object)
377                   (mapcar #'upcase
378                           (split-string capabilities)))
379             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
380               (if (not (setq credentials
381                              (if (eq nnimap-authenticator 'anonymous)
382                                  (list "anonymous"
383                                        (message-make-address))
384                                (or
385                                 ;; First look for the credentials based
386                                 ;; on the virtual server name.
387                                 (nnimap-credentials
388                                  (nnoo-current-server 'nnimap) ports t)
389                                 ;; Then look them up based on the
390                                 ;; physical address.
391                                 (nnimap-credentials nnimap-address ports)))))
392                   (setq nnimap-object nil)
393                 (setq login-result
394                       (nnimap-login (car credentials) (cadr credentials)))
395                 (unless (car login-result)
396                   ;; If the login failed, then forget the credentials
397                   ;; that are now possibly cached.
398                   (dolist (host (list (nnoo-current-server 'nnimap)
399                                       nnimap-address))
400                     (dolist (port ports)
401                       (dolist (element '("login" "password"))
402                         (auth-source-forget-user-or-password
403                          element host port))))
404                   (delete-process (nnimap-process nnimap-object))
405                   (setq nnimap-object nil))))
406             (when nnimap-object
407               (when (nnimap-capability "QRESYNC")
408                 (nnimap-command "ENABLE QRESYNC"))
409               (nnimap-process nnimap-object))))))))
410
411 (autoload 'rfc2104-hash "rfc2104")
412
413 (defun nnimap-login (user password)
414   (cond
415    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
416    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
417    ;; and we're using an encrypted connection.
418    ((and (not (nnimap-capability "LOGINDISABLED"))
419          (eq (nnimap-stream-type nnimap-object) 'tls))
420     (nnimap-command "LOGIN %S %S" user password))
421    ((nnimap-capability "AUTH=CRAM-MD5")
422     (erase-buffer)
423     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
424           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
425       (process-send-string
426        (get-buffer-process (current-buffer))
427        (concat
428         (base64-encode-string
429          (concat user " "
430                  (rfc2104-hash 'md5 64 16 password
431                                (base64-decode-string challenge))))
432         "\r\n"))
433       (nnimap-wait-for-response sequence)))
434    ((not (nnimap-capability "LOGINDISABLED"))
435     (nnimap-command "LOGIN %S %S" user password))
436    ((nnimap-capability "AUTH=PLAIN")
437     (nnimap-command
438      "AUTHENTICATE PLAIN %s"
439      (base64-encode-string
440       (format "\000%s\000%s"
441               (nnimap-quote-specials user)
442               (nnimap-quote-specials password)))))))
443
444 (defun nnimap-quote-specials (string)
445   (with-temp-buffer
446     (insert string)
447     (goto-char (point-min))
448     (while (re-search-forward "[\\\"]" nil t)
449       (forward-char -1)
450       (insert "\\")
451       (forward-char 1))
452     (buffer-string)))
453
454 (defun nnimap-find-parameter (parameter elems)
455   (let (result)
456     (dolist (elem elems)
457       (cond
458        ((equal (car elem) parameter)
459         (setq result (cdr elem)))
460        ((and (equal (car elem) "OK")
461              (consp (cadr elem))
462              (equal (caadr elem) parameter))
463         (setq result (cdr (cadr elem))))))
464     result))
465
466 (deffoo nnimap-close-server (&optional server)
467   (when (nnoo-change-server 'nnimap server nil)
468     (ignore-errors
469       (delete-process (get-buffer-process (nnimap-buffer))))
470     (nnoo-close-server 'nnimap server)
471     t))
472
473 (deffoo nnimap-request-close ()
474   t)
475
476 (deffoo nnimap-server-opened (&optional server)
477   (and (nnoo-current-server-p 'nnimap server)
478        nntp-server-buffer
479        (gnus-buffer-live-p nntp-server-buffer)
480        (nnimap-find-connection nntp-server-buffer)))
481
482 (deffoo nnimap-status-message (&optional server)
483   nnimap-status-string)
484
485 (deffoo nnimap-request-article (article &optional group server to-buffer)
486   (with-current-buffer nntp-server-buffer
487     (let ((result (nnimap-possibly-change-group group server))
488           parts structure)
489       (when (stringp article)
490         (setq article (nnimap-find-article-by-message-id group article)))
491       (when (and result
492                  article)
493         (erase-buffer)
494         (with-current-buffer (nnimap-buffer)
495           (erase-buffer)
496           (when nnimap-fetch-partial-articles
497             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
498             (goto-char (point-min))
499             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
500               (setq structure (ignore-errors
501                                 (let ((start (point)))
502                                   (forward-sexp 1)
503                                   (downcase-region start (point))
504                                   (goto-char start)
505                                   (read (current-buffer))))
506                     parts (nnimap-find-wanted-parts structure))))
507           (when (if parts
508                     (nnimap-get-partial-article article parts structure)
509                   (nnimap-get-whole-article article))
510             (let ((buffer (current-buffer)))
511               (with-current-buffer (or to-buffer nntp-server-buffer)
512                 (erase-buffer)
513                 (insert-buffer-substring buffer)
514                 (nnheader-ms-strip-cr)
515                 (cons group article)))))))))
516
517 (deffoo nnimap-request-head (article &optional group server to-buffer)
518   (when (nnimap-possibly-change-group group server)
519     (with-current-buffer (nnimap-buffer)
520       (when (stringp article)
521         (setq article (nnimap-find-article-by-message-id group article)))
522       (if (null article)
523           nil
524         (nnimap-get-whole-article
525          article (format "UID FETCH %%d %s"
526                          (nnimap-header-parameters)))
527         (let ((buffer (current-buffer)))
528           (with-current-buffer (or to-buffer nntp-server-buffer)
529             (erase-buffer)
530             (insert-buffer-substring buffer)
531             (nnheader-ms-strip-cr)
532             (cons group article)))))))
533
534 (defun nnimap-get-whole-article (article &optional command)
535   (let ((result
536          (nnimap-command
537           (or command
538               (if (nnimap-ver4-p)
539                   "UID FETCH %d BODY.PEEK[]"
540                 "UID FETCH %d RFC822.PEEK"))
541           article)))
542     ;; Check that we really got an article.
543     (goto-char (point-min))
544     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
545       (setq result nil))
546     (when result
547       ;; Remove any data that may have arrived before the FETCH data.
548       (beginning-of-line)
549       (unless (bobp)
550         (delete-region (point-min) (point)))
551       (let ((bytes (nnimap-get-length)))
552         (delete-region (line-beginning-position)
553                        (progn (forward-line 1) (point)))
554         (goto-char (+ (point) bytes))
555         (delete-region (point) (point-max)))
556       t)))
557
558 (defun nnimap-capability (capability)
559   (member capability (nnimap-capabilities nnimap-object)))
560
561 (defun nnimap-ver4-p ()
562   (nnimap-capability "IMAP4REV1"))
563
564 (defun nnimap-get-partial-article (article parts structure)
565   (let ((result
566          (nnimap-command
567           "UID FETCH %d (%s %s)"
568           article
569           (if (nnimap-ver4-p)
570               "BODY.PEEK[HEADER]"
571             "RFC822.HEADER")
572           (if (nnimap-ver4-p)
573               (mapconcat (lambda (part)
574                            (format "BODY.PEEK[%s]" part))
575                          parts " ")
576             (mapconcat (lambda (part)
577                          (format "RFC822.PEEK[%s]" part))
578                        parts " ")))))
579     (when result
580       (nnimap-convert-partial-article structure))))
581
582 (defun nnimap-convert-partial-article (structure)
583   ;; First just skip past the headers.
584   (goto-char (point-min))
585   (let ((bytes (nnimap-get-length))
586         id parts)
587     ;; Delete "FETCH" line.
588     (delete-region (line-beginning-position)
589                    (progn (forward-line 1) (point)))
590     (goto-char (+ (point) bytes))
591     ;; Collect all the body parts.
592     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
593       (setq id (match-string 1)
594             bytes (or (nnimap-get-length) 0))
595       (beginning-of-line)
596       (delete-region (point) (progn (forward-line 1) (point)))
597       (push (list id (buffer-substring (point) (+ (point) bytes)))
598             parts)
599       (delete-region (point) (+ (point) bytes)))
600     ;; Delete trailing junk.
601     (delete-region (point) (point-max))
602     ;; Now insert all the parts again where they fit in the structure.
603     (nnimap-insert-partial-structure structure parts)
604     t))
605
606 (defun nnimap-insert-partial-structure (structure parts &optional subp)
607   (let (type boundary)
608     (let ((bstruc structure))
609       (while (consp (car bstruc))
610         (pop bstruc))
611       (setq type (car bstruc))
612       (setq bstruc (car (cdr bstruc)))
613       (let ((has-boundary (member "boundary" bstruc)))
614         (when has-boundary
615           (setq boundary (cadr has-boundary)))))
616     (when subp
617       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
618                       (downcase type) boundary)))
619     (while (not (stringp (car structure)))
620       (insert "\n--" boundary "\n")
621       (if (consp (caar structure))
622           (nnimap-insert-partial-structure (pop structure) parts t)
623         (let ((bit (pop structure)))
624           (insert (format  "Content-type: %s/%s"
625                            (downcase (nth 0 bit))
626                            (downcase (nth 1 bit))))
627           (if (member "CHARSET" (nth 2 bit))
628               (insert (format
629                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
630             (insert "\n"))
631           (insert (format "Content-transfer-encoding: %s\n"
632                           (nth 5 bit)))
633           (insert "\n")
634           (when (assoc (nth 9 bit) parts)
635             (insert (cadr (assoc (nth 9 bit) parts)))))))
636     (insert "\n--" boundary "--\n")))
637
638 (defun nnimap-find-wanted-parts (structure)
639   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
640
641 (defun nnimap-find-wanted-parts-1 (structure prefix)
642   (let ((num 1)
643         parts)
644     (while (consp (car structure))
645       (let ((sub (pop structure)))
646         (if (consp (car sub))
647             (push (nnimap-find-wanted-parts-1
648                    sub (if (string= prefix "")
649                            (number-to-string num)
650                          (format "%s.%s" prefix num)))
651                   parts)
652           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
653                 (id (if (string= prefix "")
654                         (number-to-string num)
655                       (format "%s.%s" prefix num))))
656             (setcar (nthcdr 9 sub) id)
657             (when (if (eq nnimap-fetch-partial-articles t)
658                       (equal id "1")
659                     (string-match nnimap-fetch-partial-articles type))
660               (push id parts))))
661         (incf num)))
662     (nreverse parts)))
663
664 (deffoo nnimap-request-group (group &optional server dont-check info)
665   (let ((result (nnimap-possibly-change-group
666                  ;; Don't SELECT the group if we're going to select it
667                  ;; later, anyway.
668                  (if (and (not dont-check)
669                           (assoc group nnimap-current-infos))
670                      nil
671                    group)
672                  server))
673         articles active marks high low)
674     (with-current-buffer nntp-server-buffer
675       (when result
676         (if (and dont-check
677                  (setq active (nth 2 (assoc group nnimap-current-infos))))
678             (insert (format "211 %d %d %d %S\n"
679                             (- (cdr active) (car active))
680                             (car active)
681                             (cdr active)
682                             group))
683           (with-current-buffer (nnimap-buffer)
684             (erase-buffer)
685             (let ((group-sequence
686                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
687                   (flag-sequence
688                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
689               (setf (nnimap-group nnimap-object) group)
690               (nnimap-wait-for-response flag-sequence)
691               (setq marks
692                     (nnimap-flags-to-marks
693                      (nnimap-parse-flags
694                       (list (list group-sequence flag-sequence
695                                   1 group "SELECT")))))
696               (when (and info
697                          marks)
698                 (nnimap-update-infos marks (list info))
699                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
700               (goto-char (point-max))
701               (let ((uidnext (nth 5 (car marks))))
702                 (setq high (or (if uidnext
703                                    (1- uidnext)
704                                  (nth 3 (car marks)))
705                                0)
706                       low (or (nth 4 (car marks)) uidnext 1)))))
707           (erase-buffer)
708           (insert
709            (format
710             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
711         t))))
712
713 (deffoo nnimap-request-create-group (group &optional server args)
714   (when (nnimap-possibly-change-group nil server)
715     (with-current-buffer (nnimap-buffer)
716       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
717
718 (deffoo nnimap-request-delete-group (group &optional force server)
719   (when (nnimap-possibly-change-group nil server)
720     (with-current-buffer (nnimap-buffer)
721       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
722
723 (deffoo nnimap-request-rename-group (group new-name &optional server)
724   (when (nnimap-possibly-change-group nil server)
725     (with-current-buffer (nnimap-buffer)
726       (nnimap-unselect-group)
727       (car (nnimap-command "RENAME %S %S"
728                            (utf7-encode group t) (utf7-encode new-name t))))))
729
730 (defun nnimap-unselect-group ()
731   ;; Make sure we don't have this group open read/write by asking
732   ;; to examine a mailbox that doesn't exist.  This seems to be
733   ;; the only way that allows us to reliably go back to unselected
734   ;; state on Courier.
735   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
736
737 (deffoo nnimap-request-expunge-group (group &optional server)
738   (when (nnimap-possibly-change-group group server)
739     (with-current-buffer (nnimap-buffer)
740       (car (nnimap-command "EXPUNGE")))))
741
742 (defun nnimap-get-flags (spec)
743   (let ((articles nil)
744         elems end)
745     (with-current-buffer (nnimap-buffer)
746       (erase-buffer)
747       (nnimap-wait-for-response (nnimap-send-command
748                                  "UID FETCH %s FLAGS" spec))
749       (setq end (point))
750       (subst-char-in-region (point-min) (point-max)
751                             ?\\ ?% t)
752       (goto-char (point-min))
753       (while (search-forward " FETCH " end t)
754         (setq elems (read (current-buffer)))
755         (push (cons (cadr (memq 'UID elems))
756                     (cadr (memq 'FLAGS elems)))
757               articles)))
758     (nreverse articles)))
759
760 (deffoo nnimap-close-group (group &optional server)
761   t)
762
763 (deffoo nnimap-request-move-article (article group server accept-form
764                                              &optional last internal-move-group)
765   (with-temp-buffer
766     (mm-disable-multibyte)
767     (when (funcall (if internal-move-group
768                        'nnimap-request-head
769                      'nnimap-request-article)
770                    article group server (current-buffer))
771       ;; If the move is internal (on the same server), just do it the easy
772       ;; way.
773       (let ((message-id (message-field-value "message-id")))
774         (if internal-move-group
775             (let ((result
776                    (with-current-buffer (nnimap-buffer)
777                      (nnimap-command "UID COPY %d %S"
778                                      article
779                                      (utf7-encode internal-move-group t)))))
780               (when (car result)
781                 (nnimap-delete-article article)
782                 (cons internal-move-group
783                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
784                           (nnimap-find-article-by-message-id
785                            internal-move-group message-id)))))
786           ;; Move the article to a different method.
787           (let ((result (eval accept-form)))
788             (when result
789               (nnimap-delete-article article)
790               result)))))))
791
792 (deffoo nnimap-request-expire-articles (articles group &optional server force)
793   (cond
794    ((null articles)
795     nil)
796    ((not (nnimap-possibly-change-group group server))
797     articles)
798    ((and force
799          (eq nnmail-expiry-target 'delete))
800     (unless (nnimap-delete-article (gnus-compress-sequence articles))
801       (nnheader-message 7 "Article marked for deletion, but not expunged."))
802     nil)
803    (t
804     (let ((deletable-articles
805            (if (or force
806                    (eq nnmail-expiry-wait 'immediate))
807                articles
808              (gnus-sorted-intersection
809               articles
810               (nnimap-find-expired-articles group)))))
811       (if (null deletable-articles)
812           articles
813         (if (eq nnmail-expiry-target 'delete)
814             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
815           (setq deletable-articles
816                 (nnimap-process-expiry-targets
817                  deletable-articles group server)))
818         ;; Return the articles we didn't delete.
819         (gnus-sorted-complement articles deletable-articles))))))
820
821 (defun nnimap-process-expiry-targets (articles group server)
822   (let ((deleted-articles nil))
823     (cond
824      ;; shortcut further processing if we're going to delete the articles
825      ((eq nnmail-expiry-target 'delete)
826       (setq deleted-articles articles)
827       t)
828      ;; or just move them to another folder on the same IMAP server
829      ((and (not (functionp nnmail-expiry-target))
830            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
831                               (gnus-server-to-method
832                                (format "nnimap:%s" server))))
833       (and (nnimap-possibly-change-group group server)
834            (with-current-buffer (nnimap-buffer)
835              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
836              (nnimap-command
837               "UID COPY %s %S"
838               (nnimap-article-ranges (gnus-compress-sequence articles))
839               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
840              (setq deleted-articles articles)))
841       t)
842      (t
843       (dolist (article articles)
844         (let ((target nnmail-expiry-target))
845           (with-temp-buffer
846             (mm-disable-multibyte)
847             (when (nnimap-request-article article group server (current-buffer))
848               (nnheader-message 7 "Expiring article %s:%d" group article)
849               (when (functionp target)
850                 (setq target (funcall target group)))
851               (when (and target
852                          (not (eq target 'delete)))
853                 (if (or (gnus-request-group target t)
854                         (gnus-request-create-group target))
855                     (nnmail-expiry-target-group target group)
856                   (setq target nil)))
857               (when target
858                 (push article deleted-articles))))))))
859     ;; Change back to the current group again.
860     (nnimap-possibly-change-group group server)
861     (setq deleted-articles (nreverse deleted-articles))
862     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
863     deleted-articles))
864
865 (defun nnimap-find-expired-articles (group)
866   (let ((cutoff (nnmail-expired-article-p group nil nil)))
867     (with-current-buffer (nnimap-buffer)
868       (let ((result
869              (nnimap-command
870               "UID SEARCH SENTBEFORE %s"
871               (format-time-string
872                (format "%%d-%s-%%Y"
873                        (upcase
874                         (car (rassoc (nth 4 (decode-time cutoff))
875                                      parse-time-months))))
876                cutoff))))
877         (and (car result)
878              (delete 0 (mapcar #'string-to-number
879                                (cdr (assoc "SEARCH" (cdr result))))))))))
880
881
882 (defun nnimap-find-article-by-message-id (group message-id)
883   (with-current-buffer (nnimap-buffer)
884     (erase-buffer)
885     (unless (equal group (nnimap-group nnimap-object))
886       (setf (nnimap-group nnimap-object) nil)
887       (setf (nnimap-examined nnimap-object) group)
888       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
889     (let ((sequence
890            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
891           article result)
892       (setq result (nnimap-wait-for-response sequence))
893       (when (and result
894                  (car (setq result (nnimap-parse-response))))
895         ;; Select the last instance of the message in the group.
896         (and (setq article
897                    (car (last (assoc "SEARCH" (cdr result)))))
898              (string-to-number article))))))
899
900 (defun nnimap-delete-article (articles)
901   (with-current-buffer (nnimap-buffer)
902     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
903                     (nnimap-article-ranges articles))
904     (cond
905      ((nnimap-capability "UIDPLUS")
906       (nnimap-command "UID EXPUNGE %s"
907                       (nnimap-article-ranges articles))
908       t)
909      (nnimap-expunge
910       (nnimap-command "EXPUNGE")
911       t)
912      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
913                                 "server doesn't support UIDPLUS, so we won't "
914                                 "delete this article now"))))))
915
916 (deffoo nnimap-request-scan (&optional group server)
917   (when (and (nnimap-possibly-change-group nil server)
918              nnimap-inbox
919              nnimap-split-methods)
920     (nnheader-message 7 "nnimap %s splitting mail..." server)
921     (nnimap-split-incoming-mail)))
922
923 (defun nnimap-marks-to-flags (marks)
924   (let (flags flag)
925     (dolist (mark marks)
926       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
927         (push flag flags)))
928     flags))
929
930 (deffoo nnimap-request-update-group-status (group status &optional server)
931   (when (nnimap-possibly-change-group nil server)
932     (let ((command (assoc
933                     status
934                     '((subscribe "SUBSCRIBE")
935                       (unsubscribe "UNSUBSCRIBE")))))
936       (when command
937         (with-current-buffer (nnimap-buffer)
938           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
939
940 (deffoo nnimap-request-set-mark (group actions &optional server)
941   (when (nnimap-possibly-change-group group server)
942     (let (sequence)
943       (with-current-buffer (nnimap-buffer)
944         (erase-buffer)
945         ;; Just send all the STORE commands without waiting for
946         ;; response.  If they're successful, they're successful.
947         (dolist (action actions)
948           (destructuring-bind (range action marks) action
949             (let ((flags (nnimap-marks-to-flags marks)))
950               (when flags
951                 (setq sequence (nnimap-send-command
952                                 "UID STORE %s %sFLAGS.SILENT (%s)"
953                                 (nnimap-article-ranges range)
954                                 (cond
955                                  ((eq action 'del) "-")
956                                  ((eq action 'add) "+")
957                                  ((eq action 'set) ""))
958                                 (mapconcat #'identity flags " ")))))))
959         ;; Wait for the last command to complete to avoid later
960         ;; syncronisation problems with the stream.
961         (when sequence
962           (nnimap-wait-for-response sequence))))))
963
964 (deffoo nnimap-request-accept-article (group &optional server last)
965   (when (nnimap-possibly-change-group nil server)
966     (nnmail-check-syntax)
967     (let ((message-id (message-field-value "message-id"))
968           sequence message)
969       (nnimap-add-cr)
970       (setq message (buffer-substring-no-properties (point-min) (point-max)))
971       (with-current-buffer (nnimap-buffer)
972         (when (setq message (nnimap-process-quirk "OK Gimap " 'append message))
973           ;; If we have this group open read-only, then unselect it
974           ;; before appending to it.
975           (when (equal (nnimap-examined nnimap-object) group)
976             (nnimap-unselect-group))
977           (erase-buffer)
978           (setq sequence (nnimap-send-command
979                           "APPEND %S {%d}" (utf7-encode group t)
980                           (length message)))
981           (unless nnimap-streaming
982             (nnimap-wait-for-connection "^[+]"))
983           (process-send-string (get-buffer-process (current-buffer)) message)
984           (process-send-string (get-buffer-process (current-buffer))
985                                (if (nnimap-newlinep nnimap-object)
986                                    "\n"
987                                  "\r\n"))
988           (let ((result (nnimap-get-response sequence)))
989             (if (not (nnimap-ok-p result))
990                 (progn
991                   (nnheader-report 'nnimap "%s" result)
992                   nil)
993               (cons group
994                     (or (nnimap-find-uid-response "APPENDUID" (car result))
995                         (nnimap-find-article-by-message-id
996                          group message-id))))))))))
997
998 (defun nnimap-process-quirk (greeting-match type data)
999   (when (and (nnimap-greeting nnimap-object)
1000              (string-match "OK Gimap " (nnimap-greeting nnimap-object))
1001              (eq type 'append)
1002              (string-match "\000" data))
1003     (let ((choice (gnus-multiple-choice
1004                    "Message contains NUL characters.  Delete, continue, abort? "
1005                    '((?d "Delete NUL characters")
1006                      (?c "Try to APPEND the message as is")
1007                      (?a "Abort")))))
1008       (cond
1009        ((eq choice ?a)
1010         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1011        ((eq choice ?c)
1012         data)
1013        (t
1014         (with-temp-buffer
1015           (insert data)
1016           (goto-char (point-min))
1017           (while (search-forward "\000" nil t)
1018             (replace-match "" t t))
1019           (buffer-string)))))))
1020
1021 (defun nnimap-ok-p (value)
1022   (and (consp value)
1023        (consp (car value))
1024        (equal (caar value) "OK")))
1025
1026 (defun nnimap-find-uid-response (name list)
1027   (let ((result (car (last (nnimap-find-response-element name list)))))
1028     (and result
1029          (string-to-number result))))
1030
1031 (defun nnimap-find-response-element (name list)
1032   (let (result)
1033     (dolist (elem list)
1034       (when (and (consp elem)
1035                  (equal name (car elem)))
1036         (setq result elem)))
1037     result))
1038
1039 (deffoo nnimap-request-replace-article (article group buffer)
1040   (let (group-art)
1041     (when (and (nnimap-possibly-change-group group nil)
1042                ;; Put the article into the group.
1043                (with-current-buffer buffer
1044                  (setq group-art
1045                        (nnimap-request-accept-article group nil t))))
1046       (nnimap-delete-article (list article))
1047       ;; Return the new article number.
1048       (cdr group-art))))
1049
1050 (defun nnimap-add-cr ()
1051   (goto-char (point-min))
1052   (while (re-search-forward "\r?\n" nil t)
1053     (replace-match "\r\n" t t)))
1054
1055 (defun nnimap-get-groups ()
1056   (erase-buffer)
1057   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1058         groups)
1059     (nnimap-wait-for-response sequence)
1060     (subst-char-in-region (point-min) (point-max)
1061                           ?\\ ?% t)
1062     (goto-char (point-min))
1063     (nnimap-unfold-quoted-lines)
1064     (goto-char (point-min))
1065     (while (search-forward "* LIST " nil t)
1066       (let ((flags (read (current-buffer)))
1067             (separator (read (current-buffer)))
1068             (group (read (current-buffer))))
1069         (unless (member '%NoSelect flags)
1070           (push (if (stringp group)
1071                     group
1072                   (format "%s" group))
1073                 groups))))
1074     (nreverse groups)))
1075
1076 (deffoo nnimap-request-list (&optional server)
1077   (nnimap-possibly-change-group nil server)
1078   (with-current-buffer nntp-server-buffer
1079     (erase-buffer)
1080     (let ((groups
1081            (with-current-buffer (nnimap-buffer)
1082              (nnimap-get-groups)))
1083           sequences responses)
1084       (when groups
1085         (with-current-buffer (nnimap-buffer)
1086           (setf (nnimap-group nnimap-object) nil)
1087           (dolist (group groups)
1088             (setf (nnimap-examined nnimap-object) group)
1089             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
1090                         group)
1091                   sequences))
1092           (nnimap-wait-for-response (caar sequences))
1093           (setq responses
1094                 (nnimap-get-responses (mapcar #'car sequences))))
1095         (dolist (response responses)
1096           (let* ((sequence (car response))
1097                  (response (cadr response))
1098                  (group (cadr (assoc sequence sequences))))
1099             (when (and group
1100                        (equal (caar response) "OK"))
1101               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1102                     highest exists)
1103                 (dolist (elem response)
1104                   (when (equal (cadr elem) "EXISTS")
1105                     (setq exists (string-to-number (car elem)))))
1106                 (when uidnext
1107                   (setq highest (1- (string-to-number (car uidnext)))))
1108                 (cond
1109                  ((null highest)
1110                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1111                  ((zerop exists)
1112                   ;; Empty group.
1113                   (insert (format "%S %d %d y\n"
1114                                   (utf7-decode group t) highest (1+ highest))))
1115                  (t
1116                   ;; Return the widest possible range.
1117                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
1118                                   (or highest exists)))))))))
1119         t))))
1120
1121 (deffoo nnimap-request-newgroups (date &optional server)
1122   (nnimap-possibly-change-group nil server)
1123   (with-current-buffer nntp-server-buffer
1124     (erase-buffer)
1125     (dolist (group (with-current-buffer (nnimap-buffer)
1126                      (nnimap-get-groups)))
1127       (unless (assoc group nnimap-current-infos)
1128         ;; Insert dummy numbers here -- they don't matter.
1129         (insert (format "%S 0 1 y\n" group))))
1130     t))
1131
1132 (deffoo nnimap-retrieve-group-data-early (server infos)
1133   (when (nnimap-possibly-change-group nil server)
1134     (with-current-buffer (nnimap-buffer)
1135       (erase-buffer)
1136       (setf (nnimap-group nnimap-object) nil)
1137       (let ((qresyncp (nnimap-capability "QRESYNC"))
1138             params groups sequences active uidvalidity modseq group)
1139         ;; Go through the infos and gather the data needed to know
1140         ;; what and how to request the data.
1141         (dolist (info infos)
1142           (setq params (gnus-info-params info)
1143                 group (gnus-group-real-name (gnus-info-group info))
1144                 active (cdr (assq 'active params))
1145                 uidvalidity (cdr (assq 'uidvalidity params))
1146                 modseq (cdr (assq 'modseq params)))
1147           (setf (nnimap-examined nnimap-object) group)
1148           (if (and qresyncp
1149                    uidvalidity
1150                    modseq)
1151               (push
1152                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1153                                           (utf7-encode group t)
1154                                           (nnimap-quirk "QRESYNC")
1155                                           uidvalidity modseq)
1156                      'qresync
1157                      nil group 'qresync)
1158                sequences)
1159             (let ((start
1160                    (if (and active uidvalidity)
1161                        ;; Fetch the last 100 flags.
1162                        (max 1 (- (cdr active) 100))
1163                      1))
1164                   (command
1165                    (if uidvalidity
1166                        "EXAMINE"
1167                      ;; If we don't have a UIDVALIDITY, then this is
1168                      ;; the first time we've seen the group, so we
1169                      ;; have to do a SELECT (which is slower than an
1170                      ;; examine), but will tell us whether the group
1171                      ;; is read-only or not.
1172                      "SELECT")))
1173               (push (list (nnimap-send-command "%s %S" command
1174                                                (utf7-encode group t))
1175                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1176                           start group command)
1177                     sequences))))
1178         sequences))))
1179
1180 (defun nnimap-quirk (command)
1181   (let ((quirk (assoc command nnimap-quirks)))
1182     ;; If this server is of a type that matches a quirk, then return
1183     ;; the "quirked" command instead of the proper one.
1184     (if (or (null quirk)
1185             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1186         command
1187       (nth 2 quirk))))
1188
1189 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1190   (when (and sequences
1191              (nnimap-possibly-change-group nil server))
1192     (with-current-buffer (nnimap-buffer)
1193       ;; Wait for the final data to trickle in.
1194       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1195                                           (caar sequences)
1196                                         (cadar sequences))
1197                                       t)
1198         ;; Now we should have most of the data we need, no matter
1199         ;; whether we're QRESYNCING, fetching all the flags from
1200         ;; scratch, or just fetching the last 100 flags per group.
1201         (nnimap-update-infos (nnimap-flags-to-marks
1202                               (nnimap-parse-flags
1203                                (nreverse sequences)))
1204                              infos)
1205         ;; Finally, just return something resembling an active file in
1206         ;; the nntp buffer, so that the agent can save the info, too.
1207         (with-current-buffer nntp-server-buffer
1208           (erase-buffer)
1209           (dolist (info infos)
1210             (let* ((group (gnus-info-group info))
1211                    (active (gnus-active group)))
1212               (when active
1213                 (insert (format "%S %d %d y\n"
1214                                 (gnus-group-real-name group)
1215                                 (cdr active)
1216                                 (car active)))))))))))
1217
1218 (defun nnimap-update-infos (flags infos)
1219   (dolist (info infos)
1220     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1221            (marks (cdr (assoc group flags))))
1222       (when marks
1223         (nnimap-update-info info marks)))))
1224
1225 (defun nnimap-update-info (info marks)
1226   (destructuring-bind (existing flags high low uidnext start-article
1227                                 permanent-flags uidvalidity
1228                                 vanished highestmodseq) marks
1229     (cond
1230      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1231      ;; completely empty groups.
1232      ((and (not existing)
1233            (not uidnext))
1234       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1235         (when active
1236           (gnus-set-active (gnus-info-group info) active))))
1237      ;; We have a mismatch between the old and new UIDVALIDITY
1238      ;; identifiers, so we have to re-request the group info (the next
1239      ;; time).  This virtually never happens.
1240      ((let ((old-uidvalidity
1241              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1242         (and old-uidvalidity
1243              (not (equal old-uidvalidity uidvalidity))
1244              (> start-article 1)))
1245       (gnus-group-remove-parameter info 'uidvalidity)
1246       (gnus-group-remove-parameter info 'modseq))
1247      ;; We have the data needed to update.
1248      (t
1249       (let* ((group (gnus-info-group info))
1250              (completep (and start-article
1251                              (= start-article 1)))
1252              (active (or (gnus-active group)
1253                          (cdr (assq 'active (gnus-info-params info))))))
1254         (when uidnext
1255           (setq high (1- uidnext)))
1256         ;; First set the active ranges based on high/low.
1257         (gnus-set-active
1258          group
1259          (if (or completep
1260                  (not (gnus-active group)))
1261              (cond
1262               (active
1263                (cons (min (or low (car active))
1264                           (car active))
1265                      (max (or high (cdr active))
1266                           (cdr active))))
1267               ((and low high)
1268                (cons low high))
1269               (uidnext
1270                ;; No articles in this group.
1271                (cons uidnext (1- uidnext)))
1272               (start-article
1273                (cons start-article (1- start-article)))
1274               (t
1275                ;; No articles and no uidnext.
1276                nil))
1277            (cons (car active)
1278                  (or high (1- uidnext)))))
1279         ;; See whether this is a read-only group.
1280         (unless (eq permanent-flags 'not-scanned)
1281           (gnus-group-set-parameter
1282            info 'permanent-flags
1283            (and (or (memq '%* permanent-flags)
1284                     (memq '%Seen permanent-flags))
1285                 permanent-flags)))
1286         ;; Update marks and read articles if this isn't a
1287         ;; read-only IMAP group.
1288         (when (setq permanent-flags
1289                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1290           (if (and highestmodseq
1291                    (not start-article))
1292               ;; We've gotten the data by QRESYNCing.
1293               (nnimap-update-qresync-info
1294                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1295             ;; Do normal non-QRESYNC flag updates.
1296             ;; Update the list of read articles.
1297             (let* ((unread
1298                     (gnus-compress-sequence
1299                      (gnus-set-difference
1300                       (gnus-set-difference
1301                        existing
1302                        (cdr (assoc '%Seen flags)))
1303                       (cdr (assoc '%Flagged flags)))))
1304                    (read (gnus-range-difference
1305                           (cons start-article high) unread)))
1306               (when (> start-article 1)
1307                 (setq read
1308                       (gnus-range-nconcat
1309                        (if (> start-article 1)
1310                            (gnus-sorted-range-intersection
1311                             (cons 1 (1- start-article))
1312                             (gnus-info-read info))
1313                          (gnus-info-read info))
1314                        read)))
1315               (when (or (not (listp permanent-flags))
1316                         (memq '%Seen permanent-flags))
1317                 (gnus-info-set-read info read))
1318               ;; Update the marks.
1319               (setq marks (gnus-info-marks info))
1320               (dolist (type (cdr nnimap-mark-alist))
1321                 (when (or (not (listp permanent-flags))
1322                           (memq (car (assoc (caddr type) flags))
1323                                 permanent-flags)
1324                           (memq '%* permanent-flags))
1325                   (let ((old-marks (assoc (car type) marks))
1326                         (new-marks
1327                          (gnus-compress-sequence
1328                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1329                                    (assoc (intern (cadr type) obarray) flags)
1330                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1331                     (setq marks (delq old-marks marks))
1332                     (pop old-marks)
1333                     (when (and old-marks
1334                                (> start-article 1))
1335                       (setq old-marks (gnus-range-difference
1336                                        old-marks
1337                                        (cons start-article high)))
1338                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1339                     (when new-marks
1340                       (push (cons (car type) new-marks) marks)))))
1341               (gnus-info-set-marks info marks t))))
1342         ;; Tell Gnus whether there are any \Recent messages in any of
1343         ;; the groups.
1344         (let ((recent (cdr (assoc '%Recent flags))))
1345           (when (and active recent)
1346             (while recent
1347               (when (> (car recent) (cdr active))
1348                 (push (list (cons (gnus-group-real-name group) 0))
1349                       nnmail-split-history)
1350                 (setq recent nil))
1351               (pop recent))))
1352         ;; Note the active level for the next run-through.
1353         (gnus-group-set-parameter info 'active (gnus-active group))
1354         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1355         (gnus-group-set-parameter info 'modseq highestmodseq)
1356         (nnimap-store-info info (gnus-active group)))))))
1357
1358 (defun nnimap-update-qresync-info (info existing vanished flags)
1359   ;; Add all the vanished articles to the list of read articles.
1360   (gnus-info-set-read
1361    info
1362    (gnus-add-to-range
1363     (gnus-add-to-range
1364      (gnus-range-add (gnus-info-read info)
1365                      vanished)
1366      (cdr (assq '%Flagged flags)))
1367     (cdr (assq '%Seen flags))))
1368   (let ((marks (gnus-info-marks info)))
1369     (dolist (type (cdr nnimap-mark-alist))
1370       (let ((ticks (assoc (car type) marks))
1371             (new-marks
1372              (cdr (or (assoc (caddr type) flags) ; %Flagged
1373                       (assoc (intern (cadr type) obarray) flags)
1374                       (assoc (cadr type) flags))))) ; "\Flagged"
1375         (setq marks (delq ticks marks))
1376         (pop ticks)
1377         ;; Add the new marks we got.
1378         (setq ticks (gnus-add-to-range ticks new-marks))
1379         ;; Remove the marks from messages that don't have them.
1380         (setq ticks (gnus-remove-from-range
1381                      ticks
1382                      (gnus-compress-sequence
1383                       (gnus-sorted-complement existing new-marks))))
1384         (when ticks
1385           (push (cons (car type) ticks) marks)))
1386       (gnus-info-set-marks info marks t))))
1387
1388 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1389   (if (zerop (length irange))
1390       nil
1391     (let ((result nil))
1392       (dolist (elem (split-string irange ","))
1393         (push
1394          (if (string-match ":" elem)
1395              (let ((numbers (split-string elem ":")))
1396                (cons (string-to-number (car numbers))
1397                      (string-to-number (cadr numbers))))
1398            (string-to-number elem))
1399          result))
1400       (nreverse result))))
1401
1402 (defun nnimap-store-info (info active)
1403   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1404          (entry (assoc group nnimap-current-infos)))
1405     (if entry
1406         (setcdr entry (list info active))
1407       (push (list group info active) nnimap-current-infos))))
1408
1409 (defun nnimap-flags-to-marks (groups)
1410   (let (data group totalp uidnext articles start-article mark permanent-flags
1411              uidvalidity vanished highestmodseq)
1412     (dolist (elem groups)
1413       (setq group (car elem)
1414             uidnext (nth 1 elem)
1415             start-article (nth 2 elem)
1416             permanent-flags (nth 3 elem)
1417             uidvalidity (nth 4 elem)
1418             vanished (nth 5 elem)
1419             highestmodseq (nth 6 elem)
1420             articles (nthcdr 7 elem))
1421       (let ((high (caar articles))
1422             marks low existing)
1423         (dolist (article articles)
1424           (setq low (car article))
1425           (push (car article) existing)
1426           (dolist (flag (cdr article))
1427             (setq mark (assoc flag marks))
1428             (if (not mark)
1429                 (push (list flag (car article)) marks)
1430               (setcdr mark (cons (car article) (cdr mark))))))
1431         (push (list group existing marks high low uidnext start-article
1432                     permanent-flags uidvalidity vanished highestmodseq)
1433               data)))
1434     data))
1435
1436 (defun nnimap-parse-flags (sequences)
1437   (goto-char (point-min))
1438   ;; Change \Delete etc to %Delete, so that the reader can read it.
1439   (subst-char-in-region (point-min) (point-max)
1440                         ?\\ ?% t)
1441   (let (start end articles groups uidnext elems permanent-flags
1442               uidvalidity vanished highestmodseq)
1443     (dolist (elem sequences)
1444       (destructuring-bind (group-sequence flag-sequence totalp group command)
1445           elem
1446         (setq start (point))
1447         (when (and
1448                ;; The EXAMINE was successful.
1449                (search-forward (format "\n%d OK " group-sequence) nil t)
1450                (progn
1451                  (forward-line 1)
1452                  (setq end (point))
1453                  (goto-char start)
1454                  (setq permanent-flags
1455                        (if (equal command "SELECT")
1456                            (and (search-forward "PERMANENTFLAGS "
1457                                                 (or end (point-min)) t)
1458                                 (read (current-buffer)))
1459                          'not-scanned))
1460                  (goto-char start)
1461                  (setq uidnext
1462                        (and (search-forward "UIDNEXT "
1463                                             (or end (point-min)) t)
1464                             (read (current-buffer))))
1465                  (goto-char start)
1466                  (setq uidvalidity
1467                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1468                                                (or end (point-min)) t)
1469                             ;; Store UIDVALIDITY as a string, as it's
1470                             ;; too big for 32-bit Emacsen, usually.
1471                             (match-string 1)))
1472                  (goto-char start)
1473                  (setq vanished
1474                        (and (eq flag-sequence 'qresync)
1475                             (re-search-forward "^\\* VANISHED .* \\([0-9:,]+\\)"
1476                                                (or end (point-min)) t)
1477                             (match-string 1)))
1478                  (goto-char start)
1479                  (setq highestmodseq
1480                        (and (search-forward "HIGHESTMODSEQ "
1481                                             (or end (point-min)) t)
1482                             (read (current-buffer))))
1483                  (goto-char end)
1484                  (forward-line -1))
1485                ;; The UID FETCH FLAGS was successful.
1486                (or (eq flag-sequence 'qresync)
1487                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1488           (if (eq flag-sequence 'qresync)
1489               (progn
1490                 (goto-char start)
1491                 (setq start end))
1492             (setq start (point))
1493             (goto-char end))
1494           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1495             (setq elems (read (current-buffer)))
1496             (push (cons (cadr (memq 'UID elems))
1497                         (cadr (memq 'FLAGS elems)))
1498                   articles))
1499           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1500                              vanished highestmodseq)
1501                        articles)
1502                 groups)
1503           (goto-char end)
1504           (setq articles nil))))
1505     groups))
1506
1507 (defun nnimap-find-process-buffer (buffer)
1508   (cadr (assoc buffer nnimap-connection-alist)))
1509
1510 (deffoo nnimap-request-post (&optional server)
1511   (setq nnimap-status-string "Read-only server")
1512   nil)
1513
1514 (declare-function gnus-fetch-headers "gnus-sum"
1515                   (articles &optional limit force-new dependencies))
1516
1517 (deffoo nnimap-request-thread (header)
1518   (let* ((id (mail-header-id header))
1519          (refs (split-string
1520                 (or (mail-header-references header)
1521                     "")))
1522          (cmd (let ((value
1523                      (format
1524                       "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1525                       id id)))
1526                 (dolist (refid refs value)
1527                   (setq value (format
1528                                "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1529                                refid refid value)))))
1530          (result (with-current-buffer (nnimap-buffer)
1531                    (nnimap-command  "UID SEARCH %s" cmd))))
1532     (gnus-fetch-headers
1533      (and (car result) (delete 0 (mapcar #'string-to-number
1534                                          (cdr (assoc "SEARCH" (cdr result))))))
1535      nil t)))
1536
1537 (defun nnimap-possibly-change-group (group server)
1538   (let ((open-result t))
1539     (when (and server
1540                (not (nnimap-server-opened server)))
1541       (setq open-result (nnimap-open-server server)))
1542     (cond
1543      ((not open-result)
1544       nil)
1545      ((not group)
1546       t)
1547      (t
1548       (with-current-buffer (nnimap-buffer)
1549         (if (equal group (nnimap-group nnimap-object))
1550             t
1551           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1552             (when (car result)
1553               (setf (nnimap-group nnimap-object) group
1554                     (nnimap-select-result nnimap-object) result)
1555               result))))))))
1556
1557 (defun nnimap-find-connection (buffer)
1558   "Find the connection delivering to BUFFER."
1559   (let ((entry (assoc buffer nnimap-connection-alist)))
1560     (when entry
1561       (if (and (buffer-name (cadr entry))
1562                (get-buffer-process (cadr entry))
1563                (memq (process-status (get-buffer-process (cadr entry)))
1564                      '(open run)))
1565           (get-buffer-process (cadr entry))
1566         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1567         nil))))
1568
1569 (defvar nnimap-sequence 0)
1570
1571 (defun nnimap-send-command (&rest args)
1572   (process-send-string
1573    (get-buffer-process (current-buffer))
1574    (nnimap-log-command
1575     (format "%d %s%s\n"
1576             (incf nnimap-sequence)
1577             (apply #'format args)
1578             (if (nnimap-newlinep nnimap-object)
1579                 ""
1580               "\r"))))
1581   ;; Some servers apparently can't have many outstanding
1582   ;; commands, so throttle them.
1583   (unless nnimap-streaming
1584     (nnimap-wait-for-response nnimap-sequence))
1585   nnimap-sequence)
1586
1587 (defun nnimap-log-command (command)
1588   (with-current-buffer (get-buffer-create "*imap log*")
1589     (goto-char (point-max))
1590     (insert (format-time-string "%H:%M:%S") " " command))
1591   command)
1592
1593 (defun nnimap-command (&rest args)
1594   (erase-buffer)
1595   (setf (nnimap-last-command-time nnimap-object) (current-time))
1596   (let* ((sequence (apply #'nnimap-send-command args))
1597          (response (nnimap-get-response sequence)))
1598     (if (equal (caar response) "OK")
1599         (cons t response)
1600       (nnheader-report 'nnimap "%s"
1601                        (mapconcat (lambda (a)
1602                                     (format "%s" a))
1603                                   (car response) " "))
1604       nil)))
1605
1606 (defun nnimap-get-response (sequence)
1607   (nnimap-wait-for-response sequence)
1608   (nnimap-parse-response))
1609
1610 (defun nnimap-wait-for-connection (&optional regexp)
1611   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1612
1613 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1614   (let ((process (get-buffer-process (current-buffer))))
1615     (goto-char (point-min))
1616     (while (and (memq (process-status process)
1617                       '(open run))
1618                 (not (re-search-forward regexp nil t)))
1619       (nnheader-accept-process-output process)
1620       (goto-char (point-min)))
1621     (forward-line -1)
1622     (and (looking-at (or response-regexp regexp))
1623          (match-string 1))))
1624
1625 (defun nnimap-wait-for-response (sequence &optional messagep)
1626   (let ((process (get-buffer-process (current-buffer)))
1627         openp)
1628     (condition-case nil
1629         (progn
1630           (goto-char (point-max))
1631           (while (and (setq openp (memq (process-status process)
1632                                         '(open run)))
1633                       (progn
1634                         ;; Skip past any "*" lines that the server has
1635                         ;; output.
1636                         (while (and (not (bobp))
1637                                     (progn
1638                                       (forward-line -1)
1639                                       (looking-at "\\*"))))
1640                         (not (looking-at (format "%d " sequence)))))
1641             (when messagep
1642               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1643             (nnheader-accept-process-output process)
1644             (goto-char (point-max)))
1645           openp)
1646       (quit
1647        ;; The user hit C-g while we were waiting: kill the process, in case
1648        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1649        ;; NAT routers).
1650        (delete-process process)
1651        nil))))
1652
1653 (defun nnimap-parse-response ()
1654   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1655         result)
1656     (dolist (line lines)
1657       (push (cdr (nnimap-parse-line line)) result))
1658     ;; Return the OK/error code first, and then all the "continuation
1659     ;; lines" afterwards.
1660     (cons (pop result)
1661           (nreverse result))))
1662
1663 ;; Parse an IMAP response line lightly.  They look like
1664 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1665 ;; the lines into a list of strings and lists of string.
1666 (defun nnimap-parse-line (line)
1667   (let (char result)
1668     (with-temp-buffer
1669       (mm-disable-multibyte)
1670       (insert line)
1671       (goto-char (point-min))
1672       (while (not (eobp))
1673         (if (eql (setq char (following-char)) ? )
1674             (forward-char 1)
1675           (push
1676            (cond
1677             ((eql char ?\[)
1678              (split-string
1679               (buffer-substring
1680                (1+ (point))
1681                (if (search-forward "]" (line-end-position) 'move)
1682                    (1- (point))
1683                  (point)))))
1684             ((eql char ?\()
1685              (split-string
1686               (buffer-substring
1687                (1+ (point))
1688                (if (search-forward ")" (line-end-position) 'move)
1689                    (1- (point))
1690                  (point)))))
1691             ((eql char ?\")
1692              (forward-char 1)
1693              (buffer-substring
1694               (point)
1695               (1- (or (search-forward "\"" (line-end-position) 'move)
1696                       (point)))))
1697             (t
1698              (buffer-substring (point) (if (search-forward " " nil t)
1699                                            (1- (point))
1700                                          (goto-char (point-max))))))
1701            result)))
1702       (nreverse result))))
1703
1704 (defun nnimap-last-response-string ()
1705   (save-excursion
1706     (forward-line 1)
1707     (let ((end (point)))
1708       (forward-line -1)
1709       (when (not (bobp))
1710         (forward-line -1)
1711         (while (and (not (bobp))
1712                     (eql (following-char) ?*))
1713           (forward-line -1))
1714         (unless (eql (following-char) ?*)
1715           (forward-line 1)))
1716       (buffer-substring (point) end))))
1717
1718 (defun nnimap-get-responses (sequences)
1719   (let (responses)
1720     (dolist (sequence sequences)
1721       (goto-char (point-min))
1722       (when (re-search-forward (format "^%d " sequence) nil t)
1723         (push (list sequence (nnimap-parse-response))
1724               responses)))
1725     responses))
1726
1727 (defvar nnimap-incoming-split-list nil)
1728
1729 (defun nnimap-fetch-inbox (articles)
1730   (erase-buffer)
1731   (nnimap-wait-for-response
1732    (nnimap-send-command
1733     "UID FETCH %s %s"
1734     (nnimap-article-ranges articles)
1735     (format "(UID %s%s)"
1736             (format
1737              (if (nnimap-ver4-p)
1738                  "BODY.PEEK[HEADER] BODY.PEEK"
1739                "RFC822.PEEK"))
1740             (if nnimap-split-download-body-default
1741                 "[]"
1742               "[1]")))
1743    t))
1744
1745 (defun nnimap-split-incoming-mail ()
1746   (with-current-buffer (nnimap-buffer)
1747     (let ((nnimap-incoming-split-list nil)
1748           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1749                                     nnmail-split-methods
1750                                   nnimap-split-methods))
1751           (nnmail-split-fancy (or nnimap-split-fancy
1752                                   nnmail-split-fancy))
1753           (nnmail-inhibit-default-split-group t)
1754           (groups (nnimap-get-groups))
1755           new-articles)
1756       (erase-buffer)
1757       (nnimap-command "SELECT %S" nnimap-inbox)
1758       (setf (nnimap-group nnimap-object) nnimap-inbox)
1759       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1760       (when new-articles
1761         (nnimap-fetch-inbox new-articles)
1762         (nnimap-transform-split-mail)
1763         (nnheader-ms-strip-cr)
1764         (nnmail-cache-open)
1765         (nnmail-split-incoming (current-buffer)
1766                                #'nnimap-save-mail-spec
1767                                nil nil
1768                                #'nnimap-dummy-active-number
1769                                #'nnimap-save-mail-spec)
1770         (when nnimap-incoming-split-list
1771           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1772                 sequences junk-articles)
1773             ;; Create any groups that doesn't already exist on the
1774             ;; server first.
1775             (dolist (spec specs)
1776               (when (and (not (member (car spec) groups))
1777                          (not (eq (car spec) 'junk)))
1778                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1779             ;; Then copy over all the messages.
1780             (erase-buffer)
1781             (dolist (spec specs)
1782               (let ((group (car spec))
1783                     (ranges (cdr spec)))
1784                 (if (eq group 'junk)
1785                     (setq junk-articles ranges)
1786                   (push (list (nnimap-send-command
1787                                "UID COPY %s %S"
1788                                (nnimap-article-ranges ranges)
1789                                (utf7-encode group t))
1790                               ranges)
1791                         sequences))))
1792             ;; Wait for the last COPY response...
1793             (when sequences
1794               (nnimap-wait-for-response (caar sequences))
1795               ;; And then mark the successful copy actions as deleted,
1796               ;; and possibly expunge them.
1797               (nnimap-mark-and-expunge-incoming
1798                (nnimap-parse-copied-articles sequences)))
1799             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1800
1801 (defun nnimap-mark-and-expunge-incoming (range)
1802   (when range
1803     (setq range (nnimap-article-ranges range))
1804     (erase-buffer)
1805     (let ((sequence
1806            (nnimap-send-command
1807             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1808       (cond
1809        ;; If the server supports it, we now delete the message we have
1810        ;; just copied over.
1811        ((nnimap-capability "UIDPLUS")
1812         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1813        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1814        ;; user has configured it.
1815        (nnimap-expunge
1816         (setq sequence (nnimap-send-command "EXPUNGE"))))
1817       (nnimap-wait-for-response sequence))))
1818
1819 (defun nnimap-parse-copied-articles (sequences)
1820   (let (sequence copied range)
1821     (goto-char (point-min))
1822     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1823       (setq sequence (string-to-number (match-string 1)))
1824       (when (setq range (cadr (assq sequence sequences)))
1825         (push (gnus-uncompress-range range) copied)))
1826     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1827
1828 (defun nnimap-new-articles (flags)
1829   (let (new)
1830     (dolist (elem flags)
1831       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1832                                       (cdr elem))
1833         (push (car elem) new)))
1834     (gnus-compress-sequence (nreverse new))))
1835
1836 (defun nnimap-make-split-specs (list)
1837   (let ((specs nil)
1838         entry)
1839     (dolist (elem list)
1840       (destructuring-bind (article spec) elem
1841         (dolist (group (delete nil (mapcar #'car spec)))
1842           (unless (setq entry (assoc group specs))
1843             (push (setq entry (list group)) specs))
1844           (setcdr entry (cons article (cdr entry))))))
1845     (dolist (entry specs)
1846       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1847     specs))
1848
1849 (defun nnimap-transform-split-mail ()
1850   (goto-char (point-min))
1851   (let (article bytes)
1852     (block nil
1853       (while (not (eobp))
1854         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1855           (delete-region (point) (progn (forward-line 1) (point)))
1856           (when (eobp)
1857             (return)))
1858         (setq article (match-string 1)
1859               bytes (nnimap-get-length))
1860         (delete-region (line-beginning-position) (line-end-position))
1861         ;; Insert MMDF separator, and a way to remember what this
1862         ;; article UID is.
1863         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1864         (forward-char (1+ bytes))
1865         (setq bytes (nnimap-get-length))
1866         (delete-region (line-beginning-position) (line-end-position))
1867         ;; There's a body; skip past that.
1868         (when bytes
1869           (forward-char (1+ bytes))
1870           (delete-region (line-beginning-position) (line-end-position)))))))
1871
1872 (defun nnimap-dummy-active-number (group &optional server)
1873   1)
1874
1875 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1876   (let (article)
1877     (goto-char (point-min))
1878     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1879         (error "Invalid nnimap mail")
1880       (setq article (string-to-number (match-string 1))))
1881     (push (list article
1882                 (if (eq group-art 'junk)
1883                     (list (cons 'junk 1))
1884                   group-art))
1885           nnimap-incoming-split-list)))
1886
1887 (provide 'nnimap)
1888
1889 ;;; nnimap.el ends here