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