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