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