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