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