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