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