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