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