ea9512d13ee0929eabb375c854370a25a28cb50a
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
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 3, 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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, 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 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
34 ;; autoloads and defvars below...]
35
36 ;;; Code:
37
38 ;; For Emacs < 22.2.
39 (eval-and-compile
40   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
41 (eval-when-compile
42   (require 'cl))
43 ;; Fixme: this should be a gnus variable, not nnmail-.
44 (defvar nnmail-pathname-coding-system)
45 (defvar nnmail-active-file-coding-system)
46
47 ;; Inappropriate references to other parts of Gnus.
48 (defvar gnus-emphasize-whitespace-regexp)
49 (defvar gnus-original-article-buffer)
50 (defvar gnus-user-agent)
51
52 (require 'time-date)
53 (require 'netrc)
54
55 (eval-and-compile
56   (autoload 'message-fetch-field "message")
57   (autoload 'gnus-get-buffer-window "gnus-win")
58   (autoload 'rmail-insert-rmail-file-header "rmail")
59   (autoload 'rmail-count-new-messages "rmail")
60   (autoload 'rmail-show-message "rmail")
61   (autoload 'nnheader-narrow-to-headers "nnheader")
62   (autoload 'nnheader-replace-chars-in-string "nnheader"))
63
64 (eval-and-compile
65   (cond
66    ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
67    ;; SXEmacs 22.1.4) over `replace-in-string'.  The later leads to inf-loops
68    ;; on empty matches:
69    ;;   (replace-in-string "foo" "/*$" "/")
70    ;;   (replace-in-string "xe" "\\(x\\)?" "")
71    ((fboundp 'replace-regexp-in-string)
72     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
73       "Replace all matches for REGEXP with NEWTEXT in STRING.
74 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
75 string containing the replacements.
76
77 This is a compatibility function for different Emacsen."
78       (replace-regexp-in-string regexp newtext string nil literal)))
79    ((fboundp 'replace-in-string)
80     (defalias 'gnus-replace-in-string 'replace-in-string))))
81
82 (defun gnus-boundp (variable)
83   "Return non-nil if VARIABLE is bound and non-nil."
84   (and (boundp variable)
85        (symbol-value variable)))
86
87 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
88   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
89   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
90         (w (make-symbol "w"))
91         (buf (make-symbol "buf")))
92     `(let* ((,tempvar (selected-window))
93             (,buf ,buffer)
94             (,w (gnus-get-buffer-window ,buf 'visible)))
95        (unwind-protect
96            (progn
97              (if ,w
98                  (progn
99                    (select-window ,w)
100                    (set-buffer (window-buffer ,w)))
101                (pop-to-buffer ,buf))
102              ,@forms)
103          (select-window ,tempvar)))))
104
105 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
106 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
107
108 (defmacro gnus-intern-safe (string hashtable)
109   "Get hash value.  Arguments are STRING and HASHTABLE."
110   `(let ((symbol (intern ,string ,hashtable)))
111      (or (boundp symbol)
112          (set symbol nil))
113      symbol))
114
115 (defsubst gnus-goto-char (point)
116   (and point (goto-char point)))
117
118 (defmacro gnus-buffer-exists-p (buffer)
119   `(let ((buffer ,buffer))
120      (when buffer
121        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
122                 buffer))))
123
124 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
125 ;; XEmacs.  In Emacs we don't need to call `make-local-hook' first.
126 ;; It's harmless, though, so the main purpose of this alias is to shut
127 ;; up the byte compiler.
128 (defalias 'gnus-make-local-hook
129   (if (eq (get 'make-local-hook 'byte-compile)
130           'byte-compile-obsolete)
131       'ignore                           ; Emacs
132     'make-local-hook))                  ; XEmacs
133
134 (defun gnus-delete-first (elt list)
135   "Delete by side effect the first occurrence of ELT as a member of LIST."
136   (if (equal (car list) elt)
137       (cdr list)
138     (let ((total list))
139       (while (and (cdr list)
140                   (not (equal (cadr list) elt)))
141         (setq list (cdr list)))
142       (when (cdr list)
143         (setcdr list (cddr list)))
144       total)))
145
146 ;; Delete the current line (and the next N lines).
147 (defmacro gnus-delete-line (&optional n)
148   `(delete-region (point-at-bol)
149                   (progn (forward-line ,(or n 1)) (point))))
150
151 (defun gnus-byte-code (func)
152   "Return a form that can be `eval'ed based on FUNC."
153   (let ((fval (indirect-function func)))
154     (if (byte-code-function-p fval)
155         (let ((flist (append fval nil)))
156           (setcar flist 'byte-code)
157           flist)
158       (cons 'progn (cddr fval)))))
159
160 (defun gnus-extract-address-components (from)
161   "Extract address components from a From header.
162 Given an RFC-822 address FROM, extract full name and canonical address.
163 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).  Much more simple
164 solution than `mail-extract-address-components', which works much better, but
165 is slower."
166   (let (name address)
167     ;; First find the address - the thing with the @ in it.  This may
168     ;; not be accurate in mail addresses, but does the trick most of
169     ;; the time in news messages.
170     (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
171            ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
172            ;; correctly.
173            (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
174            (setq address (substring from (match-beginning 1) (match-end 1))))
175           ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
176            (setq address (substring from (match-beginning 0) (match-end 0)))))
177     ;; Then we check whether the "name <address>" format is used.
178     (and address
179          ;; Linear white space is not required.
180          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
181          (and (setq name (substring from 0 (match-beginning 0)))
182               ;; Strip any quotes from the name.
183               (string-match "^\".*\"$" name)
184               (setq name (substring name 1 (1- (match-end 0))))))
185     ;; If not, then "address (name)" is used.
186     (or name
187         (and (string-match "(.+)" from)
188              (setq name (substring from (1+ (match-beginning 0))
189                                    (1- (match-end 0)))))
190         (and (string-match "()" from)
191              (setq name address))
192         ;; XOVER might not support folded From headers.
193         (and (string-match "(.*" from)
194              (setq name (substring from (1+ (match-beginning 0))
195                                    (match-end 0)))))
196     (list (if (string= name "") nil name) (or address from))))
197
198
199 (defun gnus-fetch-field (field)
200   "Return the value of the header FIELD of current article."
201   (save-excursion
202     (save-restriction
203       (let ((inhibit-point-motion-hooks t))
204         (nnheader-narrow-to-headers)
205         (message-fetch-field field)))))
206
207 (defun gnus-fetch-original-field (field)
208   "Fetch FIELD from the original version of the current article."
209   (with-current-buffer gnus-original-article-buffer
210     (gnus-fetch-field field)))
211
212
213 (defun gnus-goto-colon ()
214   (beginning-of-line)
215   (let ((eol (point-at-eol)))
216     (goto-char (or (text-property-any (point) eol 'gnus-position t)
217                    (search-forward ":" eol t)
218                    (point)))))
219
220 (defun gnus-decode-newsgroups (newsgroups group &optional method)
221   (let ((method (or method (gnus-find-method-for-group group))))
222     (mapconcat (lambda (group)
223                  (gnus-group-name-decode group (gnus-group-name-charset
224                                                 method group)))
225                (message-tokenize-header newsgroups)
226                ",")))
227
228 (defun gnus-remove-text-with-property (prop)
229   "Delete all text in the current buffer with text property PROP."
230   (let ((start (point-min))
231         end)
232     (unless (get-text-property start prop)
233       (setq start (next-single-property-change start prop)))
234     (while start
235       (setq end (text-property-any start (point-max) prop nil))
236       (delete-region start (or end (point-max)))
237       (setq start (when end
238                     (next-single-property-change start prop))))))
239
240 (defun gnus-newsgroup-directory-form (newsgroup)
241   "Make hierarchical directory name from NEWSGROUP name."
242   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
243          (idx (string-match ":" newsgroup)))
244     (concat
245      (if idx (substring newsgroup 0 idx))
246      (if idx "/")
247      (nnheader-replace-chars-in-string
248       (if idx (substring newsgroup (1+ idx)) newsgroup)
249       ?. ?/))))
250
251 (defun gnus-newsgroup-savable-name (group)
252   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
253   ;; with dots.
254   (nnheader-replace-chars-in-string group ?/ ?.))
255
256 (defun gnus-string> (s1 s2)
257   (not (or (string< s1 s2)
258            (string= s1 s2))))
259
260 (defun gnus-string< (s1 s2)
261   "Return t if first arg string is less than second in lexicographic order.
262 Case is significant if and only if `case-fold-search' is nil.
263 Symbols are also allowed; their print names are used instead."
264   (if case-fold-search
265       (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
266                     (downcase (if (symbolp s2) (symbol-name s2) s2)))
267     (string-lessp s1 s2)))
268
269 ;;; Time functions.
270
271 (defun gnus-file-newer-than (file date)
272   (let ((fdate (nth 5 (file-attributes file))))
273     (or (> (car fdate) (car date))
274         (and (= (car fdate) (car date))
275              (> (nth 1 fdate) (nth 1 date))))))
276
277 ;;; Keymap macros.
278
279 (defmacro gnus-local-set-keys (&rest plist)
280   "Set the keys in PLIST in the current keymap."
281   `(gnus-define-keys-1 (current-local-map) ',plist))
282
283 (defmacro gnus-define-keys (keymap &rest plist)
284   "Define all keys in PLIST in KEYMAP."
285   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
286
287 (defmacro gnus-define-keys-safe (keymap &rest plist)
288   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
289   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
290
291 (put 'gnus-define-keys 'lisp-indent-function 1)
292 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
293 (put 'gnus-local-set-keys 'lisp-indent-function 1)
294
295 (defmacro gnus-define-keymap (keymap &rest plist)
296   "Define all keys in PLIST in KEYMAP."
297   `(gnus-define-keys-1 ,keymap (quote ,plist)))
298
299 (put 'gnus-define-keymap 'lisp-indent-function 1)
300
301 (defun gnus-define-keys-1 (keymap plist &optional safe)
302   (when (null keymap)
303     (error "Can't set keys in a null keymap"))
304   (cond ((symbolp keymap)
305          (setq keymap (symbol-value keymap)))
306         ((keymapp keymap))
307         ((listp keymap)
308          (set (car keymap) nil)
309          (define-prefix-command (car keymap))
310          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
311          (setq keymap (symbol-value (car keymap)))))
312   (let (key)
313     (while plist
314       (when (symbolp (setq key (pop plist)))
315         (setq key (symbol-value key)))
316       (if (or (not safe)
317               (eq (lookup-key keymap key) 'undefined))
318           (define-key keymap key (pop plist))
319         (pop plist)))))
320
321 (defun gnus-completing-read-with-default (default prompt &rest args)
322   ;; Like `completing-read', except that DEFAULT is the default argument.
323   (let* ((prompt (if default
324                      (concat prompt " (default " default "): ")
325                    (concat prompt ": ")))
326          (answer (apply 'completing-read prompt args)))
327     (if (or (null answer) (zerop (length answer)))
328         default
329       answer)))
330
331 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
332 ;; the echo area.
333 ;;
334 ;; Do we really need these aliases?  Workarounds for bugs in the corresponding
335 ;; Emacs functions?  Maybe these bug are no longer present in any supported
336 ;; (X)Emacs version?  Alias them to the original functions and see if anyone
337 ;; reports a problem.  If not, replace with original functions.  --rsteib
338 ;;
339 ;; (defun gnus-y-or-n-p (prompt)
340 ;;   (prog1
341 ;;       (y-or-n-p prompt)
342 ;;     (message "")))
343 ;; (defun gnus-yes-or-no-p (prompt)
344 ;;   (prog1
345 ;;       (yes-or-no-p prompt)
346 ;;     (message "")))
347
348 (defalias 'gnus-y-or-n-p 'y-or-n-p)
349 (defalias 'gnus-yes-or-no-p 'yes-or-no-p)
350
351 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
352 ;; age-depending date representations. (e.g. just the time if it's
353 ;; from today, the day of the week if it's within the last 7 days and
354 ;; the full date if it's older)
355
356 (defun gnus-seconds-today ()
357   "Return the number of seconds passed today."
358   (let ((now (decode-time (current-time))))
359     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
360
361 (defun gnus-seconds-month ()
362   "Return the number of seconds passed this month."
363   (let ((now (decode-time (current-time))))
364     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
365        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
366
367 (defun gnus-seconds-year ()
368   "Return the number of seconds passed this year."
369   (let ((now (decode-time (current-time)))
370         (days (format-time-string "%j" (current-time))))
371     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
372        (* (- (string-to-number days) 1) 3600 24))))
373
374 (defvar gnus-user-date-format-alist
375   '(((gnus-seconds-today) . "%k:%M")
376     (604800 . "%a %k:%M")                   ;;that's one week
377     ((gnus-seconds-month) . "%a %d")
378     ((gnus-seconds-year) . "%b %d")
379     (t . "%b %d '%y"))                      ;;this one is used when no
380                                             ;;other does match
381   "Specifies date format depending on age of article.
382 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
383 seconds) or a Lisp expression evaluating to a number.  When the age of
384 the article is less than this number, then use `format-time-string'
385 with the corresponding FORMAT for displaying the date of the article.
386 If AGE is not a number or a Lisp expression evaluating to a
387 non-number, then the corresponding FORMAT is used as a default value.
388
389 Note that the list is processed from the beginning, so it should be
390 sorted by ascending AGE.  Also note that items following the first
391 non-number AGE will be ignored.
392
393 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
394 and `gnus-seconds-year' in the AGE spec.  They return the number of
395 seconds passed since the start of today, of this month, of this year,
396 respectively.")
397
398 (defun gnus-user-date (messy-date)
399   "Format the messy-date according to gnus-user-date-format-alist.
400 Returns \"  ?  \" if there's bad input or if an other error occurs.
401 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
402   (condition-case ()
403       (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
404              (now (time-to-seconds (current-time)))
405              ;;If we don't find something suitable we'll use this one
406              (my-format "%b %d '%y"))
407         (let* ((difference (- now messy-date))
408                (templist gnus-user-date-format-alist)
409                (top (eval (caar templist))))
410           (while (if (numberp top) (< top difference) (not top))
411             (progn
412               (setq templist (cdr templist))
413               (setq top (eval (caar templist)))))
414           (if (stringp (cdr (car templist)))
415               (setq my-format (cdr (car templist)))))
416         (format-time-string (eval my-format) (seconds-to-time messy-date)))
417     (error "  ?   ")))
418
419 (defun gnus-dd-mmm (messy-date)
420   "Return a string like DD-MMM from a big messy string."
421   (condition-case ()
422       (format-time-string "%d-%b" (safe-date-to-time messy-date))
423     (error "  -   ")))
424
425 (defmacro gnus-date-get-time (date)
426   "Convert DATE string to Emacs time.
427 Cache the result as a text property stored in DATE."
428   ;; Either return the cached value...
429   `(let ((d ,date))
430      (if (equal "" d)
431          '(0 0)
432        (or (get-text-property 0 'gnus-time d)
433            ;; or compute the value...
434            (let ((time (safe-date-to-time d)))
435              ;; and store it back in the string.
436              (put-text-property 0 1 'gnus-time time d)
437              time)))))
438
439 (defsubst gnus-time-iso8601 (time)
440   "Return a string of TIME in YYYYMMDDTHHMMSS format."
441   (format-time-string "%Y%m%dT%H%M%S" time))
442
443 (defun gnus-date-iso8601 (date)
444   "Convert the DATE to YYYYMMDDTHHMMSS."
445   (condition-case ()
446       (gnus-time-iso8601 (gnus-date-get-time date))
447     (error "")))
448
449 (defun gnus-mode-string-quote (string)
450   "Quote all \"%\"'s in STRING."
451   (gnus-replace-in-string string "%" "%%"))
452
453 ;; Make a hash table (default and minimum size is 256).
454 ;; Optional argument HASHSIZE specifies the table size.
455 (defun gnus-make-hashtable (&optional hashsize)
456   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
457
458 ;; Make a number that is suitable for hashing; bigger than MIN and
459 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
460 ;; hardware modulo operation, so they implement it in software.  On
461 ;; many sparcs over 50% of the time to intern is spent in the modulo.
462 ;; Yes, it's slower than actually computing the hash from the string!
463 ;; So we use powers of 2 so people can optimize the modulo to a mask.
464 (defun gnus-create-hash-size (min)
465   (let ((i 1))
466     (while (< i min)
467       (setq i (* 2 i)))
468     i))
469
470 (defcustom gnus-verbose 7
471   "*Integer that says how verbose Gnus should be.
472 The higher the number, the more messages Gnus will flash to say what
473 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
474 display most important messages; and at ten, Gnus will keep on
475 jabbering all the time."
476   :group 'gnus-start
477   :type 'integer)
478
479 (defcustom gnus-add-timestamp-to-message nil
480   "Non-nil means add timestamps to messages that Gnus issues.
481 If it is `log', add timestamps to only the messages that go into the
482 \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
483 If it is neither nil nor `log', add timestamps not only to log messages
484 but also to the ones displayed in the echo area."
485   :version "23.0" ;; No Gnus
486   :group  'gnus-various
487   :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
488                  (const :tag "Logged messages only" log)
489                  (sexp :tag "All messages"
490                        :match (lambda (widget value) value)
491                        :value t)
492                  (const :tag "No timestamp" nil)))
493
494 (eval-when-compile
495   (defmacro gnus-message-with-timestamp-1 (format-string args)
496     (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
497                        "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
498       (if (featurep 'xemacs)
499           `(let (str time)
500              (if (or (and (null ,format-string) (null ,args))
501                      (progn
502                        (setq str (apply 'format ,format-string ,args))
503                        (zerop (length str))))
504                  (prog1
505                      (and ,format-string str)
506                    (clear-message nil))
507                (cond ((eq gnus-add-timestamp-to-message 'log)
508                       (setq time (current-time))
509                       (display-message 'no-log str)
510                       (log-message 'message (concat ,@timestamp str)))
511                      (gnus-add-timestamp-to-message
512                       (setq time (current-time))
513                       (display-message 'message (concat ,@timestamp str)))
514                      (t
515                       (display-message 'message str))))
516              str)
517         `(let (str time)
518            (cond ((eq gnus-add-timestamp-to-message 'log)
519                   (setq str (let (message-log-max)
520                               (apply 'message ,format-string ,args)))
521                   (when (and message-log-max
522                              (> message-log-max 0)
523                              (/= (length str) 0))
524                     (setq time (current-time))
525                     (with-current-buffer (get-buffer-create "*Messages*")
526                       (goto-char (point-max))
527                       (insert ,@timestamp str "\n")
528                       (forward-line (- message-log-max))
529                       (delete-region (point-min) (point))
530                       (goto-char (point-max))))
531                   str)
532                  (gnus-add-timestamp-to-message
533                   (if (or (and (null ,format-string) (null ,args))
534                           (progn
535                             (setq str (apply 'format ,format-string ,args))
536                             (zerop (length str))))
537                       (prog1
538                           (and ,format-string str)
539                         (message nil))
540                     (setq time (current-time))
541                     (message "%s" (concat ,@timestamp str))
542                     str))
543                  (t
544                   (apply 'message ,format-string ,args))))))))
545
546 (defun gnus-message-with-timestamp (format-string &rest args)
547   "Display message with timestamp.  Arguments are the same as `message'.
548 The `gnus-add-timestamp-to-message' variable controls how to add
549 timestamp to message."
550   (gnus-message-with-timestamp-1 format-string args))
551
552 (defun gnus-message (level &rest args)
553   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
554
555 Guideline for numbers:
556 1 - error messages, 3 - non-serious error messages, 5 - messages for things
557 that take a long time, 7 - not very important messages on stuff, 9 - messages
558 inside loops."
559   (if (<= level gnus-verbose)
560       (if gnus-add-timestamp-to-message
561           (apply 'gnus-message-with-timestamp args)
562         (apply 'message args))
563     ;; We have to do this format thingy here even if the result isn't
564     ;; shown - the return value has to be the same as the return value
565     ;; from `message'.
566     (apply 'format args)))
567
568 (defun gnus-error (level &rest args)
569   "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
570 ARGS are passed to `message'."
571   (when (<= (floor level) gnus-verbose)
572     (apply 'message args)
573     (ding)
574     (let (duration)
575       (when (and (floatp level)
576                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
577         (sit-for duration))))
578   nil)
579
580 (defun gnus-split-references (references)
581   "Return a list of Message-IDs in REFERENCES."
582   (let ((beg 0)
583         (references (or references ""))
584         ids)
585     (while (string-match "<[^<]+[^< \t]" references beg)
586       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
587             ids))
588     (nreverse ids)))
589
590 (defun gnus-extract-references (references)
591   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
592   format), trimmed to only contain the Message-IDs."
593   (let ((ids (gnus-split-references references))
594         refs)
595     (dolist (id ids)
596       (when (string-match "<[^<>]+>" id)
597         (push (match-string 0 id) refs)))
598     refs))
599
600 (defsubst gnus-parent-id (references &optional n)
601   "Return the last Message-ID in REFERENCES.
602 If N, return the Nth ancestor instead."
603   (when (and references
604              (not (zerop (length references))))
605     (if n
606         (let ((ids (inline (gnus-split-references references))))
607           (while (nthcdr n ids)
608             (setq ids (cdr ids)))
609           (car ids))
610       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
611         (match-string 1 references)))))
612
613 (defun gnus-buffer-live-p (buffer)
614   "Say whether BUFFER is alive or not."
615   (and buffer
616        (get-buffer buffer)
617        (buffer-name (get-buffer buffer))))
618
619 (defun gnus-horizontal-recenter ()
620   "Recenter the current buffer horizontally."
621   (if (< (current-column) (/ (window-width) 2))
622       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
623     (let* ((orig (point))
624            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
625            (max 0))
626       (when end
627         ;; Find the longest line currently displayed in the window.
628         (goto-char (window-start))
629         (while (and (not (eobp))
630                     (< (point) end))
631           (end-of-line)
632           (setq max (max max (current-column)))
633           (forward-line 1))
634         (goto-char orig)
635         ;; Scroll horizontally to center (sort of) the point.
636         (if (> max (window-width))
637             (set-window-hscroll
638              (gnus-get-buffer-window (current-buffer) t)
639              (min (- (current-column) (/ (window-width) 3))
640                   (+ 2 (- max (window-width)))))
641           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
642         max))))
643
644 (defun gnus-read-event-char (&optional prompt)
645   "Get the next event."
646   (let ((event (read-event prompt)))
647     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
648     (cons (and (numberp event) event) event)))
649
650 (defun gnus-sortable-date (date)
651   "Make string suitable for sorting from DATE."
652   (gnus-time-iso8601 (date-to-time date)))
653
654 (defun gnus-copy-file (file &optional to)
655   "Copy FILE to TO."
656   (interactive
657    (list (read-file-name "Copy file: " default-directory)
658          (read-file-name "Copy file to: " default-directory)))
659   (unless to
660     (setq to (read-file-name "Copy file to: " default-directory)))
661   (when (file-directory-p to)
662     (setq to (concat (file-name-as-directory to)
663                      (file-name-nondirectory file))))
664   (copy-file file to))
665
666 (defvar gnus-work-buffer " *gnus work*")
667
668 (defun gnus-set-work-buffer ()
669   "Put point in the empty Gnus work buffer."
670   (if (get-buffer gnus-work-buffer)
671       (progn
672         (set-buffer gnus-work-buffer)
673         (erase-buffer))
674     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
675     (kill-all-local-variables)
676     (mm-enable-multibyte)))
677
678 (defmacro gnus-group-real-name (group)
679   "Find the real name of a foreign newsgroup."
680   `(let ((gname ,group))
681      (if (string-match "^[^:]+:" gname)
682          (substring gname (match-end 0))
683        gname)))
684
685 (defmacro gnus-group-server (group)
686   "Find the server name of a foreign newsgroup.
687 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
688 yield \"nnimap:yxa\"."
689   `(let ((gname ,group))
690      (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
691          (format "%s:%s" (match-string 1 gname) (or
692                                                  (match-string 2 gname)
693                                                  ""))
694        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
695
696 (defun gnus-make-sort-function (funs)
697   "Return a composite sort condition based on the functions in FUNS."
698   (cond
699    ;; Just a simple function.
700    ((functionp funs) funs)
701    ;; No functions at all.
702    ((null funs) funs)
703    ;; A list of functions.
704    ((or (cdr funs)
705         (listp (car funs)))
706     (gnus-byte-compile
707      `(lambda (t1 t2)
708         ,(gnus-make-sort-function-1 (reverse funs)))))
709    ;; A list containing just one function.
710    (t
711     (car funs))))
712
713 (defun gnus-make-sort-function-1 (funs)
714   "Return a composite sort condition based on the functions in FUNS."
715   (let ((function (car funs))
716         (first 't1)
717         (last 't2))
718     (when (consp function)
719       (cond
720        ;; Reversed spec.
721        ((eq (car function) 'not)
722         (setq function (cadr function)
723               first 't2
724               last 't1))
725        ((functionp function)
726         ;; Do nothing.
727         )
728        (t
729         (error "Invalid sort spec: %s" function))))
730     (if (cdr funs)
731         `(or (,function ,first ,last)
732              (and (not (,function ,last ,first))
733                   ,(gnus-make-sort-function-1 (cdr funs))))
734       `(,function ,first ,last))))
735
736 (defun gnus-turn-off-edit-menu (type)
737   "Turn off edit menu in `gnus-TYPE-mode-map'."
738   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
739     [menu-bar edit] 'undefined))
740
741 (defmacro gnus-bind-print-variables (&rest forms)
742   "Bind print-* variables and evaluate FORMS.
743 This macro is used with `prin1', `pp', etc. in order to ensure printed
744 Lisp objects are loadable.  Bind `print-quoted' and `print-readably'
745 to t, and `print-escape-multibyte', `print-escape-newlines',
746 `print-escape-nonascii', `print-length', `print-level' and
747 `print-string-length' to nil."
748   `(let ((print-quoted t)
749          (print-readably t)
750          ;;print-circle
751          ;;print-continuous-numbering
752          print-escape-multibyte
753          print-escape-newlines
754          print-escape-nonascii
755          ;;print-gensym
756          print-length
757          print-level
758          print-string-length)
759      ,@forms))
760
761 (defun gnus-prin1 (form)
762   "Use `prin1' on FORM in the current buffer.
763 Bind `print-quoted' and `print-readably' to t, and `print-length' and
764 `print-level' to nil.  See also `gnus-bind-print-variables'."
765   (gnus-bind-print-variables (prin1 form (current-buffer))))
766
767 (defun gnus-prin1-to-string (form)
768   "The same as `prin1'.
769 Bind `print-quoted' and `print-readably' to t, and `print-length' and
770 `print-level' to nil.  See also `gnus-bind-print-variables'."
771   (gnus-bind-print-variables (prin1-to-string form)))
772
773 (defun gnus-pp (form &optional stream)
774   "Use `pp' on FORM in the current buffer.
775 Bind `print-quoted' and `print-readably' to t, and `print-length' and
776 `print-level' to nil.  See also `gnus-bind-print-variables'."
777   (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
778
779 (defun gnus-pp-to-string (form)
780   "The same as `pp-to-string'.
781 Bind `print-quoted' and `print-readably' to t, and `print-length' and
782 `print-level' to nil.  See also `gnus-bind-print-variables'."
783   (gnus-bind-print-variables (pp-to-string form)))
784
785 (defun gnus-make-directory (directory)
786   "Make DIRECTORY (and all its parents) if it doesn't exist."
787   (require 'nnmail)
788   (let ((file-name-coding-system nnmail-pathname-coding-system))
789     (when (and directory
790                (not (file-exists-p directory)))
791       (make-directory directory t)))
792   t)
793
794 (defun gnus-write-buffer (file)
795   "Write the current buffer's contents to FILE."
796   (let ((file-name-coding-system nnmail-pathname-coding-system))
797     ;; Make sure the directory exists.
798     (gnus-make-directory (file-name-directory file))
799     ;; Write the buffer.
800     (write-region (point-min) (point-max) file nil 'quietly)))
801
802 (defun gnus-delete-file (file)
803   "Delete FILE if it exists."
804   (when (file-exists-p file)
805     (delete-file file)))
806
807 (defun gnus-delete-directory (directory)
808   "Delete files in DIRECTORY.  Subdirectories remain.
809 If there's no subdirectory, delete DIRECTORY as well."
810   (when (file-directory-p directory)
811     (let ((files (directory-files
812                   directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
813           file dir)
814       (while files
815         (setq file (pop files))
816         (if (eq t (car (file-attributes file)))
817             ;; `file' is a subdirectory.
818             (setq dir t)
819           ;; `file' is a file or a symlink.
820           (delete-file file)))
821       (unless dir
822         (delete-directory directory)))))
823
824 ;; The following two functions are used in gnus-registry.
825 ;; They were contributed by Andreas Fuchs <asf@void.at>.
826 (defun gnus-alist-to-hashtable (alist)
827   "Build a hashtable from the values in ALIST."
828   (let ((ht (make-hash-table
829              :size 4096
830              :test 'equal)))
831     (mapc
832      (lambda (kv-pair)
833        (puthash (car kv-pair) (cdr kv-pair) ht))
834      alist)
835      ht))
836
837 (defun gnus-hashtable-to-alist (hash)
838   "Build an alist from the values in HASH."
839   (let ((list nil))
840     (maphash
841      (lambda (key value)
842        (setq list (cons (cons key value) list)))
843      hash)
844     list))
845
846 (defun gnus-strip-whitespace (string)
847   "Return STRING stripped of all whitespace."
848   (while (string-match "[\r\n\t ]+" string)
849     (setq string (replace-match "" t t string)))
850   string)
851
852 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
853   "The same as `put-text-property', but don't put this prop on any newlines in the region."
854   (save-match-data
855     (save-excursion
856       (save-restriction
857         (goto-char beg)
858         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
859           (gnus-put-text-property beg (match-beginning 0) prop val)
860           (setq beg (point)))
861         (gnus-put-text-property beg (point) prop val)))))
862
863 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
864   "The same as `put-text-property', but don't put this prop on any newlines in the region."
865   (save-match-data
866     (save-excursion
867       (save-restriction
868         (goto-char beg)
869         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
870           (gnus-overlay-put
871            (gnus-make-overlay beg (match-beginning 0))
872            prop val)
873           (setq beg (point)))
874         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
875
876 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
877                                                                    prop val)
878   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
879   (let ((b beg))
880     (while (/= b end)
881       (when (get-text-property b 'gnus-face)
882         (setq b (next-single-property-change b 'gnus-face nil end)))
883       (when (/= b end)
884         (inline
885           (gnus-put-text-property
886            b (setq b (next-single-property-change b 'gnus-face nil end))
887            prop val))))))
888
889 (defmacro gnus-faces-at (position)
890   "Return a list of faces at POSITION."
891   (if (featurep 'xemacs)
892       `(let ((pos ,position))
893          (mapcar-extents 'extent-face
894                          nil (current-buffer) pos pos nil 'face))
895     `(let ((pos ,position))
896        (delq nil (cons (get-text-property pos 'face)
897                        (mapcar
898                         (lambda (overlay)
899                           (overlay-get overlay 'face))
900                         (overlays-at pos)))))))
901
902 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
903 ;;; The primary idea here is to try to protect internal datastructures
904 ;;; from becoming corrupted when the user hits C-g, or if a hook or
905 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
906 ;;; updated at the same time, or information can be lost.
907
908 (defvar gnus-atomic-be-safe t
909   "If t, certain operations will be protected from interruption by C-g.")
910
911 (defmacro gnus-atomic-progn (&rest forms)
912   "Evaluate FORMS atomically, which means to protect the evaluation
913 from being interrupted by the user.  An error from the forms themselves
914 will return without finishing the operation.  Since interrupts from
915 the user are disabled, it is recommended that only the most minimal
916 operations are performed by FORMS.  If you wish to assign many
917 complicated values atomically, compute the results into temporary
918 variables and then do only the assignment atomically."
919   `(let ((inhibit-quit gnus-atomic-be-safe))
920      ,@forms))
921
922 (put 'gnus-atomic-progn 'lisp-indent-function 0)
923
924 (defmacro gnus-atomic-progn-assign (protect &rest forms)
925   "Evaluate FORMS, but insure that the variables listed in PROTECT
926 are not changed if anything in FORMS signals an error or otherwise
927 non-locally exits.  The variables listed in PROTECT are updated atomically.
928 It is safe to use gnus-atomic-progn-assign with long computations.
929
930 Note that if any of the symbols in PROTECT were unbound, they will be
931 set to nil on a successful assignment.  In case of an error or other
932 non-local exit, it will still be unbound."
933   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
934                                                   (concat (symbol-name x)
935                                                           "-tmp"))
936                                                  x))
937                                protect))
938          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
939                                temp-sym-map))
940          (temp-sym-let (mapcar (lambda (x) (list (car x)
941                                                  `(and (boundp ',(cadr x))
942                                                        ,(cadr x))))
943                                temp-sym-map))
944          (sym-temp-let sym-temp-map)
945          (temp-sym-assign (apply 'append temp-sym-map))
946          (sym-temp-assign (apply 'append sym-temp-map))
947          (result (make-symbol "result-tmp")))
948     `(let (,@temp-sym-let
949            ,result)
950        (let ,sym-temp-let
951          (setq ,result (progn ,@forms))
952          (setq ,@temp-sym-assign))
953        (let ((inhibit-quit gnus-atomic-be-safe))
954          (setq ,@sym-temp-assign))
955        ,result)))
956
957 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
958 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
959
960 (defmacro gnus-atomic-setq (&rest pairs)
961   "Similar to setq, except that the real symbols are only assigned when
962 there are no errors.  And when the real symbols are assigned, they are
963 done so atomically.  If other variables might be changed via side-effect,
964 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
965 with potentially long computations."
966   (let ((tpairs pairs)
967         syms)
968     (while tpairs
969       (push (car tpairs) syms)
970       (setq tpairs (cddr tpairs)))
971     `(gnus-atomic-progn-assign ,syms
972        (setq ,@pairs))))
973
974 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
975
976
977 ;;; Functions for saving to babyl/mail files.
978
979 (eval-when-compile
980   (condition-case nil
981       (progn
982         (require 'rmail)
983         (autoload 'rmail-update-summary "rmailsum"))
984     (error
985      (define-compiler-macro rmail-select-summary (&rest body)
986        ;; Rmail of the XEmacs version is supplied by the package, and
987        ;; requires tm and apel packages.  However, there may be those
988        ;; who haven't installed those packages.  This macro helps such
989        ;; people even if they install those packages later.
990        `(eval '(rmail-select-summary ,@body)))
991      ;; If there's rmail but there's no tm (or there's apel of the
992      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
993      ;; version fails halfway, however it provides the rmail-select-summary
994      ;; macro which uses the following functions:
995      (autoload 'rmail-summary-displayed "rmail")
996      (autoload 'rmail-maybe-display-summary "rmail"))))
997
998 (defvar rmail-default-rmail-file)
999 (defvar mm-text-coding-system)
1000
1001 (declare-function mm-append-to-file "mm-util"
1002                   (start end filename &optional codesys inhibit))
1003
1004 (defun gnus-output-to-rmail (filename &optional ask)
1005   "Append the current article to an Rmail file named FILENAME."
1006   (require 'rmail)
1007   (require 'mm-util)
1008   ;; Most of these codes are borrowed from rmailout.el.
1009   (setq filename (expand-file-name filename))
1010   (setq rmail-default-rmail-file filename)
1011   (let ((artbuf (current-buffer))
1012         (tmpbuf (get-buffer-create " *Gnus-output*")))
1013     (save-excursion
1014       (or (get-file-buffer filename)
1015           (file-exists-p filename)
1016           (if (or (not ask)
1017                   (gnus-yes-or-no-p
1018                    (concat "\"" filename "\" does not exist, create it? ")))
1019               (let ((file-buffer (create-file-buffer filename)))
1020                 (save-excursion
1021                   (set-buffer file-buffer)
1022                   (rmail-insert-rmail-file-header)
1023                   (let ((require-final-newline nil)
1024                         (coding-system-for-write mm-text-coding-system))
1025                     (gnus-write-buffer filename)))
1026                 (kill-buffer file-buffer))
1027             (error "Output file does not exist")))
1028       (set-buffer tmpbuf)
1029       (erase-buffer)
1030       (insert-buffer-substring artbuf)
1031       (gnus-convert-article-to-rmail)
1032       ;; Decide whether to append to a file or to an Emacs buffer.
1033       (let ((outbuf (get-file-buffer filename)))
1034         (if (not outbuf)
1035             (let ((file-name-coding-system nnmail-pathname-coding-system))
1036               (mm-append-to-file (point-min) (point-max) filename))
1037           ;; File has been visited, in buffer OUTBUF.
1038           (set-buffer outbuf)
1039           (let ((buffer-read-only nil)
1040                 (msg (and (boundp 'rmail-current-message)
1041                           (symbol-value 'rmail-current-message))))
1042             ;; If MSG is non-nil, buffer is in RMAIL mode.
1043             (when msg
1044               (widen)
1045               (narrow-to-region (point-max) (point-max)))
1046             (insert-buffer-substring tmpbuf)
1047             (when msg
1048               (goto-char (point-min))
1049               (widen)
1050               (search-backward "\n\^_")
1051               (narrow-to-region (point) (point-max))
1052               (rmail-count-new-messages t)
1053               (when (rmail-summary-exists)
1054                 (rmail-select-summary
1055                  (rmail-update-summary)))
1056               (rmail-count-new-messages t)
1057               (rmail-show-message msg))
1058             (save-buffer)))))
1059     (kill-buffer tmpbuf)))
1060
1061 (defun gnus-output-to-mail (filename &optional ask)
1062   "Append the current article to a mail file named FILENAME."
1063   (setq filename (expand-file-name filename))
1064   (let ((artbuf (current-buffer))
1065         (tmpbuf (get-buffer-create " *Gnus-output*")))
1066     (save-excursion
1067       ;; Create the file, if it doesn't exist.
1068       (when (and (not (get-file-buffer filename))
1069                  (not (file-exists-p filename)))
1070         (if (or (not ask)
1071                 (gnus-y-or-n-p
1072                  (concat "\"" filename "\" does not exist, create it? ")))
1073             (let ((file-buffer (create-file-buffer filename)))
1074               (save-excursion
1075                 (set-buffer file-buffer)
1076                 (let ((require-final-newline nil)
1077                       (coding-system-for-write mm-text-coding-system))
1078                   (gnus-write-buffer filename)))
1079               (kill-buffer file-buffer))
1080           (error "Output file does not exist")))
1081       (set-buffer tmpbuf)
1082       (erase-buffer)
1083       (insert-buffer-substring artbuf)
1084       (goto-char (point-min))
1085       (if (looking-at "From ")
1086           (forward-line 1)
1087         (insert "From nobody " (current-time-string) "\n"))
1088       (let (case-fold-search)
1089         (while (re-search-forward "^From " nil t)
1090           (beginning-of-line)
1091           (insert ">")))
1092       ;; Decide whether to append to a file or to an Emacs buffer.
1093       (let ((outbuf (get-file-buffer filename)))
1094         (if (not outbuf)
1095             (let ((buffer-read-only nil))
1096               (save-excursion
1097                 (goto-char (point-max))
1098                 (forward-char -2)
1099                 (unless (looking-at "\n\n")
1100                   (goto-char (point-max))
1101                   (unless (bolp)
1102                     (insert "\n"))
1103                   (insert "\n"))
1104                 (goto-char (point-max))
1105                 (let ((file-name-coding-system nnmail-pathname-coding-system))
1106                   (mm-append-to-file (point-min) (point-max) filename))))
1107           ;; File has been visited, in buffer OUTBUF.
1108           (set-buffer outbuf)
1109           (let ((buffer-read-only nil))
1110             (goto-char (point-max))
1111             (unless (eobp)
1112               (insert "\n"))
1113             (insert "\n")
1114             (insert-buffer-substring tmpbuf)))))
1115     (kill-buffer tmpbuf)))
1116
1117 (defun gnus-convert-article-to-rmail ()
1118   "Convert article in current buffer to Rmail message format."
1119   (let ((buffer-read-only nil))
1120     ;; Convert article directly into Babyl format.
1121     (goto-char (point-min))
1122     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1123     (while (search-forward "\n\^_" nil t) ;single char
1124       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
1125     (goto-char (point-max))
1126     (insert "\^_")))
1127
1128 (defun gnus-map-function (funs arg)
1129   "Apply the result of the first function in FUNS to the second, and so on.
1130 ARG is passed to the first function."
1131   (while funs
1132     (setq arg (funcall (pop funs) arg)))
1133   arg)
1134
1135 (defun gnus-run-hooks (&rest funcs)
1136   "Does the same as `run-hooks', but saves the current buffer."
1137   (save-current-buffer
1138     (apply 'run-hooks funcs)))
1139
1140 (defun gnus-run-mode-hooks (&rest funcs)
1141   "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1142 This function saves the current buffer."
1143   (if (fboundp 'run-mode-hooks)
1144       (save-current-buffer (apply 'run-mode-hooks funcs))
1145     (save-current-buffer (apply 'run-hooks funcs))))
1146
1147 ;;; Various
1148
1149 (defvar gnus-group-buffer)              ; Compiler directive
1150 (defun gnus-alive-p ()
1151   "Say whether Gnus is running or not."
1152   (and (boundp 'gnus-group-buffer)
1153        (get-buffer gnus-group-buffer)
1154        (save-excursion
1155          (set-buffer gnus-group-buffer)
1156          (eq major-mode 'gnus-group-mode))))
1157
1158 (defun gnus-remove-if (predicate list)
1159   "Return a copy of LIST with all items satisfying PREDICATE removed."
1160   (let (out)
1161     (while list
1162       (unless (funcall predicate (car list))
1163         (push (car list) out))
1164       (setq list (cdr list)))
1165     (nreverse out)))
1166
1167 (if (fboundp 'assq-delete-all)
1168     (defalias 'gnus-delete-alist 'assq-delete-all)
1169   (defun gnus-delete-alist (key alist)
1170     "Delete from ALIST all elements whose car is KEY.
1171 Return the modified alist."
1172     (let (entry)
1173       (while (setq entry (assq key alist))
1174         (setq alist (delq entry alist)))
1175       alist)))
1176
1177 (defmacro gnus-pull (key alist &optional assoc-p)
1178   "Modify ALIST to be without KEY."
1179   (unless (symbolp alist)
1180     (error "Not a symbol: %s" alist))
1181   (let ((fun (if assoc-p 'assoc 'assq)))
1182     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1183
1184 (defun gnus-globalify-regexp (re)
1185   "Return a regexp that matches a whole line, if RE matches a part of it."
1186   (concat (unless (string-match "^\\^" re) "^.*")
1187           re
1188           (unless (string-match "\\$$" re) ".*$")))
1189
1190 (defun gnus-set-window-start (&optional point)
1191   "Set the window start to POINT, or (point) if nil."
1192   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1193     (when win
1194       (set-window-start win (or point (point))))))
1195
1196 (defun gnus-annotation-in-region-p (b e)
1197   (if (= b e)
1198       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1199     (text-property-any b e 'gnus-undeletable t)))
1200
1201 (defun gnus-or (&rest elems)
1202   "Return non-nil if any of the elements are non-nil."
1203   (catch 'found
1204     (while elems
1205       (when (pop elems)
1206         (throw 'found t)))))
1207
1208 (defun gnus-and (&rest elems)
1209   "Return non-nil if all of the elements are non-nil."
1210   (catch 'found
1211     (while elems
1212       (unless (pop elems)
1213         (throw 'found nil)))
1214     t))
1215
1216 (defun gnus-write-active-file (file hashtb &optional full-names)
1217   ;; `coding-system-for-write' should be `raw-text' or equivalent.
1218   (let ((coding-system-for-write nnmail-active-file-coding-system))
1219     (with-temp-file file
1220       ;; The buffer should be in the unibyte mode because group names
1221       ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1222       (mm-disable-multibyte)
1223       (mapatoms
1224        (lambda (sym)
1225          (when (and sym
1226                     (boundp sym)
1227                     (symbol-value sym))
1228            (insert (format "%S %d %d y\n"
1229                            (if full-names
1230                                sym
1231                              (intern (gnus-group-real-name (symbol-name sym))))
1232                            (or (cdr (symbol-value sym))
1233                                (car (symbol-value sym)))
1234                            (car (symbol-value sym))))))
1235        hashtb)
1236       (goto-char (point-max))
1237       (while (search-backward "\\." nil t)
1238         (delete-char 1)))))
1239
1240 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1241 (defmacro gnus-with-output-to-file (file &rest body)
1242   (let ((buffer (make-symbol "output-buffer"))
1243         (size (make-symbol "output-buffer-size"))
1244         (leng (make-symbol "output-buffer-length"))
1245         (append (make-symbol "output-buffer-append")))
1246     `(let* ((,size 131072)
1247             (,buffer (make-string ,size 0))
1248             (,leng 0)
1249             (,append nil)
1250             (standard-output
1251              (lambda (c)
1252                (aset ,buffer ,leng c)
1253
1254                (if (= ,size (setq ,leng (1+ ,leng)))
1255                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1256                           (setq ,leng 0
1257                                 ,append t))))))
1258        ,@body
1259        (when (> ,leng 0)
1260          (let ((coding-system-for-write 'no-conversion))
1261          (write-region (substring ,buffer 0 ,leng) nil ,file
1262                        ,append 'no-msg))))))
1263
1264 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1265 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1266
1267 (if (fboundp 'union)
1268     (defalias 'gnus-union 'union)
1269   (defun gnus-union (l1 l2)
1270     "Set union of lists L1 and L2."
1271     (cond ((null l1) l2)
1272           ((null l2) l1)
1273           ((equal l1 l2) l1)
1274           (t
1275            (or (>= (length l1) (length l2))
1276                (setq l1 (prog1 l2 (setq l2 l1))))
1277            (while l2
1278              (or (member (car l2) l1)
1279                  (push (car l2) l1))
1280              (pop l2))
1281            l1))))
1282
1283 (defun gnus-add-text-properties-when
1284   (property value start end properties &optional object)
1285   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1286   (let (point)
1287     (while (and start
1288                 (< start end) ;; XEmacs will loop for every when start=end.
1289                 (setq point (text-property-not-all start end property value)))
1290       (gnus-add-text-properties start point properties object)
1291       (setq start (text-property-any point end property value)))
1292     (if start
1293         (gnus-add-text-properties start end properties object))))
1294
1295 (defun gnus-remove-text-properties-when
1296   (property value start end properties &optional object)
1297   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1298   (let (point)
1299     (while (and start
1300                 (< start end)
1301                 (setq point (text-property-not-all start end property value)))
1302       (remove-text-properties start point properties object)
1303       (setq start (text-property-any point end property value)))
1304     (if start
1305         (remove-text-properties start end properties object))
1306     t))
1307
1308 (defun gnus-string-remove-all-properties (string)
1309   (condition-case ()
1310       (let ((s string))
1311         (set-text-properties 0 (length string) nil string)
1312         s)
1313     (error string)))
1314
1315 ;; This might use `compare-strings' to reduce consing in the
1316 ;; case-insensitive case, but it has to cope with null args.
1317 ;; (`string-equal' uses symbol print names.)
1318 (defun gnus-string-equal (x y)
1319   "Like `string-equal', except it compares case-insensitively."
1320   (and (= (length x) (length y))
1321        (or (string-equal x y)
1322            (string-equal (downcase x) (downcase y)))))
1323
1324 (defcustom gnus-use-byte-compile t
1325   "If non-nil, byte-compile crucial run-time code.
1326 Setting it to nil has no effect after the first time `gnus-byte-compile'
1327 is run."
1328   :type 'boolean
1329   :version "22.1"
1330   :group 'gnus-various)
1331
1332 (defun gnus-byte-compile (form)
1333   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1334   (if gnus-use-byte-compile
1335       (progn
1336         (condition-case nil
1337             ;; Work around a bug in XEmacs 21.4
1338             (require 'byte-optimize)
1339           (error))
1340         (require 'bytecomp)
1341         (defalias 'gnus-byte-compile
1342           (lambda (form)
1343             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1344               (byte-compile form))))
1345         (gnus-byte-compile form))
1346     form))
1347
1348 (defun gnus-remassoc (key alist)
1349   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1350 The modified LIST is returned.  If the first member
1351 of LIST has a car that is `equal' to KEY, there is no way to remove it
1352 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1353 sure of changing the value of `foo'."
1354   (when alist
1355     (if (equal key (caar alist))
1356         (cdr alist)
1357       (setcdr alist (gnus-remassoc key (cdr alist)))
1358       alist)))
1359
1360 (defun gnus-update-alist-soft (key value alist)
1361   (if value
1362       (cons (cons key value) (gnus-remassoc key alist))
1363     (gnus-remassoc key alist)))
1364
1365 (defun gnus-create-info-command (node)
1366   "Create a command that will go to info NODE."
1367   `(lambda ()
1368      (interactive)
1369      ,(concat "Enter the info system at node " node)
1370      (Info-goto-node ,node)
1371      (setq gnus-info-buffer (current-buffer))
1372      (gnus-configure-windows 'info)))
1373
1374 (defun gnus-not-ignore (&rest args)
1375   t)
1376
1377 (defvar gnus-directory-sep-char-regexp "/"
1378   "The regexp of directory separator character.
1379 If you find some problem with the directory separator character, try
1380 \"[/\\\\\]\" for some systems.")
1381
1382 (defun gnus-url-unhex (x)
1383   (if (> x ?9)
1384       (if (>= x ?a)
1385           (+ 10 (- x ?a))
1386         (+ 10 (- x ?A)))
1387     (- x ?0)))
1388
1389 ;; Fixme: Do it like QP.
1390 (defun gnus-url-unhex-string (str &optional allow-newlines)
1391   "Remove %XX, embedded spaces, etc in a url.
1392 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1393 decoding of carriage returns and line feeds in the string, which is normally
1394 forbidden in URL encoding."
1395   (let ((tmp "")
1396         (case-fold-search t))
1397     (while (string-match "%[0-9a-f][0-9a-f]" str)
1398       (let* ((start (match-beginning 0))
1399              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1400              (code (+ (* 16 ch1)
1401                       (gnus-url-unhex (elt str (+ start 2))))))
1402         (setq tmp (concat
1403                    tmp (substring str 0 start)
1404                    (cond
1405                     (allow-newlines
1406                      (char-to-string code))
1407                     ((or (= code ?\n) (= code ?\r))
1408                      " ")
1409                     (t (char-to-string code))))
1410               str (substring str (match-end 0)))))
1411     (setq tmp (concat tmp str))
1412     tmp))
1413
1414 (defun gnus-make-predicate (spec)
1415   "Transform SPEC into a function that can be called.
1416 SPEC is a predicate specifier that contains stuff like `or', `and',
1417 `not', lists and functions.  The functions all take one parameter."
1418   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1419
1420 (defun gnus-make-predicate-1 (spec)
1421   (cond
1422    ((symbolp spec)
1423     `(,spec elem))
1424    ((listp spec)
1425     (if (memq (car spec) '(or and not))
1426         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1427       (error "Invalid predicate specifier: %s" spec)))))
1428
1429 (defun gnus-completing-read (prompt table &optional predicate require-match
1430                                     history)
1431   (when (and history
1432              (not (boundp history)))
1433     (set history nil))
1434   (completing-read
1435    (if (symbol-value history)
1436        (concat prompt " (" (car (symbol-value history)) "): ")
1437      (concat prompt ": "))
1438    table
1439    predicate
1440    require-match
1441    nil
1442    history
1443    (car (symbol-value history))))
1444
1445 (defun gnus-graphic-display-p ()
1446   (or (and (fboundp 'display-graphic-p)
1447            (display-graphic-p))
1448       ;;;!!!This is bogus.  Fixme!
1449       (and (featurep 'xemacs)
1450            t)))
1451
1452 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1453 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1454
1455 (defmacro gnus-parse-without-error (&rest body)
1456   "Allow continuing onto the next line even if an error occurs."
1457   `(while (not (eobp))
1458      (condition-case ()
1459          (progn
1460            ,@body
1461            (goto-char (point-max)))
1462        (error
1463         (gnus-error 4 "Invalid data on line %d"
1464                     (count-lines (point-min) (point)))
1465         (forward-line 1)))))
1466
1467 (defun gnus-cache-file-contents (file variable function)
1468   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1469   (let ((time (nth 5 (file-attributes file)))
1470         contents value)
1471     (if (or (null (setq value (symbol-value variable)))
1472             (not (equal (car value) file))
1473             (not (equal (nth 1 value) time)))
1474         (progn
1475           (setq contents (funcall function file))
1476           (set variable (list file time contents))
1477           contents)
1478       (nth 2 value))))
1479
1480 (defun gnus-multiple-choice (prompt choice &optional idx)
1481   "Ask user a multiple choice question.
1482 CHOICE is a list of the choice char and help message at IDX."
1483   (let (tchar buf)
1484     (save-window-excursion
1485       (save-excursion
1486         (while (not tchar)
1487           (message "%s (%s): "
1488                    prompt
1489                    (concat
1490                     (mapconcat (lambda (s) (char-to-string (car s)))
1491                                choice ", ") ", ?"))
1492           (setq tchar (read-char))
1493           (when (not (assq tchar choice))
1494             (setq tchar nil)
1495             (setq buf (get-buffer-create "*Gnus Help*"))
1496             (pop-to-buffer buf)
1497             (fundamental-mode)          ; for Emacs 20.4+
1498             (buffer-disable-undo)
1499             (erase-buffer)
1500             (insert prompt ":\n\n")
1501             (let ((max -1)
1502                   (list choice)
1503                   (alist choice)
1504                   (idx (or idx 1))
1505                   (i 0)
1506                   n width pad format)
1507               ;; find the longest string to display
1508               (while list
1509                 (setq n (length (nth idx (car list))))
1510                 (unless (> max n)
1511                   (setq max n))
1512                 (setq list (cdr list)))
1513               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1514               (setq n (/ (1- (window-width)) max)) ; items per line
1515               (setq width (/ (1- (window-width)) n)) ; width of each item
1516               ;; insert `n' items, each in a field of width `width'
1517               (while alist
1518                 (if (< i n)
1519                     ()
1520                   (setq i 0)
1521                   (delete-char -1)              ; the `\n' takes a char
1522                   (insert "\n"))
1523                 (setq pad (- width 3))
1524                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1525                 (insert (format format (caar alist) (nth idx (car alist))))
1526                 (setq alist (cdr alist))
1527                 (setq i (1+ i))))))))
1528     (if (buffer-live-p buf)
1529         (kill-buffer buf))
1530     tchar))
1531
1532 (declare-function w32-focus-frame "../term/w32-win" (frame))
1533
1534 (defun gnus-select-frame-set-input-focus (frame)
1535   "Select FRAME, raise it, and set input focus, if possible."
1536   (cond ((featurep 'xemacs)
1537          (if (fboundp 'select-frame-set-input-focus)
1538              (select-frame-set-input-focus frame)
1539            (raise-frame frame)
1540            (select-frame frame)
1541            (focus-frame frame)))
1542         ;; `select-frame-set-input-focus' defined in Emacs 21 will not
1543         ;; set the input focus.
1544         ((>= emacs-major-version 22)
1545          (select-frame-set-input-focus frame))
1546         (t
1547          (raise-frame frame)
1548          (select-frame frame)
1549          (cond ((memq window-system '(x mac))
1550                 (x-focus-frame frame))
1551                ((eq window-system 'w32)
1552                 (w32-focus-frame frame)))
1553          (when focus-follows-mouse
1554            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1555
1556 (defun gnus-frame-or-window-display-name (object)
1557   "Given a frame or window, return the associated display name.
1558 Return nil otherwise."
1559   (if (featurep 'xemacs)
1560       (device-connection (dfw-device object))
1561     (if (or (framep object)
1562             (and (windowp object)
1563                  (setq object (window-frame object))))
1564         (let ((display (frame-parameter object 'display)))
1565           (if (and (stringp display)
1566                    ;; Exclude invalid display names.
1567                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1568                                  display))
1569               display)))))
1570
1571 (defvar tool-bar-mode)
1572
1573 (defun gnus-tool-bar-update (&rest ignore)
1574   "Update the tool bar."
1575   (when (and (boundp 'tool-bar-mode)
1576              tool-bar-mode)
1577     (let* ((args nil)
1578            (func (cond ((featurep 'xemacs)
1579                         'ignore)
1580                        ((fboundp 'tool-bar-update)
1581                         'tool-bar-update)
1582                        ((fboundp 'force-window-update)
1583                         'force-window-update)
1584                        ((fboundp 'redraw-frame)
1585                         (setq args (list (selected-frame)))
1586                         'redraw-frame)
1587                        (t 'ignore))))
1588       (apply func args))))
1589
1590 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1591 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1592   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1593 If there are several sequences, FUNCTION is called with that many arguments,
1594 and mapping stops as soon as the shortest sequence runs out.  With just one
1595 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1596 `mapcar' function extended to arbitrary sequence types."
1597
1598   (if seqs2_n
1599       (let* ((seqs (cons seq1 seqs2_n))
1600              (cnt 0)
1601              (heads (mapcar (lambda (seq)
1602                               (make-symbol (concat "head"
1603                                                    (int-to-string
1604                                                     (setq cnt (1+ cnt))))))
1605                             seqs))
1606              (result (make-symbol "result"))
1607              (result-tail (make-symbol "result-tail")))
1608         `(let* ,(let* ((bindings (cons nil nil))
1609                        (heads heads))
1610                   (nconc bindings (list (list result '(cons nil nil))))
1611                   (nconc bindings (list (list result-tail result)))
1612                   (while heads
1613                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1614                   (cdr bindings))
1615            (while (and ,@heads)
1616              (setcdr ,result-tail (cons (funcall ,function
1617                                                  ,@(mapcar (lambda (h) (list 'car h))
1618                                                            heads))
1619                                         nil))
1620              (setq ,result-tail (cdr ,result-tail)
1621                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1622            (cdr ,result)))
1623     `(mapcar ,function ,seq1)))
1624
1625 (if (fboundp 'merge)
1626     (defalias 'gnus-merge 'merge)
1627   ;; Adapted from cl-seq.el
1628   (defun gnus-merge (type list1 list2 pred)
1629     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1630 Argument TYPE is for compatibility and ignored.
1631 Ordering of the elements is preserved according to PRED, a `less-than'
1632 predicate on the elements."
1633     (let ((res nil))
1634       (while (and list1 list2)
1635         (if (funcall pred (car list2) (car list1))
1636             (push (pop list2) res)
1637           (push (pop list1) res)))
1638       (nconc (nreverse res) list1 list2))))
1639
1640 (defvar xemacs-codename)
1641 (defvar sxemacs-codename)
1642 (defvar emacs-program-version)
1643
1644 (defun gnus-emacs-version ()
1645   "Stringified Emacs version."
1646   (let* ((lst (if (listp gnus-user-agent)
1647                   gnus-user-agent
1648                 '(gnus emacs type)))
1649          (system-v (cond ((memq 'config lst)
1650                           system-configuration)
1651                          ((memq 'type lst)
1652                           (symbol-name system-type))
1653                          (t nil)))
1654          codename emacsname)
1655     (cond ((featurep 'sxemacs)
1656            (setq emacsname "SXEmacs"
1657                  codename sxemacs-codename))
1658           ((featurep 'xemacs)
1659            (setq emacsname "XEmacs"
1660                  codename xemacs-codename))
1661           (t
1662            (setq emacsname "Emacs")))
1663     (cond
1664      ((not (memq 'emacs lst))
1665       nil)
1666      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1667       ;; Emacs:
1668       (concat "Emacs/" (match-string 1 emacs-version)
1669               (if system-v
1670                   (concat " (" system-v ")")
1671                 "")))
1672      ((or (featurep 'sxemacs) (featurep 'xemacs))
1673       ;; XEmacs or SXEmacs:
1674       (concat emacsname "/" emacs-program-version
1675               (let (plst)
1676                 (when (memq 'codename lst)
1677                   (push codename plst))
1678                 (when system-v
1679                   (push system-v plst))
1680                 (unless (featurep 'mule)
1681                   (push "no MULE" plst))
1682                 (when (> (length plst) 0)
1683                   (concat
1684                    " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
1685      (t emacs-version))))
1686
1687 (defun gnus-rename-file (old-path new-path &optional trim)
1688   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1689 empty directories from OLD-PATH."
1690   (when (file-exists-p old-path)
1691     (let* ((old-dir (file-name-directory old-path))
1692            (old-name (file-name-nondirectory old-path))
1693            (new-dir (file-name-directory new-path))
1694            (new-name (file-name-nondirectory new-path))
1695            temp)
1696       (gnus-make-directory new-dir)
1697       (rename-file old-path new-path t)
1698       (when trim
1699         (while (progn (setq temp (directory-files old-dir))
1700                       (while (member (car temp) '("." ".."))
1701                         (setq temp (cdr temp)))
1702                       (= (length temp) 0))
1703           (delete-directory old-dir)
1704           (setq old-dir (file-name-as-directory
1705                          (file-truename
1706                           (concat old-dir "..")))))))))
1707
1708 (defun gnus-set-file-modes (filename mode)
1709   "Wrapper for set-file-modes."
1710   (ignore-errors
1711     (set-file-modes filename mode)))
1712
1713 (if (fboundp 'set-process-query-on-exit-flag)
1714     (defalias 'gnus-set-process-query-on-exit-flag
1715       'set-process-query-on-exit-flag)
1716   (defalias 'gnus-set-process-query-on-exit-flag
1717     'process-kill-without-query))
1718
1719 (if (fboundp 'with-local-quit)
1720     (defalias 'gnus-with-local-quit 'with-local-quit)
1721   (defmacro gnus-with-local-quit (&rest body)
1722     "Execute BODY, allowing quits to terminate BODY but not escape further.
1723 When a quit terminates BODY, `gnus-with-local-quit' returns nil but
1724 requests another quit.  That quit will be processed as soon as quitting
1725 is allowed once again.  (Immediately, if `inhibit-quit' is nil.)"
1726     ;;(declare (debug t) (indent 0))
1727     `(condition-case nil
1728          (let ((inhibit-quit nil))
1729            ,@body)
1730        (quit (setq quit-flag t)
1731              ;; This call is to give a chance to handle quit-flag
1732              ;; in case inhibit-quit is nil.
1733              ;; Without this, it will not be handled until the next function
1734              ;; call, and that might allow it to exit thru a condition-case
1735              ;; that intends to handle the quit signal next time.
1736              (eval '(ignore nil))))))
1737
1738 (provide 'gnus-util)
1739
1740 ;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
1741 ;;; gnus-util.el ends here