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