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