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