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