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