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