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