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