*** empty log message ***
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- NNTP (RFC977) Interface for GNU Emacs
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 'nnheader)
30
31 (eval-and-compile
32   (autoload 'news-setup "rnewspost")
33   (autoload 'news-reply-mode "rnewspost")
34   (autoload 'nnmail-request-post-buffer "nnmail")
35   (autoload 'cancel-timer "timer"))
36
37 (defvar nntp-server-hook nil
38   "Hooks for the NNTP server.
39 If the kanji code of the NNTP server is different from the local kanji
40 code, the correct kanji code of the buffer associated with the NNTP
41 server must be specified as follows:
42
43 \(setq nntp-server-hook
44       (function
45        (lambda ()
46          ;; Server's Kanji code is EUC (NEmacs hack).
47          (make-local-variable 'kanji-fileio-code)
48          (setq kanji-fileio-code 0))))
49
50 If you'd like to change something depending on the server in this
51 hook, use the variable `nntp-address'.")
52
53 (defvar nntp-server-opened-hook nil
54   "Hook used for sending commands to the server at startup.  The
55 default value is `nntp-send-mode-reader', whick makes an innd server
56 spawn an nnrpd server.  Another useful function to put in this hook
57 might be `nntp-send-authinfo', which will prompt for a password to
58 allow posting from the server.  Note that this is only necessary to do
59 on servers that use strict access control.")
60 (add-hook 'nntp-server-opened-hook 'nntp-send-mode-reader)
61
62 (defvar nntp-address nil
63   "The name of the NNTP server.")
64
65 (defvar nntp-port-number "nntp"
66   "Port number to connect to.")
67
68 (defvar nntp-large-newsgroup 50
69   "The number of the articles which indicates a large newsgroup.
70 If the number of the articles is greater than the value, verbose
71 messages will be shown to indicate the current status.")
72
73 (defvar nntp-buggy-select (memq system-type '(fujitsu-uts))
74   "t if your select routine is buggy.
75 If the select routine signals error or fall into infinite loop while
76 waiting for the server response, the variable must be set to t.  In
77 case of Fujitsu UTS, it is set to T since `accept-process-output'
78 doesn't work properly.")
79
80 (defvar nntp-maximum-request 400
81   "The maximum number of the requests sent to the NNTP server at one time.
82 If Emacs hangs up while retrieving headers, set the variable to a
83 lower value.")
84
85 (defvar nntp-debug-read 10000
86   "Display '...' every 10Kbytes of a message being received if it is non-nil.
87 If it is a number, dots are displayed per the number.")
88
89 (defvar nntp-nov-is-evil nil
90   "If non-nil, nntp will never attempt to use XOVER when talking to the server.")
91
92 (defvar nntp-xover-commands '("XOVER" "XOVERVIEW")
93   "List of strings that are used as commands to fetch NOV lines from a server.
94 The strings are tried in turn until a positive response is gotten. If
95 none of the commands are successful, nntp will just grab headers one
96 by one.")
97
98 (defvar nntp-connection-timeout nil
99   "Number of seconds to wait before an nntp connection times out.
100 If this variable is nil, which is the default, no timers are set.")
101
102 (defvar nntp-news-default-headers nil
103   "If non-nil, override `mail-default-headers' when posting news.")
104
105 \f
106
107 (defconst nntp-version "nntp 4.0"
108   "Version numbers of this version of NNTP.")
109
110 (defvar nntp-server-buffer nil
111   "Buffer associated with the NNTP server process.")
112
113 (defvar nntp-server-process nil
114   "The NNTP server process.
115 You'd better not use this variable in NNTP front-end program, but
116 instead use `nntp-server-buffer'.")
117
118 (defvar nntp-status-string nil
119   "Save the server response message.
120 You'd better not use this variable in NNTP front-end program but
121 instead call function `nntp-status-message' to get status message.")
122
123 (defvar nntp-server-xover t)
124 (defvar nntp-server-list-active-group t)
125 (defvar nntp-current-group "")
126
127 \f
128 (defvar nntp-current-server nil)
129 (defvar nntp-server-alist nil)
130 (defvar nntp-server-variables 
131   (list
132    (list 'nntp-server-hook nntp-server-hook)
133    (list 'nntp-server-opened-hook nntp-server-opened-hook)
134    (list 'nntp-port-number nntp-port-number)
135    (list 'nntp-address nntp-address)
136    (list 'nntp-large-newsgroup nntp-large-newsgroup)
137    (list 'nntp-buggy-select nntp-buggy-select)
138    (list 'nntp-maximum-request nntp-maximum-request)
139    (list 'nntp-debug-read nntp-debug-read)
140    (list 'nntp-nov-is-evil nntp-nov-is-evil)
141    (list 'nntp-xover-commands nntp-xover-commands)
142    (list 'nntp-connection-timeout nntp-connection-timeout)
143    (list 'nntp-news-default-headers nntp-news-default-headers)
144    '(nntp-server-process nil)
145    '(nntp-status-string nil)
146    '(nntp-server-xover t)
147    '(nntp-server-list-active-group t)
148    '(nntp-current-group "")))
149
150 \f
151 ;;; Interface funtions.
152
153 (defun nntp-retrieve-headers (sequence &optional newsgroup server)
154   "Retrieve the headers to the articles in SEQUENCE."
155   (nntp-possibly-change-server newsgroup server)
156   (save-excursion
157     (set-buffer nntp-server-buffer)
158     (erase-buffer)
159     (if (and (not gnus-nov-is-evil) 
160              (not nntp-nov-is-evil)
161              (nntp-retrieve-headers-with-xover sequence))
162         'nov
163       (let ((number (length sequence))
164             (count 0)
165             (received 0)
166             (last-point (point-min)))
167         ;; Send HEAD command.
168         (while sequence
169           (nntp-send-strings-to-server "HEAD" (car sequence))
170           (setq sequence (cdr sequence))
171           (setq count (1+ count))
172           ;; Every 400 header requests we have to read stream in order
173           ;;  to avoid deadlock.
174           (if (or (null sequence)       ;All requests have been sent.
175                   (zerop (% count nntp-maximum-request)))
176               (progn
177                 (accept-process-output)
178                 (while (progn
179                          (goto-char last-point)
180                          ;; Count replies.
181                          (while (re-search-forward "^[0-9]" nil t)
182                            (setq received (1+ received)))
183                          (setq last-point (point))
184                          (< received count))
185                   ;; If number of headers is greater than 100, give
186                   ;;  informative messages.
187                   (and (numberp nntp-large-newsgroup)
188                        (> number nntp-large-newsgroup)
189                        (zerop (% received 20))
190                        (message "NNTP: Receiving headers... %d%%"
191                                 (/ (* received 100) number)))
192                   (nntp-accept-response)))))
193         ;; Wait for text of last command.
194         (goto-char (point-max))
195         (re-search-backward "^[0-9]" nil t)
196         (if (looking-at "^[23]")
197             (while (progn
198                      (goto-char (- (point-max) 3))
199                      (not (looking-at "^\\.\r$")))
200               (nntp-accept-response)))
201         (and (numberp nntp-large-newsgroup)
202              (> number nntp-large-newsgroup)
203              (message "NNTP: Receiving headers... done"))
204
205         ;; Now all of replies are received.
206         (setq received number)
207         ;; First, fold continuation lines.
208         (goto-char (point-min))
209         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
210           (replace-match " " t t))
211         ;; Remove all "\r"'s
212         (goto-char (point-min))
213         (while (re-search-forward "\r" nil t)
214           (replace-match "" t t))
215         'headers))))
216
217 (defun nntp-open-server (server &optional defs)
218   (nnheader-init-server-buffer)
219   (if (nntp-server-opened server)
220       t
221     (or (assq 'nntp-address defs)
222         (setq defs (append defs (list (list 'nntp-address server)))))
223     (if (and nntp-current-server
224              (not (equal server nntp-current-server)))
225         (setq nntp-server-alist 
226               (cons (list nntp-current-server
227                           (nnheader-save-variables nntp-server-variables))
228                     nntp-server-alist)))
229     (let ((state (assoc server nntp-server-alist)))
230       (if state 
231           (progn
232             (nnheader-restore-variables (nth 1 state))
233             (setq nntp-server-alist (delq state nntp-server-alist)))
234         (nnheader-set-init-variables nntp-server-variables defs)))
235     (setq nntp-current-server server)
236     (nntp-open-server-semi-internal nntp-address)))
237
238 (defun nntp-close-server (&optional server)
239   "Close connection to SERVER."
240   (nntp-possibly-change-server nil server)
241   (unwind-protect
242       (progn
243         ;; Un-set default sentinel function before closing connection.
244         (and nntp-server-process
245              (eq 'nntp-default-sentinel
246                  (process-sentinel nntp-server-process))
247              (set-process-sentinel nntp-server-process nil))
248         ;; We cannot send QUIT command unless the process is running.
249         (if (nntp-server-opened)
250             (nntp-send-command nil "QUIT")))
251     (nntp-close-server-internal server)))
252
253 (fset 'nntp-request-quit (symbol-function 'nntp-close-server))
254
255 (defun nntp-request-close ()
256   "Close all server connections."
257   (let (proc)
258     (while nntp-server-alist
259       (setq proc (nth 1 (assq 'nntp-server-process (car nntp-server-alist))))
260       (and proc (delete-process proc))
261       (setq nntp-server-alist (cdr nntp-server-alist)))
262     (setq nntp-current-server nil)))
263
264 (defun nntp-server-opened (&optional server)
265   "Say whether a connection to SERVER has been opened."
266   (and (equal server nntp-current-server)
267        nntp-server-buffer
268        (buffer-name nntp-server-buffer)
269        nntp-server-process
270        (memq (process-status nntp-server-process) '(open run))))
271
272 (defun nntp-status-message (&optional server)
273   "Return server status as a string."
274   (if (and nntp-status-string
275            ;; NNN MESSAGE
276            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
277                          nntp-status-string))
278       (substring nntp-status-string (match-beginning 1) (match-end 1))
279     ;; Empty message if nothing.
280     nntp-status-string))
281
282 (defun nntp-request-article (id &optional newsgroup server buffer)
283   "Request article ID (message-id or number)."
284   (nntp-possibly-change-server newsgroup server)
285   (unwind-protect
286       (progn
287         (if buffer (set-process-buffer nntp-server-process buffer))
288         (let ((nntp-server-buffer (or buffer nntp-server-buffer))
289               (id (or (and (numberp id) (int-to-string id)) id)))
290           ;; If NEmacs, end of message may look like: "\256\215" (".^M")
291           (prog1
292               (nntp-send-command "^\\.\r$" "ARTICLE" id)
293             (nntp-decode-text))))
294     (if buffer (set-process-buffer nntp-server-process nntp-server-buffer))))
295
296 (defun nntp-request-body (id &optional newsgroup server)
297   "Request body of article ID (message-id or number)."
298   (nntp-possibly-change-server newsgroup server)
299   (prog1
300       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
301       (nntp-send-command
302        "^\\.\r$" "BODY" (or (and (numberp id) (int-to-string id)) id))
303     (nntp-decode-text)))
304
305 (defun nntp-request-head (id &optional newsgroup server)
306   "Request head of article ID (message-id or number)."
307   (nntp-possibly-change-server newsgroup server)
308   (prog1
309       (nntp-send-command 
310        "^\\.\r$" "HEAD" (or (and (numberp id) (int-to-string id)) id))
311     (nntp-decode-text)))
312
313 (defun nntp-request-stat (id &optional newsgroup server)
314   "Request STAT of article ID (message-id or number)."
315   (nntp-possibly-change-server newsgroup server)
316   (nntp-send-command 
317    "^[23].*\r$" "STAT" (or (and (numberp id) (int-to-string id)) id)))
318
319 (defun nntp-request-group (group &optional server dont-check)
320   "Select GROUP."
321   (if dont-check
322       (nntp-send-command "^.*\r$" "GROUP" group)
323     (if nntp-server-list-active-group
324         (save-excursion
325           (nntp-list-active-group group server)
326           (set-buffer nntp-server-buffer)
327           (goto-char (point-min))
328           ;; We look at the output from `nntp-list-active-group' to
329           ;; see whether the server supports this command.  If it
330           ;; does, we transform the output.  
331           (cond ((looking-at "2[0-9]+")
332                  (forward-line 1)
333                  (if (looking-at "[^ ]+[ \t]+\\([0-9]\\)[ \t]+\\([0-9]\\)")
334                      (let ((end (progn (goto-char (match-beginning 1))
335                                        (read (current-buffer))))
336                            (beg (read (current-buffer))))
337                        (and (> beg end)
338                             (setq end 0
339                                   beg 0))
340                        (erase-buffer)
341                        (insert (format "211 %s %d %d %d\n"
342                                        group (max (- (1+ end) beg) 0)
343                                        beg end)))))
344                 ;; The server does not support the command.
345                 ((looking-at "5[0-9]+")
346                  (setq nntp-server-list-active-group nil)
347                  (nntp-send-command "^.*\r$" "GROUP" group))
348                 ;; The server supports it, but the group doesn't
349                 ;; exist. 
350                 ((looking-at "4[0-9]+")
351                  (erase-buffer)
352                  nil)))
353       (nntp-send-command "^.*\r$" "GROUP" group))))
354
355 (defun nntp-list-active-group (group &optional server)
356   (nntp-send-command "^.*\r$" "LIST ACTIVE" group))
357
358 (defun nntp-request-group-description (group &optional server)
359   "Get description of GROUP."
360   (if (nntp-possibly-change-server nil server)
361       (prog1
362           (nntp-send-command "^.*\r$" "XGTITLE" group)
363         (nntp-decode-text))))
364
365 (defun nntp-close-group (group &optional server)
366   t)
367
368 (defun nntp-request-list (&optional server)
369   "List active groups."
370   (nntp-possibly-change-server nil server)
371   (prog1
372       (nntp-send-command "^\\.\r$" "LIST")
373     (nntp-decode-text)))
374
375 (defun nntp-request-list-newsgroups (&optional server)
376   "List groups."
377   (nntp-possibly-change-server nil server)
378   (prog1
379       (nntp-send-command "^\\.\r$" "LIST NEWSGROUPS")
380     (nntp-decode-text)))
381
382 (defun nntp-request-newgroups (date &optional server)
383   "List new groups."
384   (nntp-possibly-change-server nil server)
385   (let* ((date (timezone-parse-date date))
386          (time-string
387           (format "%s%02d%02d %s%s%s"
388                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
389                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
390                   (substring 
391                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
392     (prog1
393         (nntp-send-command "^\\.\r$" "NEWGROUPS" time-string)
394       (nntp-decode-text))))
395
396 (defun nntp-request-list-distributions (&optional server)
397   "List distributions."
398   (nntp-possibly-change-server nil server)
399   (prog1
400       (nntp-send-command "^\\.\r$" "LIST DISTRIBUTIONS")
401     (nntp-decode-text)))
402
403 (defun nntp-request-last (&optional newsgroup server)
404   "Decrease the current article pointer."
405   (nntp-possibly-change-server newsgroup server)
406   (nntp-send-command "^[23].*\r$" "LAST"))
407
408 (defun nntp-request-next (&optional newsgroup server)
409   "Advance the current article pointer."
410   (nntp-possibly-change-server newsgroup server)
411   (nntp-send-command "^[23].*\r$" "NEXT"))
412
413 (defun nntp-request-post (&optional server)
414   "Post the current buffer."
415   (nntp-possibly-change-server nil server)
416   (if (nntp-send-command "^[23].*\r$" "POST")
417       (progn
418         (nntp-encode-text)
419         (nntp-send-region-to-server (point-min) (point-max))
420         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
421         ;;  appended to end of the status message.
422         (nntp-wait-for-response "^[23].*$"))))
423
424 (defun nntp-request-post-buffer 
425   (post group subject header article-buffer info follow-to respect-poster)
426   "Request a buffer suitable for composing an article.
427 If POST, this is an original article; otherwise it's a followup.
428 GROUP is the group to be posted to, the article should have subject
429 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
430 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
431 post to this group instead.  If RESPECT-POSTER, heed the special
432 \"poster\" value of the Followup-to header."
433   (if (assq 'to-address (nth 4 info))
434       (nnmail-request-post-buffer 
435        post group subject header article-buffer info follow-to respect-poster)
436     (let ((mail-default-headers 
437            (or nntp-news-default-headers mail-default-headers))
438           from date to followup-to newsgroups message-of
439           references distribution message-id)
440       (save-excursion
441         (set-buffer (get-buffer-create "*post-news*"))
442         (news-reply-mode)
443         (if (and (buffer-modified-p)
444                  (> (buffer-size) 0)
445                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
446             ()
447           (erase-buffer)
448           (if post
449               (news-setup nil subject nil group nil)
450             (save-excursion
451               (set-buffer article-buffer)
452               (goto-char (point-min))
453               (narrow-to-region (point-min)
454                                 (progn (search-forward "\n\n") (point)))
455               (setq from (header-from header))
456               (setq date (header-date header))
457               (and from
458                    (let ((stop-pos 
459                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
460                      (setq 
461                       message-of
462                       (concat (if stop-pos (substring from 0 stop-pos) from) 
463                               "'s message of " date))))
464               (setq subject (or subject (header-subject header)))
465               (or (string-match "^[Rr][Ee]:" subject)
466                   (setq subject (concat "Re: " subject)))
467               (setq followup-to (mail-fetch-field "followup-to"))
468               (if (or (null respect-poster) ;Ignore followup-to: field.
469                       (string-equal "" followup-to) ;Bogus header.
470                       (string-equal "poster" followup-to)) ;Poster
471                   (setq followup-to nil))
472               (setq newsgroups
473                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
474               (setq references (header-references header))
475               (setq distribution (mail-fetch-field "distribution"))
476               ;; Remove bogus distribution.
477               (and (stringp distribution)
478                    (string-match "world" distribution)
479                    (setq distribution nil))
480               (setq message-id (header-id header))
481               (widen))
482             (setq news-reply-yank-from from)
483             (setq news-reply-yank-message-id message-id)
484             (news-setup to subject message-of 
485                         (if (stringp newsgroups) newsgroups "") 
486                         article-buffer)
487             (if (and newsgroups (listp newsgroups))
488                 (progn
489                   (goto-char (point-min))
490                   (while newsgroups
491                     (insert (car (car newsgroups)) ": " 
492                             (cdr (car newsgroups)) "\n")
493                     (setq newsgroups (cdr newsgroups)))))
494             ;; Fold long references line to follow RFC1036.
495             (mail-position-on-field "References")
496             (let ((begin (- (point) (length "References: ")))
497                   (fill-column 79)
498                   (fill-prefix "\t"))
499               (if references (insert references))
500               (if (and references message-id) (insert " "))
501               (if message-id (insert message-id))
502               ;; The region must end with a newline to fill the region
503               ;; without inserting extra newline.
504               (fill-region-as-paragraph begin (1+ (point))))
505             (if distribution
506                 (progn
507                   (mail-position-on-field "Distribution")
508                   (insert distribution)))))
509         (current-buffer)))))
510
511 ;;; Internal functions.
512
513 (defun nntp-send-mode-reader ()
514   "Send the MODE READER command to the nntp server.
515 This function is supposed to be called from `nntp-server-opened-hook'.
516 It will make innd servers spawn an nnrpd process to allow actual article
517 reading."
518   (nntp-send-command "^.*\r$" "MODE READER"))
519
520 (defun nntp-send-authinfo ()
521   "Send the AUTHINFO to the nntp server.
522 This function is supposed to be called from `nntp-server-opened-hook'.
523 It will prompt for a password."
524   (nntp-send-command "^.*\r$" "AUTHINFO USER" (user-login-name))
525   (nntp-send-command "^.*\r$" "AUTHINFO PASS" (read-string "NNTP password: ")))
526
527 (defun nntp-default-sentinel (proc status)
528   "Default sentinel function for NNTP server process."
529   (let ((servers nntp-server-alist))
530     ;; Go through the alist of server names and find the name of the
531     ;; server that the process that sent the signal is connected to.
532     ;; If you get my drift.
533     (while (and servers 
534                 (not (equal proc (nth 1 (assq 'nntp-server-process
535                                               (car servers))))))
536       (setq servers (cdr servers)))
537     (message "nntp: Connection closed to server %s." 
538              (or (car (car servers)) "(none)"))
539     (ding)))
540
541 (defun nntp-kill-connection (server)
542   (let ((proc (nth 1 (assq 'nntp-server-process 
543                            (assoc server nntp-server-alist)))))
544     (and proc (delete-process (process-name proc)))
545     (nntp-close-server server)
546     (setq nntp-status-string 
547           (message "Connection timed out to server %s." server))
548     (ding)))
549
550 ;; Encoding and decoding of NNTP text.
551
552 (defun nntp-decode-text ()
553   "Decode text transmitted by NNTP.
554 0. Delete status line.
555 1. Delete `^M' at end of line.
556 2. Delete `.' at end of buffer (end of text mark).
557 3. Delete `.' at beginning of line."
558   (save-excursion
559     (set-buffer nntp-server-buffer)
560     ;; Insert newline at end of buffer.
561     (goto-char (point-max))
562     (or (bolp) (insert "\n"))
563     ;; Delete status line.
564     (goto-char (point-min))
565     (delete-region (point) (progn (forward-line 1) (point)))
566     ;; Delete `^M' at the end of lines.
567     (while (not (eobp))
568       (end-of-line)
569       (and (= (preceding-char) ?\r)
570            (delete-char -1))
571       (forward-line 1))
572     ;; Delete `.' at end of the buffer (end of text mark).
573     (goto-char (point-max))
574     (forward-line -1)
575     (if (looking-at "^\\.$")
576         (delete-region (point) (progn (forward-line 1) (point))))
577     ;; Replace `..' at beginning of line with `.'.
578     (goto-char (point-min))
579     ;; (replace-regexp "^\\.\\." ".")
580     (while (search-forward "\n.." nil t)
581       (delete-char -1))))
582
583 (defun nntp-encode-text ()
584   "Encode text in current buffer for NNTP transmission.
585 1. Insert `.' at beginning of line.
586 2. Insert `.' at end of buffer (end of text mark)."
587   (save-excursion
588     ;; Insert newline at end of buffer.
589     (goto-char (point-max))
590     (or (bolp) (insert "\n"))
591     ;; Replace `.' at beginning of line with `..'.
592     (goto-char (point-min))
593     ;; (replace-regexp "^\\." "..")
594     (while (search-forward "\n." nil t)
595       (insert "."))
596     ;; Insert `.' at end of buffer (end of text mark).
597     (goto-char (point-max))
598     (insert ".\r\n")))
599
600 \f
601 ;;;
602 ;;; Synchronous Communication with NNTP Server.
603 ;;;
604
605 (defun nntp-send-command (response cmd &rest args)
606   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
607   (save-excursion
608     ;; Clear communication buffer.
609     (set-buffer nntp-server-buffer)
610     (erase-buffer)
611     (apply 'nntp-send-strings-to-server cmd args)
612     (if response
613         (nntp-wait-for-response response)
614       t)))
615
616 (defun nntp-wait-for-response (regexp)
617   "Wait for server response which matches REGEXP."
618   (save-excursion
619     (let ((status t)
620           (wait t)
621           (dotnum 0)                    ;Number of "." being displayed.
622           (dotsize                      ;How often "." displayed.
623            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
624       (set-buffer nntp-server-buffer)
625       ;; Wait for status response (RFC977).
626       ;; 1xx - Informative message.
627       ;; 2xx - Command ok.
628       ;; 3xx - Command ok so far, send the rest of it.
629       ;; 4xx - Command was correct, but couldn't be performed for some
630       ;;       reason.
631       ;; 5xx - Command unimplemented, or incorrect, or a serious
632       ;;       program error occurred.
633       (nntp-accept-response)
634       (while wait
635         (goto-char (point-min))
636         (cond ((looking-at "[23]")
637                (setq wait nil))
638               ((looking-at "[45]")
639                (setq status nil)
640                (setq wait nil))
641               (t (nntp-accept-response))))
642       ;; Save status message.
643       (end-of-line)
644       (setq nntp-status-string
645             (buffer-substring (point-min) (point)))
646       (if status
647           (progn
648             (setq wait t)
649             (while wait
650               (goto-char (point-max))
651               (forward-line -1)         ;(beginning-of-line)
652               ;;(message (buffer-substring
653               ;;         (point)
654               ;;         (save-excursion (end-of-line) (point))))
655               (if (looking-at regexp)
656                   (setq wait nil)
657                 (if nntp-debug-read
658                     (let ((newnum (/ (buffer-size) dotsize)))
659                       (if (not (= dotnum newnum))
660                           (progn
661                             (setq dotnum newnum)
662                             (message "NNTP: Reading %s"
663                                      (make-string dotnum ?.))))))
664                 (nntp-accept-response)))
665             ;; Remove "...".
666             (if (and nntp-debug-read (> dotnum 0))
667                 (message ""))
668             ;; Successfully received server response.
669             t)))))
670
671 \f
672 ;;;
673 ;;; Low-Level Interface to NNTP Server.
674 ;;; 
675
676 (defun nntp-retrieve-headers-with-xover (sequence)
677   (if (not nntp-server-xover)
678       ()
679     (let ((range (format "%d-%d" (car sequence)
680                          (nntp-last-element sequence))))
681       (prog1
682           (if (stringp nntp-server-xover)
683               (nntp-send-command "^\\.\r$" nntp-server-xover range)
684             (let ((commands nntp-xover-commands))
685               (while (and commands
686                           (eq t nntp-server-xover))
687                 (nntp-send-command "^\\.\r$" (car commands) range)
688                 (save-excursion
689                   (set-buffer nntp-server-buffer)
690                   (goto-char 1)
691                   (if (looking-at "[23]") 
692                       (setq nntp-server-xover (car commands))))
693                 (setq commands (cdr commands)))
694               (if (eq t nntp-server-xover)
695                   (setq nntp-server-xover nil))
696               nntp-server-xover))
697         (if nntp-server-xover (nntp-decode-text) (erase-buffer))))))
698
699 (defun nntp-send-strings-to-server (&rest strings)
700   "Send list of STRINGS to news server as command and its arguments."
701   (let ((cmd (car strings))
702         (strings (cdr strings)))
703     ;; Command and each argument must be separated by one or more spaces.
704     (while strings
705       (setq cmd (concat cmd " " (car strings)))
706       (setq strings (cdr strings)))
707     ;; Command line must be terminated by a CR-LF.
708     (if (not (nntp-server-opened nntp-current-server))
709         (progn
710           (nntp-close-server nntp-address)
711           (if (not (nntp-open-server nntp-address))
712               (error (nntp-status-message)))
713           (save-excursion
714             (set-buffer nntp-server-buffer)
715             (erase-buffer))))
716     (process-send-string nntp-server-process (concat cmd "\r\n"))))
717
718 (defun nntp-send-region-to-server (begin end)
719   "Send current buffer region (from BEGIN to END) to news server."
720   (save-excursion
721     ;; We have to work in the buffer associated with NNTP server
722     ;;  process because of NEmacs hack.
723     (copy-to-buffer nntp-server-buffer begin end)
724     (set-buffer nntp-server-buffer)
725     (setq begin (point-min))
726     (setq end (point-max))
727     ;; `process-send-region' does not work if text to be sent is very
728     ;;  large. I don't know maximum size of text sent correctly.
729     (let ((last nil)
730           (size 100))                   ;Size of text sent at once.
731       (save-restriction
732         (narrow-to-region begin end)
733         (goto-char begin)
734         (while (not (eobp))
735           ;;(setq last (min end (+ (point) size)))
736           ;; NEmacs gets confused if character at `last' is Kanji.
737           (setq last (save-excursion
738                        (goto-char (min end (+ (point) size)))
739                        (or (eobp) (forward-char 1)) ;Adjust point
740                        (point)))
741           (process-send-region nntp-server-process (point) last)
742           ;; I don't know whether the next codes solve the known
743           ;;  problem of communication error of GNU Emacs.
744           (accept-process-output)
745           ;;(sit-for 0)
746           (goto-char last))))
747     ;; We cannot erase buffer, because reply may be received.
748     (delete-region begin end)))
749
750 (defun nntp-open-server-semi-internal (server &optional service)
751   "Open SERVER.
752 If SERVER is nil, use value of environment variable `NNTPSERVER'.
753 If SERVICE, this this as the port number."
754   (let ((server (or server (getenv "NNTPSERVER")))
755         (status nil)
756         (timer 
757          (and nntp-connection-timeout 
758               (run-at-time nntp-connection-timeout
759                            nil 'nntp-kill-connection server))))
760     (setq nntp-status-string "")
761     (message "nntp: Connecting to server on %s..." server)
762     (cond ((and server (nntp-open-server-internal server service))
763            (setq nntp-address server)
764            (setq status
765                  (condition-case nil
766                      (nntp-wait-for-response "^[23].*\r$")
767                    (error nil)
768                    (quit nil)))
769            (or status (nntp-close-server-internal server))
770            (and nntp-server-process
771                 (progn
772                   (set-process-sentinel 
773                    nntp-server-process 'nntp-default-sentinel)
774                   ;; You can send commands at startup like AUTHINFO here.
775                   ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
776                   (run-hooks 'nntp-server-opened-hook))))
777           ((null server)
778            (setq nntp-status-string "NNTP server is not specified.")))
779     (and timer (cancel-timer timer))
780     (message "")
781     (or status
782         (setq nntp-current-server nil))
783     status))
784
785 (defun nntp-open-server-internal (server &optional service)
786   "Open connection to news server on SERVER by SERVICE (default is nntp)."
787   (let (proc)
788     (save-excursion
789       ;; Use TCP/IP stream emulation package if needed.
790       (or (fboundp 'open-network-stream)
791           (require 'tcp))
792       ;; Initialize communication buffer.
793       (nnheader-init-server-buffer)
794       (set-buffer nntp-server-buffer)
795       (if (setq proc
796                 (condition-case nil
797                     (open-network-stream 
798                      "nntpd" (current-buffer) server nntp-port-number)
799                   (error nil)))
800           (progn
801             (setq nntp-server-process proc)
802             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
803             (process-kill-without-query proc)
804             (setq nntp-server-xover t)
805             (setq nntp-server-list-active-group t)
806             (setq nntp-address server)
807             ;; It is possible to change kanji-fileio-code in this hook.
808             (run-hooks 'nntp-server-hook)
809             nntp-server-process)))))
810
811 (defun nntp-close-server-internal (&optional server)
812   "Close connection to news server."
813   (nntp-possibly-change-server nil server)
814   (if nntp-server-process
815       (delete-process nntp-server-process))
816   (setq nntp-server-process nil)
817   (setq nntp-address ""))
818
819 (defun nntp-accept-response ()
820   "Read response of server.
821 It is well-known that the communication speed will be much improved by
822 defining this function as macro."
823   ;; To deal with server process exiting before
824   ;;  accept-process-output is called.
825   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
826   ;; This is a copy of `nntp-default-sentinel'.
827   (if (or (not nntp-server-process)
828           (not (memq (process-status nntp-server-process) '(open run))))
829       (error "nntp: Process connection closed; %s" (nntp-status-message))
830     (if nntp-buggy-select
831         (progn
832           ;; We cannot use `accept-process-output'.
833           ;; Fujitsu UTS requires messages during sleep-for. I don't know why.
834           (message "NNTP: Reading...")
835           (sleep-for 1)
836           (message ""))
837       (condition-case errorcode
838           (accept-process-output nntp-server-process)
839         (error
840          (cond ((string-equal "select error: Invalid argument" 
841                               (nth 1 errorcode))
842                 ;; Ignore select error.
843                 nil)
844                (t
845                 (signal (car errorcode) (cdr errorcode)))))))))
846
847 (defun nntp-last-element (list)
848   "Return last element of LIST."
849   (while (cdr list)
850     (setq list (cdr list)))
851   (car list))
852
853 (defun nntp-possibly-change-server (newsgroup server)
854   (let ((result t))
855     ;; We see whether it is necessary to change newsgroup.
856     (and newsgroup 
857          (or (not (string= newsgroup nntp-current-group)))
858          (progn
859            (setq result (nntp-request-group newsgroup server))
860            (setq nntp-current-group newsgroup)))
861     result))
862
863 (provide 'nntp)
864
865 ;;; nntp.el ends here