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