Revision: miles@gnu.org--gnu-2004/gnus--devo--0--patch-143
[gnus] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Gnus and its backends
2
3 ;; Copyright (C) 1987, 1988, 1989, 1990, 1993, 1994, 1995, 1996,
4 ;;        1997, 1998, 2000, 2001, 2002, 2003, 2004
5 ;;        Free Software Foundation, Inc.
6
7 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
8 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
9 ;; Keywords: news
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 ;; Requiring `gnus-util' at compile time creates a circular
35 ;; dependency between nnheader.el and gnus-util.el.
36 ;;(eval-when-compile (require 'gnus-util))
37
38 (require 'mail-utils)
39 (require 'mm-util)
40 (require 'gnus-util)
41 (eval-and-compile
42   (autoload 'gnus-sorted-intersection "gnus-range")
43   (autoload 'gnus-intersection "gnus-range")
44   (autoload 'gnus-sorted-complement "gnus-range")
45   (autoload 'gnus-sorted-difference "gnus-range"))
46
47 (defcustom gnus-verbose-backends 7
48   "Integer that says how verbose the Gnus backends should be.
49 The higher the number, the more messages the Gnus backends will flash
50 to say what it's doing.  At zero, the Gnus backends will be totally
51 mute; at five, they will display most important messages; and at ten,
52 they will keep on jabbering all the time."
53   :group 'gnus-start
54   :type 'integer)
55
56 (defcustom gnus-nov-is-evil nil
57   "If non-nil, Gnus backends will never output headers in the NOV format."
58   :group 'gnus-server
59   :type 'boolean)
60
61 (defvar nnheader-max-head-length 8192
62   "*Max length of the head of articles.
63
64 Value is an integer, nil, or t.  nil means read in chunks of a file
65 indefinitely until a complete head is found\; t means always read the
66 entire file immediately, disregarding `nnheader-head-chop-length'.
67
68 Integer values will in effect be rounded up to the nearest multiple of
69 `nnheader-head-chop-length'.")
70
71 (defvar nnheader-head-chop-length 2048
72   "*Length of each read operation when trying to fetch HEAD headers.")
73
74 (defvar nnheader-read-timeout
75   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
76                     (symbol-name system-type))
77       ;; http://thread.gmane.org/v9655t3pjo.fsf@marauder.physik.uni-ulm.de
78       ;;
79       ;; IIRC, values lower than 1.0 didn't/don't work on Windows/DOS.
80       ;;
81       ;; There should probably be a runtime test to determine the timing
82       ;; resolution, or a primitive to report it.  I don't know off-hand
83       ;; what's possible.  Perhaps better, maybe the Windows/DOS primitive
84       ;; could round up non-zero timeouts to a minimum of 1.0?
85       1.0
86     0.1)
87   "How long nntp should wait between checking for the end of output.
88 Shorter values mean quicker response, but are more CPU intensive.")
89
90 (defvar nnheader-file-name-translation-alist
91   (let ((case-fold-search t))
92     (cond
93      ((string-match "windows-nt\\|os/2\\|emx\\|cygwin"
94                     (symbol-name system-type))
95       (append (mapcar (lambda (c) (cons c ?_))
96                       '(?: ?* ?\" ?< ?> ??))
97               (if (string-match "windows-nt\\|cygwin"
98                                 (symbol-name system-type))
99                   nil
100                 '((?+ . ?-)))))
101      (t nil)))
102   "*Alist that says how to translate characters in file names.
103 For instance, if \":\" is invalid as a file character in file names
104 on your system, you could say something like:
105
106 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
107
108 (defvar nnheader-directory-separator-character
109   (string-to-char (substring (file-name-as-directory ".") -1))
110   "*A character used to a directory separator.")
111
112 (eval-and-compile
113   (autoload 'nnmail-message-id "nnmail")
114   (autoload 'mail-position-on-field "sendmail")
115   (autoload 'message-remove-header "message")
116   (autoload 'gnus-buffer-live-p "gnus-util"))
117
118 ;;; Header access macros.
119
120 ;; These macros may look very much like the ones in GNUS 4.1.  They
121 ;; are, in a way, but you should note that the indices they use have
122 ;; been changed from the internal GNUS format to the NOV format.  The
123 ;; makes it possible to read headers from XOVER much faster.
124 ;;
125 ;; The format of a header is now:
126 ;; [number subject from date id references chars lines xref extra]
127 ;;
128 ;; (That next-to-last entry is defined as "misc" in the NOV format,
129 ;; but Gnus uses it for xrefs.)
130
131 (defmacro mail-header-number (header)
132   "Return article number in HEADER."
133   `(aref ,header 0))
134
135 (defmacro mail-header-set-number (header number)
136   "Set article number of HEADER to NUMBER."
137   `(aset ,header 0 ,number))
138
139 (defmacro mail-header-subject (header)
140   "Return subject string in HEADER."
141   `(aref ,header 1))
142
143 (defmacro mail-header-set-subject (header subject)
144   "Set article subject of HEADER to SUBJECT."
145   `(aset ,header 1 ,subject))
146
147 (defmacro mail-header-from (header)
148   "Return author string in HEADER."
149   `(aref ,header 2))
150
151 (defmacro mail-header-set-from (header from)
152   "Set article author of HEADER to FROM."
153   `(aset ,header 2 ,from))
154
155 (defmacro mail-header-date (header)
156   "Return date in HEADER."
157   `(aref ,header 3))
158
159 (defmacro mail-header-set-date (header date)
160   "Set article date of HEADER to DATE."
161   `(aset ,header 3 ,date))
162
163 (defalias 'mail-header-message-id 'mail-header-id)
164 (defmacro mail-header-id (header)
165   "Return Id in HEADER."
166   `(aref ,header 4))
167
168 (defalias 'mail-header-set-message-id 'mail-header-set-id)
169 (defmacro mail-header-set-id (header id)
170   "Set article Id of HEADER to ID."
171   `(aset ,header 4 ,id))
172
173 (defmacro mail-header-references (header)
174   "Return references in HEADER."
175   `(aref ,header 5))
176
177 (defmacro mail-header-set-references (header ref)
178   "Set article references of HEADER to REF."
179   `(aset ,header 5 ,ref))
180
181 (defmacro mail-header-chars (header)
182   "Return number of chars of article in HEADER."
183   `(aref ,header 6))
184
185 (defmacro mail-header-set-chars (header chars)
186   "Set number of chars in article of HEADER to CHARS."
187   `(aset ,header 6 ,chars))
188
189 (defmacro mail-header-lines (header)
190   "Return lines in HEADER."
191   `(aref ,header 7))
192
193 (defmacro mail-header-set-lines (header lines)
194   "Set article lines of HEADER to LINES."
195   `(aset ,header 7 ,lines))
196
197 (defmacro mail-header-xref (header)
198   "Return xref string in HEADER."
199   `(aref ,header 8))
200
201 (defmacro mail-header-set-xref (header xref)
202   "Set article XREF of HEADER to xref."
203   `(aset ,header 8 ,xref))
204
205 (defmacro mail-header-extra (header)
206   "Return the extra headers in HEADER."
207   `(aref ,header 9))
208
209 (defmacro mail-header-set-extra (header extra)
210   "Set the extra headers in HEADER to EXTRA."
211   `(aset ,header 9 ',extra))
212
213 (defsubst make-mail-header (&optional init)
214   "Create a new mail header structure initialized with INIT."
215   (make-vector 10 init))
216
217 (defsubst make-full-mail-header (&optional number subject from date id
218                                            references chars lines xref
219                                            extra)
220   "Create a new mail header structure initialized with the parameters given."
221   (vector number subject from date id references chars lines xref extra))
222
223 ;; fake message-ids: generation and detection
224
225 (defvar nnheader-fake-message-id 1)
226
227 (defsubst nnheader-generate-fake-message-id (&optional number)
228   (if (numberp number)
229       (format "fake+none+%s+%d" gnus-newsgroup-name number)
230     (format "fake+none+%s+%s"
231             gnus-newsgroup-name
232             (int-to-string (incf nnheader-fake-message-id)))))
233
234 (defsubst nnheader-fake-message-id-p (id)
235   (save-match-data                     ; regular message-id's are <.*>
236     (string-match "\\`fake\\+none\\+.*\\+[0-9]+\\'" id)))
237
238 ;; Parsing headers and NOV lines.
239
240 (defsubst nnheader-remove-cr-followed-by-lf ()
241   (goto-char (point-max))
242   (while (search-backward "\r\n" nil t)
243     (delete-char 1)))
244
245 (defsubst nnheader-header-value ()
246   (skip-chars-forward " \t")
247   (buffer-substring (point) (point-at-eol)))
248
249 (defun nnheader-parse-naked-head (&optional number)
250   ;; This function unfolds continuation lines in this buffer
251   ;; destructively.  When this side effect is unwanted, use
252   ;; `nnheader-parse-head' instead of this function.
253   (let ((case-fold-search t)
254         (buffer-read-only nil)
255         (cur (current-buffer))
256         (p (point-min))
257         in-reply-to lines ref)
258     (nnheader-remove-cr-followed-by-lf)
259     (ietf-drums-unfold-fws)
260     (subst-char-in-region (point-min) (point-max) ?\t ? )
261     (goto-char p)
262     (insert "\n")
263     (prog1
264         ;; This implementation of this function, with nine
265         ;; search-forwards instead of the one re-search-forward and a
266         ;; case (which basically was the old function) is actually
267         ;; about twice as fast, even though it looks messier.  You
268         ;; can't have everything, I guess.  Speed and elegance don't
269         ;; always go hand in hand.
270         (vector
271          ;; Number.
272          (or number 0)
273          ;; Subject.
274          (progn
275            (goto-char p)
276            (if (search-forward "\nsubject:" nil t)
277                (nnheader-header-value) "(none)"))
278          ;; From.
279          (progn
280            (goto-char p)
281            (if (search-forward "\nfrom:" nil t)
282                (nnheader-header-value) "(nobody)"))
283          ;; Date.
284          (progn
285            (goto-char p)
286            (if (search-forward "\ndate:" nil t)
287                (nnheader-header-value) ""))
288          ;; Message-ID.
289          (progn
290            (goto-char p)
291            (if (search-forward "\nmessage-id:" nil t)
292                (buffer-substring
293                 (1- (or (search-forward "<" (point-at-eol) t)
294                         (point)))
295                 (or (search-forward ">" (point-at-eol) t) (point)))
296              ;; If there was no message-id, we just fake one to make
297              ;; subsequent routines simpler.
298              (nnheader-generate-fake-message-id number)))
299          ;; References.
300          (progn
301            (goto-char p)
302            (if (search-forward "\nreferences:" nil t)
303                (nnheader-header-value)
304              ;; Get the references from the in-reply-to header if
305              ;; there were no references and the in-reply-to header
306              ;; looks promising.
307              (if (and (search-forward "\nin-reply-to:" nil t)
308                       (setq in-reply-to (nnheader-header-value))
309                       (string-match "<[^\n>]+>" in-reply-to))
310                  (let (ref2)
311                    (setq ref (substring in-reply-to (match-beginning 0)
312                                         (match-end 0)))
313                    (while (string-match "<[^\n>]+>"
314                                         in-reply-to (match-end 0))
315                      (setq ref2 (substring in-reply-to (match-beginning 0)
316                                            (match-end 0)))
317                      (when (> (length ref2) (length ref))
318                        (setq ref ref2)))
319                    ref)
320                nil)))
321          ;; Chars.
322          0
323          ;; Lines.
324          (progn
325            (goto-char p)
326            (if (search-forward "\nlines: " nil t)
327                (if (numberp (setq lines (read cur)))
328                    lines 0)
329              0))
330          ;; Xref.
331          (progn
332            (goto-char p)
333            (and (search-forward "\nxref:" nil t)
334                 (nnheader-header-value)))
335          ;; Extra.
336          (when nnmail-extra-headers
337            (let ((extra nnmail-extra-headers)
338                  out)
339              (while extra
340                (goto-char p)
341                (when (search-forward
342                       (concat "\n" (symbol-name (car extra)) ":") nil t)
343                  (push (cons (car extra) (nnheader-header-value))
344                        out))
345                (pop extra))
346              out)))
347       (goto-char p)
348       (delete-char 1))))
349
350 (defun nnheader-parse-head (&optional naked)
351   (let ((cur (current-buffer)) num beg end)
352     (when (if naked
353               (setq num 0
354                     beg (point-min)
355                     end (point-max))
356             (goto-char (point-min))
357             ;; Search to the beginning of the next header.  Error
358             ;; messages do not begin with 2 or 3.
359             (when (re-search-forward "^[23][0-9]+ " nil t)
360               (end-of-line)
361               (setq num (read cur)
362                     beg (point)
363                     end (if (search-forward "\n.\n" nil t)
364                             (- (point) 2)
365                           (point)))))
366       (with-temp-buffer
367         (insert-buffer-substring cur beg end)
368         (nnheader-parse-naked-head num)))))
369
370 (defmacro nnheader-nov-skip-field ()
371   '(search-forward "\t" eol 'move))
372
373 (defmacro nnheader-nov-field ()
374   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
375
376 (defmacro nnheader-nov-read-integer ()
377   '(prog1
378        (if (eq (char-after) ?\t)
379            0
380          (let ((num (condition-case nil
381                         (read (current-buffer))
382                       (error nil))))
383            (if (numberp num) num 0)))
384      (or (eobp) (forward-char 1))))
385
386 (defmacro nnheader-nov-parse-extra ()
387   '(let (out string)
388      (while (not (memq (char-after) '(?\n nil)))
389        (setq string (nnheader-nov-field))
390        (when (string-match "^\\([^ :]+\\): " string)
391          (push (cons (intern (match-string 1 string))
392                      (substring string (match-end 0)))
393                out)))
394      out))
395
396 (defvar nnheader-uniquify-message-id nil)
397
398 (defmacro nnheader-nov-read-message-id (&optional number)
399   `(let ((id (nnheader-nov-field)))
400      (if (string-match "^<[^>]+>$" id)
401          ,(if nnheader-uniquify-message-id
402               `(if (string-match "__[^@]+@" id)
403                    (concat (substring id 0 (match-beginning 0))
404                            (substring id (1- (match-end 0))))
405                  id)
406             'id)
407        (nnheader-generate-fake-message-id ,number))))
408
409 (defun nnheader-parse-nov ()
410   (let ((eol (point-at-eol))
411         (number (nnheader-nov-read-integer)))
412     (vector
413      number                             ; number
414      (nnheader-nov-field)               ; subject
415      (nnheader-nov-field)               ; from
416      (nnheader-nov-field)               ; date
417      (nnheader-nov-read-message-id number) ; id
418      (nnheader-nov-field)               ; refs
419      (nnheader-nov-read-integer)        ; chars
420      (nnheader-nov-read-integer)        ; lines
421      (if (eq (char-after) ?\n)
422          nil
423        (if (looking-at "Xref: ")
424            (goto-char (match-end 0)))
425        (nnheader-nov-field))            ; Xref
426      (nnheader-nov-parse-extra))))      ; extra
427
428 (defun nnheader-insert-nov (header)
429   (princ (mail-header-number header) (current-buffer))
430   (let ((p (point)))
431     (insert
432      "\t"
433      (or (mail-header-subject header) "(none)") "\t"
434      (or (mail-header-from header) "(nobody)") "\t"
435      (or (mail-header-date header) "") "\t"
436      (or (mail-header-id header)
437          (nnmail-message-id))
438      "\t"
439      (or (mail-header-references header) "") "\t")
440     (princ (or (mail-header-chars header) 0) (current-buffer))
441     (insert "\t")
442     (princ (or (mail-header-lines header) 0) (current-buffer))
443     (insert "\t")
444     (when (mail-header-xref header)
445       (insert "Xref: " (mail-header-xref header)))
446     (when (or (mail-header-xref header)
447               (mail-header-extra header))
448       (insert "\t"))
449     (when (mail-header-extra header)
450       (let ((extra (mail-header-extra header)))
451         (while extra
452           (insert (symbol-name (caar extra))
453                   ": " (cdar extra) "\t")
454           (pop extra))))
455     (insert "\n")
456     (backward-char 1)
457     (while (search-backward "\n" p t)
458       (delete-char 1))
459     (forward-line 1)))
460
461 (defun nnheader-parse-overview-file (file)
462   "Parse FILE and return a list of headers."
463   (mm-with-unibyte-buffer
464     (nnheader-insert-file-contents file)
465     (goto-char (point-min))
466     (let (headers)
467       (while (not (eobp))
468         (push (nnheader-parse-nov) headers)
469         (forward-line 1))
470       (nreverse headers))))
471
472 (defun nnheader-write-overview-file (file headers)
473   "Write HEADERS to FILE."
474   (with-temp-file file
475     (mapcar 'nnheader-insert-nov headers)))
476
477 (defun nnheader-insert-header (header)
478   (insert
479    "Subject: " (or (mail-header-subject header) "(none)") "\n"
480    "From: " (or (mail-header-from header) "(nobody)") "\n"
481    "Date: " (or (mail-header-date header) "") "\n"
482    "Message-ID: " (or (mail-header-id header) (nnmail-message-id)) "\n"
483    "References: " (or (mail-header-references header) "") "\n"
484    "Lines: ")
485   (princ (or (mail-header-lines header) 0) (current-buffer))
486   (insert "\n\n"))
487
488 (defun nnheader-insert-article-line (article)
489   (goto-char (point-min))
490   (insert "220 ")
491   (princ article (current-buffer))
492   (insert " Article retrieved.\n")
493   (search-forward "\n\n" nil 'move)
494   (delete-region (point) (point-max))
495   (forward-char -1)
496   (insert "."))
497
498 (defun nnheader-nov-delete-outside-range (beg end)
499   "Delete all NOV lines that lie outside the BEG to END range."
500   ;; First we find the first wanted line.
501   (nnheader-find-nov-line beg)
502   (delete-region (point-min) (point))
503   ;; Then we find the last wanted line.
504   (when (nnheader-find-nov-line end)
505     (forward-line 1))
506   (delete-region (point) (point-max)))
507
508 (defun nnheader-find-nov-line (article)
509   "Put point at the NOV line that start with ARTICLE.
510 If ARTICLE doesn't exist, put point where that line
511 would have been.  The function will return non-nil if
512 the line could be found."
513   ;; This function basically does a binary search.
514   (let ((max (point-max))
515         (min (goto-char (point-min)))
516         (cur (current-buffer))
517         (prev (point-min))
518         num found)
519     (while (not found)
520       (goto-char (+ min (/ (- max min) 2)))
521       (beginning-of-line)
522       (if (or (= (point) prev)
523               (eobp))
524           (setq found t)
525         (setq prev (point))
526         (while (and (not (numberp (setq num (read cur))))
527                     (not (eobp)))
528           (gnus-delete-line))
529         (cond ((> num article)
530                (setq max (point)))
531               ((< num article)
532                (setq min (point)))
533               (t
534                (setq found 'yes)))))
535     ;; We may be at the first line.
536     (when (and (not num)
537                (not (eobp)))
538       (setq num (read cur)))
539     ;; Now we may have found the article we're looking for, or we
540     ;; may be somewhere near it.
541     (when (and (not (eq found 'yes))
542                (not (eq num article)))
543       (setq found (point))
544       (while (and (< (point) max)
545                   (or (not (numberp num))
546                       (< num article)))
547         (forward-line 1)
548         (setq found (point))
549         (or (eobp)
550             (= (setq num (read cur)) article)))
551       (unless (eq num article)
552         (goto-char found)))
553     (beginning-of-line)
554     (eq num article)))
555
556 ;; Various cruft the backends and Gnus need to communicate.
557
558 (defvar nntp-server-buffer nil)
559 (defvar nntp-process-response nil)
560 (defvar news-reply-yank-from nil)
561 (defvar news-reply-yank-message-id nil)
562
563 (defvar nnheader-callback-function nil)
564
565 (defun nnheader-init-server-buffer ()
566   "Initialize the Gnus-backend communication buffer."
567   (save-excursion
568     (unless (gnus-buffer-live-p nntp-server-buffer)
569       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
570     (set-buffer nntp-server-buffer)
571     (mm-enable-multibyte)
572     (erase-buffer)
573     (kill-all-local-variables)
574     (setq case-fold-search t)           ;Should ignore case.
575     (set (make-local-variable 'nntp-process-response) nil)
576     t))
577
578 ;;; Various functions the backends use.
579
580 (defun nnheader-file-error (file)
581   "Return a string that says what is wrong with FILE."
582   (format
583    (cond
584     ((not (file-exists-p file))
585      "%s does not exist")
586     ((file-directory-p file)
587      "%s is a directory")
588     ((not (file-readable-p file))
589      "%s is not readable"))
590    file))
591
592 (defun nnheader-insert-head (file)
593   "Insert the head of the article."
594   (when (file-exists-p file)
595     (if (eq nnheader-max-head-length t)
596         ;; Just read the entire file.
597         (nnheader-insert-file-contents file)
598       ;; Read 1K blocks until we find a separator.
599       (let ((beg 0)
600             format-alist)
601         (while (and (eq nnheader-head-chop-length
602                         (nth 1 (nnheader-insert-file-contents
603                                 file nil beg
604                                 (incf beg nnheader-head-chop-length))))
605                     (prog1 (not (search-forward "\n\n" nil t))
606                       (goto-char (point-max)))
607                     (or (null nnheader-max-head-length)
608                         (< beg nnheader-max-head-length))))))
609     t))
610
611 (defun nnheader-article-p ()
612   "Say whether the current buffer looks like an article."
613   (goto-char (point-min))
614   (if (not (search-forward "\n\n" nil t))
615       nil
616     (narrow-to-region (point-min) (1- (point)))
617     (goto-char (point-min))
618     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
619       (goto-char (match-end 0)))
620     (prog1
621         (eobp)
622       (widen))))
623
624 (defun nnheader-insert-references (references message-id)
625   "Insert a References header based on REFERENCES and MESSAGE-ID."
626   (if (and (not references) (not message-id))
627       ;; This is invalid, but not all articles have Message-IDs.
628       ()
629     (mail-position-on-field "References")
630     (let ((begin (point-at-bol))
631           (fill-column 78)
632           (fill-prefix "\t"))
633       (when references
634         (insert references))
635       (when (and references message-id)
636         (insert " "))
637       (when message-id
638         (insert message-id))
639       ;; Fold long References lines to conform to RFC1036 (sort of).
640       ;; The region must end with a newline to fill the region
641       ;; without inserting extra newline.
642       (fill-region-as-paragraph begin (1+ (point))))))
643
644 (defun nnheader-replace-header (header new-value)
645   "Remove HEADER and insert the NEW-VALUE."
646   (save-excursion
647     (save-restriction
648       (nnheader-narrow-to-headers)
649       (prog1
650           (message-remove-header header)
651         (goto-char (point-max))
652         (insert header ": " new-value "\n")))))
653
654 (defun nnheader-narrow-to-headers ()
655   "Narrow to the head of an article."
656   (widen)
657   (narrow-to-region
658    (goto-char (point-min))
659    (if (search-forward "\n\n" nil t)
660        (1- (point))
661      (point-max)))
662   (goto-char (point-min)))
663
664 (defun nnheader-get-lines-and-char ()
665   "Return the number of lines and chars in the article body."
666   (goto-char (point-min))
667   (if (not (re-search-forward "\n\r?\n" nil t))
668       (list 0 0)
669     (list (count-lines (point) (point-max))
670           (- (point-max) (point)))))
671
672 (defun nnheader-remove-body ()
673   "Remove the body from an article in this current buffer."
674   (goto-char (point-min))
675   (when (re-search-forward "\n\r?\n" nil t)
676     (delete-region (point) (point-max))))
677
678 (defun nnheader-set-temp-buffer (name &optional noerase)
679   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
680   (set-buffer (get-buffer-create name))
681   (buffer-disable-undo)
682   (unless noerase
683     (erase-buffer))
684   (current-buffer))
685
686 (eval-when-compile (defvar jka-compr-compression-info-list))
687 (defvar nnheader-numerical-files
688   (if (boundp 'jka-compr-compression-info-list)
689       (concat "\\([0-9]+\\)\\("
690               (mapconcat (lambda (i) (aref i 0))
691                          jka-compr-compression-info-list "\\|")
692               "\\)?")
693     "[0-9]+$")
694   "Regexp that match numerical files.")
695
696 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
697   "Regexp that matches numerical file names.")
698
699 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
700   "Regexp that matches numerical full file names.")
701
702 (defsubst nnheader-file-to-number (file)
703   "Take a FILE name and return the article number."
704   (if (string= nnheader-numerical-short-files "^[0-9]+$")
705       (string-to-int file)
706     (string-match nnheader-numerical-short-files file)
707     (string-to-int (match-string 0 file))))
708
709 (defvar nnheader-directory-files-is-safe
710   (or (eq system-type 'windows-nt)
711       (not (featurep 'xemacs)))
712   "If non-nil, Gnus believes `directory-files' is safe.
713 It has been reported numerous times that `directory-files' fails with
714 an alarming frequency on NFS mounted file systems. If it is nil,
715 `nnheader-directory-files-safe' is used.")
716
717 (defun nnheader-directory-files-safe (&rest args)
718   "Execute `directory-files' twice and returns the longer result."
719   (let ((first (apply 'directory-files args))
720         (second (apply 'directory-files args)))
721     (if (> (length first) (length second))
722         first
723       second)))
724
725 (defun nnheader-directory-articles (dir)
726   "Return a list of all article files in directory DIR."
727   (mapcar 'nnheader-file-to-number
728           (if nnheader-directory-files-is-safe
729               (directory-files
730                dir nil nnheader-numerical-short-files t)
731             (nnheader-directory-files-safe
732              dir nil nnheader-numerical-short-files t))))
733
734 (defun nnheader-article-to-file-alist (dir)
735   "Return an alist of article/file pairs in DIR."
736   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
737           (if nnheader-directory-files-is-safe
738               (directory-files
739                dir nil nnheader-numerical-short-files t)
740             (nnheader-directory-files-safe
741              dir nil nnheader-numerical-short-files t))))
742
743 (defun nnheader-fold-continuation-lines ()
744   "Fold continuation lines in the current buffer."
745   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
746
747 (defun nnheader-translate-file-chars (file &optional full)
748   "Translate FILE into something that can be a file name.
749 If FULL, translate everything."
750   (if (null nnheader-file-name-translation-alist)
751       ;; No translation is necessary.
752       file
753     (let* ((i 0)
754            trans leaf path len)
755       (if full
756           ;; Do complete translation.
757           (setq leaf (copy-sequence file)
758                 path ""
759                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1)))
760                       2 0))
761         ;; We translate -- but only the file name.  We leave the directory
762         ;; alone.
763         (if (and (featurep 'xemacs)
764                  (memq system-type '(cygwin32 win32 w32 mswindows windows-nt
765                                               cygwin)))
766             ;; This is needed on NT and stuff, because
767             ;; file-name-nondirectory is not enough to split
768             ;; file names, containing ':', e.g.
769             ;; "d:\\Work\\News\\nntp+news.fido7.ru:fido7.ru.gnu.SCORE"
770             ;;
771             ;; we are trying to correctly split such names:
772             ;; "d:file.name" -> "a:" "file.name"
773             ;; "aaa:bbb.ccc" -> "" "aaa:bbb.ccc"
774             ;; "d:aaa\\bbb:ccc"   -> "d:aaa\\" "bbb:ccc"
775             ;; etc.
776             ;; to translate then only the file name part.
777             (progn
778               (setq leaf file
779                     path "")
780               (if (string-match "\\(^\\w:\\|[/\\]\\)\\([^/\\]+\\)$" file)
781                   (setq leaf (substring file (match-beginning 2))
782                         path (substring file 0 (match-beginning 2)))))
783           ;; Emacs DTRT, says andrewi.
784           (setq leaf (file-name-nondirectory file)
785                 path (file-name-directory file))))
786       (setq len (length leaf))
787       (while (< i len)
788         (when (setq trans (cdr (assq (aref leaf i)
789                                      nnheader-file-name-translation-alist)))
790           (aset leaf i trans))
791         (incf i))
792       (concat path leaf))))
793
794 (defun nnheader-report (backend &rest args)
795   "Report an error from the BACKEND.
796 The first string in ARGS can be a format string."
797   (set (intern (format "%s-status-string" backend))
798        (if (< (length args) 2)
799            (car args)
800          (apply 'format args)))
801   nil)
802
803 (defun nnheader-get-report (backend)
804   "Get the most recent report from BACKEND."
805   (condition-case ()
806       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
807                                                              backend))))
808     (error (nnheader-message 5 ""))))
809
810 (defun nnheader-insert (format &rest args)
811   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
812 If FORMAT isn't a format string, it and all ARGS will be inserted
813 without formatting."
814   (save-excursion
815     (set-buffer nntp-server-buffer)
816     (erase-buffer)
817     (if (string-match "%" format)
818         (insert (apply 'format format args))
819       (apply 'insert format args))
820     t))
821
822 (defsubst nnheader-replace-chars-in-string (string from to)
823   (mm-subst-char-in-string from to string))
824
825 (defun nnheader-replace-duplicate-chars-in-string (string from to)
826   "Replace characters in STRING from FROM to TO."
827   (let ((string (substring string 0))   ;Copy string.
828         (len (length string))
829         (idx 0) prev i)
830     ;; Replace all occurrences of FROM with TO.
831     (while (< idx len)
832       (setq i (aref string idx))
833       (when (and (eq prev from) (= i from))
834         (aset string (1- idx) to)
835         (aset string idx to))
836       (setq prev i)
837       (setq idx (1+ idx)))
838     string))
839
840 (defun nnheader-file-to-group (file &optional top)
841   "Return a group name based on FILE and TOP."
842   (nnheader-replace-chars-in-string
843    (if (not top)
844        file
845      (condition-case ()
846          (substring (expand-file-name file)
847                     (length
848                      (expand-file-name
849                       (file-name-as-directory top))))
850        (error "")))
851    nnheader-directory-separator-character ?.))
852
853 (defun nnheader-message (level &rest args)
854   "Message if the Gnus backends are talkative."
855   (if (or (not (numberp gnus-verbose-backends))
856           (<= level gnus-verbose-backends))
857       (apply 'message args)
858     (apply 'format args)))
859
860 (defun nnheader-be-verbose (level)
861   "Return whether the backends should be verbose on LEVEL."
862   (or (not (numberp gnus-verbose-backends))
863       (<= level gnus-verbose-backends)))
864
865 (defvar nnheader-pathname-coding-system 'iso-8859-1
866   "*Coding system for file name.")
867
868 (defun nnheader-group-pathname (group dir &optional file)
869   "Make file name for GROUP."
870   (concat
871    (let ((dir (file-name-as-directory (expand-file-name dir))))
872      ;; If this directory exists, we use it directly.
873      (file-name-as-directory
874       (if (file-directory-p (concat dir group))
875           (expand-file-name group dir)
876         ;; If not, we translate dots into slashes.
877         (expand-file-name (mm-encode-coding-string
878                            (nnheader-replace-chars-in-string group ?. ?/)
879                            nnheader-pathname-coding-system)
880                           dir))))
881    (cond ((null file) "")
882          ((numberp file) (int-to-string file))
883          (t file))))
884
885 (defun nnheader-concat (dir &rest files)
886   "Concat DIR as directory to FILES."
887   (apply 'concat (file-name-as-directory dir) files))
888
889 (defun nnheader-ms-strip-cr ()
890   "Strip ^M from the end of all lines."
891   (save-excursion
892     (nnheader-remove-cr-followed-by-lf)))
893
894 (defun nnheader-file-size (file)
895   "Return the file size of FILE or 0."
896   (or (nth 7 (file-attributes file)) 0))
897
898 (defun nnheader-find-etc-directory (package &optional file first)
899   "Go through `load-path' and find the \"../etc/PACKAGE\" directory.
900 This function will look in the parent directory of each `load-path'
901 entry, and look for the \"etc\" directory there.
902 If FILE, find the \".../etc/PACKAGE\" file instead.
903 If FIRST is non-nil, return the directory or the file found at the
904 first.  Otherwise, find the newest one, though it may take a time."
905   (let ((path load-path)
906         dir results)
907     ;; We try to find the dir by looking at the load path,
908     ;; stripping away the last component and adding "etc/".
909     (while path
910       (if (and (car path)
911                (file-exists-p
912                 (setq dir (concat
913                            (file-name-directory
914                             (directory-file-name (car path)))
915                            "etc/" package
916                            (if file "" "/"))))
917                (or file (file-directory-p dir)))
918           (progn
919             (or (member dir results)
920                 (push dir results))
921             (setq path (if first nil (cdr path))))
922         (setq path (cdr path))))
923     (if (or first (not (cdr results)))
924         (car results)
925       (car (sort results 'file-newer-than-file-p)))))
926
927 (eval-when-compile
928   (defvar ange-ftp-path-format)
929   (defvar efs-path-regexp))
930 (defun nnheader-re-read-dir (path)
931   "Re-read directory PATH if PATH is on a remote system."
932   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
933       (when (string-match efs-path-regexp path)
934         (efs-re-read-dir path))
935     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
936       (when (string-match (car ange-ftp-path-format) path)
937         (ange-ftp-re-read-dir path)))))
938
939 (defvar nnheader-file-coding-system 'raw-text
940   "Coding system used in file backends of Gnus.")
941
942 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
943   "Like `insert-file-contents', q.v., but only reads in the file.
944 A buffer may be modified in several ways after reading into the buffer due
945 to advanced Emacs features, such as file-name-handlers, format decoding,
946 find-file-hooks, etc.
947   This function ensures that none of these modifications will take place."
948   (let ((coding-system-for-read nnheader-file-coding-system))
949     (mm-insert-file-contents filename visit beg end replace)))
950
951 (defun nnheader-insert-nov-file (file first)
952   (let ((size (nth 7 (file-attributes file)))
953         (cutoff (* 32 1024)))
954     (when size
955       (if (< size cutoff)
956           ;; If the file is small, we just load it.
957           (nnheader-insert-file-contents file)
958         ;; We start on the assumption that FIRST is pretty recent.  If
959         ;; not, we just insert the rest of the file as well.
960         (let (current)
961           (nnheader-insert-file-contents file nil (- size cutoff) size)
962           (goto-char (point-min))
963           (delete-region (point) (or (search-forward "\n" nil 'move) (point)))
964           (setq current (ignore-errors (read (current-buffer))))
965           (if (and (numberp current)
966                    (< current first))
967               t
968             (delete-region (point-min) (point-max))
969             (nnheader-insert-file-contents file)))))))
970
971 (defun nnheader-find-file-noselect (&rest args)
972   (let ((format-alist nil)
973         (auto-mode-alist (mm-auto-mode-alist))
974         (default-major-mode 'fundamental-mode)
975         (enable-local-variables nil)
976         (after-insert-file-functions nil)
977         (enable-local-eval nil)
978         (find-file-hooks nil)
979         (coding-system-for-read nnheader-file-coding-system))
980     (apply 'find-file-noselect args)))
981
982 (defun nnheader-directory-regular-files (dir)
983   "Return a list of all regular files in DIR."
984   (let ((files (directory-files dir t))
985         out)
986     (while files
987       (when (file-regular-p (car files))
988         (push (car files) out))
989       (pop files))
990     (nreverse out)))
991
992 (defun nnheader-directory-files (&rest args)
993   "Same as `directory-files', but prune \".\" and \"..\"."
994   (let ((files (apply 'directory-files args))
995         out)
996     (while files
997       (unless (member (file-name-nondirectory (car files)) '("." ".."))
998         (push (car files) out))
999       (pop files))
1000     (nreverse out)))
1001
1002 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1003   `(let ((new (generate-new-buffer " *nnheader replace*"))
1004          (cur (current-buffer))
1005          (start (point-min)))
1006      (set-buffer cur)
1007      (goto-char (point-min))
1008      (while (,(if regexp 're-search-forward 'search-forward)
1009              ,from nil t)
1010        (insert-buffer-substring
1011         cur start (prog1 (match-beginning 0) (set-buffer new)))
1012        (goto-char (point-max))
1013        ,(when to `(insert ,to))
1014        (set-buffer cur)
1015        (setq start (point)))
1016      (insert-buffer-substring
1017       cur start (prog1 (point-max) (set-buffer new)))
1018      (copy-to-buffer cur (point-min) (point-max))
1019      (kill-buffer (current-buffer))
1020      (set-buffer cur)))
1021
1022 (defun nnheader-replace-string (from to)
1023   "Do a fast replacement of FROM to TO from point to `point-max'."
1024   (nnheader-skeleton-replace from to))
1025
1026 (defun nnheader-replace-regexp (from to)
1027   "Do a fast regexp replacement of FROM to TO from point to `point-max'."
1028   (nnheader-skeleton-replace from to t))
1029
1030 (defun nnheader-strip-cr ()
1031   "Strip all \r's from the current buffer."
1032   (nnheader-skeleton-replace "\r"))
1033
1034 (defalias 'nnheader-cancel-timer 'cancel-timer)
1035 (defalias 'nnheader-cancel-function-timers 'cancel-function-timers)
1036 (defalias 'nnheader-string-as-multibyte 'string-as-multibyte)
1037
1038 (defun nnheader-accept-process-output (process)
1039   (accept-process-output
1040    process
1041    (truncate nnheader-read-timeout)
1042    (truncate (* (- nnheader-read-timeout
1043                    (truncate nnheader-read-timeout))
1044                 1000))))
1045
1046 (when (featurep 'xemacs)
1047   (require 'nnheaderxm))
1048
1049 (run-hooks 'nnheader-load-hook)
1050
1051 (provide 'nnheader)
1052
1053 ;;; arch-tag: a9c4b7d9-52ae-4ec9-b196-dfd93124d202
1054 ;;; nnheader.el ends here