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