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