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