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