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