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