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