Get the number of lines by using BODYSTRUCTURE.
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 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 (eval-and-compile
30   (require 'nnheader))
31
32 (nnoo-declare nnimap)
33
34 (defvoo nnimap-address nil
35   "The address of the IMAP server.")
36
37 (defvoo nnimap-server-port nil
38   "The IMAP port used.
39 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
40 it will default to `imap'.")
41
42 (defvoo nnimap-stream 'ssl
43   "How nnimap will talk to the IMAP server.
44 Values are `ssl' and `network'.")
45
46 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
47                                  (if (listp imap-shell-program)
48                                      (car imap-shell-program)
49                                    imap-shell-program)
50                                "ssh %s imapd"))
51
52 (defvoo nnimap-inbox nil
53   "The mail box where incoming mail arrives and should be split out of.")
54
55 (defvoo nnimap-expunge-inbox nil
56   "If non-nil, expunge the inbox after fetching mail.
57 This is always done if the server supports UID EXPUNGE, but it's
58 not done by default on servers that doesn't support that command.")
59
60 (defvoo nnimap-connection-alist nil)
61 (defvar nnimap-process nil)
62
63 (defvar nnimap-status-string "")
64
65 (defvar nnimap-split-download-body-default nil
66   "Internal variable with default value for `nnimap-split-download-body'.")
67
68 (defstruct nnimap
69   group process commands capabilities)
70
71 (defvar nnimap-object nil)
72
73 (defvar nnimap-mark-alist
74   '((read "\\Seen")
75     (tick "\\Flagged")
76     (reply "\\Answered")
77     (expire "gnus-expire")
78     (dormant "gnus-dormant")
79     (score "gnus-score")
80     (save "gnus-save")
81     (download "gnus-download")
82     (forward "gnus-forward")))
83
84 (defvar nnimap-split-methods nil)
85
86 (defun nnimap-buffer ()
87   (nnimap-find-process-buffer nntp-server-buffer))
88
89 (defmacro nnimap-with-process-buffer (&rest body)
90   `(with-current-buffer (nnimap-find-process-buffer (current-buffer))
91      ,@body))
92
93 (defun nnimap-retrieve-headers (articles &optional group server fetch-old)
94   (with-current-buffer nntp-server-buffer
95     (erase-buffer)
96     (when (nnimap-possibly-change-group group server)
97       (with-current-buffer (nnimap-buffer)
98         (nnimap-send-command "SELECT %S" (utf7-encode group t))
99         (erase-buffer)
100         (nnimap-wait-for-response
101          (nnimap-send-command
102           "UID FETCH %s %s"
103           (nnimap-article-ranges (gnus-compress-sequence articles))
104           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
105                   (format
106                    (if (member "IMAP4rev1"
107                                (nnimap-capabilities nnimap-object))
108                        "BODY.PEEK[HEADER.FIELDS %s]"
109                      "RFC822.HEADER.LINES %s")
110                    (append '(Subject From Date Message-Id
111                                      References In-Reply-To Xref)
112                            nnmail-extra-headers))))
113          t)
114         (nnimap-transform-headers))
115       (insert-buffer-substring
116        (nnimap-find-process-buffer (current-buffer))))
117     t))
118
119 (defun nnimap-transform-headers ()
120   (goto-char (point-min))
121   (let (article bytes lines)
122     (block nil
123       (while (not (eobp))
124         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
125           (delete-region (point) (progn (forward-line 1) (point)))
126           (when (eobp)
127             (return)))
128         (setq article (match-string 1)
129               bytes (nnimap-get-length)
130               lines nil)
131         (beginning-of-line)
132         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
133           (let ((structure (ignore-errors (read (current-buffer)))))
134             (while (and (consp structure)
135                         (not (stringp (car structure))))
136               (setq structure (car structure)))
137             (setq lines (nth 7 structure))))
138         (delete-region (line-beginning-position) (line-end-position))
139         (insert (format "211 %s Article retrieved." article))
140         (forward-line 1)
141         (insert (format "Bytes: %d\n" bytes))
142         (when lines
143           (insert (format "Lines: %s\n" lines)))
144         (re-search-forward "^\r$")
145         (delete-region (line-beginning-position) (line-end-position))
146         (insert ".")
147         (forward-line 1)))))
148
149 (defun nnimap-get-length ()
150   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
151        (string-to-number (match-string 1))))
152
153 (defun nnimap-article-ranges (ranges)
154   (let (result)
155     (cond
156      ((numberp ranges)
157       (number-to-string ranges))
158      ((numberp (cdr ranges))
159       (format "%d:%d" (car ranges) (cdr ranges)))
160      (t
161       (dolist (elem ranges)
162         (push
163          (if (consp elem)
164              (format "%d:%d" (car elem) (cdr elem))
165            (number-to-string elem))
166          result))
167       (mapconcat #'identity (nreverse result) ",")))))
168
169 (defun nnimap-open-server (server &optional defs)
170   (if (nnimap-server-opened server)
171       t
172     (unless (assq 'nnimap-address defs)
173       (setq defs (append defs (list (list 'nnimap-address server)))))
174     (nnoo-change-server 'nnimap server defs)
175     (or (nnimap-find-connection nntp-server-buffer)
176         (nnimap-open-connection nntp-server-buffer))))
177
178 (defun nnimap-make-process-buffer (buffer)
179   (with-current-buffer
180       (generate-new-buffer (format "*nnimap %s %s %s*"
181                                    nnimap-address nnimap-server-port
182                                    (gnus-buffer-exists-p buffer)))
183     (mm-disable-multibyte)
184     (buffer-disable-undo)
185     (gnus-add-buffer)
186     (set (make-local-variable 'after-change-functions) nil)
187     (set (make-local-variable 'nnimap-object) (make-nnimap))
188     (push (list buffer (current-buffer)) nnimap-connection-alist)
189     (current-buffer)))
190
191 (defun nnimap-open-shell-stream (name buffer host port)
192   (let ((process (start-process name buffer shell-file-name
193                                 shell-command-switch
194                                 (format-spec
195                                  nnimap-shell-program
196                                  (format-spec-make
197                                   ?s host
198                                   ?p port)))))
199     process))
200
201 (defun nnimap-open-connection (buffer)
202   (with-current-buffer (nnimap-make-process-buffer buffer)
203     (let* ((coding-system-for-read 'binary)
204            (coding-system-for-write 'binary)
205            (credentials
206             (cond
207              ((eq nnimap-stream 'network)
208               (open-network-stream "*nnimap*" (current-buffer) nnimap-address
209                                    (or nnimap-server-port "imap"))
210               (netrc-credentials nnimap-address "imap"))
211              ((eq nnimap-stream 'stream)
212               (nnimap-open-shell-stream
213                "*nnimap*" (current-buffer) nnimap-address
214                (or nnimap-server-port "imap"))
215               (netrc-credentials nnimap-address "imap"))
216              ((eq nnimap-stream 'ssl)
217               (open-tls-stream "*nnimap*" (current-buffer) nnimap-address
218                                (or nnimap-server-port "imaps"))
219               (netrc-credentials nnimap-address "imaps" "imap")))))
220       (setf (nnimap-process nnimap-object)
221             (get-buffer-process (current-buffer)))
222       (unless credentials
223         (delete-process (nnimap-process nnimap-object))
224         (error "Can't find user name/password for %s" nnimap-address))
225       (when (and (nnimap-process nnimap-object)
226                  (memq (process-status (nnimap-process nnimap-object))
227                        '(open run)))
228         (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
229         (let ((result (nnimap-command "LOGIN %S %S"
230                                       (car credentials) (cadr credentials))))
231           (unless (car result)
232             (delete-process (nnimap-process nnimap-object))
233             (error "Unable to login to the server: %s"
234                    (mapconcat #'identity (cadr result) " ")))
235           (setf (nnimap-capabilities nnimap-object)
236                 (or (nnimap-find-parameter "CAPABILITY" (cdr result))
237                     (nnimap-find-parameter
238                      "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
239           (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
240             (nnimap-command "ENABLE QRESYNC"))
241           t)))))
242
243 (defun nnimap-find-parameter (parameter elems)
244   (let (result)
245     (dolist (elem elems)
246       (cond
247        ((equal (car elem) parameter)
248         (setq result (cdr elem)))
249        ((and (equal (car elem) "OK")
250              (consp (cadr elem))
251              (equal (caadr elem) parameter))
252         (setq result (cdr (cadr elem))))))
253     result))
254
255 (defun nnimap-close-server (&optional server)
256   t)
257
258 (defun nnimap-request-close ()
259   t)
260
261 (defun nnimap-server-opened (&optional server)
262   (and (nnoo-current-server-p 'nnimap server)
263        nntp-server-buffer
264        (gnus-buffer-live-p nntp-server-buffer)
265        (nnimap-find-connection nntp-server-buffer)))
266
267 (defun nnimap-status-message (&optional server)
268   nnimap-status-string)
269
270 (defun nnimap-request-article (article &optional group server to-buffer)
271   (with-current-buffer nntp-server-buffer
272     (let ((result (nnimap-possibly-change-group group server)))
273       (when (stringp article)
274         (setq article (nnimap-find-article-by-message-id group article)))
275       (when (and result
276                  article)
277         (erase-buffer)
278         (nnimap-with-process-buffer
279          (erase-buffer)
280          (setq result
281                (nnimap-command
282                 (if (member "IMAP4rev1" (nnimap-capabilities nnimap-object))
283                     "UID FETCH %d BODY.PEEK[]"
284                   "UID FETCH %d RFC822.PEEK")
285                 article)))
286         (let ((buffer (nnimap-find-process-buffer (current-buffer))))
287           (when (car result)
288             (with-current-buffer to-buffer
289               (insert-buffer-substring buffer)
290               (goto-char (point-min))
291               (let ((bytes (nnimap-get-length)))
292                 (delete-region (line-beginning-position)
293                                (progn (forward-line 1) (point)))
294                 (goto-char (+ (point) bytes))
295                 (delete-region (point) (point-max))
296                 (nnheader-ms-strip-cr))
297               t)))))))
298
299 (defun nnimap-request-group (group &optional server dont-check)
300   (with-current-buffer nntp-server-buffer
301     (let ((result (nnimap-possibly-change-group group server))
302           articles)
303       (when result
304         (setq articles (nnimap-get-flags "1:*"))
305         (erase-buffer)
306         (insert
307          (format
308           "211 %d %d %d %S\n"
309           (length articles)
310           (or (caar articles) 0)
311           (or (caar (last articles)) 0)
312           group))
313         t))))
314
315 (defun nnimap-get-flags (spec)
316   (let ((articles nil)
317         elems)
318     (with-current-buffer (nnimap-buffer)
319       (erase-buffer)
320       (nnimap-wait-for-response (nnimap-send-command
321                                  "UID FETCH %s FLAGS" spec))
322       (goto-char (point-min))
323       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
324         (setq elems (nnimap-parse-line (match-string 1)))
325         (push (cons (string-to-number (cadr (member "UID" elems)))
326                     (cadr (member "FLAGS" elems)))
327               articles)))
328     (nreverse articles)))
329
330 (defun nnimap-close-group (group &optional server)
331   t)
332
333 (deffoo nnimap-request-move-article (article group server accept-form
334                                              &optional last internal-move-group)
335   (when (nnimap-possibly-change-group group server)
336     ;; If the move is internal (on the same server), just do it the easy
337     ;; way.
338     (let ((message-id (message-field-value "message-id")))
339       (if internal-move-group
340           (let ((result
341                  (with-current-buffer (nnimap-buffer)
342                    (nnimap-command "UID COPY %d %S"
343                                    article
344                                    (utf7-encode internal-move-group t)))))
345             (when (car result)
346               (nnimap-delete-article article)
347               (cons internal-move-group
348                     (nnimap-find-article-by-message-id
349                      internal-move-group message-id))))
350         (with-temp-buffer
351           (let ((result (eval accept-form)))
352             (when result
353               (nnimap-delete-article article)
354               result)))))))
355
356 (deffoo nnimap-request-expire-articles (articles group &optional server force)
357   (cond
358    ((not (nnimap-possibly-change-group group server))
359     articles)
360    (force
361     (unless (nnimap-delete-article articles)
362       (message "Article marked for deletion, but not expunged."))
363     nil)
364    (t
365     articles)))
366
367 (defun nnimap-find-article-by-message-id (group message-id)
368   (when (nnimap-possibly-change-group group nil)
369     (with-current-buffer (nnimap-buffer)
370       (let ((result
371              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
372             article)
373         (when (car result)
374           ;; Select the last instance of the message in the group.
375           (and (setq article
376                      (car (last (assoc "SEARCH" (cdr result)))))
377                (string-to-number article)))))))
378
379 (defun nnimap-delete-article (articles)
380   (with-current-buffer (nnimap-buffer)
381     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
382                     (nnimap-article-ranges articles))
383     (when (member "UIDPLUS" (nnimap-capabilities nnimap-object))
384       (nnimap-send-command "UID EXPUNGE %s"
385                            (nnimap-article-ranges articles))
386       t)))
387
388 (deffoo nnimap-request-scan (&optional group server)
389   (when (and (nnimap-possibly-change-group nil server)
390              (equal group nnimap-inbox)
391              nnimap-inbox
392              nnimap-split-methods)
393     (nnimap-split-incoming-mail)))
394
395 (defun nnimap-marks-to-flags (marks)
396   (let (flags flag)
397     (dolist (mark marks)
398       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
399         (push flag flags)))
400     flags))
401
402 (defun nnimap-request-set-mark (group actions &optional server)
403   (when (nnimap-possibly-change-group group server)
404     (let (sequence)
405       (with-current-buffer (nnimap-find-process-buffer nntp-server-buffer)
406         ;; Just send all the STORE commands without waiting for
407         ;; response.  If they're successful, they're successful.
408         (dolist (action actions)
409           (destructuring-bind (range action marks) action
410             (let ((flags (nnimap-marks-to-flags marks)))
411               (when flags
412                 (setq sequence (nnimap-send-command
413                                 "UID STORE %s %sFLAGS.SILENT (%s)"
414                                 (nnimap-article-ranges range)
415                                 (if (eq action 'del)
416                                     "-"
417                                   "+")
418                                 (mapconcat #'identity flags " ")))))))
419         ;; Wait for the last command to complete to avoid later
420         ;; syncronisation problems with the stream.
421         (nnimap-wait-for-response sequence)))))
422
423 (deffoo nnimap-request-accept-article (group &optional server last)
424   (when (nnimap-possibly-change-group nil server)
425     (nnmail-check-syntax)
426     (let ((message (buffer-string))
427           (message-id (message-field-value "message-id"))
428           sequence)
429       (with-current-buffer nntp-server-buffer
430         (nnimap-with-process-buffer
431          (setq sequence (nnimap-send-command
432                          "APPEND %S {%d}" (utf7-encode group t)
433                          (length message)))
434          (process-send-string (get-buffer-process (current-buffer)) message)
435          (process-send-string (get-buffer-process (current-buffer)) "\r\n")
436          (let ((result (nnimap-get-response sequence)))
437            (when result
438              (cons group
439                    (nnimap-find-article-by-message-id group message-id)))))))))
440
441 (defun nnimap-add-cr ()
442   (goto-char (point-min))
443   (while (re-search-forward "\r?\n" nil t)
444     (replace-match "\r\n" t t)))
445
446 (defun nnimap-get-groups ()
447   (let ((result (nnimap-command "LIST \"\" \"*\""))
448         groups)
449     (when (car result)
450       (dolist (line (cdr result))
451         (when (and (equal (car line) "LIST")
452                    (not (string-match "noselect" (caadr line))))
453           (push (car (last line)) groups)))
454       (nreverse groups))))
455
456 (defun nnimap-request-list (&optional server)
457   (nnimap-possibly-change-group nil server)
458   (with-current-buffer nntp-server-buffer
459     (erase-buffer)
460     (let ((groups
461            (nnimap-with-process-buffer
462             (nnimap-get-groups)))
463           sequences responses)
464       (when groups
465         (nnimap-with-process-buffer
466          (dolist (group groups)
467            (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
468                        group)
469                  sequences))
470          (nnimap-wait-for-response (caar sequences))
471          (setq responses
472                (nnimap-get-responses (mapcar #'car sequences))))
473         (dolist (response responses)
474           (let* ((sequence (car response))
475                  (response (cadr response))
476                  (group (cadr (assoc sequence sequences))))
477             (when (and group
478                        (equal (caar response) "OK"))
479               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
480                     highest exists)
481                 (dolist (elem response)
482                   (when (equal (cadr elem) "EXISTS")
483                     (setq exists (string-to-number (car elem)))))
484                 (when uidnext
485                   (setq highest (1- (string-to-number (car uidnext)))))
486                 (if (zerop exists)
487                     ;; Empty group.
488                     (insert (format "%S %d %d y\n"
489                                     (utf7-decode group t) highest (1+ highest)))
490                   ;; Return the widest possible range.
491                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
492                                   (or highest exists))))))))
493         t))))
494
495 (defun nnimap-retrieve-group-data-early (server infos)
496   (when (nnimap-possibly-change-group nil server)
497     (with-current-buffer (nnimap-buffer)
498       ;; QRESYNC handling isn't implemented.
499       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
500             marks groups sequences)
501         ;; Go through the infos and gather the data needed to know
502         ;; what and how to request the data.
503         (dolist (info infos)
504           (setq marks (gnus-info-marks info))
505           (push (list (gnus-group-real-name (gnus-info-group info))
506                       (cdr (assq 'active marks))
507                       (cdr (assq 'uid marks)))
508                 groups))
509         ;; Then request the data.
510         (erase-buffer)
511         (dolist (elem groups)
512           (if (and qresyncp
513                    (nth 2 elem))
514               (push
515                (list 'qresync
516                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
517                                           (car elem)
518                                           (car (nth 2 elem))
519                                           (cdr (nth 2 elem)))
520                      nil
521                      (car elem))
522                sequences)
523             (let ((start
524                    (if (nth 1 elem)
525                        ;; Fetch the last 100 flags.
526                        (max 1 (- (cdr (nth 1 elem)) 100))
527                      1)))
528               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
529                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
530                           start
531                           (car elem))
532                     sequences))))
533         sequences))))
534
535 (defun nnimap-finish-retrieve-group-infos (server infos sequences)
536   (when (nnimap-possibly-change-group nil server)
537     (with-current-buffer (nnimap-buffer)
538       ;; Wait for the final data to trickle in.
539       (nnimap-wait-for-response (cadar sequences))
540       ;; Now we should have all the data we need, no matter whether
541       ;; we're QRESYNCING, fetching all the flags from scratch, or
542       ;; just fetching the last 100 flags per group.
543       (nnimap-update-infos (nnimap-flags-to-marks
544                             (nnimap-parse-flags
545                              (nreverse sequences)))
546                            infos))))
547
548 (defun nnimap-update-infos (flags infos)
549   (dolist (info infos)
550     (let ((group (gnus-group-real-name (gnus-info-group info))))
551       (nnimap-update-info info (cdr (assoc group flags))))))
552
553 (defun nnimap-update-info (info marks)
554   (when marks
555     (destructuring-bind (existing flags high low uidnext start-article) marks
556       (let ((group (gnus-info-group info))
557             (completep (and start-article
558                             (= start-article 1))))
559         ;; First set the active ranges based on high/low.
560         (if completep
561             (gnus-set-active group
562                              (if high
563                                  (cons low high)
564                                ;; No articles in this group.
565                                (cons (1- uidnext) uidnext)))
566           (setcdr (gnus-active group) high))
567         ;; Then update the list of read articles.
568         (let* ((unread
569                 (gnus-compress-sequence
570                  (gnus-set-difference
571                   (gnus-set-difference
572                    existing
573                    (cdr (assoc "\\Seen" flags)))
574                   (cdr (assoc "\\Flagged" flags)))))
575                (read (gnus-range-difference
576                       (cons start-article high) unread)))
577           (when (> start-article 1)
578             (setq read
579                   (gnus-range-nconcat
580                    (gnus-sorted-range-intersection
581                     (cons 1 start-article)
582                     (gnus-info-read info))
583                    read)))
584           (gnus-info-set-read info read)
585           ;; Update the marks.
586           (setq marks (gnus-info-marks info))
587           ;; Note the active level for the next run-through.
588           (let ((active (assq 'active marks)))
589             (if active
590                 (setcdr active (gnus-active group))
591               (push (cons 'active (gnus-active group)) marks)))
592           (dolist (type (cdr nnimap-mark-alist))
593             (let ((old-marks (assoc (car type) marks))
594                   (new-marks (gnus-compress-sequence
595                               (cdr (assoc (cadr type) flags)))))
596               (setq marks (delq old-marks marks))
597               (pop old-marks)
598               (when (and old-marks
599                          (> start-article 1))
600                 (setq old-marks (gnus-range-difference
601                                  (cons start-article high)
602                                  old-marks))
603                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
604               (when new-marks
605                 (push (cons (car type) new-marks) marks)))
606             (gnus-info-set-marks info marks)))))))
607
608 (defun nnimap-flags-to-marks (groups)
609   (let (data group totalp uidnext articles start-article mark)
610     (dolist (elem groups)
611       (setq group (car elem)
612             uidnext (cadr elem)
613             start-article (caddr elem)
614             articles (cdddr elem))
615       (let ((high (caar articles))
616             marks low existing)
617         (dolist (article articles)
618           (setq low (car article))
619           (push (car article) existing)
620           (dolist (flag (cdr article))
621             (setq mark (assoc flag marks))
622             (if (not mark)
623                 (push (list flag (car article)) marks)
624               (setcdr mark (cons (car article) (cdr mark)))))
625           (push (list group existing marks high low uidnext start-article)
626                 data))))
627     data))
628
629 (defun nnimap-parse-flags (sequences)
630   (goto-char (point-min))
631   (let (start end articles groups uidnext elems)
632     (dolist (elem sequences)
633       (destructuring-bind (group-sequence flag-sequence totalp group) elem
634         ;; The EXAMINE was successful.
635         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
636                    (progn
637                      (forward-line 1)
638                      (setq start (point))
639                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
640                                                (or end (point-min)) t)
641                          (setq uidnext (string-to-number (match-string 1)))
642                        (setq uidnext nil))
643                      (goto-char start))
644                    ;; The UID FETCH FLAGS was successful.
645                    (search-forward (format "\n%d OK " flag-sequence) nil t))
646           (setq end (point))
647           (goto-char start)
648           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
649             (setq elems (nnimap-parse-line (match-string 1)))
650             (push (cons (string-to-number (cadr (member "UID" elems)))
651                         (cadr (member "FLAGS" elems)))
652                   articles))
653           (push (nconc (list group uidnext totalp) articles) groups)
654           (setq articles nil))))
655     groups))
656
657 (defun nnimap-find-process-buffer (buffer)
658   (cadr (assoc buffer nnimap-connection-alist)))
659
660 (defun nnimap-request-post (&optional server)
661   (setq nnimap-status-string "Read-only server")
662   nil)
663
664 (defun nnimap-possibly-change-group (group server)
665   (when (and server
666              (not (nnimap-server-opened server)))
667     (nnimap-open-server server))
668   (if (not group)
669       t
670     (with-current-buffer (nnimap-buffer)
671       (if (equal group (nnimap-group nnimap-object))
672           t
673         (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
674           (when (car result)
675             (setf (nnimap-group nnimap-object) group)
676             result))))))
677
678 (defun nnimap-find-connection (buffer)
679   "Find the connection delivering to BUFFER."
680   (let ((entry (assoc buffer nnimap-connection-alist)))
681     (when entry
682       (if (and (buffer-name (cadr entry))
683                (get-buffer-process (cadr entry))
684                (memq (process-status (get-buffer-process (cadr entry)))
685                      '(open run)))
686           (get-buffer-process (cadr entry))
687         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
688         nil))))
689
690 (defvar nnimap-sequence 0)
691
692 (defun nnimap-send-command (&rest args)
693   (process-send-string
694    (get-buffer-process (current-buffer))
695    (nnimap-log-command
696     (format "%d %s\r\n"
697             (incf nnimap-sequence)
698             (apply #'format args))))
699   nnimap-sequence)
700
701 (defun nnimap-log-command (command)
702   (with-current-buffer (get-buffer-create "*imap log*")
703     (goto-char (point-max))
704     (insert (format-time-string "%H:%M:%S") " " command))
705   command)
706
707 (defun nnimap-command (&rest args)
708   (erase-buffer)
709   (let* ((sequence (apply #'nnimap-send-command args))
710          (response (nnimap-get-response sequence)))
711     (if (equal (caar response) "OK")
712         (cons t response)
713       (nnheader-report 'nnimap "%s"
714                        (mapconcat #'identity (car response) " "))
715       nil)))
716
717 (defun nnimap-get-response (sequence)
718   (nnimap-wait-for-response sequence)
719   (nnimap-parse-response))
720
721 (defun nnimap-wait-for-response (sequence &optional messagep)
722   (goto-char (point-max))
723   (while (or (bobp)
724              (progn
725                (forward-line -1)
726                (not (looking-at (format "^%d .*\n" sequence)))))
727     (when messagep
728       (message "Read %dKB" (/ (buffer-size) 1000)))
729     (nnheader-accept-process-output (get-buffer-process (current-buffer)))
730     (goto-char (point-max))))
731
732 (defun nnimap-parse-response ()
733   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
734         result)
735     (dolist (line lines)
736       (push (cdr (nnimap-parse-line line)) result))
737     ;; Return the OK/error code first, and then all the "continuation
738     ;; lines" afterwards.
739     (cons (pop result)
740           (nreverse result))))
741
742 ;; Parse an IMAP response line lightly.  They look like
743 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
744 ;; the lines into a list of strings and lists of string.
745 (defun nnimap-parse-line (line)
746   (let (char result)
747     (with-temp-buffer
748       (insert line)
749       (goto-char (point-min))
750       (while (not (eobp))
751         (if (eql (setq char (following-char)) ? )
752             (forward-char 1)
753           (push
754            (cond
755             ((eql char ?\[)
756              (split-string (buffer-substring
757                             (1+ (point)) (1- (search-forward "]")))))
758             ((eql char ?\()
759              (split-string (buffer-substring
760                             (1+ (point)) (1- (search-forward ")")))))
761             ((eql char ?\")
762              (forward-char 1)
763              (buffer-substring (point) (1- (search-forward "\""))))
764             (t
765              (buffer-substring (point) (if (search-forward " " nil t)
766                                            (1- (point))
767                                          (goto-char (point-max))))))
768            result)))
769       (nreverse result))))
770
771 (defun nnimap-last-response-string ()
772   (save-excursion
773     (forward-line 1)
774     (let ((end (point)))
775       (forward-line -1)
776       (when (not (bobp))
777         (forward-line -1)
778         (while (and (not (bobp))
779                     (eql (following-char) ?*))
780           (forward-line -1))
781         (unless (eql (following-char) ?*)
782           (forward-line 1)))
783       (buffer-substring (point) end))))
784
785 (defun nnimap-get-responses (sequences)
786   (let (responses)
787     (dolist (sequence sequences)
788       (goto-char (point-min))
789       (when (re-search-forward (format "^%d " sequence) nil t)
790         (push (list sequence (nnimap-parse-response))
791               responses)))
792     responses))
793
794 (defvar nnimap-incoming-split-list nil)
795
796 (defun nnimap-fetch-inbox (articles)
797   (erase-buffer)
798   (nnimap-wait-for-response
799    (nnimap-send-command
800     "UID FETCH %s %s"
801     (nnimap-article-ranges articles)
802     (format "(UID %s%s)"
803             (format
804              (if (member "IMAP4rev1"
805                          (nnimap-capabilities nnimap-object))
806                  "BODY.PEEK[HEADER] BODY.PEEK"
807                "RFC822.PEEK"))
808             (if nnimap-split-download-body-default
809                 ""
810               "[1]")))
811    t))
812
813 (defun nnimap-split-incoming-mail ()
814   (with-current-buffer (nnimap-buffer)
815     (let ((nnimap-incoming-split-list nil)
816           (nnmail-split-methods nnimap-split-methods)
817           (nnmail-inhibit-default-split-group t)
818           (groups (nnimap-get-groups))
819           new-articles)
820       (erase-buffer)
821       (nnimap-command "SELECT %S" nnimap-inbox)
822       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
823       (when new-articles
824         (nnimap-fetch-inbox new-articles)
825         (nnimap-transform-split-mail)
826         (nnheader-ms-strip-cr)
827         (nnmail-cache-open)
828         (nnmail-split-incoming (current-buffer)
829                                #'nnimap-save-mail-spec
830                                nil nil
831                                #'nnimap-dummy-active-number)
832         (when nnimap-incoming-split-list
833           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
834                 sequences)
835             ;; Create any groups that doesn't already exist on the
836             ;; server first.
837             (dolist (spec specs)
838               (unless (member (car spec) groups)
839                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
840             ;; Then copy over all the messages.
841             (erase-buffer)
842             (dolist (spec specs)
843               (let ((group (car spec))
844                     (ranges (cdr spec)))
845                 (push (list (nnimap-send-command "UID COPY %s %S"
846                                                  (nnimap-article-ranges ranges)
847                                                  (utf7-encode group t))
848                             ranges)
849                       sequences)))
850             ;; Wait for the last COPY response...
851             (when sequences
852               (nnimap-wait-for-response (caar sequences))
853               ;; And then mark the successful copy actions as deleted,
854               ;; and possibly expunge them.
855               (nnimap-mark-and-expunge-incoming
856                (nnimap-parse-copied-articles sequences)))))))))
857
858 (defun nnimap-mark-and-expunge-incoming (range)
859   (when range
860     (setq range (nnimap-article-ranges range))
861     (nnimap-send-command
862      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
863     (cond
864      ;; If the server supports it, we now delete the message we have
865      ;; just copied over.
866      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
867       (nnimap-send-command "UID EXPUNGE %s" range))
868      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
869      ;; user has configured it.
870      (nnimap-expunge-inbox
871       (nnimap-send-command "EXPUNGE")))))
872
873 (defun nnimap-parse-copied-articles (sequences)
874   (let (sequence copied range)
875     (goto-char (point-min))
876     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
877       (setq sequence (string-to-number (match-string 1)))
878       (when (setq range (cadr (assq sequence sequences)))
879         (push (gnus-uncompress-range range) copied)))
880     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
881
882 (defun nnimap-new-articles (flags)
883   (let (new)
884     (dolist (elem flags)
885       (when (or (null (cdr elem))
886                 (and (not (member "\\Deleted" (cdr elem)))
887                      (not (member "\\Seen" (cdr elem)))))
888         (push (car elem) new)))
889     (gnus-compress-sequence (nreverse new))))
890
891 (defun nnimap-make-split-specs (list)
892   (let ((specs nil)
893         entry)
894     (dolist (elem list)
895       (destructuring-bind (article spec) elem
896         (dolist (group (delete nil (mapcar #'car spec)))
897           (unless (setq entry (assoc group specs))
898             (push (setq entry (list group)) specs))
899           (setcdr entry (cons article (cdr entry))))))
900     (dolist (entry specs)
901       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
902     specs))
903
904 (defun nnimap-transform-split-mail ()
905   (goto-char (point-min))
906   (let (article bytes)
907     (block nil
908       (while (not (eobp))
909         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
910           (delete-region (point) (progn (forward-line 1) (point)))
911           (when (eobp)
912             (return)))
913         (setq article (match-string 1)
914               bytes (nnimap-get-length))
915         (delete-region (line-beginning-position) (line-end-position))
916         ;; Insert MMDF separator, and a way to remember what this
917         ;; article UID is.
918         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
919         (forward-char (1+ bytes))
920         (setq bytes (nnimap-get-length))
921         (delete-region (line-beginning-position) (line-end-position))
922         (forward-char (1+ bytes))
923         (delete-region (line-beginning-position) (line-end-position))))))
924
925 (defun nnimap-dummy-active-number (group &optional server)
926   1)
927
928 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
929   (let (article)
930     (goto-char (point-min))
931     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
932         (error "Invalid nnimap mail")
933       (setq article (string-to-number (match-string 1))))
934     (push (list article group-art)
935           nnimap-incoming-split-list)))
936
937 (provide 'nnimap)
938
939 ;;; nnimap.el ends here
940 bash: imapd: command not found
941
942 Process name exited abnormally with code 127