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