Merge changes made in Emacs trunk.
[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', `default', `try-starttls', `starttls' or
66 `shell'.  The default is to try `ssl' first, and then
67 `try-starttls'.")
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 try-starttls)
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              ((memq nnimap-stream '(try-starttls default starttls))
343               (nnheader-message 7 "Opening connection to %s..."
344                                 nnimap-address)
345               '("imap" "143"))
346              ((eq nnimap-stream 'shell)
347               (nnheader-message 7 "Opening connection to %s via shell..."
348                                 nnimap-address)
349               '("imap"))
350              ((memq nnimap-stream '(ssl tls))
351               (nnheader-message 7 "Opening connection to %s via tls..."
352                                 nnimap-address)
353               '("imaps" "imap" "993" "143"))
354              (t
355               (error "Unknown stream type: %s" nnimap-stream))))
356            login-result credentials)
357       (when nnimap-server-port
358         (push nnimap-server-port ports))
359       (let* ((stream-list
360               (open-protocol-stream
361                "*nnimap*" (current-buffer) nnimap-address (car ports)
362                :type nnimap-stream
363                :return-list t
364                :shell-command nnimap-shell-program
365                :capability-command "1 CAPABILITY\r\n"
366                :success " OK "
367                :starttls-function
368                (lambda (capabilities)
369                  (when (gnus-string-match-p "STARTTLS" capabilities)
370                    "1 STARTTLS\r\n"))))
371              (stream (car stream-list))
372              (props (cdr stream-list))
373              (greeting (plist-get props :greeting))
374              (capabilities (plist-get props :capabilities))
375              (stream-type (plist-get props :type)))
376         (when (and stream (not (memq (process-status stream) '(open run))))
377           (setq stream nil))
378         (setf (nnimap-process nnimap-object) stream)
379         (setf (nnimap-stream-type nnimap-object) stream-type)
380         (if (not stream)
381             (progn
382               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
383                                nnimap-address port nnimap-stream)
384               'no-connect)
385           (gnus-set-process-query-on-exit-flag stream nil)
386           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
387               (nnheader-report 'nnimap "%s" greeting)
388             ;; Store the greeting (for debugging purposes).
389             (setf (nnimap-greeting nnimap-object) greeting)
390             (setf (nnimap-capabilities nnimap-object)
391                   (mapcar #'upcase
392                           (split-string capabilities)))
393             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
394               (if (not (setq credentials
395                              (if (eq nnimap-authenticator 'anonymous)
396                                  (list "anonymous"
397                                        (message-make-address))
398                                ;; Look for the credentials based on
399                                ;; the virtual server name and the address
400                                (nnimap-credentials
401                                 (gnus-delete-duplicates
402                                  (list
403                                   nnimap-address
404                                   (nnoo-current-server 'nnimap)))
405                                 ports))))
406                   (setq nnimap-object nil)
407                 (let ((nnimap-inhibit-logging t))
408                   (setq login-result
409                         (nnimap-login (car credentials) (cadr credentials))))
410                 (if (car login-result)
411                     ;; save the credentials if a save function exists
412                     ;; (such a function will only be passed if a new
413                     ;; token was created)
414                     (when (functionp (nth 2 credentials))
415                       (funcall (nth 2 credentials)))
416                   ;; If the login failed, then forget the credentials
417                   ;; that are now possibly cached.
418                   (dolist (host (list (nnoo-current-server 'nnimap)
419                                       nnimap-address))
420                     (dolist (port ports)
421                       (auth-source-forget+ :host host :port port)))
422                   (delete-process (nnimap-process nnimap-object))
423                   (setq nnimap-object nil))))
424             (when nnimap-object
425               (when (nnimap-capability "QRESYNC")
426                 (nnimap-command "ENABLE QRESYNC"))
427               (nnimap-process nnimap-object))))))))
428
429 (autoload 'rfc2104-hash "rfc2104")
430
431 (defun nnimap-login (user password)
432   (cond
433    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
434    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
435    ;; and we're using an encrypted connection.
436    ((and (not (nnimap-capability "LOGINDISABLED"))
437          (eq (nnimap-stream-type nnimap-object) 'tls))
438     (nnimap-command "LOGIN %S %S" user password))
439    ((nnimap-capability "AUTH=CRAM-MD5")
440     (erase-buffer)
441     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
442           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
443       (process-send-string
444        (get-buffer-process (current-buffer))
445        (concat
446         (base64-encode-string
447          (concat user " "
448                  (rfc2104-hash 'md5 64 16 password
449                                (base64-decode-string challenge))))
450         "\r\n"))
451       (nnimap-wait-for-response sequence)))
452    ((not (nnimap-capability "LOGINDISABLED"))
453     (nnimap-command "LOGIN %S %S" user password))
454    ((nnimap-capability "AUTH=PLAIN")
455     (nnimap-command
456      "AUTHENTICATE PLAIN %s"
457      (base64-encode-string
458       (format "\000%s\000%s"
459               (nnimap-quote-specials user)
460               (nnimap-quote-specials password)))))))
461
462 (defun nnimap-quote-specials (string)
463   (with-temp-buffer
464     (insert string)
465     (goto-char (point-min))
466     (while (re-search-forward "[\\\"]" nil t)
467       (forward-char -1)
468       (insert "\\")
469       (forward-char 1))
470     (buffer-string)))
471
472 (defun nnimap-find-parameter (parameter elems)
473   (let (result)
474     (dolist (elem elems)
475       (cond
476        ((equal (car elem) parameter)
477         (setq result (cdr elem)))
478        ((and (equal (car elem) "OK")
479              (consp (cadr elem))
480              (equal (caadr elem) parameter))
481         (setq result (cdr (cadr elem))))))
482     result))
483
484 (deffoo nnimap-close-server (&optional server)
485   (when (nnoo-change-server 'nnimap server nil)
486     (ignore-errors
487       (delete-process (get-buffer-process (nnimap-buffer))))
488     (nnoo-close-server 'nnimap server)
489     t))
490
491 (deffoo nnimap-request-close ()
492   t)
493
494 (deffoo nnimap-server-opened (&optional server)
495   (and (nnoo-current-server-p 'nnimap server)
496        nntp-server-buffer
497        (gnus-buffer-live-p nntp-server-buffer)
498        (nnimap-find-connection nntp-server-buffer)))
499
500 (deffoo nnimap-status-message (&optional server)
501   nnimap-status-string)
502
503 (deffoo nnimap-request-article (article &optional group server to-buffer)
504   (with-current-buffer nntp-server-buffer
505     (let ((result (nnimap-possibly-change-group group server))
506           parts structure)
507       (when (stringp article)
508         (setq article (nnimap-find-article-by-message-id group article)))
509       (when (and result
510                  article)
511         (erase-buffer)
512         (with-current-buffer (nnimap-buffer)
513           (erase-buffer)
514           (when nnimap-fetch-partial-articles
515             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
516             (goto-char (point-min))
517             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
518               (setq structure (ignore-errors
519                                 (let ((start (point)))
520                                   (forward-sexp 1)
521                                   (downcase-region start (point))
522                                   (goto-char start)
523                                   (read (current-buffer))))
524                     parts (nnimap-find-wanted-parts structure))))
525           (when (if parts
526                     (nnimap-get-partial-article article parts structure)
527                   (nnimap-get-whole-article article))
528             (let ((buffer (current-buffer)))
529               (with-current-buffer (or to-buffer nntp-server-buffer)
530                 (erase-buffer)
531                 (insert-buffer-substring buffer)
532                 (nnheader-ms-strip-cr)
533                 (cons group article)))))))))
534
535 (deffoo nnimap-request-head (article &optional group server to-buffer)
536   (when (nnimap-possibly-change-group group server)
537     (with-current-buffer (nnimap-buffer)
538       (when (stringp article)
539         (setq article (nnimap-find-article-by-message-id group article)))
540       (if (null article)
541           nil
542         (nnimap-get-whole-article
543          article (format "UID FETCH %%d %s"
544                          (nnimap-header-parameters)))
545         (let ((buffer (current-buffer)))
546           (with-current-buffer (or to-buffer nntp-server-buffer)
547             (erase-buffer)
548             (insert-buffer-substring buffer)
549             (nnheader-ms-strip-cr)
550             (cons group article)))))))
551
552 (defun nnimap-get-whole-article (article &optional command)
553   (let ((result
554          (nnimap-command
555           (or command
556               (if (nnimap-ver4-p)
557                   "UID FETCH %d BODY.PEEK[]"
558                 "UID FETCH %d RFC822.PEEK"))
559           article)))
560     ;; Check that we really got an article.
561     (goto-char (point-min))
562     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
563       (setq result nil))
564     (when result
565       ;; Remove any data that may have arrived before the FETCH data.
566       (beginning-of-line)
567       (unless (bobp)
568         (delete-region (point-min) (point)))
569       (let ((bytes (nnimap-get-length)))
570         (delete-region (line-beginning-position)
571                        (progn (forward-line 1) (point)))
572         (goto-char (+ (point) bytes))
573         (delete-region (point) (point-max)))
574       t)))
575
576 (defun nnimap-capability (capability)
577   (member capability (nnimap-capabilities nnimap-object)))
578
579 (defun nnimap-ver4-p ()
580   (nnimap-capability "IMAP4REV1"))
581
582 (defun nnimap-get-partial-article (article parts structure)
583   (let ((result
584          (nnimap-command
585           "UID FETCH %d (%s %s)"
586           article
587           (if (nnimap-ver4-p)
588               "BODY.PEEK[HEADER]"
589             "RFC822.HEADER")
590           (if (nnimap-ver4-p)
591               (mapconcat (lambda (part)
592                            (format "BODY.PEEK[%s]" part))
593                          parts " ")
594             (mapconcat (lambda (part)
595                          (format "RFC822.PEEK[%s]" part))
596                        parts " ")))))
597     (when result
598       (nnimap-convert-partial-article structure))))
599
600 (defun nnimap-convert-partial-article (structure)
601   ;; First just skip past the headers.
602   (goto-char (point-min))
603   (let ((bytes (nnimap-get-length))
604         id parts)
605     ;; Delete "FETCH" line.
606     (delete-region (line-beginning-position)
607                    (progn (forward-line 1) (point)))
608     (goto-char (+ (point) bytes))
609     ;; Collect all the body parts.
610     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
611       (setq id (match-string 1)
612             bytes (or (nnimap-get-length) 0))
613       (beginning-of-line)
614       (delete-region (point) (progn (forward-line 1) (point)))
615       (push (list id (buffer-substring (point) (+ (point) bytes)))
616             parts)
617       (delete-region (point) (+ (point) bytes)))
618     ;; Delete trailing junk.
619     (delete-region (point) (point-max))
620     ;; Now insert all the parts again where they fit in the structure.
621     (nnimap-insert-partial-structure structure parts)
622     t))
623
624 (defun nnimap-insert-partial-structure (structure parts &optional subp)
625   (let (type boundary)
626     (let ((bstruc structure))
627       (while (consp (car bstruc))
628         (pop bstruc))
629       (setq type (car bstruc))
630       (setq bstruc (car (cdr bstruc)))
631       (let ((has-boundary (member "boundary" bstruc)))
632         (when has-boundary
633           (setq boundary (cadr has-boundary)))))
634     (when subp
635       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
636                       (downcase type) boundary)))
637     (while (not (stringp (car structure)))
638       (insert "\n--" boundary "\n")
639       (if (consp (caar structure))
640           (nnimap-insert-partial-structure (pop structure) parts t)
641         (let ((bit (pop structure)))
642           (insert (format  "Content-type: %s/%s"
643                            (downcase (nth 0 bit))
644                            (downcase (nth 1 bit))))
645           (if (member "CHARSET" (nth 2 bit))
646               (insert (format
647                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
648             (insert "\n"))
649           (insert (format "Content-transfer-encoding: %s\n"
650                           (nth 5 bit)))
651           (insert "\n")
652           (when (assoc (nth 9 bit) parts)
653             (insert (cadr (assoc (nth 9 bit) parts)))))))
654     (insert "\n--" boundary "--\n")))
655
656 (defun nnimap-find-wanted-parts (structure)
657   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
658
659 (defun nnimap-find-wanted-parts-1 (structure prefix)
660   (let ((num 1)
661         parts)
662     (while (consp (car structure))
663       (let ((sub (pop structure)))
664         (if (consp (car sub))
665             (push (nnimap-find-wanted-parts-1
666                    sub (if (string= prefix "")
667                            (number-to-string num)
668                          (format "%s.%s" prefix num)))
669                   parts)
670           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
671                 (id (if (string= prefix "")
672                         (number-to-string num)
673                       (format "%s.%s" prefix num))))
674             (setcar (nthcdr 9 sub) id)
675             (when (if (eq nnimap-fetch-partial-articles t)
676                       (equal id "1")
677                     (string-match nnimap-fetch-partial-articles type))
678               (push id parts))))
679         (incf num)))
680     (nreverse parts)))
681
682 (deffoo nnimap-request-group (group &optional server dont-check info)
683   (let ((result (nnimap-possibly-change-group
684                  ;; Don't SELECT the group if we're going to select it
685                  ;; later, anyway.
686                  (if (and (not dont-check)
687                           (assoc group nnimap-current-infos))
688                      nil
689                    group)
690                  server))
691         articles active marks high low)
692     (with-current-buffer nntp-server-buffer
693       (when result
694         (if (and dont-check
695                  (setq active (nth 2 (assoc group nnimap-current-infos))))
696             (insert (format "211 %d %d %d %S\n"
697                             (- (cdr active) (car active))
698                             (car active)
699                             (cdr active)
700                             group))
701           (with-current-buffer (nnimap-buffer)
702             (erase-buffer)
703             (let ((group-sequence
704                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
705                   (flag-sequence
706                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
707               (setf (nnimap-group nnimap-object) group)
708               (nnimap-wait-for-response flag-sequence)
709               (setq marks
710                     (nnimap-flags-to-marks
711                      (nnimap-parse-flags
712                       (list (list group-sequence flag-sequence
713                                   1 group "SELECT")))))
714               (when (and info
715                          marks)
716                 (nnimap-update-infos marks (list info))
717                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
718               (goto-char (point-max))
719               (let ((uidnext (nth 5 (car marks))))
720                 (setq high (or (if uidnext
721                                    (1- uidnext)
722                                  (nth 3 (car marks)))
723                                0)
724                       low (or (nth 4 (car marks)) uidnext 1)))))
725           (erase-buffer)
726           (insert
727            (format
728             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
729         t))))
730
731 (deffoo nnimap-request-create-group (group &optional server args)
732   (when (nnimap-possibly-change-group nil server)
733     (with-current-buffer (nnimap-buffer)
734       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
735
736 (deffoo nnimap-request-delete-group (group &optional force server)
737   (when (nnimap-possibly-change-group nil server)
738     (with-current-buffer (nnimap-buffer)
739       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
740
741 (deffoo nnimap-request-rename-group (group new-name &optional server)
742   (when (nnimap-possibly-change-group nil server)
743     (with-current-buffer (nnimap-buffer)
744       (nnimap-unselect-group)
745       (car (nnimap-command "RENAME %S %S"
746                            (utf7-encode group t) (utf7-encode new-name t))))))
747
748 (defun nnimap-unselect-group ()
749   ;; Make sure we don't have this group open read/write by asking
750   ;; to examine a mailbox that doesn't exist.  This seems to be
751   ;; the only way that allows us to reliably go back to unselected
752   ;; state on Courier.
753   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
754
755 (deffoo nnimap-request-expunge-group (group &optional server)
756   (when (nnimap-possibly-change-group group server)
757     (with-current-buffer (nnimap-buffer)
758       (car (nnimap-command "EXPUNGE")))))
759
760 (defun nnimap-get-flags (spec)
761   (let ((articles nil)
762         elems end)
763     (with-current-buffer (nnimap-buffer)
764       (erase-buffer)
765       (nnimap-wait-for-response (nnimap-send-command
766                                  "UID FETCH %s FLAGS" spec))
767       (setq end (point))
768       (subst-char-in-region (point-min) (point-max)
769                             ?\\ ?% t)
770       (goto-char (point-min))
771       (while (search-forward " FETCH " end t)
772         (setq elems (read (current-buffer)))
773         (push (cons (cadr (memq 'UID elems))
774                     (cadr (memq 'FLAGS elems)))
775               articles)))
776     (nreverse articles)))
777
778 (deffoo nnimap-close-group (group &optional server)
779   t)
780
781 (deffoo nnimap-request-move-article (article group server accept-form
782                                              &optional last internal-move-group)
783   (with-temp-buffer
784     (mm-disable-multibyte)
785     (when (funcall (if internal-move-group
786                        'nnimap-request-head
787                      'nnimap-request-article)
788                    article group server (current-buffer))
789       ;; If the move is internal (on the same server), just do it the easy
790       ;; way.
791       (let ((message-id (message-field-value "message-id")))
792         (if internal-move-group
793             (let ((result
794                    (with-current-buffer (nnimap-buffer)
795                      (nnimap-command "UID COPY %d %S"
796                                      article
797                                      (utf7-encode internal-move-group t)))))
798               (when (car result)
799                 (nnimap-delete-article article)
800                 (cons internal-move-group
801                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
802                           (nnimap-find-article-by-message-id
803                            internal-move-group message-id)))))
804           ;; Move the article to a different method.
805           (let ((result (eval accept-form)))
806             (when result
807               (nnimap-delete-article article)
808               result)))))))
809
810 (deffoo nnimap-request-expire-articles (articles group &optional server force)
811   (cond
812    ((null articles)
813     nil)
814    ((not (nnimap-possibly-change-group group server))
815     articles)
816    ((and force
817          (eq nnmail-expiry-target 'delete))
818     (unless (nnimap-delete-article (gnus-compress-sequence articles))
819       (nnheader-message 7 "Article marked for deletion, but not expunged."))
820     nil)
821    (t
822     (let ((deletable-articles
823            (if (or force
824                    (eq nnmail-expiry-wait 'immediate))
825                articles
826              (gnus-sorted-intersection
827               articles
828               (nnimap-find-expired-articles group)))))
829       (if (null deletable-articles)
830           articles
831         (if (eq nnmail-expiry-target 'delete)
832             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
833           (setq deletable-articles
834                 (nnimap-process-expiry-targets
835                  deletable-articles group server)))
836         ;; Return the articles we didn't delete.
837         (gnus-sorted-complement articles deletable-articles))))))
838
839 (defun nnimap-process-expiry-targets (articles group server)
840   (let ((deleted-articles nil))
841     (cond
842      ;; shortcut further processing if we're going to delete the articles
843      ((eq nnmail-expiry-target 'delete)
844       (setq deleted-articles articles)
845       t)
846      ;; or just move them to another folder on the same IMAP server
847      ((and (not (functionp nnmail-expiry-target))
848            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
849                               (gnus-server-to-method
850                                (format "nnimap:%s" server))))
851       (and (nnimap-possibly-change-group group server)
852            (with-current-buffer (nnimap-buffer)
853              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
854              (nnimap-command
855               "UID COPY %s %S"
856               (nnimap-article-ranges (gnus-compress-sequence articles))
857               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
858              (setq deleted-articles articles)))
859       t)
860      (t
861       (dolist (article articles)
862         (let ((target nnmail-expiry-target))
863           (with-temp-buffer
864             (mm-disable-multibyte)
865             (when (nnimap-request-article article group server (current-buffer))
866               (nnheader-message 7 "Expiring article %s:%d" group article)
867               (when (functionp target)
868                 (setq target (funcall target group)))
869               (when (and target
870                          (not (eq target 'delete)))
871                 (if (or (gnus-request-group target t)
872                         (gnus-request-create-group target))
873                     (nnmail-expiry-target-group target group)
874                   (setq target nil)))
875               (when target
876                 (push article deleted-articles))))))))
877     ;; Change back to the current group again.
878     (nnimap-possibly-change-group group server)
879     (setq deleted-articles (nreverse deleted-articles))
880     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
881     deleted-articles))
882
883 (defun nnimap-find-expired-articles (group)
884   (let ((cutoff (nnmail-expired-article-p group nil nil)))
885     (with-current-buffer (nnimap-buffer)
886       (let ((result
887              (nnimap-command
888               "UID SEARCH SENTBEFORE %s"
889               (format-time-string
890                (format "%%d-%s-%%Y"
891                        (upcase
892                         (car (rassoc (nth 4 (decode-time cutoff))
893                                      parse-time-months))))
894                cutoff))))
895         (and (car result)
896              (delete 0 (mapcar #'string-to-number
897                                (cdr (assoc "SEARCH" (cdr result))))))))))
898
899
900 (defun nnimap-find-article-by-message-id (group message-id)
901   (with-current-buffer (nnimap-buffer)
902     (erase-buffer)
903     (unless (equal group (nnimap-group nnimap-object))
904       (setf (nnimap-group nnimap-object) nil)
905       (setf (nnimap-examined nnimap-object) group)
906       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
907     (let ((sequence
908            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
909           article result)
910       (setq result (nnimap-wait-for-response sequence))
911       (when (and result
912                  (car (setq result (nnimap-parse-response))))
913         ;; Select the last instance of the message in the group.
914         (and (setq article
915                    (car (last (assoc "SEARCH" (cdr result)))))
916              (string-to-number article))))))
917
918 (defun nnimap-delete-article (articles)
919   (with-current-buffer (nnimap-buffer)
920     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
921                     (nnimap-article-ranges articles))
922     (cond
923      ((nnimap-capability "UIDPLUS")
924       (nnimap-command "UID EXPUNGE %s"
925                       (nnimap-article-ranges articles))
926       t)
927      (nnimap-expunge
928       (nnimap-command "EXPUNGE")
929       t)
930      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
931                                 "server doesn't support UIDPLUS, so we won't "
932                                 "delete this article now"))))))
933
934 (deffoo nnimap-request-scan (&optional group server)
935   (when (and (nnimap-possibly-change-group nil server)
936              nnimap-inbox
937              nnimap-split-methods)
938     (nnheader-message 7 "nnimap %s splitting mail..." server)
939     (nnimap-split-incoming-mail)))
940
941 (defun nnimap-marks-to-flags (marks)
942   (let (flags flag)
943     (dolist (mark marks)
944       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
945         (push flag flags)))
946     flags))
947
948 (deffoo nnimap-request-update-group-status (group status &optional server)
949   (when (nnimap-possibly-change-group nil server)
950     (let ((command (assoc
951                     status
952                     '((subscribe "SUBSCRIBE")
953                       (unsubscribe "UNSUBSCRIBE")))))
954       (when command
955         (with-current-buffer (nnimap-buffer)
956           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
957
958 (deffoo nnimap-request-set-mark (group actions &optional server)
959   (when (nnimap-possibly-change-group group server)
960     (let (sequence)
961       (with-current-buffer (nnimap-buffer)
962         (erase-buffer)
963         ;; Just send all the STORE commands without waiting for
964         ;; response.  If they're successful, they're successful.
965         (dolist (action actions)
966           (destructuring-bind (range action marks) action
967             (let ((flags (nnimap-marks-to-flags marks)))
968               (when flags
969                 (setq sequence (nnimap-send-command
970                                 "UID STORE %s %sFLAGS.SILENT (%s)"
971                                 (nnimap-article-ranges range)
972                                 (cond
973                                  ((eq action 'del) "-")
974                                  ((eq action 'add) "+")
975                                  ((eq action 'set) ""))
976                                 (mapconcat #'identity flags " ")))))))
977         ;; Wait for the last command to complete to avoid later
978         ;; syncronisation problems with the stream.
979         (when sequence
980           (nnimap-wait-for-response sequence))))))
981
982 (deffoo nnimap-request-accept-article (group &optional server last)
983   (when (nnimap-possibly-change-group nil server)
984     (nnmail-check-syntax)
985     (let ((message-id (message-field-value "message-id"))
986           sequence message)
987       (nnimap-add-cr)
988       (setq message (buffer-substring-no-properties (point-min) (point-max)))
989       (with-current-buffer (nnimap-buffer)
990         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
991                                 message))
992           ;; If we have this group open read-only, then unselect it
993           ;; before appending to it.
994           (when (equal (nnimap-examined nnimap-object) group)
995             (nnimap-unselect-group))
996           (erase-buffer)
997           (setq sequence (nnimap-send-command
998                           "APPEND %S {%d}" (utf7-encode group t)
999                           (length message)))
1000           (unless nnimap-streaming
1001             (nnimap-wait-for-connection "^[+]"))
1002           (process-send-string (get-buffer-process (current-buffer)) message)
1003           (process-send-string (get-buffer-process (current-buffer))
1004                                (if (nnimap-newlinep nnimap-object)
1005                                    "\n"
1006                                  "\r\n"))
1007           (let ((result (nnimap-get-response sequence)))
1008             (if (not (nnimap-ok-p result))
1009                 (progn
1010                   (nnheader-report 'nnimap "%s" result)
1011                   nil)
1012               (cons group
1013                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1014                         (nnimap-find-article-by-message-id
1015                          group message-id))))))))))
1016
1017 (defun nnimap-process-quirk (greeting-match type data)
1018   (when (and (nnimap-greeting nnimap-object)
1019              (string-match greeting-match (nnimap-greeting nnimap-object))
1020              (eq type 'append)
1021              (string-match "\000" data))
1022     (let ((choice (gnus-multiple-choice
1023                    "Message contains NUL characters.  Delete, continue, abort? "
1024                    '((?d "Delete NUL characters")
1025                      (?c "Try to APPEND the message as is")
1026                      (?a "Abort")))))
1027       (cond
1028        ((eq choice ?a)
1029         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1030        ((eq choice ?c)
1031         data)
1032        (t
1033         (with-temp-buffer
1034           (insert data)
1035           (goto-char (point-min))
1036           (while (search-forward "\000" nil t)
1037             (replace-match "" t t))
1038           (buffer-string)))))))
1039
1040 (defun nnimap-ok-p (value)
1041   (and (consp value)
1042        (consp (car value))
1043        (equal (caar value) "OK")))
1044
1045 (defun nnimap-find-uid-response (name list)
1046   (let ((result (car (last (nnimap-find-response-element name list)))))
1047     (and result
1048          (string-to-number result))))
1049
1050 (defun nnimap-find-response-element (name list)
1051   (let (result)
1052     (dolist (elem list)
1053       (when (and (consp elem)
1054                  (equal name (car elem)))
1055         (setq result elem)))
1056     result))
1057
1058 (deffoo nnimap-request-replace-article (article group buffer)
1059   (let (group-art)
1060     (when (and (nnimap-possibly-change-group group nil)
1061                ;; Put the article into the group.
1062                (with-current-buffer buffer
1063                  (setq group-art
1064                        (nnimap-request-accept-article group nil t))))
1065       (nnimap-delete-article (list article))
1066       ;; Return the new article number.
1067       (cdr group-art))))
1068
1069 (defun nnimap-add-cr ()
1070   (goto-char (point-min))
1071   (while (re-search-forward "\r?\n" nil t)
1072     (replace-match "\r\n" t t)))
1073
1074 (defun nnimap-get-groups ()
1075   (erase-buffer)
1076   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1077         groups)
1078     (nnimap-wait-for-response sequence)
1079     (subst-char-in-region (point-min) (point-max)
1080                           ?\\ ?% t)
1081     (goto-char (point-min))
1082     (nnimap-unfold-quoted-lines)
1083     (goto-char (point-min))
1084     (while (search-forward "* LIST " nil t)
1085       (let ((flags (read (current-buffer)))
1086             (separator (read (current-buffer)))
1087             (group (read (current-buffer))))
1088         (unless (member '%NoSelect flags)
1089           (push (if (stringp group)
1090                     group
1091                   (format "%s" group))
1092                 groups))))
1093     (nreverse groups)))
1094
1095 (deffoo nnimap-request-list (&optional server)
1096   (when (nnimap-possibly-change-group nil server)
1097     (with-current-buffer nntp-server-buffer
1098       (erase-buffer)
1099       (let ((groups
1100              (with-current-buffer (nnimap-buffer)
1101                (nnimap-get-groups)))
1102             sequences responses)
1103         (when groups
1104           (with-current-buffer (nnimap-buffer)
1105             (setf (nnimap-group nnimap-object) nil)
1106             (dolist (group groups)
1107               (setf (nnimap-examined nnimap-object) group)
1108               (push (list (nnimap-send-command "EXAMINE %S"
1109                                                (utf7-encode group t))
1110                           group)
1111                     sequences))
1112             (nnimap-wait-for-response (caar sequences))
1113             (setq responses
1114                   (nnimap-get-responses (mapcar #'car sequences))))
1115           (dolist (response responses)
1116             (let* ((sequence (car response))
1117                    (response (cadr response))
1118                    (group (cadr (assoc sequence sequences))))
1119               (when (and group
1120                          (equal (caar response) "OK"))
1121                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1122                       highest exists)
1123                   (dolist (elem response)
1124                     (when (equal (cadr elem) "EXISTS")
1125                       (setq exists (string-to-number (car elem)))))
1126                   (when uidnext
1127                     (setq highest (1- (string-to-number (car uidnext)))))
1128                   (cond
1129                    ((null highest)
1130                     (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1131                    ((zerop exists)
1132                     ;; Empty group.
1133                     (insert (format "%S %d %d y\n"
1134                                     (utf7-decode group t)
1135                                     highest (1+ highest))))
1136                    (t
1137                     ;; Return the widest possible range.
1138                     (insert (format "%S %d 1 y\n" (utf7-decode group t)
1139                                     (or highest exists)))))))))
1140           t)))))
1141
1142 (deffoo nnimap-request-newgroups (date &optional server)
1143   (when (nnimap-possibly-change-group nil server)
1144     (with-current-buffer nntp-server-buffer
1145       (erase-buffer)
1146       (dolist (group (with-current-buffer (nnimap-buffer)
1147                        (nnimap-get-groups)))
1148         (unless (assoc group nnimap-current-infos)
1149           ;; Insert dummy numbers here -- they don't matter.
1150           (insert (format "%S 0 1 y\n" group))))
1151       t)))
1152
1153 (deffoo nnimap-retrieve-group-data-early (server infos)
1154   (when (nnimap-possibly-change-group nil server)
1155     (with-current-buffer (nnimap-buffer)
1156       (erase-buffer)
1157       (setf (nnimap-group nnimap-object) nil)
1158       (let ((qresyncp (nnimap-capability "QRESYNC"))
1159             params groups sequences active uidvalidity modseq group)
1160         ;; Go through the infos and gather the data needed to know
1161         ;; what and how to request the data.
1162         (dolist (info infos)
1163           (setq params (gnus-info-params info)
1164                 group (gnus-group-real-name (gnus-info-group info))
1165                 active (cdr (assq 'active params))
1166                 uidvalidity (cdr (assq 'uidvalidity params))
1167                 modseq (cdr (assq 'modseq params)))
1168           (setf (nnimap-examined nnimap-object) group)
1169           (if (and qresyncp
1170                    uidvalidity
1171                    active
1172                    modseq)
1173               (push
1174                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1175                                           (utf7-encode group t)
1176                                           (nnimap-quirk "QRESYNC")
1177                                           uidvalidity modseq)
1178                      'qresync
1179                      nil group 'qresync)
1180                sequences)
1181             (let ((start
1182                    (if (and active uidvalidity)
1183                        ;; Fetch the last 100 flags.
1184                        (max 1 (- (cdr active) 100))
1185                      1))
1186                   (command
1187                    (if uidvalidity
1188                        "EXAMINE"
1189                      ;; If we don't have a UIDVALIDITY, then this is
1190                      ;; the first time we've seen the group, so we
1191                      ;; have to do a SELECT (which is slower than an
1192                      ;; examine), but will tell us whether the group
1193                      ;; is read-only or not.
1194                      "SELECT")))
1195               (push (list (nnimap-send-command "%s %S" command
1196                                                (utf7-encode group t))
1197                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1198                           start group command)
1199                     sequences))))
1200         sequences))))
1201
1202 (defun nnimap-quirk (command)
1203   (let ((quirk (assoc command nnimap-quirks)))
1204     ;; If this server is of a type that matches a quirk, then return
1205     ;; the "quirked" command instead of the proper one.
1206     (if (or (null quirk)
1207             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1208         command
1209       (nth 2 quirk))))
1210
1211 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1212   (when (and sequences
1213              (nnimap-possibly-change-group nil server))
1214     (with-current-buffer (nnimap-buffer)
1215       ;; Wait for the final data to trickle in.
1216       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1217                                           (caar sequences)
1218                                         (cadar sequences))
1219                                       t)
1220         ;; Now we should have most of the data we need, no matter
1221         ;; whether we're QRESYNCING, fetching all the flags from
1222         ;; scratch, or just fetching the last 100 flags per group.
1223         (nnimap-update-infos (nnimap-flags-to-marks
1224                               (nnimap-parse-flags
1225                                (nreverse sequences)))
1226                              infos)
1227         ;; Finally, just return something resembling an active file in
1228         ;; the nntp buffer, so that the agent can save the info, too.
1229         (with-current-buffer nntp-server-buffer
1230           (erase-buffer)
1231           (dolist (info infos)
1232             (let* ((group (gnus-info-group info))
1233                    (active (gnus-active group)))
1234               (when active
1235                 (insert (format "%S %d %d y\n"
1236                                 (gnus-group-real-name group)
1237                                 (cdr active)
1238                                 (car active)))))))))))
1239
1240 (defun nnimap-update-infos (flags infos)
1241   (dolist (info infos)
1242     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1243            (marks (cdr (assoc group flags))))
1244       (when marks
1245         (nnimap-update-info info marks)))))
1246
1247 (defun nnimap-update-info (info marks)
1248   (destructuring-bind (existing flags high low uidnext start-article
1249                                 permanent-flags uidvalidity
1250                                 vanished highestmodseq) marks
1251     (cond
1252      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1253      ;; completely empty groups.
1254      ((and (not existing)
1255            (not uidnext))
1256       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1257         (when active
1258           (gnus-set-active (gnus-info-group info) active))))
1259      ;; We have a mismatch between the old and new UIDVALIDITY
1260      ;; identifiers, so we have to re-request the group info (the next
1261      ;; time).  This virtually never happens.
1262      ((let ((old-uidvalidity
1263              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1264         (and old-uidvalidity
1265              (not (equal old-uidvalidity uidvalidity))
1266              (> start-article 1)))
1267       (gnus-group-remove-parameter info 'uidvalidity)
1268       (gnus-group-remove-parameter info 'modseq))
1269      ;; We have the data needed to update.
1270      (t
1271       (let* ((group (gnus-info-group info))
1272              (completep (and start-article
1273                              (= start-article 1)))
1274              (active (or (gnus-active group)
1275                          (cdr (assq 'active (gnus-info-params info))))))
1276         (when uidnext
1277           (setq high (1- uidnext)))
1278         ;; First set the active ranges based on high/low.
1279         (if (or completep
1280                 (not (gnus-active group)))
1281             (gnus-set-active group
1282                              (cond
1283                               (active
1284                                (cons (min (or low (car active))
1285                                           (car active))
1286                                      (max (or high (cdr active))
1287                                           (cdr active))))
1288                               ((and low high)
1289                                (cons low high))
1290                               (uidnext
1291                                ;; No articles in this group.
1292                                (cons uidnext (1- uidnext)))
1293                               (start-article
1294                                (cons start-article (1- start-article)))
1295                               (t
1296                                ;; No articles and no uidnext.
1297                                nil)))
1298           (gnus-set-active group
1299                            (cons (car active)
1300                                  (or high (1- uidnext)))))
1301         ;; See whether this is a read-only group.
1302         (unless (eq permanent-flags 'not-scanned)
1303           (gnus-group-set-parameter
1304            info 'permanent-flags
1305            (and (or (memq '%* permanent-flags)
1306                     (memq '%Seen permanent-flags))
1307                 permanent-flags)))
1308         ;; Update marks and read articles if this isn't a
1309         ;; read-only IMAP group.
1310         (when (setq permanent-flags
1311                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1312           (if (and highestmodseq
1313                    (not start-article))
1314               ;; We've gotten the data by QRESYNCing.
1315               (nnimap-update-qresync-info
1316                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1317             ;; Do normal non-QRESYNC flag updates.
1318             ;; Update the list of read articles.
1319             (let* ((unread
1320                     (gnus-compress-sequence
1321                      (gnus-set-difference
1322                       (gnus-set-difference
1323                        existing
1324                        (cdr (assoc '%Seen flags)))
1325                       (cdr (assoc '%Flagged flags)))))
1326                    (read (gnus-range-difference
1327                           (cons start-article high) unread)))
1328               (when (> start-article 1)
1329                 (setq read
1330                       (gnus-range-nconcat
1331                        (if (> start-article 1)
1332                            (gnus-sorted-range-intersection
1333                             (cons 1 (1- start-article))
1334                             (gnus-info-read info))
1335                          (gnus-info-read info))
1336                        read)))
1337               (when (or (not (listp permanent-flags))
1338                         (memq '%Seen permanent-flags))
1339                 (gnus-info-set-read info read))
1340               ;; Update the marks.
1341               (setq marks (gnus-info-marks info))
1342               (dolist (type (cdr nnimap-mark-alist))
1343                 (when (or (not (listp permanent-flags))
1344                           (memq (car (assoc (caddr type) flags))
1345                                 permanent-flags)
1346                           (memq '%* permanent-flags))
1347                   (let ((old-marks (assoc (car type) marks))
1348                         (new-marks
1349                          (gnus-compress-sequence
1350                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1351                                    (assoc (intern (cadr type) obarray) flags)
1352                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1353                     (setq marks (delq old-marks marks))
1354                     (pop old-marks)
1355                     (when (and old-marks
1356                                (> start-article 1))
1357                       (setq old-marks (gnus-range-difference
1358                                        old-marks
1359                                        (cons start-article high)))
1360                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1361                     (when new-marks
1362                       (push (cons (car type) new-marks) marks)))))
1363               (gnus-info-set-marks info marks t))))
1364         ;; Tell Gnus whether there are any \Recent messages in any of
1365         ;; the groups.
1366         (let ((recent (cdr (assoc '%Recent flags))))
1367           (when (and active
1368                      recent
1369                      (> (car (last recent)) (cdr active)))
1370             (push (list (cons (gnus-group-real-name group) 0))
1371                   nnmail-split-history)))
1372         ;; Note the active level for the next run-through.
1373         (gnus-group-set-parameter info 'active (gnus-active group))
1374         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1375         (gnus-group-set-parameter info 'modseq highestmodseq)
1376         (nnimap-store-info info (gnus-active group)))))))
1377
1378 (defun nnimap-update-qresync-info (info existing vanished flags)
1379   ;; Add all the vanished articles to the list of read articles.
1380   (gnus-info-set-read
1381    info
1382    (gnus-add-to-range
1383     (gnus-add-to-range
1384      (gnus-range-add (gnus-info-read info)
1385                      vanished)
1386      (cdr (assq '%Flagged flags)))
1387     (cdr (assq '%Seen flags))))
1388   (let ((marks (gnus-info-marks info)))
1389     (dolist (type (cdr nnimap-mark-alist))
1390       (let ((ticks (assoc (car type) marks))
1391             (new-marks
1392              (cdr (or (assoc (caddr type) flags) ; %Flagged
1393                       (assoc (intern (cadr type) obarray) flags)
1394                       (assoc (cadr type) flags))))) ; "\Flagged"
1395         (setq marks (delq ticks marks))
1396         (pop ticks)
1397         ;; Add the new marks we got.
1398         (setq ticks (gnus-add-to-range ticks new-marks))
1399         ;; Remove the marks from messages that don't have them.
1400         (setq ticks (gnus-remove-from-range
1401                      ticks
1402                      (gnus-compress-sequence
1403                       (gnus-sorted-complement existing new-marks))))
1404         (when ticks
1405           (push (cons (car type) ticks) marks)))
1406       (gnus-info-set-marks info marks t))))
1407
1408 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1409   (if (zerop (length irange))
1410       nil
1411     (let ((result nil))
1412       (dolist (elem (split-string irange ","))
1413         (push
1414          (if (string-match ":" elem)
1415              (let ((numbers (split-string elem ":")))
1416                (cons (string-to-number (car numbers))
1417                      (string-to-number (cadr numbers))))
1418            (string-to-number elem))
1419          result))
1420       (nreverse result))))
1421
1422 (defun nnimap-store-info (info active)
1423   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1424          (entry (assoc group nnimap-current-infos)))
1425     (if entry
1426         (setcdr entry (list info active))
1427       (push (list group info active) nnimap-current-infos))))
1428
1429 (defun nnimap-flags-to-marks (groups)
1430   (let (data group totalp uidnext articles start-article mark permanent-flags
1431              uidvalidity vanished highestmodseq)
1432     (dolist (elem groups)
1433       (setq group (car elem)
1434             uidnext (nth 1 elem)
1435             start-article (nth 2 elem)
1436             permanent-flags (nth 3 elem)
1437             uidvalidity (nth 4 elem)
1438             vanished (nth 5 elem)
1439             highestmodseq (nth 6 elem)
1440             articles (nthcdr 7 elem))
1441       (let ((high (caar articles))
1442             marks low existing)
1443         (dolist (article articles)
1444           (setq low (car article))
1445           (push (car article) existing)
1446           (dolist (flag (cdr article))
1447             (setq mark (assoc flag marks))
1448             (if (not mark)
1449                 (push (list flag (car article)) marks)
1450               (setcdr mark (cons (car article) (cdr mark))))))
1451         (push (list group existing marks high low uidnext start-article
1452                     permanent-flags uidvalidity vanished highestmodseq)
1453               data)))
1454     data))
1455
1456 (defun nnimap-parse-flags (sequences)
1457   (goto-char (point-min))
1458   ;; Change \Delete etc to %Delete, so that the reader can read it.
1459   (subst-char-in-region (point-min) (point-max)
1460                         ?\\ ?% t)
1461   ;; Remove any MODSEQ entries in the buffer, because they may contain
1462   ;; numbers that are too large for 32-bit Emacsen.
1463   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1464     (replace-match "" t t))
1465   (goto-char (point-min))
1466   (let (start end articles groups uidnext elems permanent-flags
1467               uidvalidity vanished highestmodseq)
1468     (dolist (elem sequences)
1469       (destructuring-bind (group-sequence flag-sequence totalp group command)
1470           elem
1471         (setq start (point))
1472         (when (and
1473                ;; The EXAMINE was successful.
1474                (search-forward (format "\n%d OK " group-sequence) nil t)
1475                (progn
1476                  (forward-line 1)
1477                  (setq end (point))
1478                  (goto-char start)
1479                  (setq permanent-flags
1480                        (if (equal command "SELECT")
1481                            (and (search-forward "PERMANENTFLAGS "
1482                                                 (or end (point-min)) t)
1483                                 (read (current-buffer)))
1484                          'not-scanned))
1485                  (goto-char start)
1486                  (setq uidnext
1487                        (and (search-forward "UIDNEXT "
1488                                             (or end (point-min)) t)
1489                             (read (current-buffer))))
1490                  (goto-char start)
1491                  (setq uidvalidity
1492                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1493                                                (or end (point-min)) t)
1494                             ;; Store UIDVALIDITY as a string, as it's
1495                             ;; too big for 32-bit Emacsen, usually.
1496                             (match-string 1)))
1497                  (goto-char start)
1498                  (setq vanished
1499                        (and (eq flag-sequence 'qresync)
1500                             (re-search-forward "^\\* VANISHED .* \\([0-9:,]+\\)"
1501                                                (or end (point-min)) t)
1502                             (match-string 1)))
1503                  (goto-char start)
1504                  (setq highestmodseq
1505                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1506                                             (or end (point-min)) t)
1507                             (match-string 1)))
1508                  (goto-char end)
1509                  (forward-line -1))
1510                ;; The UID FETCH FLAGS was successful.
1511                (or (eq flag-sequence 'qresync)
1512                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1513           (if (eq flag-sequence 'qresync)
1514               (progn
1515                 (goto-char start)
1516                 (setq start end))
1517             (setq start (point))
1518             (goto-char end))
1519           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1520             (let ((p (point)))
1521               (setq elems (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        (when debug-on-quit
1678          (debug "Quit"))
1679        ;; The user hit C-g while we were waiting: kill the process, in case
1680        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1681        ;; NAT routers).
1682        (delete-process process)
1683        nil))))
1684
1685 (defun nnimap-parse-response ()
1686   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1687         result)
1688     (dolist (line lines)
1689       (push (cdr (nnimap-parse-line line)) result))
1690     ;; Return the OK/error code first, and then all the "continuation
1691     ;; lines" afterwards.
1692     (cons (pop result)
1693           (nreverse result))))
1694
1695 ;; Parse an IMAP response line lightly.  They look like
1696 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1697 ;; the lines into a list of strings and lists of string.
1698 (defun nnimap-parse-line (line)
1699   (let (char result)
1700     (with-temp-buffer
1701       (mm-disable-multibyte)
1702       (insert line)
1703       (goto-char (point-min))
1704       (while (not (eobp))
1705         (if (eql (setq char (following-char)) ? )
1706             (forward-char 1)
1707           (push
1708            (cond
1709             ((eql char ?\[)
1710              (split-string
1711               (buffer-substring
1712                (1+ (point))
1713                (if (search-forward "]" (line-end-position) 'move)
1714                    (1- (point))
1715                  (point)))))
1716             ((eql char ?\()
1717              (split-string
1718               (buffer-substring
1719                (1+ (point))
1720                (if (search-forward ")" (line-end-position) 'move)
1721                    (1- (point))
1722                  (point)))))
1723             ((eql char ?\")
1724              (forward-char 1)
1725              (buffer-substring
1726               (point)
1727               (1- (or (search-forward "\"" (line-end-position) 'move)
1728                       (point)))))
1729             (t
1730              (buffer-substring (point) (if (search-forward " " nil t)
1731                                            (1- (point))
1732                                          (goto-char (point-max))))))
1733            result)))
1734       (nreverse result))))
1735
1736 (defun nnimap-last-response-string ()
1737   (save-excursion
1738     (forward-line 1)
1739     (let ((end (point)))
1740       (forward-line -1)
1741       (when (not (bobp))
1742         (forward-line -1)
1743         (while (and (not (bobp))
1744                     (eql (following-char) ?*))
1745           (forward-line -1))
1746         (unless (eql (following-char) ?*)
1747           (forward-line 1)))
1748       (buffer-substring (point) end))))
1749
1750 (defun nnimap-get-responses (sequences)
1751   (let (responses)
1752     (dolist (sequence sequences)
1753       (goto-char (point-min))
1754       (when (re-search-forward (format "^%d " sequence) nil t)
1755         (push (list sequence (nnimap-parse-response))
1756               responses)))
1757     responses))
1758
1759 (defvar nnimap-incoming-split-list nil)
1760
1761 (defun nnimap-fetch-inbox (articles)
1762   (erase-buffer)
1763   (nnimap-wait-for-response
1764    (nnimap-send-command
1765     "UID FETCH %s %s"
1766     (nnimap-article-ranges articles)
1767     (format "(UID %s%s)"
1768             (format
1769              (if (nnimap-ver4-p)
1770                  "BODY.PEEK"
1771                "RFC822.PEEK"))
1772             (cond
1773              (nnimap-split-download-body-default
1774               "[]")
1775              ((nnimap-ver4-p)
1776               "[HEADER]")
1777              (t
1778               "[1]"))))
1779    t))
1780
1781 (defun nnimap-split-incoming-mail ()
1782   (with-current-buffer (nnimap-buffer)
1783     (let ((nnimap-incoming-split-list nil)
1784           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1785                                     nnmail-split-methods
1786                                   nnimap-split-methods))
1787           (nnmail-split-fancy (or nnimap-split-fancy
1788                                   nnmail-split-fancy))
1789           (nnmail-inhibit-default-split-group t)
1790           (groups (nnimap-get-groups))
1791           new-articles)
1792       (erase-buffer)
1793       (nnimap-command "SELECT %S" nnimap-inbox)
1794       (setf (nnimap-group nnimap-object) nnimap-inbox)
1795       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1796       (when new-articles
1797         (nnimap-fetch-inbox new-articles)
1798         (nnimap-transform-split-mail)
1799         (nnheader-ms-strip-cr)
1800         (nnmail-cache-open)
1801         (nnmail-split-incoming (current-buffer)
1802                                #'nnimap-save-mail-spec
1803                                nil nil
1804                                #'nnimap-dummy-active-number
1805                                #'nnimap-save-mail-spec)
1806         (when nnimap-incoming-split-list
1807           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1808                 sequences junk-articles)
1809             ;; Create any groups that doesn't already exist on the
1810             ;; server first.
1811             (dolist (spec specs)
1812               (when (and (not (member (car spec) groups))
1813                          (not (eq (car spec) 'junk)))
1814                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1815             ;; Then copy over all the messages.
1816             (erase-buffer)
1817             (dolist (spec specs)
1818               (let ((group (car spec))
1819                     (ranges (cdr spec)))
1820                 (if (eq group 'junk)
1821                     (setq junk-articles ranges)
1822                   (push (list (nnimap-send-command
1823                                "UID COPY %s %S"
1824                                (nnimap-article-ranges ranges)
1825                                (utf7-encode group t))
1826                               ranges)
1827                         sequences))))
1828             ;; Wait for the last COPY response...
1829             (when sequences
1830               (nnimap-wait-for-response (caar sequences))
1831               ;; And then mark the successful copy actions as deleted,
1832               ;; and possibly expunge them.
1833               (nnimap-mark-and-expunge-incoming
1834                (nnimap-parse-copied-articles sequences)))
1835             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1836
1837 (defun nnimap-mark-and-expunge-incoming (range)
1838   (when range
1839     (setq range (nnimap-article-ranges range))
1840     (erase-buffer)
1841     (let ((sequence
1842            (nnimap-send-command
1843             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1844       (cond
1845        ;; If the server supports it, we now delete the message we have
1846        ;; just copied over.
1847        ((nnimap-capability "UIDPLUS")
1848         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1849        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1850        ;; user has configured it.
1851        (nnimap-expunge
1852         (setq sequence (nnimap-send-command "EXPUNGE"))))
1853       (nnimap-wait-for-response sequence))))
1854
1855 (defun nnimap-parse-copied-articles (sequences)
1856   (let (sequence copied range)
1857     (goto-char (point-min))
1858     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1859       (setq sequence (string-to-number (match-string 1)))
1860       (when (setq range (cadr (assq sequence sequences)))
1861         (push (gnus-uncompress-range range) copied)))
1862     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1863
1864 (defun nnimap-new-articles (flags)
1865   (let (new)
1866     (dolist (elem flags)
1867       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1868                                       (cdr elem))
1869         (push (car elem) new)))
1870     (gnus-compress-sequence (nreverse new))))
1871
1872 (defun nnimap-make-split-specs (list)
1873   (let ((specs nil)
1874         entry)
1875     (dolist (elem list)
1876       (destructuring-bind (article spec) elem
1877         (dolist (group (delete nil (mapcar #'car spec)))
1878           (unless (setq entry (assoc group specs))
1879             (push (setq entry (list group)) specs))
1880           (setcdr entry (cons article (cdr entry))))))
1881     (dolist (entry specs)
1882       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1883     specs))
1884
1885 (defun nnimap-transform-split-mail ()
1886   (goto-char (point-min))
1887   (let (article bytes)
1888     (block nil
1889       (while (not (eobp))
1890         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1891           (delete-region (point) (progn (forward-line 1) (point)))
1892           (when (eobp)
1893             (return)))
1894         (setq article (match-string 1)
1895               bytes (nnimap-get-length))
1896         (delete-region (line-beginning-position) (line-end-position))
1897         ;; Insert MMDF separator, and a way to remember what this
1898         ;; article UID is.
1899         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1900         (forward-char (1+ bytes))
1901         (setq bytes (nnimap-get-length))
1902         (delete-region (line-beginning-position) (line-end-position))
1903         ;; There's a body; skip past that.
1904         (when bytes
1905           (forward-char (1+ bytes))
1906           (delete-region (line-beginning-position) (line-end-position)))))))
1907
1908 (defun nnimap-dummy-active-number (group &optional server)
1909   1)
1910
1911 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1912   (let (article)
1913     (goto-char (point-min))
1914     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1915         (error "Invalid nnimap mail")
1916       (setq article (string-to-number (match-string 1))))
1917     (push (list article
1918                 (if (eq group-art 'junk)
1919                     (list (cons 'junk 1))
1920                   group-art))
1921           nnimap-incoming-split-list)))
1922
1923 (provide 'nnimap)
1924
1925 ;;; nnimap.el ends here