Synch with Gnus.
[elisp/gnus.git-] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Semi-gnus and its backends
2
3 ;; Copyright (C) 1987, 1988, 1989, 1990, 1993, 1994, 1995, 1996,
4 ;;        1997, 1998, 2000
5 ;;        Free Software Foundation, Inc.
6
7 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
8 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
9 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
10 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
11 ;; Keywords: mail, news, MIME
12
13 ;; This file is part of GNU Emacs.
14
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; any later version.
19
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
27 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28 ;; Boston, MA 02111-1307, USA.
29
30 ;;; Commentary:
31
32 ;;; Code:
33
34 (eval-when-compile (require 'cl))
35
36 (require 'mail-utils)
37 (require 'mime)
38
39 (defvar nnheader-max-head-length 4096
40   "*Max length of the head of articles.")
41
42 (defvar nnheader-head-chop-length 2048
43   "*Length of each read operation when trying to fetch HEAD headers.")
44
45 (defvar nnheader-file-name-translation-alist nil
46   "*Alist that says how to translate characters in file names.
47 For instance, if \":\" is invalid as a file character in file names
48 on your system, you could say something like:
49
50 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
51
52 (defvar nnheader-text-coding-system
53   (if (memq system-type '(windows-nt ms-dos ms-windows))
54       'raw-text-dos
55     'raw-text)
56   "Text-safe coding system (For removing ^M).
57 This variable is a substitute for `mm-text-coding-system'.")
58
59 (defvar nnheader-text-coding-system-for-write nil
60   "Text coding system for write.
61 This variable is a substitute for `mm-text-coding-system-for-write'.")
62
63 (eval-and-compile
64   (autoload 'nnmail-message-id "nnmail")
65   (autoload 'mail-position-on-field "sendmail")
66   (autoload 'message-remove-header "message")
67   (autoload 'gnus-point-at-eol "gnus-util")
68   (autoload 'gnus-delete-line "gnus-util")
69   (autoload 'gnus-buffer-live-p "gnus-util"))
70
71 ;;; Header access macros.
72
73 ;; These macros may look very much like the ones in GNUS 4.1.  They
74 ;; are, in a way, but you should note that the indices they use have
75 ;; been changed from the internal GNUS format to the NOV format.  The
76 ;; makes it possible to read headers from XOVER much faster.
77 ;;
78 ;; The format of a header is now:
79 ;; [number subject from date id references chars lines xref extra]
80 ;;
81 ;; (That next-to-last entry is defined as "misc" in the NOV format,
82 ;; but Gnus uses it for xrefs.)
83
84 (require 'mmgnus)
85
86 (defmacro mail-header-number (header)
87   "Return article number in HEADER."
88   `(mime-entity-location-internal ,header))
89
90 (defmacro mail-header-set-number (header number)
91   "Set article number of HEADER to NUMBER."
92   `(mime-entity-set-location-internal ,header ,number))
93
94 (defalias 'mail-header-subject 'mime-gnus-entity-subject-internal)
95 (defalias 'mail-header-set-subject 'mime-gnus-entity-set-subject-internal)
96
97 (defalias 'mail-header-from 'mime-gnus-entity-from-internal)
98 (defalias 'mail-header-set-from 'mime-gnus-entity-set-from-internal)
99
100 (defalias 'mail-header-date 'mime-gnus-entity-date-internal)
101 (defalias 'mail-header-set-date 'mime-gnus-entity-set-date-internal)
102
103 (defalias 'mail-header-message-id 'mime-gnus-entity-id-internal)
104 (defalias 'mail-header-id 'mime-gnus-entity-id-internal)
105 (defalias 'mail-header-set-message-id 'mime-gnus-entity-set-id-internal)
106 (defalias 'mail-header-set-id 'mime-gnus-entity-set-id-internal)
107
108 (defalias 'mail-header-references 'mime-gnus-entity-references-internal)
109 (defalias 'mail-header-set-references
110   'mime-gnus-entity-set-references-internal)
111
112 (defalias 'mail-header-chars 'mime-gnus-entity-chars-internal)
113 (defalias 'mail-header-set-chars 'mime-gnus-entity-set-chars-internal)
114
115 (defalias 'mail-header-lines 'mime-gnus-entity-lines-internal)
116 (defalias 'mail-header-set-lines 'mime-gnus-entity-set-lines-internal)
117
118 (defalias 'mail-header-xref 'mime-gnus-entity-xref-internal)
119 (defalias 'mail-header-set-xref 'mime-gnus-entity-set-xref-internal)
120
121 (defalias 'nnheader-decode-subject
122   (mime-find-field-decoder 'Subject 'nov))
123 (defalias 'nnheader-decode-from
124   (mime-find-field-decoder 'From 'nov))
125
126 (defalias 'mail-header-extra 'mime-gnus-entity-extra-internal)
127 (defalias 'mail-header-set-extra 'mime-gnus-entity-set-extra-internal)
128
129 (defun nnheader-decode-field-body (field-body field-name
130                                               &optional mode max-column)
131   (mime-decode-field-body field-body
132                           (if (stringp field-name)
133                               (intern (capitalize field-name))
134                             field-name)
135                           mode max-column))
136
137 (defsubst make-full-mail-header (&optional number subject from date id
138                                            references chars lines xref
139                                            extra)
140   "Create a new mail header structure initialized with the parameters given."
141   (luna-make-entity (mm-expand-class-name 'gnus)
142                     :location number
143                     :subject (if subject
144                                  (nnheader-decode-subject subject))
145                     :from (if from
146                               (nnheader-decode-from from))
147                     :date date
148                     :id id
149                     :references references
150                     :chars chars
151                     :lines lines
152                     :xref xref
153                     :original-header (list (cons 'Subject subject)
154                                            (cons 'From from))
155                     :extra extra))
156
157 (defsubst make-full-mail-header-from-decoded-header
158   (&optional number subject from date id references chars lines xref extra)
159   "Create a new mail header structure initialized with the parameters given."
160   (luna-make-entity (mm-expand-class-name 'gnus)
161                     :location number
162                     :subject subject
163                     :from from
164                     :date date
165                     :id id
166                     :references references
167                     :chars chars
168                     :lines lines
169                     :xref xref
170                     :extra extra))
171
172 (defsubst make-mail-header (&optional init)
173   "Create a new mail header structure initialized with INIT."
174   (make-full-mail-header init init init init init
175                          init init init init init))
176
177 ;; fake message-ids: generation and detection
178
179 (defvar nnheader-fake-message-id 1)
180
181 (defsubst nnheader-generate-fake-message-id ()
182   (concat "fake+none+" (int-to-string (incf nnheader-fake-message-id))))
183
184 (defsubst nnheader-fake-message-id-p (id)
185   (save-match-data                      ; regular message-id's are <.*>
186     (string-match "\\`fake\\+none\\+[0-9]+\\'" id)))
187
188 ;; Parsing headers and NOV lines.
189
190 (defsubst nnheader-header-value ()
191   (buffer-substring (match-end 0) (gnus-point-at-eol)))
192
193 (defun nnheader-parse-head (&optional naked)
194   (let ((case-fold-search t)
195         (cur (current-buffer))
196         (buffer-read-only nil)
197         in-reply-to lines p ref)
198     (goto-char (point-min))
199     (when naked
200       (insert "\n"))
201     ;; Search to the beginning of the next header.  Error messages
202     ;; do not begin with 2 or 3.
203     (prog1
204         (when (or naked (re-search-forward "^[23][0-9]+ " nil t))
205           ;; This implementation of this function, with nine
206           ;; search-forwards instead of the one re-search-forward and
207           ;; a case (which basically was the old function) is actually
208           ;; about twice as fast, even though it looks messier.  You
209           ;; can't have everything, I guess.  Speed and elegance
210           ;; don't always go hand in hand.
211           (make-full-mail-header
212            ;; Number.
213            (if naked
214                (progn
215                  (setq p (point-min))
216                  0)
217              (prog1
218                  (read cur)
219                (end-of-line)
220                (setq p (point))
221                (narrow-to-region (point)
222                                  (or (and (search-forward "\n.\n" nil t)
223                                           (- (point) 2))
224                                      (point)))))
225            ;; Subject.
226            (progn
227              (goto-char p)
228              (if (search-forward "\nsubject: " nil t)
229                  (nnheader-header-value) "(none)"))
230            ;; From.
231            (progn
232              (goto-char p)
233              (if (search-forward "\nfrom: " nil t)
234                  (nnheader-header-value) "(nobody)"))
235            ;; Date.
236            (progn
237              (goto-char p)
238              (if (search-forward "\ndate: " nil t)
239                  (nnheader-header-value) ""))
240            ;; Message-ID.
241            (progn
242              (goto-char p)
243              (if (search-forward "\nmessage-id:" nil t)
244                  (buffer-substring
245                   (1- (or (search-forward "<" (gnus-point-at-eol) t)
246                           (point)))
247                   (or (search-forward ">" (gnus-point-at-eol) t) (point)))
248                ;; If there was no message-id, we just fake one to make
249                ;; subsequent routines simpler.
250                (nnheader-generate-fake-message-id)))
251            ;; References.
252            (progn
253              (goto-char p)
254              (if (search-forward "\nreferences: " nil t)
255                  (nnheader-header-value)
256                ;; Get the references from the in-reply-to header if there
257                ;; were no references and the in-reply-to header looks
258                ;; promising.
259                (if (and (search-forward "\nin-reply-to: " nil t)
260                         (setq in-reply-to (nnheader-header-value))
261                         (string-match "<[^\n>]+>" in-reply-to))
262                    (let (ref2)
263                      (setq ref (substring in-reply-to (match-beginning 0)
264                                           (match-end 0)))
265                      (while (string-match "<[^\n>]+>"
266                                           in-reply-to (match-end 0))
267                        (setq ref2 (substring in-reply-to (match-beginning 0)
268                                              (match-end 0)))
269                        (when (> (length ref2) (length ref))
270                          (setq ref ref2)))
271                      ref)
272                  nil)))
273            ;; Chars.
274            0
275            ;; Lines.
276            (progn
277              (goto-char p)
278              (if (search-forward "\nlines: " nil t)
279                  (if (numberp (setq lines (read cur)))
280                      lines 0)
281                0))
282            ;; Xref.
283            (progn
284              (goto-char p)
285              (and (search-forward "\nxref: " nil t)
286                   (nnheader-header-value)))
287
288            ;; Extra.
289            (when nnmail-extra-headers
290              (let ((extra nnmail-extra-headers)
291                    out)
292                (while extra
293                  (goto-char p)
294                  (when (search-forward
295                         (concat "\n" (symbol-name (car extra)) ": ") nil t)
296                    (push (cons (car extra) (nnheader-header-value))
297                          out))
298                  (pop extra))
299                out))))
300       (when naked
301         (goto-char (point-min))
302         (delete-char 1)))))
303
304 (defmacro nnheader-nov-skip-field ()
305   '(search-forward "\t" eol 'move))
306
307 (defmacro nnheader-nov-field ()
308   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
309
310 (defmacro nnheader-nov-read-integer ()
311   '(prog1
312        (if (eq (char-after) ?\t)
313            0
314          (let ((num (condition-case nil
315                         (read (current-buffer))
316                       (error nil))))
317            (if (numberp num) num 0)))
318      (unless (eobp)
319        (search-forward "\t" eol 'move))))
320
321 (defmacro nnheader-nov-parse-extra ()
322   '(let (out string)
323      (while (not (memq (char-after) '(?\n nil)))
324        (setq string (nnheader-nov-field))
325        (when (string-match "^\\([^ :]+\\): " string)
326          (push (cons (intern (match-string 1 string))
327                      (substring string (match-end 0)))
328                out)))
329      out))
330
331 (defmacro nnheader-nov-read-message-id ()
332   '(let ((id (nnheader-nov-field)))
333      (if (string-match "^<[^>]+>$" id)
334          id
335        (nnheader-generate-fake-message-id))))
336
337 (defun nnheader-parse-nov ()
338   (let ((eol (gnus-point-at-eol)))
339     (make-full-mail-header
340      (nnheader-nov-read-integer)        ; number
341      (nnheader-nov-field)               ; subject
342      (nnheader-nov-field)               ; from
343      (nnheader-nov-field)               ; date
344      (nnheader-nov-read-message-id)     ; id
345      (nnheader-nov-field)               ; refs
346      (nnheader-nov-read-integer)        ; chars
347      (nnheader-nov-read-integer)        ; lines
348      (if (eq (char-after) ?\n)
349          nil
350        (nnheader-nov-field))            ; misc
351      (nnheader-nov-parse-extra))))      ; extra
352
353 (defun nnheader-insert-nov (header)
354   (princ (mail-header-number header) (current-buffer))
355   (let ((p (point)))
356     (insert
357      "\t"
358      (or (mime-entity-fetch-field header 'Subject) "(none)") "\t"
359      (or (mime-entity-fetch-field header 'From) "(nobody)") "\t"
360      (or (mail-header-date header) "") "\t"
361      (or (mail-header-id header)
362          (nnmail-message-id))
363      "\t"
364      (or (mail-header-references header) "") "\t")
365     (princ (or (mail-header-chars header) 0) (current-buffer))
366     (insert "\t")
367     (princ (or (mail-header-lines header) 0) (current-buffer))
368     (insert "\t")
369     (when (mail-header-xref header)
370       (insert "Xref: " (mail-header-xref header)))
371     (when (or (mail-header-xref header)
372               (mail-header-extra header))
373       (insert "\t"))
374     (when (mail-header-extra header)
375       (let ((extra (mail-header-extra header)))
376         (while extra
377           (insert (symbol-name (caar extra))
378                   ": " (cdar extra) "\t")
379           (pop extra))))
380     (insert "\n")
381     (backward-char 1)
382     (while (search-backward "\n" p t)
383       (delete-char 1))
384     (forward-line 1)))
385
386 (defun nnheader-insert-header (header)
387   (insert
388    "Subject: " (or (mail-header-subject header) "(none)") "\n"
389    "From: " (or (mail-header-from header) "(nobody)") "\n"
390    "Date: " (or (mail-header-date header) "") "\n"
391    "Message-ID: " (or (mail-header-id header) (nnmail-message-id)) "\n"
392    "References: " (or (mail-header-references header) "") "\n"
393    "Lines: ")
394   (princ (or (mail-header-lines header) 0) (current-buffer))
395   (insert "\n\n"))
396
397 (defun nnheader-insert-article-line (article)
398   (goto-char (point-min))
399   (insert "220 ")
400   (princ article (current-buffer))
401   (insert " Article retrieved.\n")
402   (search-forward "\n\n" nil 'move)
403   (delete-region (point) (point-max))
404   (forward-char -1)
405   (insert "."))
406
407 (defun nnheader-nov-delete-outside-range (beg end)
408   "Delete all NOV lines that lie outside the BEG to END range."
409   ;; First we find the first wanted line.
410   (nnheader-find-nov-line beg)
411   (delete-region (point-min) (point))
412   ;; Then we find the last wanted line.
413   (when (nnheader-find-nov-line end)
414     (forward-line 1))
415   (delete-region (point) (point-max)))
416
417 (defun nnheader-find-nov-line (article)
418   "Put point at the NOV line that start with ARTICLE.
419 If ARTICLE doesn't exist, put point where that line
420 would have been.  The function will return non-nil if
421 the line could be found."
422   ;; This function basically does a binary search.
423   (let ((max (point-max))
424         (min (goto-char (point-min)))
425         (cur (current-buffer))
426         (prev (point-min))
427         num found)
428     (while (not found)
429       (goto-char (/ (+ max min) 2))
430       (beginning-of-line)
431       (if (or (= (point) prev)
432               (eobp))
433           (setq found t)
434         (setq prev (point))
435         (while (and (not (numberp (setq num (read cur))))
436                     (not (eobp)))
437           (gnus-delete-line))
438         (cond ((> num article)
439                (setq max (point)))
440               ((< num article)
441                (setq min (point)))
442               (t
443                (setq found 'yes)))))
444     ;; We may be at the first line.
445     (when (and (not num)
446                (not (eobp)))
447       (setq num (read cur)))
448     ;; Now we may have found the article we're looking for, or we
449     ;; may be somewhere near it.
450     (when (and (not (eq found 'yes))
451                (not (eq num article)))
452       (setq found (point))
453       (while (and (< (point) max)
454                   (or (not (numberp num))
455                       (< num article)))
456         (forward-line 1)
457         (setq found (point))
458         (or (eobp)
459             (= (setq num (read cur)) article)))
460       (unless (eq num article)
461         (goto-char found)))
462     (beginning-of-line)
463     (eq num article)))
464
465 (defun nnheader-retrieve-headers-from-directory* (articles
466                                                   directory dependencies
467                                                   &optional
468                                                   fetch-old force-new large
469                                                   backend)
470   (with-temp-buffer
471     (let* ((file nil)
472            (number (length articles))
473            (count 0)
474            (file-name-coding-system 'binary)
475            (pathname-coding-system 'binary)
476            (case-fold-search t)
477            (cur (current-buffer))
478            article
479            headers header id end ref in-reply-to lines chars ctype)
480       ;; We don't support fetching by Message-ID.
481       (if (stringp (car articles))
482           'headers
483         (while articles
484           (when (and (file-exists-p
485                       (setq file (expand-file-name
486                                   (int-to-string
487                                    (setq article (pop articles)))
488                                   directory)))
489                      (not (file-directory-p file)))
490             (erase-buffer)
491             (nnheader-insert-head file)
492             (save-restriction
493               (std11-narrow-to-header)
494               (setq
495                header
496                (make-full-mail-header
497                 ;; Number.
498                 article
499                 ;; Subject.
500                 (or (std11-fetch-field "Subject")
501                     "(none)")
502                 ;; From.
503                 (or (std11-fetch-field "From")
504                     "(nobody)")
505                 ;; Date.
506                 (or (std11-fetch-field "Date")
507                     "")
508                 ;; Message-ID.
509                 (progn
510                   (goto-char (point-min))
511                   (setq id (if (re-search-forward
512                                 "^Message-ID: *\\(<[^\n\t> ]+>\\)" nil t)
513                                ;; We do it this way to make sure the Message-ID
514                                ;; is (somewhat) syntactically valid.
515                                (buffer-substring (match-beginning 1)
516                                                  (match-end 1))
517                              ;; If there was no message-id, we just fake one
518                              ;; to make subsequent routines simpler.
519                              (nnheader-generate-fake-message-id))))
520                 ;; References.
521                 (progn
522                   (goto-char (point-min))
523                   (if (search-forward "\nReferences: " nil t)
524                       (progn
525                         (setq end (point))
526                         (prog1
527                             (buffer-substring (match-end 0) (std11-field-end))
528                           (setq ref
529                                 (buffer-substring
530                                  (progn
531                                    ;; (end-of-line)
532                                    (search-backward ">" end t)
533                                    (1+ (point)))
534                                  (progn
535                                    (search-backward "<" end t)
536                                    (point))))))
537                     ;; Get the references from the in-reply-to header if there
538                     ;; were no references and the in-reply-to header looks
539                     ;; promising.
540                     (if (and (search-forward "\nIn-Reply-To: " nil t)
541                              (setq in-reply-to
542                                    (buffer-substring (match-end 0)
543                                                      (std11-field-end)))
544                              (string-match "<[^>]+>" in-reply-to))
545                         (let (ref2)
546                           (setq ref (substring in-reply-to (match-beginning 0)
547                                                (match-end 0)))
548                           (while (string-match "<[^>]+>"
549                                                in-reply-to (match-end 0))
550                             (setq ref2
551                                   (substring in-reply-to (match-beginning 0)
552                                              (match-end 0)))
553                             (when (> (length ref2) (length ref))
554                               (setq ref ref2)))
555                           ref)
556                       (setq ref nil))))
557                 ;; Chars.
558                 (progn
559                   (goto-char (point-min))
560                   (if (search-forward "\nChars: " nil t)
561                       (if (numberp (setq chars (ignore-errors (read cur))))
562                           chars 0)
563                     0))
564                 ;; Lines.
565                 (progn
566                   (goto-char (point-min))
567                   (if (search-forward "\nLines: " nil t)
568                       (if (numberp (setq lines (ignore-errors (read cur))))
569                           lines 0)
570                     0))
571                 ;; Xref.
572                 (std11-fetch-field "Xref")
573                 ))
574               (goto-char (point-min))
575               (if (setq ctype (std11-fetch-field "Content-Type"))
576                   (mime-entity-set-content-type-internal
577                    header (mime-parse-Content-Type ctype)))
578               )
579             (when (setq header
580                         (gnus-dependencies-add-header
581                          header dependencies force-new))
582               (push header headers))
583             )
584           (setq count (1+ count))
585
586           (and large
587                (zerop (% count 20))
588                (nnheader-message 5 "%s: Receiving headers... %d%%"
589                                  backend
590                                  (/ (* count 100) number))))
591
592         (when large
593           (nnheader-message 5 "%s: Receiving headers...done" backend))
594
595         headers))))
596
597 (defun nnheader-retrieve-headers-from-directory (articles
598                                                  directory dependencies
599                                                  &optional
600                                                  fetch-old force-new large
601                                                  backend)
602   (cons 'header
603         (nreverse (nnheader-retrieve-headers-from-directory*
604                    articles directory dependencies
605                    fetch-old force-new large backend))))
606
607 (defun nnheader-get-newsgroup-headers-xover* (sequence
608                                               &optional
609                                               force-new dependencies
610                                               group)
611   "Parse the news overview data in the server buffer, and return a
612 list of headers that match SEQUENCE (see `nntp-retrieve-headers')."
613   ;; Get the Xref when the users reads the articles since most/some
614   ;; NNTP servers do not include Xrefs when using XOVER.
615   ;; (setq gnus-article-internal-prepare-hook '(gnus-article-get-xrefs))
616   (let ((cur nntp-server-buffer)
617         number headers header)
618     (save-excursion
619       (set-buffer nntp-server-buffer)
620       ;; Allow the user to mangle the headers before parsing them.
621       (gnus-run-hooks 'gnus-parse-headers-hook)
622       (goto-char (point-min))
623       (while (not (eobp))
624         (condition-case ()
625             (while (and sequence (not (eobp)))
626               (setq number (read cur))
627               (while (and sequence
628                           (< (car sequence) number))
629                 (setq sequence (cdr sequence)))
630               (and sequence
631                    (eq number (car sequence))
632                    (progn
633                      (setq sequence (cdr sequence))
634                      (setq header (inline
635                                     (gnus-nov-parse-line
636                                      number dependencies force-new))))
637                    (push header headers))
638               (forward-line 1))
639           (error
640            (gnus-error 4 "Strange nov line (%d)"
641                        (count-lines (point-min) (point)))))
642         (forward-line 1))
643       ;; A common bug in inn is that if you have posted an article and
644       ;; then retrieves the active file, it will answer correctly --
645       ;; the new article is included.  However, a NOV entry for the
646       ;; article may not have been generated yet, so this may fail.
647       ;; We work around this problem by retrieving the last few
648       ;; headers using HEAD.
649       headers)))
650
651 ;; Various cruft the backends and Gnus need to communicate.
652
653 (defvar nntp-server-buffer nil)
654 (defvar nntp-process-response nil)
655 (defvar gnus-verbose-backends 7
656   "*A number that says how talkative the Gnus backends should be.")
657 (defvar gnus-nov-is-evil nil
658   "If non-nil, Gnus backends will never output headers in the NOV format.")
659 (defvar news-reply-yank-from nil)
660 (defvar news-reply-yank-message-id nil)
661
662 (defvar nnheader-callback-function nil)
663
664 (defun nnheader-init-server-buffer ()
665   "Initialize the Gnus-backend communication buffer."
666   (save-excursion
667     (unless (gnus-buffer-live-p nntp-server-buffer)
668       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
669     (set-buffer nntp-server-buffer)
670     (erase-buffer)
671     (kill-all-local-variables)
672     (setq case-fold-search t)           ;Should ignore case.
673     (set (make-local-variable 'nntp-process-response) nil)
674     t))
675
676 ;;; Various functions the backends use.
677
678 (defun nnheader-file-error (file)
679   "Return a string that says what is wrong with FILE."
680   (format
681    (cond
682     ((not (file-exists-p file))
683      "%s does not exist")
684     ((file-directory-p file)
685      "%s is a directory")
686     ((not (file-readable-p file))
687      "%s is not readable"))
688    file))
689
690 (defun nnheader-insert-head (file)
691   "Insert the head of the article."
692   (when (file-exists-p file)
693     (if (eq nnheader-max-head-length t)
694         ;; Just read the entire file.
695         (nnheader-insert-file-contents file)
696       ;; Read 1K blocks until we find a separator.
697       (let ((beg 0)
698             format-alist)
699         (while (and (eq nnheader-head-chop-length
700                         (nth 1 (nnheader-insert-file-contents
701                                 file nil beg
702                                 (incf beg nnheader-head-chop-length))))
703                     (prog1 (not (search-forward "\n\n" nil t))
704                       (goto-char (point-max)))
705                     (or (null nnheader-max-head-length)
706                         (< beg nnheader-max-head-length))))))
707     t))
708
709 (defun nnheader-article-p ()
710   "Say whether the current buffer looks like an article."
711   (goto-char (point-min))
712   (if (not (search-forward "\n\n" nil t))
713       nil
714     (narrow-to-region (point-min) (1- (point)))
715     (goto-char (point-min))
716     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
717       (goto-char (match-end 0)))
718     (prog1
719         (eobp)
720       (widen))))
721
722 (defun nnheader-insert-references (references message-id)
723   "Insert a References header based on REFERENCES and MESSAGE-ID."
724   (if (and (not references) (not message-id))
725       ;; This is invalid, but not all articles have Message-IDs.
726       ()
727     (mail-position-on-field "References")
728     (let ((begin (save-excursion (beginning-of-line) (point)))
729           (fill-column 78)
730           (fill-prefix "\t"))
731       (when references
732         (insert references))
733       (when (and references message-id)
734         (insert " "))
735       (when message-id
736         (insert message-id))
737       ;; Fold long References lines to conform to RFC1036 (sort of).
738       ;; The region must end with a newline to fill the region
739       ;; without inserting extra newline.
740       (fill-region-as-paragraph begin (1+ (point))))))
741
742 (defun nnheader-replace-header (header new-value)
743   "Remove HEADER and insert the NEW-VALUE."
744   (save-excursion
745     (save-restriction
746       (nnheader-narrow-to-headers)
747       (prog1
748           (message-remove-header header)
749         (goto-char (point-max))
750         (insert header ": " new-value "\n")))))
751
752 (defun nnheader-narrow-to-headers ()
753   "Narrow to the head of an article."
754   (widen)
755   (narrow-to-region
756    (goto-char (point-min))
757    (if (search-forward "\n\n" nil t)
758        (1- (point))
759      (point-max)))
760   (goto-char (point-min)))
761
762 (defun nnheader-set-temp-buffer (name &optional noerase)
763   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
764   (set-buffer (get-buffer-create name))
765   (buffer-disable-undo)
766   (unless noerase
767     (erase-buffer))
768   (current-buffer))
769
770 (eval-when-compile (defvar jka-compr-compression-info-list))
771 (defvar nnheader-numerical-files
772   (if (boundp 'jka-compr-compression-info-list)
773       (concat "\\([0-9]+\\)\\("
774               (mapconcat (lambda (i) (aref i 0))
775                          jka-compr-compression-info-list "\\|")
776               "\\)?")
777     "[0-9]+$")
778   "Regexp that match numerical files.")
779
780 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
781   "Regexp that matches numerical file names.")
782
783 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
784   "Regexp that matches numerical full file paths.")
785
786 (defsubst nnheader-file-to-number (file)
787   "Take a file name and return the article number."
788   (if (string= nnheader-numerical-short-files "^[0-9]+$")
789       (string-to-int file)
790     (string-match nnheader-numerical-short-files file)
791     (string-to-int (match-string 0 file))))
792
793 (defun nnheader-directory-files-safe (&rest args)
794   ;; It has been reported numerous times that `directory-files'
795   ;; fails with an alarming frequency on NFS mounted file systems.
796   ;; This function executes that function twice and returns
797   ;; the longest result.
798   (let ((first (apply 'directory-files args))
799         (second (apply 'directory-files args)))
800     (if (> (length first) (length second))
801         first
802       second)))
803
804 (defun nnheader-directory-articles (dir)
805   "Return a list of all article files in a directory."
806   (mapcar 'nnheader-file-to-number
807           (nnheader-directory-files-safe
808            dir nil nnheader-numerical-short-files t)))
809
810 (defun nnheader-article-to-file-alist (dir)
811   "Return an alist of article/file pairs in DIR."
812   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
813           (nnheader-directory-files-safe
814            dir nil nnheader-numerical-short-files t)))
815
816 (defun nnheader-fold-continuation-lines ()
817   "Fold continuation lines in the current buffer."
818   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
819
820 (defun nnheader-translate-file-chars (file &optional full)
821   "Translate FILE into something that can be a file name.
822 If FULL, translate everything."
823   (if (null nnheader-file-name-translation-alist)
824       ;; No translation is necessary.
825       file
826     (let* ((i 0)
827            trans leaf path len)
828       (if full
829           ;; Do complete translation.
830           (setq leaf (copy-sequence file)
831                 path ""
832                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1))) 
833                       2 0))
834         ;; We translate -- but only the file name.  We leave the directory
835         ;; alone.
836         (if (string-match "/[^/]+\\'" file)
837             ;; This is needed on NT's and stuff.
838             (setq leaf (substring file (1+ (match-beginning 0)))
839                   path (substring file 0 (1+ (match-beginning 0))))
840           ;; Fall back on this.
841           (setq leaf (file-name-nondirectory file)
842                 path (file-name-directory file))))
843       (setq len (length leaf))
844       (while (< i len)
845         (when (setq trans (cdr (assq (aref leaf i)
846                                      nnheader-file-name-translation-alist)))
847           (aset leaf i trans))
848         (incf i))
849       (concat path leaf))))
850
851 (defun nnheader-report (backend &rest args)
852   "Report an error from the BACKEND.
853 The first string in ARGS can be a format string."
854   (set (intern (format "%s-status-string" backend))
855        (if (< (length args) 2)
856            (car args)
857          (apply 'format args)))
858   nil)
859
860 (defun nnheader-get-report (backend)
861   "Get the most recent report from BACKEND."
862   (condition-case ()
863       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
864                                                              backend))))
865     (error (nnheader-message 5 ""))))
866
867 (defun nnheader-insert (format &rest args)
868   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
869 If FORMAT isn't a format string, it and all ARGS will be inserted
870 without formatting."
871   (save-excursion
872     (set-buffer nntp-server-buffer)
873     (erase-buffer)
874     (if (string-match "%" format)
875         (insert (apply 'format format args))
876       (apply 'insert format args))
877     t))
878
879 (defun nnheader-replace-chars-in-string (string from to)
880   "Replace characters in STRING from FROM to TO."
881   (let ((string (substring string 0))   ;Copy string.
882         (len (length string))
883         (idx 0))
884     ;; Replace all occurrences of FROM with TO.
885     (while (< idx len)
886       (when (= (aref string idx) from)
887         (aset string idx to))
888       (setq idx (1+ idx)))
889     string))
890
891 (defun nnheader-replace-duplicate-chars-in-string (string from to)
892   "Replace characters in STRING from FROM to TO."
893   (let ((string (substring string 0))   ;Copy string.
894         (len (length string))
895         (idx 0) prev i)
896     ;; Replace all occurrences of FROM with TO.
897     (while (< idx len)
898       (setq i (aref string idx))
899       (when (and (eq prev from) (= i from))
900         (aset string (1- idx) to)
901         (aset string idx to))
902       (setq prev i)
903       (setq idx (1+ idx)))
904     string))
905
906 (defun nnheader-file-to-group (file &optional top)
907   "Return a group name based on FILE and TOP."
908   (nnheader-replace-chars-in-string
909    (if (not top)
910        file
911      (condition-case ()
912          (substring (expand-file-name file)
913                     (length
914                      (expand-file-name
915                       (file-name-as-directory top))))
916        (error "")))
917    ?/ ?.))
918
919 (defun nnheader-message (level &rest args)
920   "Message if the Gnus backends are talkative."
921   (if (or (not (numberp gnus-verbose-backends))
922           (<= level gnus-verbose-backends))
923       (apply 'message args)
924     (apply 'format args)))
925
926 (defun nnheader-be-verbose (level)
927   "Return whether the backends should be verbose on LEVEL."
928   (or (not (numberp gnus-verbose-backends))
929       (<= level gnus-verbose-backends)))
930
931 (defvar nnheader-pathname-coding-system 'binary
932   "*Coding system for pathname.")
933
934 (defun nnheader-group-pathname (group dir &optional file)
935   "Make pathname for GROUP."
936   (concat
937    (let ((dir (file-name-as-directory (expand-file-name dir))))
938      ;; If this directory exists, we use it directly.
939      (file-name-as-directory
940       (if (file-directory-p (concat dir group))
941           (expand-file-name group dir)
942         ;; If not, we translate dots into slashes.
943         (expand-file-name (encode-coding-string
944                            (nnheader-replace-chars-in-string group ?. ?/)
945                            nnheader-pathname-coding-system)
946                           dir))))
947    (cond ((null file) "")
948          ((numberp file) (int-to-string file))
949          (t file))))
950
951 (defun nnheader-functionp (form)
952   "Return non-nil if FORM is funcallable."
953   (or (and (symbolp form) (fboundp form))
954       (and (listp form) (eq (car form) 'lambda))))
955
956 (defun nnheader-concat (dir &rest files)
957   "Concat DIR as directory to FILE."
958   (apply 'concat (file-name-as-directory dir) files))
959
960 (defun nnheader-ms-strip-cr ()
961   "Strip ^M from the end of all lines."
962   (save-excursion
963     (goto-char (point-min))
964     (while (re-search-forward "\r$" nil t)
965       (delete-backward-char 1))))
966
967 (defun nnheader-file-size (file)
968   "Return the file size of FILE or 0."
969   (or (nth 7 (file-attributes file)) 0))
970
971 (defun nnheader-find-etc-directory (package &optional file)
972   "Go through the path and find the \".../etc/PACKAGE\" directory.
973 If FILE, find the \".../etc/PACKAGE\" file instead."
974   (let ((path load-path)
975         dir result)
976     ;; We try to find the dir by looking at the load path,
977     ;; stripping away the last component and adding "etc/".
978     (while path
979       (if (and (car path)
980                (file-exists-p
981                 (setq dir (concat
982                            (file-name-directory
983                             (directory-file-name (car path)))
984                            "etc/" package
985                            (if file "" "/"))))
986                (or file (file-directory-p dir)))
987           (setq result dir
988                 path nil)
989         (setq path (cdr path))))
990     result))
991
992 (defvar ange-ftp-path-format)
993 (defvar efs-path-regexp)
994 (defun nnheader-re-read-dir (path)
995   "Re-read directory PATH if PATH is on a remote system."
996   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
997       (when (string-match efs-path-regexp path)
998         (efs-re-read-dir path))
999     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
1000       (when (string-match (car ange-ftp-path-format) path)
1001         (ange-ftp-re-read-dir path)))))
1002
1003 (defvar nnheader-file-coding-system 'raw-text
1004   "Coding system used in file backends of Gnus.")
1005
1006 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
1007   "Like `insert-file-contents', q.v., but only reads in the file.
1008 A buffer may be modified in several ways after reading into the buffer due
1009 to advanced Emacs features, such as file-name-handlers, format decoding,
1010 find-file-hooks, etc.
1011   This function ensures that none of these modifications will take place."
1012   (let ((format-alist nil)
1013         (auto-mode-alist (nnheader-auto-mode-alist))
1014         (default-major-mode 'fundamental-mode)
1015         (enable-local-variables nil)
1016         (after-insert-file-functions nil)
1017         (enable-local-eval nil)
1018         (find-file-hooks nil))
1019     (insert-file-contents-as-coding-system
1020      nnheader-file-coding-system filename visit beg end replace)))
1021
1022 (defun nnheader-find-file-noselect (&rest args)
1023   (let ((format-alist nil)
1024         (auto-mode-alist (nnheader-auto-mode-alist))
1025         (default-major-mode 'fundamental-mode)
1026         (enable-local-variables nil)
1027         (after-insert-file-functions nil)
1028         (enable-local-eval nil)
1029         (find-file-hooks nil))
1030     (apply 'find-file-noselect-as-coding-system
1031            nnheader-file-coding-system args)))
1032
1033 (defun nnheader-auto-mode-alist ()
1034   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
1035   (let ((alist auto-mode-alist)
1036         out)
1037     (while alist
1038       (when (listp (cdar alist))
1039         (push (car alist) out))
1040       (pop alist))
1041     (nreverse out)))
1042
1043 (defun nnheader-directory-regular-files (dir)
1044   "Return a list of all regular files in DIR."
1045   (let ((files (directory-files dir t))
1046         out)
1047     (while files
1048       (when (file-regular-p (car files))
1049         (push (car files) out))
1050       (pop files))
1051     (nreverse out)))
1052
1053 (defun nnheader-directory-files (&rest args)
1054   "Same as `directory-files', but prune \".\" and \"..\"."
1055   (let ((files (apply 'directory-files args))
1056         out)
1057     (while files
1058       (unless (member (file-name-nondirectory (car files)) '("." ".."))
1059         (push (car files) out))
1060       (pop files))
1061     (nreverse out)))
1062
1063 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1064   `(let ((new (generate-new-buffer " *nnheader replace*"))
1065          (cur (current-buffer))
1066          (start (point-min)))
1067      (set-buffer cur)
1068      (goto-char (point-min))
1069      (while (,(if regexp 're-search-forward 'search-forward)
1070              ,from nil t)
1071        (insert-buffer-substring
1072         cur start (prog1 (match-beginning 0) (set-buffer new)))
1073        (goto-char (point-max))
1074        ,(when to `(insert ,to))
1075        (set-buffer cur)
1076        (setq start (point)))
1077      (insert-buffer-substring
1078       cur start (prog1 (point-max) (set-buffer new)))
1079      (copy-to-buffer cur (point-min) (point-max))
1080      (kill-buffer (current-buffer))
1081      (set-buffer cur)))
1082
1083 (defun nnheader-replace-string (from to)
1084   "Do a fast replacement of FROM to TO from point to point-max."
1085   (nnheader-skeleton-replace from to))
1086
1087 (defun nnheader-replace-regexp (from to)
1088   "Do a fast regexp replacement of FROM to TO from point to point-max."
1089   (nnheader-skeleton-replace from to t))
1090
1091 (defun nnheader-strip-cr ()
1092   "Strip all \r's from the current buffer."
1093   (nnheader-skeleton-replace "\r"))
1094
1095 (defalias 'nnheader-run-at-time 'run-at-time)
1096 (defalias 'nnheader-cancel-timer 'cancel-timer)
1097 (defalias 'nnheader-cancel-function-timers 'cancel-function-timers)
1098
1099 (defun nnheader-Y-or-n-p (prompt)
1100   "Ask user a \"Y/n\" question. Return t if answer is neither \"n\", \"N\" nor \"C-g\"."
1101   (let ((cursor-in-echo-area t)
1102         (echo-keystrokes 0)
1103         (inhibit-quit t)
1104         ans)
1105     (let (message-log-max)
1106       (while (not (memq ans '(?\  ?N ?Y ?\C-g ?\e ?\n ?\r ?n ?y)))
1107         (message "%s(Y/n) " prompt)
1108         (setq ans (read-char-exclusive))))
1109     (if (memq ans '(?\C-g ?N ?n))
1110         (progn
1111           (message "%s(Y/n) No" prompt)
1112           nil)
1113       (message "%s(Y/n) Yes" prompt)
1114       t)))
1115
1116 (when (string-match "XEmacs" emacs-version)
1117   (require 'nnheaderxm))
1118
1119 (run-hooks 'nnheader-load-hook)
1120
1121 (provide 'nnheader)
1122
1123 ;;; nnheader.el ends here