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