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