*** 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
42 (defvar nnheader-max-head-length 4096
43   "*Max length of the head of articles.")
44
45 (defvar nnheader-file-name-translation-alist nil
46   "*Alist that says how to translate characters in file names.
47 For instance, if \":\" is illegal as a file character in file names
48 on your system, you could say something like:
49
50 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
51
52 (eval-and-compile
53  (autoload 'nnmail-message-id "nnmail")
54  (autoload 'mail-position-on-field "sendmail")
55  (autoload 'message-remove-header "message")
56  (autoload 'cancel-function-timers "timers"))
57
58 ;;; Header access macros.
59
60 (defmacro mail-header-number (header)
61   "Return article number in HEADER."
62   `(aref ,header 0))
63
64 (defmacro mail-header-set-number (header number)
65   "Set article number of HEADER to NUMBER."
66   `(aset ,header 0 ,number))
67
68 (defmacro mail-header-subject (header)
69   "Return subject string in HEADER."
70   `(aref ,header 1))
71
72 (defmacro mail-header-set-subject (header subject)
73   "Set article subject of HEADER to SUBJECT."
74   `(aset ,header 1 ,subject))
75
76 (defmacro mail-header-from (header)
77   "Return author string in HEADER."
78   `(aref ,header 2))
79
80 (defmacro mail-header-set-from (header from)
81   "Set article author of HEADER to FROM."
82   `(aset ,header 2 ,from))
83
84 (defmacro mail-header-date (header)
85   "Return date in HEADER."
86   `(aref ,header 3))
87
88 (defmacro mail-header-set-date (header date)
89   "Set article date of HEADER to DATE."
90   `(aset ,header 3 ,date))
91
92 (defalias 'mail-header-message-id 'mail-header-id)
93 (defmacro mail-header-id (header)
94   "Return Id in HEADER."
95   `(aref ,header 4))
96
97 (defalias 'mail-header-set-message-id 'mail-header-set-id)
98 (defmacro mail-header-set-id (header id)
99   "Set article Id of HEADER to ID."
100   `(aset ,header 4 ,id))
101
102 (defmacro mail-header-references (header)
103   "Return references in HEADER."
104   `(aref ,header 5))
105
106 (defmacro mail-header-set-references (header ref)
107   "Set article references of HEADER to REF."
108   `(aset ,header 5 ,ref))
109
110 (defmacro mail-header-chars (header)
111   "Return number of chars of article in HEADER."
112   `(aref ,header 6))
113
114 (defmacro mail-header-set-chars (header chars)
115   "Set number of chars in article of HEADER to CHARS."
116   `(aset ,header 6 ,chars))
117
118 (defmacro mail-header-lines (header)
119   "Return lines in HEADER."
120   `(aref ,header 7))
121
122 (defmacro mail-header-set-lines (header lines)
123   "Set article lines of HEADER to LINES."
124   `(aset ,header 7 ,lines))
125
126 (defmacro mail-header-xref (header)
127   "Return xref string in HEADER."
128   `(aref ,header 8))
129
130 (defmacro mail-header-set-xref (header xref)
131   "Set article xref of HEADER to xref."
132   `(aset ,header 8 ,xref))
133
134 (defun make-mail-header (&optional init)
135   "Create a new mail header structure initialized with INIT."
136   (make-vector 9 init))
137
138 (defun make-full-mail-header (&optional number subject from date id
139                                         references chars lines xref)
140   "Create a new mail header structure initialized with the parameters given."
141   (vector number subject from date id references chars lines xref))
142   
143 ;; Parsing headers and NOV lines.
144
145 (defsubst nnheader-header-value ()
146   (buffer-substring (match-end 0) (gnus-point-at-eol)))
147
148 (defvar nnheader-newsgroup-none-id 1)
149
150 (defun nnheader-parse-head (&optional naked)
151   (let ((case-fold-search t)
152         (cur (current-buffer))
153         (buffer-read-only nil)
154         end ref in-reply-to lines p)
155     (goto-char (point-min))
156     (when naked
157       (insert "\n"))
158     ;; Search to the beginning of the next header. Error messages
159     ;; do not begin with 2 or 3.
160     (prog1
161         (when (or naked (re-search-forward "^[23][0-9]+ " nil t))
162           ;; This implementation of this function, with nine
163           ;; search-forwards instead of the one re-search-forward and
164           ;; a case (which basically was the old function) is actually
165           ;; about twice as fast, even though it looks messier.  You
166           ;; can't have everything, I guess.  Speed and elegance
167           ;; doesn't always go hand in hand.
168           (vector
169            ;; Number.
170            (if naked
171                (progn
172                  (setq p (point-min))
173                  0)
174              (prog1
175                  (read cur)
176                (end-of-line)
177                (setq p (point))
178                (narrow-to-region (point)
179                                  (or (and (search-forward "\n.\n" nil t)
180                                           (- (point) 2))
181                                      (point)))))
182            ;; Subject.
183            (progn
184              (goto-char p)
185              (if (search-forward "\nsubject: " nil t)
186                  (nnheader-header-value) "(none)"))
187            ;; From.
188            (progn
189              (goto-char p)
190              (if (search-forward "\nfrom: " nil t)
191                  (nnheader-header-value) "(nobody)"))
192            ;; Date.
193            (progn
194              (goto-char p)
195              (if (search-forward "\ndate: " nil t)
196                  (nnheader-header-value) ""))
197            ;; Message-ID.
198            (progn
199              (goto-char p)
200              (if (search-forward "\nmessage-id: " nil t)
201                  (nnheader-header-value)
202                ;; If there was no message-id, we just fake one to make
203                ;; subsequent routines simpler.
204                (concat "none+"
205                        (int-to-string
206                         (incf nnheader-newsgroup-none-id)))))
207            ;; References.
208            (progn
209              (goto-char p)
210              (if (search-forward "\nreferences: " nil t)
211                  (nnheader-header-value)
212                ;; Get the references from the in-reply-to header if there
213                ;; were no references and the in-reply-to header looks
214                ;; promising.
215                (if (and (search-forward "\nin-reply-to: " nil t)
216                         (setq in-reply-to (nnheader-header-value))
217                         (string-match "<[^>]+>" in-reply-to))
218                    (substring in-reply-to (match-beginning 0)
219                               (match-end 0))
220                  "")))
221            ;; Chars.
222            0
223            ;; Lines.
224            (progn
225              (goto-char p)
226              (if (search-forward "\nlines: " nil t)
227                  (if (numberp (setq lines (read cur)))
228                      lines 0)
229                0))
230            ;; Xref.
231            (progn
232              (goto-char p)
233              (and (search-forward "\nxref: " nil t)
234                   (nnheader-header-value)))))
235       (when naked
236         (goto-char (point-min))
237         (delete-char 1)))))
238
239 (defun nnheader-insert-nov (header)
240   (princ (mail-header-number header) (current-buffer))
241   (insert 
242    "\t"
243    (or (mail-header-subject header) "(none)") "\t"
244    (or (mail-header-from header) "(nobody)") "\t"
245    (or (mail-header-date header) "") "\t"
246    (or (mail-header-id header) 
247        (nnmail-message-id)) "\t"
248    (or (mail-header-references header) "") "\t")
249   (princ (or (mail-header-chars header) 0) (current-buffer))
250   (insert "\t")
251   (princ (or (mail-header-lines header) 0) (current-buffer))
252   (insert "\t")
253   (when (mail-header-xref header) 
254     (insert "Xref: " (mail-header-xref header) "\t"))
255   (insert "\n"))
256
257 (defun nnheader-insert-article-line (article)
258   (goto-char (point-min))
259   (insert "220 ")
260   (princ article (current-buffer))
261   (insert " Article retrieved.\n")
262   (search-forward "\n\n" nil 'move)
263   (delete-region (point) (point-max))
264   (forward-char -1)
265   (insert "."))
266
267 ;; Various cruft the backends and Gnus need to communicate.
268
269 (defvar nntp-server-buffer nil)
270 (defvar gnus-verbose-backends 7
271   "*A number that says how talkative the Gnus backends should be.")
272 (defvar gnus-nov-is-evil nil
273   "If non-nil, Gnus backends will never output headers in the NOV format.")
274 (defvar news-reply-yank-from nil)
275 (defvar news-reply-yank-message-id nil)
276
277 (defvar nnheader-callback-function nil)
278
279 (defun nnheader-init-server-buffer ()
280   "Initialize the Gnus-backend communication buffer."
281   (save-excursion
282     (unless (gnus-buffer-live-p nntp-server-buffer)
283       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
284     (set-buffer nntp-server-buffer)
285     (buffer-disable-undo (current-buffer))
286     (erase-buffer)
287     (kill-all-local-variables)
288     (setq case-fold-search t)           ;Should ignore case.
289     t))
290
291 ;;; Various functions the backends use.
292
293 (defun nnheader-file-error (file)
294   "Return a string that says what is wrong with FILE."
295   (format
296    (cond
297     ((not (file-exists-p file))
298      "%s does not exist")
299     ((file-directory-p file)
300      "%s is a directory")
301     ((not (file-readable-p file))
302      "%s is not readable"))
303    file))
304
305 (defun nnheader-insert-head (file)
306   "Insert the head of the article."
307   (when (file-exists-p file)
308     (if (eq nnheader-max-head-length t)
309         ;; Just read the entire file.
310         (nnheader-insert-file-contents-literally file)
311       ;; Read 1K blocks until we find a separator.
312       (let ((beg 0)
313             format-alist 
314             (chop 1024))
315         (while (and (eq chop (nth 1 (insert-file-contents
316                                      file nil beg (incf beg chop))))
317                     (prog1 (not (search-forward "\n\n" nil t)) 
318                       (goto-char (point-max)))
319                     (or (null nnheader-max-head-length)
320                         (< beg nnheader-max-head-length))))))
321     t))
322
323 (defun nnheader-article-p ()
324   "Say whether the current buffer looks like an article."
325   (goto-char (point-min))
326   (if (not (search-forward "\n\n" nil t))
327       nil
328     (narrow-to-region (point-min) (1- (point)))
329     (goto-char (point-min))
330     (while (looking-at "[A-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
331       (goto-char (match-end 0)))
332     (prog1
333         (eobp)
334       (widen))))    
335
336 (defun nnheader-insert-references (references message-id)
337   "Insert a References header based on REFERENCES and MESSAGE-ID."
338   (if (and (not references) (not message-id)) 
339       ()        ; This is illegal, but not all articles have Message-IDs.
340     (mail-position-on-field "References")
341     (let ((begin (save-excursion (beginning-of-line) (point)))
342           (fill-column 78)
343           (fill-prefix "\t"))
344       (if references (insert references))
345       (if (and references message-id) (insert " "))
346       (if message-id (insert message-id))
347       ;; Fold long References lines to conform to RFC1036 (sort of).
348       ;; The region must end with a newline to fill the region
349       ;; without inserting extra newline.
350       (fill-region-as-paragraph begin (1+ (point))))))
351
352 (defun nnheader-replace-header (header new-value)
353   "Remove HEADER and insert the NEW-VALUE."
354   (save-excursion
355     (save-restriction
356       (nnheader-narrow-to-headers)
357       (prog1
358           (message-remove-header header)
359         (goto-char (point-max))
360         (insert header ": " new-value "\n")))))
361
362 (defun nnheader-narrow-to-headers ()
363   "Narrow to the head of an article."
364   (widen)
365   (narrow-to-region
366    (goto-char (point-min))
367    (if (search-forward "\n\n" nil t)
368        (1- (point))
369      (point-max)))
370   (goto-char (point-min)))
371
372 (defun nnheader-set-temp-buffer (name &optional noerase)
373   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
374   (set-buffer (get-buffer-create name))
375   (buffer-disable-undo (current-buffer))
376   (unless noerase
377     (erase-buffer))
378   (current-buffer))
379
380 (defmacro nnheader-temp-write (file &rest forms)
381   "Create a new buffer, evaluate FORM there, and write the buffer to FILE."
382   `(save-excursion
383      (let* ((nnheader-temp-file ,file)
384             (default-major-mode 'fundamental-mode)
385             (nnheader-temp-cur-buffer
386              (nnheader-set-temp-buffer
387               (generate-new-buffer-name " *nnheader temp*"))))
388        (when (and nnheader-temp-file 
389                   (not (file-directory-p (file-name-directory 
390                                           nnheader-temp-file))))
391          (make-directory (file-name-directory nnheader-temp-file) t))
392        (unwind-protect
393            (prog1
394                (progn
395                  ,@forms)
396              (when nnheader-temp-file
397                (set-buffer nnheader-temp-cur-buffer)
398                (write-region (point-min) (point-max) 
399                              nnheader-temp-file nil 'nomesg)))
400          (when (buffer-name nnheader-temp-cur-buffer)
401            (kill-buffer nnheader-temp-cur-buffer))))))
402
403 (put 'nnheader-temp-write 'lisp-indent-function 1)
404 (put 'nnheader-temp-write 'lisp-indent-hook 1)
405 (put 'nnheader-temp-write 'edebug-form-spec '(form body))
406
407 (defvar jka-compr-compression-info-list)
408 (defvar nnheader-numerical-files
409   (if (boundp 'jka-compr-compression-info-list)
410       (concat "\\([0-9]+\\)\\(" 
411               (mapconcat (lambda (i) (aref i 0))
412                          jka-compr-compression-info-list "\\|")
413               "\\)?")
414     "[0-9]+$")
415   "Regexp that match numerical files.")
416
417 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
418   "Regexp that matches numerical file names.")
419
420 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
421   "Regexp that matches numerical full file paths.")
422
423 (defsubst nnheader-file-to-number (file)
424   "Take a file name and return the article number."
425   (if (not (boundp 'jka-compr-compression-info-list))
426       (string-to-int file)
427     (string-match nnheader-numerical-short-files file)
428     (string-to-int (match-string 0 file))))
429
430 (defun nnheader-directory-files-safe (&rest args)
431   ;; It has been reported numerous times that `directory-files'
432   ;; fails with an alarming frequency on NFS mounted file systems.
433   ;; This function executes that function twice and returns 
434   ;; the longest result.
435   (let ((first (apply 'directory-files args))
436         (second (apply 'directory-files args)))
437     (if (> (length first) (length second))
438         first
439       second)))
440
441 (defun nnheader-directory-articles (dir)
442   "Return a list of all article files in a directory."
443   (mapcar 'nnheader-file-to-number
444           (nnheader-directory-files-safe
445            dir nil nnheader-numerical-short-files t)))
446
447 (defun nnheader-article-to-file-alist (dir)
448   "Return an alist of article/file pairs in DIR."
449   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
450           (nnheader-directory-files-safe
451            dir nil nnheader-numerical-short-files t)))
452
453 (defun nnheader-fold-continuation-lines ()
454   "Fold continuation lines in the current buffer."
455   (goto-char (point-min))
456   (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
457     (replace-match " " t t)))
458
459 (defun nnheader-translate-file-chars (file)
460   (if (null nnheader-file-name-translation-alist)
461       ;; No translation is necessary.
462       file 
463     ;; We translate -- but only the file name.  We leave the directory
464     ;; alone.
465     (let* ((i 0)
466            trans leaf path len)
467       (if (string-match "/[^/]+\\'" file)
468           ;; This is needed on NT's and stuff.
469           (setq leaf (substring file (1+ (match-beginning 0)))
470                 path (substring file 0 (1+ (match-beginning 0))))
471         ;; Fall back on this.
472         (setq leaf (file-name-nondirectory file)
473               path (file-name-directory file)))
474       (setq len (length leaf))
475       (while (< i len)
476         (when (setq trans (cdr (assq (aref leaf i)
477                                      nnheader-file-name-translation-alist)))
478           (aset leaf i trans))
479         (incf i))
480       (concat path leaf))))
481
482 (defun nnheader-report (backend &rest args)
483   "Report an error from the BACKEND.
484 The first string in ARGS can be a format string."
485   (set (intern (format "%s-status-string" backend))
486        (if (< (length args) 2)
487            (car args)
488          (apply 'format args)))
489   nil)
490
491 (defun nnheader-get-report (backend)
492   "Get the most recent report from BACKEND."
493   (condition-case ()
494       (message "%s" (symbol-value (intern (format "%s-status-string"
495                                                   backend))))
496     (error (message ""))))
497
498 (defun nnheader-insert (format &rest args)
499   "Clear the communicaton buffer and insert FORMAT and ARGS into the buffer.
500 If FORMAT isn't a format string, it and all ARGS will be inserted
501 without formatting."
502   (save-excursion
503     (set-buffer nntp-server-buffer)
504     (erase-buffer)
505     (if (string-match "%" format)
506         (insert (apply 'format format args))
507       (apply 'insert format args))
508     t))
509
510 (defun nnheader-mail-file-mbox-p (file)
511   "Say whether FILE looks like an Unix mbox file."
512   (when (and (file-exists-p file)
513              (file-readable-p file)
514              (file-regular-p file))
515     (save-excursion
516       (nnheader-set-temp-buffer " *mail-file-mbox-p*")
517       (nnheader-insert-file-contents-literally file)
518       (goto-char (point-min))
519       (prog1
520           (looking-at message-unix-mail-delimiter)
521         (kill-buffer (current-buffer))))))
522
523 (defun nnheader-replace-chars-in-string (string from to)
524   "Replace characters in STRING from FROM to TO."
525   (let ((string (substring string 0))   ;Copy string.
526         (len (length string))
527         (idx 0))
528     ;; Replace all occurrences of FROM with TO.
529     (while (< idx len)
530       (if (= (aref string idx) from)
531           (aset string idx to))
532       (setq idx (1+ idx)))
533     string))
534
535 (defun nnheader-file-to-group (file &optional top)
536   "Return a group name based on FILE and TOP."
537   (nnheader-replace-chars-in-string 
538    (if (not top)
539        file
540      (condition-case ()
541          (substring (expand-file-name file)
542                     (length 
543                      (expand-file-name
544                       (file-name-as-directory top))))
545        (error "")))
546    ?/ ?.))
547
548 (defun nnheader-message (level &rest args)
549   "Message if the Gnus backends are talkative."
550   (if (or (not (numberp gnus-verbose-backends))
551           (<= level gnus-verbose-backends))
552       (apply 'message args)
553     (apply 'format args)))
554
555 (defun nnheader-be-verbose (level)
556   "Return whether the backends should be verbose on LEVEL."
557   (or (not (numberp gnus-verbose-backends))
558       (<= level gnus-verbose-backends)))
559
560 (defun nnheader-group-pathname (group dir &optional file)
561   "Make pathname for GROUP."
562   (concat
563    (let ((dir (file-name-as-directory (expand-file-name dir))))
564      ;; If this directory exists, we use it directly.
565      (if (file-directory-p (concat dir group))
566          (concat dir group "/")
567        ;; If not, we translate dots into slashes.
568        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
569    (cond ((null file) "")
570          ((numberp file) (int-to-string file))
571          (t file))))
572
573 (defun nnheader-functionp (form)
574   "Return non-nil if FORM is funcallable."
575   (or (and (symbolp form) (fboundp form))
576       (and (listp form) (eq (car form) 'lambda))))
577
578 (defun nnheader-concat (dir file)
579   "Concat DIR as directory to FILE."
580   (concat (file-name-as-directory dir) file))
581
582 (defun nnheader-ms-strip-cr ()
583   "Strip ^M from the end of all lines."
584   (save-excursion
585     (goto-char (point-min))
586     (while (re-search-forward "\r$" nil t)
587       (delete-backward-char 1))))
588
589 (defun nnheader-file-size (file)
590   "Return the file size of FILE or 0."
591   (or (nth 7 (file-attributes file)) 0))
592
593 (defun nnheader-find-etc-directory (package)
594   "Go through the path and find the \".../etc/PACKAGE\" directory."
595   (let ((path load-path)
596         dir result)
597     ;; We try to find the dir by looking at the load path,
598     ;; stripping away the last component and adding "etc/".
599     (while path
600       (if (and (car path)
601                (file-exists-p
602                 (setq dir (concat
603                            (file-name-directory
604                             (directory-file-name (car path)))
605                            "etc/" package "/")))
606                (file-directory-p dir))
607           (setq result dir
608                 path nil)
609         (setq path (cdr path))))
610     result))
611
612 (defvar ange-ftp-path-format)
613 (defvar efs-path-regexp)
614 (defun nnheader-re-read-dir (path)
615   "Re-read directory PATH if PATH is on a remote system."
616     (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
617         (when (string-match efs-path-regexp path)
618           (efs-re-read-dir path))
619      (if (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
620       (when (string-match (car ange-ftp-path-format) path)
621         (ange-ftp-re-read-dir path)))))
622
623 (fset 'nnheader-run-at-time 'run-at-time)
624 (fset 'nnheader-cancel-timer 'cancel-timer)
625 (fset 'nnheader-cancel-function-timers 'cancel-function-timers)
626 (fset 'nnheader-find-file-noselect 'find-file-noselect)
627 (fset 'nnheader-insert-file-contents-literally
628       'insert-file-contents-literally)
629
630 (when (string-match "XEmacs\\|Lucid" emacs-version)
631   (require 'nnheaderxm))
632
633 (run-hooks 'nnheader-load-hook)
634
635 (provide 'nnheader)
636
637 ;;; nnheader.el ends here