1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;; Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
9 ;; This file is part of GNU Emacs.
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)
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.
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.
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
37 ;; Fixme: this should be a gnus variable, not nnmail-.
38 (defvar nnmail-pathname-coding-system))
39 (eval-when-compile (require 'static))
46 (autoload 'message-fetch-field "message")
47 (autoload 'gnus-get-buffer-window "gnus-win")
48 (autoload 'rmail-insert-rmail-file-header "rmail")
49 (autoload 'rmail-count-new-messages "rmail")
50 (autoload 'rmail-show-message "rmail"))
54 ((fboundp 'replace-in-string)
55 (defalias 'gnus-replace-in-string 'replace-in-string))
56 ((fboundp 'replace-regexp-in-string)
57 (defun gnus-replace-in-string (string regexp newtext &optional literal)
58 (replace-regexp-in-string regexp newtext string nil literal)))
60 (defun gnus-replace-in-string (string regexp newtext &optional literal)
62 (while (string-match regexp string start)
63 (setq tail (- (length string) (match-end 0)))
64 (setq string (replace-match newtext nil literal string))
65 (setq start (- (length string) tail))))
68 (defun gnus-boundp (variable)
69 "Return non-nil if VARIABLE is bound and non-nil."
70 (and (boundp variable)
71 (symbol-value variable)))
73 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
74 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
75 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
77 (buf (make-symbol "buf"))
78 (frame (make-symbol "frame")))
79 `(let* ((,tempvar (selected-window))
81 (,w (gnus-get-buffer-window ,buf 'visible))
88 (set-buffer (window-buffer ,w)))
91 (setq ,frame (selected-frame))
92 (select-window ,tempvar)
93 (select-frame ,frame)))))
95 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
96 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
98 (defmacro gnus-intern-safe (string hashtable)
99 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
100 `(let ((symbol (intern ,string ,hashtable)))
105 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
106 ;; to limit the length of a string. This function is necessary since
107 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
108 (defsubst gnus-limit-string (str width)
109 (if (> (length str) width)
110 (substring str 0 width)
113 (defsubst gnus-functionp (form)
114 "Return non-nil if FORM is funcallable."
115 (or (and (symbolp form) (fboundp form))
116 (and (listp form) (eq (car form) 'lambda))
117 (byte-code-function-p form)))
119 (defsubst gnus-goto-char (point)
120 (and point (goto-char point)))
122 (defmacro gnus-buffer-exists-p (buffer)
123 `(let ((buffer ,buffer))
125 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
128 (defmacro gnus-kill-buffer (buffer)
129 `(let ((buf ,buffer))
130 (when (gnus-buffer-exists-p buf)
134 ((fboundp 'point-at-bol)
135 (defalias 'gnus-point-at-bol 'point-at-bol))
136 ((fboundp 'line-beginning-position)
137 (defalias 'gnus-point-at-bol 'line-beginning-position))
139 (defun gnus-point-at-bol ()
140 "Return point at the beginning of the line."
148 ((fboundp 'point-at-eol)
149 (defalias 'gnus-point-at-eol 'point-at-eol))
150 ((fboundp 'line-end-position)
151 (defalias 'gnus-point-at-eol 'line-end-position))
153 (defun gnus-point-at-eol ()
154 "Return point at the end of the line."
162 (defun gnus-delete-first (elt list)
163 "Delete by side effect the first occurrence of ELT as a member of LIST."
164 (if (equal (car list) elt)
167 (while (and (cdr list)
168 (not (equal (cadr list) elt)))
169 (setq list (cdr list)))
171 (setcdr list (cddr list)))
174 ;; Delete the current line (and the next N lines).
175 (defmacro gnus-delete-line (&optional n)
176 `(delete-region (progn (beginning-of-line) (point))
177 (progn (forward-line ,(or n 1)) (point))))
179 (defun gnus-byte-code (func)
180 "Return a form that can be `eval'ed based on FUNC."
181 (let ((fval (indirect-function func)))
182 (if (byte-code-function-p fval)
183 (let ((flist (append fval nil)))
184 (setcar flist 'byte-code)
186 (cons 'progn (cddr fval)))))
188 (defun gnus-extract-address-components (from)
190 ;; First find the address - the thing with the @ in it. This may
191 ;; not be accurate in mail addresses, but does the trick most of
192 ;; the time in news messages.
193 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
194 (setq address (substring from (match-beginning 0) (match-end 0))))
195 ;; Then we check whether the "name <address>" format is used.
197 ;; Linear white space is not required.
198 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
199 (and (setq name (substring from 0 (match-beginning 0)))
200 ;; Strip any quotes from the name.
201 (string-match "^\".*\"$" name)
202 (setq name (substring name 1 (1- (match-end 0))))))
203 ;; If not, then "address (name)" is used.
205 (and (string-match "(.+)" from)
206 (setq name (substring from (1+ (match-beginning 0))
207 (1- (match-end 0)))))
208 (and (string-match "()" from)
210 ;; XOVER might not support folded From headers.
211 (and (string-match "(.*" from)
212 (setq name (substring from (1+ (match-beginning 0))
214 (list (if (string= name "") nil name) (or address from))))
217 (defun gnus-fetch-field (field)
218 "Return the value of the header FIELD of current article."
221 (let ((case-fold-search t)
222 (inhibit-point-motion-hooks t))
223 (nnheader-narrow-to-headers)
224 (message-fetch-field field)))))
226 (defun gnus-goto-colon ()
228 (let ((eol (gnus-point-at-eol)))
229 (goto-char (or (text-property-any (point) eol 'gnus-position t)
230 (search-forward ":" eol t)
233 (defun gnus-decode-newsgroups (newsgroups group &optional method)
234 (let ((method (or method (gnus-find-method-for-group group))))
235 (mapconcat (lambda (group)
236 (gnus-group-name-decode group (gnus-group-name-charset
238 (message-tokenize-header newsgroups)
241 (defun gnus-remove-text-with-property (prop)
242 "Delete all text in the current buffer with text property PROP."
244 (goto-char (point-min))
246 (while (get-text-property (point) prop)
248 (goto-char (next-single-property-change (point) prop nil (point-max))))))
251 (defun gnus-newsgroup-directory-form (newsgroup)
252 "Make hierarchical directory name from NEWSGROUP name."
253 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
254 (idx (string-match ":" newsgroup)))
256 (if idx (substring newsgroup 0 idx))
258 (nnheader-replace-chars-in-string
259 (if idx (substring newsgroup (1+ idx)) newsgroup)
262 (defun gnus-newsgroup-savable-name (group)
263 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
265 (nnheader-replace-chars-in-string group ?/ ?.))
267 (defun gnus-string> (s1 s2)
268 (not (or (string< s1 s2)
273 (defun gnus-file-newer-than (file date)
274 (let ((fdate (nth 5 (file-attributes file))))
275 (or (> (car fdate) (car date))
276 (and (= (car fdate) (car date))
277 (> (nth 1 fdate) (nth 1 date))))))
281 (defmacro gnus-local-set-keys (&rest plist)
282 "Set the keys in PLIST in the current keymap."
283 `(gnus-define-keys-1 (current-local-map) ',plist))
285 (defmacro gnus-define-keys (keymap &rest plist)
286 "Define all keys in PLIST in KEYMAP."
287 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
289 (defmacro gnus-define-keys-safe (keymap &rest plist)
290 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
291 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
293 (put 'gnus-define-keys 'lisp-indent-function 1)
294 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
295 (put 'gnus-local-set-keys 'lisp-indent-function 1)
297 (defmacro gnus-define-keymap (keymap &rest plist)
298 "Define all keys in PLIST in KEYMAP."
299 `(gnus-define-keys-1 ,keymap (quote ,plist)))
301 (put 'gnus-define-keymap 'lisp-indent-function 1)
303 (defun gnus-define-keys-1 (keymap plist &optional safe)
305 (error "Can't set keys in a null keymap"))
306 (cond ((symbolp keymap)
307 (setq keymap (symbol-value keymap)))
310 (set (car keymap) nil)
311 (define-prefix-command (car keymap))
312 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
313 (setq keymap (symbol-value (car keymap)))))
316 (when (symbolp (setq key (pop plist)))
317 (setq key (symbol-value key)))
319 (eq (lookup-key keymap key) 'undefined))
320 (define-key keymap key (pop plist))
323 (defun gnus-completing-read-with-default (default prompt &rest args)
324 ;; Like `completing-read', except that DEFAULT is the default argument.
325 (let* ((prompt (if default
326 (concat prompt " (default " default ") ")
327 (concat prompt " ")))
328 (answer (apply 'completing-read prompt args)))
329 (if (or (null answer) (zerop (length answer)))
333 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
335 (defun gnus-y-or-n-p (prompt)
340 (defun gnus-yes-or-no-p (prompt)
345 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
346 ;; age-depending date representations. (e.g. just the time if it's
347 ;; from today, the day of the week if it's within the last 7 days and
348 ;; the full date if it's older)
349 (defun gnus-seconds-today ()
350 "Returns the number of seconds passed today"
351 (let ((now (decode-time (current-time))))
352 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
354 (defun gnus-seconds-month ()
355 "Returns the number of seconds passed this month"
356 (let ((now (decode-time (current-time))))
357 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
358 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
360 (defun gnus-seconds-year ()
361 "Returns the number of seconds passed this year"
362 (let ((now (decode-time (current-time)))
363 (days (format-time-string "%j" (current-time))))
364 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
365 (* (- (string-to-number days) 1) 3600 24))))
367 (defvar gnus-user-date-format-alist
368 '(((gnus-seconds-today) . "%k:%M")
369 (604800 . "%a %k:%M") ;;that's one week
370 ((gnus-seconds-month) . "%a %d")
371 ((gnus-seconds-year) . "%b %d")
372 (t . "%b %d '%y")) ;;this one is used when no
374 "Alist of time in seconds and format specification used to display dates not older.
375 The first element must be a number or a function returning a
376 number. The second element is a format-specification as described in
377 the documentation for format-time-string. The list must be ordered
378 smallest number up. When there is an element, which is not a number,
379 the corresponding format-specification will be used, disregarding any
380 following elements. You can use the functions gnus-seconds-today,
381 gnus-seconds-month, gnus-seconds-year which will return the number of
382 seconds which passed today/this month/this year.")
384 (defun gnus-user-date (messy-date)
385 "Format the messy-date acording to gnus-user-date-format-alist.
386 Returns \" ? \" if there's bad input or if an other error occurs.
387 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
389 (let* ((messy-date (safe-date-to-time messy-date))
391 ;;If we don't find something suitable we'll use this one
392 (my-format "%b %m '%y")
393 (high (lsh (- (car now) (car messy-date)) 16)))
394 (if (and (> high -1) (= (logand high 65535) 0))
395 ;;overflow and bad input
396 (let* ((difference (+ high (- (car (cdr now))
397 (car (cdr messy-date)))))
398 (templist gnus-user-date-format-alist)
399 (top (eval (caar templist))))
400 (while (if (numberp top) (< top difference) (not top))
402 (setq templist (cdr templist))
403 (setq top (eval (caar templist)))))
404 (if (stringp (cdr (car templist)))
405 (setq my-format (cdr (car templist))))))
406 (format-time-string (eval my-format) messy-date))
408 ;;end of Frank's code
410 (defun gnus-dd-mmm (messy-date)
411 "Return a string like DD-MMM from a big messy string."
413 (format-time-string "%d-%b" (safe-date-to-time messy-date))
416 (defmacro gnus-date-get-time (date)
417 "Convert DATE string to Emacs time.
418 Cache the result as a text property stored in DATE."
419 ;; Either return the cached value...
423 (or (get-text-property 0 'gnus-time d)
424 ;; or compute the value...
425 (let ((time (safe-date-to-time d)))
426 ;; and store it back in the string.
427 (put-text-property 0 1 'gnus-time time d)
430 (defsubst gnus-time-iso8601 (time)
431 "Return a string of TIME in YYYYMMDDTHHMMSS format."
432 (format-time-string "%Y%m%dT%H%M%S" time))
434 (defun gnus-date-iso8601 (date)
435 "Convert the DATE to YYYYMMDDTHHMMSS."
437 (gnus-time-iso8601 (gnus-date-get-time date))
440 (defun gnus-mode-string-quote (string)
441 "Quote all \"%\"'s in STRING."
442 (gnus-replace-in-string string "%" "%%"))
444 ;; Make a hash table (default and minimum size is 256).
445 ;; Optional argument HASHSIZE specifies the table size.
446 (defun gnus-make-hashtable (&optional hashsize)
447 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
449 ;; Make a number that is suitable for hashing; bigger than MIN and
450 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
451 ;; hardware modulo operation, so they implement it in software. On
452 ;; many sparcs over 50% of the time to intern is spent in the modulo.
453 ;; Yes, it's slower than actually computing the hash from the string!
454 ;; So we use powers of 2 so people can optimize the modulo to a mask.
455 (defun gnus-create-hash-size (min)
461 (defcustom gnus-verbose 7
462 "*Integer that says how verbose Gnus should be.
463 The higher the number, the more messages Gnus will flash to say what
464 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
465 display most important messages; and at ten, Gnus will keep on
466 jabbering all the time."
470 ;; Show message if message has a lower level than `gnus-verbose'.
471 ;; Guideline for numbers:
472 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
473 ;; for things that take a long time, 7 - not very important messages
474 ;; on stuff, 9 - messages inside loops.
475 (defun gnus-message (level &rest args)
476 (if (<= level gnus-verbose)
477 (apply 'message args)
478 ;; We have to do this format thingy here even if the result isn't
479 ;; shown - the return value has to be the same as the return value
481 (apply 'format args)))
483 (defun gnus-error (level &rest args)
484 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
485 (when (<= (floor level) gnus-verbose)
486 (apply 'message args)
489 (when (and (floatp level)
490 (not (zerop (setq duration (* 10 (- level (floor level)))))))
491 (sit-for duration))))
494 (defun gnus-split-references (references)
495 "Return a list of Message-IDs in REFERENCES."
498 (while (string-match "<[^<]+[^< \t]" references beg)
499 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
503 (defsubst gnus-parent-id (references &optional n)
504 "Return the last Message-ID in REFERENCES.
505 If N, return the Nth ancestor instead."
506 (when (and references
507 (not (zerop (length references))))
509 (let ((ids (inline (gnus-split-references references))))
510 (while (nthcdr n ids)
511 (setq ids (cdr ids)))
513 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
514 (match-string 1 references)))))
516 (defun gnus-buffer-live-p (buffer)
517 "Say whether BUFFER is alive or not."
520 (buffer-name (get-buffer buffer))))
522 (defun gnus-horizontal-recenter ()
523 "Recenter the current buffer horizontally."
524 (if (< (current-column) (/ (window-width) 2))
525 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
526 (let* ((orig (point))
527 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
530 ;; Find the longest line currently displayed in the window.
531 (goto-char (window-start))
532 (while (and (not (eobp))
535 (setq max (max max (current-column)))
538 ;; Scroll horizontally to center (sort of) the point.
539 (if (> max (window-width))
541 (gnus-get-buffer-window (current-buffer) t)
542 (min (- (current-column) (/ (window-width) 3))
543 (+ 2 (- max (window-width)))))
544 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
547 (defun gnus-read-event-char ()
548 "Get the next event."
549 (let ((event (read-event)))
550 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
551 (cons (and (numberp event) event) event)))
553 (defun gnus-sortable-date (date)
554 "Make string suitable for sorting from DATE."
555 (gnus-time-iso8601 (date-to-time date)))
557 (defun gnus-copy-file (file &optional to)
560 (list (read-file-name "Copy file: " default-directory)
561 (read-file-name "Copy file to: " default-directory)))
563 (setq to (read-file-name "Copy file to: " default-directory)))
564 (when (file-directory-p to)
565 (setq to (concat (file-name-as-directory to)
566 (file-name-nondirectory file))))
569 (defvar gnus-work-buffer " *gnus work*")
571 (defun gnus-set-work-buffer ()
572 "Put point in the empty Gnus work buffer."
573 (if (get-buffer gnus-work-buffer)
575 (set-buffer gnus-work-buffer)
577 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
578 (kill-all-local-variables)))
580 (defmacro gnus-group-real-name (group)
581 "Find the real name of a foreign newsgroup."
582 `(let ((gname ,group))
583 (if (string-match "^[^:]+:" gname)
584 (substring gname (match-end 0))
587 (defun gnus-make-sort-function (funs)
588 "Return a composite sort condition based on the functions in FUNC."
590 ;; Just a simple function.
591 ((gnus-functionp funs) funs)
592 ;; No functions at all.
594 ;; A list of functions.
599 ,(gnus-make-sort-function-1 (reverse funs)))))
600 ;; A list containing just one function.
604 (defun gnus-make-sort-function-1 (funs)
605 "Return a composite sort condition based on the functions in FUNC."
606 (let ((function (car funs))
609 (when (consp function)
612 ((eq (car function) 'not)
613 (setq function (cadr function)
616 ((gnus-functionp function)
620 (error "Invalid sort spec: %s" function))))
622 `(or (,function ,first ,last)
623 (and (not (,function ,last ,first))
624 ,(gnus-make-sort-function-1 (cdr funs))))
625 `(,function ,first ,last))))
627 (defun gnus-turn-off-edit-menu (type)
628 "Turn off edit menu in `gnus-TYPE-mode-map'."
629 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
630 [menu-bar edit] 'undefined))
632 (defun gnus-prin1 (form)
633 "Use `prin1' on FORM in the current buffer.
634 Bind `print-quoted' and `print-readably' to t while printing."
635 (let ((print-quoted t)
637 (print-escape-multibyte nil)
638 print-level print-length)
639 (prin1 form (current-buffer))))
641 (defun gnus-prin1-to-string (form)
642 "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
643 (let ((print-quoted t)
645 (prin1-to-string form)))
647 (defun gnus-make-directory (directory)
648 "Make DIRECTORY (and all its parents) if it doesn't exist."
650 (let ((file-name-coding-system nnmail-pathname-coding-system)
651 (pathname-coding-system nnmail-pathname-coding-system))
653 (not (file-exists-p directory)))
654 (make-directory directory t)))
657 (defun gnus-write-buffer (file)
658 "Write the current buffer's contents to FILE."
659 ;; Make sure the directory exists.
660 (gnus-make-directory (file-name-directory file))
661 (let ((file-name-coding-system nnmail-pathname-coding-system)
662 (pathname-coding-system nnmail-pathname-coding-system))
664 (write-region (point-min) (point-max) file nil 'quietly)))
666 (defun gnus-write-buffer-as-binary (file)
667 "Write the current buffer's contents to FILE without code conversion."
668 ;; Make sure the directory exists.
669 (gnus-make-directory (file-name-directory file))
671 (write-region-as-binary (point-min) (point-max) file nil 'quietly))
673 (defun gnus-write-buffer-as-coding-system (coding-system file)
674 "Write the current buffer's contents to FILE with code conversion."
675 ;; Make sure the directory exists.
676 (gnus-make-directory (file-name-directory file))
678 (write-region-as-coding-system
679 coding-system (point-min) (point-max) file nil 'quietly))
681 (defun gnus-delete-file (file)
682 "Delete FILE if it exists."
683 (when (file-exists-p file)
686 (defun gnus-strip-whitespace (string)
687 "Return STRING stripped of all whitespace."
688 (while (string-match "[\r\n\t ]+" string)
689 (setq string (replace-match "" t t string)))
692 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
693 "The same as `put-text-property', but don't put this prop on any newlines in the region."
698 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
699 (gnus-put-text-property beg (match-beginning 0) prop val)
701 (gnus-put-text-property beg (point) prop val)))))
703 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
704 "The same as `put-text-property', but don't put this prop on any newlines in the region."
709 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
711 (gnus-make-overlay beg (match-beginning 0))
714 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
716 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
718 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
721 (when (get-text-property b 'gnus-face)
722 (setq b (next-single-property-change b 'gnus-face nil end)))
725 (gnus-put-text-property
726 b (setq b (next-single-property-change b 'gnus-face nil end))
729 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
730 ;;; The primary idea here is to try to protect internal datastructures
731 ;;; from becoming corrupted when the user hits C-g, or if a hook or
732 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
733 ;;; updated at the same time, or information can be lost.
735 (defvar gnus-atomic-be-safe t
736 "If t, certain operations will be protected from interruption by C-g.")
738 (defmacro gnus-atomic-progn (&rest forms)
739 "Evaluate FORMS atomically, which means to protect the evaluation
740 from being interrupted by the user. An error from the forms themselves
741 will return without finishing the operation. Since interrupts from
742 the user are disabled, it is recommended that only the most minimal
743 operations are performed by FORMS. If you wish to assign many
744 complicated values atomically, compute the results into temporary
745 variables and then do only the assignment atomically."
746 `(let ((inhibit-quit gnus-atomic-be-safe))
749 (put 'gnus-atomic-progn 'lisp-indent-function 0)
751 (defmacro gnus-atomic-progn-assign (protect &rest forms)
752 "Evaluate FORMS, but insure that the variables listed in PROTECT
753 are not changed if anything in FORMS signals an error or otherwise
754 non-locally exits. The variables listed in PROTECT are updated atomically.
755 It is safe to use gnus-atomic-progn-assign with long computations.
757 Note that if any of the symbols in PROTECT were unbound, they will be
758 set to nil on a sucessful assignment. In case of an error or other
759 non-local exit, it will still be unbound."
760 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
761 (concat (symbol-name x)
765 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
767 (temp-sym-let (mapcar (lambda (x) (list (car x)
768 `(and (boundp ',(cadr x))
771 (sym-temp-let sym-temp-map)
772 (temp-sym-assign (apply 'append temp-sym-map))
773 (sym-temp-assign (apply 'append sym-temp-map))
774 (result (make-symbol "result-tmp")))
775 `(let (,@temp-sym-let
778 (setq ,result (progn ,@forms))
779 (setq ,@temp-sym-assign))
780 (let ((inhibit-quit gnus-atomic-be-safe))
781 (setq ,@sym-temp-assign))
784 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
785 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
787 (defmacro gnus-atomic-setq (&rest pairs)
788 "Similar to setq, except that the real symbols are only assigned when
789 there are no errors. And when the real symbols are assigned, they are
790 done so atomically. If other variables might be changed via side-effect,
791 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
792 with potentially long computations."
796 (push (car tpairs) syms)
797 (setq tpairs (cddr tpairs)))
798 `(gnus-atomic-progn-assign ,syms
801 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
804 ;;; Functions for saving to babyl/mail files.
806 (defvar rmail-default-rmail-file)
807 (defun gnus-output-to-rmail (filename &optional ask)
808 "Append the current article to an Rmail file named FILENAME."
810 ;; Most of these codes are borrowed from rmailout.el.
811 (setq filename (expand-file-name filename))
812 (setq rmail-default-rmail-file filename)
813 (let ((artbuf (current-buffer))
814 (tmpbuf (get-buffer-create " *Gnus-output*")))
816 (or (get-file-buffer filename)
817 (file-exists-p filename)
820 (concat "\"" filename "\" does not exist, create it? ")))
821 (let ((file-buffer (create-file-buffer filename)))
823 (set-buffer file-buffer)
824 (rmail-insert-rmail-file-header)
825 (let ((require-final-newline nil))
826 (gnus-write-buffer-as-coding-system
827 nnheader-text-coding-system filename)))
828 (kill-buffer file-buffer))
829 (error "Output file does not exist")))
832 (insert-buffer-substring artbuf)
833 (gnus-convert-article-to-rmail)
834 ;; Decide whether to append to a file or to an Emacs buffer.
835 (let ((outbuf (get-file-buffer filename)))
837 (let ((file-name-coding-system nnmail-pathname-coding-system)
838 (pathname-coding-system nnmail-pathname-coding-system))
839 (write-region-as-binary (point-min) (point-max)
841 ;; File has been visited, in buffer OUTBUF.
843 (let ((buffer-read-only nil)
844 (msg (and (boundp 'rmail-current-message)
845 (symbol-value 'rmail-current-message))))
846 ;; If MSG is non-nil, buffer is in RMAIL mode.
849 (narrow-to-region (point-max) (point-max)))
850 (insert-buffer-substring tmpbuf)
852 (goto-char (point-min))
854 (search-backward "\n\^_")
855 (narrow-to-region (point) (point-max))
856 (rmail-count-new-messages t)
857 (when (rmail-summary-exists)
858 (rmail-select-summary
859 (rmail-update-summary)))
860 (rmail-count-new-messages t)
861 (rmail-show-message msg))
863 (kill-buffer tmpbuf)))
865 (defun gnus-output-to-mail (filename &optional ask)
866 "Append the current article to a mail file named FILENAME."
867 (setq filename (expand-file-name filename))
868 (let ((artbuf (current-buffer))
869 (tmpbuf (get-buffer-create " *Gnus-output*")))
871 ;; Create the file, if it doesn't exist.
872 (when (and (not (get-file-buffer filename))
873 (not (file-exists-p filename)))
876 (concat "\"" filename "\" does not exist, create it? ")))
877 (let ((file-buffer (create-file-buffer filename)))
879 (set-buffer file-buffer)
880 (let ((require-final-newline nil))
881 (gnus-write-buffer-as-coding-system
882 nnheader-text-coding-system filename)))
883 (kill-buffer file-buffer))
884 (error "Output file does not exist")))
887 (insert-buffer-substring artbuf)
888 (goto-char (point-min))
889 (if (looking-at "From ")
891 (insert "From nobody " (current-time-string) "\n"))
892 (let (case-fold-search)
893 (while (re-search-forward "^From " nil t)
896 ;; Decide whether to append to a file or to an Emacs buffer.
897 (let ((outbuf (get-file-buffer filename)))
899 (let ((buffer-read-only nil))
901 (goto-char (point-max))
903 (unless (looking-at "\n\n")
904 (goto-char (point-max))
908 (goto-char (point-max))
909 (let ((file-name-coding-system nnmail-pathname-coding-system)
910 (pathname-coding-system nnmail-pathname-coding-system))
911 (write-region-as-binary (point-min) (point-max)
913 ;; File has been visited, in buffer OUTBUF.
915 (let ((buffer-read-only nil))
916 (goto-char (point-max))
920 (insert-buffer-substring tmpbuf)))))
921 (kill-buffer tmpbuf)))
923 (defun gnus-convert-article-to-rmail ()
924 "Convert article in current buffer to Rmail message format."
925 (let ((buffer-read-only nil))
926 ;; Convert article directly into Babyl format.
927 (goto-char (point-min))
928 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
929 (while (search-forward "\n\^_" nil t) ;single char
930 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
931 (goto-char (point-max))
934 (defun gnus-map-function (funs arg)
935 "Applies the result of the first function in FUNS to the second, and so on.
936 ARG is passed to the first function."
939 (setq arg (funcall (pop myfuns) arg)))
942 (defun gnus-run-hooks (&rest funcs)
943 "Does the same as `run-hooks', but saves excursion."
944 (let ((buf (current-buffer)))
946 (apply 'run-hooks funcs)
950 ;;; .netrc and .authinforc parsing
953 (defun gnus-parse-netrc (file)
954 "Parse FILE and return an list of all entries in the file."
955 (when (file-exists-p file)
957 (let ((tokens '("machine" "default" "login"
958 "password" "account" "macdef" "force"
960 alist elem result pair)
961 (insert-file-contents file)
962 (goto-char (point-min))
963 ;; Go through the file, line by line.
965 (narrow-to-region (point) (gnus-point-at-eol))
966 ;; For each line, get the tokens and values.
968 (skip-chars-forward "\t ")
969 ;; Skip lines that begin with a "#".
970 (if (eq (char-after) ?#)
971 (goto-char (point-max))
974 (if (= (following-char) ?\")
975 (read (current-buffer))
977 (point) (progn (skip-chars-forward "^\t ")
980 ((equal elem "macdef")
981 ;; We skip past the macro definition.
983 (while (and (zerop (forward-line 1))
985 (narrow-to-region (point) (point)))
986 ((member elem tokens)
987 ;; Tokens that don't have a following value are ignored,
989 (when (and pair (or (cdr pair)
990 (equal (car pair) "default")))
992 (setq pair (list elem)))
994 ;; Values that haven't got a preceding token are ignored.
998 (setq pair nil)))))))
1000 (push (nreverse alist) result))
1005 (nreverse result)))))
1007 (defun gnus-netrc-machine (list machine &optional port defaultport)
1008 "Return the netrc values from LIST for MACHINE or for the default entry.
1009 If PORT specified, only return entries with matching port tokens.
1010 Entries without port tokens default to DEFAULTPORT."
1014 (when (equal (cdr (assoc "machine" (car list))) machine)
1015 (push (car list) result))
1018 ;; No machine name matches, so we look for default entries.
1020 (when (assoc "default" (car rest))
1021 (push (car rest) result))
1024 (setq result (nreverse result))
1026 (not (equal (or port defaultport "nntp")
1027 (or (gnus-netrc-get (car result) "port")
1028 defaultport "nntp"))))
1032 (defun gnus-netrc-get (alist type)
1033 "Return the value of token TYPE from ALIST."
1034 (cdr (assoc type alist)))
1038 (defvar gnus-group-buffer) ; Compiler directive
1039 (defun gnus-alive-p ()
1040 "Say whether Gnus is running or not."
1041 (and (boundp 'gnus-group-buffer)
1042 (get-buffer gnus-group-buffer)
1044 (set-buffer gnus-group-buffer)
1045 (eq major-mode 'gnus-group-mode))))
1047 (defun gnus-remove-duplicates (list)
1048 (let (new (tail list))
1050 (or (member (car tail) new)
1051 (setq new (cons (car tail) new)))
1052 (setq tail (cdr tail)))
1055 (defun gnus-delete-if (predicate list)
1056 "Delete elements from LIST that satisfy PREDICATE."
1059 (unless (funcall predicate (car list))
1060 (push (car list) out))
1064 (if (fboundp 'assq-delete-all)
1065 (defalias 'gnus-delete-alist 'assq-delete-all)
1066 (defun gnus-delete-alist (key alist)
1067 "Delete from ALIST all elements whose car is KEY.
1068 Return the modified alist."
1070 (while (setq entry (assq key alist))
1071 (setq alist (delq entry alist)))
1074 (defmacro gnus-pull (key alist &optional assoc-p)
1075 "Modify ALIST to be without KEY."
1076 (unless (symbolp alist)
1077 (error "Not a symbol: %s" alist))
1078 (let ((fun (if assoc-p 'assoc 'assq)))
1079 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1081 (defun gnus-globalify-regexp (re)
1082 "Returns a regexp that matches a whole line, iff RE matches a part of it."
1083 (concat (unless (string-match "^\\^" re) "^.*")
1085 (unless (string-match "\\$$" re) ".*$")))
1087 (defun gnus-set-window-start (&optional point)
1088 "Set the window start to POINT, or (point) if nil."
1089 (let ((win (gnus-get-buffer-window (current-buffer) t)))
1091 (set-window-start win (or point (point))))))
1093 (defun gnus-annotation-in-region-p (b e)
1095 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1096 (text-property-any b e 'gnus-undeletable t)))
1098 (defun gnus-or (&rest elems)
1099 "Return non-nil if any of the elements are non-nil."
1103 (throw 'found t)))))
1105 (defun gnus-and (&rest elems)
1106 "Return non-nil if all of the elements are non-nil."
1110 (throw 'found nil)))
1113 (defun gnus-write-active-file (file hashtb &optional full-names)
1114 (let ((output-coding-system nnmail-active-file-coding-system)
1115 (coding-system-for-write nnmail-active-file-coding-system))
1116 (with-temp-file file
1122 (insert (format "%S %d %d y\n"
1125 (intern (gnus-group-real-name (symbol-name sym))))
1126 (or (cdr (symbol-value sym))
1127 (car (symbol-value sym)))
1128 (car (symbol-value sym))))))
1130 (goto-char (point-max))
1131 (while (search-backward "\\." nil t)
1134 (if (fboundp 'union)
1135 (defalias 'gnus-union 'union)
1136 (defun gnus-union (l1 l2)
1137 "Set union of lists L1 and L2."
1138 (cond ((null l1) l2)
1142 (or (>= (length l1) (length l2))
1143 (setq l1 (prog1 l2 (setq l2 l1))))
1145 (or (member (car l2) l1)
1150 (defun gnus-add-text-properties-when
1151 (property value start end properties &optional object)
1152 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1155 (< start end) ;; XEmacs will loop for every when start=end.
1156 (setq point (text-property-not-all start end property value)))
1157 (gnus-add-text-properties start point properties object)
1158 (setq start (text-property-any point end property value)))
1160 (gnus-add-text-properties start end properties object))))
1162 (defun gnus-remove-text-properties-when
1163 (property value start end properties &optional object)
1164 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1168 (setq point (text-property-not-all start end property value)))
1169 (remove-text-properties start point properties object)
1170 (setq start (text-property-any point end property value)))
1172 (remove-text-properties start end properties object))
1175 (defun gnus-string-equal (x y)
1176 "Like `string-equal', except it compares case-insensitively."
1177 (and (= (length x) (length y))
1178 (or (string-equal x y)
1179 (string-equal (downcase x) (downcase y)))))
1181 (defcustom gnus-use-byte-compile t
1182 "If non-nil, byte-compile crucial run-time codes.
1183 Setting it to `nil' has no effect after first time running
1184 `gnus-byte-compile'."
1187 :group 'gnus-various)
1189 (defun gnus-byte-compile (form)
1190 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1191 (if gnus-use-byte-compile
1194 ;; Work around a bug in XEmacs 21.4
1195 (require 'byte-optimize)
1198 (defalias 'gnus-byte-compile 'byte-compile)
1199 (byte-compile form))
1202 (defun gnus-remassoc (key alist)
1203 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1204 The modified LIST is returned. If the first member
1205 of LIST has a car that is `equal' to KEY, there is no way to remove it
1206 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1207 sure of changing the value of `foo'."
1209 (if (equal key (caar alist))
1211 (setcdr alist (gnus-remassoc key (cdr alist)))
1214 (defun gnus-update-alist-soft (key value alist)
1216 (cons (cons key value) (gnus-remassoc key alist))
1217 (gnus-remassoc key alist)))
1219 (defun gnus-create-info-command (node)
1220 "Create a command that will go to info NODE."
1223 ,(concat "Enter the info system at node " node)
1224 (Info-goto-node ,node)
1225 (setq gnus-info-buffer (current-buffer))
1226 (gnus-configure-windows 'info)))
1228 (defun gnus-not-ignore (&rest args)
1231 (defvar gnus-directory-sep-char-regexp "/"
1232 "The regexp of directory separator character.
1233 If you find some problem with the directory separator character, try
1234 \"[/\\\\\]\" for some systems.")
1236 (defun gnus-url-unhex (x)
1243 (defun gnus-url-unhex-string (str &optional allow-newlines)
1244 "Remove %XXX embedded spaces, etc in a url.
1245 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1246 decoding of carriage returns and line feeds in the string, which is normally
1247 forbidden in URL encoding."
1248 (setq str (or (mm-subst-char-in-string ?+ ? str) ""))
1250 (case-fold-search t))
1251 (while (string-match "%[0-9a-f][0-9a-f]" str)
1252 (let* ((start (match-beginning 0))
1253 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1255 (gnus-url-unhex (elt str (+ start 2))))))
1257 tmp (substring str 0 start)
1260 (char-to-string code))
1261 ((or (= code ?\n) (= code ?\r))
1263 (t (char-to-string code))))
1264 str (substring str (match-end 0)))))
1265 (setq tmp (concat tmp str))
1268 (defun gnus-make-predicate (spec)
1269 "Transform SPEC into a function that can be called.
1270 SPEC is a predicate specifier that contains stuff like `or', `and',
1271 `not', lists and functions. The functions all take one parameter."
1272 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1274 (defun gnus-make-predicate-1 (spec)
1279 (if (memq (car spec) '(or and not))
1280 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1281 (error "Invalid predicate specifier: %s" spec)))))
1283 (defun gnus-local-map-property (map)
1284 "Return a list suitable for a text property list specifying keymap MAP."
1288 ((>= emacs-major-version 21)
1291 (list 'local-map map))))
1293 (defun gnus-completing-read (prompt table &optional predicate require-match
1296 (not (boundp history)))
1299 (if (symbol-value history)
1300 (concat prompt " (" (car (symbol-value history)) "): ")
1301 (concat prompt ": "))
1307 (car (symbol-value history))))
1309 (defun gnus-graphic-display-p ()
1310 (or (and (fboundp 'display-graphic-p)
1311 (display-graphic-p))
1312 ;;;!!!This is bogus. Fixme!
1313 (and (featurep 'xemacs)
1316 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1317 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1319 (defmacro gnus-parse-without-error (&rest body)
1320 "Allow continuing onto the next line even if an error occurs."
1321 `(while (not (eobp))
1325 (goto-char (point-max)))
1327 (gnus-error 4 "Invalid data on line %d"
1328 (count-lines (point-min) (point)))
1329 (forward-line 1)))))
1331 (defun gnus-cache-file-contents (file variable function)
1332 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1333 (let ((time (nth 5 (file-attributes file)))
1335 (if (or (null (setq value (symbol-value variable)))
1336 (not (equal (car value) file))
1337 (not (equal (nth 1 value) time)))
1339 (setq contents (funcall function file))
1340 (set variable (list file time contents))
1344 (defun gnus-multiple-choice (prompt choice &optional idx)
1345 "Ask user a multiple choice question.
1346 CHOICE is a list of the choice char and help message at IDX."
1348 (save-window-excursion
1351 (message "%s (%s?): "
1353 (mapconcat (lambda (s) (char-to-string (car s)))
1355 (setq tchar (read-char))
1356 (when (not (assq tchar choice))
1358 (setq buf (get-buffer-create "*Gnus Help*"))
1360 (fundamental-mode) ; for Emacs 20.4+
1361 (buffer-disable-undo)
1363 (insert prompt ":\n\n")
1370 ;; find the longest string to display
1372 (setq n (length (nth idx (car list))))
1375 (setq list (cdr list)))
1376 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1377 (setq n (/ (1- (window-width)) max)) ; items per line
1378 (setq width (/ (1- (window-width)) n)) ; width of each item
1379 ;; insert `n' items, each in a field of width `width'
1384 (delete-char -1) ; the `\n' takes a char
1386 (setq pad (- width 3))
1387 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1388 (insert (format format (caar alist) (nth idx (car alist))))
1389 (setq alist (cdr alist))
1390 (setq i (1+ i))))))))
1391 (if (buffer-live-p buf)
1395 (provide 'gnus-util)
1397 ;;; gnus-util.el ends here