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