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