T-gnus 6.15.18 (quimby) revision 00.
[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, 2002, 2003
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   (autoload 'gnus-sorted-difference "gnus-range"))
54
55 (defcustom gnus-verbose-backends 7
56   "Integer that says how verbose the Gnus backends should be.
57 The higher the number, the more messages the Gnus backends will flash
58 to say what it's doing.  At zero, the Gnus backends will be totally
59 mute; at five, they will display most important messages; and at ten,
60 they will keep on jabbering all the time."
61   :group 'gnus-start
62   :type 'integer)
63
64 (defcustom gnus-nov-is-evil nil
65   "If non-nil, Gnus backends will never output headers in the NOV format."
66   :group 'gnus-server
67   :type 'boolean)
68
69 (defvar nnheader-max-head-length 4096
70   "*Max length of the head of articles.
71
72 Value is an integer, nil, or t.  nil means read in chunks of a file
73 indefinitely until a complete head is found\; t means always read the
74 entire file immediately, disregarding `nnheader-head-chop-length'.
75
76 Integer values will in effect be rounded up to the nearest multiple of
77 `nnheader-head-chop-length'.")
78
79 (defvar nnheader-head-chop-length 2048
80   "*Length of each read operation when trying to fetch HEAD headers.")
81
82 (defvar nnheader-read-timeout
83   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
84                     (symbol-name system-type))
85       1.0
86     0.1)
87   "How long nntp should wait between checking for the end of output.
88 Shorter values mean quicker response, but is more CPU intensive.")
89
90 (defvar nnheader-file-name-translation-alist
91   (let ((case-fold-search t))
92     (cond
93      ((string-match "windows-nt\\|os/2\\|emx\\|cygwin"
94                     (symbol-name system-type))
95       (append (mapcar (lambda (c) (cons c ?_))
96                       '(?: ?* ?\" ?< ?> ??))
97               (if (string-match "windows-nt\\|cygwin"
98                                 (symbol-name system-type))
99                   nil
100                 '((?+ . ?-)))))
101      (t nil)))
102   "*Alist that says how to translate characters in file names.
103 For instance, if \":\" is invalid as a file character in file names
104 on your system, you could say something like:
105
106 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
107
108 (defvar nnheader-text-coding-system
109   (if (memq system-type '(windows-nt ms-dos ms-windows))
110       'raw-text-dos
111     'raw-text)
112   "Text-safe coding system (For removing ^M).
113 This variable is a substitute for `mm-text-coding-system'.")
114
115 (defvar nnheader-text-coding-system-for-write nil
116   "Text coding system for write.
117 This variable is a substitute for `mm-text-coding-system-for-write'.")
118
119 (defvar nnheader-auto-save-coding-system
120   (cond
121    ((boundp 'MULE) '*junet*)
122    ((not (fboundp 'find-coding-system)) nil)
123    ((find-coding-system 'emacs-mule)
124     (if (memq system-type '(windows-nt ms-dos ms-windows))
125         'emacs-mule-dos 'emacs-mule))
126    ((find-coding-system 'escape-quoted) 'escape-quoted)
127    ((find-coding-system 'no-conversion) 'no-conversion)
128    (t nil))
129   "Coding system of auto save file.")
130
131 (defvar nnheader-directory-separator-character
132   (string-to-char (substring (file-name-as-directory ".") -1))
133   "*A character used to a directory separator.")
134
135 (eval-and-compile
136   (autoload 'nnmail-message-id "nnmail")
137   (autoload 'mail-position-on-field "sendmail")
138   (autoload 'message-remove-header "message")
139   (autoload 'gnus-point-at-eol "gnus-util")
140   (autoload 'gnus-buffer-live-p "gnus-util"))
141
142 ;; mm-util stuff.
143 (unless (featurep 'mm-util)
144   ;; Should keep track of `mm-image-load-path' in mm-util.el.
145   (defun nnheader-image-load-path (&optional package)
146     (let (dir result)
147       (dolist (path load-path (nreverse result))
148         (if (file-directory-p
149              (setq dir (concat (file-name-directory
150                                 (directory-file-name path))
151                                "etc/" (or package "gnus/"))))
152             (push dir result))
153         (push path result))))
154   (defalias 'mm-image-load-path 'nnheader-image-load-path)
155
156   ;; Should keep track of `mm-read-coding-system' in mm-util.el.
157   (defalias 'mm-read-coding-system
158     (if (or (and (featurep 'xemacs)
159                  (<= (string-to-number emacs-version) 21.1))
160             (boundp 'MULE))
161         (lambda (prompt &optional default-coding-system)
162           (read-coding-system prompt))
163       'read-coding-system))
164
165   ;; Should keep track of `mm-%s' in mm-util.el.
166   (defalias 'mm-multibyte-string-p
167     (if (fboundp 'multibyte-string-p)
168         'multibyte-string-p
169       'ignore))
170   (defalias 'mm-encode-coding-string 'encode-coding-string)
171   (defalias 'mm-decode-coding-string 'decode-coding-string)
172
173   ;; Should keep track of `mm-detect-coding-region' in mm-util.el.
174   (defun nnheader-detect-coding-region (start end)
175     "Like 'detect-coding-region' except returning the best one."
176     (let ((coding-systems
177            (static-if (boundp 'MULE)
178                (code-detect-region (point) (point-max))
179              (detect-coding-region (point) (point-max)))))
180       (or (car-safe coding-systems)
181           coding-systems)))
182   (defalias 'mm-detect-coding-region 'nnheader-detect-coding-region)
183
184   ;; Should keep track of `mm-detect-mime-charset-region' in mm-util.el.
185   (defun nnheader-detect-mime-charset-region (start end)
186     "Detect MIME charset of the text in the region between START and END."
187     (coding-system-to-mime-charset
188      (nnheader-detect-coding-region start end)))
189   (defalias 'mm-detect-mime-charset-region
190     'nnheader-detect-mime-charset-region)
191
192   ;; Should keep track of `mm-with-unibyte-buffer' in mm-util.el.
193   (defmacro nnheader-with-unibyte-buffer (&rest forms)
194   "Create a temporary buffer, and evaluate FORMS there like `progn'.
195 Use unibyte mode for this."
196   `(let (default-enable-multibyte-characters default-mc-flag)
197      (with-temp-buffer ,@forms)))
198   (put 'nnheader-with-unibyte-buffer 'lisp-indent-function 0)
199   (put 'nnheader-with-unibyte-buffer 'edebug-form-spec '(body))
200   (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
201   (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
202   (defalias 'mm-with-unibyte-buffer 'nnheader-with-unibyte-buffer)
203
204   ;; Should keep track of `mm-with-unibyte-current-buffer' in mm-util.el.
205   (defmacro nnheader-with-unibyte-current-buffer (&rest forms)
206     "Evaluate FORMS with current current buffer temporarily made unibyte.
207 Also bind `default-enable-multibyte-characters' to nil.
208 Equivalent to `progn' in XEmacs"
209     (let ((multibyte (make-symbol "multibyte"))
210           (buffer (make-symbol "buffer")))
211       (cond ((featurep 'xemacs)
212              `(let (default-enable-multibyte-characters)
213                 ,@forms))
214             ((boundp 'MULE)
215              `(let ((,multibyte mc-flag)
216                     (,buffer (current-buffer)))
217                 (unwind-protect
218                     (let (default-enable-multibyte-characters default-mc-flag)
219                       (setq mc-flag nil)
220                       ,@forms)
221                   (set-buffer ,buffer)
222                   (setq mc-flag ,multibyte))))
223             (t
224              `(let ((,multibyte enable-multibyte-characters)
225                     (,buffer (current-buffer)))
226                 (unwind-protect
227                     (let (default-enable-multibyte-characters)
228                       (set-buffer-multibyte nil)
229                       ,@forms)
230                   (set-buffer ,buffer)
231                   (set-buffer-multibyte ,multibyte)))))))
232   (put 'nnheader-with-unibyte-current-buffer 'lisp-indent-function 0)
233   (put 'nnheader-with-unibyte-current-buffer 'edebug-form-spec '(body))
234   (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
235   (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
236   (defalias 'mm-with-unibyte-current-buffer
237     'nnheader-with-unibyte-current-buffer)
238
239   ;; Should keep track of `mm-with-unibyte' in mm-util.el.
240   (defmacro nnheader-with-unibyte (&rest forms)
241     "Eval the FORMS with the default value of `enable-multibyte-characters'
242 nil, ."
243     `(let (default-enable-multibyte-characters)
244        ,@forms))
245   (put 'nnheader-with-unibyte 'lisp-indent-function 0)
246   (put 'nnheader-with-unibyte 'edebug-form-spec '(body))
247   (put 'mm-with-unibyte 'lisp-indent-function 0)
248   (put 'mm-with-unibyte 'edebug-form-spec '(body))
249   (defalias 'mm-with-unibyte 'nnheader-with-unibyte)
250
251   ;; Should keep track of `mm-guess-mime-charset' in mm-util.el.
252   (defun nnheader-guess-mime-charset ()
253   "Guess the default MIME charset from the language environment."
254   (let ((language-info
255          (and (boundp 'current-language-environment)
256               (assoc current-language-environment
257                      language-info-alist)))
258         item)
259     (cond
260      ((null language-info)
261       'iso-8859-1)
262      ((setq item
263             (cadr
264              (or (assq 'coding-priority language-info)
265                  (assq 'coding-system language-info))))
266       (if (fboundp 'coding-system-get)
267           (or (coding-system-get item 'mime-charset)
268               item)
269         item))
270      ((setq item (car (last (assq 'charset language-info))))
271       (if (eq item 'ascii)
272           'iso-8859-1
273          (charsets-to-mime-charset (list item))))
274      (t
275       'iso-8859-1))))
276   (defalias 'mm-guess-mime-charset 'nnheader-guess-mime-charset)
277
278   (defalias 'mm-char-int 'char-int)
279
280   ;; Should keep track of the same alias in mm-util.el.
281   (defalias 'mm-multibyte-p
282     (static-cond ((and (featurep 'xemacs) (featurep 'mule))
283                   (lambda nil t))
284                  ((featurep 'xemacs)
285                   (lambda nil nil))
286                  ((boundp 'MULE)
287                   (lambda nil mc-flag))
288                  (t
289                   (lambda nil enable-multibyte-characters))))
290
291   ;; Should keep track of the same alias in mm-util.el.
292   (defalias 'mm-make-temp-file
293     (if (fboundp 'make-temp-file)
294         'make-temp-file
295       (lambda (prefix &optional dir-flag)
296         (let ((file (expand-file-name
297                      (make-temp-name prefix)
298                      (if (fboundp 'temp-directory)
299                          (temp-directory)
300                        temporary-file-directory))))
301           (if dir-flag
302               (make-directory file))
303           file)))))
304
305 ;; mail-parse stuff.
306 (unless (featurep 'mail-parse)
307   ;; Should keep track of `rfc2047-narrow-to-field' in rfc2047.el.
308   (defun-maybe std11-narrow-to-field ()
309     "Narrow the buffer to the header on the current line."
310     (forward-line 0)
311     (narrow-to-region (point)
312                       (progn
313                         (std11-field-end)
314                         (when (eolp) (forward-line 1))
315                         (point)))
316     (goto-char (point-min)))
317   (defalias 'mail-header-narrow-to-field 'std11-narrow-to-field)
318
319   ;; Should keep track of `ietf-drums-narrow-to-header' in ietf-drums.el.
320   (defun mail-narrow-to-head ()
321     "Narrow to the header section in the current buffer."
322     (narrow-to-region
323      (goto-char (point-min))
324      (if (re-search-forward "^\r?$" nil 1)
325          (match-beginning 0)
326        (point-max)))
327     (goto-char (point-min)))
328
329   ;; Should keep track of `rfc2047-fold-region' in rfc2047.el.
330   (defun-maybe std11-fold-region (b e)
331     "Fold long lines in region B to E."
332     (save-restriction
333       (narrow-to-region b e)
334       (goto-char (point-min))
335       (let ((break nil)
336             (qword-break nil)
337             (first t)
338             (bol (save-restriction
339                    (widen)
340                    (gnus-point-at-bol))))
341         (while (not (eobp))
342           (when (and (or break qword-break)
343                      (> (- (point) bol) 76))
344             (goto-char (or break qword-break))
345             (setq break nil
346                   qword-break nil)
347             (if (looking-at "[ \t]")
348                 (insert "\n")
349               (insert "\n "))
350             (setq bol (1- (point)))
351             ;; Don't break before the first non-LWSP characters.
352             (skip-chars-forward " \t")
353             (unless (eobp)
354               (forward-char 1)))
355           (cond
356            ((eq (char-after) ?\n)
357             (forward-char 1)
358             (setq bol (point)
359                   break nil
360                   qword-break nil)
361             (skip-chars-forward " \t")
362             (unless (or (eobp) (eq (char-after) ?\n))
363               (forward-char 1)))
364            ((eq (char-after) ?\r)
365             (forward-char 1))
366            ((memq (char-after) '(?  ?\t))
367             (skip-chars-forward " \t")
368             (if first
369                 ;; Don't break just after the header name.
370                 (setq first nil)
371               (setq break (1- (point)))))
372            ((not break)
373             (if (not (looking-at "=\\?[^=]"))
374                 (if (eq (char-after) ?=)
375                     (forward-char 1)
376                   (skip-chars-forward "^ \t\n\r="))
377               (setq qword-break (point))
378               (skip-chars-forward "^ \t\n\r")))
379            (t
380             (skip-chars-forward "^ \t\n\r"))))
381         (when (and (or break qword-break)
382                    (> (- (point) bol) 76))
383           (goto-char (or break qword-break))
384           (setq break nil
385                 qword-break nil)
386           (if (looking-at "[ \t]")
387               (insert "\n")
388             (insert "\n "))
389           (setq bol (1- (point)))
390           ;; Don't break before the first non-LWSP characters.
391           (skip-chars-forward " \t")
392           (unless (eobp)
393             (forward-char 1))))))
394
395   ;; Should keep track of `rfc2047-fold-field' in rfc2047.el.
396   (defun-maybe std11-fold-field ()
397     "Fold the current line."
398     (save-excursion
399       (save-restriction
400         (std11-narrow-to-field)
401         (std11-fold-region (point-min) (point-max)))))
402
403   (defalias 'mail-header-fold-field 'std11-fold-field)
404
405   ;; Should keep track of `rfc2047-unfold-region' in rfc2047.el.
406   (defun-maybe std11-unfold-region (b e)
407     "Unfold lines in region B to E."
408     (save-restriction
409       (narrow-to-region b e)
410       (goto-char (point-min))
411       (let ((bol (save-restriction
412                    (widen)
413                    (gnus-point-at-bol)))
414             (eol (gnus-point-at-eol)))
415         (forward-line 1)
416         (while (not (eobp))
417           (if (and (looking-at "[ \t]")
418                    (< (- (gnus-point-at-eol) bol) 76))
419               (delete-region eol (progn
420                                    (goto-char eol)
421                                    (skip-chars-forward "\r\n")
422                                    (point)))
423             (setq bol (gnus-point-at-bol)))
424           (setq eol (gnus-point-at-eol))
425           (forward-line 1)))))
426
427   ;; Should keep track of `rfc2047-unfold-field' in rfc2047.el.
428   (defun-maybe std11-unfold-field ()
429     "Fold the current line."
430     (save-excursion
431       (save-restriction
432         (std11-narrow-to-field)
433         (std11-unfold-region (point-min) (point-max)))))
434
435   (defalias 'mail-header-unfold-field 'std11-unfold-field)
436
437   ;; This is the original function in T-gnus.
438   (defun-maybe std11-extract-addresses-components (string)
439     "Extract a list of full name and canonical address from STRING.  Each
440 element looks like a list of the form (FULL-NAME CANONICAL-ADDRESS).
441 If no name can be extracted, FULL-NAME will be nil."
442     (when string
443       (let (addresses)
444         (dolist (structure (std11-parse-addresses-string
445                             (std11-unfold-string string))
446                            addresses)
447           (push (list (std11-full-name-string structure)
448                       (std11-address-string structure))
449                 addresses))
450         (nreverse addresses))))
451
452   ;; Should keep track of `ietf-drums-parse-addresses' in ietf-drums.el.
453   (defun mail-header-parse-addresses (string)
454     "Parse STRING and return a list of MAILBOX / DISPLAY-NAME pairs."
455     (mapcar (function
456              (lambda (components)
457                (cons (nth 1 components) (car components))))
458             (std11-extract-addresses-components string)))
459
460   ;; Should keep track of `rfc2047-field-value' in rfc2047.el.
461   (defun std11-field-value (&optional dont-include-last-newline)
462     "Return the value of the field at point.  If the optional argument is
463 given, the return value will not contain the last newline."
464     (let ((begin (point))
465           (inhibit-point-motion-hooks t)
466           start value)
467       (beginning-of-line)
468       (unless (eobp)
469         (while (and (memq (char-after) '(?\t ?\ ))
470                     (zerop (forward-line -1))))
471         (when (looking-at "[^\t\n ]+:[\t\n ]+")
472           (goto-char (setq start (match-end 0)))
473           (forward-line 1)
474           (while (and (memq (char-after) '(?\t ?\ ))
475                       (zerop (forward-line 1))))
476           (when dont-include-last-newline
477             (skip-chars-backward "\t\n " start))
478           (setq value (buffer-substring start (point)))))
479       (goto-char begin)
480       value))
481
482   (defalias 'mail-header-field-value 'std11-field-value))
483
484 ;; ietf-drums stuff.
485 (unless (featurep 'ietf-drums)
486   ;; Should keep track of `ietf-drums-unfold-fws' in ietf-drums.el.
487   (defun nnheader-unfold-fws ()
488     "Unfold folding white space in the current buffer."
489     (goto-char (point-min))
490     (while (re-search-forward "[ \t]*\n[ \t]+" nil t)
491       (replace-match " " t t))
492     (goto-char (point-min)))
493
494   (defalias 'ietf-drums-unfold-fws 'nnheader-unfold-fws))
495
496 ;;; Header access macros.
497
498 ;; These macros may look very much like the ones in GNUS 4.1.  They
499 ;; are, in a way, but you should note that the indices they use have
500 ;; been changed from the internal GNUS format to the NOV format.  The
501 ;; makes it possible to read headers from XOVER much faster.
502 ;;
503 ;; The format of a header is now:
504 ;; [number subject from date id references chars lines xref extra]
505 ;;
506 ;; (That next-to-last entry is defined as "misc" in the NOV format,
507 ;; but Gnus uses it for xrefs.)
508
509 (require 'mmgnus)
510
511 (defmacro mail-header-number (header)
512   "Return article number in HEADER."
513   `(mime-entity-location-internal ,header))
514
515 (defmacro mail-header-set-number (header number)
516   "Set article number of HEADER to NUMBER."
517   `(mime-entity-set-location-internal ,header ,number))
518
519 (defalias 'mail-header-subject 'mime-gnus-entity-subject-internal)
520 (defalias 'mail-header-set-subject 'mime-gnus-entity-set-subject-internal)
521
522 (defalias 'mail-header-from 'mime-gnus-entity-from-internal)
523 (defalias 'mail-header-set-from 'mime-gnus-entity-set-from-internal)
524
525 (defalias 'mail-header-date 'mime-gnus-entity-date-internal)
526 (defalias 'mail-header-set-date 'mime-gnus-entity-set-date-internal)
527
528 (defalias 'mail-header-message-id 'mime-gnus-entity-id-internal)
529 (defalias 'mail-header-id 'mime-gnus-entity-id-internal)
530 (defalias 'mail-header-set-message-id 'mime-gnus-entity-set-id-internal)
531 (defalias 'mail-header-set-id 'mime-gnus-entity-set-id-internal)
532
533 (defalias 'mail-header-references 'mime-gnus-entity-references-internal)
534 (defalias 'mail-header-set-references
535   'mime-gnus-entity-set-references-internal)
536
537 (defalias 'mail-header-chars 'mime-gnus-entity-chars-internal)
538 (defalias 'mail-header-set-chars 'mime-gnus-entity-set-chars-internal)
539
540 (defalias 'mail-header-lines 'mime-gnus-entity-lines-internal)
541 (defalias 'mail-header-set-lines 'mime-gnus-entity-set-lines-internal)
542
543 (defalias 'mail-header-xref 'mime-gnus-entity-xref-internal)
544 (defalias 'mail-header-set-xref 'mime-gnus-entity-set-xref-internal)
545
546 (defalias 'nnheader-decode-subject
547   (mime-find-field-decoder 'Subject 'nov))
548 (defalias 'nnheader-decode-from
549   (mime-find-field-decoder 'From 'nov))
550
551 (defalias 'mail-header-extra 'mime-gnus-entity-extra-internal)
552 (defalias 'mail-header-set-extra 'mime-gnus-entity-set-extra-internal)
553
554 (defun nnheader-decode-field-body (field-body field-name
555                                               &optional mode max-column)
556   (mime-decode-field-body field-body
557                           (if (stringp field-name)
558                               (intern (capitalize field-name))
559                             field-name)
560                           mode max-column))
561
562 (defsubst make-full-mail-header (&optional number subject from date id
563                                            references chars lines xref
564                                            extra)
565   "Create a new mail header structure initialized with the parameters given."
566   (luna-make-entity (mm-expand-class-name 'gnus)
567                     :location number
568                     :subject (if subject
569                                  (nnheader-decode-subject subject))
570                     :from (if from
571                               (nnheader-decode-from from))
572                     :date date
573                     :id id
574                     :references references
575                     :chars chars
576                     :lines lines
577                     :xref xref
578                     :original-header (list (cons 'Subject subject)
579                                            (cons 'From from))
580                     :extra extra))
581
582 (defsubst make-full-mail-header-from-decoded-header
583   (&optional number subject from date id references chars lines xref extra)
584   "Create a new mail header structure initialized with the parameters given."
585   (luna-make-entity (mm-expand-class-name 'gnus)
586                     :location number
587                     :subject subject
588                     :from from
589                     :date date
590                     :id id
591                     :references references
592                     :chars chars
593                     :lines lines
594                     :xref xref
595                     :extra extra))
596
597 (defsubst make-mail-header (&optional init)
598   "Create a new mail header structure initialized with INIT."
599   (make-full-mail-header init init init init init
600                          init init init init init))
601
602 ;; fake message-ids: generation and detection
603
604 (defvar nnheader-fake-message-id 1)
605
606 (defsubst nnheader-generate-fake-message-id ()
607   (concat "fake+none+" (int-to-string (incf nnheader-fake-message-id))))
608
609 (defsubst nnheader-fake-message-id-p (id)
610   (save-match-data                      ; regular message-id's are <.*>
611     (string-match "\\`fake\\+none\\+[0-9]+\\'" id)))
612
613 ;; Parsing headers and NOV lines.
614
615 (defsubst nnheader-remove-cr-followed-by-lf ()
616   (goto-char (point-max))
617   (while (search-backward "\r\n" nil t)
618     (delete-char 1)))
619
620 (defsubst nnheader-header-value ()
621   (let ((pt (point)))
622     (prog2
623         (skip-chars-forward " \t")
624         (buffer-substring (point) (std11-field-end))
625       (goto-char pt))))
626
627 (defun nnheader-parse-naked-head (&optional number)
628   ;; This function unfolds continuation lines in this buffer
629   ;; destructively.  When this side effect is unwanted, use
630   ;; `nnheader-parse-head' instead of this function.
631   (let ((case-fold-search t)
632         (buffer-read-only nil)
633         (cur (current-buffer))
634         (p (point-min))
635         in-reply-to lines ref)
636     (nnheader-remove-cr-followed-by-lf)
637     (ietf-drums-unfold-fws)
638     (subst-char-in-region (point-min) (point-max) ?\t ? )
639     (goto-char p)
640     (insert "\n")
641     (prog1
642         ;; This implementation of this function, with nine
643         ;; search-forwards instead of the one re-search-forward and a
644         ;; case (which basically was the old function) is actually
645         ;; about twice as fast, even though it looks messier.  You
646         ;; can't have everything, I guess.  Speed and elegance don't
647         ;; always go hand in hand.
648         (make-full-mail-header
649          ;; Number.
650          (or number 0)
651          ;; Subject.
652          (progn
653            (goto-char p)
654            (if (search-forward "\nsubject:" nil t)
655                (nnheader-header-value) "(none)"))
656          ;; From.
657          (progn
658            (goto-char p)
659            (if (search-forward "\nfrom:" nil t)
660                (nnheader-header-value) "(nobody)"))
661          ;; Date.
662          (progn
663            (goto-char p)
664            (if (search-forward "\ndate:" nil t)
665                (nnheader-header-value) ""))
666          ;; Message-ID.
667          (progn
668            (goto-char p)
669            (if (search-forward "\nmessage-id:" nil t)
670                (buffer-substring
671                 (1- (or (search-forward "<" (gnus-point-at-eol) t)
672                         (point)))
673                 (or (search-forward ">" (gnus-point-at-eol) t) (point)))
674              ;; If there was no message-id, we just fake one to make
675              ;; subsequent routines simpler.
676              (nnheader-generate-fake-message-id)))
677          ;; References.
678          (progn
679            (goto-char p)
680            (if (search-forward "\nreferences:" nil t)
681                (nnheader-header-value)
682              ;; Get the references from the in-reply-to header if
683              ;; there were no references and the in-reply-to header
684              ;; looks promising.
685              (if (and (search-forward "\nin-reply-to:" nil t)
686                       (setq in-reply-to (nnheader-header-value))
687                       (string-match "<[^\n>]+>" in-reply-to))
688                  (let (ref2)
689                    (setq ref (substring in-reply-to (match-beginning 0)
690                                         (match-end 0)))
691                    (while (string-match "<[^\n>]+>"
692                                         in-reply-to (match-end 0))
693                      (setq ref2 (substring in-reply-to (match-beginning 0)
694                                            (match-end 0)))
695                      (when (> (length ref2) (length ref))
696                        (setq ref ref2)))
697                    ref)
698                nil)))
699          ;; Chars.
700          0
701          ;; Lines.
702          (progn
703            (goto-char p)
704            (if (search-forward "\nlines: " nil t)
705                (if (numberp (setq lines (read cur)))
706                    lines 0)
707              0))
708          ;; Xref.
709          (progn
710            (goto-char p)
711            (and (search-forward "\nxref:" nil t)
712                 (nnheader-header-value)))
713          ;; Extra.
714          (when nnmail-extra-headers
715            (let ((extra nnmail-extra-headers)
716                  out)
717              (while extra
718                (goto-char p)
719                (when (search-forward
720                       (concat "\n" (symbol-name (car extra)) ":") nil t)
721                  (push (cons (car extra) (nnheader-header-value))
722                        out))
723                (pop extra))
724              out)))
725       (goto-char p)
726       (delete-char 1))))
727
728 (defun nnheader-parse-head (&optional naked)
729   (let ((cur (current-buffer)) num beg end)
730     (when (if naked
731               (setq num 0
732                     beg (point-min)
733                     end (point-max))
734             (goto-char (point-min))
735             ;; Search to the beginning of the next header.  Error
736             ;; messages do not begin with 2 or 3.
737             (when (re-search-forward "^[23][0-9]+ " nil t)
738               (end-of-line)
739               (setq num (read cur)
740                     beg (point)
741                     end (if (search-forward "\n.\n" nil t)
742                             (- (point) 2)
743                           (point)))))
744       (with-temp-buffer
745         (insert-buffer-substring cur beg end)
746         (nnheader-parse-naked-head num)))))
747
748 (defmacro nnheader-nov-skip-field ()
749   '(search-forward "\t" eol 'move))
750
751 (defmacro nnheader-nov-field ()
752   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
753
754 (defmacro nnheader-nov-read-integer ()
755   '(prog1
756        (if (eq (char-after) ?\t)
757            0
758          (let ((num (condition-case nil
759                         (read (current-buffer))
760                       (error nil))))
761            (if (numberp num) num 0)))
762      (unless (eobp)
763        (search-forward "\t" eol 'move))))
764
765 (defmacro nnheader-nov-parse-extra ()
766   '(let (out string)
767      (while (not (memq (char-after) '(?\n nil)))
768        (setq string (nnheader-nov-field))
769        (when (string-match "^\\([^ :]+\\): " string)
770          (push (cons (intern (match-string 1 string))
771                      (substring string (match-end 0)))
772                out)))
773      out))
774
775 (defmacro nnheader-nov-read-message-id ()
776   '(let ((id (nnheader-nov-field)))
777      (if (string-match "^<[^>]+>$" id)
778          id
779        (nnheader-generate-fake-message-id))))
780
781 (defun nnheader-parse-nov ()
782   (let ((eol (gnus-point-at-eol)))
783     (make-full-mail-header
784      (nnheader-nov-read-integer)        ; number
785      (nnheader-nov-field)               ; subject
786      (nnheader-nov-field)               ; from
787      (nnheader-nov-field)               ; date
788      (nnheader-nov-read-message-id)     ; id
789      (nnheader-nov-field)               ; refs
790      (nnheader-nov-read-integer)        ; chars
791      (nnheader-nov-read-integer)        ; lines
792      (if (eq (char-after) ?\n)
793          nil
794        (if (looking-at "Xref: ")
795            (goto-char (match-end 0)))
796        (nnheader-nov-field))            ; Xref
797      (nnheader-nov-parse-extra))))      ; extra
798
799 (defun nnheader-insert-nov (header)
800   (princ (mail-header-number header) (current-buffer))
801   (let ((p (point)))
802     (insert
803      "\t"
804      (or (mime-entity-fetch-field header 'Subject) "(none)") "\t"
805      (or (mime-entity-fetch-field header 'From) "(nobody)") "\t"
806      (or (mail-header-date header) "") "\t"
807      (or (mail-header-id header)
808          (nnmail-message-id))
809      "\t"
810      (or (mail-header-references header) "") "\t")
811     (princ (or (mail-header-chars header) 0) (current-buffer))
812     (insert "\t")
813     (princ (or (mail-header-lines header) 0) (current-buffer))
814     (insert "\t")
815     (when (mail-header-xref header)
816       (insert "Xref: " (mail-header-xref header)))
817     (when (or (mail-header-xref header)
818               (mail-header-extra header))
819       (insert "\t"))
820     (when (mail-header-extra header)
821       (let ((extra (mail-header-extra header)))
822         (while extra
823           (insert (symbol-name (caar extra))
824                   ": " (cdar extra) "\t")
825           (pop extra))))
826     (insert "\n")
827     (backward-char 1)
828     (while (search-backward "\n" p t)
829       (delete-char 1))
830     (forward-line 1)))
831
832 (defun nnheader-parse-overview-file (file)
833   "Parse FILE and return a list of headers."
834   (mm-with-unibyte-buffer
835     (nnheader-insert-file-contents file)
836     (goto-char (point-min))
837     (let (headers)
838       (while (not (eobp))
839         (push (nnheader-parse-nov) headers)
840         (forward-line 1))
841       (nreverse headers))))
842
843 (defun nnheader-write-overview-file (file headers)
844   "Write HEADERS to FILE."
845   (with-temp-file file
846     (mapcar 'nnheader-insert-nov headers)))
847
848 (defun nnheader-insert-header (header)
849   (insert
850    "Subject: " (or (mail-header-subject header) "(none)") "\n"
851    "From: " (or (mail-header-from header) "(nobody)") "\n"
852    "Date: " (or (mail-header-date header) "") "\n"
853    "Message-ID: " (or (mail-header-id header) (nnmail-message-id)) "\n"
854    "References: " (or (mail-header-references header) "") "\n"
855    "Lines: ")
856   (princ (or (mail-header-lines header) 0) (current-buffer))
857   (insert "\n\n"))
858
859 (defun nnheader-insert-article-line (article)
860   (goto-char (point-min))
861   (insert "220 ")
862   (princ article (current-buffer))
863   (insert " Article retrieved.\n")
864   (search-forward "\n\n" nil 'move)
865   (delete-region (point) (point-max))
866   (forward-char -1)
867   (insert "."))
868
869 (defun nnheader-nov-delete-outside-range (beg end)
870   "Delete all NOV lines that lie outside the BEG to END range."
871   ;; First we find the first wanted line.
872   (nnheader-find-nov-line beg)
873   (delete-region (point-min) (point))
874   ;; Then we find the last wanted line.
875   (when (nnheader-find-nov-line end)
876     (forward-line 1))
877   (delete-region (point) (point-max)))
878
879 (defun nnheader-find-nov-line (article)
880   "Put point at the NOV line that start with ARTICLE.
881 If ARTICLE doesn't exist, put point where that line
882 would have been.  The function will return non-nil if
883 the line could be found."
884   ;; This function basically does a binary search.
885   (let ((max (point-max))
886         (min (goto-char (point-min)))
887         (cur (current-buffer))
888         (prev (point-min))
889         num found)
890     (while (not found)
891       (goto-char (+ min (/ (- max min) 2)))
892       (beginning-of-line)
893       (if (or (= (point) prev)
894               (eobp))
895           (setq found t)
896         (setq prev (point))
897         (while (and (not (numberp (setq num (read cur))))
898                     (not (eobp)))
899           (gnus-delete-line))
900         (cond ((> num article)
901                (setq max (point)))
902               ((< num article)
903                (setq min (point)))
904               (t
905                (setq found 'yes)))))
906     ;; We may be at the first line.
907     (when (and (not num)
908                (not (eobp)))
909       (setq num (read cur)))
910     ;; Now we may have found the article we're looking for, or we
911     ;; may be somewhere near it.
912     (when (and (not (eq found 'yes))
913                (not (eq num article)))
914       (setq found (point))
915       (while (and (< (point) max)
916                   (or (not (numberp num))
917                       (< num article)))
918         (forward-line 1)
919         (setq found (point))
920         (or (eobp)
921             (= (setq num (read cur)) article)))
922       (unless (eq num article)
923         (goto-char found)))
924     (beginning-of-line)
925     (eq num article)))
926
927 (defun nnheader-retrieve-headers-from-directory* (articles
928                                                   directory dependencies
929                                                   &optional
930                                                   fetch-old force-new large
931                                                   backend)
932   (with-temp-buffer
933     (let* ((file nil)
934            (number (length articles))
935            (count 0)
936            (file-name-coding-system 'binary)
937            (pathname-coding-system 'binary)
938            (case-fold-search t)
939            (cur (current-buffer))
940            article
941            headers header id end ref in-reply-to lines chars ctype)
942       ;; We don't support fetching by Message-ID.
943       (if (stringp (car articles))
944           'headers
945         (while articles
946           (when (and (file-exists-p
947                       (setq file (expand-file-name
948                                   (int-to-string
949                                    (setq article (pop articles)))
950                                   directory)))
951                      (not (file-directory-p file)))
952             (erase-buffer)
953             (nnheader-insert-head file)
954             (save-restriction
955               (std11-narrow-to-header)
956               (setq
957                header
958                (make-full-mail-header
959                 ;; Number.
960                 article
961                 ;; Subject.
962                 (or (std11-fetch-field "Subject")
963                     "(none)")
964                 ;; From.
965                 (or (std11-fetch-field "From")
966                     "(nobody)")
967                 ;; Date.
968                 (or (std11-fetch-field "Date")
969                     "")
970                 ;; Message-ID.
971                 (progn
972                   (goto-char (point-min))
973                   (setq id (if (re-search-forward
974                                 "^Message-ID: *\\(<[^\n\t> ]+>\\)" nil t)
975                                ;; We do it this way to make sure the Message-ID
976                                ;; is (somewhat) syntactically valid.
977                                (buffer-substring (match-beginning 1)
978                                                  (match-end 1))
979                              ;; If there was no message-id, we just fake one
980                              ;; to make subsequent routines simpler.
981                              (nnheader-generate-fake-message-id))))
982                 ;; References.
983                 (progn
984                   (goto-char (point-min))
985                   (if (search-forward "\nReferences: " nil t)
986                       (progn
987                         (setq end (point))
988                         (prog1
989                             (buffer-substring (match-end 0) (std11-field-end))
990                           (setq ref
991                                 (buffer-substring
992                                  (progn
993                                    ;; (end-of-line)
994                                    (search-backward ">" end t)
995                                    (1+ (point)))
996                                  (progn
997                                    (search-backward "<" end t)
998                                    (point))))))
999                     ;; Get the references from the in-reply-to header if there
1000                     ;; were no references and the in-reply-to header looks
1001                     ;; promising.
1002                     (if (and (search-forward "\nIn-Reply-To: " nil t)
1003                              (setq in-reply-to
1004                                    (buffer-substring (match-end 0)
1005                                                      (std11-field-end)))
1006                              (string-match "<[^>]+>" in-reply-to))
1007                         (let (ref2)
1008                           (setq ref (substring in-reply-to (match-beginning 0)
1009                                                (match-end 0)))
1010                           (while (string-match "<[^>]+>"
1011                                                in-reply-to (match-end 0))
1012                             (setq ref2
1013                                   (substring in-reply-to (match-beginning 0)
1014                                              (match-end 0)))
1015                             (when (> (length ref2) (length ref))
1016                               (setq ref ref2)))
1017                           ref)
1018                       (setq ref nil))))
1019                 ;; Chars.
1020                 (progn
1021                   (goto-char (point-min))
1022                   (if (search-forward "\nChars: " nil t)
1023                       (if (numberp (setq chars (ignore-errors (read cur))))
1024                           chars 0)
1025                     0))
1026                 ;; Lines.
1027                 (progn
1028                   (goto-char (point-min))
1029                   (if (search-forward "\nLines: " nil t)
1030                       (if (numberp (setq lines (ignore-errors (read cur))))
1031                           lines 0)
1032                     0))
1033                 ;; Xref.
1034                 (std11-fetch-field "Xref")
1035                 ))
1036               (goto-char (point-min))
1037               (if (setq ctype (std11-fetch-field "Content-Type"))
1038                   (mime-entity-set-content-type-internal
1039                    header (mime-parse-Content-Type ctype)))
1040               )
1041             (when (setq header
1042                         (gnus-dependencies-add-header
1043                          header dependencies force-new))
1044               (push header headers))
1045             )
1046           (setq count (1+ count))
1047
1048           (and large
1049                (zerop (% count 20))
1050                (nnheader-message 5 "%s: Receiving headers... %d%%"
1051                                  backend
1052                                  (/ (* count 100) number))))
1053
1054         (when large
1055           (nnheader-message 5 "%s: Receiving headers...done" backend))
1056
1057         headers))))
1058
1059 (defun nnheader-retrieve-headers-from-directory (articles
1060                                                  directory dependencies
1061                                                  &optional
1062                                                  fetch-old force-new large
1063                                                  backend)
1064   (cons 'header
1065         (nreverse (nnheader-retrieve-headers-from-directory*
1066                    articles directory dependencies
1067                    fetch-old force-new large backend))))
1068
1069 (defun nnheader-get-newsgroup-headers-xover* (sequence
1070                                               &optional
1071                                               force-new dependencies
1072                                               group)
1073   "Parse the news overview data in the server buffer, and return a
1074 list of headers that match SEQUENCE (see `nntp-retrieve-headers')."
1075   ;; Get the Xref when the users reads the articles since most/some
1076   ;; NNTP servers do not include Xrefs when using XOVER.
1077   ;; (setq gnus-article-internal-prepare-hook '(gnus-article-get-xrefs))
1078   (let ((cur nntp-server-buffer)
1079         number headers header)
1080     (save-excursion
1081       (set-buffer nntp-server-buffer)
1082       ;; Allow the user to mangle the headers before parsing them.
1083       (gnus-run-hooks 'gnus-parse-headers-hook)
1084       (goto-char (point-min))
1085       (while (not (eobp))
1086         (condition-case ()
1087             (while (and sequence (not (eobp)))
1088               (setq number (read cur))
1089               (while (and sequence
1090                           (< (car sequence) number))
1091                 (setq sequence (cdr sequence)))
1092               (and sequence
1093                    (eq number (car sequence))
1094                    (progn
1095                      (setq sequence (cdr sequence))
1096                      (setq header (inline
1097                                     (gnus-nov-parse-line
1098                                      number dependencies force-new))))
1099                    (push header headers))
1100               (forward-line 1))
1101           (error
1102            (gnus-error 4 "Strange nov line (%d)"
1103                        (count-lines (point-min) (point)))))
1104         (forward-line 1))
1105       ;; A common bug in inn is that if you have posted an article and
1106       ;; then retrieves the active file, it will answer correctly --
1107       ;; the new article is included.  However, a NOV entry for the
1108       ;; article may not have been generated yet, so this may fail.
1109       ;; We work around this problem by retrieving the last few
1110       ;; headers using HEAD.
1111       headers)))
1112
1113 ;; Various cruft the backends and Gnus need to communicate.
1114
1115 (defvar nntp-server-buffer nil)
1116 (defvar nntp-process-response nil)
1117 (defvar news-reply-yank-from nil)
1118 (defvar news-reply-yank-message-id nil)
1119
1120 (defvar nnheader-callback-function nil)
1121
1122 (defun nnheader-init-server-buffer ()
1123   "Initialize the Gnus-backend communication buffer."
1124   (save-excursion
1125     (unless (gnus-buffer-live-p nntp-server-buffer)
1126       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
1127     (set-buffer nntp-server-buffer)
1128     (erase-buffer)
1129     (kill-all-local-variables)
1130     (setq case-fold-search t)           ;Should ignore case.
1131     (set (make-local-variable 'nntp-process-response) nil)
1132     t))
1133
1134 ;;; Various functions the backends use.
1135
1136 (defun nnheader-file-error (file)
1137   "Return a string that says what is wrong with FILE."
1138   (format
1139    (cond
1140     ((not (file-exists-p file))
1141      "%s does not exist")
1142     ((file-directory-p file)
1143      "%s is a directory")
1144     ((not (file-readable-p file))
1145      "%s is not readable"))
1146    file))
1147
1148 (defun nnheader-insert-head (file)
1149   "Insert the head of the article."
1150   (when (file-exists-p file)
1151     (if (eq nnheader-max-head-length t)
1152         ;; Just read the entire file.
1153         (nnheader-insert-file-contents file)
1154       ;; Read 1K blocks until we find a separator.
1155       (let ((beg 0)
1156             format-alist)
1157         (while (and (eq nnheader-head-chop-length
1158                         (nth 1 (nnheader-insert-file-contents
1159                                 file nil beg
1160                                 (incf beg nnheader-head-chop-length))))
1161                     (prog1 (not (search-forward "\n\n" nil t))
1162                       (goto-char (point-max)))
1163                     (or (null nnheader-max-head-length)
1164                         (< beg nnheader-max-head-length))))))
1165     t))
1166
1167 (defun nnheader-article-p ()
1168   "Say whether the current buffer looks like an article."
1169   (goto-char (point-min))
1170   (if (not (search-forward "\n\n" nil t))
1171       nil
1172     (narrow-to-region (point-min) (1- (point)))
1173     (goto-char (point-min))
1174     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
1175       (goto-char (match-end 0)))
1176     (prog1
1177         (eobp)
1178       (widen))))
1179
1180 (defun nnheader-insert-references (references message-id)
1181   "Insert a References header based on REFERENCES and MESSAGE-ID."
1182   (if (and (not references) (not message-id))
1183       ;; This is invalid, but not all articles have Message-IDs.
1184       ()
1185     (mail-position-on-field "References")
1186     (let ((begin (gnus-point-at-bol))
1187           (fill-column 78)
1188           (fill-prefix "\t"))
1189       (when references
1190         (insert references))
1191       (when (and references message-id)
1192         (insert " "))
1193       (when message-id
1194         (insert message-id))
1195       ;; Fold long References lines to conform to RFC1036 (sort of).
1196       ;; The region must end with a newline to fill the region
1197       ;; without inserting extra newline.
1198       (fill-region-as-paragraph begin (1+ (point))))))
1199
1200 (defun nnheader-replace-header (header new-value)
1201   "Remove HEADER and insert the NEW-VALUE."
1202   (save-excursion
1203     (save-restriction
1204       (nnheader-narrow-to-headers)
1205       (prog1
1206           (message-remove-header header)
1207         (goto-char (point-max))
1208         (insert header ": " new-value "\n")))))
1209
1210 (defun nnheader-narrow-to-headers ()
1211   "Narrow to the head of an article."
1212   (widen)
1213   (narrow-to-region
1214    (goto-char (point-min))
1215    (if (search-forward "\n\n" nil t)
1216        (1- (point))
1217      (point-max)))
1218   (goto-char (point-min)))
1219
1220 (defun nnheader-remove-body ()
1221   "Remove the body from an article in this current buffer."
1222   (goto-char (point-min))
1223   (when (re-search-forward "\n\r?\n" nil t)
1224     (delete-region (point) (point-max))))
1225
1226 (defun nnheader-set-temp-buffer (name &optional noerase)
1227   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
1228   (set-buffer (get-buffer-create name))
1229   (buffer-disable-undo)
1230   (unless noerase
1231     (erase-buffer))
1232   (current-buffer))
1233
1234 (eval-when-compile (defvar jka-compr-compression-info-list))
1235 (defvar nnheader-numerical-files
1236   (if (boundp 'jka-compr-compression-info-list)
1237       (concat "\\([0-9]+\\)\\("
1238               (mapconcat (lambda (i) (aref i 0))
1239                          jka-compr-compression-info-list "\\|")
1240               "\\)?")
1241     "[0-9]+$")
1242   "Regexp that match numerical files.")
1243
1244 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
1245   "Regexp that matches numerical file names.")
1246
1247 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
1248   "Regexp that matches numerical full file names.")
1249
1250 (defsubst nnheader-file-to-number (file)
1251   "Take a FILE name and return the article number."
1252   (if (string= nnheader-numerical-short-files "^[0-9]+$")
1253       (string-to-int file)
1254     (string-match nnheader-numerical-short-files file)
1255     (string-to-int (match-string 0 file))))
1256
1257 (defvar nnheader-directory-files-is-safe
1258   (or (eq system-type 'windows-nt)
1259       (and (not (featurep 'xemacs))
1260            (> emacs-major-version 20)))
1261   "If non-nil, Gnus believes `directory-files' is safe.
1262 It has been reported numerous times that `directory-files' fails with
1263 an alarming frequency on NFS mounted file systems. If it is nil,
1264 `nnheader-directory-files-safe' is used.")
1265
1266 (defun nnheader-directory-files-safe (&rest args)
1267   "Execute `directory-files' twice and returns the longer result."
1268   (let ((first (apply 'directory-files args))
1269         (second (apply 'directory-files args)))
1270     (if (> (length first) (length second))
1271         first
1272       second)))
1273
1274 (defun nnheader-directory-articles (dir)
1275   "Return a list of all article files in directory DIR."
1276   (mapcar 'nnheader-file-to-number
1277           (if nnheader-directory-files-is-safe
1278               (directory-files
1279                dir nil nnheader-numerical-short-files t)
1280             (nnheader-directory-files-safe
1281              dir nil nnheader-numerical-short-files t))))
1282
1283 (defun nnheader-article-to-file-alist (dir)
1284   "Return an alist of article/file pairs in DIR."
1285   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
1286           (if nnheader-directory-files-is-safe
1287               (directory-files
1288                dir nil nnheader-numerical-short-files t)
1289             (nnheader-directory-files-safe
1290              dir nil nnheader-numerical-short-files t))))
1291
1292 (defun nnheader-fold-continuation-lines ()
1293   "Fold continuation lines in the current buffer."
1294   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
1295
1296 (defun nnheader-translate-file-chars (file &optional full)
1297   "Translate FILE into something that can be a file name.
1298 If FULL, translate everything."
1299   (if (null nnheader-file-name-translation-alist)
1300       ;; No translation is necessary.
1301       file
1302     (let* ((i 0)
1303            trans leaf path len)
1304       (if full
1305           ;; Do complete translation.
1306           (setq leaf (copy-sequence file)
1307                 path ""
1308                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1)))
1309                       2 0))
1310         ;; We translate -- but only the file name.  We leave the directory
1311         ;; alone.
1312         (if (and (featurep 'xemacs)
1313                  (memq system-type '(cygwin32 win32 w32 mswindows windows-nt
1314                                               cygwin)))
1315             ;; This is needed on NT and stuff, because
1316             ;; file-name-nondirectory is not enough to split
1317             ;; file names, containing ':', e.g.
1318             ;; "d:\\Work\\News\\nntp+news.fido7.ru:fido7.ru.gnu.SCORE"
1319             ;;
1320             ;; we are trying to correctly split such names:
1321             ;; "d:file.name" -> "a:" "file.name"
1322             ;; "aaa:bbb.ccc" -> "" "aaa:bbb.ccc"
1323             ;; "d:aaa\\bbb:ccc"   -> "d:aaa\\" "bbb:ccc"
1324             ;; etc.
1325             ;; to translate then only the file name part.
1326             (progn
1327               (setq leaf file
1328                     path "")
1329               (if (string-match "\\(^\\w:\\|[/\\]\\)\\([^/\\]+\\)$" file)
1330                   (setq leaf (substring file (match-beginning 2))
1331                         path (substring file 0 (match-beginning 2)))))
1332           ;; Emacs DTRT, says andrewi.
1333           (setq leaf (file-name-nondirectory file)
1334                 path (file-name-directory file))))
1335       (setq len (length leaf))
1336       (while (< i len)
1337         (when (setq trans (cdr (assq (aref leaf i)
1338                                      nnheader-file-name-translation-alist)))
1339           (aset leaf i trans))
1340         (incf i))
1341       (concat path leaf))))
1342
1343 (defun nnheader-report (backend &rest args)
1344   "Report an error from the BACKEND.
1345 The first string in ARGS can be a format string."
1346   (set (intern (format "%s-status-string" backend))
1347        (if (< (length args) 2)
1348            (car args)
1349          (apply 'format args)))
1350   nil)
1351
1352 (defun nnheader-get-report (backend)
1353   "Get the most recent report from BACKEND."
1354   (condition-case ()
1355       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
1356                                                              backend))))
1357     (error (nnheader-message 5 ""))))
1358
1359 (defun nnheader-insert (format &rest args)
1360   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
1361 If FORMAT isn't a format string, it and all ARGS will be inserted
1362 without formatting."
1363   (save-excursion
1364     (set-buffer nntp-server-buffer)
1365     (erase-buffer)
1366     (if (string-match "%" format)
1367         (insert (apply 'format format args))
1368       (apply 'insert format args))
1369     t))
1370
1371 (static-if (fboundp 'subst-char-in-string)
1372     (defsubst nnheader-replace-chars-in-string (string from to)
1373       (subst-char-in-string from to string))
1374   (defun nnheader-replace-chars-in-string (string from to)
1375     "Replace characters in STRING from FROM to TO."
1376     (let ((string (substring string 0)) ;Copy string.
1377           (len (length string))
1378           (idx 0))
1379       ;; Replace all occurrences of FROM with TO.
1380       (while (< idx len)
1381         (when (= (aref string idx) from)
1382           (aset string idx to))
1383         (setq idx (1+ idx)))
1384       string)))
1385
1386 (defun nnheader-replace-duplicate-chars-in-string (string from to)
1387   "Replace characters in STRING from FROM to TO."
1388   (let ((string (substring string 0))   ;Copy string.
1389         (len (length string))
1390         (idx 0) prev i)
1391     ;; Replace all occurrences of FROM with TO.
1392     (while (< idx len)
1393       (setq i (aref string idx))
1394       (when (and (eq prev from) (= i from))
1395         (aset string (1- idx) to)
1396         (aset string idx to))
1397       (setq prev i)
1398       (setq idx (1+ idx)))
1399     string))
1400
1401 (defun nnheader-file-to-group (file &optional top)
1402   "Return a group name based on FILE and TOP."
1403   (nnheader-replace-chars-in-string
1404    (if (not top)
1405        file
1406      (condition-case ()
1407          (substring (expand-file-name file)
1408                     (length
1409                      (expand-file-name
1410                       (file-name-as-directory top))))
1411        (error "")))
1412    nnheader-directory-separator-character ?.))
1413
1414 (defun nnheader-message (level &rest args)
1415   "Message if the Gnus backends are talkative."
1416   (if (or (not (numberp gnus-verbose-backends))
1417           (<= level gnus-verbose-backends))
1418       (apply 'message args)
1419     (apply 'format args)))
1420
1421 (defun nnheader-be-verbose (level)
1422   "Return whether the backends should be verbose on LEVEL."
1423   (or (not (numberp gnus-verbose-backends))
1424       (<= level gnus-verbose-backends)))
1425
1426 (defvar nnheader-pathname-coding-system 'binary
1427   "*Coding system for file name.")
1428
1429 (defun nnheader-group-pathname (group dir &optional file)
1430   "Make file name for GROUP."
1431   (concat
1432    (let ((dir (file-name-as-directory (expand-file-name dir))))
1433      ;; If this directory exists, we use it directly.
1434      (file-name-as-directory
1435       (if (file-directory-p (concat dir group))
1436           (expand-file-name group dir)
1437         ;; If not, we translate dots into slashes.
1438         (expand-file-name (encode-coding-string
1439                            (nnheader-replace-chars-in-string group ?. ?/)
1440                            nnheader-pathname-coding-system)
1441                           dir))))
1442    (cond ((null file) "")
1443          ((numberp file) (int-to-string file))
1444          (t file))))
1445
1446 (defun nnheader-functionp (form)
1447   "Return non-nil if FORM is funcallable."
1448   (or (and (symbolp form) (fboundp form))
1449       (and (listp form) (eq (car form) 'lambda))))
1450
1451 (defun nnheader-concat (dir &rest files)
1452   "Concat DIR as directory to FILES."
1453   (apply 'concat (file-name-as-directory dir) files))
1454
1455 (defun nnheader-ms-strip-cr ()
1456   "Strip ^M from the end of all lines."
1457   (save-excursion
1458     (nnheader-remove-cr-followed-by-lf)))
1459
1460 (defun nnheader-file-size (file)
1461   "Return the file size of FILE or 0."
1462   (or (nth 7 (file-attributes file)) 0))
1463
1464 (defun nnheader-find-etc-directory (package &optional file)
1465   "Go through `load-path' and find the \"../etc/PACKAGE\" directory.
1466 This function will look in the parent directory of each `load-path'
1467 entry, and look for the \"etc\" directory there.
1468 If FILE, find the \".../etc/PACKAGE\" file instead."
1469   (let ((path load-path)
1470         dir result)
1471     ;; We try to find the dir by looking at the load path,
1472     ;; stripping away the last component and adding "etc/".
1473     (while path
1474       (if (and (car path)
1475                (file-exists-p
1476                 (setq dir (concat
1477                            (file-name-directory
1478                             (directory-file-name (car path)))
1479                            "etc/" package
1480                            (if file "" "/"))))
1481                (or file (file-directory-p dir)))
1482           (setq result dir
1483                 path nil)
1484         (setq path (cdr path))))
1485     result))
1486
1487 (eval-when-compile
1488   (defvar ange-ftp-path-format)
1489   (defvar efs-path-regexp))
1490 (defun nnheader-re-read-dir (path)
1491   "Re-read directory PATH if PATH is on a remote system."
1492   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
1493       (when (string-match efs-path-regexp path)
1494         (efs-re-read-dir path))
1495     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
1496       (when (string-match (car ange-ftp-path-format) path)
1497         (ange-ftp-re-read-dir path)))))
1498
1499 (defvar nnheader-file-coding-system 'raw-text
1500   "Coding system used in file backends of Gnus.")
1501
1502 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
1503   "Like `insert-file-contents', q.v., but only reads in the file.
1504 A buffer may be modified in several ways after reading into the buffer due
1505 to advanced Emacs features, such as file-name-handlers, format decoding,
1506 find-file-hooks, etc.
1507   This function ensures that none of these modifications will take place."
1508   (let ((format-alist nil)
1509         (auto-mode-alist (nnheader-auto-mode-alist))
1510         (default-major-mode 'fundamental-mode)
1511         (enable-local-variables nil)
1512         (after-insert-file-functions nil)
1513         (enable-local-eval nil)
1514         (find-file-hooks nil))
1515     (insert-file-contents-as-coding-system
1516      nnheader-file-coding-system filename visit beg end replace)))
1517
1518 (defun nnheader-insert-nov-file (file first)
1519   (let ((size (nth 7 (file-attributes file)))
1520         (cutoff (* 32 1024)))
1521     (when size
1522       (if (< size cutoff)
1523           ;; If the file is small, we just load it.
1524           (nnheader-insert-file-contents file)
1525         ;; We start on the assumption that FIRST is pretty recent.  If
1526         ;; not, we just insert the rest of the file as well.
1527         (let (current)
1528           (nnheader-insert-file-contents file nil (- size cutoff) size)
1529           (goto-char (point-min))
1530           (delete-region (point) (or (search-forward "\n" nil 'move) (point)))
1531           (setq current (ignore-errors (read (current-buffer))))
1532           (if (and (numberp current)
1533                    (< current first))
1534               t
1535             (delete-region (point-min) (point-max))
1536             (nnheader-insert-file-contents file)))))))
1537
1538 (defun nnheader-find-file-noselect (&rest args)
1539   (let ((format-alist nil)
1540         (auto-mode-alist (nnheader-auto-mode-alist))
1541         (default-major-mode 'fundamental-mode)
1542         (enable-local-variables nil)
1543         (after-insert-file-functions nil)
1544         (enable-local-eval nil)
1545         (find-file-hooks nil))
1546     (apply 'find-file-noselect-as-coding-system
1547            nnheader-file-coding-system args)))
1548
1549 (defun nnheader-auto-mode-alist ()
1550   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
1551   (let ((alist auto-mode-alist)
1552         out)
1553     (while alist
1554       (when (listp (cdar alist))
1555         (push (car alist) out))
1556       (pop alist))
1557     (nreverse out)))
1558
1559 (defun nnheader-directory-regular-files (dir)
1560   "Return a list of all regular files in DIR."
1561   (let ((files (directory-files dir t))
1562         out)
1563     (while files
1564       (when (file-regular-p (car files))
1565         (push (car files) out))
1566       (pop files))
1567     (nreverse out)))
1568
1569 (defun nnheader-directory-files (&rest args)
1570   "Same as `directory-files', but prune \".\" and \"..\"."
1571   (let ((files (apply 'directory-files args))
1572         out)
1573     (while files
1574       (unless (member (file-name-nondirectory (car files)) '("." ".."))
1575         (push (car files) out))
1576       (pop files))
1577     (nreverse out)))
1578
1579 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1580   `(let ((new (generate-new-buffer " *nnheader replace*"))
1581          (cur (current-buffer))
1582          (start (point-min)))
1583      (set-buffer cur)
1584      (goto-char (point-min))
1585      (while (,(if regexp 're-search-forward 'search-forward)
1586              ,from nil t)
1587        (insert-buffer-substring
1588         cur start (prog1 (match-beginning 0) (set-buffer new)))
1589        (goto-char (point-max))
1590        ,(when to `(insert ,to))
1591        (set-buffer cur)
1592        (setq start (point)))
1593      (insert-buffer-substring
1594       cur start (prog1 (point-max) (set-buffer new)))
1595      (copy-to-buffer cur (point-min) (point-max))
1596      (kill-buffer (current-buffer))
1597      (set-buffer cur)))
1598
1599 (defun nnheader-replace-string (from to)
1600   "Do a fast replacement of FROM to TO from point to `point-max'."
1601   (nnheader-skeleton-replace from to))
1602
1603 (defun nnheader-replace-regexp (from to)
1604   "Do a fast regexp replacement of FROM to TO from point to `point-max'."
1605   (nnheader-skeleton-replace from to t))
1606
1607 (defun nnheader-strip-cr ()
1608   "Strip all \r's from the current buffer."
1609   (nnheader-skeleton-replace "\r"))
1610
1611 (defalias 'nnheader-run-at-time 'run-at-time)
1612 (defalias 'nnheader-cancel-timer 'cancel-timer)
1613 (defalias 'nnheader-cancel-function-timers 'cancel-function-timers)
1614 (defalias 'nnheader-string-as-multibyte 'string-as-multibyte)
1615
1616 (defun nnheader-Y-or-n-p (prompt)
1617   "Ask user a \"Y/n\" question. Return t if answer is neither \"n\", \"N\" nor \"C-g\"."
1618   (let ((cursor-in-echo-area t)
1619         (echo-keystrokes 0)
1620         (inhibit-quit t)
1621         ans)
1622     (let (message-log-max)
1623       (while (not (memq ans '(?\  ?N ?Y ?\C-g ?\e ?\n ?\r ?n ?y)))
1624         (message "%s(Y/n) " prompt)
1625         (setq ans (read-char-exclusive))))
1626     (if (memq ans '(?\C-g ?N ?n))
1627         (progn
1628           (message "%s(Y/n) No" prompt)
1629           nil)
1630       (message "%s(Y/n) Yes" prompt)
1631       t)))
1632
1633 (defun-maybe shell-command-to-string (command)
1634   "Execute shell command COMMAND and return its output as a string."
1635   (with-output-to-string
1636     (with-current-buffer
1637         standard-output
1638       (call-process shell-file-name nil t nil shell-command-switch command))))
1639
1640 (defun nnheader-accept-process-output (process)
1641   (accept-process-output
1642    process
1643    (truncate nnheader-read-timeout)
1644    (truncate (* (- nnheader-read-timeout
1645                    (truncate nnheader-read-timeout))
1646                 1000))))
1647
1648 (when (featurep 'xemacs)
1649   (require 'nnheaderxm))
1650
1651 (run-hooks 'nnheader-load-hook)
1652
1653 (provide 'nnheader)
1654
1655 ;;; nnheader.el ends here