Synch with `t-gnus-6_14' and Gnus.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; Nothing in this file depends on any other parts of Gnus -- all
29 ;; functions and macros in this file are utility functions that are
30 ;; used by Gnus and may be used by any other package without loading
31 ;; Gnus first.
32
33 ;;; Code:
34
35 (eval-when-compile (require 'cl))
36 (eval-when-compile (require 'static))
37
38 (require 'custom)
39 (require 'nnheader)
40 (require 'message)
41 (require 'time-date)
42
43 (eval-and-compile
44   (autoload 'rmail-insert-rmail-file-header "rmail")
45   (autoload 'rmail-count-new-messages "rmail")
46   (autoload 'rmail-show-message "rmail"))
47
48 (defun gnus-boundp (variable)
49   "Return non-nil if VARIABLE is bound and non-nil."
50   (and (boundp variable)
51        (symbol-value variable)))
52
53 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
54   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
55   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
56         (w (make-symbol "w"))
57         (buf (make-symbol "buf"))
58         (frame (make-symbol "frame")))
59     `(let* ((,tempvar (selected-window))
60             (,buf ,buffer)
61             (,w (get-buffer-window ,buf 'visible))
62             ,frame)
63        (unwind-protect
64            (progn
65              (if ,w
66                  (progn
67                    (select-window ,w)
68                    (set-buffer (window-buffer ,w)))
69                (pop-to-buffer ,buf))
70              ,@forms)
71          (setq ,frame (selected-frame))
72          (select-window ,tempvar)
73          (select-frame ,frame)))))
74
75 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
76 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
77
78 (defmacro gnus-intern-safe (string hashtable)
79   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
80   `(let ((symbol (intern ,string ,hashtable)))
81      (or (boundp symbol)
82          (set symbol nil))
83      symbol))
84
85 ;; Avoid byte-compile warning.
86 ;; In Mule, this function will be redefined to `truncate-string',
87 ;; which takes 3 or 4 args.
88 (defun gnus-truncate-string (str width &rest ignore)
89   (substring str 0 width))
90
91 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
92 ;; to limit the length of a string.  This function is necessary since
93 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
94 (defsubst gnus-limit-string (str width)
95   (if (> (length str) width)
96       (substring str 0 width)
97     str))
98
99 (defsubst gnus-functionp (form)
100   "Return non-nil if FORM is funcallable."
101   (or (and (symbolp form) (fboundp form))
102       (and (listp form) (eq (car form) 'lambda))
103       (byte-code-function-p form)))
104
105 (defsubst gnus-goto-char (point)
106   (and point (goto-char point)))
107
108 (defmacro gnus-buffer-exists-p (buffer)
109   `(let ((buffer ,buffer))
110      (when buffer
111        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
112                 buffer))))
113
114 (defmacro gnus-kill-buffer (buffer)
115   `(let ((buf ,buffer))
116      (when (gnus-buffer-exists-p buf)
117        (kill-buffer buf))))
118
119 (static-cond
120  ((fboundp 'point-at-bol)
121   (defalias 'gnus-point-at-bol 'point-at-bol))
122  ((fboundp 'line-beginning-position)
123   (defalias 'gnus-point-at-bol 'line-beginning-position))
124  (t
125   (defun gnus-point-at-bol ()
126     "Return point at the beginning of the line."
127     (let ((p (point)))
128       (beginning-of-line)
129       (prog1
130           (point)
131         (goto-char p))))
132   ))
133 (static-cond
134  ((fboundp 'point-at-eol)
135   (defalias 'gnus-point-at-eol 'point-at-eol))
136  ((fboundp 'line-end-position)
137   (defalias 'gnus-point-at-eol 'line-end-position))
138  (t
139   (defun gnus-point-at-eol ()
140     "Return point at the end of the line."
141     (let ((p (point)))
142       (end-of-line)
143       (prog1
144           (point)
145         (goto-char p))))
146   ))
147
148 (defun gnus-delete-first (elt list)
149   "Delete by side effect the first occurrence of ELT as a member of LIST."
150   (if (equal (car list) elt)
151       (cdr list)
152     (let ((total list))
153       (while (and (cdr list)
154                   (not (equal (cadr list) elt)))
155         (setq list (cdr list)))
156       (when (cdr list)
157         (setcdr list (cddr list)))
158       total)))
159
160 ;; Delete the current line (and the next N lines).
161 (defmacro gnus-delete-line (&optional n)
162   `(delete-region (progn (beginning-of-line) (point))
163                   (progn (forward-line ,(or n 1)) (point))))
164
165 (defun gnus-byte-code (func)
166   "Return a form that can be `eval'ed based on FUNC."
167   (let ((fval (indirect-function func)))
168     (if (byte-code-function-p fval)
169         (let ((flist (append fval nil)))
170           (setcar flist 'byte-code)
171           flist)
172       (cons 'progn (cddr fval)))))
173
174 (defun gnus-extract-address-components (from)
175   (let (name address)
176     ;; First find the address - the thing with the @ in it.  This may
177     ;; not be accurate in mail addresses, but does the trick most of
178     ;; the time in news messages.
179     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
180       (setq address (substring from (match-beginning 0) (match-end 0))))
181     ;; Then we check whether the "name <address>" format is used.
182     (and address
183          ;; Linear white space is not required.
184          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
185          (and (setq name (substring from 0 (match-beginning 0)))
186               ;; Strip any quotes from the name.
187               (string-match "\".*\"" name)
188               (setq name (substring name 1 (1- (match-end 0))))))
189     ;; If not, then "address (name)" is used.
190     (or name
191         (and (string-match "(.+)" from)
192              (setq name (substring from (1+ (match-beginning 0))
193                                    (1- (match-end 0)))))
194         (and (string-match "()" from)
195              (setq name address))
196         ;; XOVER might not support folded From headers.
197         (and (string-match "(.*" from)
198              (setq name (substring from (1+ (match-beginning 0))
199                                    (match-end 0)))))
200     (list (if (string= name "") nil name) (or address from))))
201
202
203 (defun gnus-fetch-field (field)
204   "Return the value of the header FIELD of current article."
205   (save-excursion
206     (save-restriction
207       (let ((case-fold-search t)
208             (inhibit-point-motion-hooks t))
209         (nnheader-narrow-to-headers)
210         (message-fetch-field field)))))
211
212 (defun gnus-goto-colon ()
213   (beginning-of-line)
214   (search-forward ":" (gnus-point-at-eol) t))
215
216 (defun gnus-remove-text-with-property (prop)
217   "Delete all text in the current buffer with text property PROP."
218   (save-excursion
219     (goto-char (point-min))
220     (while (not (eobp))
221       (while (get-text-property (point) prop)
222         (delete-char 1))
223       (goto-char (next-single-property-change (point) prop nil (point-max))))))
224
225 (defun gnus-newsgroup-directory-form (newsgroup)
226   "Make hierarchical directory name from NEWSGROUP name."
227   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
228         (len (length newsgroup))
229         idx)
230     ;; If this is a foreign group, we don't want to translate the
231     ;; entire name.
232     (if (setq idx (string-match ":" newsgroup))
233         (aset newsgroup idx ?/)
234       (setq idx 0))
235     ;; Replace all occurrences of `.' with `/'.
236     (while (< idx len)
237       (when (= (aref newsgroup idx) ?.)
238         (aset newsgroup idx ?/))
239       (setq idx (1+ idx)))
240     newsgroup))
241
242 (defun gnus-newsgroup-savable-name (group)
243   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
244   ;; with dots.
245   (nnheader-replace-chars-in-string group ?/ ?.))
246
247 (defun gnus-string> (s1 s2)
248   (not (or (string< s1 s2)
249            (string= s1 s2))))
250
251 ;;; Time functions.
252
253 (defun gnus-file-newer-than (file date)
254   (let ((fdate (nth 5 (file-attributes file))))
255     (or (> (car fdate) (car date))
256         (and (= (car fdate) (car date))
257              (> (nth 1 fdate) (nth 1 date))))))
258
259 ;;; Keymap macros.
260
261 (defmacro gnus-local-set-keys (&rest plist)
262   "Set the keys in PLIST in the current keymap."
263   `(gnus-define-keys-1 (current-local-map) ',plist))
264
265 (defmacro gnus-define-keys (keymap &rest plist)
266   "Define all keys in PLIST in KEYMAP."
267   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
268
269 (defmacro gnus-define-keys-safe (keymap &rest plist)
270   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
271   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
272
273 (put 'gnus-define-keys 'lisp-indent-function 1)
274 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
275 (put 'gnus-local-set-keys 'lisp-indent-function 1)
276
277 (defmacro gnus-define-keymap (keymap &rest plist)
278   "Define all keys in PLIST in KEYMAP."
279   `(gnus-define-keys-1 ,keymap (quote ,plist)))
280
281 (put 'gnus-define-keymap 'lisp-indent-function 1)
282
283 (defun gnus-define-keys-1 (keymap plist &optional safe)
284   (when (null keymap)
285     (error "Can't set keys in a null keymap"))
286   (cond ((symbolp keymap)
287          (setq keymap (symbol-value keymap)))
288         ((keymapp keymap))
289         ((listp keymap)
290          (set (car keymap) nil)
291          (define-prefix-command (car keymap))
292          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
293          (setq keymap (symbol-value (car keymap)))))
294   (let (key)
295     (while plist
296       (when (symbolp (setq key (pop plist)))
297         (setq key (symbol-value key)))
298       (if (or (not safe)
299               (eq (lookup-key keymap key) 'undefined))
300           (define-key keymap key (pop plist))
301         (pop plist)))))
302
303 (defun gnus-completing-read (default prompt &rest args)
304   ;; Like `completing-read', except that DEFAULT is the default argument.
305   (let* ((prompt (if default
306                      (concat prompt " (default " default ") ")
307                    (concat prompt " ")))
308          (answer (apply 'completing-read prompt args)))
309     (if (or (null answer) (zerop (length answer)))
310         default
311       answer)))
312
313 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
314 ;; the echo area.
315 (defun gnus-y-or-n-p (prompt)
316   (prog1
317       (y-or-n-p prompt)
318     (message "")))
319
320 (defun gnus-yes-or-no-p (prompt)
321   (prog1
322       (yes-or-no-p prompt)
323     (message "")))
324
325 (defun gnus-dd-mmm (messy-date)
326   "Return a string like DD-MMM from a big messy string."
327   (condition-case ()
328       (format-time-string "%d-%b" (safe-date-to-time messy-date))
329     (error "  -   ")))
330
331 (defmacro gnus-date-get-time (date)
332   "Convert DATE string to Emacs time.
333 Cache the result as a text property stored in DATE."
334   ;; Either return the cached value...
335   `(let ((d ,date))
336      (if (equal "" d)
337          '(0 0)
338        (or (get-text-property 0 'gnus-time d)
339            ;; or compute the value...
340            (let ((time (safe-date-to-time d)))
341              ;; and store it back in the string.
342              (put-text-property 0 1 'gnus-time time d)
343              time)))))
344
345 (defsubst gnus-time-iso8601 (time)
346   "Return a string of TIME in YYYYMMDDTHHMMSS format."
347   (format-time-string "%Y%m%dT%H%M%S" time))
348
349 (defun gnus-date-iso8601 (date)
350   "Convert the DATE to YYYYMMDDTHHMMSS."
351   (condition-case ()
352       (gnus-time-iso8601 (gnus-date-get-time date))
353     (error "")))
354
355 (defun gnus-mode-string-quote (string)
356   "Quote all \"%\"'s in STRING."
357   (save-excursion
358     (gnus-set-work-buffer)
359     (insert string)
360     (goto-char (point-min))
361     (while (search-forward "%" nil t)
362       (insert "%"))
363     (buffer-string)))
364
365 ;; Make a hash table (default and minimum size is 256).
366 ;; Optional argument HASHSIZE specifies the table size.
367 (defun gnus-make-hashtable (&optional hashsize)
368   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
369
370 ;; Make a number that is suitable for hashing; bigger than MIN and
371 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
372 ;; hardware modulo operation, so they implement it in software.  On
373 ;; many sparcs over 50% of the time to intern is spent in the modulo.
374 ;; Yes, it's slower than actually computing the hash from the string!
375 ;; So we use powers of 2 so people can optimize the modulo to a mask.
376 (defun gnus-create-hash-size (min)
377   (let ((i 1))
378     (while (< i min)
379       (setq i (* 2 i)))
380     i))
381
382 (defcustom gnus-verbose 7
383   "*Integer that says how verbose Gnus should be.
384 The higher the number, the more messages Gnus will flash to say what
385 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
386 display most important messages; and at ten, Gnus will keep on
387 jabbering all the time."
388   :group 'gnus-start
389   :type 'integer)
390
391 ;; Show message if message has a lower level than `gnus-verbose'.
392 ;; Guideline for numbers:
393 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
394 ;; for things that take a long time, 7 - not very important messages
395 ;; on stuff, 9 - messages inside loops.
396 (defun gnus-message (level &rest args)
397   (if (<= level gnus-verbose)
398       (apply 'message args)
399     ;; We have to do this format thingy here even if the result isn't
400     ;; shown - the return value has to be the same as the return value
401     ;; from `message'.
402     (apply 'format args)))
403
404 (defun gnus-error (level &rest args)
405   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
406   (when (<= (floor level) gnus-verbose)
407     (apply 'message args)
408     (ding)
409     (let (duration)
410       (when (and (floatp level)
411                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
412         (sit-for duration))))
413   nil)
414
415 (defun gnus-split-references (references)
416   "Return a list of Message-IDs in REFERENCES."
417   (let ((beg 0)
418         ids)
419     (while (string-match "<[^>]+>" references beg)
420       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
421             ids))
422     (nreverse ids)))
423
424 (defsubst gnus-parent-id (references &optional n)
425   "Return the last Message-ID in REFERENCES.
426 If N, return the Nth ancestor instead."
427   (when references
428     (let ((ids (inline (gnus-split-references references))))
429       (while (nthcdr (or n 1) ids)
430         (setq ids (cdr ids)))
431       (car ids))))
432
433 (defsubst gnus-buffer-live-p (buffer)
434   "Say whether BUFFER is alive or not."
435   (and buffer
436        (get-buffer buffer)
437        (buffer-name (get-buffer buffer))))
438
439 (defun gnus-horizontal-recenter ()
440   "Recenter the current buffer horizontally."
441   (if (< (current-column) (/ (window-width) 2))
442       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
443     (let* ((orig (point))
444            (end (window-end (get-buffer-window (current-buffer) t)))
445            (max 0))
446       (when end
447         ;; Find the longest line currently displayed in the window.
448         (goto-char (window-start))
449         (while (and (not (eobp))
450                     (< (point) end))
451           (end-of-line)
452           (setq max (max max (current-column)))
453           (forward-line 1))
454         (goto-char orig)
455         ;; Scroll horizontally to center (sort of) the point.
456         (if (> max (window-width))
457             (set-window-hscroll
458              (get-buffer-window (current-buffer) t)
459              (min (- (current-column) (/ (window-width) 3))
460                   (+ 2 (- max (window-width)))))
461           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
462         max))))
463
464 (defun gnus-read-event-char ()
465   "Get the next event."
466   (let ((event (read-event)))
467     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
468     (cons (and (numberp event) event) event)))
469
470 (defun gnus-sortable-date (date)
471   "Make string suitable for sorting from DATE."
472   (gnus-time-iso8601 (date-to-time date)))
473
474 (defun gnus-copy-file (file &optional to)
475   "Copy FILE to TO."
476   (interactive
477    (list (read-file-name "Copy file: " default-directory)
478          (read-file-name "Copy file to: " default-directory)))
479   (unless to
480     (setq to (read-file-name "Copy file to: " default-directory)))
481   (when (file-directory-p to)
482     (setq to (concat (file-name-as-directory to)
483                      (file-name-nondirectory file))))
484   (copy-file file to))
485
486 (defun gnus-kill-all-overlays ()
487   "Delete all overlays in the current buffer."
488   (let* ((overlayss (overlay-lists))
489          (buffer-read-only nil)
490          (overlays (delq nil (nconc (car overlayss) (cdr overlayss)))))
491     (while overlays
492       (delete-overlay (pop overlays)))))
493
494 (defvar gnus-work-buffer " *gnus work*")
495
496 (defun gnus-set-work-buffer ()
497   "Put point in the empty Gnus work buffer."
498   (if (get-buffer gnus-work-buffer)
499       (progn
500         (set-buffer gnus-work-buffer)
501         (erase-buffer))
502     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
503     (kill-all-local-variables)))
504
505 (defmacro gnus-group-real-name (group)
506   "Find the real name of a foreign newsgroup."
507   `(let ((gname ,group))
508      (if (string-match "^[^:]+:" gname)
509          (substring gname (match-end 0))
510        gname)))
511
512 (defun gnus-make-sort-function (funs)
513   "Return a composite sort condition based on the functions in FUNC."
514   (cond
515    ;; Just a simple function.
516    ((gnus-functionp funs) funs)
517    ;; No functions at all.
518    ((null funs) funs)
519    ;; A list of functions.
520    ((or (cdr funs)
521         (listp (car funs)))
522     `(lambda (t1 t2)
523        ,(gnus-make-sort-function-1 (reverse funs))))
524    ;; A list containing just one function.
525    (t
526     (car funs))))
527
528 (defun gnus-make-sort-function-1 (funs)
529   "Return a composite sort condition based on the functions in FUNC."
530   (let ((function (car funs))
531         (first 't1)
532         (last 't2))
533     (when (consp function)
534       (cond
535        ;; Reversed spec.
536        ((eq (car function) 'not)
537         (setq function (cadr function)
538               first 't2
539               last 't1))
540        ((gnus-functionp function)
541         ;; Do nothing.
542         )
543        (t
544         (error "Invalid sort spec: %s" function))))
545     (if (cdr funs)
546         `(or (,function ,first ,last)
547              (and (not (,function ,last ,first))
548                   ,(gnus-make-sort-function-1 (cdr funs))))
549       `(,function ,first ,last))))
550
551 (defun gnus-turn-off-edit-menu (type)
552   "Turn off edit menu in `gnus-TYPE-mode-map'."
553   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
554     [menu-bar edit] 'undefined))
555
556 (defun gnus-prin1 (form)
557   "Use `prin1' on FORM in the current buffer.
558 Bind `print-quoted' and `print-readably' to t while printing."
559   (let ((print-quoted t)
560         (print-readably t)
561         (print-escape-multibyte nil)
562         print-level print-length)
563     (prin1 form (current-buffer))))
564
565 (defun gnus-prin1-to-string (form)
566   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
567   (let ((print-quoted t)
568         (print-readably t))
569     (prin1-to-string form)))
570
571 (defun gnus-make-directory (directory)
572   "Make DIRECTORY (and all its parents) if it doesn't exist."
573   (let ((file-name-coding-system nnmail-pathname-coding-system)
574         (pathname-coding-system nnmail-pathname-coding-system))
575     (when (and directory
576                (not (file-exists-p directory)))
577       (make-directory directory t)))
578   t)
579
580 (defun gnus-write-buffer (file)
581   "Write the current buffer's contents to FILE."
582   ;; Make sure the directory exists.
583   (gnus-make-directory (file-name-directory file))
584   (let ((file-name-coding-system nnmail-pathname-coding-system)
585         (pathname-coding-system nnmail-pathname-coding-system))
586     ;; Write the buffer.
587     (write-region (point-min) (point-max) file nil 'quietly)))
588
589 (defun gnus-write-buffer-as-binary (file)
590   "Write the current buffer's contents to FILE without code conversion."
591   ;; Make sure the directory exists.
592   (gnus-make-directory (file-name-directory file))
593   ;; Write the buffer.
594   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
595
596 (defun gnus-write-buffer-as-coding-system (coding-system file)
597   "Write the current buffer's contents to FILE with code conversion."
598   ;; Make sure the directory exists.
599   (gnus-make-directory (file-name-directory file))
600   ;; Write the buffer.
601   (write-region-as-coding-system
602    coding-system (point-min) (point-max) file nil 'quietly))
603
604 (defun gnus-delete-file (file)
605   "Delete FILE if it exists."
606   (when (file-exists-p file)
607     (delete-file file)))
608
609 (defun gnus-strip-whitespace (string)
610   "Return STRING stripped of all whitespace."
611   (while (string-match "[\r\n\t ]+" string)
612     (setq string (replace-match "" t t string)))
613   string)
614
615 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
616   "The same as `put-text-property', but don't put this prop on any newlines in the region."
617   (save-match-data
618     (save-excursion
619       (save-restriction
620         (goto-char beg)
621         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
622           (gnus-put-text-property beg (match-beginning 0) prop val)
623           (setq beg (point)))
624         (gnus-put-text-property beg (point) prop val)))))
625
626 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
627                                                                    prop val)
628   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
629   (let ((b beg))
630     (while (/= b end)
631       (when (get-text-property b 'gnus-face)
632         (setq b (next-single-property-change b 'gnus-face nil end)))
633       (when (/= b end)
634         (gnus-put-text-property
635          b (setq b (next-single-property-change b 'gnus-face nil end))
636          prop val)))))
637
638 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
639 ;;; The primary idea here is to try to protect internal datastructures
640 ;;; from becoming corrupted when the user hits C-g, or if a hook or
641 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
642 ;;; updated at the same time, or information can be lost.
643
644 (defvar gnus-atomic-be-safe t
645   "If t, certain operations will be protected from interruption by C-g.")
646
647 (defmacro gnus-atomic-progn (&rest forms)
648   "Evaluate FORMS atomically, which means to protect the evaluation
649 from being interrupted by the user.  An error from the forms themselves
650 will return without finishing the operation.  Since interrupts from
651 the user are disabled, it is recommended that only the most minimal
652 operations are performed by FORMS.  If you wish to assign many
653 complicated values atomically, compute the results into temporary
654 variables and then do only the assignment atomically."
655   `(let ((inhibit-quit gnus-atomic-be-safe))
656      ,@forms))
657
658 (put 'gnus-atomic-progn 'lisp-indent-function 0)
659
660 (defmacro gnus-atomic-progn-assign (protect &rest forms)
661   "Evaluate FORMS, but insure that the variables listed in PROTECT
662 are not changed if anything in FORMS signals an error or otherwise
663 non-locally exits.  The variables listed in PROTECT are updated atomically.
664 It is safe to use gnus-atomic-progn-assign with long computations.
665
666 Note that if any of the symbols in PROTECT were unbound, they will be
667 set to nil on a sucessful assignment.  In case of an error or other
668 non-local exit, it will still be unbound."
669   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
670                                                   (concat (symbol-name x)
671                                                           "-tmp"))
672                                                  x))
673                                protect))
674          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
675                                temp-sym-map))
676          (temp-sym-let (mapcar (lambda (x) (list (car x)
677                                                  `(and (boundp ',(cadr x))
678                                                        ,(cadr x))))
679                                temp-sym-map))
680          (sym-temp-let sym-temp-map)
681          (temp-sym-assign (apply 'append temp-sym-map))
682          (sym-temp-assign (apply 'append sym-temp-map))
683          (result (make-symbol "result-tmp")))
684     `(let (,@temp-sym-let
685            ,result)
686        (let ,sym-temp-let
687          (setq ,result (progn ,@forms))
688          (setq ,@temp-sym-assign))
689        (let ((inhibit-quit gnus-atomic-be-safe))
690          (setq ,@sym-temp-assign))
691        ,result)))
692
693 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
694 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
695
696 (defmacro gnus-atomic-setq (&rest pairs)
697   "Similar to setq, except that the real symbols are only assigned when
698 there are no errors.  And when the real symbols are assigned, they are
699 done so atomically.  If other variables might be changed via side-effect,
700 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
701 with potentially long computations."
702   (let ((tpairs pairs)
703         syms)
704     (while tpairs
705       (push (car tpairs) syms)
706       (setq tpairs (cddr tpairs)))
707     `(gnus-atomic-progn-assign ,syms
708        (setq ,@pairs))))
709
710 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
711
712
713 ;;; Functions for saving to babyl/mail files.
714
715 (defvar rmail-default-rmail-file)
716 (defun gnus-output-to-rmail (filename &optional ask)
717   "Append the current article to an Rmail file named FILENAME."
718   (require 'rmail)
719   ;; Most of these codes are borrowed from rmailout.el.
720   (setq filename (expand-file-name filename))
721   (setq rmail-default-rmail-file filename)
722   (let ((artbuf (current-buffer))
723         (tmpbuf (get-buffer-create " *Gnus-output*")))
724     (save-excursion
725       (or (get-file-buffer filename)
726           (file-exists-p filename)
727           (if (or (not ask)
728                   (gnus-yes-or-no-p
729                    (concat "\"" filename "\" does not exist, create it? ")))
730               (let ((file-buffer (create-file-buffer filename)))
731                 (save-excursion
732                   (set-buffer file-buffer)
733                   (rmail-insert-rmail-file-header)
734                   (let ((require-final-newline nil))
735                     (gnus-write-buffer-as-coding-system
736                      nnheader-text-coding-system filename)))
737                 (kill-buffer file-buffer))
738             (error "Output file does not exist")))
739       (set-buffer tmpbuf)
740       (erase-buffer)
741       (insert-buffer-substring artbuf)
742       (gnus-convert-article-to-rmail)
743       ;; Decide whether to append to a file or to an Emacs buffer.
744       (let ((outbuf (get-file-buffer filename)))
745         (if (not outbuf)
746             (write-region-as-binary (point-min) (point-max) filename 'append)
747           ;; File has been visited, in buffer OUTBUF.
748           (set-buffer outbuf)
749           (let ((buffer-read-only nil)
750                 (msg (and (boundp 'rmail-current-message)
751                           (symbol-value 'rmail-current-message))))
752             ;; If MSG is non-nil, buffer is in RMAIL mode.
753             (when msg
754               (widen)
755               (narrow-to-region (point-max) (point-max)))
756             (insert-buffer-substring tmpbuf)
757             (when msg
758               (goto-char (point-min))
759               (widen)
760               (search-backward "\n\^_")
761               (narrow-to-region (point) (point-max))
762               (rmail-count-new-messages t)
763               (when (rmail-summary-exists)
764                 (rmail-select-summary
765                  (rmail-update-summary)))
766               (rmail-count-new-messages t)
767               (rmail-show-message msg))
768             (save-buffer)))))
769     (kill-buffer tmpbuf)))
770
771 (defun gnus-output-to-mail (filename &optional ask)
772   "Append the current article to a mail file named FILENAME."
773   (setq filename (expand-file-name filename))
774   (let ((artbuf (current-buffer))
775         (tmpbuf (get-buffer-create " *Gnus-output*")))
776     (save-excursion
777       ;; Create the file, if it doesn't exist.
778       (when (and (not (get-file-buffer filename))
779                  (not (file-exists-p filename)))
780         (if (or (not ask)
781                 (gnus-y-or-n-p
782                  (concat "\"" filename "\" does not exist, create it? ")))
783             (let ((file-buffer (create-file-buffer filename)))
784               (save-excursion
785                 (set-buffer file-buffer)
786                 (let ((require-final-newline nil))
787                   (gnus-write-buffer-as-coding-system
788                    nnheader-text-coding-system filename)))
789               (kill-buffer file-buffer))
790           (error "Output file does not exist")))
791       (set-buffer tmpbuf)
792       (erase-buffer)
793       (insert-buffer-substring artbuf)
794       (goto-char (point-min))
795       (if (looking-at "From ")
796           (forward-line 1)
797         (insert "From nobody " (current-time-string) "\n"))
798       (let (case-fold-search)
799         (while (re-search-forward "^From " nil t)
800           (beginning-of-line)
801           (insert ">")))
802       ;; Decide whether to append to a file or to an Emacs buffer.
803       (let ((outbuf (get-file-buffer filename)))
804         (if (not outbuf)
805             (let ((buffer-read-only nil))
806               (save-excursion
807                 (goto-char (point-max))
808                 (forward-char -2)
809                 (unless (looking-at "\n\n")
810                   (goto-char (point-max))
811                   (unless (bolp)
812                     (insert "\n"))
813                   (insert "\n"))
814                 (goto-char (point-max))
815                 (write-region-as-binary (point-min) (point-max)
816                                         filename 'append)))
817           ;; File has been visited, in buffer OUTBUF.
818           (set-buffer outbuf)
819           (let ((buffer-read-only nil))
820             (goto-char (point-max))
821             (unless (eobp)
822               (insert "\n"))
823             (insert "\n")
824             (insert-buffer-substring tmpbuf)))))
825     (kill-buffer tmpbuf)))
826
827 (defun gnus-convert-article-to-rmail ()
828   "Convert article in current buffer to Rmail message format."
829   (let ((buffer-read-only nil))
830     ;; Convert article directly into Babyl format.
831     (goto-char (point-min))
832     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
833     (while (search-forward "\n\^_" nil t) ;single char
834       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
835     (goto-char (point-max))
836     (insert "\^_")))
837
838 (defun gnus-map-function (funs arg)
839   "Applies the result of the first function in FUNS to the second, and so on.
840 ARG is passed to the first function."
841   (let ((myfuns funs))
842     (while myfuns
843       (setq arg (funcall (pop myfuns) arg)))
844     arg))
845
846 (defun gnus-run-hooks (&rest funcs)
847   "Does the same as `run-hooks', but saves excursion."
848   (let ((buf (current-buffer)))
849     (unwind-protect
850         (apply 'run-hooks funcs)
851       (set-buffer buf))))
852
853 ;;;
854 ;;; .netrc and .authinforc parsing
855 ;;;
856
857 (defun gnus-parse-netrc (file)
858   "Parse FILE and return an list of all entries in the file."
859   (when (file-exists-p file)
860     (with-temp-buffer
861       (let ((tokens '("machine" "default" "login"
862                       "password" "account" "macdef" "force"
863                       "port"))
864             alist elem result pair)
865         (insert-file-contents file)
866         (goto-char (point-min))
867         ;; Go through the file, line by line.
868         (while (not (eobp))
869           (narrow-to-region (point) (gnus-point-at-eol))
870           ;; For each line, get the tokens and values.
871           (while (not (eobp))
872             (skip-chars-forward "\t ")
873             ;; Skip lines that begin with a "#".
874             (if (eq (char-after) ?#)
875                 (goto-char (point-max))
876               (unless (eobp)
877                 (setq elem
878                       (if (= (following-char) ?\")
879                           (read (current-buffer))
880                         (buffer-substring
881                          (point) (progn (skip-chars-forward "^\t ")
882                                         (point)))))
883                 (cond
884                  ((equal elem "macdef")
885                   ;; We skip past the macro definition.
886                   (widen)
887                   (while (and (zerop (forward-line 1))
888                               (looking-at "$")))
889                   (narrow-to-region (point) (point)))
890                  ((member elem tokens)
891                   ;; Tokens that don't have a following value are ignored,
892                   ;; except "default".
893                   (when (and pair (or (cdr pair)
894                                       (equal (car pair) "default")))
895                     (push pair alist))
896                   (setq pair (list elem)))
897                  (t
898                   ;; Values that haven't got a preceding token are ignored.
899                   (when pair
900                     (setcdr pair elem)
901                     (push pair alist)
902                     (setq pair nil)))))))
903           (when alist
904             (push (nreverse alist) result))
905           (setq alist nil
906                 pair nil)
907           (widen)
908           (forward-line 1))
909         (nreverse result)))))
910
911 (defun gnus-netrc-machine (list machine &optional port defaultport)
912   "Return the netrc values from LIST for MACHINE or for the default entry.
913 If PORT specified, only return entries with matching port tokens.
914 Entries without port tokens default to DEFAULTPORT."
915   (let ((rest list)
916         result)
917     (while list
918       (when (equal (cdr (assoc "machine" (car list))) machine)
919         (push (car list) result))
920       (pop list))
921     (unless result
922       ;; No machine name matches, so we look for default entries.
923       (while rest
924         (when (assoc "default" (car rest))
925           (push (car rest) result))
926         (pop rest)))
927     (when result
928       (setq result (nreverse result))
929       (while (and result
930                   (not (equal (or port defaultport "nntp")
931                               (or (gnus-netrc-get (car result) "port")
932                                   defaultport "nntp"))))
933         (pop result))
934       (car result))))
935
936 (defun gnus-netrc-get (alist type)
937   "Return the value of token TYPE from ALIST."
938   (cdr (assoc type alist)))
939
940 ;;; Various
941
942 (defvar gnus-group-buffer)              ; Compiler directive
943 (defun gnus-alive-p ()
944   "Say whether Gnus is running or not."
945   (and (boundp 'gnus-group-buffer)
946        (get-buffer gnus-group-buffer)
947        (save-excursion
948          (set-buffer gnus-group-buffer)
949          (eq major-mode 'gnus-group-mode))))
950
951 (defun gnus-remove-duplicates (list)
952   (let (new (tail list))
953     (while tail
954       (or (member (car tail) new)
955           (setq new (cons (car tail) new)))
956       (setq tail (cdr tail)))
957     (nreverse new)))
958
959 (defun gnus-delete-if (predicate list)
960   "Delete elements from LIST that satisfy PREDICATE."
961   (let (out)
962     (while list
963       (unless (funcall predicate (car list))
964         (push (car list) out))
965       (pop list))
966     (nreverse out)))
967
968 (defun gnus-delete-alist (key alist)
969   "Delete all entries in ALIST that have a key eq to KEY."
970   (let (entry)
971     (while (setq entry (assq key alist))
972       (setq alist (delq entry alist)))
973     alist))
974
975 (defmacro gnus-pull (key alist &optional assoc-p)
976   "Modify ALIST to be without KEY."
977   (unless (symbolp alist)
978     (error "Not a symbol: %s" alist))
979   (let ((fun (if assoc-p 'assoc 'assq)))
980     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
981
982 (defun gnus-globalify-regexp (re)
983   "Returns a regexp that matches a whole line, iff RE matches a part of it."
984   (concat (unless (string-match "^\\^" re) "^.*")
985           re
986           (unless (string-match "\\$$" re) ".*$")))
987
988 (defun gnus-set-window-start (&optional point)
989   "Set the window start to POINT, or (point) if nil."
990   (let ((win (get-buffer-window (current-buffer) t)))
991     (when win
992       (set-window-start win (or point (point))))))
993
994 (defun gnus-annotation-in-region-p (b e)
995   (if (= b e)
996       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
997     (text-property-any b e 'gnus-undeletable t)))
998
999 (defun gnus-or (&rest elems)
1000   "Return non-nil if any of the elements are non-nil."
1001   (catch 'found
1002     (while elems
1003       (when (pop elems)
1004         (throw 'found t)))))
1005
1006 (defun gnus-and (&rest elems)
1007   "Return non-nil if all of the elements are non-nil."
1008   (catch 'found
1009     (while elems
1010       (unless (pop elems)
1011         (throw 'found nil)))
1012     t))
1013
1014 (defun gnus-write-active-file (file hashtb &optional full-names)
1015   (let ((output-coding-system nnmail-active-file-coding-system)
1016         (coding-system-for-write nnmail-active-file-coding-system))
1017     (with-temp-file file
1018       (mapatoms
1019        (lambda (sym)
1020          (when (and sym
1021                     (boundp sym)
1022                     (symbol-value sym))
1023            (insert (format "%S %d %d y\n"
1024                            (if full-names
1025                                sym
1026                              (intern (gnus-group-real-name (symbol-name sym))))
1027                            (or (cdr (symbol-value sym))
1028                                (car (symbol-value sym)))
1029                            (car (symbol-value sym))))))
1030        hashtb)
1031       (goto-char (point-max))
1032       (while (search-backward "\\." nil t)
1033         (delete-char 1)))))
1034
1035 (provide 'gnus-util)
1036
1037 ;;; gnus-util.el ends here