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