1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Simon Josefsson <simon@josefsson.org>
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;; nnimap interfaces Gnus with IMAP servers.
29 ;; For Emacs <22.2 and XEmacs.
31 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
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)))
53 (autoload 'auth-source-forget+ "auth-source")
54 (autoload 'auth-source-search "auth-source")
58 (defvoo nnimap-address nil
59 "The address of the IMAP server.")
61 (defvoo nnimap-user nil
62 "Username to use for authentication to the IMAP server.")
64 (defvoo nnimap-server-port nil
66 If nnimap-stream is `ssl', this will default to `imaps'. If not,
67 it will default to `imap'.")
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'.
74 If the value is `undecided', nnimap tries `ssl' first, then falls
77 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78 (if (listp imap-shell-program)
79 (car imap-shell-program)
83 (defvoo nnimap-inbox nil
84 "The mail box where incoming mail arrives and should be split out of.
85 For example, \"INBOX\".")
87 (defvoo nnimap-split-methods nil
89 Uses the same syntax as `nnmail-split-methods'.")
91 (defvoo nnimap-split-fancy nil
92 "Uses the same syntax as `nnmail-split-fancy'.")
94 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
95 "Articles with the flags in the list will not be considered when splitting.")
97 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
100 (defvoo nnimap-authenticator nil
101 "How nnimap authenticate itself to the server.
102 Possible choices are nil (use default methods) or `anonymous'.")
104 (defvoo nnimap-expunge t
105 "If non-nil, expunge articles after deleting them.
106 This is always done if the server supports UID EXPUNGE, but it's
107 not done by default on servers that doesn't support that command.")
109 (defvoo nnimap-streaming t
110 "If non-nil, try to use streaming commands with IMAP servers.
111 Switching this off will make nnimap slower, but it helps with
114 (defvoo nnimap-connection-alist nil)
116 (defvoo nnimap-current-infos nil)
118 (defvoo nnimap-fetch-partial-articles nil
119 "If non-nil, Gnus will fetch partial articles.
120 If t, nnimap will fetch only the first part. If a string, it
121 will fetch all parts that have types that match that string. A
122 likely value would be \"text/\" to automatically fetch all
125 (defvar nnimap-process nil)
127 (defvar nnimap-status-string "")
129 (defvar nnimap-split-download-body-default nil
130 "Internal variable with default value for `nnimap-split-download-body'.")
132 (defvar nnimap-keepalive-timer nil)
133 (defvar nnimap-process-buffers nil)
136 group process commands capabilities select-result newlinep server
137 last-command-time greeting examined stream-type initial-resync)
139 (defvar nnimap-object nil)
141 (defvar nnimap-mark-alist
142 '((read "\\Seen" %Seen)
143 (tick "\\Flagged" %Flagged)
144 (reply "\\Answered" %Answered)
145 (expire "gnus-expire")
146 (dormant "gnus-dormant")
149 (download "gnus-download")
150 (forward "gnus-forward")))
152 (defvar nnimap-quirks
153 '(("QRESYNC" "Zimbra" "QRESYNC ")))
155 (defvar nnimap-inhibit-logging nil)
157 (defun nnimap-buffer ()
158 (nnimap-find-process-buffer nntp-server-buffer))
160 (defun nnimap-header-parameters ()
161 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
164 "BODY.PEEK[HEADER.FIELDS %s]"
165 "RFC822.HEADER.LINES %s")
166 (append '(Subject From Date Message-Id
167 References In-Reply-To Xref)
168 nnmail-extra-headers))))
170 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
172 (setq group (nnimap-decode-gnus-group group)))
173 (with-current-buffer nntp-server-buffer
175 (when (nnimap-possibly-change-group group server)
176 (with-current-buffer (nnimap-buffer)
178 (nnimap-wait-for-response
181 (nnimap-article-ranges (gnus-compress-sequence articles))
182 (nnimap-header-parameters))
184 (nnimap-transform-headers)
185 (nnheader-remove-cr-followed-by-lf))
186 (insert-buffer-substring
187 (nnimap-find-process-buffer (current-buffer))))
190 (defun nnimap-transform-headers ()
191 (goto-char (point-min))
192 (let (article lines size string)
195 (while (not (looking-at "\\* [0-9]+ FETCH"))
196 (delete-region (point) (progn (forward-line 1) (point)))
199 (goto-char (match-end 0))
200 ;; Unfold quoted {number} strings.
201 (while (re-search-forward
202 "[^]][ (]{\\([0-9]+\\)}\r?\n"
204 ;; Start of the header section.
205 (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
206 ;; Start of the next FETCH.
207 (re-search-forward "\\* [0-9]+ FETCH" nil t)
210 (setq size (string-to-number (match-string 1)))
211 (delete-region (+ (match-beginning 0) 2) (point))
212 (setq string (buffer-substring (point) (+ (point) size)))
213 (delete-region (point) (+ (point) size))
214 (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
217 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
222 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
227 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
228 (let ((structure (ignore-errors
229 (read (current-buffer)))))
230 (while (and (consp structure)
231 (not (atom (car structure))))
232 (setq structure (car structure)))
234 (stringp (car structure))
235 (equal (upcase (nth 0 structure)) "MESSAGE")
236 (equal (upcase (nth 1 structure)) "RFC822"))
238 (nth 7 structure)))))
239 (delete-region (line-beginning-position) (line-end-position))
240 (insert (format "211 %s Article retrieved." article))
243 (insert (format "Chars: %s\n" size)))
245 (insert (format "Lines: %s\n" lines)))
246 (unless (re-search-forward "^\r$" nil t)
247 (goto-char (point-max)))
248 (delete-region (line-beginning-position) (line-end-position))
252 (defun nnimap-unfold-quoted-lines ()
253 ;; Unfold quoted {number} strings.
255 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
256 (setq size (string-to-number (match-string 1)))
257 (delete-region (1+ (match-beginning 0)) (point))
258 (setq string (buffer-substring (point) (+ (point) size)))
259 (delete-region (point) (+ (point) size))
260 (insert (format "%S" string)))))
262 (defun nnimap-get-length ()
263 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
264 (string-to-number (match-string 1))))
266 (defun nnimap-article-ranges (ranges)
270 (number-to-string ranges))
271 ((numberp (cdr ranges))
272 (format "%d:%d" (car ranges) (cdr ranges)))
274 (dolist (elem ranges)
277 (format "%d:%d" (car elem) (cdr elem))
278 (number-to-string elem))
280 (mapconcat #'identity (nreverse result) ",")))))
282 (deffoo nnimap-open-server (server &optional defs no-reconnect)
283 (if (nnimap-server-opened server)
285 (unless (assq 'nnimap-address defs)
286 (setq defs (append defs (list (list 'nnimap-address server)))))
287 (nnoo-change-server 'nnimap server defs)
289 (nnimap-find-connection nntp-server-buffer)
290 (or (nnimap-find-connection nntp-server-buffer)
291 (nnimap-open-connection nntp-server-buffer)))))
293 (defun nnimap-make-process-buffer (buffer)
295 (generate-new-buffer (format " *nnimap %s %s %s*"
296 nnimap-address nnimap-server-port
297 (gnus-buffer-exists-p buffer)))
298 (mm-disable-multibyte)
299 (buffer-disable-undo)
301 (set (make-local-variable 'after-change-functions) nil)
302 (set (make-local-variable 'nnimap-object)
303 (make-nnimap :server (nnoo-current-server 'nnimap)
305 (push (list buffer (current-buffer)) nnimap-connection-alist)
306 (push (current-buffer) nnimap-process-buffers)
309 (defun nnimap-credentials (address ports user)
310 (let* ((auth-source-creation-prompts
311 '((user . "IMAP user at %h: ")
312 (secret . "IMAP password for %u@%h: ")))
313 (found (nth 0 (auth-source-search :max 1
317 :require '(:user :secret)
320 (list (plist-get found :user)
321 (let ((secret (plist-get found :secret)))
322 (if (functionp secret)
325 (plist-get found :save-function))
328 (defun nnimap-keepalive ()
329 (let ((now (current-time)))
330 (dolist (buffer nnimap-process-buffers)
331 (when (buffer-name buffer)
332 (with-current-buffer buffer
333 (when (and nnimap-object
334 (nnimap-last-command-time nnimap-object)
338 (nnimap-last-command-time nnimap-object)))
339 ;; More than five minutes since the last command.
341 (nnimap-send-command "NOOP")))))))
343 (defun nnimap-open-connection (buffer)
344 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
345 ;; `ssl' when nnimap-server-port was nil. Sort of.
346 (when (and nnimap-server-port
347 (eq nnimap-stream 'undecided))
348 (setq nnimap-stream 'ssl))
350 (if (eq nnimap-stream 'undecided)
351 (loop for type in '(ssl network)
352 for stream = (let ((nnimap-stream type))
353 (nnimap-open-connection-1 buffer))
354 while (eq stream 'no-connect)
355 finally (return stream))
356 (nnimap-open-connection-1 buffer))))
357 (if (eq stream 'no-connect)
361 (defun nnimap-map-port (port)
362 (if (equal port "imaps")
366 (defun nnimap-open-connection-1 (buffer)
367 (unless nnimap-keepalive-timer
368 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
370 (with-current-buffer (nnimap-make-process-buffer buffer)
371 (let* ((coding-system-for-read 'binary)
372 (coding-system-for-write 'binary)
375 ((memq nnimap-stream '(network plain starttls))
376 (nnheader-message 7 "Opening connection to %s..."
379 ((eq nnimap-stream 'shell)
380 (nnheader-message 7 "Opening connection to %s via shell..."
383 ((memq nnimap-stream '(ssl tls))
384 (nnheader-message 7 "Opening connection to %s via tls..."
386 '("imaps" "imap" "993" "143"))
388 (error "Unknown stream type: %s" nnimap-stream))))
389 login-result credentials)
390 (when nnimap-server-port
391 (push nnimap-server-port ports))
393 (open-protocol-stream
394 "*nnimap*" (current-buffer) nnimap-address
395 (nnimap-map-port (car ports))
398 :shell-command nnimap-shell-program
399 :capability-command "1 CAPABILITY\r\n"
400 :end-of-command "\r\n"
403 (lambda (capabilities)
404 (when (gnus-string-match-p "STARTTLS" capabilities)
406 (stream (car stream-list))
407 (props (cdr stream-list))
408 (greeting (plist-get props :greeting))
409 (capabilities (plist-get props :capabilities))
410 (stream-type (plist-get props :type)))
411 (when (and stream (not (memq (process-status stream) '(open run))))
414 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
415 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
416 (eq (process-type stream) 'network))
417 ;; Use TCP-keepalive so that connections that pass through a NAT
418 ;; router don't hang when left idle.
419 (set-network-process-option stream :keepalive t))
421 (setf (nnimap-process nnimap-object) stream)
422 (setf (nnimap-stream-type nnimap-object) stream-type)
425 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
426 nnimap-address (car ports) nnimap-stream)
428 (gnus-set-process-query-on-exit-flag stream nil)
429 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
430 (nnheader-report 'nnimap "%s" greeting)
431 ;; Store the greeting (for debugging purposes).
432 (setf (nnimap-greeting nnimap-object) greeting)
433 (setf (nnimap-capabilities nnimap-object)
435 (split-string capabilities)))
436 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
437 (if (not (setq credentials
438 (if (eq nnimap-authenticator 'anonymous)
440 (message-make-address))
441 ;; Look for the credentials based on
442 ;; the virtual server name and the address
444 (gnus-delete-duplicates
447 (nnoo-current-server 'nnimap)))
450 (setq nnimap-object nil)
451 (let ((nnimap-inhibit-logging t))
453 (nnimap-login (car credentials) (cadr credentials))))
454 (if (car login-result)
456 ;; Save the credentials if a save function exists
457 ;; (such a function will only be passed if a new
458 ;; token was created).
459 (when (functionp (nth 2 credentials))
460 (funcall (nth 2 credentials)))
461 ;; See if CAPABILITY is set as part of login
463 (dolist (response (cddr login-result))
464 (when (string= "CAPABILITY" (upcase (car response)))
465 (setf (nnimap-capabilities nnimap-object)
466 (mapcar #'upcase (cdr response))))))
467 ;; If the login failed, then forget the credentials
468 ;; that are now possibly cached.
469 (dolist (host (list (nnoo-current-server 'nnimap)
472 (auth-source-forget+ :host host :port port)))
473 (delete-process (nnimap-process nnimap-object))
474 (setq nnimap-object nil))))
476 (when (nnimap-capability "QRESYNC")
477 (nnimap-command "ENABLE QRESYNC"))
478 (nnimap-process nnimap-object))))))))
480 (autoload 'rfc2104-hash "rfc2104")
482 (defun nnimap-login (user password)
484 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
485 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
486 ;; and we're using an encrypted connection.
487 ((and (not (nnimap-capability "LOGINDISABLED"))
488 (eq (nnimap-stream-type nnimap-object) 'tls))
489 (nnimap-command "LOGIN %S %S" user password))
490 ((nnimap-capability "AUTH=CRAM-MD5")
492 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
493 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
495 (get-buffer-process (current-buffer))
497 (base64-encode-string
499 (rfc2104-hash 'md5 64 16 password
500 (base64-decode-string challenge))))
502 (nnimap-wait-for-response sequence)))
503 ((not (nnimap-capability "LOGINDISABLED"))
504 (nnimap-command "LOGIN %S %S" user password))
505 ((nnimap-capability "AUTH=PLAIN")
507 "AUTHENTICATE PLAIN %s"
508 (base64-encode-string
509 (format "\000%s\000%s"
510 (nnimap-quote-specials user)
511 (nnimap-quote-specials password)))))))
513 (defun nnimap-quote-specials (string)
516 (goto-char (point-min))
517 (while (re-search-forward "[\\\"]" nil t)
523 (defun nnimap-find-parameter (parameter elems)
527 ((equal (car elem) parameter)
528 (setq result (cdr elem)))
529 ((and (equal (car elem) "OK")
531 (equal (caadr elem) parameter))
532 (setq result (cdr (cadr elem))))))
535 (deffoo nnimap-close-server (&optional server)
536 (when (nnoo-change-server 'nnimap server nil)
538 (delete-process (get-buffer-process (nnimap-buffer))))
539 (nnoo-close-server 'nnimap server)
542 (deffoo nnimap-request-close ()
545 (deffoo nnimap-server-opened (&optional server)
546 (and (nnoo-current-server-p 'nnimap server)
548 (gnus-buffer-live-p nntp-server-buffer)
549 (nnimap-find-connection nntp-server-buffer)))
551 (deffoo nnimap-status-message (&optional server)
552 nnimap-status-string)
554 (deffoo nnimap-request-article (article &optional group server to-buffer)
556 (setq group (nnimap-decode-gnus-group group)))
557 (with-current-buffer nntp-server-buffer
558 (let ((result (nnimap-possibly-change-group group server))
560 (when (stringp article)
561 (setq article (nnimap-find-article-by-message-id group article)))
565 (with-current-buffer (nnimap-buffer)
567 (when nnimap-fetch-partial-articles
568 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
569 (goto-char (point-min))
570 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
571 (setq structure (ignore-errors
572 (let ((start (point)))
574 (downcase-region start (point))
576 (read (current-buffer))))
577 parts (nnimap-find-wanted-parts structure))))
579 (nnimap-get-partial-article article parts structure)
580 (nnimap-get-whole-article article))
581 (let ((buffer (current-buffer)))
582 (with-current-buffer (or to-buffer nntp-server-buffer)
583 (nnheader-insert-buffer-substring buffer)
584 (nnheader-ms-strip-cr)))
585 (cons group article)))))))
587 (deffoo nnimap-request-head (article &optional group server to-buffer)
589 (setq group (nnimap-decode-gnus-group group)))
590 (when (nnimap-possibly-change-group group server)
591 (with-current-buffer (nnimap-buffer)
592 (when (stringp article)
593 (setq article (nnimap-find-article-by-message-id group article)))
596 (nnimap-get-whole-article
597 article (format "UID FETCH %%d %s"
598 (nnimap-header-parameters)))
599 (let ((buffer (current-buffer)))
600 (with-current-buffer (or to-buffer nntp-server-buffer)
602 (insert-buffer-substring buffer)
603 (nnheader-ms-strip-cr)
604 (cons group article)))))))
606 (defun nnimap-get-whole-article (article &optional command)
611 "UID FETCH %d BODY.PEEK[]"
612 "UID FETCH %d RFC822.PEEK"))
614 ;; Check that we really got an article.
615 (goto-char (point-min))
616 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
619 ;; Remove any data that may have arrived before the FETCH data.
622 (delete-region (point-min) (point)))
623 (let ((bytes (nnimap-get-length)))
624 (delete-region (line-beginning-position)
625 (progn (forward-line 1) (point)))
626 (goto-char (+ (point) bytes))
627 (delete-region (point) (point-max)))
630 (defun nnimap-capability (capability)
631 (member capability (nnimap-capabilities nnimap-object)))
633 (defun nnimap-ver4-p ()
634 (nnimap-capability "IMAP4REV1"))
636 (defun nnimap-get-partial-article (article parts structure)
639 "UID FETCH %d (%s %s)"
645 (mapconcat (lambda (part)
646 (format "BODY.PEEK[%s]" part))
648 (mapconcat (lambda (part)
649 (format "RFC822.PEEK[%s]" part))
652 (nnimap-convert-partial-article structure))))
654 (defun nnimap-convert-partial-article (structure)
655 ;; First just skip past the headers.
656 (goto-char (point-min))
657 (let ((bytes (nnimap-get-length))
659 ;; Delete "FETCH" line.
660 (delete-region (line-beginning-position)
661 (progn (forward-line 1) (point)))
662 (goto-char (+ (point) bytes))
663 ;; Collect all the body parts.
664 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
665 (setq id (match-string 1)
666 bytes (or (nnimap-get-length) 0))
668 (delete-region (point) (progn (forward-line 1) (point)))
669 (push (list id (buffer-substring (point) (+ (point) bytes)))
671 (delete-region (point) (+ (point) bytes)))
672 ;; Delete trailing junk.
673 (delete-region (point) (point-max))
674 ;; Now insert all the parts again where they fit in the structure.
675 (nnimap-insert-partial-structure structure parts)
678 (defun nnimap-insert-partial-structure (structure parts &optional subp)
680 (let ((bstruc structure))
681 (while (consp (car bstruc))
683 (setq type (car bstruc))
684 (setq bstruc (car (cdr bstruc)))
685 (let ((has-boundary (member "boundary" bstruc)))
687 (setq boundary (cadr has-boundary)))))
689 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
690 (downcase type) boundary)))
691 (while (not (stringp (car structure)))
692 (insert "\n--" boundary "\n")
693 (if (consp (caar structure))
694 (nnimap-insert-partial-structure (pop structure) parts t)
695 (let ((bit (pop structure)))
696 (insert (format "Content-type: %s/%s"
697 (downcase (nth 0 bit))
698 (downcase (nth 1 bit))))
699 (if (member-ignore-case "CHARSET" (nth 2 bit))
702 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
704 (insert (format "Content-transfer-encoding: %s\n"
707 (when (assoc (nth 9 bit) parts)
708 (insert (cadr (assoc (nth 9 bit) parts)))))))
709 (insert "\n--" boundary "--\n")))
711 (defun nnimap-find-wanted-parts (structure)
712 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
714 (defun nnimap-find-wanted-parts-1 (structure prefix)
717 (while (consp (car structure))
718 (let ((sub (pop structure)))
719 (if (consp (car sub))
720 (push (nnimap-find-wanted-parts-1
721 sub (if (string= prefix "")
722 (number-to-string num)
723 (format "%s.%s" prefix num)))
725 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
726 (id (if (string= prefix "")
727 (number-to-string num)
728 (format "%s.%s" prefix num))))
729 (setcar (nthcdr 9 sub) id)
730 (when (if (eq nnimap-fetch-partial-articles t)
732 (string-match nnimap-fetch-partial-articles type))
737 (defun nnimap-decode-gnus-group (group)
738 (decode-coding-string group 'utf-8))
740 (deffoo nnimap-request-group (group &optional server dont-check info)
741 (setq group (nnimap-decode-gnus-group group))
742 (let ((result (nnimap-possibly-change-group
743 ;; Don't SELECT the group if we're going to select it
745 (if (and (not dont-check)
746 (assoc group nnimap-current-infos))
750 articles active marks high low)
751 (with-current-buffer nntp-server-buffer
754 (setq active (nth 2 (assoc group nnimap-current-infos))))
755 (insert (format "211 %d %d %d %S\n"
756 (- (cdr active) (car active))
760 (with-current-buffer (nnimap-buffer)
762 (let ((group-sequence
763 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
765 (nnimap-send-command "UID FETCH 1:* FLAGS")))
766 (setf (nnimap-group nnimap-object) group)
767 (nnimap-wait-for-response flag-sequence)
769 (nnimap-flags-to-marks
771 (list (list group-sequence flag-sequence
772 1 group "SELECT")))))
775 (nnimap-update-infos marks (list info))
776 (nnimap-store-info info (gnus-active (gnus-info-group info))))
777 (goto-char (point-max))
778 (let ((uidnext (nth 5 (car marks))))
779 (setq high (or (if uidnext
783 low (or (nth 4 (car marks)) uidnext 1)))))
787 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
790 (deffoo nnimap-request-create-group (group &optional server args)
791 (setq group (nnimap-decode-gnus-group group))
792 (when (nnimap-possibly-change-group nil server)
793 (with-current-buffer (nnimap-buffer)
794 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
796 (deffoo nnimap-request-delete-group (group &optional force server)
797 (setq group (nnimap-decode-gnus-group group))
798 (when (nnimap-possibly-change-group nil server)
799 (with-current-buffer (nnimap-buffer)
800 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
802 (deffoo nnimap-request-rename-group (group new-name &optional server)
803 (setq group (nnimap-decode-gnus-group group))
804 (when (nnimap-possibly-change-group nil server)
805 (with-current-buffer (nnimap-buffer)
806 (nnimap-unselect-group)
807 (car (nnimap-command "RENAME %S %S"
808 (utf7-encode group t) (utf7-encode new-name t))))))
810 (defun nnimap-unselect-group ()
811 ;; Make sure we don't have this group open read/write by asking
812 ;; to examine a mailbox that doesn't exist. This seems to be
813 ;; the only way that allows us to reliably go back to unselected
815 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
817 (deffoo nnimap-request-expunge-group (group &optional server)
818 (setq group (nnimap-decode-gnus-group group))
819 (when (nnimap-possibly-change-group group server)
820 (with-current-buffer (nnimap-buffer)
821 (car (nnimap-command "EXPUNGE")))))
823 (defun nnimap-get-flags (spec)
826 (with-current-buffer (nnimap-buffer)
828 (nnimap-wait-for-response (nnimap-send-command
829 "UID FETCH %s FLAGS" spec))
831 (subst-char-in-region (point-min) (point-max)
833 (goto-char (point-min))
834 (while (search-forward " FETCH " end t)
835 (setq elems (read (current-buffer)))
836 (push (cons (cadr (memq 'UID elems))
837 (cadr (memq 'FLAGS elems)))
839 (nreverse articles)))
841 (deffoo nnimap-close-group (group &optional server)
844 (deffoo nnimap-request-move-article (article group server accept-form
845 &optional last internal-move-group)
846 (setq group (nnimap-decode-gnus-group group))
848 (mm-disable-multibyte)
849 (when (funcall (if internal-move-group
851 'nnimap-request-article)
852 article group server (current-buffer))
853 ;; If the move is internal (on the same server), just do it the easy
855 (let ((message-id (message-field-value "message-id")))
856 (if internal-move-group
858 (with-current-buffer (nnimap-buffer)
859 (nnimap-command "UID COPY %d %S"
861 (utf7-encode internal-move-group t)))))
863 (nnimap-delete-article article)
864 (cons internal-move-group
865 (or (nnimap-find-uid-response "COPYUID" (cadr result))
866 (nnimap-find-article-by-message-id
867 internal-move-group message-id)))))
868 ;; Move the article to a different method.
869 (let ((result (eval accept-form)))
871 (nnimap-delete-article article)
874 (deffoo nnimap-request-expire-articles (articles group &optional server force)
875 (setq group (nnimap-decode-gnus-group group))
879 ((not (nnimap-possibly-change-group group server))
882 (eq nnmail-expiry-target 'delete))
883 (unless (nnimap-delete-article (gnus-compress-sequence articles))
884 (nnheader-message 7 "Article marked for deletion, but not expunged."))
887 (let ((deletable-articles
889 (eq nnmail-expiry-wait 'immediate))
891 (gnus-sorted-intersection
893 (nnimap-find-expired-articles group)))))
894 (if (null deletable-articles)
896 (if (eq nnmail-expiry-target 'delete)
897 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
898 (setq deletable-articles
899 (nnimap-process-expiry-targets
900 deletable-articles group server)))
901 ;; Return the articles we didn't delete.
902 (gnus-sorted-complement articles deletable-articles))))))
904 (defun nnimap-process-expiry-targets (articles group server)
905 (let ((deleted-articles nil))
907 ;; shortcut further processing if we're going to delete the articles
908 ((eq nnmail-expiry-target 'delete)
909 (setq deleted-articles articles)
911 ;; or just move them to another folder on the same IMAP server
912 ((and (not (functionp nnmail-expiry-target))
913 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
914 (gnus-server-to-method
915 (format "nnimap:%s" server))))
916 (and (nnimap-possibly-change-group group server)
917 (with-current-buffer (nnimap-buffer)
918 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
921 (nnimap-article-ranges (gnus-compress-sequence articles))
922 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
923 (setq deleted-articles articles)))
926 (dolist (article articles)
927 (let ((target nnmail-expiry-target))
929 (mm-disable-multibyte)
930 (when (nnimap-request-article article group server (current-buffer))
931 (when (functionp target)
932 (setq target (funcall target group)))
934 (not (eq target 'delete)))
935 (if (or (gnus-request-group target t)
936 (gnus-request-create-group target))
938 (nnmail-expiry-target-group target group)
939 (nnheader-message 7 "Expiring article %s:%d to %s"
940 group article target))
942 (nnheader-message 7 "Expiring article %s:%d" group article))
944 (push article deleted-articles))))))))
945 ;; Change back to the current group again.
946 (nnimap-possibly-change-group group server)
947 (setq deleted-articles (nreverse deleted-articles))
948 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
951 (defun nnimap-find-expired-articles (group)
952 (let ((cutoff (nnmail-expired-article-p group nil nil)))
953 (with-current-buffer (nnimap-buffer)
956 "UID SEARCH SENTBEFORE %s"
960 (car (rassoc (nth 4 (decode-time cutoff))
961 parse-time-months))))
964 (delete 0 (mapcar #'string-to-number
965 (cdr (assoc "SEARCH" (cdr result))))))))))
968 (defun nnimap-find-article-by-message-id (group message-id)
969 (with-current-buffer (nnimap-buffer)
971 (unless (equal group (nnimap-group nnimap-object))
972 (setf (nnimap-group nnimap-object) nil)
973 (setf (nnimap-examined nnimap-object) group)
974 (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
976 (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
978 (setq result (nnimap-wait-for-response sequence))
980 (car (setq result (nnimap-parse-response))))
981 ;; Select the last instance of the message in the group.
983 (car (last (cdr (assoc "SEARCH" (cdr result))))))
984 (string-to-number article))))))
986 (defun nnimap-delete-article (articles)
987 (with-current-buffer (nnimap-buffer)
988 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
989 (nnimap-article-ranges articles))
991 ((nnimap-capability "UIDPLUS")
992 (nnimap-command "UID EXPUNGE %s"
993 (nnimap-article-ranges articles))
996 (nnimap-command "EXPUNGE")
998 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
999 "server doesn't support UIDPLUS, so we won't "
1000 "delete this article now"))))))
1002 (deffoo nnimap-request-scan (&optional group server)
1004 (setq group (nnimap-decode-gnus-group group)))
1005 (when (and (nnimap-possibly-change-group nil server)
1007 nnimap-split-methods)
1008 (nnheader-message 7 "nnimap %s splitting mail..." server)
1009 (nnimap-split-incoming-mail)
1010 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1012 (defun nnimap-marks-to-flags (marks)
1014 (dolist (mark marks)
1015 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1019 (deffoo nnimap-request-update-group-status (group status &optional server)
1020 (setq group (nnimap-decode-gnus-group group))
1021 (when (nnimap-possibly-change-group nil server)
1022 (let ((command (assoc
1024 '((subscribe "SUBSCRIBE")
1025 (unsubscribe "UNSUBSCRIBE")))))
1027 (with-current-buffer (nnimap-buffer)
1028 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1030 (deffoo nnimap-request-set-mark (group actions &optional server)
1031 (setq group (nnimap-decode-gnus-group group))
1032 (when (nnimap-possibly-change-group group server)
1034 (with-current-buffer (nnimap-buffer)
1036 ;; Just send all the STORE commands without waiting for
1037 ;; response. If they're successful, they're successful.
1038 (dolist (action actions)
1039 (destructuring-bind (range action marks) action
1040 (let ((flags (nnimap-marks-to-flags marks)))
1042 (setq sequence (nnimap-send-command
1043 "UID STORE %s %sFLAGS.SILENT (%s)"
1044 (nnimap-article-ranges range)
1046 ((eq action 'del) "-")
1047 ((eq action 'add) "+")
1048 ((eq action 'set) ""))
1049 (mapconcat #'identity flags " ")))))))
1050 ;; Wait for the last command to complete to avoid later
1051 ;; synchronization problems with the stream.
1053 (nnimap-wait-for-response sequence))))))
1055 (deffoo nnimap-request-accept-article (group &optional server last)
1056 (setq group (nnimap-decode-gnus-group group))
1057 (when (nnimap-possibly-change-group nil server)
1058 (nnmail-check-syntax)
1059 (let ((message-id (message-field-value "message-id"))
1062 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1063 (with-current-buffer (nnimap-buffer)
1064 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1066 ;; If we have this group open read-only, then unselect it
1067 ;; before appending to it.
1068 (when (equal (nnimap-examined nnimap-object) group)
1069 (nnimap-unselect-group))
1071 (setq sequence (nnimap-send-command
1072 "APPEND %S {%d}" (utf7-encode group t)
1074 (unless nnimap-streaming
1075 (nnimap-wait-for-connection "^[+]"))
1076 (process-send-string (get-buffer-process (current-buffer)) message)
1077 (process-send-string (get-buffer-process (current-buffer))
1078 (if (nnimap-newlinep nnimap-object)
1081 (let ((result (nnimap-get-response sequence)))
1082 (if (not (nnimap-ok-p result))
1084 (nnheader-report 'nnimap "%s" result)
1087 (or (nnimap-find-uid-response "APPENDUID" (car result))
1088 (nnimap-find-article-by-message-id
1089 group message-id))))))))))
1091 (defun nnimap-process-quirk (greeting-match type data)
1092 (when (and (nnimap-greeting nnimap-object)
1093 (string-match greeting-match (nnimap-greeting nnimap-object))
1095 (string-match "\000" data))
1096 (let ((choice (gnus-multiple-choice
1097 "Message contains NUL characters. Delete, continue, abort? "
1098 '((?d "Delete NUL characters")
1099 (?c "Try to APPEND the message as is")
1103 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1109 (goto-char (point-min))
1110 (while (search-forward "\000" nil t)
1111 (replace-match "" t t))
1112 (buffer-string)))))))
1114 (defun nnimap-ok-p (value)
1117 (equal (caar value) "OK")))
1119 (defun nnimap-find-uid-response (name list)
1120 (let ((result (car (last (nnimap-find-response-element name list)))))
1122 (string-to-number result))))
1124 (defun nnimap-find-response-element (name list)
1127 (when (and (consp elem)
1128 (equal name (car elem)))
1129 (setq result elem)))
1132 (deffoo nnimap-request-replace-article (article group buffer)
1133 (setq group (nnimap-decode-gnus-group group))
1135 (when (and (nnimap-possibly-change-group group nil)
1136 ;; Put the article into the group.
1137 (with-current-buffer buffer
1139 (nnimap-request-accept-article group nil t))))
1140 (nnimap-delete-article (list article))
1141 ;; Return the new article number.
1144 (defun nnimap-add-cr ()
1145 (goto-char (point-min))
1146 (while (re-search-forward "\r?\n" nil t)
1147 (replace-match "\r\n" t t)))
1149 (defun nnimap-get-groups ()
1151 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1153 (nnimap-wait-for-response sequence)
1154 (subst-char-in-region (point-min) (point-max)
1156 (goto-char (point-min))
1157 (nnimap-unfold-quoted-lines)
1158 (goto-char (point-min))
1159 (while (search-forward "* LIST " nil t)
1160 (let ((flags (read (current-buffer)))
1161 (separator (read (current-buffer)))
1162 (group (read (current-buffer))))
1163 (unless (member '%NoSelect flags)
1164 (push (utf7-decode (if (stringp group)
1166 (format "%s" group)) t)
1170 (deffoo nnimap-request-list (&optional server)
1171 (when (nnimap-possibly-change-group nil server)
1172 (with-current-buffer nntp-server-buffer
1175 (with-current-buffer (nnimap-buffer)
1176 (nnimap-get-groups)))
1177 sequences responses)
1179 (with-current-buffer (nnimap-buffer)
1180 (setf (nnimap-group nnimap-object) nil)
1181 (dolist (group groups)
1182 (setf (nnimap-examined nnimap-object) group)
1183 (push (list (nnimap-send-command "EXAMINE %S"
1184 (utf7-encode group t))
1187 (nnimap-wait-for-response (caar sequences))
1189 (nnimap-get-responses (mapcar #'car sequences))))
1190 (dolist (response responses)
1191 (let* ((sequence (car response))
1192 (response (cadr response))
1193 (group (cadr (assoc sequence sequences))))
1195 (equal (caar response) "OK"))
1196 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1198 (dolist (elem response)
1199 (when (equal (cadr elem) "EXISTS")
1200 (setq exists (string-to-number (car elem)))))
1202 (setq highest (1- (string-to-number (car uidnext)))))
1205 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1208 (insert (format "%S %d %d y\n"
1209 (utf7-decode group t)
1210 highest (1+ highest))))
1212 ;; Return the widest possible range.
1213 (insert (format "%S %d 1 y\n" (utf7-decode group t)
1214 (or highest exists)))))))))
1217 (deffoo nnimap-request-newgroups (date &optional server)
1218 (when (nnimap-possibly-change-group nil server)
1219 (with-current-buffer nntp-server-buffer
1221 (dolist (group (with-current-buffer (nnimap-buffer)
1222 (nnimap-get-groups)))
1223 (unless (assoc group nnimap-current-infos)
1224 ;; Insert dummy numbers here -- they don't matter.
1225 (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1228 (deffoo nnimap-retrieve-group-data-early (server infos)
1229 (when (and (nnimap-possibly-change-group nil server)
1231 (with-current-buffer (nnimap-buffer)
1233 (setf (nnimap-group nnimap-object) nil)
1234 (setf (nnimap-initial-resync nnimap-object) 0)
1235 (let ((qresyncp (nnimap-capability "QRESYNC"))
1236 params groups sequences active uidvalidity modseq group
1238 ;; Go through the infos and gather the data needed to know
1239 ;; what and how to request the data.
1240 (dolist (info infos)
1241 (setq params (gnus-info-params info)
1242 group (nnimap-decode-gnus-group
1243 (gnus-group-real-name (gnus-info-group info)))
1244 active (cdr (assq 'active params))
1245 unexist (assq 'unexist (gnus-info-marks info))
1246 uidvalidity (cdr (assq 'uidvalidity params))
1247 modseq (cdr (assq 'modseq params)))
1248 (setf (nnimap-examined nnimap-object) group)
1255 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1256 (utf7-encode group t)
1257 (nnimap-quirk "QRESYNC")
1265 ;; If we don't have a UIDVALIDITY, then this is
1266 ;; the first time we've seen the group, so we
1267 ;; have to do a SELECT (which is slower than an
1268 ;; examine), but will tell us whether the group
1269 ;; is read-only or not.
1272 (if (and active uidvalidity unexist)
1273 ;; Fetch the last 100 flags.
1274 (setq start (max 1 (- (cdr active) 100)))
1275 (incf (nnimap-initial-resync nnimap-object))
1277 (push (list (nnimap-send-command "%s %S" command
1278 (utf7-encode group t))
1279 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1280 start group command)
1284 (defun nnimap-quirk (command)
1285 (let ((quirk (assoc command nnimap-quirks)))
1286 ;; If this server is of a type that matches a quirk, then return
1287 ;; the "quirked" command instead of the proper one.
1288 (if (or (null quirk)
1289 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1293 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1294 (when (and sequences
1295 (nnimap-possibly-change-group nil server t)
1296 ;; Check that the process is still alive.
1297 (get-buffer-process (nnimap-buffer))
1298 (memq (process-status (get-buffer-process (nnimap-buffer)))
1300 (with-current-buffer (nnimap-buffer)
1301 ;; Wait for the final data to trickle in.
1302 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1306 ;; Now we should have most of the data we need, no matter
1307 ;; whether we're QRESYNCING, fetching all the flags from
1308 ;; scratch, or just fetching the last 100 flags per group.
1309 (nnimap-update-infos (nnimap-flags-to-marks
1311 (nreverse sequences)))
1313 ;; Finally, just return something resembling an active file in
1314 ;; the nntp buffer, so that the agent can save the info, too.
1315 (with-current-buffer nntp-server-buffer
1317 (dolist (info infos)
1318 (let* ((group (gnus-info-group info))
1319 (active (gnus-active group)))
1321 (insert (format "%S %d %d y\n"
1322 (decode-coding-string
1323 (gnus-group-real-name group) 'utf-8)
1325 (car active)))))))))))
1327 (defun nnimap-update-infos (flags infos)
1328 (dolist (info infos)
1329 (let* ((group (nnimap-decode-gnus-group
1330 (gnus-group-real-name (gnus-info-group info))))
1331 (marks (cdr (assoc group flags))))
1333 (nnimap-update-info info marks)))))
1335 (defun nnimap-update-info (info marks)
1336 (destructuring-bind (existing flags high low uidnext start-article
1337 permanent-flags uidvalidity
1338 vanished highestmodseq) marks
1340 ;; Ignore groups with no UIDNEXT/marks. This happens for
1341 ;; completely empty groups.
1342 ((and (not existing)
1344 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1346 (gnus-set-active (gnus-info-group info) active))))
1347 ;; We have a mismatch between the old and new UIDVALIDITY
1348 ;; identifiers, so we have to re-request the group info (the next
1349 ;; time). This virtually never happens.
1350 ((let ((old-uidvalidity
1351 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1352 (and old-uidvalidity
1353 (not (equal old-uidvalidity uidvalidity))
1354 (or (not start-article)
1355 (> start-article 1))))
1356 (gnus-group-remove-parameter info 'uidvalidity)
1357 (gnus-group-remove-parameter info 'modseq))
1358 ;; We have the data needed to update.
1360 (let* ((group (gnus-info-group info))
1361 (completep (and start-article
1362 (= start-article 1)))
1363 (active (or (gnus-active group)
1364 (cdr (assq 'active (gnus-info-params info))))))
1366 (setq high (1- uidnext)))
1367 ;; First set the active ranges based on high/low.
1369 (not (gnus-active group)))
1370 (gnus-set-active group
1373 (cons (min (or low (car active))
1375 (max (or high (cdr active))
1380 ;; No articles in this group.
1381 (cons uidnext (1- uidnext)))
1383 (cons start-article (1- start-article)))
1385 ;; No articles and no uidnext.
1387 (gnus-set-active group
1389 (or high (1- uidnext)))))
1390 ;; See whether this is a read-only group.
1391 (unless (eq permanent-flags 'not-scanned)
1392 (gnus-group-set-parameter
1393 info 'permanent-flags
1394 (and (or (memq '%* permanent-flags)
1395 (memq '%Seen permanent-flags))
1397 ;; Update marks and read articles if this isn't a
1398 ;; read-only IMAP group.
1399 (when (setq permanent-flags
1400 (cdr (assq 'permanent-flags (gnus-info-params info))))
1401 (if (and highestmodseq
1402 (not start-article))
1403 ;; We've gotten the data by QRESYNCing.
1404 (nnimap-update-qresync-info
1405 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1406 ;; Do normal non-QRESYNC flag updates.
1407 ;; Update the list of read articles.
1409 (gnus-compress-sequence
1410 (gnus-set-difference
1411 (gnus-set-difference
1413 (cdr (assoc '%Seen flags)))
1414 (cdr (assoc '%Flagged flags)))))
1415 (read (gnus-range-difference
1416 (cons start-article high) unread)))
1417 (when (> start-article 1)
1420 (if (> start-article 1)
1421 (gnus-sorted-range-intersection
1422 (cons 1 (1- start-article))
1423 (gnus-info-read info))
1424 (gnus-info-read info))
1426 (when (or (not (listp permanent-flags))
1427 (memq '%Seen permanent-flags))
1428 (gnus-info-set-read info read))
1429 ;; Update the marks.
1430 (setq marks (gnus-info-marks info))
1431 (dolist (type (cdr nnimap-mark-alist))
1432 (when (or (not (listp permanent-flags))
1433 (memq (car (assoc (caddr type) flags))
1435 (memq '%* permanent-flags))
1436 (let ((old-marks (assoc (car type) marks))
1438 (gnus-compress-sequence
1439 (cdr (or (assoc (caddr type) flags) ; %Flagged
1440 (assoc (intern (cadr type) obarray) flags)
1441 (assoc (cadr type) flags)))))) ; "\Flagged"
1442 (setq marks (delq old-marks marks))
1444 (when (and old-marks
1445 (> start-article 1))
1446 (setq old-marks (gnus-range-difference
1448 (cons start-article high)))
1449 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1451 (push (cons (car type) new-marks) marks)))))
1452 ;; Keep track of non-existing articles.
1453 (let* ((old-unexists (assq 'unexist marks))
1456 (gnus-range-difference
1458 (gnus-compress-sequence existing))
1461 (gnus-list-range-difference
1462 existing (gnus-active group))))))
1464 (setcdr old-unexists unexists)
1465 (push (cons 'unexist unexists) marks)))
1466 (gnus-info-set-marks info marks t))))
1467 ;; Tell Gnus whether there are any \Recent messages in any of
1469 (let ((recent (cdr (assoc '%Recent flags))))
1472 (> (car (last recent)) (cdr active)))
1473 (push (list (cons (gnus-group-real-name group) 0))
1474 nnmail-split-history)))
1475 ;; Note the active level for the next run-through.
1476 (gnus-group-set-parameter info 'active (gnus-active group))
1477 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1478 (gnus-group-set-parameter info 'modseq highestmodseq)
1479 (nnimap-store-info info (gnus-active group)))))))
1481 (defun nnimap-update-qresync-info (info existing vanished flags)
1482 ;; Add all the vanished articles to the list of read articles.
1487 (gnus-range-add (gnus-info-read info)
1489 (cdr (assq '%Flagged flags)))
1490 (cdr (assq '%Seen flags))))
1491 (let ((marks (gnus-info-marks info)))
1492 (dolist (type (cdr nnimap-mark-alist))
1493 (let ((ticks (assoc (car type) marks))
1495 (cdr (or (assoc (caddr type) flags) ; %Flagged
1496 (assoc (intern (cadr type) obarray) flags)
1497 (assoc (cadr type) flags))))) ; "\Flagged"
1498 (setq marks (delq ticks marks))
1500 ;; Add the new marks we got.
1501 (setq ticks (gnus-add-to-range ticks new-marks))
1502 ;; Remove the marks from messages that don't have them.
1503 (setq ticks (gnus-remove-from-range
1505 (gnus-compress-sequence
1506 (gnus-sorted-complement existing new-marks))))
1508 (push (cons (car type) ticks) marks)))
1509 (gnus-info-set-marks info marks t))
1510 ;; Add vanished to the list of unexisting articles.
1512 (let* ((old-unexists (assq 'unexist marks))
1513 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1515 (setcdr old-unexists unexists)
1516 (push (cons 'unexist unexists) marks)))
1517 (gnus-info-set-marks info marks t))))
1519 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1520 (if (zerop (length irange))
1523 (dolist (elem (split-string irange ","))
1525 (if (string-match ":" elem)
1526 (let ((numbers (split-string elem ":")))
1527 (cons (string-to-number (car numbers))
1528 (string-to-number (cadr numbers))))
1529 (string-to-number elem))
1531 (nreverse result))))
1533 (defun nnimap-store-info (info active)
1534 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1535 (entry (assoc group nnimap-current-infos)))
1537 (setcdr entry (list info active))
1538 (push (list group info active) nnimap-current-infos))))
1540 (defun nnimap-flags-to-marks (groups)
1541 (let (data group totalp uidnext articles start-article mark permanent-flags
1542 uidvalidity vanished highestmodseq)
1543 (dolist (elem groups)
1544 (setq group (car elem)
1545 uidnext (nth 1 elem)
1546 start-article (nth 2 elem)
1547 permanent-flags (nth 3 elem)
1548 uidvalidity (nth 4 elem)
1549 vanished (nth 5 elem)
1550 highestmodseq (nth 6 elem)
1551 articles (nthcdr 7 elem))
1552 (let ((high (caar articles))
1554 (dolist (article articles)
1555 (setq low (car article))
1556 (push (car article) existing)
1557 (dolist (flag (cdr article))
1558 (setq mark (assoc flag marks))
1560 (push (list flag (car article)) marks)
1561 (setcdr mark (cons (car article) (cdr mark))))))
1562 (push (list group existing marks high low uidnext start-article
1563 permanent-flags uidvalidity vanished highestmodseq)
1567 (defun nnimap-parse-flags (sequences)
1568 (goto-char (point-min))
1569 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1571 (subst-char-in-region (point-min) (point-max)
1573 ;; Remove any MODSEQ entries in the buffer, because they may contain
1574 ;; numbers that are too large for 32-bit Emacsen.
1575 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1576 (replace-match "" t t))
1577 (goto-char (point-min))
1578 (let (start end articles groups uidnext elems permanent-flags
1579 uidvalidity vanished highestmodseq)
1580 (dolist (elem sequences)
1581 (destructuring-bind (group-sequence flag-sequence totalp group command)
1583 (setq start (point))
1585 ;; The EXAMINE was successful.
1586 (search-forward (format "\n%d OK " group-sequence) nil t)
1591 (setq permanent-flags
1592 (if (equal command "SELECT")
1593 (and (search-forward "PERMANENTFLAGS "
1594 (or end (point-min)) t)
1595 (read (current-buffer)))
1599 (and (search-forward "UIDNEXT "
1600 (or end (point-min)) t)
1601 (read (current-buffer))))
1604 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1605 (or end (point-min)) t)
1606 ;; Store UIDVALIDITY as a string, as it's
1607 ;; too big for 32-bit Emacsen, usually.
1611 (and (eq flag-sequence 'qresync)
1612 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1613 (or end (point-min)) t)
1617 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1618 (or end (point-min)) t)
1622 ;; The UID FETCH FLAGS was successful.
1623 (or (eq flag-sequence 'qresync)
1624 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1625 (if (eq flag-sequence 'qresync)
1629 (setq start (point))
1631 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1633 (setq elems (read (current-buffer)))
1634 (push (cons (cadr (memq 'UID elems))
1635 (cadr (memq 'FLAGS elems)))
1637 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1638 vanished highestmodseq)
1641 (if (eq flag-sequence 'qresync)
1644 (setq articles nil))))
1647 (defun nnimap-find-process-buffer (buffer)
1648 (cadr (assoc buffer nnimap-connection-alist)))
1650 (deffoo nnimap-request-post (&optional server)
1651 (setq nnimap-status-string "Read-only server")
1654 (declare-function gnus-fetch-headers "gnus-sum"
1655 (articles &optional limit force-new dependencies))
1657 (autoload 'nnir-search-thread "nnir")
1659 (deffoo nnimap-request-thread (header &optional group server)
1661 (setq group (nnimap-decode-gnus-group group)))
1662 (if gnus-refer-thread-use-nnir
1663 (nnir-search-thread header)
1664 (when (nnimap-possibly-change-group group server)
1665 (let* ((cmd (nnimap-make-thread-query header))
1666 (result (with-current-buffer (nnimap-buffer)
1667 (nnimap-command "UID SEARCH %s" cmd))))
1671 (delete 0 (mapcar #'string-to-number
1672 (cdr (assoc "SEARCH" (cdr result))))))
1675 (defun nnimap-possibly-change-group (group server &optional no-reconnect)
1676 (let ((open-result t))
1678 (not (nnimap-server-opened server)))
1679 (setq open-result (nnimap-open-server server nil no-reconnect)))
1686 (with-current-buffer (nnimap-buffer)
1687 (if (equal group (nnimap-group nnimap-object))
1689 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1691 (setf (nnimap-group nnimap-object) group
1692 (nnimap-select-result nnimap-object) result)
1695 (defun nnimap-find-connection (buffer)
1696 "Find the connection delivering to BUFFER."
1697 (let ((entry (assoc buffer nnimap-connection-alist)))
1699 (if (and (buffer-name (cadr entry))
1700 (get-buffer-process (cadr entry))
1701 (memq (process-status (get-buffer-process (cadr entry)))
1703 (get-buffer-process (cadr entry))
1704 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1707 (defvar nnimap-sequence 0)
1709 (defun nnimap-send-command (&rest args)
1710 (setf (nnimap-last-command-time nnimap-object) (current-time))
1711 (process-send-string
1712 (get-buffer-process (current-buffer))
1715 (incf nnimap-sequence)
1716 (apply #'format args)
1717 (if (nnimap-newlinep nnimap-object)
1720 ;; Some servers apparently can't have many outstanding
1721 ;; commands, so throttle them.
1722 (unless nnimap-streaming
1723 (nnimap-wait-for-response nnimap-sequence))
1726 (defvar nnimap-record-commands nil
1727 "If non-nil, log commands to the \"*imap log*\" buffer.")
1729 (defun nnimap-log-command (command)
1730 (when nnimap-record-commands
1731 (with-current-buffer (get-buffer-create "*imap log*")
1732 (goto-char (point-max))
1733 (insert (format-time-string "%H:%M:%S") " "
1734 (if nnimap-inhibit-logging
1739 (defun nnimap-command (&rest args)
1741 (let* ((sequence (apply #'nnimap-send-command args))
1742 (response (nnimap-get-response sequence)))
1743 (if (equal (caar response) "OK")
1745 (nnheader-report 'nnimap "%s"
1746 (mapconcat (lambda (a)
1748 (car response) " "))
1751 (defun nnimap-get-response (sequence)
1752 (nnimap-wait-for-response sequence)
1753 (nnimap-parse-response))
1755 (defun nnimap-wait-for-connection (&optional regexp)
1756 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1758 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1759 (let ((process (get-buffer-process (current-buffer))))
1760 (goto-char (point-min))
1761 (while (and (memq (process-status process)
1763 (not (re-search-forward regexp nil t)))
1764 (nnheader-accept-process-output process)
1765 (goto-char (point-min)))
1767 (and (looking-at (or response-regexp regexp))
1770 (defun nnimap-wait-for-response (sequence &optional messagep)
1771 (let ((process (get-buffer-process (current-buffer)))
1775 (goto-char (point-max))
1776 (while (and (setq openp (memq (process-status process)
1779 ;; Skip past any "*" lines that the server has
1781 (while (and (not (bobp))
1784 (looking-at "\\*"))))
1785 (not (looking-at (format "%d .*\n" sequence)))))
1787 (nnheader-message-maybe
1788 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1790 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1791 (format " (initial sync of %d group%s; please wait)"
1792 (nnimap-initial-resync nnimap-object)
1793 (if (= (nnimap-initial-resync nnimap-object) 1)
1797 (nnheader-accept-process-output process)
1798 (goto-char (point-max)))
1799 (setf (nnimap-initial-resync nnimap-object) 0)
1804 ;; The user hit C-g while we were waiting: kill the process, in case
1805 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1807 (delete-process process)
1810 (defun nnimap-parse-response ()
1811 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1813 (dolist (line lines)
1814 (push (cdr (nnimap-parse-line line)) result))
1815 ;; Return the OK/error code first, and then all the "continuation
1816 ;; lines" afterwards.
1818 (nreverse result))))
1820 ;; Parse an IMAP response line lightly. They look like
1821 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1822 ;; the lines into a list of strings and lists of string.
1823 (defun nnimap-parse-line (line)
1826 (mm-disable-multibyte)
1828 (goto-char (point-min))
1830 (if (eql (setq char (following-char)) ? )
1838 (if (search-forward "]" (line-end-position) 'move)
1845 (if (search-forward ")" (line-end-position) 'move)
1852 (1- (or (search-forward "\"" (line-end-position) 'move)
1855 (buffer-substring (point) (if (search-forward " " nil t)
1857 (goto-char (point-max))))))
1859 (nreverse result))))
1861 (defun nnimap-last-response-string ()
1864 (let ((end (point)))
1868 (while (and (not (bobp))
1869 (eql (following-char) ?*))
1871 (unless (eql (following-char) ?*)
1873 (buffer-substring (point) end))))
1875 (defun nnimap-get-responses (sequences)
1877 (dolist (sequence sequences)
1878 (goto-char (point-min))
1879 (when (re-search-forward (format "^%d " sequence) nil t)
1880 (push (list sequence (nnimap-parse-response))
1884 (defvar nnimap-incoming-split-list nil)
1886 (defun nnimap-fetch-inbox (articles)
1888 (nnimap-wait-for-response
1889 (nnimap-send-command
1891 (nnimap-article-ranges articles)
1892 (format "(UID %s%s)"
1898 (nnimap-split-download-body-default
1906 (defun nnimap-split-incoming-mail ()
1907 (with-current-buffer (nnimap-buffer)
1908 (let ((nnimap-incoming-split-list nil)
1909 (nnmail-split-methods
1911 ((eq nnimap-split-methods 'default)
1912 nnmail-split-methods)
1913 (nnimap-split-methods
1914 nnimap-split-methods)
1916 'nnmail-split-fancy)))
1917 (nnmail-split-fancy (or nnimap-split-fancy
1918 nnmail-split-fancy))
1919 (nnmail-inhibit-default-split-group t)
1920 (groups (nnimap-get-groups))
1923 (nnimap-command "SELECT %S" nnimap-inbox)
1924 (setf (nnimap-group nnimap-object) nnimap-inbox)
1925 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1927 (nnimap-fetch-inbox new-articles)
1928 (nnimap-transform-split-mail)
1929 (nnheader-ms-strip-cr)
1931 (nnmail-split-incoming (current-buffer)
1932 #'nnimap-save-mail-spec
1934 #'nnimap-dummy-active-number
1935 #'nnimap-save-mail-spec)
1936 (when nnimap-incoming-split-list
1937 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1938 sequences junk-articles)
1939 ;; Create any groups that doesn't already exist on the
1941 (dolist (spec specs)
1942 (when (and (not (member (car spec) groups))
1943 (not (eq (car spec) 'junk)))
1944 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1945 ;; Then copy over all the messages.
1947 (dolist (spec specs)
1948 (let ((group (car spec))
1949 (ranges (cdr spec)))
1950 (if (eq group 'junk)
1951 (setq junk-articles ranges)
1952 (push (list (nnimap-send-command
1954 (nnimap-article-ranges ranges)
1955 (utf7-encode group t))
1958 ;; Wait for the last COPY response...
1960 (nnimap-wait-for-response (caar sequences))
1961 ;; And then mark the successful copy actions as deleted,
1962 ;; and possibly expunge them.
1963 (nnimap-mark-and-expunge-incoming
1964 (nnimap-parse-copied-articles sequences)))
1965 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1967 (defun nnimap-mark-and-expunge-incoming (range)
1969 (setq range (nnimap-article-ranges range))
1972 (nnimap-send-command
1973 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1975 ;; If the server supports it, we now delete the message we have
1976 ;; just copied over.
1977 ((nnimap-capability "UIDPLUS")
1978 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1979 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1980 ;; user has configured it.
1982 (setq sequence (nnimap-send-command "EXPUNGE"))))
1983 (nnimap-wait-for-response sequence))))
1985 (defun nnimap-parse-copied-articles (sequences)
1986 (let (sequence copied range)
1987 (goto-char (point-min))
1988 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1989 (setq sequence (string-to-number (match-string 1)))
1990 (when (setq range (cadr (assq sequence sequences)))
1991 (push (gnus-uncompress-range range) copied)))
1992 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1994 (defun nnimap-new-articles (flags)
1996 (dolist (elem flags)
1997 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1999 (push (car elem) new)))
2000 (gnus-compress-sequence (nreverse new))))
2002 (defun nnimap-make-split-specs (list)
2006 (destructuring-bind (article spec) elem
2007 (dolist (group (delete nil (mapcar #'car spec)))
2008 (unless (setq entry (assoc group specs))
2009 (push (setq entry (list group)) specs))
2010 (setcdr entry (cons article (cdr entry))))))
2011 (dolist (entry specs)
2012 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2015 (defun nnimap-transform-split-mail ()
2016 (goto-char (point-min))
2017 (let (article bytes)
2020 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2021 (delete-region (point) (progn (forward-line 1) (point)))
2024 (setq article (match-string 1)
2025 bytes (nnimap-get-length))
2026 (delete-region (line-beginning-position) (line-end-position))
2027 ;; Insert MMDF separator, and a way to remember what this
2029 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2030 (forward-char (1+ bytes))
2031 (setq bytes (nnimap-get-length))
2032 (delete-region (line-beginning-position) (line-end-position))
2033 ;; There's a body; skip past that.
2035 (forward-char (1+ bytes))
2036 (delete-region (line-beginning-position) (line-end-position)))))))
2038 (defun nnimap-dummy-active-number (group &optional server)
2041 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2043 (goto-char (point-min))
2044 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2045 (error "Invalid nnimap mail")
2046 (setq article (string-to-number (match-string 1))))
2048 (if (eq group-art 'junk)
2049 (list (cons 'junk 1))
2051 nnimap-incoming-split-list)))
2053 (defun nnimap-make-thread-query (header)
2054 (let* ((id (mail-header-id header))
2056 (or (mail-header-references header)
2060 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2062 (dolist (refid refs value)
2064 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2065 refid refid value)))))
2070 ;;; nnimap.el ends here