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