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