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