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