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