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