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