Synch to Oort Gnus 200303171913.
[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 (+ min (/ (- 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           (gnus-delete-line))
892         (cond ((> num article)
893                (setq max (point)))
894               ((< num article)
895                (setq min (point)))
896               (t
897                (setq found 'yes)))))
898     ;; We may be at the first line.
899     (when (and (not num)
900                (not (eobp)))
901       (setq num (read cur)))
902     ;; Now we may have found the article we're looking for, or we
903     ;; may be somewhere near it.
904     (when (and (not (eq found 'yes))
905                (not (eq num article)))
906       (setq found (point))
907       (while (and (< (point) max)
908                   (or (not (numberp num))
909                       (< num article)))
910         (forward-line 1)
911         (setq found (point))
912         (or (eobp)
913             (= (setq num (read cur)) article)))
914       (unless (eq num article)
915         (goto-char found)))
916     (beginning-of-line)
917     (eq num article)))
918
919 (defun nnheader-retrieve-headers-from-directory* (articles
920                                                   directory dependencies
921                                                   &optional
922                                                   fetch-old force-new large
923                                                   backend)
924   (with-temp-buffer
925     (let* ((file nil)
926            (number (length articles))
927            (count 0)
928            (file-name-coding-system 'binary)
929            (pathname-coding-system 'binary)
930            (case-fold-search t)
931            (cur (current-buffer))
932            article
933            headers header id end ref in-reply-to lines chars ctype)
934       ;; We don't support fetching by Message-ID.
935       (if (stringp (car articles))
936           'headers
937         (while articles
938           (when (and (file-exists-p
939                       (setq file (expand-file-name
940                                   (int-to-string
941                                    (setq article (pop articles)))
942                                   directory)))
943                      (not (file-directory-p file)))
944             (erase-buffer)
945             (nnheader-insert-head file)
946             (save-restriction
947               (std11-narrow-to-header)
948               (setq
949                header
950                (make-full-mail-header
951                 ;; Number.
952                 article
953                 ;; Subject.
954                 (or (std11-fetch-field "Subject")
955                     "(none)")
956                 ;; From.
957                 (or (std11-fetch-field "From")
958                     "(nobody)")
959                 ;; Date.
960                 (or (std11-fetch-field "Date")
961                     "")
962                 ;; Message-ID.
963                 (progn
964                   (goto-char (point-min))
965                   (setq id (if (re-search-forward
966                                 "^Message-ID: *\\(<[^\n\t> ]+>\\)" nil t)
967                                ;; We do it this way to make sure the Message-ID
968                                ;; is (somewhat) syntactically valid.
969                                (buffer-substring (match-beginning 1)
970                                                  (match-end 1))
971                              ;; If there was no message-id, we just fake one
972                              ;; to make subsequent routines simpler.
973                              (nnheader-generate-fake-message-id))))
974                 ;; References.
975                 (progn
976                   (goto-char (point-min))
977                   (if (search-forward "\nReferences: " nil t)
978                       (progn
979                         (setq end (point))
980                         (prog1
981                             (buffer-substring (match-end 0) (std11-field-end))
982                           (setq ref
983                                 (buffer-substring
984                                  (progn
985                                    ;; (end-of-line)
986                                    (search-backward ">" end t)
987                                    (1+ (point)))
988                                  (progn
989                                    (search-backward "<" end t)
990                                    (point))))))
991                     ;; Get the references from the in-reply-to header if there
992                     ;; were no references and the in-reply-to header looks
993                     ;; promising.
994                     (if (and (search-forward "\nIn-Reply-To: " nil t)
995                              (setq in-reply-to
996                                    (buffer-substring (match-end 0)
997                                                      (std11-field-end)))
998                              (string-match "<[^>]+>" in-reply-to))
999                         (let (ref2)
1000                           (setq ref (substring in-reply-to (match-beginning 0)
1001                                                (match-end 0)))
1002                           (while (string-match "<[^>]+>"
1003                                                in-reply-to (match-end 0))
1004                             (setq ref2
1005                                   (substring in-reply-to (match-beginning 0)
1006                                              (match-end 0)))
1007                             (when (> (length ref2) (length ref))
1008                               (setq ref ref2)))
1009                           ref)
1010                       (setq ref nil))))
1011                 ;; Chars.
1012                 (progn
1013                   (goto-char (point-min))
1014                   (if (search-forward "\nChars: " nil t)
1015                       (if (numberp (setq chars (ignore-errors (read cur))))
1016                           chars 0)
1017                     0))
1018                 ;; Lines.
1019                 (progn
1020                   (goto-char (point-min))
1021                   (if (search-forward "\nLines: " nil t)
1022                       (if (numberp (setq lines (ignore-errors (read cur))))
1023                           lines 0)
1024                     0))
1025                 ;; Xref.
1026                 (std11-fetch-field "Xref")
1027                 ))
1028               (goto-char (point-min))
1029               (if (setq ctype (std11-fetch-field "Content-Type"))
1030                   (mime-entity-set-content-type-internal
1031                    header (mime-parse-Content-Type ctype)))
1032               )
1033             (when (setq header
1034                         (gnus-dependencies-add-header
1035                          header dependencies force-new))
1036               (push header headers))
1037             )
1038           (setq count (1+ count))
1039
1040           (and large
1041                (zerop (% count 20))
1042                (nnheader-message 5 "%s: Receiving headers... %d%%"
1043                                  backend
1044                                  (/ (* count 100) number))))
1045
1046         (when large
1047           (nnheader-message 5 "%s: Receiving headers...done" backend))
1048
1049         headers))))
1050
1051 (defun nnheader-retrieve-headers-from-directory (articles
1052                                                  directory dependencies
1053                                                  &optional
1054                                                  fetch-old force-new large
1055                                                  backend)
1056   (cons 'header
1057         (nreverse (nnheader-retrieve-headers-from-directory*
1058                    articles directory dependencies
1059                    fetch-old force-new large backend))))
1060
1061 (defun nnheader-get-newsgroup-headers-xover* (sequence
1062                                               &optional
1063                                               force-new dependencies
1064                                               group)
1065   "Parse the news overview data in the server buffer, and return a
1066 list of headers that match SEQUENCE (see `nntp-retrieve-headers')."
1067   ;; Get the Xref when the users reads the articles since most/some
1068   ;; NNTP servers do not include Xrefs when using XOVER.
1069   ;; (setq gnus-article-internal-prepare-hook '(gnus-article-get-xrefs))
1070   (let ((cur nntp-server-buffer)
1071         number headers header)
1072     (save-excursion
1073       (set-buffer nntp-server-buffer)
1074       ;; Allow the user to mangle the headers before parsing them.
1075       (gnus-run-hooks 'gnus-parse-headers-hook)
1076       (goto-char (point-min))
1077       (while (not (eobp))
1078         (condition-case ()
1079             (while (and sequence (not (eobp)))
1080               (setq number (read cur))
1081               (while (and sequence
1082                           (< (car sequence) number))
1083                 (setq sequence (cdr sequence)))
1084               (and sequence
1085                    (eq number (car sequence))
1086                    (progn
1087                      (setq sequence (cdr sequence))
1088                      (setq header (inline
1089                                     (gnus-nov-parse-line
1090                                      number dependencies force-new))))
1091                    (push header headers))
1092               (forward-line 1))
1093           (error
1094            (gnus-error 4 "Strange nov line (%d)"
1095                        (count-lines (point-min) (point)))))
1096         (forward-line 1))
1097       ;; A common bug in inn is that if you have posted an article and
1098       ;; then retrieves the active file, it will answer correctly --
1099       ;; the new article is included.  However, a NOV entry for the
1100       ;; article may not have been generated yet, so this may fail.
1101       ;; We work around this problem by retrieving the last few
1102       ;; headers using HEAD.
1103       headers)))
1104
1105 ;; Various cruft the backends and Gnus need to communicate.
1106
1107 (defvar nntp-server-buffer nil)
1108 (defvar nntp-process-response nil)
1109 (defvar news-reply-yank-from nil)
1110 (defvar news-reply-yank-message-id nil)
1111
1112 (defvar nnheader-callback-function nil)
1113
1114 (defun nnheader-init-server-buffer ()
1115   "Initialize the Gnus-backend communication buffer."
1116   (save-excursion
1117     (unless (gnus-buffer-live-p nntp-server-buffer)
1118       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
1119     (set-buffer nntp-server-buffer)
1120     (erase-buffer)
1121     (kill-all-local-variables)
1122     (setq case-fold-search t)           ;Should ignore case.
1123     (set (make-local-variable 'nntp-process-response) nil)
1124     t))
1125
1126 ;;; Various functions the backends use.
1127
1128 (defun nnheader-file-error (file)
1129   "Return a string that says what is wrong with FILE."
1130   (format
1131    (cond
1132     ((not (file-exists-p file))
1133      "%s does not exist")
1134     ((file-directory-p file)
1135      "%s is a directory")
1136     ((not (file-readable-p file))
1137      "%s is not readable"))
1138    file))
1139
1140 (defun nnheader-insert-head (file)
1141   "Insert the head of the article."
1142   (when (file-exists-p file)
1143     (if (eq nnheader-max-head-length t)
1144         ;; Just read the entire file.
1145         (nnheader-insert-file-contents file)
1146       ;; Read 1K blocks until we find a separator.
1147       (let ((beg 0)
1148             format-alist)
1149         (while (and (eq nnheader-head-chop-length
1150                         (nth 1 (nnheader-insert-file-contents
1151                                 file nil beg
1152                                 (incf beg nnheader-head-chop-length))))
1153                     (prog1 (not (search-forward "\n\n" nil t))
1154                       (goto-char (point-max)))
1155                     (or (null nnheader-max-head-length)
1156                         (< beg nnheader-max-head-length))))))
1157     t))
1158
1159 (defun nnheader-article-p ()
1160   "Say whether the current buffer looks like an article."
1161   (goto-char (point-min))
1162   (if (not (search-forward "\n\n" nil t))
1163       nil
1164     (narrow-to-region (point-min) (1- (point)))
1165     (goto-char (point-min))
1166     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
1167       (goto-char (match-end 0)))
1168     (prog1
1169         (eobp)
1170       (widen))))
1171
1172 (defun nnheader-insert-references (references message-id)
1173   "Insert a References header based on REFERENCES and MESSAGE-ID."
1174   (if (and (not references) (not message-id))
1175       ;; This is invalid, but not all articles have Message-IDs.
1176       ()
1177     (mail-position-on-field "References")
1178     (let ((begin (gnus-point-at-bol))
1179           (fill-column 78)
1180           (fill-prefix "\t"))
1181       (when references
1182         (insert references))
1183       (when (and references message-id)
1184         (insert " "))
1185       (when message-id
1186         (insert message-id))
1187       ;; Fold long References lines to conform to RFC1036 (sort of).
1188       ;; The region must end with a newline to fill the region
1189       ;; without inserting extra newline.
1190       (fill-region-as-paragraph begin (1+ (point))))))
1191
1192 (defun nnheader-replace-header (header new-value)
1193   "Remove HEADER and insert the NEW-VALUE."
1194   (save-excursion
1195     (save-restriction
1196       (nnheader-narrow-to-headers)
1197       (prog1
1198           (message-remove-header header)
1199         (goto-char (point-max))
1200         (insert header ": " new-value "\n")))))
1201
1202 (defun nnheader-narrow-to-headers ()
1203   "Narrow to the head of an article."
1204   (widen)
1205   (narrow-to-region
1206    (goto-char (point-min))
1207    (if (search-forward "\n\n" nil t)
1208        (1- (point))
1209      (point-max)))
1210   (goto-char (point-min)))
1211
1212 (defun nnheader-remove-body ()
1213   "Remove the body from an article in this current buffer."
1214   (goto-char (point-min))
1215   (when (re-search-forward "\n\r?\n" nil t)
1216     (delete-region (point) (point-max))))
1217
1218 (defun nnheader-set-temp-buffer (name &optional noerase)
1219   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
1220   (set-buffer (get-buffer-create name))
1221   (buffer-disable-undo)
1222   (unless noerase
1223     (erase-buffer))
1224   (current-buffer))
1225
1226 (eval-when-compile (defvar jka-compr-compression-info-list))
1227 (defvar nnheader-numerical-files
1228   (if (boundp 'jka-compr-compression-info-list)
1229       (concat "\\([0-9]+\\)\\("
1230               (mapconcat (lambda (i) (aref i 0))
1231                          jka-compr-compression-info-list "\\|")
1232               "\\)?")
1233     "[0-9]+$")
1234   "Regexp that match numerical files.")
1235
1236 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
1237   "Regexp that matches numerical file names.")
1238
1239 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
1240   "Regexp that matches numerical full file names.")
1241
1242 (defsubst nnheader-file-to-number (file)
1243   "Take a FILE name and return the article number."
1244   (if (string= nnheader-numerical-short-files "^[0-9]+$")
1245       (string-to-int file)
1246     (string-match nnheader-numerical-short-files file)
1247     (string-to-int (match-string 0 file))))
1248
1249 (defvar nnheader-directory-files-is-safe
1250   (or (eq system-type 'windows-nt)
1251       (and (not (featurep 'xemacs))
1252            (> emacs-major-version 20)))
1253   "If non-nil, Gnus believes `directory-files' is safe.
1254 It has been reported numerous times that `directory-files' fails with
1255 an alarming frequency on NFS mounted file systems. If it is nil,
1256 `nnheader-directory-files-safe' is used.")
1257
1258 (defun nnheader-directory-files-safe (&rest args)
1259   "Execute `directory-files' twice and returns the longer result."
1260   (let ((first (apply 'directory-files args))
1261         (second (apply 'directory-files args)))
1262     (if (> (length first) (length second))
1263         first
1264       second)))
1265
1266 (defun nnheader-directory-articles (dir)
1267   "Return a list of all article files in directory DIR."
1268   (mapcar 'nnheader-file-to-number
1269           (if nnheader-directory-files-is-safe
1270               (directory-files
1271                dir nil nnheader-numerical-short-files t)
1272             (nnheader-directory-files-safe
1273              dir nil nnheader-numerical-short-files t))))
1274
1275 (defun nnheader-article-to-file-alist (dir)
1276   "Return an alist of article/file pairs in DIR."
1277   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
1278           (if nnheader-directory-files-is-safe
1279               (directory-files
1280                dir nil nnheader-numerical-short-files t)
1281             (nnheader-directory-files-safe
1282              dir nil nnheader-numerical-short-files t))))
1283
1284 (defun nnheader-fold-continuation-lines ()
1285   "Fold continuation lines in the current buffer."
1286   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
1287
1288 (defun nnheader-translate-file-chars (file &optional full)
1289   "Translate FILE into something that can be a file name.
1290 If FULL, translate everything."
1291   (if (null nnheader-file-name-translation-alist)
1292       ;; No translation is necessary.
1293       file
1294     (let* ((i 0)
1295            trans leaf path len)
1296       (if full
1297           ;; Do complete translation.
1298           (setq leaf (copy-sequence file)
1299                 path ""
1300                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1)))
1301                       2 0))
1302         ;; We translate -- but only the file name.  We leave the directory
1303         ;; alone.
1304         (if (and (featurep 'xemacs)
1305                  (memq system-type '(cygwin32 win32 w32 mswindows windows-nt
1306                                               cygwin)))
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 `load-path' and find the \"../etc/PACKAGE\" directory.
1458 This function will look in the parent directory of each `load-path'
1459 entry, and look for the \"etc\" directory there.
1460 If FILE, find the \".../etc/PACKAGE\" file instead."
1461   (let ((path load-path)
1462         dir result)
1463     ;; We try to find the dir by looking at the load path,
1464     ;; stripping away the last component and adding "etc/".
1465     (while path
1466       (if (and (car path)
1467                (file-exists-p
1468                 (setq dir (concat
1469                            (file-name-directory
1470                             (directory-file-name (car path)))
1471                            "etc/" package
1472                            (if file "" "/"))))
1473                (or file (file-directory-p dir)))
1474           (setq result dir
1475                 path nil)
1476         (setq path (cdr path))))
1477     result))
1478
1479 (eval-when-compile
1480   (defvar ange-ftp-path-format)
1481   (defvar efs-path-regexp))
1482 (defun nnheader-re-read-dir (path)
1483   "Re-read directory PATH if PATH is on a remote system."
1484   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
1485       (when (string-match efs-path-regexp path)
1486         (efs-re-read-dir path))
1487     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
1488       (when (string-match (car ange-ftp-path-format) path)
1489         (ange-ftp-re-read-dir path)))))
1490
1491 (defvar nnheader-file-coding-system 'raw-text
1492   "Coding system used in file backends of Gnus.")
1493
1494 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
1495   "Like `insert-file-contents', q.v., but only reads in the file.
1496 A buffer may be modified in several ways after reading into the buffer due
1497 to advanced Emacs features, such as file-name-handlers, format decoding,
1498 find-file-hooks, etc.
1499   This function ensures that none of these modifications will take place."
1500   (let ((format-alist nil)
1501         (auto-mode-alist (nnheader-auto-mode-alist))
1502         (default-major-mode 'fundamental-mode)
1503         (enable-local-variables nil)
1504         (after-insert-file-functions nil)
1505         (enable-local-eval nil)
1506         (find-file-hooks nil))
1507     (insert-file-contents-as-coding-system
1508      nnheader-file-coding-system filename visit beg end replace)))
1509
1510 (defun nnheader-insert-nov-file (file first)
1511   (let ((size (nth 7 (file-attributes file)))
1512         (cutoff (* 32 1024)))
1513     (when size
1514       (if (< size cutoff)
1515           ;; If the file is small, we just load it.
1516           (nnheader-insert-file-contents file)
1517         ;; We start on the assumption that FIRST is pretty recent.  If
1518         ;; not, we just insert the rest of the file as well.
1519         (let (current)
1520           (nnheader-insert-file-contents file nil (- size cutoff) size)
1521           (goto-char (point-min))
1522           (delete-region (point) (or (search-forward "\n" nil 'move) (point)))
1523           (setq current (ignore-errors (read (current-buffer))))
1524           (if (and (numberp current)
1525                    (< current first))
1526               t
1527             (delete-region (point-min) (point-max))
1528             (nnheader-insert-file-contents file)))))))
1529
1530 (defun nnheader-find-file-noselect (&rest args)
1531   (let ((format-alist nil)
1532         (auto-mode-alist (nnheader-auto-mode-alist))
1533         (default-major-mode 'fundamental-mode)
1534         (enable-local-variables nil)
1535         (after-insert-file-functions nil)
1536         (enable-local-eval nil)
1537         (find-file-hooks nil))
1538     (apply 'find-file-noselect-as-coding-system
1539            nnheader-file-coding-system args)))
1540
1541 (defun nnheader-auto-mode-alist ()
1542   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
1543   (let ((alist auto-mode-alist)
1544         out)
1545     (while alist
1546       (when (listp (cdar alist))
1547         (push (car alist) out))
1548       (pop alist))
1549     (nreverse out)))
1550
1551 (defun nnheader-directory-regular-files (dir)
1552   "Return a list of all regular files in DIR."
1553   (let ((files (directory-files dir t))
1554         out)
1555     (while files
1556       (when (file-regular-p (car files))
1557         (push (car files) out))
1558       (pop files))
1559     (nreverse out)))
1560
1561 (defun nnheader-directory-files (&rest args)
1562   "Same as `directory-files', but prune \".\" and \"..\"."
1563   (let ((files (apply 'directory-files args))
1564         out)
1565     (while files
1566       (unless (member (file-name-nondirectory (car files)) '("." ".."))
1567         (push (car files) out))
1568       (pop files))
1569     (nreverse out)))
1570
1571 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1572   `(let ((new (generate-new-buffer " *nnheader replace*"))
1573          (cur (current-buffer))
1574          (start (point-min)))
1575      (set-buffer cur)
1576      (goto-char (point-min))
1577      (while (,(if regexp 're-search-forward 'search-forward)
1578              ,from nil t)
1579        (insert-buffer-substring
1580         cur start (prog1 (match-beginning 0) (set-buffer new)))
1581        (goto-char (point-max))
1582        ,(when to `(insert ,to))
1583        (set-buffer cur)
1584        (setq start (point)))
1585      (insert-buffer-substring
1586       cur start (prog1 (point-max) (set-buffer new)))
1587      (copy-to-buffer cur (point-min) (point-max))
1588      (kill-buffer (current-buffer))
1589      (set-buffer cur)))
1590
1591 (defun nnheader-replace-string (from to)
1592   "Do a fast replacement of FROM to TO from point to `point-max'."
1593   (nnheader-skeleton-replace from to))
1594
1595 (defun nnheader-replace-regexp (from to)
1596   "Do a fast regexp replacement of FROM to TO from point to `point-max'."
1597   (nnheader-skeleton-replace from to t))
1598
1599 (defun nnheader-strip-cr ()
1600   "Strip all \r's from the current buffer."
1601   (nnheader-skeleton-replace "\r"))
1602
1603 (defalias 'nnheader-run-at-time 'run-at-time)
1604 (defalias 'nnheader-cancel-timer 'cancel-timer)
1605 (defalias 'nnheader-cancel-function-timers 'cancel-function-timers)
1606 (defalias 'nnheader-string-as-multibyte 'string-as-multibyte)
1607
1608 (defun nnheader-Y-or-n-p (prompt)
1609   "Ask user a \"Y/n\" question. Return t if answer is neither \"n\", \"N\" nor \"C-g\"."
1610   (let ((cursor-in-echo-area t)
1611         (echo-keystrokes 0)
1612         (inhibit-quit t)
1613         ans)
1614     (let (message-log-max)
1615       (while (not (memq ans '(?\  ?N ?Y ?\C-g ?\e ?\n ?\r ?n ?y)))
1616         (message "%s(Y/n) " prompt)
1617         (setq ans (read-char-exclusive))))
1618     (if (memq ans '(?\C-g ?N ?n))
1619         (progn
1620           (message "%s(Y/n) No" prompt)
1621           nil)
1622       (message "%s(Y/n) Yes" prompt)
1623       t)))
1624
1625 (defun-maybe shell-command-to-string (command)
1626   "Execute shell command COMMAND and return its output as a string."
1627   (with-output-to-string
1628     (with-current-buffer
1629         standard-output
1630       (call-process shell-file-name nil t nil shell-command-switch command))))
1631
1632 (when (featurep 'xemacs)
1633   (require 'nnheaderxm))
1634
1635 (run-hooks 'nnheader-load-hook)
1636
1637 (provide 'nnheader)
1638
1639 ;;; nnheader.el ends here