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