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