*** empty log message ***
[gnus] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Gnus and its backends
2 ;; Copyright (C) 1987,88,89,90,93,94,95,96 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; These macros may look very much like the ones in GNUS 4.1.  They
28 ;; are, in a way, but you should note that the indices they use have
29 ;; been changed from the internal GNUS format to the NOV format.  The
30 ;; makes it possible to read headers from XOVER much faster.
31 ;;
32 ;; The format of a header is now:
33 ;; [number subject from date id references chars lines xref]
34 ;;
35 ;; (That last entry is defined as "misc" in the NOV format, but Gnus
36 ;; uses it for xrefs.)
37
38 ;;; Code:
39
40 (require 'mail-utils)
41 (require 'sendmail)
42 (eval-when-compile (require 'cl))
43
44 (defvar nnheader-max-head-length 4096
45   "*Max length of the head of articles.")
46
47 (defvar nnheader-file-name-translation-alist nil
48   "*Alist that says how to translate characters in file names.
49 For instance, if \":\" is illegal as a file character in file names
50 on your system, you could say something like:
51
52 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
53
54 ;;; Header access macros.
55
56 (defmacro mail-header-number (header)
57   "Return article number in HEADER."
58   `(aref ,header 0))
59
60 (defmacro mail-header-set-number (header number)
61   "Set article number of HEADER to NUMBER."
62   `(aset ,header 0 ,number))
63
64 (defmacro mail-header-subject (header)
65   "Return subject string in HEADER."
66   `(aref ,header 1))
67
68 (defmacro mail-header-set-subject (header subject)
69   "Set article subject of HEADER to SUBJECT."
70   `(aset ,header 1 ,subject))
71
72 (defmacro mail-header-from (header)
73   "Return author string in HEADER."
74   `(aref ,header 2))
75
76 (defmacro mail-header-set-from (header from)
77   "Set article author of HEADER to FROM."
78   `(aset ,header 2 ,from))
79
80 (defmacro mail-header-date (header)
81   "Return date in HEADER."
82   `(aref ,header 3))
83
84 (defmacro mail-header-set-date (header date)
85   "Set article date of HEADER to DATE."
86   `(aset ,header 3 ,date))
87
88 (defalias 'mail-header-message-id 'mail-header-id)
89 (defmacro mail-header-id (header)
90   "Return Id in HEADER."
91   `(aref ,header 4))
92
93 (defalias 'mail-header-set-message-id 'mail-header-set-id)
94 (defmacro mail-header-set-id (header id)
95   "Set article Id of HEADER to ID."
96   `(aset ,header 4 ,id))
97
98 (defmacro mail-header-references (header)
99   "Return references in HEADER."
100   `(aref ,header 5))
101
102 (defmacro mail-header-set-references (header ref)
103   "Set article references of HEADER to REF."
104   `(aset ,header 5 ,ref))
105
106 (defmacro mail-header-chars (header)
107   "Return number of chars of article in HEADER."
108   `(aref ,header 6))
109
110 (defmacro mail-header-set-chars (header chars)
111   "Set number of chars in article of HEADER to CHARS."
112   `(aset ,header 6 ,chars))
113
114 (defmacro mail-header-lines (header)
115   "Return lines in HEADER."
116   `(aref ,header 7))
117
118 (defmacro mail-header-set-lines (header lines)
119   "Set article lines of HEADER to LINES."
120   `(aset ,header 7 ,lines))
121
122 (defmacro mail-header-xref (header)
123   "Return xref string in HEADER."
124   `(aref ,header 8))
125
126 (defmacro mail-header-set-xref (header xref)
127   "Set article xref of HEADER to xref."
128   `(aset ,header 8 ,xref))
129
130 (defun make-mail-header (&optional init)
131   "Create a new mail header structure initialized with INIT."
132   (make-vector 9 init))
133
134 ;; Parsing headers and NOV lines.
135
136 (defsubst nnheader-header-value ()
137   (buffer-substring (match-end 0) (gnus-point-at-eol)))
138
139 (defvar nnheader-newsgroup-none-id 1)
140
141 (defun nnheader-parse-head ()
142   (let ((case-fold-search t)
143         (cur (current-buffer))
144         end ref in-reply-to lines p)
145     (goto-char (point-min))
146     ;; Search to the beginning of the next header. Error messages
147     ;; do not begin with 2 or 3.
148     (when (re-search-forward "^[23][0-9]+ " nil t)
149       ;; This implementation of this function, with nine
150       ;; search-forwards instead of the one re-search-forward and
151       ;; a case (which basically was the old function) is actually
152       ;; about twice as fast, even though it looks messier.      You
153       ;; can't have everything, I guess.  Speed and elegance
154       ;; doesn't always go hand in hand.
155       (vector
156        ;; Number.
157        (prog1
158            (read cur)
159          (end-of-line)
160          (setq p (point))
161          (narrow-to-region (point)
162                            (or (and (search-forward "\n.\n" nil t)
163                                     (- (point) 2))
164                                (point))))
165        ;; Subject.
166        (progn
167          (goto-char p)
168          (if (search-forward "\nsubject: " nil t)
169              (nnheader-header-value) "(none)"))
170        ;; From.
171        (progn
172          (goto-char p)
173          (if (search-forward "\nfrom: " nil t)
174              (nnheader-header-value) "(nobody)"))
175        ;; Date.
176        (progn
177          (goto-char p)
178          (if (search-forward "\ndate: " nil t)
179              (nnheader-header-value) ""))
180        ;; Message-ID.
181        (progn
182          (goto-char p)
183          (if (search-forward "\nmessage-id: " nil t)
184              (nnheader-header-value)
185            ;; If there was no message-id, we just fake one to make
186            ;; subsequent routines simpler.
187            (concat "none+"
188                    (int-to-string
189                     (incf nnheader-newsgroup-none-id)))))
190        ;; References.
191        (progn
192          (goto-char p)
193          (if (search-forward "\nreferences: " nil t)
194              (nnheader-header-value)
195            ;; Get the references from the in-reply-to header if there
196            ;; were no references and the in-reply-to header looks
197            ;; promising.
198            (if (and (search-forward "\nin-reply-to: " nil t)
199                     (setq in-reply-to (nnheader-header-value))
200                     (string-match "<[^>]+>" in-reply-to))
201                (substring in-reply-to (match-beginning 0)
202                           (match-end 0))
203              "")))
204        ;; Chars.
205        0
206        ;; Lines.
207        (progn
208          (goto-char p)
209          (if (search-forward "\nlines: " nil t)
210              (if (numberp (setq lines (read cur)))
211                  lines 0)
212            0))
213        ;; Xref.
214        (progn
215          (goto-char p)
216          (and (search-forward "\nxref: " nil t)
217               (nnheader-header-value)))))))
218
219 (defun nnheader-insert-nov (header)
220   (princ (mail-header-number header) (current-buffer))
221   (insert 
222    "\t"
223    (or (mail-header-subject header) "") "\t"
224    (or (mail-header-from header) "") "\t"
225    (or (mail-header-date header) "") "\t"
226    (or (mail-header-id header) "") "\t"
227    (or (mail-header-references header) "") "\t")
228   (princ (or (mail-header-chars header) 0) (current-buffer))
229   (insert "\t")
230   (princ (or (mail-header-lines header) 0) (current-buffer))
231   (insert "\t")
232   (when (mail-header-xref header) 
233     (insert "Xref: " (mail-header-xref header) "\t"))
234   (insert "\n"))
235
236 (defun nnheader-insert-article-line (article)
237   (goto-char (point-min))
238   (insert "220 ")
239   (princ article (current-buffer))
240   (insert " Article retrieved.\n")
241   (search-forward "\n\n" nil 'move)
242   (delete-region (point) (point-max))
243   (forward-char -1)
244   (insert "."))
245
246 ;; Various cruft the backends and Gnus need to communicate.
247
248 (defvar nntp-server-buffer nil)
249 (defvar gnus-verbose-backends 7
250   "*A number that says how talkative the Gnus backends should be.")
251 (defvar gnus-nov-is-evil nil
252   "If non-nil, Gnus backends will never output headers in the NOV format.")
253 (defvar news-reply-yank-from nil)
254 (defvar news-reply-yank-message-id nil)
255
256 (defvar nnheader-callback-function nil)
257
258 (defun nnheader-init-server-buffer ()
259   "Initialize the Gnus-backend communication buffer."
260   (save-excursion
261     (setq nntp-server-buffer (get-buffer-create " *nntpd*"))
262     (set-buffer nntp-server-buffer)
263     (buffer-disable-undo (current-buffer))
264     (erase-buffer)
265     (kill-all-local-variables)
266     (setq case-fold-search t)           ;Should ignore case.
267     t))
268
269
270 ;;; Various functions the backends use.
271
272 (defun nnheader-file-error (file)
273   "Return a string that says what is wrong with FILE."
274   (format
275    (cond
276     ((not (file-exists-p file))
277      "%s does not exist")
278     ((file-directory-p file)
279      "%s is a directory")
280     ((not (file-readable-p file))
281      "%s is not readable"))
282    file))
283
284 (defun nnheader-insert-head (file)
285   "Insert the head of the article."
286   (when (file-exists-p file)
287     (if (eq nnheader-max-head-length t)
288         ;; Just read the entire file.
289         (insert-file-contents-literally file)
290       ;; Read 1K blocks until we find a separator.
291       (let ((beg 0)
292             format-alist 
293             (chop 1024))
294         (while (and (eq chop (nth 1 (insert-file-contents
295                                      file nil beg (incf beg chop))))
296                     (prog1 (not (search-forward "\n\n" nil t)) 
297                       (goto-char (point-max)))
298                     (or (null nnheader-max-head-length)
299                         (< beg nnheader-max-head-length))))))
300     t))
301
302 (defun nnheader-article-p ()
303   "Say whether the current buffer looks like an article."
304   (goto-char (point-min))
305   (if (not (search-forward "\n\n" nil t))
306       nil
307     (narrow-to-region (point-min) (1- (point)))
308     (goto-char (point-min))
309     (while (looking-at "[A-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
310       (goto-char (match-end 0)))
311     (prog1
312         (eobp)
313       (widen))))    
314
315 (defun nnheader-insert-references (references message-id)
316   "Insert a References header based on REFERENCES and MESSAGE-ID."
317   (if (and (not references) (not message-id)) 
318       ()        ; This is illegal, but not all articles have Message-IDs.
319     (mail-position-on-field "References")
320     (let ((begin (save-excursion (beginning-of-line) (point)))
321           (fill-column 78)
322           (fill-prefix "\t"))
323       (if references (insert references))
324       (if (and references message-id) (insert " "))
325       (if message-id (insert message-id))
326       ;; Fold long References lines to conform to RFC1036 (sort of).
327       ;; The region must end with a newline to fill the region
328       ;; without inserting extra newline.
329       (fill-region-as-paragraph begin (1+ (point))))))
330
331 (defun nnheader-replace-header (header new-value)
332   "Remove HEADER and insert the NEW-VALUE."
333   (save-excursion
334     (save-restriction
335       (nnheader-narrow-to-headers)
336       (prog1
337           (message-remove-header header)
338         (goto-char (point-max))
339         (insert header ": " new-value "\n")))))
340
341 (defun nnheader-narrow-to-headers ()
342   "Narrow to the head of an article."
343   (widen)
344   (narrow-to-region
345    (goto-char (point-min))
346    (if (search-forward "\n\n" nil t)
347        (1- (point))
348      (point-max)))
349   (goto-char (point-min)))
350
351 (defun nnheader-set-temp-buffer (name)
352   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
353   (set-buffer (get-buffer-create name))
354   (buffer-disable-undo (current-buffer))
355   (erase-buffer)
356   (current-buffer))
357
358 (defmacro nnheader-temp-write (file &rest forms)
359   "Create a new buffer, evaluate FORM there, and write the buffer to FILE."
360   `(save-excursion
361      (let ((nnheader-temp-file ,file)
362            (nnheader-temp-cur-buffer
363             (nnheader-set-temp-buffer
364              (generate-new-buffer-name " *nnheader temp*"))))
365        (when (and nnheader-temp-file 
366                   (not (file-directory-p (file-name-directory 
367                                           nnheader-temp-file))))
368          (make-directory (file-name-directory nnheader-temp-file) t))
369        (unwind-protect
370            (prog1
371                (progn
372                  ,@forms)
373              (when nnheader-temp-file
374                (set-buffer nnheader-temp-cur-buffer)
375                (write-region (point-min) (point-max) 
376                              nnheader-temp-file nil 'nomesg)))
377          (when (buffer-name nnheader-temp-cur-buffer)
378            (kill-buffer nnheader-temp-cur-buffer))))))
379
380 (put 'nnheader-temp-write 'lisp-indent-function 1)
381 (put 'nnheader-temp-write 'lisp-indent-hook 1)
382 (put 'nnheader-temp-write 'edebug-form-spec '(file &rest form))
383
384 (defvar jka-compr-compression-info-list)
385 (defvar nnheader-numerical-files
386   (if (boundp 'jka-compr-compression-info-list)
387       (concat "\\([0-9]+\\)\\(" 
388               (mapconcat (lambda (i) (aref i 0))
389                          jka-compr-compression-info-list "\\|")
390               "\\)?")
391     "[0-9]+$")
392   "Regexp that match numerical files.")
393
394 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
395   "Regexp that matches numerical file names.")
396
397 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
398   "Regexp that matches numerical full file paths.")
399
400 (defsubst nnheader-file-to-number (file)
401   "Take a file name and return the article number."
402   (if (not (boundp 'jka-compr-compression-info-list))
403       (string-to-int file)
404     (string-match nnheader-numerical-short-files file)
405     (string-to-int (match-string 0 file))))
406
407 (defun nnheader-directory-articles (dir)
408   "Return a list of all article files in a directory."
409   (mapcar 'nnheader-file-to-number
410           (directory-files dir nil nnheader-numerical-short-files t)))
411
412 (defun nnheader-article-to-file-alist (dir)
413   "Return an alist of article/file pairs in DIR."
414   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
415           (directory-files dir nil nnheader-numerical-short-files t)))
416
417 (defun nnheader-fold-continuation-lines ()
418   "Fold continuation lines in the current buffer."
419   (goto-char (point-min))
420   (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
421     (replace-match " " t t)))
422
423 (defun nnheader-translate-file-chars (file)
424   (if (null nnheader-file-name-translation-alist)
425       ;; No translation is necessary.
426       file 
427     ;; We translate -- but only the file name.  We leave the directory
428     ;; alone.
429     (let* ((new (file-name-nondirectory file))
430            (len (length new))
431            (i 0)
432           trans)
433       (while (< i len)
434         (when (setq trans (cdr (assq (aref new i)
435                                      nnheader-file-name-translation-alist)))
436           (aset new i trans))
437         (incf i))
438       (concat (file-name-directory file) new))))
439
440 (defun nnheader-report (backend &rest args)
441   "Report an error from the BACKEND.
442 The first string in ARGS can be a format string."
443   (set (intern (format "%s-status-string" backend))
444        (if (< (length args) 2)
445            (car args)
446          (apply 'format args)))
447   nil)
448
449 (defun nnheader-get-report (backend)
450   (message "%s" (symbol-value (intern (format "%s-status-string" backend)))))
451
452 (defun nnheader-insert (format &rest args)
453   "Clear the communicaton buffer and insert FORMAT and ARGS into the buffer.
454 If FORMAT isn't a format string, it and all ARGS will be inserted
455 without formatting."
456   (save-excursion
457     (set-buffer nntp-server-buffer)
458     (erase-buffer)
459     (if (string-match "%" format)
460         (insert (apply 'format format args))
461       (apply 'insert format args))
462     t))
463
464 (defun nnheader-mail-file-mbox-p (file)
465   "Say whether FILE looks like an Unix mbox file."
466   (when (and (file-exists-p file)
467              (file-readable-p file)
468              (file-regular-p file))
469     (save-excursion
470       (nnheader-set-temp-buffer " *mail-file-mbox-p*")
471       (insert-file-contents-literally file)
472       (goto-char (point-min))
473       (prog1
474           (looking-at message-unix-mail-delimiter)
475         (kill-buffer (current-buffer))))))
476
477 (defun nnheader-replace-chars-in-string (string from to)
478   "Replace characters in STRING from FROM to TO."
479   (let ((string (substring string 0))   ;Copy string.
480         (len (length string))
481         (idx 0))
482     ;; Replace all occurrences of FROM with TO.
483     (while (< idx len)
484       (if (= (aref string idx) from)
485           (aset string idx to))
486       (setq idx (1+ idx)))
487     string))
488
489 (defun nnheader-file-to-group (file &optional top)
490   "Return a group name based on FILE and TOP."
491   (nnheader-replace-chars-in-string 
492    (if (not top)
493        file
494      (condition-case ()
495          (substring (expand-file-name file)
496                     (length 
497                      (expand-file-name
498                       (file-name-as-directory top))))
499        (error "")))
500    ?/ ?.))
501
502 (defun nnheader-message (level &rest args)
503   "Message if the Gnus backends are talkative."
504   (if (or (not (numberp gnus-verbose-backends))
505           (<= level gnus-verbose-backends))
506       (apply 'message args)
507     (apply 'format args)))
508
509 (defun nnheader-be-verbose (level)
510   "Return whether the backends should be verbose on LEVEL."
511   (or (not (numberp gnus-verbose-backends))
512       (<= level gnus-verbose-backends)))
513
514 (defun nnheader-group-pathname (group dir &optional file)
515   "Make pathname for GROUP."
516   (concat
517    (let ((dir (file-name-as-directory (expand-file-name dir))))
518      ;; If this directory exists, we use it directly.
519      (if (file-directory-p (concat dir group))
520          (concat dir group "/")
521        ;; If not, we translate dots into slashes.
522        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
523    (cond ((null file) "")
524          ((numberp file) (int-to-string file))
525          (t file))))
526
527 (defun nnheader-functionp (form)
528   "Return non-nil if FORM is funcallable."
529   (or (and (symbolp form) (fboundp form))
530       (and (listp form) (eq (car form) 'lambda))))
531
532 (fset 'nnheader-find-file-noselect 'find-file-noselect)
533 (fset 'nnheader-insert-raw-file-contents 'insert-file-contents)
534
535 (provide 'nnheader)
536
537 (run-hooks 'nnheader-load-hook)
538
539 ;;; nnheader.el ends here