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