*** empty log message ***
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2 ;; Copyright (C) 1987,88,89,90,92,93,94,95 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
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 2, or (at your option)
13 ;; 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; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'rnews)
29 (require 'sendmail)
30 (require 'nnheader)
31
32 (eval-and-compile
33   (autoload 'news-setup "rnewspost")
34   (autoload 'news-reply-mode "rnewspost")
35   (autoload 'nnmail-request-post-buffer "nnmail")
36   (autoload 'cancel-timer "timer")
37   (autoload 'telnet "telnet" nil t)
38   (autoload 'telnet-send-input "telnet" nil t)
39   (autoload 'timezone-parse-date "timezone"))
40
41 (defvar nntp-server-hook nil
42   "*Hooks for the NNTP server.
43 If the kanji code of the NNTP server is different from the local kanji
44 code, the correct kanji code of the buffer associated with the NNTP
45 server must be specified as follows:
46
47 \(setq nntp-server-hook
48       (function
49        (lambda ()
50          ;; Server's Kanji code is EUC (NEmacs hack).
51          (make-local-variable 'kanji-fileio-code)
52          (setq kanji-fileio-code 0))))
53
54 If you'd like to change something depending on the server in this
55 hook, use the variable `nntp-address'.")
56
57 (defvar nntp-server-opened-hook nil
58   "*Hook used for sending commands to the server at startup.  
59 The default value is `nntp-send-mode-reader', which makes an innd
60 server spawn an nnrpd server.  Another useful function to put in this
61 hook might be `nntp-send-authinfo', which will prompt for a password
62 to allow posting from the server.  Note that this is only necessary to
63 do on servers that use strict access control.")  
64 (add-hook 'nntp-server-opened-hook 'nntp-send-mode-reader)
65
66 (defvar nntp-open-server-function 'nntp-open-network-stream
67   "*Function used for connecting to a remote system.
68 It will be called with the address of the remote system.
69
70 Two pre-made functions are `nntp-open-network-stream', which is the
71 default, and simply connects to some port or other on the remote
72 system (see nntp-port-number).  The other is `nntp-open-rlogin', which
73 does an rlogin on the remote system, and then does a telnet to the
74 NNTP server available there (see nntp-rlogin-parameters).")
75
76 (defvar nntp-rlogin-parameters '("telnet" "${NNTPSERVER:=localhost}" "nntp")
77   "*Parameters to `nntp-open-login'.
78 That function may be used as `nntp-open-server-function'.  In that
79 case, this list will be used as the parameter list given to rsh.")
80
81 (defvar nntp-rlogin-user-name nil
82   "*User name on remote system when using the rlogin connect method.")
83
84 (defvar nntp-address nil
85   "*The name of the NNTP server.")
86
87 (defvar nntp-port-number "nntp"
88   "*Port number to connect to.")
89
90 (defvar nntp-large-newsgroup 50
91   "*The number of the articles which indicates a large newsgroup.
92 If the number of the articles is greater than the value, verbose
93 messages will be shown to indicate the current status.")
94
95 (defvar nntp-buggy-select (memq system-type '(fujitsu-uts))
96   "*t if your select routine is buggy.
97 If the select routine signals error or fall into infinite loop while
98 waiting for the server response, the variable must be set to t.  In
99 case of Fujitsu UTS, it is set to T since `accept-process-output'
100 doesn't work properly.")
101
102 (defvar nntp-maximum-request 400
103   "*The maximum number of the requests sent to the NNTP server at one time.
104 If Emacs hangs up while retrieving headers, set the variable to a
105 lower value.")
106
107 (defvar nntp-debug-read 10000
108   "*Display '...' every 10Kbytes of a message being received if it is non-nil.
109 If it is a number, dots are displayed per the number.")
110
111 (defvar nntp-nov-is-evil nil
112   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
113
114 (defvar nntp-xover-commands '("XOVER" "XOVERVIEW")
115   "*List of strings that are used as commands to fetch NOV lines from a server.
116 The strings are tried in turn until a positive response is gotten. If
117 none of the commands are successful, nntp will just grab headers one
118 by one.")
119
120 (defvar nntp-nov-gap 20
121   "*Maximum allowed gap between two articles.
122 If the gap between two consecutive articles is bigger than this
123 variable, split the XOVER request into two requests.")
124
125 (defvar nntp-connection-timeout nil
126   "*Number of seconds to wait before an nntp connection times out.
127 If this variable is nil, which is the default, no timers are set.")
128
129 (defvar nntp-news-default-headers nil
130   "*If non-nil, override `mail-default-headers' when posting news.")
131
132 (defvar nntp-prepare-server-hook nil
133   "*Hook run before a server is opened.
134 If can be used to set up a server remotely, for instance.  Say you
135 have an account at the machine \"other.machine\".  This machine has
136 access to an NNTP server that you can't access locally.  You could
137 then use this hook to rsh to the remote machine and start a proxy NNTP
138 server there that you can connect to.")
139
140 (defvar nntp-async-number 5
141   "*How many articles should be prefetched when in asynchronous mode.")
142
143 (defvar nntp-warn-about-losing-connection t
144   "*If non-nil, beep when a server closes connection.")
145
146 \f
147
148 (defconst nntp-version "nntp 4.0"
149   "Version numbers of this version of NNTP.")
150
151 (defvar nntp-server-buffer nil
152   "Buffer associated with the NNTP server process.")
153
154 (defvar nntp-server-process nil
155   "The NNTP server process.
156 You'd better not use this variable in NNTP front-end program, but
157 instead use `nntp-server-buffer'.")
158
159 (defvar nntp-status-string nil
160   "Save the server response message.
161 You'd better not use this variable in NNTP front-end program but
162 instead call function `nntp-status-message' to get status message.")
163
164 (defvar nntp-server-xover 'try)
165 (defvar nntp-server-list-active-group 'try)
166 (defvar nntp-current-group "")
167 (defvar nntp-timeout-servers nil)
168
169 (defvar nntp-async-process nil)
170 (defvar nntp-async-buffer nil)
171 (defvar nntp-async-articles nil)
172 (defvar nntp-async-fetched nil)
173 (defvar nntp-async-group-alist nil)
174
175
176 \f
177 (defvar nntp-current-server nil)
178 (defvar nntp-server-alist nil)
179 (defvar nntp-server-variables 
180   (list
181    (list 'nntp-server-hook nntp-server-hook)
182    (list 'nntp-server-opened-hook nntp-server-opened-hook)
183    (list 'nntp-port-number nntp-port-number)
184    (list 'nntp-address nntp-address)
185    (list 'nntp-large-newsgroup nntp-large-newsgroup)
186    (list 'nntp-buggy-select nntp-buggy-select)
187    (list 'nntp-maximum-request nntp-maximum-request)
188    (list 'nntp-debug-read nntp-debug-read)
189    (list 'nntp-nov-is-evil nntp-nov-is-evil)
190    (list 'nntp-xover-commands nntp-xover-commands)
191    (list 'nntp-connection-timeout nntp-connection-timeout)
192    (list 'nntp-news-default-headers nntp-news-default-headers)
193    (list 'nntp-prepare-server-hook nntp-prepare-server-hook) 
194    (list 'nntp-async-number nntp-async-number)
195    '(nntp-async-process nil)
196    '(nntp-async-buffer nil)
197    '(nntp-async-articles nil)
198    '(nntp-async-fetched nil)
199    '(nntp-async-group-alist nil)
200    '(nntp-server-process nil)
201    '(nntp-status-string nil)
202    '(nntp-server-xover try)
203    '(nntp-server-list-active-group try)
204    '(nntp-current-group "")))
205
206 \f
207 ;;; Interface functions.
208
209 (defun nntp-retrieve-headers (sequence &optional newsgroup server fetch-old)
210   "Retrieve the headers to the articles in SEQUENCE."
211   (nntp-possibly-change-server newsgroup server)
212   (save-excursion
213     (set-buffer nntp-server-buffer)
214     (erase-buffer)
215     (if (and (not gnus-nov-is-evil) 
216              (not nntp-nov-is-evil)
217              (nntp-retrieve-headers-with-xover sequence fetch-old))
218         'nov
219       (let ((number (length sequence))
220             (count 0)
221             (received 0)
222             (last-point (point-min)))
223         ;; Send HEAD command.
224         (while sequence
225           (nntp-send-strings-to-server 
226            "HEAD" (if (numberp (car sequence)) (int-to-string (car sequence))
227                     (car sequence)))
228           (setq sequence (cdr sequence)
229                 count (1+ count))
230           ;; Every 400 header requests we have to read stream in order
231           ;;  to avoid deadlock.
232           (if (or (null sequence)       ;All requests have been sent.
233                   (zerop (% count nntp-maximum-request)))
234               (progn
235                 (nntp-accept-response)
236                 (while (progn
237                          (goto-char last-point)
238                          ;; Count replies.
239                          (while (re-search-forward "^[0-9]" nil t)
240                            (setq received (1+ received)))
241                          (setq last-point (point))
242                          (< received count))
243                   ;; If number of headers is greater than 100, give
244                   ;;  informative messages.
245                   (and (numberp nntp-large-newsgroup)
246                        (> number nntp-large-newsgroup)
247                        (zerop (% received 20))
248                        (message "NNTP: Receiving headers... %d%%"
249                                 (/ (* received 100) number)))
250                   (nntp-accept-response)))))
251         ;; Wait for text of last command.
252         (goto-char (point-max))
253         (re-search-backward "^[0-9]" nil t)
254         (if (looking-at "^[23]")
255             (while (progn
256                      (goto-char (- (point-max) 3))
257                      (not (looking-at "^\\.\r?\n")))
258               (nntp-accept-response)))
259         (and (numberp nntp-large-newsgroup)
260              (> number nntp-large-newsgroup)
261              (message "NNTP: Receiving headers...done"))
262
263         ;; Now all of replies are received.
264         (setq received number)
265         ;; First, fold continuation lines.
266         (goto-char (point-min))
267         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
268           (replace-match " "))
269         ;; Remove all "\r"'s
270         (goto-char (point-min))
271         (while (search-forward "\r" nil t)
272           (replace-match ""))
273         'headers))))
274
275
276 (defun nntp-retrieve-groups (groups &optional server)
277   (nntp-possibly-change-server nil server)
278   (save-excursion
279     (set-buffer nntp-server-buffer)
280     (and (eq nntp-server-list-active-group 'try)
281          (nntp-try-list-active (car groups)))
282     (erase-buffer)
283     (let ((count 0)
284           (received 0)
285           (last-point (point-min))
286           (command (if nntp-server-list-active-group
287                        "LIST ACTIVE" "GROUP")))
288       (while groups
289         (nntp-send-strings-to-server command (car groups))
290         (setq groups (cdr groups))
291         (setq count (1+ count))
292         ;; Every 400 requests we have to read the stream in
293         ;; order to avoid deadlocks.
294         (if (or (null groups)           ;All requests have been sent.
295                 (zerop (% count nntp-maximum-request)))
296             (progn
297               (nntp-accept-response)
298               (while (progn
299                        (goto-char last-point)
300                        ;; Count replies.
301                        (while (re-search-forward "^[0-9]" nil t)
302                          (setq received (1+ received)))
303                        (setq last-point (point))
304                        (< received count))
305                 (nntp-accept-response)))))
306
307       ;; Wait for the reply from the final command.
308       (if nntp-server-list-active-group
309           (progn
310             (goto-char (point-max))
311             (re-search-backward "^[0-9]" nil t)
312             (if (looking-at "^[23]")
313                 (while (progn
314                          (goto-char (- (point-max) 3))
315                          (not (looking-at "^\\.\r?\n")))
316                   (nntp-accept-response)))))
317
318       ;; Now all replies are received. We remove CRs.
319       (goto-char (point-min))
320       (while (search-forward "\r" nil t)
321         (replace-match "" t t))
322
323       (if nntp-server-list-active-group
324           (progn
325             ;; We have read active entries, so we just delete the
326             ;; superfluos gunk.
327             (goto-char (point-min))
328             (while (re-search-forward "^[.2-5]" nil t)
329               (delete-region (match-beginning 0) 
330                              (progn (forward-line 1) (point))))
331             'active)
332         'group))))
333
334 (defun nntp-open-server (server &optional defs)
335   (nnheader-init-server-buffer)
336   (if (nntp-server-opened server)
337       t
338     (if (or (stringp (car defs))
339             (numberp (car defs)))
340         (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
341     (or (assq 'nntp-address defs)
342         (setq defs (append defs (list (list 'nntp-address server)))))
343     (if (and nntp-current-server
344              (not (equal server nntp-current-server)))
345         (setq nntp-server-alist 
346               (cons (list nntp-current-server
347                           (nnheader-save-variables nntp-server-variables))
348                     nntp-server-alist)))
349     (let ((state (assoc server nntp-server-alist)))
350       (if state 
351           (progn
352             (nnheader-restore-variables (nth 1 state))
353             (setq nntp-server-alist (delq state nntp-server-alist)))
354         (nnheader-set-init-variables nntp-server-variables defs)))
355     (setq nntp-current-server server)
356     (or (nntp-server-opened server)
357         (progn
358           (if (member nntp-address nntp-timeout-servers)
359               nil
360             (run-hooks 'nntp-prepare-server-hook)
361             (nntp-open-server-semi-internal nntp-address nntp-port-number))))))
362
363 (defun nntp-close-server (&optional server)
364   "Close connection to SERVER."
365   (nntp-possibly-change-server nil server)
366   (unwind-protect
367       (progn
368         ;; Un-set default sentinel function before closing connection.
369         (and nntp-server-process
370              (eq 'nntp-default-sentinel
371                  (process-sentinel nntp-server-process))
372              (set-process-sentinel nntp-server-process nil))
373         ;; We cannot send QUIT command unless the process is running.
374         (if (nntp-server-opened)
375             (nntp-send-command nil "QUIT")))
376     (nntp-close-server-internal server)
377     (setq nntp-timeout-servers (delete server nntp-timeout-servers))))
378
379 (defalias 'nntp-request-quit (symbol-function 'nntp-close-server))
380
381 (defun nntp-request-close ()
382   "Close all server connections."
383   (let (proc)
384     (and nntp-async-process
385          (progn
386            (delete-process nntp-async-process)
387            (and (get-buffer nntp-async-buffer)
388                 (kill-buffer nntp-async-buffer))))
389     (while nntp-async-group-alist
390       (and (nth 3 (car nntp-async-group-alist))
391            (delete-process (nth 3 (car nntp-async-group-alist))))
392       (setq nntp-async-group-alist (cdr nntp-async-group-alist)))
393     (while nntp-server-alist
394       (and 
395        (setq proc (nth 1 (assq 'nntp-server-process (car nntp-server-alist))))
396        (delete-process proc))
397       (and 
398        (setq proc (nth 1 (assq 'nntp-async-process (car nntp-server-alist))))
399        (delete-process proc))
400       (and (setq proc (nth 1 (assq 'nntp-async-buffer
401                                    (car nntp-server-alist))))
402            (buffer-name proc)
403            (kill-buffer proc))
404       (setq nntp-server-alist (cdr nntp-server-alist)))
405     (setq nntp-current-server nil
406           nntp-timeout-servers nil
407           nntp-async-group-alist nil)))
408
409 (defun nntp-server-opened (&optional server)
410   "Say whether a connection to SERVER has been opened."
411   (and (equal server nntp-current-server)
412        nntp-server-buffer
413        (buffer-name nntp-server-buffer)
414        nntp-server-process
415        (memq (process-status nntp-server-process) '(open run))))
416
417 (defun nntp-status-message (&optional server)
418   "Return server status as a string."
419   (if (and nntp-status-string
420            ;; NNN MESSAGE
421            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
422                          nntp-status-string))
423       (substring nntp-status-string (match-beginning 1) (match-end 1))
424     ;; Empty message if nothing.
425     (or nntp-status-string "")))
426
427 (defun nntp-request-article (id &optional newsgroup server buffer)
428   "Request article ID (message-id or number)."
429   (nntp-possibly-change-server newsgroup server)
430
431   (let (found)
432
433     ;; First we see whether we can get the article from the async buffer. 
434     (if (and (numberp id)
435              nntp-async-articles
436              (memq id nntp-async-fetched))
437         (save-excursion
438           (set-buffer nntp-async-buffer)
439           (let ((opoint (point))
440                 (art (if (numberp id) (int-to-string id) id))
441                 beg end)
442             (if (and (or (re-search-forward (concat "^2.. +" art) nil t)
443                          (progn
444                            (goto-char (point-min))
445                            (re-search-forward (concat "^2.. +" art) opoint t)))
446                      (progn
447                        (beginning-of-line)
448                        (setq beg (point)
449                              end (re-search-forward "^\\.\r?\n" nil t))))
450                 (progn
451                   (setq found t)
452                   (save-excursion
453                     (set-buffer (or buffer nntp-server-buffer))
454                     (erase-buffer)
455                     (insert-buffer-substring nntp-async-buffer beg end)
456                     (let ((nntp-server-buffer (current-buffer)))
457                       (nntp-decode-text)))
458                   (delete-region beg end)
459                   (and nntp-async-articles
460                        (nntp-async-fetch-articles id)))))))
461
462     (if found 
463         id
464       ;; The article was not in the async buffer, so we fetch it now.
465       (unwind-protect
466           (progn
467             (if buffer (set-process-buffer nntp-server-process buffer))
468             (let ((nntp-server-buffer (or buffer nntp-server-buffer))
469                   (art (or (and (numberp id) (int-to-string id)) id)))
470               (prog1
471                   (and (nntp-send-command "^\\.\r?\n" "ARTICLE" art)
472                        (if (numberp id) 
473                            (cons nntp-current-group id)
474                          ;; We find out what the article number was.
475                          (nntp-find-group-and-number)))
476                 (nntp-decode-text)
477                 (and nntp-async-articles (nntp-async-fetch-articles id)))))
478         (if buffer (set-process-buffer 
479                     nntp-server-process nntp-server-buffer))))))
480
481 (defun nntp-request-body (id &optional newsgroup server)
482   "Request body of article ID (message-id or number)."
483   (nntp-possibly-change-server newsgroup server)
484   (prog1
485       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
486       (nntp-send-command
487        "^\\.\r?\n" "BODY" (or (and (numberp id) (int-to-string id)) id))
488     (nntp-decode-text)))
489
490 (defun nntp-request-head (id &optional newsgroup server)
491   "Request head of article ID (message-id or number)."
492   (nntp-possibly-change-server newsgroup server)
493   (prog1
494       (and (nntp-send-command 
495             "^\\.\r?\n" "HEAD" (if (numberp id) (int-to-string id) id))
496            (if (numberp id) id
497              ;; We find out what the article number was.
498              (nntp-find-group-and-number)))
499     (nntp-decode-text)))
500
501 (defun nntp-request-stat (id &optional newsgroup server)
502   "Request STAT of article ID (message-id or number)."
503   (nntp-possibly-change-server newsgroup server)
504   (nntp-send-command 
505    "^[23].*\r?\n" "STAT" (or (and (numberp id) (int-to-string id)) id)))
506
507 (defun nntp-request-group (group &optional server dont-check)
508   "Select GROUP."
509   (nntp-send-command "^.*\r?\n" "GROUP" group)
510   (setq nntp-current-group group)
511   (save-excursion
512     (set-buffer nntp-server-buffer)
513     (goto-char (point-min))
514     (looking-at "[23]")))
515
516 (defun nntp-request-asynchronous (group &optional server articles)
517   (and nntp-async-articles (nntp-async-request-group group))
518   (and 
519    nntp-async-number
520    (if (not (or (nntp-async-server-opened)
521                 (nntp-async-open-server)))
522        (progn
523          (message "Can't open second connection to %s" nntp-address)
524          (ding)
525          (setq nntp-async-articles nil)
526          (sit-for 2))
527      (setq nntp-async-articles articles)
528      (setq nntp-async-fetched nil)
529      (save-excursion
530        (set-buffer nntp-async-buffer)
531        (erase-buffer))
532      (nntp-async-send-strings "GROUP" group)
533      t)))
534
535 (defun nntp-list-active-group (group &optional server)
536   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
537
538 (defun nntp-request-group-description (group &optional server)
539   "Get description of GROUP."
540   (if (nntp-possibly-change-server nil server)
541       (prog1
542           (nntp-send-command "^.*\r?\n" "XGTITLE" group)
543         (nntp-decode-text))))
544
545 (defun nntp-close-group (group &optional server)
546   (setq nntp-current-group nil)
547   t)
548
549 (defun nntp-request-list (&optional server)
550   "List active groups."
551   (nntp-possibly-change-server nil server)
552   (prog1
553       (nntp-send-command "^\\.\r?\n" "LIST")
554     (nntp-decode-text)))
555
556 (defun nntp-request-list-newsgroups (&optional server)
557   "List groups."
558   (nntp-possibly-change-server nil server)
559   (prog1
560       (nntp-send-command "^\\.\r?\n" "LIST NEWSGROUPS")
561     (nntp-decode-text)))
562
563 (defun nntp-request-newgroups (date &optional server)
564   "List new groups."
565   (nntp-possibly-change-server nil server)
566   (let* ((date (timezone-parse-date date))
567          (time-string
568           (format "%s%02d%02d %s%s%s"
569                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
570                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
571                   (substring 
572                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
573     (prog1
574         (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
575       (nntp-decode-text))))
576
577 (defun nntp-request-list-distributions (&optional server)
578   "List distributions."
579   (nntp-possibly-change-server nil server)
580   (prog1
581       (nntp-send-command "^\\.\r?\n" "LIST DISTRIBUTIONS")
582     (nntp-decode-text)))
583
584 (defun nntp-request-last (&optional newsgroup server)
585   "Decrease the current article pointer."
586   (nntp-possibly-change-server newsgroup server)
587   (nntp-send-command "^[23].*\r?\n" "LAST"))
588
589 (defun nntp-request-next (&optional newsgroup server)
590   "Advance the current article pointer."
591   (nntp-possibly-change-server newsgroup server)
592   (nntp-send-command "^[23].*\r?\n" "NEXT"))
593
594 (defun nntp-request-post (&optional server)
595   "Post the current buffer."
596   (nntp-possibly-change-server nil server)
597   (if (nntp-send-command "^[23].*\r?\n" "POST")
598       (progn
599         (nntp-encode-text)
600         (nntp-send-region-to-server (point-min) (point-max))
601         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
602         ;;  appended to end of the status message.
603         (nntp-wait-for-response "^[23].*\n"))))
604
605 (defun nntp-request-post-buffer 
606   (post group subject header article-buffer info follow-to respect-poster)
607   "Request a buffer suitable for composing an article.
608 If POST, this is an original article; otherwise it's a followup.
609 GROUP is the group to be posted to, the article should have subject
610 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
611 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
612 post to this group instead.  If RESPECT-POSTER, heed the special
613 \"poster\" value of the Followup-to header."
614   (if (assq 'to-address (nth 5 info))
615       (nnmail-request-post-buffer 
616        post group subject header article-buffer info follow-to respect-poster)
617     (let ((mail-default-headers 
618            (or nntp-news-default-headers mail-default-headers))
619           from date to followup-to newsgroups message-of
620           references distribution message-id)
621       (save-excursion
622         (set-buffer (get-buffer-create "*post-news*"))
623         (news-reply-mode)
624         (if (and (buffer-modified-p)
625                  (> (buffer-size) 0)
626                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
627             ()
628           (erase-buffer)
629           (if post
630               (news-setup nil subject nil group nil)
631             (save-excursion
632               (set-buffer article-buffer)
633               (goto-char (point-min))
634               (narrow-to-region (point-min)
635                                 (progn (search-forward "\n\n") (point)))
636               (setq from (mail-header-from header))
637               (setq date (mail-header-date header))
638               (and from
639                    (let ((stop-pos 
640                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
641                      (setq 
642                       message-of
643                       (concat (if stop-pos (substring from 0 stop-pos) from) 
644                               "'s message of " date))))
645               (setq subject (or subject (mail-header-subject header)))
646               (or (string-match "^[Rr][Ee]:" subject)
647                   (setq subject (concat "Re: " subject)))
648               (setq followup-to (mail-fetch-field "followup-to"))
649               (if (or (null respect-poster) ;Ignore followup-to: field.
650                       (string-equal "" followup-to) ;Bogus header.
651                       (string-equal "poster" followup-to);Poster
652                       (and (eq respect-poster 'ask)
653                            followup-to
654                            (not (y-or-n-p (concat "Followup to " 
655                                                   followup-to "? ")))))
656                   (setq followup-to nil))
657               (setq newsgroups
658                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
659               (setq references (mail-header-references header))
660               (setq distribution (mail-fetch-field "distribution"))
661               ;; Remove bogus distribution.
662               (and (stringp distribution)
663                    (string-match "world" distribution)
664                    (setq distribution nil))
665               (setq message-id (mail-header-id header))
666               (widen))
667             (setq news-reply-yank-from from)
668             (setq news-reply-yank-message-id message-id)
669             (news-setup to subject message-of 
670                         (if (stringp newsgroups) newsgroups "") 
671                         article-buffer)
672             (if (and newsgroups (listp newsgroups))
673                 (progn
674                   (goto-char (point-min))
675                   (while newsgroups
676                     (insert (car (car newsgroups)) ": " 
677                             (cdr (car newsgroups)) "\n")
678                     (setq newsgroups (cdr newsgroups)))))
679             (nnheader-insert-references references message-id)
680             (if distribution
681                 (progn
682                   (mail-position-on-field "Distribution")
683                   (insert distribution)))))
684         (current-buffer)))))
685
686 ;;; Internal functions.
687
688 (defun nntp-send-mode-reader ()
689   "Send the MODE READER command to the nntp server.
690 This function is supposed to be called from `nntp-server-opened-hook'.
691 It will make innd servers spawn an nnrpd process to allow actual article
692 reading."
693   (nntp-send-command "^.*\r?\n" "MODE READER"))
694
695 (defun nntp-send-authinfo ()
696   "Send the AUTHINFO to the nntp server.
697 This function is supposed to be called from `nntp-server-opened-hook'.
698 It will prompt for a password."
699   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
700   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
701                      (read-string "NNTP password: ")))
702
703 (defun nntp-send-authinfo-from-file ()
704   "Send the AUTHINFO to the nntp server.
705 This function is supposed to be called from `nntp-server-opened-hook'.
706 It will prompt for a password."
707   (and (file-exists-p "~/.nntp-authinfo")
708        (save-excursion
709          (set-buffer (get-buffer-create " *tull*"))
710          (insert-file-contents "~/.nntp-authinfo")
711          (goto-char (point-min))
712          (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
713          (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
714                             (buffer-substring (point)
715                                               (progn (end-of-line) (point))))
716          (kill-buffer (current-buffer)))))
717
718 (defun nntp-default-sentinel (proc status)
719   "Default sentinel function for NNTP server process."
720   (let ((servers nntp-server-alist)
721         server)
722     ;; Go through the alist of server names and find the name of the
723     ;; server that the process that sent the signal is connected to.
724     ;; If you get my drift.
725     (if (equal proc nntp-server-process)
726         (setq server nntp-address)
727       (while (and servers 
728                   (not (equal proc (nth 1 (assq 'nntp-server-process
729                                                 (car servers))))))
730         (setq servers (cdr servers)))
731       (setq server (car (car servers))))
732     (and server
733          nntp-warn-about-losing-connection
734          (progn
735            (message "nntp: Connection closed to server %s" server)
736            (ding)))))
737
738 (defun nntp-kill-connection (server)
739   (let ((proc (nth 1 (assq 'nntp-server-process 
740                            (assoc server nntp-server-alist)))))
741     (and proc (delete-process (process-name proc)))
742     (nntp-close-server server)
743     (setq nntp-timeout-servers (cons server nntp-timeout-servers))
744     (setq nntp-status-string 
745           (message "Connection timed out to server %s." server))
746     (ding)
747     (sit-for 1)))
748
749 ;; Encoding and decoding of NNTP text.
750
751 (defun nntp-decode-text ()
752   "Decode text transmitted by NNTP.
753 0. Delete status line.
754 1. Delete `^M' at end of line.
755 2. Delete `.' at end of buffer (end of text mark).
756 3. Delete `.' at beginning of line."
757   (save-excursion
758     (set-buffer nntp-server-buffer)
759     ;; Insert newline at end of buffer.
760     (goto-char (point-max))
761     (or (bolp) (insert "\n"))
762     ;; Delete status line.
763     (goto-char (point-min))
764     (delete-region (point) (progn (forward-line 1) (point)))
765     ;; Delete `^M' at the end of lines.
766     (while (not (eobp))
767       (end-of-line)
768       (and (= (preceding-char) ?\r)
769            (delete-char -1))
770       (forward-line 1))
771     ;; Delete `.' at end of the buffer (end of text mark).
772     (goto-char (point-max))
773     (forward-line -1)
774     (if (looking-at "^\\.\n")
775         (delete-region (point) (progn (forward-line 1) (point))))
776     ;; Replace `..' at beginning of line with `.'.
777     (goto-char (point-min))
778     ;; (replace-regexp "^\\.\\." ".")
779     (while (search-forward "\n.." nil t)
780       (delete-char -1))))
781
782 (defun nntp-encode-text ()
783   "Encode text in current buffer for NNTP transmission.
784 1. Insert `.' at beginning of line.
785 2. Insert `.' at end of buffer (end of text mark)."
786   (save-excursion
787     ;; Insert newline at end of buffer.
788     (goto-char (point-max))
789     (or (bolp) (insert "\n"))
790     ;; Replace `.' at beginning of line with `..'.
791     (goto-char (point-min))
792     ;; (replace-regexp "^\\." "..")
793     (while (search-forward "\n." nil t)
794       (insert "."))
795     ;; Insert `.' at end of buffer (end of text mark).
796     (goto-char (point-max))
797     (insert ".\r\n")))
798
799 \f
800 ;;;
801 ;;; Synchronous Communication with NNTP Server.
802 ;;;
803
804 (defun nntp-send-command (response cmd &rest args)
805   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
806   (save-excursion
807     ;; Clear communication buffer.
808     (set-buffer nntp-server-buffer)
809     (erase-buffer)
810     (apply 'nntp-send-strings-to-server cmd args)
811     (if response
812         (nntp-wait-for-response response)
813       t)))
814
815 (defun nntp-wait-for-response (regexp &optional slow)
816   "Wait for server response which matches REGEXP."
817   (save-excursion
818     (let ((status t)
819           (wait t)
820           (dotnum 0)                    ;Number of "." being displayed.
821           (dotsize                      ;How often "." displayed.
822            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
823       (set-buffer nntp-server-buffer)
824       ;; Wait for status response (RFC977).
825       ;; 1xx - Informative message.
826       ;; 2xx - Command ok.
827       ;; 3xx - Command ok so far, send the rest of it.
828       ;; 4xx - Command was correct, but couldn't be performed for some
829       ;;       reason.
830       ;; 5xx - Command unimplemented, or incorrect, or a serious
831       ;;       program error occurred.
832       (nntp-accept-response)
833       (while wait
834         (goto-char (point-min))
835         (if slow
836             (progn
837               (cond ((re-search-forward "^[23][0-9][0-9]" nil t)
838                      (setq wait nil))
839                     ((re-search-forward "^[45][0-9][0-9]" nil t)
840                      (setq status nil)
841                      (setq wait nil))
842                     (t (nntp-accept-response)))
843               (if (not wait) (delete-region (point-min) 
844                                             (progn (beginning-of-line)
845                                                    (point)))))
846           (cond ((looking-at "[23]")
847                  (setq wait nil))
848                 ((looking-at "[45]")
849                  (setq status nil)
850                  (setq wait nil))
851                 (t (nntp-accept-response)))))
852       ;; Save status message.
853       (end-of-line)
854       (setq nntp-status-string
855             (buffer-substring (point-min) (point)))
856       (if status
857           (progn
858             (setq wait t)
859             (while wait
860               (goto-char (point-max))
861               (forward-line -1)         ;(beginning-of-line)
862               ;;(message (buffer-substring
863               ;;         (point)
864               ;;         (save-excursion (end-of-line) (point))))
865               (if (looking-at regexp)
866                   (setq wait nil)
867                 (if nntp-debug-read
868                     (let ((newnum (/ (buffer-size) dotsize)))
869                       (if (not (= dotnum newnum))
870                           (progn
871                             (setq dotnum newnum)
872                             (message "NNTP: Reading %s"
873                                      (make-string dotnum ?.))))))
874                 (nntp-accept-response)))
875             ;; Remove "...".
876             (if (and nntp-debug-read (> dotnum 0))
877                 (message ""))
878             ;; Successfully received server response.
879             t)))))
880
881 \f
882
883 ;;;
884 ;;; Low-Level Interface to NNTP Server.
885 ;;; 
886
887 (defun nntp-find-group-and-number ()
888   (save-excursion
889     (save-restriction
890       (set-buffer nntp-server-buffer)
891       (narrow-to-region (goto-char (point-min))
892                         (or (search-forward "\n\n" nil t) (point-max)))
893       (goto-char (point-min))
894       ;; We first find the number by looking at the status line.
895       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
896                          (int-to-string 
897                           (buffer-substring (match-beginning 0)
898                                             (match-end 0)))))
899             group newsgroups xref)
900         ;; Then we find the group name.
901         (setq group
902               (cond 
903                ;; If there is only one group in the Newsgroups header,
904                ;; then it seems quite likely that this article comes
905                ;; from that group, I'd say.
906                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
907                      (not (string-match "," newsgroups)))
908                 newsgroups)
909                ;; If there is more than one group in the Newsgroups
910                ;; header, then the Xref header should be filled out.
911                ;; We hazard a guess that the group that has this
912                ;; article number in the Xref header is the one we are
913                ;; looking for.  This might very well be wrong if this
914                ;; article happens to have the same number in several
915                ;; groups, but that's life. 
916                ((and (setq xref (mail-fetch-field "xref"))
917                      (string-match (format "\\([^ :]+\\):%d" number) xref))
918                 (substring xref (match-beginning 1) (match-end 1)))
919                (t "")))
920         (cons group number)))))
921
922 (defun nntp-retrieve-headers-with-xover (sequence &optional fetch-old)
923   (erase-buffer)
924   (cond 
925
926    ;; This server does not talk NOV.
927    ((not nntp-server-xover)
928     nil)
929
930    ;; We don't care about gaps.
931    ((or (not nntp-nov-gap)
932         fetch-old)
933     (nntp-send-xover-command 
934      (if fetch-old
935          (if (numberp fetch-old) 
936              (max 1 (- (car sequence) fetch-old)) 
937            1)
938        (car sequence))
939      (nntp-last-element sequence) 'wait)
940
941     (goto-char (point-min))
942     (if (looking-at "[1-5][0-9][0-9] ")
943         (delete-region (point) (progn (forward-line 1) (point))))
944     (while (search-forward "\r" nil t)
945       (replace-match "" t t))
946     (goto-char (point-max))
947     (forward-line -1)
948     (if (looking-at "\\.")
949         (delete-region (point) (progn (forward-line 1) (point)))))
950
951    ;; We do it the hard way.  For each gap, an XOVER command is sent
952    ;; to the server.  We do not wait for a reply from the server, we
953    ;; just send them off as fast as we can.  That means that we have
954    ;; to count the number of responses we get back to find out when we
955    ;; have gotten all we asked for.
956    ((numberp nntp-nov-gap)
957     (let ((count 0)
958           (received 0)
959           (last-point (point-min))
960           (buf (current-buffer))
961           first)
962       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
963       ;; that means that the server does not understand XOVER, but we
964       ;; won't know that until we try.
965       (while (and nntp-server-xover sequence)
966         (setq first (car sequence))
967         ;; Search forward until we find a gap, or until we run out of
968         ;; articles. 
969         (while (and (cdr sequence) 
970                     (< (- (nth 1 sequence) (car sequence)) nntp-nov-gap))
971           (setq sequence (cdr sequence)))
972
973         (if (not (nntp-send-xover-command first (car sequence)))
974             ()
975           (setq sequence (cdr sequence)
976                 count (1+ count))
977
978           ;; Every 400 requests we have to read the stream in
979           ;; order to avoid deadlocks.
980           (if (or (null sequence)       ;All requests have been sent.
981                   (zerop (% count nntp-maximum-request)))
982               (progn
983                 (accept-process-output)
984                 ;; On some Emacs versions the preceding function has
985                 ;; a tendency to change the buffer. Perhaps. It's
986                 ;; quite difficult to reporduce, because it only
987                 ;; seems to happen once in a blue moon. 
988                 (set-buffer buf) 
989                 (while (progn
990                          (goto-char last-point)
991                          ;; Count replies.
992                          (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
993                            (setq received (1+ received)))
994                          (setq last-point (point))
995                          (< received count))
996                   (accept-process-output)
997                   (set-buffer buf))))))
998
999       (if (not nntp-server-xover)
1000           ()
1001         ;; Wait for the reply from the final command.
1002         (goto-char (point-max))
1003         (re-search-backward "^[0-9][0-9][0-9] " nil t)
1004         (if (looking-at "^[23]")
1005             (while (progn
1006                      (goto-char (point-max))
1007                      (forward-line -1)
1008                      (not (looking-at "^\\.\r?\n")))
1009               (nntp-accept-response)))
1010         
1011         ;; We remove any "." lines and status lines.
1012         (goto-char (point-min))
1013         (while (search-forward "\r" nil t)
1014           (delete-char -1))
1015         (goto-char (point-min))
1016         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")))))
1017
1018   nntp-server-xover)
1019
1020 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1021   (let ((range (format "%d-%d" beg end)))
1022     (if (stringp nntp-server-xover)
1023         ;; If `nntp-server-xover' is a string, then we just send this
1024         ;; command.
1025         (if wait-for-reply
1026             (nntp-send-command "^\\.\r?\n" nntp-server-xover range)
1027           ;; We do not wait for the reply.
1028           (progn
1029             (nntp-send-strings-to-server nntp-server-xover range)
1030             t))
1031       (let ((commands nntp-xover-commands))
1032         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1033         ;; We try them all until we get at positive response. 
1034         (while (and commands (eq nntp-server-xover 'try))
1035           (nntp-send-command "^\\.\r?\n" (car commands) range)
1036           (save-excursion
1037             (set-buffer nntp-server-buffer)
1038             (goto-char (point-min))
1039             (and (looking-at "[23]") (setq nntp-server-xover (car commands))))
1040           (setq commands (cdr commands)))
1041         ;; If none of the commands worked, we disable XOVER.
1042         (if (eq nntp-server-xover 'try)
1043             (save-excursion
1044               (set-buffer nntp-server-buffer)
1045               (erase-buffer)
1046               (setq nntp-server-xover nil)))
1047         nntp-server-xover))))
1048
1049 (defun nntp-send-strings-to-server (&rest strings)
1050   "Send list of STRINGS to news server as command and its arguments."
1051   (let ((cmd (concat (mapconcat 'identity strings " ") "\r\n")))
1052     ;; We open the nntp server if it is down.
1053     (or (nntp-server-opened nntp-current-server)
1054         (nntp-open-server nntp-current-server)
1055         (error (nntp-status-message)))
1056     ;; Send the strings.
1057     (process-send-string nntp-server-process cmd)))
1058
1059 (defun nntp-send-region-to-server (begin end)
1060   "Send current buffer region (from BEGIN to END) to news server."
1061   (save-excursion
1062     ;; We have to work in the buffer associated with NNTP server
1063     ;;  process because of NEmacs hack.
1064     (copy-to-buffer nntp-server-buffer begin end)
1065     (set-buffer nntp-server-buffer)
1066     (setq begin (point-min))
1067     (setq end (point-max))
1068     ;; `process-send-region' does not work if text to be sent is very
1069     ;;  large. I don't know maximum size of text sent correctly.
1070     (let ((last nil)
1071           (size 100))                   ;Size of text sent at once.
1072       (save-restriction
1073         (narrow-to-region begin end)
1074         (goto-char begin)
1075         (while (not (eobp))
1076           ;;(setq last (min end (+ (point) size)))
1077           ;; NEmacs gets confused if character at `last' is Kanji.
1078           (setq last (save-excursion
1079                        (goto-char (min end (+ (point) size)))
1080                        (or (eobp) (forward-char 1)) ;Adjust point
1081                        (point)))
1082           (process-send-region nntp-server-process (point) last)
1083           ;; I don't know whether the next codes solve the known
1084           ;;  problem of communication error of GNU Emacs.
1085           (accept-process-output)
1086           ;;(sit-for 0)
1087           (goto-char last))))
1088     ;; We cannot erase buffer, because reply may be received.
1089     (delete-region begin end)))
1090
1091 (defun nntp-open-server-semi-internal (server &optional service)
1092   "Open SERVER.
1093 If SERVER is nil, use value of environment variable `NNTPSERVER'.
1094 If SERVICE, this this as the port number."
1095   (let ((server (or server (getenv "NNTPSERVER")))
1096         (status nil)
1097         (timer 
1098          (and nntp-connection-timeout 
1099               (cond
1100                ((fboundp 'run-at-time)
1101                 (run-at-time nntp-connection-timeout
1102                              nil 'nntp-kill-connection server))
1103                ((fboundp 'start-itimer)
1104                 ;; Not sure if this will work or not, only one way to
1105                 ;; find out
1106                 (eval '(start-itimer "nntp-timeout"
1107                                      (lambda ()
1108                                        (nntp-kill-connection server))
1109                                      nntp-connection-timeout nil)))))))
1110     (save-excursion
1111       (set-buffer nntp-server-buffer)
1112       (setq nntp-status-string "")
1113       (message "nntp: Connecting to server on %s..." server)
1114       (cond ((and server (nntp-open-server-internal server service))
1115              (setq nntp-address server)
1116              (setq status
1117                    (condition-case nil
1118                        (nntp-wait-for-response "^[23].*\r?\n" 'slow)
1119                      (error nil)
1120                      (quit nil)))
1121              (or status (nntp-close-server-internal server))
1122              (and nntp-server-process
1123                   (progn
1124                     (set-process-sentinel 
1125                      nntp-server-process 'nntp-default-sentinel)
1126                     ;; You can send commands at startup like AUTHINFO here.
1127                     ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
1128                     (run-hooks 'nntp-server-opened-hook))))
1129             ((null server)
1130              (setq nntp-status-string "NNTP server is not specified."))
1131             (t                          ; We couldn't open the server.
1132              (setq nntp-status-string 
1133                    (buffer-substring (point-min) (point-max)))
1134              (setq nntp-timeout-servers (cons server nntp-timeout-servers))))
1135       (and timer (cancel-timer timer))
1136       (message "")
1137       (or status
1138           (setq nntp-current-server nil
1139                 nntp-async-number nil))
1140       status)))
1141
1142 (defun nntp-open-server-internal (server &optional service)
1143   "Open connection to news server on SERVER by SERVICE (default is nntp)."
1144   (let (proc)
1145     (save-excursion
1146       ;; Use TCP/IP stream emulation package if needed.
1147       (or (fboundp 'open-network-stream)
1148           (require 'tcp))
1149       ;; Initialize communication buffer.
1150       (nnheader-init-server-buffer)
1151       (set-buffer nntp-server-buffer)
1152       (if (setq proc
1153                 (condition-case nil
1154                     (funcall nntp-open-server-function server)
1155                   (error nil)))
1156           (progn
1157             (setq nntp-server-process proc)
1158             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
1159             (process-kill-without-query proc)
1160             (setq nntp-address server)
1161             ;; It is possible to change kanji-fileio-code in this hook.
1162             (run-hooks 'nntp-server-hook)
1163             nntp-server-process)))))
1164
1165 (defun nntp-open-network-stream (server)
1166   (open-network-stream 
1167    "nntpd" nntp-server-buffer server nntp-port-number))
1168
1169 (defun nntp-open-rlogin (server)
1170   (let ((proc (start-process "nntpd" nntp-server-buffer "rsh" server)))
1171     (process-send-string proc (mapconcat 'identity nntp-rlogin-parameters
1172                                          " "))
1173     (process-send-string proc "\n")))
1174
1175 (defun nntp-telnet-to-machine ()
1176   (let (b)
1177     (telnet "localhost")
1178     (goto-char (point-min))
1179     (while (not (re-search-forward "^login: *" nil t))
1180       (sit-for 1)
1181       (goto-char (point-min)))
1182     (goto-char (point-max))
1183     (insert "larsi")
1184     (telnet-send-input)
1185     (setq b (point))
1186     (while (not (re-search-forward ">" nil t))
1187       (sit-for 1)
1188       (goto-char b))
1189     (goto-char (point-max))
1190     (insert "ls")
1191     (telnet-send-input)))
1192
1193 (defun nntp-close-server-internal (&optional server)
1194   "Close connection to news server."
1195   (nntp-possibly-change-server nil server)
1196   (if nntp-server-process
1197       (delete-process nntp-server-process))
1198   (setq nntp-server-process nil)
1199   (setq nntp-address ""))
1200
1201 (defun nntp-accept-response ()
1202   "Read response of server.
1203 It is well-known that the communication speed will be much improved by
1204 defining this function as macro."
1205   ;; To deal with server process exiting before
1206   ;;  accept-process-output is called.
1207   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
1208   ;; This is a copy of `nntp-default-sentinel'.
1209   (let ((buf (current-buffer)))
1210     (prog1
1211         (if (or (not nntp-server-process)
1212                 (not (memq (process-status nntp-server-process) '(open run))))
1213             (error "nntp: Process connection closed; %s" (nntp-status-message))
1214           (if nntp-buggy-select
1215               (progn
1216                 ;; We cannot use `accept-process-output'.
1217                 ;; Fujitsu UTS requires messages during sleep-for.
1218                 ;; I don't know why.
1219                 (message "NNTP: Reading...")
1220                 (sleep-for 1)
1221                 (message ""))
1222             (condition-case errorcode
1223                 (accept-process-output nntp-server-process)
1224               (error
1225                (cond ((string-equal "select error: Invalid argument" 
1226                                     (nth 1 errorcode))
1227                       ;; Ignore select error.
1228                       nil)
1229                      (t
1230                       (signal (car errorcode) (cdr errorcode))))))))
1231       (set-buffer buf))))
1232
1233 (defun nntp-last-element (list)
1234   "Return last element of LIST."
1235   (while (cdr list)
1236     (setq list (cdr list)))
1237   (car list))
1238
1239 (defun nntp-possibly-change-server (newsgroup server)
1240   ;; We see whether it is necessary to change newsgroup.
1241   (and newsgroup 
1242        (not (equal newsgroup nntp-current-group))
1243        (nntp-request-group newsgroup server)))
1244
1245 (defun nntp-try-list-active (group)
1246   (nntp-list-active-group group)
1247   (save-excursion
1248     (set-buffer nntp-server-buffer)
1249     (goto-char (point-min))
1250     (cond ((looking-at "5[0-9]+")
1251            (setq nntp-server-list-active-group nil))
1252           (t
1253            (setq nntp-server-list-active-group t)))))
1254
1255 (defun nntp-async-server-opened ()
1256   (and nntp-async-process
1257        (memq (process-status nntp-async-process) '(open run))))
1258
1259 (defun nntp-async-open-server ()
1260   (save-excursion
1261     (set-buffer (generate-new-buffer " *async-nntp*"))
1262     (setq nntp-async-buffer (current-buffer))
1263     (buffer-disable-undo (current-buffer)))
1264   (let ((nntp-server-process nil)
1265         (nntp-server-buffer nntp-async-buffer))
1266     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1267     (if (not (setq nntp-async-process nntp-server-process))
1268         (progn
1269           (setq nntp-async-number nil))
1270       (set-process-buffer nntp-async-process nntp-async-buffer))))
1271
1272 (defun nntp-async-fetch-articles (article)
1273   (if (stringp article)
1274       ()
1275     (let ((articles (cdr (memq (assq article nntp-async-articles)
1276                                nntp-async-articles)))
1277           (max (cond ((numberp nntp-async-number)
1278                       nntp-async-number) 
1279                      ((eq nntp-async-number t)
1280                       (length nntp-async-articles))
1281                      (t 0)))
1282           nart)
1283       (while (and (>= (setq max (1- max)) 0)
1284                   articles)
1285         (or (memq (setq nart (car (car articles))) nntp-async-fetched)
1286             (progn
1287               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1288               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1289         (setq articles (cdr articles))))))
1290
1291 (defun nntp-async-send-strings (&rest strings)
1292   (let ((cmd (concat (mapconcat 'identity strings " ") "\r\n")))
1293     (or (nntp-async-server-opened)
1294         (nntp-async-open-server)
1295         (error (nntp-status-message)))
1296     (process-send-string nntp-async-process cmd)))
1297
1298 (defun nntp-async-request-group (group)
1299   (if (equal group nntp-current-group)
1300       ()
1301     (let ((asyncs (assoc group nntp-async-group-alist)))
1302       ;; A new group has been selected, so we push the current state
1303       ;; of async articles on an alist, and pull the old state off.
1304       (setq nntp-async-group-alist 
1305             (cons (list nntp-current-group
1306                         nntp-async-articles nntp-async-fetched
1307                         nntp-async-process)
1308                   (delq asyncs nntp-async-group-alist)))
1309       (and asyncs
1310            (progn
1311              (setq nntp-async-articles (nth 1 asyncs))
1312              (setq nntp-async-fetched (nth 2 asyncs))
1313              (setq nntp-async-process (nth 3 asyncs)))))))
1314
1315 (provide 'nntp)
1316
1317 ;;; nntp.el ends here