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