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