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