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