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