*** 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     (erase-buffer)
403     (kill-all-local-variables)
404     (setq case-fold-search t)           ;Should ignore case.
405     t))
406
407 ;;; Various functions the backends use.
408
409 (defun nnheader-file-error (file)
410   "Return a string that says what is wrong with FILE."
411   (format
412    (cond
413     ((not (file-exists-p file))
414      "%s does not exist")
415     ((file-directory-p file)
416      "%s is a directory")
417     ((not (file-readable-p file))
418      "%s is not readable"))
419    file))
420
421 (defun nnheader-insert-head (file)
422   "Insert the head of the article."
423   (when (file-exists-p file)
424     (if (eq nnheader-max-head-length t)
425         ;; Just read the entire file.
426         (nnheader-insert-file-contents file)
427       ;; Read 1K blocks until we find a separator.
428       (let ((beg 0)
429             format-alist)
430         (while (and (eq nnheader-head-chop-length
431                         (nth 1 (nnheader-insert-file-contents
432                                 file nil beg
433                                 (incf beg nnheader-head-chop-length))))
434                     (prog1 (not (search-forward "\n\n" nil t))
435                       (goto-char (point-max)))
436                     (or (null nnheader-max-head-length)
437                         (< beg nnheader-max-head-length))))))
438     t))
439
440 (defun nnheader-article-p ()
441   "Say whether the current buffer looks like an article."
442   (goto-char (point-min))
443   (if (not (search-forward "\n\n" nil t))
444       nil
445     (narrow-to-region (point-min) (1- (point)))
446     (goto-char (point-min))
447     (while (looking-at "[A-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
448       (goto-char (match-end 0)))
449     (prog1
450         (eobp)
451       (widen))))
452
453 (defun nnheader-insert-references (references message-id)
454   "Insert a References header based on REFERENCES and MESSAGE-ID."
455   (if (and (not references) (not message-id))
456       ()                                ; This is illegal, but not all articles have Message-IDs.
457     (mail-position-on-field "References")
458     (let ((begin (save-excursion (beginning-of-line) (point)))
459           (fill-column 78)
460           (fill-prefix "\t"))
461       (when references
462         (insert references))
463       (when (and references message-id)
464         (insert " "))
465       (when message-id
466         (insert message-id))
467       ;; Fold long References lines to conform to RFC1036 (sort of).
468       ;; The region must end with a newline to fill the region
469       ;; without inserting extra newline.
470       (fill-region-as-paragraph begin (1+ (point))))))
471
472 (defun nnheader-replace-header (header new-value)
473   "Remove HEADER and insert the NEW-VALUE."
474   (save-excursion
475     (save-restriction
476       (nnheader-narrow-to-headers)
477       (prog1
478           (message-remove-header header)
479         (goto-char (point-max))
480         (insert header ": " new-value "\n")))))
481
482 (defun nnheader-narrow-to-headers ()
483   "Narrow to the head of an article."
484   (widen)
485   (narrow-to-region
486    (goto-char (point-min))
487    (if (search-forward "\n\n" nil t)
488        (1- (point))
489      (point-max)))
490   (goto-char (point-min)))
491
492 (defun nnheader-set-temp-buffer (name &optional noerase)
493   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
494   (set-buffer (get-buffer-create name))
495   (buffer-disable-undo (current-buffer))
496   (unless noerase
497     (erase-buffer))
498   (current-buffer))
499
500 (defvar jka-compr-compression-info-list)
501 (defvar nnheader-numerical-files
502   (if (boundp 'jka-compr-compression-info-list)
503       (concat "\\([0-9]+\\)\\("
504               (mapconcat (lambda (i) (aref i 0))
505                          jka-compr-compression-info-list "\\|")
506               "\\)?")
507     "[0-9]+$")
508   "Regexp that match numerical files.")
509
510 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
511   "Regexp that matches numerical file names.")
512
513 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
514   "Regexp that matches numerical full file paths.")
515
516 (defsubst nnheader-file-to-number (file)
517   "Take a file name and return the article number."
518   (if (string= nnheader-numerical-short-files "^[0-9]+$")
519       (string-to-int file)
520     (string-match nnheader-numerical-short-files file)
521     (string-to-int (match-string 0 file))))
522
523 (defun nnheader-directory-files-safe (&rest args)
524   ;; It has been reported numerous times that `directory-files'
525   ;; fails with an alarming frequency on NFS mounted file systems.
526   ;; This function executes that function twice and returns
527   ;; the longest result.
528   (let ((first (apply 'directory-files args))
529         (second (apply 'directory-files args)))
530     (if (> (length first) (length second))
531         first
532       second)))
533
534 (defun nnheader-directory-articles (dir)
535   "Return a list of all article files in a directory."
536   (mapcar 'nnheader-file-to-number
537           (nnheader-directory-files-safe
538            dir nil nnheader-numerical-short-files t)))
539
540 (defun nnheader-article-to-file-alist (dir)
541   "Return an alist of article/file pairs in DIR."
542   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
543           (nnheader-directory-files-safe
544            dir nil nnheader-numerical-short-files t)))
545
546 (defun nnheader-fold-continuation-lines ()
547   "Fold continuation lines in the current buffer."
548   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
549
550 (defun nnheader-translate-file-chars (file &optional full)
551   "Translate FILE into something that can be a file name.
552 If FULL, translate everything."
553   (if (null nnheader-file-name-translation-alist)
554       ;; No translation is necessary.
555       file
556     (let* ((i 0)
557            trans leaf path len)
558       (if full
559           ;; Do complete translation.
560           (setq leaf (copy-sequence file)
561                 path "")
562         ;; We translate -- but only the file name.  We leave the directory
563         ;; alone.
564         (if (string-match "/[^/]+\\'" file)
565             ;; This is needed on NT's and stuff.
566             (setq leaf (substring file (1+ (match-beginning 0)))
567                   path (substring file 0 (1+ (match-beginning 0))))
568           ;; Fall back on this.
569           (setq leaf (file-name-nondirectory file)
570                 path (file-name-directory file))))
571       (setq len (length leaf))
572       (while (< i len)
573         (when (setq trans (cdr (assq (aref leaf i)
574                                      nnheader-file-name-translation-alist)))
575           (aset leaf i trans))
576         (incf i))
577       (concat path leaf))))
578
579 (defun nnheader-report (backend &rest args)
580   "Report an error from the BACKEND.
581 The first string in ARGS can be a format string."
582   (set (intern (format "%s-status-string" backend))
583        (if (< (length args) 2)
584            (car args)
585          (apply 'format args)))
586   nil)
587
588 (defun nnheader-get-report (backend)
589   "Get the most recent report from BACKEND."
590   (condition-case ()
591       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
592                                                   backend))))
593     (error (nnheader-message 5 ""))))
594
595 (defun nnheader-insert (format &rest args)
596   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
597 If FORMAT isn't a format string, it and all ARGS will be inserted
598 without formatting."
599   (save-excursion
600     (set-buffer nntp-server-buffer)
601     (erase-buffer)
602     (if (string-match "%" format)
603         (insert (apply 'format format args))
604       (apply 'insert format args))
605     t))
606
607 (defun nnheader-replace-chars-in-string (string from to)
608   "Replace characters in STRING from FROM to TO."
609   (let ((string (substring string 0))   ;Copy string.
610         (len (length string))
611         (idx 0))
612     ;; Replace all occurrences of FROM with TO.
613     (while (< idx len)
614       (when (= (aref string idx) from)
615         (aset string idx to))
616       (setq idx (1+ idx)))
617     string))
618
619 (defun nnheader-file-to-group (file &optional top)
620   "Return a group name based on FILE and TOP."
621   (nnheader-replace-chars-in-string
622    (if (not top)
623        file
624      (condition-case ()
625          (substring (expand-file-name file)
626                     (length
627                      (expand-file-name
628                       (file-name-as-directory top))))
629        (error "")))
630    ?/ ?.))
631
632 (defun nnheader-message (level &rest args)
633   "Message if the Gnus backends are talkative."
634   (if (or (not (numberp gnus-verbose-backends))
635           (<= level gnus-verbose-backends))
636       (apply 'message args)
637     (apply 'format args)))
638
639 (defun nnheader-be-verbose (level)
640   "Return whether the backends should be verbose on LEVEL."
641   (or (not (numberp gnus-verbose-backends))
642       (<= level gnus-verbose-backends)))
643
644 (defvar nnheader-pathname-coding-system 'iso-8859-1
645   "*Coding system for pathname.")
646
647 (defun nnheader-group-pathname (group dir &optional file)
648   "Make pathname for GROUP."
649   (concat
650    (let ((dir (file-name-as-directory (expand-file-name dir))))
651      ;; If this directory exists, we use it directly.
652      (if (file-directory-p (concat dir group))
653          (concat dir group "/")
654        ;; If not, we translate dots into slashes.
655        (concat dir
656                (nnheader-encode-coding-string
657                 (nnheader-replace-chars-in-string group ?. ?/)
658                 nnheader-pathname-coding-system)
659                "/")))
660    (cond ((null file) "")
661          ((numberp file) (int-to-string file))
662          (t file))))
663
664 (defun nnheader-functionp (form)
665   "Return non-nil if FORM is funcallable."
666   (or (and (symbolp form) (fboundp form))
667       (and (listp form) (eq (car form) 'lambda))))
668
669 (defun nnheader-concat (dir &rest files)
670   "Concat DIR as directory to FILE."
671   (apply 'concat (file-name-as-directory dir) files))
672
673 (defun nnheader-ms-strip-cr ()
674   "Strip ^M from the end of all lines."
675   (save-excursion
676     (goto-char (point-min))
677     (while (re-search-forward "\r$" nil t)
678       (delete-backward-char 1))))
679
680 (defun nnheader-file-size (file)
681   "Return the file size of FILE or 0."
682   (or (nth 7 (file-attributes file)) 0))
683
684 (defun nnheader-find-etc-directory (package &optional file)
685   "Go through the path and find the \".../etc/PACKAGE\" directory.
686 If FILE, find the \".../etc/PACKAGE\" file instead."
687   (let ((path load-path)
688         dir result)
689     ;; We try to find the dir by looking at the load path,
690     ;; stripping away the last component and adding "etc/".
691     (while path
692       (if (and (car path)
693                (file-exists-p
694                 (setq dir (concat
695                            (file-name-directory
696                             (directory-file-name (car path)))
697                            "etc/" package
698                            (if file "" "/"))))
699                (or file (file-directory-p dir)))
700           (setq result dir
701                 path nil)
702         (setq path (cdr path))))
703     result))
704
705 (defvar ange-ftp-path-format)
706 (defvar efs-path-regexp)
707 (defun nnheader-re-read-dir (path)
708   "Re-read directory PATH if PATH is on a remote system."
709   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
710       (when (string-match efs-path-regexp path)
711         (efs-re-read-dir path))
712     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
713       (when (string-match (car ange-ftp-path-format) path)
714         (ange-ftp-re-read-dir path)))))
715
716 (defvar nnheader-file-coding-system 'raw-text
717   "Coding system used in file backends of Gnus.")
718
719 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
720   "Like `insert-file-contents', q.v., but only reads in the file.
721 A buffer may be modified in several ways after reading into the buffer due
722 to advanced Emacs features, such as file-name-handlers, format decoding,
723 find-file-hooks, etc.
724   This function ensures that none of these modifications will take place."
725   (let ((format-alist nil)
726         (auto-mode-alist (nnheader-auto-mode-alist))
727         (default-major-mode 'fundamental-mode)
728         (enable-local-variables nil)
729         (after-insert-file-functions nil)
730         (find-file-hooks nil)
731         (coding-system-for-read nnheader-file-coding-system))
732     (insert-file-contents filename visit beg end replace)))
733
734 (defun nnheader-find-file-noselect (&rest args)
735   (let ((format-alist nil)
736         (auto-mode-alist (nnheader-auto-mode-alist))
737         (default-major-mode 'fundamental-mode)
738         (enable-local-variables nil)
739         (after-insert-file-functions nil)
740         (find-file-hooks nil)
741         (coding-system-for-read nnheader-file-coding-system))
742     (apply 'find-file-noselect args)))
743
744 (defun nnheader-auto-mode-alist ()
745   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
746   (let ((alist auto-mode-alist)
747         out)
748     (while alist
749       (when (listp (cdar alist))
750         (push (car alist) out))
751       (pop alist))
752     (nreverse out)))
753
754 (defun nnheader-directory-regular-files (dir)
755   "Return a list of all regular files in DIR."
756   (let ((files (directory-files dir t))
757         out)
758     (while files
759       (when (file-regular-p (car files))
760         (push (car files) out))
761       (pop files))
762     (nreverse out)))
763
764 (defun nnheader-directory-files (&rest args)
765   "Same as `directory-files', but prune \".\" and \"..\"."
766   (let ((files (apply 'directory-files args))
767         out)
768     (while files
769       (unless (member (file-name-nondirectory (car files)) '("." ".."))
770         (push (car files) out))
771       (pop files))
772     (nreverse out)))
773
774 (defmacro nnheader-skeleton-replace (from &optional to regexp)
775   `(let ((new (generate-new-buffer " *nnheader replace*"))
776          (cur (current-buffer))
777          (start (point-min)))
778      (set-buffer new)
779      (buffer-disable-undo (current-buffer))
780      (set-buffer cur)
781      (goto-char (point-min))
782      (while (,(if regexp 're-search-forward 'search-forward)
783              ,from nil t)
784        (insert-buffer-substring
785         cur start (prog1 (match-beginning 0) (set-buffer new)))
786        (goto-char (point-max))
787        ,(when to `(insert ,to))
788        (set-buffer cur)
789        (setq start (point)))
790      (insert-buffer-substring
791       cur start (prog1 (point-max) (set-buffer new)))
792      (copy-to-buffer cur (point-min) (point-max))
793      (kill-buffer (current-buffer))
794      (set-buffer cur)))
795
796 (defun nnheader-replace-string (from to)
797   "Do a fast replacement of FROM to TO from point to point-max."
798   (nnheader-skeleton-replace from to))
799
800 (defun nnheader-replace-regexp (from to)
801   "Do a fast regexp replacement of FROM to TO from point to point-max."
802   (nnheader-skeleton-replace from to t))
803
804 (defun nnheader-strip-cr ()
805   "Strip all \r's from the current buffer."
806   (nnheader-skeleton-replace "\r"))
807
808 (fset 'nnheader-run-at-time 'run-at-time)
809 (fset 'nnheader-cancel-timer 'cancel-timer)
810 (fset 'nnheader-cancel-function-timers 'cancel-function-timers)
811
812 (if (fboundp 'encode-coding-string)
813     (fset 'nnheader-encode-coding-string 'encode-coding-string)
814   (fset 'nnheader-encode-coding-string (lambda (s a) s)))
815
816 (if (fboundp 'decode-coding-string)
817     (fset 'nnheader-decode-coding-string 'decode-coding-string)
818   (fset 'nnheader-decode-coding-string (lambda (s a) s)))
819
820 (when (string-match "XEmacs\\|Lucid" emacs-version)
821   (require 'nnheaderxm))
822
823 (run-hooks 'nnheader-load-hook)
824
825 (provide 'nnheader)
826
827 ;;; nnheader.el ends here