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