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