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