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