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