Import Oort Gnus v0.13.
[elisp/gnus.git-] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Gnus and its backends
2
3 ;; Copyright (C) 1987, 1988, 1989, 1990, 1993, 1994, 1995, 1996,
4 ;;        1997, 1998, 2000, 2001, 2002
5 ;;        Free Software Foundation, Inc.
6
7 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
8 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
9 ;; Keywords: news
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 ;; Requiring `gnus-util' at compile time creates a circular
35 ;; dependency between nnheader.el and gnus-util.el.
36                              ;(eval-when-compile (require 'gnus-util))
37
38 (require 'mail-utils)
39 (require 'mm-util)
40 (eval-and-compile
41   (autoload 'gnus-sorted-intersection "gnus-range")
42   (autoload 'gnus-intersection "gnus-range")
43   (autoload 'gnus-sorted-complement "gnus-range")
44   (autoload 'gnus-sorted-difference "gnus-range"))
45
46 (defcustom gnus-verbose-backends 7
47   "Integer that says how verbose the Gnus backends should be.
48 The higher the number, the more messages the Gnus backends will flash
49 to say what it's doing.  At zero, the Gnus backends will be totally
50 mute; at five, they will display most important messages; and at ten,
51 they will keep on jabbering all the time."
52   :group 'gnus-start
53   :type 'integer)
54
55 (defcustom gnus-nov-is-evil nil
56   "If non-nil, Gnus backends will never output headers in the NOV format."
57   :group 'gnus-server
58   :type 'boolean)
59
60 (defvar nnheader-max-head-length 4096
61   "*Max length of the head of articles.
62
63 Value is an integer, nil, or t.  nil means read in chunks of a file
64 indefinitely until a complete head is found\; t means always read the
65 entire file immediately, disregarding `nnheader-head-chop-length'.
66
67 Integer values will in effect be rounded up to the nearest multiple of
68 `nnheader-head-chop-length'.")
69
70 (defvar nnheader-head-chop-length 2048
71   "*Length of each read operation when trying to fetch HEAD headers.")
72
73 (defvar nnheader-file-name-translation-alist
74   (let ((case-fold-search t))
75     (cond
76      ((string-match "windows-nt\\|os/2\\|emx\\|cygwin"
77                     (symbol-name system-type))
78       (append (mapcar (lambda (c) (cons c ?_))
79                       '(?: ?* ?\" ?< ?> ??))
80               (if (string-match "windows-nt\\|cygwin"
81                                 (symbol-name system-type))
82                   nil
83                 '((?+ . ?-)))))
84      (t nil)))
85   "*Alist that says how to translate characters in file names.
86 For instance, if \":\" is invalid as a file character in file names
87 on your system, you could say something like:
88
89 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
90
91 (eval-and-compile
92   (autoload 'nnmail-message-id "nnmail")
93   (autoload 'mail-position-on-field "sendmail")
94   (autoload 'message-remove-header "message")
95   (autoload 'gnus-point-at-eol "gnus-util")
96   (autoload 'gnus-buffer-live-p "gnus-util"))
97
98 ;;; Header access macros.
99
100 ;; These macros may look very much like the ones in GNUS 4.1.  They
101 ;; are, in a way, but you should note that the indices they use have
102 ;; been changed from the internal GNUS format to the NOV format.  The
103 ;; makes it possible to read headers from XOVER much faster.
104 ;;
105 ;; The format of a header is now:
106 ;; [number subject from date id references chars lines xref extra]
107 ;;
108 ;; (That next-to-last entry is defined as "misc" in the NOV format,
109 ;; but Gnus uses it for xrefs.)
110
111 (defmacro mail-header-number (header)
112   "Return article number in HEADER."
113   `(aref ,header 0))
114
115 (defmacro mail-header-set-number (header number)
116   "Set article number of HEADER to NUMBER."
117   `(aset ,header 0 ,number))
118
119 (defmacro mail-header-subject (header)
120   "Return subject string in HEADER."
121   `(aref ,header 1))
122
123 (defmacro mail-header-set-subject (header subject)
124   "Set article subject of HEADER to SUBJECT."
125   `(aset ,header 1 ,subject))
126
127 (defmacro mail-header-from (header)
128   "Return author string in HEADER."
129   `(aref ,header 2))
130
131 (defmacro mail-header-set-from (header from)
132   "Set article author of HEADER to FROM."
133   `(aset ,header 2 ,from))
134
135 (defmacro mail-header-date (header)
136   "Return date in HEADER."
137   `(aref ,header 3))
138
139 (defmacro mail-header-set-date (header date)
140   "Set article date of HEADER to DATE."
141   `(aset ,header 3 ,date))
142
143 (defalias 'mail-header-message-id 'mail-header-id)
144 (defmacro mail-header-id (header)
145   "Return Id in HEADER."
146   `(aref ,header 4))
147
148 (defalias 'mail-header-set-message-id 'mail-header-set-id)
149 (defmacro mail-header-set-id (header id)
150   "Set article Id of HEADER to ID."
151   `(aset ,header 4 ,id))
152
153 (defmacro mail-header-references (header)
154   "Return references in HEADER."
155   `(aref ,header 5))
156
157 (defmacro mail-header-set-references (header ref)
158   "Set article references of HEADER to REF."
159   `(aset ,header 5 ,ref))
160
161 (defmacro mail-header-chars (header)
162   "Return number of chars of article in HEADER."
163   `(aref ,header 6))
164
165 (defmacro mail-header-set-chars (header chars)
166   "Set number of chars in article of HEADER to CHARS."
167   `(aset ,header 6 ,chars))
168
169 (defmacro mail-header-lines (header)
170   "Return lines in HEADER."
171   `(aref ,header 7))
172
173 (defmacro mail-header-set-lines (header lines)
174   "Set article lines of HEADER to LINES."
175   `(aset ,header 7 ,lines))
176
177 (defmacro mail-header-xref (header)
178   "Return xref string in HEADER."
179   `(aref ,header 8))
180
181 (defmacro mail-header-set-xref (header xref)
182   "Set article XREF of HEADER to xref."
183   `(aset ,header 8 ,xref))
184
185 (defmacro mail-header-extra (header)
186   "Return the extra headers in HEADER."
187   `(aref ,header 9))
188
189 (defmacro mail-header-set-extra (header extra)
190   "Set the extra headers in HEADER to EXTRA."
191   `(aset ,header 9 ',extra))
192
193 (defsubst make-mail-header (&optional init)
194   "Create a new mail header structure initialized with INIT."
195   (make-vector 10 init))
196
197 (defsubst make-full-mail-header (&optional number subject from date id
198                                            references chars lines xref
199                                            extra)
200   "Create a new mail header structure initialized with the parameters given."
201   (vector number subject from date id references chars lines xref extra))
202
203 ;; fake message-ids: generation and detection
204
205 (defvar nnheader-fake-message-id 1)
206
207 (defsubst nnheader-generate-fake-message-id ()
208   (concat "fake+none+" (int-to-string (incf nnheader-fake-message-id))))
209
210 (defsubst nnheader-fake-message-id-p (id)
211   (save-match-data                     ; regular message-id's are <.*>
212     (string-match "\\`fake\\+none\\+[0-9]+\\'" id)))
213
214 ;; Parsing headers and NOV lines.
215
216 (defsubst nnheader-remove-cr-followed-by-lf ()
217   (goto-char (point-max))
218   (while (search-backward "\r\n" nil t)
219     (delete-char 1)))
220
221 (defsubst nnheader-header-value ()
222   (skip-chars-forward " \t")
223   (buffer-substring (point) (gnus-point-at-eol)))
224
225 (defun nnheader-parse-naked-head (&optional number)
226   ;; This function unfolds continuation lines in this buffer
227   ;; destructively.  When this side effect is unwanted, use
228   ;; `nnheader-parse-head' instead of this function.
229   (let ((case-fold-search t)
230         (buffer-read-only nil)
231         (cur (current-buffer))
232         (p (point-min))
233         in-reply-to lines ref)
234     (nnheader-remove-cr-followed-by-lf)
235     (ietf-drums-unfold-fws)
236     (subst-char-in-region (point-min) (point-max) ?\t ? )
237     (goto-char p)
238     (insert "\n")
239     (prog1
240         ;; This implementation of this function, with nine
241         ;; search-forwards instead of the one re-search-forward and a
242         ;; case (which basically was the old function) is actually
243         ;; about twice as fast, even though it looks messier.  You
244         ;; can't have everything, I guess.  Speed and elegance don't
245         ;; always go hand in hand.
246         (vector
247          ;; Number.
248          (or number 0)
249          ;; Subject.
250          (progn
251            (goto-char p)
252            (if (search-forward "\nsubject:" nil t)
253                (nnheader-header-value) "(none)"))
254          ;; From.
255          (progn
256            (goto-char p)
257            (if (search-forward "\nfrom:" nil t)
258                (nnheader-header-value) "(nobody)"))
259          ;; Date.
260          (progn
261            (goto-char p)
262            (if (search-forward "\ndate:" nil t)
263                (nnheader-header-value) ""))
264          ;; Message-ID.
265          (progn
266            (goto-char p)
267            (if (search-forward "\nmessage-id:" nil t)
268                (buffer-substring
269                 (1- (or (search-forward "<" (gnus-point-at-eol) t)
270                         (point)))
271                 (or (search-forward ">" (gnus-point-at-eol) t) (point)))
272              ;; If there was no message-id, we just fake one to make
273              ;; subsequent routines simpler.
274              (nnheader-generate-fake-message-id)))
275          ;; References.
276          (progn
277            (goto-char p)
278            (if (search-forward "\nreferences:" nil t)
279                (nnheader-header-value)
280              ;; Get the references from the in-reply-to header if
281              ;; there were no references and the in-reply-to header
282              ;; looks promising.
283              (if (and (search-forward "\nin-reply-to:" nil t)
284                       (setq in-reply-to (nnheader-header-value))
285                       (string-match "<[^\n>]+>" in-reply-to))
286                  (let (ref2)
287                    (setq ref (substring in-reply-to (match-beginning 0)
288                                         (match-end 0)))
289                    (while (string-match "<[^\n>]+>"
290                                         in-reply-to (match-end 0))
291                      (setq ref2 (substring in-reply-to (match-beginning 0)
292                                            (match-end 0)))
293                      (when (> (length ref2) (length ref))
294                        (setq ref ref2)))
295                    ref)
296                nil)))
297          ;; Chars.
298          0
299          ;; Lines.
300          (progn
301            (goto-char p)
302            (if (search-forward "\nlines: " nil t)
303                (if (numberp (setq lines (read cur)))
304                    lines 0)
305              0))
306          ;; Xref.
307          (progn
308            (goto-char p)
309            (and (search-forward "\nxref:" nil t)
310                 (nnheader-header-value)))
311          ;; Extra.
312          (when nnmail-extra-headers
313            (let ((extra nnmail-extra-headers)
314                  out)
315              (while extra
316                (goto-char p)
317                (when (search-forward
318                       (concat "\n" (symbol-name (car extra)) ":") nil t)
319                  (push (cons (car extra) (nnheader-header-value))
320                        out))
321                (pop extra))
322              out)))
323       (goto-char p)
324       (delete-char 1))))
325
326 (defun nnheader-parse-head (&optional naked)
327   (let ((cur (current-buffer)) num beg end)
328     (when (if naked
329               (setq num 0
330                     beg (point-min)
331                     end (point-max))
332             (goto-char (point-min))
333             ;; Search to the beginning of the next header.  Error
334             ;; messages do not begin with 2 or 3.
335             (when (re-search-forward "^[23][0-9]+ " nil t)
336               (end-of-line)
337               (setq num (read cur)
338                     beg (point)
339                     end (if (search-forward "\n.\n" nil t)
340                             (- (point) 2)
341                           (point)))))
342       (with-temp-buffer
343         (insert-buffer-substring cur beg end)
344         (nnheader-parse-naked-head num)))))
345
346 (defmacro nnheader-nov-skip-field ()
347   '(search-forward "\t" eol 'move))
348
349 (defmacro nnheader-nov-field ()
350   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
351
352 (defmacro nnheader-nov-read-integer ()
353   '(prog1
354        (if (eq (char-after) ?\t)
355            0
356          (let ((num (condition-case nil
357                         (read (current-buffer))
358                       (error nil))))
359            (if (numberp num) num 0)))
360      (or (eobp) (forward-char 1))))
361
362 (defmacro nnheader-nov-parse-extra ()
363   '(let (out string)
364      (while (not (memq (char-after) '(?\n nil)))
365        (setq string (nnheader-nov-field))
366        (when (string-match "^\\([^ :]+\\): " string)
367          (push (cons (intern (match-string 1 string))
368                      (substring string (match-end 0)))
369                out)))
370      out))
371
372 (defmacro nnheader-nov-read-message-id ()
373   '(let ((id (nnheader-nov-field)))
374      (if (string-match "^<[^>]+>$" id)
375          id
376        (nnheader-generate-fake-message-id))))
377
378 (defun nnheader-parse-nov ()
379   (let ((eol (gnus-point-at-eol)))
380     (vector
381      (nnheader-nov-read-integer)        ; number
382      (nnheader-nov-field)               ; subject
383      (nnheader-nov-field)               ; from
384      (nnheader-nov-field)               ; date
385      (nnheader-nov-read-message-id)     ; id
386      (nnheader-nov-field)               ; refs
387      (nnheader-nov-read-integer)        ; chars
388      (nnheader-nov-read-integer)        ; lines
389      (if (eq (char-after) ?\n)
390          nil
391        (if (looking-at "Xref: ")
392            (goto-char (match-end 0)))
393        (nnheader-nov-field))            ; Xref
394      (nnheader-nov-parse-extra))))      ; extra
395
396 (defun nnheader-insert-nov (header)
397   (princ (mail-header-number header) (current-buffer))
398   (let ((p (point)))
399     (insert
400      "\t"
401      (or (mail-header-subject header) "(none)") "\t"
402      (or (mail-header-from header) "(nobody)") "\t"
403      (or (mail-header-date header) "") "\t"
404      (or (mail-header-id header)
405          (nnmail-message-id))
406      "\t"
407      (or (mail-header-references header) "") "\t")
408     (princ (or (mail-header-chars header) 0) (current-buffer))
409     (insert "\t")
410     (princ (or (mail-header-lines header) 0) (current-buffer))
411     (insert "\t")
412     (when (mail-header-xref header)
413       (insert "Xref: " (mail-header-xref header)))
414     (when (or (mail-header-xref header)
415               (mail-header-extra header))
416       (insert "\t"))
417     (when (mail-header-extra header)
418       (let ((extra (mail-header-extra header)))
419         (while extra
420           (insert (symbol-name (caar extra))
421                   ": " (cdar extra) "\t")
422           (pop extra))))
423     (insert "\n")
424     (backward-char 1)
425     (while (search-backward "\n" p t)
426       (delete-char 1))
427     (forward-line 1)))
428
429 (defun nnheader-parse-overview-file (file)
430   "Parse FILE and return a list of headers."
431   (mm-with-unibyte-buffer
432     (nnheader-insert-file-contents file)
433     (goto-char (point-min))
434     (let (headers)
435       (while (not (eobp))
436         (push (nnheader-parse-nov) headers)
437         (forward-line 1))
438       (nreverse headers))))
439
440 (defun nnheader-write-overview-file (file headers)
441   "Write HEADERS to FILE."
442   (with-temp-file file
443     (mapcar 'nnheader-insert-nov headers)))
444
445 (defun nnheader-insert-header (header)
446   (insert
447    "Subject: " (or (mail-header-subject header) "(none)") "\n"
448    "From: " (or (mail-header-from header) "(nobody)") "\n"
449    "Date: " (or (mail-header-date header) "") "\n"
450    "Message-ID: " (or (mail-header-id header) (nnmail-message-id)) "\n"
451    "References: " (or (mail-header-references header) "") "\n"
452    "Lines: ")
453   (princ (or (mail-header-lines header) 0) (current-buffer))
454   (insert "\n\n"))
455
456 (defun nnheader-insert-article-line (article)
457   (goto-char (point-min))
458   (insert "220 ")
459   (princ article (current-buffer))
460   (insert " Article retrieved.\n")
461   (search-forward "\n\n" nil 'move)
462   (delete-region (point) (point-max))
463   (forward-char -1)
464   (insert "."))
465
466 (defun nnheader-nov-delete-outside-range (beg end)
467   "Delete all NOV lines that lie outside the BEG to END range."
468   ;; First we find the first wanted line.
469   (nnheader-find-nov-line beg)
470   (delete-region (point-min) (point))
471   ;; Then we find the last wanted line.
472   (when (nnheader-find-nov-line end)
473     (forward-line 1))
474   (delete-region (point) (point-max)))
475
476 (defun nnheader-find-nov-line (article)
477   "Put point at the NOV line that start with ARTICLE.
478 If ARTICLE doesn't exist, put point where that line
479 would have been.  The function will return non-nil if
480 the line could be found."
481   ;; This function basically does a binary search.
482   (let ((max (point-max))
483         (min (goto-char (point-min)))
484         (cur (current-buffer))
485         (prev (point-min))
486         num found)
487     (while (not found)
488       (goto-char (/ (+ max min) 2))
489       (beginning-of-line)
490       (if (or (= (point) prev)
491               (eobp))
492           (setq found t)
493         (setq prev (point))
494         (while (and (not (numberp (setq num (read cur))))
495                     (not (eobp)))
496           (delete-region (progn (beginning-of-line) (point))
497                          (progn (forward-line 1) (point))))
498         (cond ((> num article)
499                (setq max (point)))
500               ((< num article)
501                (setq min (point)))
502               (t
503                (setq found 'yes)))))
504     ;; We may be at the first line.
505     (when (and (not num)
506                (not (eobp)))
507       (setq num (read cur)))
508     ;; Now we may have found the article we're looking for, or we
509     ;; may be somewhere near it.
510     (when (and (not (eq found 'yes))
511                (not (eq num article)))
512       (setq found (point))
513       (while (and (< (point) max)
514                   (or (not (numberp num))
515                       (< num article)))
516         (forward-line 1)
517         (setq found (point))
518         (or (eobp)
519             (= (setq num (read cur)) article)))
520       (unless (eq num article)
521         (goto-char found)))
522     (beginning-of-line)
523     (eq num article)))
524
525 ;; Various cruft the backends and Gnus need to communicate.
526
527 (defvar nntp-server-buffer nil)
528 (defvar nntp-process-response nil)
529 (defvar news-reply-yank-from nil)
530 (defvar news-reply-yank-message-id nil)
531
532 (defvar nnheader-callback-function nil)
533
534 (defun nnheader-init-server-buffer ()
535   "Initialize the Gnus-backend communication buffer."
536   (save-excursion
537     (unless (gnus-buffer-live-p nntp-server-buffer)
538       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
539     (set-buffer nntp-server-buffer)
540     (mm-enable-multibyte)
541     (erase-buffer)
542     (kill-all-local-variables)
543     (setq case-fold-search t)           ;Should ignore case.
544     (set (make-local-variable 'nntp-process-response) nil)
545     t))
546
547 ;;; Various functions the backends use.
548
549 (defun nnheader-file-error (file)
550   "Return a string that says what is wrong with FILE."
551   (format
552    (cond
553     ((not (file-exists-p file))
554      "%s does not exist")
555     ((file-directory-p file)
556      "%s is a directory")
557     ((not (file-readable-p file))
558      "%s is not readable"))
559    file))
560
561 (defun nnheader-insert-head (file)
562   "Insert the head of the article."
563   (when (file-exists-p file)
564     (if (eq nnheader-max-head-length t)
565         ;; Just read the entire file.
566         (nnheader-insert-file-contents file)
567       ;; Read 1K blocks until we find a separator.
568       (let ((beg 0)
569             format-alist)
570         (while (and (eq nnheader-head-chop-length
571                         (nth 1 (nnheader-insert-file-contents
572                                 file nil beg
573                                 (incf beg nnheader-head-chop-length))))
574                     (prog1 (not (search-forward "\n\n" nil t))
575                       (goto-char (point-max)))
576                     (or (null nnheader-max-head-length)
577                         (< beg nnheader-max-head-length))))))
578     t))
579
580 (defun nnheader-article-p ()
581   "Say whether the current buffer looks like an article."
582   (goto-char (point-min))
583   (if (not (search-forward "\n\n" nil t))
584       nil
585     (narrow-to-region (point-min) (1- (point)))
586     (goto-char (point-min))
587     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
588       (goto-char (match-end 0)))
589     (prog1
590         (eobp)
591       (widen))))
592
593 (defun nnheader-insert-references (references message-id)
594   "Insert a References header based on REFERENCES and MESSAGE-ID."
595   (if (and (not references) (not message-id))
596       ;; This is invalid, but not all articles have Message-IDs.
597       ()
598     (mail-position-on-field "References")
599     (let ((begin (save-excursion (beginning-of-line) (point)))
600           (fill-column 78)
601           (fill-prefix "\t"))
602       (when references
603         (insert references))
604       (when (and references message-id)
605         (insert " "))
606       (when message-id
607         (insert message-id))
608       ;; Fold long References lines to conform to RFC1036 (sort of).
609       ;; The region must end with a newline to fill the region
610       ;; without inserting extra newline.
611       (fill-region-as-paragraph begin (1+ (point))))))
612
613 (defun nnheader-replace-header (header new-value)
614   "Remove HEADER and insert the NEW-VALUE."
615   (save-excursion
616     (save-restriction
617       (nnheader-narrow-to-headers)
618       (prog1
619           (message-remove-header header)
620         (goto-char (point-max))
621         (insert header ": " new-value "\n")))))
622
623 (defun nnheader-narrow-to-headers ()
624   "Narrow to the head of an article."
625   (widen)
626   (narrow-to-region
627    (goto-char (point-min))
628    (if (search-forward "\n\n" nil t)
629        (1- (point))
630      (point-max)))
631   (goto-char (point-min)))
632
633 (defun nnheader-remove-body ()
634   "Remove the body from an article in this current buffer."
635   (goto-char (point-min))
636   (when (re-search-forward "\n\r?\n" nil t)
637     (delete-region (point) (point-max))))
638
639 (defun nnheader-set-temp-buffer (name &optional noerase)
640   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
641   (set-buffer (get-buffer-create name))
642   (buffer-disable-undo)
643   (unless noerase
644     (erase-buffer))
645   (current-buffer))
646
647 (eval-when-compile (defvar jka-compr-compression-info-list))
648 (defvar nnheader-numerical-files
649   (if (boundp 'jka-compr-compression-info-list)
650       (concat "\\([0-9]+\\)\\("
651               (mapconcat (lambda (i) (aref i 0))
652                          jka-compr-compression-info-list "\\|")
653               "\\)?")
654     "[0-9]+$")
655   "Regexp that match numerical files.")
656
657 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
658   "Regexp that matches numerical file names.")
659
660 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
661   "Regexp that matches numerical full file names.")
662
663 (defsubst nnheader-file-to-number (file)
664   "Take a FILE name and return the article number."
665   (if (string= nnheader-numerical-short-files "^[0-9]+$")
666       (string-to-int file)
667     (string-match nnheader-numerical-short-files file)
668     (string-to-int (match-string 0 file))))
669
670 (defvar nnheader-directory-files-is-safe
671   (or (eq system-type 'windows-nt)
672       (and (not (featurep 'xemacs))
673            (> emacs-major-version 20)))
674   "If non-nil, Gnus believes `directory-files' is safe.
675 It has been reported numerous times that `directory-files' fails with
676 an alarming frequency on NFS mounted file systems. If it is nil,
677 `nnheader-directory-files-safe' is used.")
678
679 (defun nnheader-directory-files-safe (&rest args)
680   "Execute `directory-files' twice and returns the longer result."
681   (let ((first (apply 'directory-files args))
682         (second (apply 'directory-files args)))
683     (if (> (length first) (length second))
684         first
685       second)))
686
687 (defun nnheader-directory-articles (dir)
688   "Return a list of all article files in directory DIR."
689   (mapcar 'nnheader-file-to-number
690           (if nnheader-directory-files-is-safe
691               (directory-files
692                dir nil nnheader-numerical-short-files t)
693             (nnheader-directory-files-safe
694              dir nil nnheader-numerical-short-files t))))
695
696 (defun nnheader-article-to-file-alist (dir)
697   "Return an alist of article/file pairs in DIR."
698   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
699           (if nnheader-directory-files-is-safe
700               (directory-files
701                dir nil nnheader-numerical-short-files t)
702             (nnheader-directory-files-safe
703              dir nil nnheader-numerical-short-files t))))
704
705 (defun nnheader-fold-continuation-lines ()
706   "Fold continuation lines in the current buffer."
707   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
708
709 (defun nnheader-translate-file-chars (file &optional full)
710   "Translate FILE into something that can be a file name.
711 If FULL, translate everything."
712   (if (null nnheader-file-name-translation-alist)
713       ;; No translation is necessary.
714       file
715     (let* ((i 0)
716            trans leaf path len)
717       (if full
718           ;; Do complete translation.
719           (setq leaf (copy-sequence file)
720                 path ""
721                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1)))
722                       2 0))
723         ;; We translate -- but only the file name.  We leave the directory
724         ;; alone.
725         (if (and (featurep 'xemacs)
726                  (memq system-type '(cygwin32 win32 w32 mswindows windows-nt)))
727             ;; This is needed on NT and stuff, because
728             ;; file-name-nondirectory is not enough to split
729             ;; file names, containing ':', e.g.
730             ;; "d:\\Work\\News\\nntp+news.fido7.ru:fido7.ru.gnu.SCORE"
731             ;;
732             ;; we are trying to correctly split such names:
733             ;; "d:file.name" -> "a:" "file.name"
734             ;; "aaa:bbb.ccc" -> "" "aaa:bbb.ccc"
735             ;; "d:aaa\\bbb:ccc"   -> "d:aaa\\" "bbb:ccc"
736             ;; etc.
737             ;; to translate then only the file name part.
738             (progn
739               (setq leaf file
740                     path "")
741               (if (string-match "\\(^\\w:\\|[/\\]\\)\\([^/\\]+\\)$" file)
742                   (setq leaf (substring file (match-beginning 2))
743                         path (substring file 0 (match-beginning 2)))))
744           ;; Emacs DTRT, says andrewi.
745           (setq leaf (file-name-nondirectory file)
746                 path (file-name-directory file))))
747       (setq len (length leaf))
748       (while (< i len)
749         (when (setq trans (cdr (assq (aref leaf i)
750                                      nnheader-file-name-translation-alist)))
751           (aset leaf i trans))
752         (incf i))
753       (concat path leaf))))
754
755 (defun nnheader-report (backend &rest args)
756   "Report an error from the BACKEND.
757 The first string in ARGS can be a format string."
758   (set (intern (format "%s-status-string" backend))
759        (if (< (length args) 2)
760            (car args)
761          (apply 'format args)))
762   nil)
763
764 (defun nnheader-get-report (backend)
765   "Get the most recent report from BACKEND."
766   (condition-case ()
767       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
768                                                              backend))))
769     (error (nnheader-message 5 ""))))
770
771 (defun nnheader-insert (format &rest args)
772   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
773 If FORMAT isn't a format string, it and all ARGS will be inserted
774 without formatting."
775   (save-excursion
776     (set-buffer nntp-server-buffer)
777     (erase-buffer)
778     (if (string-match "%" format)
779         (insert (apply 'format format args))
780       (apply 'insert format args))
781     t))
782
783 (defsubst nnheader-replace-chars-in-string (string from to)
784   (mm-subst-char-in-string from to string))
785
786 (defun nnheader-replace-duplicate-chars-in-string (string from to)
787   "Replace characters in STRING from FROM to TO."
788   (let ((string (substring string 0))   ;Copy string.
789         (len (length string))
790         (idx 0) prev i)
791     ;; Replace all occurrences of FROM with TO.
792     (while (< idx len)
793       (setq i (aref string idx))
794       (when (and (eq prev from) (= i from))
795         (aset string (1- idx) to)
796         (aset string idx to))
797       (setq prev i)
798       (setq idx (1+ idx)))
799     string))
800
801 (defun nnheader-file-to-group (file &optional top)
802   "Return a group name based on FILE and TOP."
803   (nnheader-replace-chars-in-string
804    (if (not top)
805        file
806      (condition-case ()
807          (substring (expand-file-name file)
808                     (length
809                      (expand-file-name
810                       (file-name-as-directory top))))
811        (error "")))
812    ?/ ?.))
813
814 (defun nnheader-message (level &rest args)
815   "Message if the Gnus backends are talkative."
816   (if (or (not (numberp gnus-verbose-backends))
817           (<= level gnus-verbose-backends))
818       (apply 'message args)
819     (apply 'format args)))
820
821 (defun nnheader-be-verbose (level)
822   "Return whether the backends should be verbose on LEVEL."
823   (or (not (numberp gnus-verbose-backends))
824       (<= level gnus-verbose-backends)))
825
826 (defvar nnheader-pathname-coding-system 'iso-8859-1
827   "*Coding system for file name.")
828
829 (defun nnheader-group-pathname (group dir &optional file)
830   "Make file name for GROUP."
831   (concat
832    (let ((dir (file-name-as-directory (expand-file-name dir))))
833      ;; If this directory exists, we use it directly.
834      (file-name-as-directory
835       (if (file-directory-p (concat dir group))
836           (expand-file-name group dir)
837         ;; If not, we translate dots into slashes.
838         (expand-file-name (mm-encode-coding-string
839                            (nnheader-replace-chars-in-string group ?. ?/)
840                            nnheader-pathname-coding-system)
841                           dir))))
842    (cond ((null file) "")
843          ((numberp file) (int-to-string file))
844          (t file))))
845
846 (defun nnheader-functionp (form)
847   "Return non-nil if FORM is funcallable."
848   (or (and (symbolp form) (fboundp form))
849       (and (listp form) (eq (car form) 'lambda))))
850
851 (defun nnheader-concat (dir &rest files)
852   "Concat DIR as directory to FILES."
853   (apply 'concat (file-name-as-directory dir) files))
854
855 (defun nnheader-ms-strip-cr ()
856   "Strip ^M from the end of all lines."
857   (save-excursion
858     (nnheader-remove-cr-followed-by-lf)))
859
860 (defun nnheader-file-size (file)
861   "Return the file size of FILE or 0."
862   (or (nth 7 (file-attributes file)) 0))
863
864 (defun nnheader-find-etc-directory (package &optional file)
865   "Go through the path and find the \".../etc/PACKAGE\" directory.
866 If FILE, find the \".../etc/PACKAGE\" file instead."
867   (let ((path load-path)
868         dir result)
869     ;; We try to find the dir by looking at the load path,
870     ;; stripping away the last component and adding "etc/".
871     (while path
872       (if (and (car path)
873                (file-exists-p
874                 (setq dir (concat
875                            (file-name-directory
876                             (directory-file-name (car path)))
877                            "etc/" package
878                            (if file "" "/"))))
879                (or file (file-directory-p dir)))
880           (setq result dir
881                 path nil)
882         (setq path (cdr path))))
883     result))
884
885 (eval-when-compile
886   (defvar ange-ftp-path-format)
887   (defvar efs-path-regexp))
888 (defun nnheader-re-read-dir (path)
889   "Re-read directory PATH if PATH is on a remote system."
890   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
891       (when (string-match efs-path-regexp path)
892         (efs-re-read-dir path))
893     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
894       (when (string-match (car ange-ftp-path-format) path)
895         (ange-ftp-re-read-dir path)))))
896
897 (defvar nnheader-file-coding-system 'raw-text
898   "Coding system used in file backends of Gnus.")
899
900 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
901   "Like `insert-file-contents', q.v., but only reads in the file.
902 A buffer may be modified in several ways after reading into the buffer due
903 to advanced Emacs features, such as file-name-handlers, format decoding,
904 find-file-hooks, etc.
905   This function ensures that none of these modifications will take place."
906   (let ((coding-system-for-read nnheader-file-coding-system))
907     (mm-insert-file-contents filename visit beg end replace)))
908
909 (defun nnheader-insert-nov-file (file first)
910   (let ((size (nth 7 (file-attributes file)))
911         (cutoff (* 32 1024)))
912     (when size
913       (if (< size cutoff)
914           ;; If the file is small, we just load it.
915           (nnheader-insert-file-contents file)
916         ;; We start on the assumption that FIRST is pretty recent.  If
917         ;; not, we just insert the rest of the file as well.
918         (let (current)
919           (nnheader-insert-file-contents file nil (- size cutoff) size)
920           (goto-char (point-min))
921           (delete-region (point) (or (search-forward "\n" nil 'move) (point)))
922           (setq current (ignore-errors (read (current-buffer))))
923           (if (and (numberp current)
924                    (< current first))
925               t
926             (delete-region (point-min) (point-max))
927             (nnheader-insert-file-contents file)))))))
928
929 (defun nnheader-find-file-noselect (&rest args)
930   (let ((format-alist nil)
931         (auto-mode-alist (mm-auto-mode-alist))
932         (default-major-mode 'fundamental-mode)
933         (enable-local-variables nil)
934         (after-insert-file-functions nil)
935         (enable-local-eval nil)
936         (find-file-hooks nil)
937         (coding-system-for-read nnheader-file-coding-system))
938     (apply 'find-file-noselect args)))
939
940 (defun nnheader-directory-regular-files (dir)
941   "Return a list of all regular files in DIR."
942   (let ((files (directory-files dir t))
943         out)
944     (while files
945       (when (file-regular-p (car files))
946         (push (car files) out))
947       (pop files))
948     (nreverse out)))
949
950 (defun nnheader-directory-files (&rest args)
951   "Same as `directory-files', but prune \".\" and \"..\"."
952   (let ((files (apply 'directory-files args))
953         out)
954     (while files
955       (unless (member (file-name-nondirectory (car files)) '("." ".."))
956         (push (car files) out))
957       (pop files))
958     (nreverse out)))
959
960 (defmacro nnheader-skeleton-replace (from &optional to regexp)
961   `(let ((new (generate-new-buffer " *nnheader replace*"))
962          (cur (current-buffer))
963          (start (point-min)))
964      (set-buffer cur)
965      (goto-char (point-min))
966      (while (,(if regexp 're-search-forward 'search-forward)
967              ,from nil t)
968        (insert-buffer-substring
969         cur start (prog1 (match-beginning 0) (set-buffer new)))
970        (goto-char (point-max))
971        ,(when to `(insert ,to))
972        (set-buffer cur)
973        (setq start (point)))
974      (insert-buffer-substring
975       cur start (prog1 (point-max) (set-buffer new)))
976      (copy-to-buffer cur (point-min) (point-max))
977      (kill-buffer (current-buffer))
978      (set-buffer cur)))
979
980 (defun nnheader-replace-string (from to)
981   "Do a fast replacement of FROM to TO from point to `point-max'."
982   (nnheader-skeleton-replace from to))
983
984 (defun nnheader-replace-regexp (from to)
985   "Do a fast regexp replacement of FROM to TO from point to `point-max'."
986   (nnheader-skeleton-replace from to t))
987
988 (defun nnheader-strip-cr ()
989   "Strip all \r's from the current buffer."
990   (nnheader-skeleton-replace "\r"))
991
992 (defalias 'nnheader-run-at-time 'run-at-time)
993 (defalias 'nnheader-cancel-timer 'cancel-timer)
994 (defalias 'nnheader-cancel-function-timers 'cancel-function-timers)
995 (defalias 'nnheader-string-as-multibyte 'string-as-multibyte)
996
997 (when (featurep 'xemacs)
998   (require 'nnheaderxm))
999
1000 (run-hooks 'nnheader-load-hook)
1001
1002 (provide 'nnheader)
1003
1004 ;;; nnheader.el ends here