1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;; Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; This file is part of GNU Emacs.
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)
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.
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.
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; used by Gnus and may be used by any other package without loading
37 ;; Fixme: this should be a gnus variable, not nnmail-.
38 (defvar nnmail-pathname-coding-system))
44 (autoload 'message-fetch-field "message")
45 (autoload 'gnus-get-buffer-window "gnus-win")
46 (autoload 'rmail-insert-rmail-file-header "rmail")
47 (autoload 'rmail-count-new-messages "rmail")
48 (autoload 'rmail-show-message "rmail"))
52 ((fboundp 'replace-in-string)
53 (defalias 'gnus-replace-in-string 'replace-in-string))
54 ((fboundp 'replace-regexp-in-string)
55 (defun gnus-replace-in-string (string regexp newtext &optional literal)
56 (replace-regexp-in-string regexp newtext string nil literal)))
58 (defun gnus-replace-in-string (string regexp newtext &optional literal)
60 (while (string-match regexp string start)
61 (setq tail (- (length string) (match-end 0)))
62 (setq string (replace-match newtext nil literal string))
63 (setq start (- (length string) tail))))
66 ;;; bring in the netrc functions as aliases
67 (defalias 'gnus-netrc-get 'netrc-get)
68 (defalias 'gnus-netrc-machine 'netrc-machine)
69 (defalias 'gnus-parse-netrc 'netrc-parse)
71 (defun gnus-boundp (variable)
72 "Return non-nil if VARIABLE is bound and non-nil."
73 (and (boundp variable)
74 (symbol-value variable)))
76 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
77 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
78 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
80 (buf (make-symbol "buf")))
81 `(let* ((,tempvar (selected-window))
83 (,w (gnus-get-buffer-window ,buf 'visible)))
89 (set-buffer (window-buffer ,w)))
92 (select-window ,tempvar)))))
94 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
95 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
97 (defmacro gnus-intern-safe (string hashtable)
98 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
99 `(let ((symbol (intern ,string ,hashtable)))
104 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
105 ;; to limit the length of a string. This function is necessary since
106 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
107 (defsubst gnus-limit-string (str width)
108 (if (> (length str) width)
109 (substring str 0 width)
112 (defsubst gnus-functionp (form)
113 "Return non-nil if FORM is funcallable."
114 (or (and (symbolp form) (fboundp form))
115 (and (listp form) (eq (car form) 'lambda))
116 (byte-code-function-p form)))
118 (defsubst gnus-goto-char (point)
119 (and point (goto-char point)))
121 (defmacro gnus-buffer-exists-p (buffer)
122 `(let ((buffer ,buffer))
124 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
127 (defalias 'gnus-point-at-bol
128 (if (fboundp 'point-at-bol)
130 'line-beginning-position))
132 (defalias 'gnus-point-at-eol
133 (if (fboundp 'point-at-eol)
137 (defun gnus-delete-first (elt list)
138 "Delete by side effect the first occurrence of ELT as a member of LIST."
139 (if (equal (car list) elt)
142 (while (and (cdr list)
143 (not (equal (cadr list) elt)))
144 (setq list (cdr list)))
146 (setcdr list (cddr list)))
149 ;; Delete the current line (and the next N lines).
150 (defmacro gnus-delete-line (&optional n)
151 `(delete-region (gnus-point-at-bol)
152 (progn (forward-line ,(or n 1)) (point))))
154 (defun gnus-byte-code (func)
155 "Return a form that can be `eval'ed based on FUNC."
156 (let ((fval (indirect-function func)))
157 (if (byte-code-function-p fval)
158 (let ((flist (append fval nil)))
159 (setcar flist 'byte-code)
161 (cons 'progn (cddr fval)))))
163 (defun gnus-extract-address-components (from)
165 ;; First find the address - the thing with the @ in it. This may
166 ;; not be accurate in mail addresses, but does the trick most of
167 ;; the time in news messages.
168 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
169 (setq address (substring from (match-beginning 0) (match-end 0))))
170 ;; Then we check whether the "name <address>" format is used.
172 ;; Linear white space is not required.
173 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
174 (and (setq name (substring from 0 (match-beginning 0)))
175 ;; Strip any quotes from the name.
176 (string-match "^\".*\"$" name)
177 (setq name (substring name 1 (1- (match-end 0))))))
178 ;; If not, then "address (name)" is used.
180 (and (string-match "(.+)" from)
181 (setq name (substring from (1+ (match-beginning 0))
182 (1- (match-end 0)))))
183 (and (string-match "()" from)
185 ;; XOVER might not support folded From headers.
186 (and (string-match "(.*" from)
187 (setq name (substring from (1+ (match-beginning 0))
189 (list (if (string= name "") nil name) (or address from))))
192 (defun gnus-fetch-field (field)
193 "Return the value of the header FIELD of current article."
196 (let ((case-fold-search t)
197 (inhibit-point-motion-hooks t))
198 (nnheader-narrow-to-headers)
199 (message-fetch-field field)))))
201 (defun gnus-fetch-original-field (field)
202 "Fetch FIELD from the original version of the current article."
203 (with-current-buffer gnus-original-article-buffer
204 (gnus-fetch-field field)))
207 (defun gnus-goto-colon ()
209 (let ((eol (gnus-point-at-eol)))
210 (goto-char (or (text-property-any (point) eol 'gnus-position t)
211 (search-forward ":" eol t)
214 (defun gnus-decode-newsgroups (newsgroups group &optional method)
215 (let ((method (or method (gnus-find-method-for-group group))))
216 (mapconcat (lambda (group)
217 (gnus-group-name-decode group (gnus-group-name-charset
219 (message-tokenize-header newsgroups)
222 (defun gnus-remove-text-with-property (prop)
223 "Delete all text in the current buffer with text property PROP."
225 (goto-char (point-min))
227 (while (get-text-property (point) prop)
229 (goto-char (next-single-property-change (point) prop nil (point-max))))))
232 (defun gnus-newsgroup-directory-form (newsgroup)
233 "Make hierarchical directory name from NEWSGROUP name."
234 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
235 (idx (string-match ":" newsgroup)))
237 (if idx (substring newsgroup 0 idx))
239 (nnheader-replace-chars-in-string
240 (if idx (substring newsgroup (1+ idx)) newsgroup)
243 (defun gnus-newsgroup-savable-name (group)
244 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
246 (nnheader-replace-chars-in-string group ?/ ?.))
248 (defun gnus-string> (s1 s2)
249 (not (or (string< s1 s2)
254 (defun gnus-file-newer-than (file date)
255 (let ((fdate (nth 5 (file-attributes file))))
256 (or (> (car fdate) (car date))
257 (and (= (car fdate) (car date))
258 (> (nth 1 fdate) (nth 1 date))))))
262 (defmacro gnus-local-set-keys (&rest plist)
263 "Set the keys in PLIST in the current keymap."
264 `(gnus-define-keys-1 (current-local-map) ',plist))
266 (defmacro gnus-define-keys (keymap &rest plist)
267 "Define all keys in PLIST in KEYMAP."
268 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
270 (defmacro gnus-define-keys-safe (keymap &rest plist)
271 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
272 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
274 (put 'gnus-define-keys 'lisp-indent-function 1)
275 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
276 (put 'gnus-local-set-keys 'lisp-indent-function 1)
278 (defmacro gnus-define-keymap (keymap &rest plist)
279 "Define all keys in PLIST in KEYMAP."
280 `(gnus-define-keys-1 ,keymap (quote ,plist)))
282 (put 'gnus-define-keymap 'lisp-indent-function 1)
284 (defun gnus-define-keys-1 (keymap plist &optional safe)
286 (error "Can't set keys in a null keymap"))
287 (cond ((symbolp keymap)
288 (setq keymap (symbol-value keymap)))
291 (set (car keymap) nil)
292 (define-prefix-command (car keymap))
293 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
294 (setq keymap (symbol-value (car keymap)))))
297 (when (symbolp (setq key (pop plist)))
298 (setq key (symbol-value key)))
300 (eq (lookup-key keymap key) 'undefined))
301 (define-key keymap key (pop plist))
304 (defun gnus-completing-read-with-default (default prompt &rest args)
305 ;; Like `completing-read', except that DEFAULT is the default argument.
306 (let* ((prompt (if default
307 (concat prompt " (default " default ") ")
308 (concat prompt " ")))
309 (answer (apply 'completing-read prompt args)))
310 (if (or (null answer) (zerop (length answer)))
314 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
316 (defun gnus-y-or-n-p (prompt)
321 (defun gnus-yes-or-no-p (prompt)
326 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
327 ;; age-depending date representations. (e.g. just the time if it's
328 ;; from today, the day of the week if it's within the last 7 days and
329 ;; the full date if it's older)
330 (defun gnus-seconds-today ()
331 "Returns the number of seconds passed today"
332 (let ((now (decode-time (current-time))))
333 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
335 (defun gnus-seconds-month ()
336 "Returns the number of seconds passed this month"
337 (let ((now (decode-time (current-time))))
338 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
339 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
341 (defun gnus-seconds-year ()
342 "Returns the number of seconds passed this year"
343 (let ((now (decode-time (current-time)))
344 (days (format-time-string "%j" (current-time))))
345 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
346 (* (- (string-to-number days) 1) 3600 24))))
348 (defvar gnus-user-date-format-alist
349 '(((gnus-seconds-today) . "%k:%M")
350 (604800 . "%a %k:%M") ;;that's one week
351 ((gnus-seconds-month) . "%a %d")
352 ((gnus-seconds-year) . "%b %d")
353 (t . "%b %d '%y")) ;;this one is used when no
355 "Specifies date format depending on age of article.
356 This is an alist of items (AGE . FORMAT). AGE can be a number (of
357 seconds) or a Lisp expression evaluating to a number. When the age of
358 the article is less than this number, then use `format-time-string'
359 with the corresponding FORMAT for displaying the date of the article.
360 If AGE is not a number or a Lisp expression evaluating to a
361 non-number, then the corresponding FORMAT is used as a default value.
363 Note that the list is processed from the beginning, so it should be
364 sorted by ascending AGE. Also note that items following the first
365 non-number AGE will be ignored.
367 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
368 and `gnus-seconds-year' in the AGE spec. They return the number of
369 seconds passed since the start of today, of this month, of this year,
372 (defun gnus-user-date (messy-date)
373 "Format the messy-date acording to gnus-user-date-format-alist.
374 Returns \" ? \" if there's bad input or if an other error occurs.
375 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
377 (let* ((messy-date (safe-date-to-time messy-date))
379 ;;If we don't find something suitable we'll use this one
380 (my-format "%b %m '%y")
381 (high (lsh (- (car now) (car messy-date)) 16)))
382 (if (and (> high -1) (= (logand high 65535) 0))
383 ;;overflow and bad input
384 (let* ((difference (+ high (- (car (cdr now))
385 (car (cdr messy-date)))))
386 (templist gnus-user-date-format-alist)
387 (top (eval (caar templist))))
388 (while (if (numberp top) (< top difference) (not top))
390 (setq templist (cdr templist))
391 (setq top (eval (caar templist)))))
392 (if (stringp (cdr (car templist)))
393 (setq my-format (cdr (car templist))))))
394 (format-time-string (eval my-format) messy-date))
396 ;;end of Frank's code
398 (defun gnus-dd-mmm (messy-date)
399 "Return a string like DD-MMM from a big messy string."
401 (format-time-string "%d-%b" (safe-date-to-time messy-date))
404 (defmacro gnus-date-get-time (date)
405 "Convert DATE string to Emacs time.
406 Cache the result as a text property stored in DATE."
407 ;; Either return the cached value...
411 (or (get-text-property 0 'gnus-time d)
412 ;; or compute the value...
413 (let ((time (safe-date-to-time d)))
414 ;; and store it back in the string.
415 (put-text-property 0 1 'gnus-time time d)
418 (defsubst gnus-time-iso8601 (time)
419 "Return a string of TIME in YYYYMMDDTHHMMSS format."
420 (format-time-string "%Y%m%dT%H%M%S" time))
422 (defun gnus-date-iso8601 (date)
423 "Convert the DATE to YYYYMMDDTHHMMSS."
425 (gnus-time-iso8601 (gnus-date-get-time date))
428 (defun gnus-mode-string-quote (string)
429 "Quote all \"%\"'s in STRING."
430 (gnus-replace-in-string string "%" "%%"))
432 ;; Make a hash table (default and minimum size is 256).
433 ;; Optional argument HASHSIZE specifies the table size.
434 (defun gnus-make-hashtable (&optional hashsize)
435 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
437 ;; Make a number that is suitable for hashing; bigger than MIN and
438 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
439 ;; hardware modulo operation, so they implement it in software. On
440 ;; many sparcs over 50% of the time to intern is spent in the modulo.
441 ;; Yes, it's slower than actually computing the hash from the string!
442 ;; So we use powers of 2 so people can optimize the modulo to a mask.
443 (defun gnus-create-hash-size (min)
449 (defcustom gnus-verbose 7
450 "*Integer that says how verbose Gnus should be.
451 The higher the number, the more messages Gnus will flash to say what
452 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
453 display most important messages; and at ten, Gnus will keep on
454 jabbering all the time."
458 ;; Show message if message has a lower level than `gnus-verbose'.
459 ;; Guideline for numbers:
460 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
461 ;; for things that take a long time, 7 - not very important messages
462 ;; on stuff, 9 - messages inside loops.
463 (defun gnus-message (level &rest args)
464 (if (<= level gnus-verbose)
465 (apply 'message args)
466 ;; We have to do this format thingy here even if the result isn't
467 ;; shown - the return value has to be the same as the return value
469 (apply 'format args)))
471 (defun gnus-error (level &rest args)
472 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
473 (when (<= (floor level) gnus-verbose)
474 (apply 'message args)
477 (when (and (floatp level)
478 (not (zerop (setq duration (* 10 (- level (floor level)))))))
479 (sit-for duration))))
482 (defun gnus-split-references (references)
483 "Return a list of Message-IDs in REFERENCES."
486 (while (string-match "<[^<]+[^< \t]" references beg)
487 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
491 (defsubst gnus-parent-id (references &optional n)
492 "Return the last Message-ID in REFERENCES.
493 If N, return the Nth ancestor instead."
494 (when (and references
495 (not (zerop (length references))))
497 (let ((ids (inline (gnus-split-references references))))
498 (while (nthcdr n ids)
499 (setq ids (cdr ids)))
501 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
502 (match-string 1 references)))))
504 (defun gnus-buffer-live-p (buffer)
505 "Say whether BUFFER is alive or not."
508 (buffer-name (get-buffer buffer))))
510 (defun gnus-horizontal-recenter ()
511 "Recenter the current buffer horizontally."
512 (if (< (current-column) (/ (window-width) 2))
513 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
514 (let* ((orig (point))
515 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
518 ;; Find the longest line currently displayed in the window.
519 (goto-char (window-start))
520 (while (and (not (eobp))
523 (setq max (max max (current-column)))
526 ;; Scroll horizontally to center (sort of) the point.
527 (if (> max (window-width))
529 (gnus-get-buffer-window (current-buffer) t)
530 (min (- (current-column) (/ (window-width) 3))
531 (+ 2 (- max (window-width)))))
532 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
535 (defun gnus-read-event-char (&optional prompt)
536 "Get the next event."
537 (let ((event (read-event prompt)))
538 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
539 (cons (and (numberp event) event) event)))
541 (defun gnus-sortable-date (date)
542 "Make string suitable for sorting from DATE."
543 (gnus-time-iso8601 (date-to-time date)))
545 (defun gnus-copy-file (file &optional to)
548 (list (read-file-name "Copy file: " default-directory)
549 (read-file-name "Copy file to: " default-directory)))
551 (setq to (read-file-name "Copy file to: " default-directory)))
552 (when (file-directory-p to)
553 (setq to (concat (file-name-as-directory to)
554 (file-name-nondirectory file))))
557 (defvar gnus-work-buffer " *gnus work*")
559 (defun gnus-set-work-buffer ()
560 "Put point in the empty Gnus work buffer."
561 (if (get-buffer gnus-work-buffer)
563 (set-buffer gnus-work-buffer)
565 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
566 (kill-all-local-variables)
567 (mm-enable-multibyte)))
569 (defmacro gnus-group-real-name (group)
570 "Find the real name of a foreign newsgroup."
571 `(let ((gname ,group))
572 (if (string-match "^[^:]+:" gname)
573 (substring gname (match-end 0))
576 (defun gnus-make-sort-function (funs)
577 "Return a composite sort condition based on the functions in FUNC."
579 ;; Just a simple function.
580 ((gnus-functionp funs) funs)
581 ;; No functions at all.
583 ;; A list of functions.
588 ,(gnus-make-sort-function-1 (reverse funs)))))
589 ;; A list containing just one function.
593 (defun gnus-make-sort-function-1 (funs)
594 "Return a composite sort condition based on the functions in FUNC."
595 (let ((function (car funs))
598 (when (consp function)
601 ((eq (car function) 'not)
602 (setq function (cadr function)
605 ((gnus-functionp function)
609 (error "Invalid sort spec: %s" function))))
611 `(or (,function ,first ,last)
612 (and (not (,function ,last ,first))
613 ,(gnus-make-sort-function-1 (cdr funs))))
614 `(,function ,first ,last))))
616 (defun gnus-turn-off-edit-menu (type)
617 "Turn off edit menu in `gnus-TYPE-mode-map'."
618 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
619 [menu-bar edit] 'undefined))
621 (defun gnus-prin1 (form)
622 "Use `prin1' on FORM in the current buffer.
623 Bind `print-quoted' and `print-readably' to t while printing."
624 (let ((print-quoted t)
626 (print-escape-multibyte nil)
627 print-level print-length)
628 (prin1 form (current-buffer))))
630 (defun gnus-prin1-to-string (form)
631 "The same as `prin1'.
632 Bind `print-quoted' and `print-readably' to t, and `print-length'
633 and `print-level' to nil."
634 (let ((print-quoted t)
638 (prin1-to-string form)))
640 (defun gnus-make-directory (directory)
641 "Make DIRECTORY (and all its parents) if it doesn't exist."
643 (let ((file-name-coding-system nnmail-pathname-coding-system))
645 (not (file-exists-p directory)))
646 (make-directory directory t)))
649 (defun gnus-write-buffer (file)
650 "Write the current buffer's contents to FILE."
651 ;; Make sure the directory exists.
652 (gnus-make-directory (file-name-directory file))
653 (let ((file-name-coding-system nnmail-pathname-coding-system))
655 (write-region (point-min) (point-max) file nil 'quietly)))
657 (defun gnus-delete-file (file)
658 "Delete FILE if it exists."
659 (when (file-exists-p file)
662 (defun gnus-strip-whitespace (string)
663 "Return STRING stripped of all whitespace."
664 (while (string-match "[\r\n\t ]+" string)
665 (setq string (replace-match "" t t string)))
668 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
669 "The same as `put-text-property', but don't put this prop on any newlines in the region."
674 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
675 (gnus-put-text-property beg (match-beginning 0) prop val)
677 (gnus-put-text-property beg (point) prop val)))))
679 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
680 "The same as `put-text-property', but don't put this prop on any newlines in the region."
685 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
687 (gnus-make-overlay beg (match-beginning 0))
690 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
692 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
694 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
697 (when (get-text-property b 'gnus-face)
698 (setq b (next-single-property-change b 'gnus-face nil end)))
701 (gnus-put-text-property
702 b (setq b (next-single-property-change b 'gnus-face nil end))
705 (defmacro gnus-faces-at (position)
706 "Return a list of faces at POSITION."
707 (if (featurep 'xemacs)
708 `(let ((pos ,position))
709 (mapcar-extents 'extent-face
710 nil (current-buffer) pos pos nil 'face))
711 `(let ((pos ,position))
712 (delq nil (cons (get-text-property pos 'face)
715 (overlay-get overlay 'face))
716 (overlays-at pos)))))))
718 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
719 ;;; The primary idea here is to try to protect internal datastructures
720 ;;; from becoming corrupted when the user hits C-g, or if a hook or
721 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
722 ;;; updated at the same time, or information can be lost.
724 (defvar gnus-atomic-be-safe t
725 "If t, certain operations will be protected from interruption by C-g.")
727 (defmacro gnus-atomic-progn (&rest forms)
728 "Evaluate FORMS atomically, which means to protect the evaluation
729 from being interrupted by the user. An error from the forms themselves
730 will return without finishing the operation. Since interrupts from
731 the user are disabled, it is recommended that only the most minimal
732 operations are performed by FORMS. If you wish to assign many
733 complicated values atomically, compute the results into temporary
734 variables and then do only the assignment atomically."
735 `(let ((inhibit-quit gnus-atomic-be-safe))
738 (put 'gnus-atomic-progn 'lisp-indent-function 0)
740 (defmacro gnus-atomic-progn-assign (protect &rest forms)
741 "Evaluate FORMS, but insure that the variables listed in PROTECT
742 are not changed if anything in FORMS signals an error or otherwise
743 non-locally exits. The variables listed in PROTECT are updated atomically.
744 It is safe to use gnus-atomic-progn-assign with long computations.
746 Note that if any of the symbols in PROTECT were unbound, they will be
747 set to nil on a successful assignment. In case of an error or other
748 non-local exit, it will still be unbound."
749 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
750 (concat (symbol-name x)
754 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
756 (temp-sym-let (mapcar (lambda (x) (list (car x)
757 `(and (boundp ',(cadr x))
760 (sym-temp-let sym-temp-map)
761 (temp-sym-assign (apply 'append temp-sym-map))
762 (sym-temp-assign (apply 'append sym-temp-map))
763 (result (make-symbol "result-tmp")))
764 `(let (,@temp-sym-let
767 (setq ,result (progn ,@forms))
768 (setq ,@temp-sym-assign))
769 (let ((inhibit-quit gnus-atomic-be-safe))
770 (setq ,@sym-temp-assign))
773 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
774 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
776 (defmacro gnus-atomic-setq (&rest pairs)
777 "Similar to setq, except that the real symbols are only assigned when
778 there are no errors. And when the real symbols are assigned, they are
779 done so atomically. If other variables might be changed via side-effect,
780 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
781 with potentially long computations."
785 (push (car tpairs) syms)
786 (setq tpairs (cddr tpairs)))
787 `(gnus-atomic-progn-assign ,syms
790 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
793 ;;; Functions for saving to babyl/mail files.
795 (defvar rmail-default-rmail-file)
796 (defun gnus-output-to-rmail (filename &optional ask)
797 "Append the current article to an Rmail file named FILENAME."
799 ;; Most of these codes are borrowed from rmailout.el.
800 (setq filename (expand-file-name filename))
801 (setq rmail-default-rmail-file filename)
802 (let ((artbuf (current-buffer))
803 (tmpbuf (get-buffer-create " *Gnus-output*")))
805 (or (get-file-buffer filename)
806 (file-exists-p filename)
809 (concat "\"" filename "\" does not exist, create it? ")))
810 (let ((file-buffer (create-file-buffer filename)))
812 (set-buffer file-buffer)
813 (rmail-insert-rmail-file-header)
814 (let ((require-final-newline nil)
815 (coding-system-for-write mm-text-coding-system))
816 (gnus-write-buffer filename)))
817 (kill-buffer file-buffer))
818 (error "Output file does not exist")))
821 (insert-buffer-substring artbuf)
822 (gnus-convert-article-to-rmail)
823 ;; Decide whether to append to a file or to an Emacs buffer.
824 (let ((outbuf (get-file-buffer filename)))
826 (let ((file-name-coding-system nnmail-pathname-coding-system))
827 (mm-append-to-file (point-min) (point-max) filename))
828 ;; File has been visited, in buffer OUTBUF.
830 (let ((buffer-read-only nil)
831 (msg (and (boundp 'rmail-current-message)
832 (symbol-value 'rmail-current-message))))
833 ;; If MSG is non-nil, buffer is in RMAIL mode.
836 (narrow-to-region (point-max) (point-max)))
837 (insert-buffer-substring tmpbuf)
839 (goto-char (point-min))
841 (search-backward "\n\^_")
842 (narrow-to-region (point) (point-max))
843 (rmail-count-new-messages t)
844 (when (rmail-summary-exists)
845 (rmail-select-summary
846 (rmail-update-summary)))
847 (rmail-count-new-messages t)
848 (rmail-show-message msg))
850 (kill-buffer tmpbuf)))
852 (defun gnus-output-to-mail (filename &optional ask)
853 "Append the current article to a mail file named FILENAME."
854 (setq filename (expand-file-name filename))
855 (let ((artbuf (current-buffer))
856 (tmpbuf (get-buffer-create " *Gnus-output*")))
858 ;; Create the file, if it doesn't exist.
859 (when (and (not (get-file-buffer filename))
860 (not (file-exists-p filename)))
863 (concat "\"" filename "\" does not exist, create it? ")))
864 (let ((file-buffer (create-file-buffer filename)))
866 (set-buffer file-buffer)
867 (let ((require-final-newline nil)
868 (coding-system-for-write mm-text-coding-system))
869 (gnus-write-buffer filename)))
870 (kill-buffer file-buffer))
871 (error "Output file does not exist")))
874 (insert-buffer-substring artbuf)
875 (goto-char (point-min))
876 (if (looking-at "From ")
878 (insert "From nobody " (current-time-string) "\n"))
879 (let (case-fold-search)
880 (while (re-search-forward "^From " nil t)
883 ;; Decide whether to append to a file or to an Emacs buffer.
884 (let ((outbuf (get-file-buffer filename)))
886 (let ((buffer-read-only nil))
888 (goto-char (point-max))
890 (unless (looking-at "\n\n")
891 (goto-char (point-max))
895 (goto-char (point-max))
896 (let ((file-name-coding-system nnmail-pathname-coding-system))
897 (mm-append-to-file (point-min) (point-max) filename))))
898 ;; File has been visited, in buffer OUTBUF.
900 (let ((buffer-read-only nil))
901 (goto-char (point-max))
905 (insert-buffer-substring tmpbuf)))))
906 (kill-buffer tmpbuf)))
908 (defun gnus-convert-article-to-rmail ()
909 "Convert article in current buffer to Rmail message format."
910 (let ((buffer-read-only nil))
911 ;; Convert article directly into Babyl format.
912 (goto-char (point-min))
913 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
914 (while (search-forward "\n\^_" nil t) ;single char
915 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
916 (goto-char (point-max))
919 (defun gnus-map-function (funs arg)
920 "Applies the result of the first function in FUNS to the second, and so on.
921 ARG is passed to the first function."
923 (setq arg (funcall (pop funs) arg)))
926 (defun gnus-run-hooks (&rest funcs)
927 "Does the same as `run-hooks', but saves the current buffer."
929 (apply 'run-hooks funcs)))
933 (defvar gnus-group-buffer) ; Compiler directive
934 (defun gnus-alive-p ()
935 "Say whether Gnus is running or not."
936 (and (boundp 'gnus-group-buffer)
937 (get-buffer gnus-group-buffer)
939 (set-buffer gnus-group-buffer)
940 (eq major-mode 'gnus-group-mode))))
942 (defun gnus-remove-duplicates (list)
945 (or (member (car list) new)
946 (setq new (cons (car list) new)))
947 (setq list (cdr list)))
950 (defun gnus-remove-if (predicate list)
951 "Return a copy of LIST with all items satisfying PREDICATE removed."
954 (unless (funcall predicate (car list))
955 (push (car list) out))
956 (setq list (cdr list)))
959 (if (fboundp 'assq-delete-all)
960 (defalias 'gnus-delete-alist 'assq-delete-all)
961 (defun gnus-delete-alist (key alist)
962 "Delete from ALIST all elements whose car is KEY.
963 Return the modified alist."
965 (while (setq entry (assq key alist))
966 (setq alist (delq entry alist)))
969 (defmacro gnus-pull (key alist &optional assoc-p)
970 "Modify ALIST to be without KEY."
971 (unless (symbolp alist)
972 (error "Not a symbol: %s" alist))
973 (let ((fun (if assoc-p 'assoc 'assq)))
974 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
976 (defun gnus-globalify-regexp (re)
977 "Returns a regexp that matches a whole line, iff RE matches a part of it."
978 (concat (unless (string-match "^\\^" re) "^.*")
980 (unless (string-match "\\$$" re) ".*$")))
982 (defun gnus-set-window-start (&optional point)
983 "Set the window start to POINT, or (point) if nil."
984 (let ((win (gnus-get-buffer-window (current-buffer) t)))
986 (set-window-start win (or point (point))))))
988 (defun gnus-annotation-in-region-p (b e)
990 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
991 (text-property-any b e 'gnus-undeletable t)))
993 (defun gnus-or (&rest elems)
994 "Return non-nil if any of the elements are non-nil."
1000 (defun gnus-and (&rest elems)
1001 "Return non-nil if all of the elements are non-nil."
1005 (throw 'found nil)))
1008 (defun gnus-write-active-file (file hashtb &optional full-names)
1009 (let ((coding-system-for-write nnmail-active-file-coding-system))
1010 (with-temp-file file
1016 (insert (format "%S %d %d y\n"
1019 (intern (gnus-group-real-name (symbol-name sym))))
1020 (or (cdr (symbol-value sym))
1021 (car (symbol-value sym)))
1022 (car (symbol-value sym))))))
1024 (goto-char (point-max))
1025 (while (search-backward "\\." nil t)
1028 (defmacro gnus-with-output-to-file (file &rest body)
1029 (let ((buffer (make-symbol "output-buffer"))
1030 (size (make-symbol "output-buffer-size"))
1031 (leng (make-symbol "output-buffer-length")))
1032 `(let* ((print-quoted t)
1034 (print-escape-multibyte nil)
1038 (,buffer (make-string ,size 0))
1041 (standard-output (lambda (c)
1042 (aset ,buffer ,leng c)
1043 (if (= ,size (setq ,leng (1+ ,leng)))
1044 (progn (write-region ,buffer nil ,file append 'no-msg)
1049 (write-region (substring ,buffer 0 ,leng) nil ,file append 'no-msg)))))
1051 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1052 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1054 (if (fboundp 'union)
1055 (defalias 'gnus-union 'union)
1056 (defun gnus-union (l1 l2)
1057 "Set union of lists L1 and L2."
1058 (cond ((null l1) l2)
1062 (or (>= (length l1) (length l2))
1063 (setq l1 (prog1 l2 (setq l2 l1))))
1065 (or (member (car l2) l1)
1070 (defun gnus-add-text-properties-when
1071 (property value start end properties &optional object)
1072 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1075 (< start end) ;; XEmacs will loop for every when start=end.
1076 (setq point (text-property-not-all start end property value)))
1077 (gnus-add-text-properties start point properties object)
1078 (setq start (text-property-any point end property value)))
1080 (gnus-add-text-properties start end properties object))))
1082 (defun gnus-remove-text-properties-when
1083 (property value start end properties &optional object)
1084 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1088 (setq point (text-property-not-all start end property value)))
1089 (remove-text-properties start point properties object)
1090 (setq start (text-property-any point end property value)))
1092 (remove-text-properties start end properties object))
1095 (defun gnus-string-equal (x y)
1096 "Like `string-equal', except it compares case-insensitively."
1097 (and (= (length x) (length y))
1098 (or (string-equal x y)
1099 (string-equal (downcase x) (downcase y)))))
1101 (defcustom gnus-use-byte-compile t
1102 "If non-nil, byte-compile crucial run-time codes.
1103 Setting it to nil has no effect after first time running
1104 `gnus-byte-compile'."
1107 :group 'gnus-various)
1109 (defun gnus-byte-compile (form)
1110 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1111 (if gnus-use-byte-compile
1114 ;; Work around a bug in XEmacs 21.4
1115 (require 'byte-optimize)
1118 (defalias 'gnus-byte-compile 'byte-compile)
1119 (byte-compile form))
1122 (defun gnus-remassoc (key alist)
1123 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1124 The modified LIST is returned. If the first member
1125 of LIST has a car that is `equal' to KEY, there is no way to remove it
1126 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1127 sure of changing the value of `foo'."
1129 (if (equal key (caar alist))
1131 (setcdr alist (gnus-remassoc key (cdr alist)))
1134 (defun gnus-update-alist-soft (key value alist)
1136 (cons (cons key value) (gnus-remassoc key alist))
1137 (gnus-remassoc key alist)))
1139 (defun gnus-create-info-command (node)
1140 "Create a command that will go to info NODE."
1143 ,(concat "Enter the info system at node " node)
1144 (Info-goto-node ,node)
1145 (setq gnus-info-buffer (current-buffer))
1146 (gnus-configure-windows 'info)))
1148 (defun gnus-not-ignore (&rest args)
1151 (defvar gnus-directory-sep-char-regexp "/"
1152 "The regexp of directory separator character.
1153 If you find some problem with the directory separator character, try
1154 \"[/\\\\\]\" for some systems.")
1156 (defun gnus-url-unhex (x)
1163 (defun gnus-url-unhex-string (str &optional allow-newlines)
1164 "Remove %XXX embedded spaces, etc in a url.
1165 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1166 decoding of carriage returns and line feeds in the string, which is normally
1167 forbidden in URL encoding."
1168 (setq str (or (mm-subst-char-in-string ?+ ? str) ""))
1170 (case-fold-search t))
1171 (while (string-match "%[0-9a-f][0-9a-f]" str)
1172 (let* ((start (match-beginning 0))
1173 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1175 (gnus-url-unhex (elt str (+ start 2))))))
1177 tmp (substring str 0 start)
1180 (char-to-string code))
1181 ((or (= code ?\n) (= code ?\r))
1183 (t (char-to-string code))))
1184 str (substring str (match-end 0)))))
1185 (setq tmp (concat tmp str))
1188 (defun gnus-make-predicate (spec)
1189 "Transform SPEC into a function that can be called.
1190 SPEC is a predicate specifier that contains stuff like `or', `and',
1191 `not', lists and functions. The functions all take one parameter."
1192 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1194 (defun gnus-make-predicate-1 (spec)
1199 (if (memq (car spec) '(or and not))
1200 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1201 (error "Invalid predicate specifier: %s" spec)))))
1203 (defun gnus-local-map-property (map)
1204 "Return a list suitable for a text property list specifying keymap MAP."
1208 ((>= emacs-major-version 21)
1211 (list 'local-map map))))
1213 (defun gnus-completing-read (prompt table &optional predicate require-match
1216 (not (boundp history)))
1219 (if (symbol-value history)
1220 (concat prompt " (" (car (symbol-value history)) "): ")
1221 (concat prompt ": "))
1227 (car (symbol-value history))))
1229 (defun gnus-graphic-display-p ()
1230 (or (and (fboundp 'display-graphic-p)
1231 (display-graphic-p))
1232 ;;;!!!This is bogus. Fixme!
1233 (and (featurep 'xemacs)
1236 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1237 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1239 (defmacro gnus-parse-without-error (&rest body)
1240 "Allow continuing onto the next line even if an error occurs."
1241 `(while (not (eobp))
1245 (goto-char (point-max)))
1247 (gnus-error 4 "Invalid data on line %d"
1248 (count-lines (point-min) (point)))
1249 (forward-line 1)))))
1251 (defun gnus-cache-file-contents (file variable function)
1252 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1253 (let ((time (nth 5 (file-attributes file)))
1255 (if (or (null (setq value (symbol-value variable)))
1256 (not (equal (car value) file))
1257 (not (equal (nth 1 value) time)))
1259 (setq contents (funcall function file))
1260 (set variable (list file time contents))
1264 (defun gnus-multiple-choice (prompt choice &optional idx)
1265 "Ask user a multiple choice question.
1266 CHOICE is a list of the choice char and help message at IDX."
1268 (save-window-excursion
1271 (message "%s (%s): "
1273 (mapconcat (lambda (s) (char-to-string (car s)))
1275 (setq tchar (read-char))
1276 (when (not (assq tchar choice))
1278 (setq buf (get-buffer-create "*Gnus Help*"))
1280 (fundamental-mode) ; for Emacs 20.4+
1281 (buffer-disable-undo)
1283 (insert prompt ":\n\n")
1290 ;; find the longest string to display
1292 (setq n (length (nth idx (car list))))
1295 (setq list (cdr list)))
1296 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1297 (setq n (/ (1- (window-width)) max)) ; items per line
1298 (setq width (/ (1- (window-width)) n)) ; width of each item
1299 ;; insert `n' items, each in a field of width `width'
1304 (delete-char -1) ; the `\n' takes a char
1306 (setq pad (- width 3))
1307 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1308 (insert (format format (caar alist) (nth idx (car alist))))
1309 (setq alist (cdr alist))
1310 (setq i (1+ i))))))))
1311 (if (buffer-live-p buf)
1315 (defun gnus-select-frame-set-input-focus (frame)
1316 "Select FRAME, raise it, and set input focus, if possible."
1317 (cond ((featurep 'xemacs)
1319 (select-frame frame)
1320 (focus-frame frame))
1321 ;; The function `select-frame-set-input-focus' won't set
1322 ;; the input focus under Emacs 21.2 and X window system.
1323 ;;((fboundp 'select-frame-set-input-focus)
1324 ;; (defalias 'gnus-select-frame-set-input-focus
1325 ;; 'select-frame-set-input-focus)
1326 ;; (select-frame-set-input-focus frame))
1329 (select-frame frame)
1330 (cond ((and (eq window-system 'x)
1331 (fboundp 'x-focus-frame))
1332 (x-focus-frame frame))
1333 ((eq window-system 'w32)
1334 (w32-focus-frame frame)))
1335 (when focus-follows-mouse
1336 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1338 (defun gnus-frame-or-window-display-name (object)
1339 "Given a frame or window, return the associated display name.
1340 Return nil otherwise."
1341 (if (featurep 'xemacs)
1342 (device-connection (dfw-device object))
1343 (if (or (framep object)
1344 (and (windowp object)
1345 (setq object (window-frame object))))
1346 (let ((display (frame-parameter object 'display)))
1347 (if (and (stringp display)
1348 ;; Exclude invalid display names.
1349 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1353 (provide 'gnus-util)
1355 ;;; gnus-util.el ends here