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