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