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