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