* gnus-util.el (gnus-split-references): accept a nil references
[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         (references (or references ""))
478         ids)
479     (while (string-match "<[^<]+[^< \t]" references beg)
480       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
481             ids))
482     (nreverse ids)))
483
484 (defun gnus-extract-references (references)
485   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
486   format), trimmed to only contain the Message-IDs."
487   (let ((ids (gnus-split-references references)) 
488         refs)
489     (dolist (id ids)
490       (when (string-match "<[^<>]+>" id)
491         (push (match-string 0 id) refs)))
492     refs))
493
494 (defsubst gnus-parent-id (references &optional n)
495   "Return the last Message-ID in REFERENCES.
496 If N, return the Nth ancestor instead."
497   (when (and references
498              (not (zerop (length references))))
499     (if n
500         (let ((ids (inline (gnus-split-references references))))
501           (while (nthcdr n ids)
502             (setq ids (cdr ids)))
503           (car ids))
504       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
505         (match-string 1 references)))))
506
507 (defun gnus-buffer-live-p (buffer)
508   "Say whether BUFFER is alive or not."
509   (and buffer
510        (get-buffer buffer)
511        (buffer-name (get-buffer buffer))))
512
513 (defun gnus-horizontal-recenter ()
514   "Recenter the current buffer horizontally."
515   (if (< (current-column) (/ (window-width) 2))
516       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
517     (let* ((orig (point))
518            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
519            (max 0))
520       (when end
521         ;; Find the longest line currently displayed in the window.
522         (goto-char (window-start))
523         (while (and (not (eobp))
524                     (< (point) end))
525           (end-of-line)
526           (setq max (max max (current-column)))
527           (forward-line 1))
528         (goto-char orig)
529         ;; Scroll horizontally to center (sort of) the point.
530         (if (> max (window-width))
531             (set-window-hscroll
532              (gnus-get-buffer-window (current-buffer) t)
533              (min (- (current-column) (/ (window-width) 3))
534                   (+ 2 (- max (window-width)))))
535           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
536         max))))
537
538 (defun gnus-read-event-char (&optional prompt)
539   "Get the next event."
540   (let ((event (read-event prompt)))
541     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
542     (cons (and (numberp event) event) event)))
543
544 (defun gnus-sortable-date (date)
545   "Make string suitable for sorting from DATE."
546   (gnus-time-iso8601 (date-to-time date)))
547
548 (defun gnus-copy-file (file &optional to)
549   "Copy FILE to TO."
550   (interactive
551    (list (read-file-name "Copy file: " default-directory)
552          (read-file-name "Copy file to: " default-directory)))
553   (unless to
554     (setq to (read-file-name "Copy file to: " default-directory)))
555   (when (file-directory-p to)
556     (setq to (concat (file-name-as-directory to)
557                      (file-name-nondirectory file))))
558   (copy-file file to))
559
560 (defvar gnus-work-buffer " *gnus work*")
561
562 (defun gnus-set-work-buffer ()
563   "Put point in the empty Gnus work buffer."
564   (if (get-buffer gnus-work-buffer)
565       (progn
566         (set-buffer gnus-work-buffer)
567         (erase-buffer))
568     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
569     (kill-all-local-variables)
570     (mm-enable-multibyte)))
571
572 (defmacro gnus-group-real-name (group)
573   "Find the real name of a foreign newsgroup."
574   `(let ((gname ,group))
575      (if (string-match "^[^:]+:" gname)
576          (substring gname (match-end 0))
577        gname)))
578
579 (defmacro gnus-group-server (group)
580   "Find the server name of a foreign newsgroup.
581 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
582 yield \"nnimap:yxa\"."
583   `(let ((gname ,group))
584      (if (string-match "^\\([^+]+\\).\\([^:]+\\):" gname)
585          (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
586        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
587
588 (defun gnus-make-sort-function (funs)
589   "Return a composite sort condition based on the functions in FUNS."
590   (cond
591    ;; Just a simple function.
592    ((functionp funs) funs)
593    ;; No functions at all.
594    ((null funs) funs)
595    ;; A list of functions.
596    ((or (cdr funs)
597         (listp (car funs)))
598     (gnus-byte-compile
599      `(lambda (t1 t2)
600         ,(gnus-make-sort-function-1 (reverse funs)))))
601    ;; A list containing just one function.
602    (t
603     (car funs))))
604
605 (defun gnus-make-sort-function-1 (funs)
606   "Return a composite sort condition based on the functions in FUNS."
607   (let ((function (car funs))
608         (first 't1)
609         (last 't2))
610     (when (consp function)
611       (cond
612        ;; Reversed spec.
613        ((eq (car function) 'not)
614         (setq function (cadr function)
615               first 't2
616               last 't1))
617        ((functionp function)
618         ;; Do nothing.
619         )
620        (t
621         (error "Invalid sort spec: %s" function))))
622     (if (cdr funs)
623         `(or (,function ,first ,last)
624              (and (not (,function ,last ,first))
625                   ,(gnus-make-sort-function-1 (cdr funs))))
626       `(,function ,first ,last))))
627
628 (defun gnus-turn-off-edit-menu (type)
629   "Turn off edit menu in `gnus-TYPE-mode-map'."
630   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
631     [menu-bar edit] 'undefined))
632
633 (defmacro gnus-bind-print-variables (&rest forms)
634   "Bind print-* variables and evaluate FORMS.
635 This macro is used with `prin1', `pp', etc. in order to ensure printed
636 Lisp objects are loadable.  Bind `print-quoted' and `print-readably'
637 to t, and `print-escape-multibyte', `print-escape-newlines',
638 `print-escape-nonascii', `print-length', `print-level' and
639 `print-string-length' to nil."
640   `(let ((print-quoted t)
641          (print-readably t)
642          ;;print-circle
643          ;;print-continuous-numbering
644          print-escape-multibyte
645          print-escape-newlines
646          print-escape-nonascii
647          ;;print-gensym
648          print-length
649          print-level
650          print-string-length)
651      ,@forms))
652
653 (defun gnus-prin1 (form)
654   "Use `prin1' on FORM in the current buffer.
655 Bind `print-quoted' and `print-readably' to t, and `print-length' and
656 `print-level' to nil.  See also `gnus-bind-print-variables'."
657   (gnus-bind-print-variables (prin1 form (current-buffer))))
658
659 (defun gnus-prin1-to-string (form)
660   "The same as `prin1'.
661 Bind `print-quoted' and `print-readably' to t, and `print-length' and
662 `print-level' to nil.  See also `gnus-bind-print-variables'."
663   (gnus-bind-print-variables (prin1-to-string form)))
664
665 (defun gnus-pp (form &optional stream)
666   "Use `pp' on FORM in the current buffer.
667 Bind `print-quoted' and `print-readably' to t, and `print-length' and
668 `print-level' to nil.  See also `gnus-bind-print-variables'."
669   (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
670
671 (defun gnus-pp-to-string (form)
672   "The same as `pp-to-string'.
673 Bind `print-quoted' and `print-readably' to t, and `print-length' and
674 `print-level' to nil.  See also `gnus-bind-print-variables'."
675   (gnus-bind-print-variables (pp-to-string form)))
676
677 (defun gnus-make-directory (directory)
678   "Make DIRECTORY (and all its parents) if it doesn't exist."
679   (require 'nnmail)
680   (let ((file-name-coding-system nnmail-pathname-coding-system))
681     (when (and directory
682                (not (file-exists-p directory)))
683       (make-directory directory t)))
684   t)
685
686 (defun gnus-write-buffer (file)
687   "Write the current buffer's contents to FILE."
688   ;; Make sure the directory exists.
689   (gnus-make-directory (file-name-directory file))
690   (let ((file-name-coding-system nnmail-pathname-coding-system))
691     ;; Write the buffer.
692     (write-region (point-min) (point-max) file nil 'quietly)))
693
694 (defun gnus-delete-file (file)
695   "Delete FILE if it exists."
696   (when (file-exists-p file)
697     (delete-file file)))
698
699 (defun gnus-strip-whitespace (string)
700   "Return STRING stripped of all whitespace."
701   (while (string-match "[\r\n\t ]+" string)
702     (setq string (replace-match "" t t string)))
703   string)
704
705 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
706   "The same as `put-text-property', but don't put this prop on any newlines in the region."
707   (save-match-data
708     (save-excursion
709       (save-restriction
710         (goto-char beg)
711         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
712           (gnus-put-text-property beg (match-beginning 0) prop val)
713           (setq beg (point)))
714         (gnus-put-text-property beg (point) prop val)))))
715
716 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
717   "The same as `put-text-property', but don't put this prop on any newlines in the region."
718   (save-match-data
719     (save-excursion
720       (save-restriction
721         (goto-char beg)
722         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
723           (gnus-overlay-put
724            (gnus-make-overlay beg (match-beginning 0))
725            prop val)
726           (setq beg (point)))
727         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
728
729 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
730                                                                    prop val)
731   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
732   (let ((b beg))
733     (while (/= b end)
734       (when (get-text-property b 'gnus-face)
735         (setq b (next-single-property-change b 'gnus-face nil end)))
736       (when (/= b end)
737         (inline
738           (gnus-put-text-property
739            b (setq b (next-single-property-change b 'gnus-face nil end))
740            prop val))))))
741
742 (defmacro gnus-faces-at (position)
743   "Return a list of faces at POSITION."
744   (if (featurep 'xemacs)
745       `(let ((pos ,position))
746          (mapcar-extents 'extent-face
747                          nil (current-buffer) pos pos nil 'face))
748     `(let ((pos ,position))
749        (delq nil (cons (get-text-property pos 'face)
750                        (mapcar
751                         (lambda (overlay)
752                           (overlay-get overlay 'face))
753                         (overlays-at pos)))))))
754
755 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
756 ;;; The primary idea here is to try to protect internal datastructures
757 ;;; from becoming corrupted when the user hits C-g, or if a hook or
758 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
759 ;;; updated at the same time, or information can be lost.
760
761 (defvar gnus-atomic-be-safe t
762   "If t, certain operations will be protected from interruption by C-g.")
763
764 (defmacro gnus-atomic-progn (&rest forms)
765   "Evaluate FORMS atomically, which means to protect the evaluation
766 from being interrupted by the user.  An error from the forms themselves
767 will return without finishing the operation.  Since interrupts from
768 the user are disabled, it is recommended that only the most minimal
769 operations are performed by FORMS.  If you wish to assign many
770 complicated values atomically, compute the results into temporary
771 variables and then do only the assignment atomically."
772   `(let ((inhibit-quit gnus-atomic-be-safe))
773      ,@forms))
774
775 (put 'gnus-atomic-progn 'lisp-indent-function 0)
776
777 (defmacro gnus-atomic-progn-assign (protect &rest forms)
778   "Evaluate FORMS, but insure that the variables listed in PROTECT
779 are not changed if anything in FORMS signals an error or otherwise
780 non-locally exits.  The variables listed in PROTECT are updated atomically.
781 It is safe to use gnus-atomic-progn-assign with long computations.
782
783 Note that if any of the symbols in PROTECT were unbound, they will be
784 set to nil on a successful assignment.  In case of an error or other
785 non-local exit, it will still be unbound."
786   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
787                                                   (concat (symbol-name x)
788                                                           "-tmp"))
789                                                  x))
790                                protect))
791          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
792                                temp-sym-map))
793          (temp-sym-let (mapcar (lambda (x) (list (car x)
794                                                  `(and (boundp ',(cadr x))
795                                                        ,(cadr x))))
796                                temp-sym-map))
797          (sym-temp-let sym-temp-map)
798          (temp-sym-assign (apply 'append temp-sym-map))
799          (sym-temp-assign (apply 'append sym-temp-map))
800          (result (make-symbol "result-tmp")))
801     `(let (,@temp-sym-let
802            ,result)
803        (let ,sym-temp-let
804          (setq ,result (progn ,@forms))
805          (setq ,@temp-sym-assign))
806        (let ((inhibit-quit gnus-atomic-be-safe))
807          (setq ,@sym-temp-assign))
808        ,result)))
809
810 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
811 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
812
813 (defmacro gnus-atomic-setq (&rest pairs)
814   "Similar to setq, except that the real symbols are only assigned when
815 there are no errors.  And when the real symbols are assigned, they are
816 done so atomically.  If other variables might be changed via side-effect,
817 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
818 with potentially long computations."
819   (let ((tpairs pairs)
820         syms)
821     (while tpairs
822       (push (car tpairs) syms)
823       (setq tpairs (cddr tpairs)))
824     `(gnus-atomic-progn-assign ,syms
825        (setq ,@pairs))))
826
827 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
828
829
830 ;;; Functions for saving to babyl/mail files.
831
832 (eval-when-compile
833   (condition-case nil
834       (progn
835         (require 'rmail)
836         (autoload 'rmail-update-summary "rmailsum"))
837     (error
838      (define-compiler-macro rmail-select-summary (&rest body)
839        ;; Rmail of the XEmacs version is supplied by the package, and
840        ;; requires tm and apel packages.  However, there may be those
841        ;; who haven't installed those packages.  This macro helps such
842        ;; people even if they install those packages later.
843        `(eval '(rmail-select-summary ,@body)))
844      ;; If there's rmail but there's no tm (or there's apel of the
845      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
846      ;; version fails halfway, however it provides the rmail-select-summary
847      ;; macro which uses the following functions:
848      (autoload 'rmail-summary-displayed "rmail")
849      (autoload 'rmail-maybe-display-summary "rmail")))
850   (defvar rmail-default-rmail-file)
851   (defvar mm-text-coding-system))
852
853 (defun gnus-output-to-rmail (filename &optional ask)
854   "Append the current article to an Rmail file named FILENAME."
855   (require 'rmail)
856   (require 'mm-util)
857   ;; Most of these codes are borrowed from rmailout.el.
858   (setq filename (expand-file-name filename))
859   (setq rmail-default-rmail-file filename)
860   (let ((artbuf (current-buffer))
861         (tmpbuf (get-buffer-create " *Gnus-output*")))
862     (save-excursion
863       (or (get-file-buffer filename)
864           (file-exists-p filename)
865           (if (or (not ask)
866                   (gnus-yes-or-no-p
867                    (concat "\"" filename "\" does not exist, create it? ")))
868               (let ((file-buffer (create-file-buffer filename)))
869                 (save-excursion
870                   (set-buffer file-buffer)
871                   (rmail-insert-rmail-file-header)
872                   (let ((require-final-newline nil)
873                         (coding-system-for-write mm-text-coding-system))
874                     (gnus-write-buffer filename)))
875                 (kill-buffer file-buffer))
876             (error "Output file does not exist")))
877       (set-buffer tmpbuf)
878       (erase-buffer)
879       (insert-buffer-substring artbuf)
880       (gnus-convert-article-to-rmail)
881       ;; Decide whether to append to a file or to an Emacs buffer.
882       (let ((outbuf (get-file-buffer filename)))
883         (if (not outbuf)
884             (let ((file-name-coding-system nnmail-pathname-coding-system))
885               (mm-append-to-file (point-min) (point-max) filename))
886           ;; File has been visited, in buffer OUTBUF.
887           (set-buffer outbuf)
888           (let ((buffer-read-only nil)
889                 (msg (and (boundp 'rmail-current-message)
890                           (symbol-value 'rmail-current-message))))
891             ;; If MSG is non-nil, buffer is in RMAIL mode.
892             (when msg
893               (widen)
894               (narrow-to-region (point-max) (point-max)))
895             (insert-buffer-substring tmpbuf)
896             (when msg
897               (goto-char (point-min))
898               (widen)
899               (search-backward "\n\^_")
900               (narrow-to-region (point) (point-max))
901               (rmail-count-new-messages t)
902               (when (rmail-summary-exists)
903                 (rmail-select-summary
904                  (rmail-update-summary)))
905               (rmail-count-new-messages t)
906               (rmail-show-message msg))
907             (save-buffer)))))
908     (kill-buffer tmpbuf)))
909
910 (defun gnus-output-to-mail (filename &optional ask)
911   "Append the current article to a mail file named FILENAME."
912   (setq filename (expand-file-name filename))
913   (let ((artbuf (current-buffer))
914         (tmpbuf (get-buffer-create " *Gnus-output*")))
915     (save-excursion
916       ;; Create the file, if it doesn't exist.
917       (when (and (not (get-file-buffer filename))
918                  (not (file-exists-p filename)))
919         (if (or (not ask)
920                 (gnus-y-or-n-p
921                  (concat "\"" filename "\" does not exist, create it? ")))
922             (let ((file-buffer (create-file-buffer filename)))
923               (save-excursion
924                 (set-buffer file-buffer)
925                 (let ((require-final-newline nil)
926                       (coding-system-for-write mm-text-coding-system))
927                   (gnus-write-buffer filename)))
928               (kill-buffer file-buffer))
929           (error "Output file does not exist")))
930       (set-buffer tmpbuf)
931       (erase-buffer)
932       (insert-buffer-substring artbuf)
933       (goto-char (point-min))
934       (if (looking-at "From ")
935           (forward-line 1)
936         (insert "From nobody " (current-time-string) "\n"))
937       (let (case-fold-search)
938         (while (re-search-forward "^From " nil t)
939           (beginning-of-line)
940           (insert ">")))
941       ;; Decide whether to append to a file or to an Emacs buffer.
942       (let ((outbuf (get-file-buffer filename)))
943         (if (not outbuf)
944             (let ((buffer-read-only nil))
945               (save-excursion
946                 (goto-char (point-max))
947                 (forward-char -2)
948                 (unless (looking-at "\n\n")
949                   (goto-char (point-max))
950                   (unless (bolp)
951                     (insert "\n"))
952                   (insert "\n"))
953                 (goto-char (point-max))
954                 (let ((file-name-coding-system nnmail-pathname-coding-system))
955                   (mm-append-to-file (point-min) (point-max) filename))))
956           ;; File has been visited, in buffer OUTBUF.
957           (set-buffer outbuf)
958           (let ((buffer-read-only nil))
959             (goto-char (point-max))
960             (unless (eobp)
961               (insert "\n"))
962             (insert "\n")
963             (insert-buffer-substring tmpbuf)))))
964     (kill-buffer tmpbuf)))
965
966 (defun gnus-convert-article-to-rmail ()
967   "Convert article in current buffer to Rmail message format."
968   (let ((buffer-read-only nil))
969     ;; Convert article directly into Babyl format.
970     (goto-char (point-min))
971     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
972     (while (search-forward "\n\^_" nil t) ;single char
973       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
974     (goto-char (point-max))
975     (insert "\^_")))
976
977 (defun gnus-map-function (funs arg)
978   "Apply the result of the first function in FUNS to the second, and so on.
979 ARG is passed to the first function."
980   (while funs
981     (setq arg (funcall (pop funs) arg)))
982   arg)
983
984 (defun gnus-run-hooks (&rest funcs)
985   "Does the same as `run-hooks', but saves the current buffer."
986   (save-current-buffer
987     (apply 'run-hooks funcs)))
988
989 ;;; Various
990
991 (defvar gnus-group-buffer)              ; Compiler directive
992 (defun gnus-alive-p ()
993   "Say whether Gnus is running or not."
994   (and (boundp 'gnus-group-buffer)
995        (get-buffer gnus-group-buffer)
996        (save-excursion
997          (set-buffer gnus-group-buffer)
998          (eq major-mode 'gnus-group-mode))))
999
1000 (defun gnus-remove-duplicates (list)
1001   (let (new)
1002     (while list
1003       (or (member (car list) new)
1004           (setq new (cons (car list) new)))
1005       (setq list (cdr list)))
1006     (nreverse new)))
1007
1008 (defun gnus-remove-if (predicate list)
1009   "Return a copy of LIST with all items satisfying PREDICATE removed."
1010   (let (out)
1011     (while list
1012       (unless (funcall predicate (car list))
1013         (push (car list) out))
1014       (setq list (cdr list)))
1015     (nreverse out)))
1016
1017 (if (fboundp 'assq-delete-all)
1018     (defalias 'gnus-delete-alist 'assq-delete-all)
1019   (defun gnus-delete-alist (key alist)
1020     "Delete from ALIST all elements whose car is KEY.
1021 Return the modified alist."
1022     (let (entry)
1023       (while (setq entry (assq key alist))
1024         (setq alist (delq entry alist)))
1025       alist)))
1026
1027 (defmacro gnus-pull (key alist &optional assoc-p)
1028   "Modify ALIST to be without KEY."
1029   (unless (symbolp alist)
1030     (error "Not a symbol: %s" alist))
1031   (let ((fun (if assoc-p 'assoc 'assq)))
1032     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1033
1034 (defun gnus-globalify-regexp (re)
1035   "Return a regexp that matches a whole line, iff RE matches a part of it."
1036   (concat (unless (string-match "^\\^" re) "^.*")
1037           re
1038           (unless (string-match "\\$$" re) ".*$")))
1039
1040 (defun gnus-set-window-start (&optional point)
1041   "Set the window start to POINT, or (point) if nil."
1042   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1043     (when win
1044       (set-window-start win (or point (point))))))
1045
1046 (defun gnus-annotation-in-region-p (b e)
1047   (if (= b e)
1048       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1049     (text-property-any b e 'gnus-undeletable t)))
1050
1051 (defun gnus-or (&rest elems)
1052   "Return non-nil if any of the elements are non-nil."
1053   (catch 'found
1054     (while elems
1055       (when (pop elems)
1056         (throw 'found t)))))
1057
1058 (defun gnus-and (&rest elems)
1059   "Return non-nil if all of the elements are non-nil."
1060   (catch 'found
1061     (while elems
1062       (unless (pop elems)
1063         (throw 'found nil)))
1064     t))
1065
1066 (defun gnus-write-active-file (file hashtb &optional full-names)
1067   (let ((coding-system-for-write nnmail-active-file-coding-system))
1068     (with-temp-file file
1069       (mapatoms
1070        (lambda (sym)
1071          (when (and sym
1072                     (boundp sym)
1073                     (symbol-value sym))
1074            (insert (format "%S %d %d y\n"
1075                            (if full-names
1076                                sym
1077                              (intern (gnus-group-real-name (symbol-name sym))))
1078                            (or (cdr (symbol-value sym))
1079                                (car (symbol-value sym)))
1080                            (car (symbol-value sym))))))
1081        hashtb)
1082       (goto-char (point-max))
1083       (while (search-backward "\\." nil t)
1084         (delete-char 1)))))
1085
1086 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1087 (defmacro gnus-with-output-to-file (file &rest body)
1088   (let ((buffer (make-symbol "output-buffer"))
1089         (size (make-symbol "output-buffer-size"))
1090         (leng (make-symbol "output-buffer-length"))
1091         (append (make-symbol "output-buffer-append")))
1092     `(let* ((,size 131072)
1093             (,buffer (make-string ,size 0))
1094             (,leng 0)
1095             (,append nil)
1096             (standard-output
1097              (lambda (c)
1098                (aset ,buffer ,leng c)
1099                    
1100                (if (= ,size (setq ,leng (1+ ,leng)))
1101                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1102                           (setq ,leng 0
1103                                 ,append t))))))
1104        ,@body
1105        (when (> ,leng 0)
1106          (let ((coding-system-for-write 'no-conversion))
1107          (write-region (substring ,buffer 0 ,leng) nil ,file
1108                        ,append 'no-msg))))))
1109
1110 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1111 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1112
1113 (if (fboundp 'union)
1114     (defalias 'gnus-union 'union)
1115   (defun gnus-union (l1 l2)
1116     "Set union of lists L1 and L2."
1117     (cond ((null l1) l2)
1118           ((null l2) l1)
1119           ((equal l1 l2) l1)
1120           (t
1121            (or (>= (length l1) (length l2))
1122                (setq l1 (prog1 l2 (setq l2 l1))))
1123            (while l2
1124              (or (member (car l2) l1)
1125                  (push (car l2) l1))
1126              (pop l2))
1127            l1))))
1128
1129 (defun gnus-add-text-properties-when
1130   (property value start end properties &optional object)
1131   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1132   (let (point)
1133     (while (and start
1134                 (< start end) ;; XEmacs will loop for every when start=end.
1135                 (setq point (text-property-not-all start end property value)))
1136       (gnus-add-text-properties start point properties object)
1137       (setq start (text-property-any point end property value)))
1138     (if start
1139         (gnus-add-text-properties start end properties object))))
1140
1141 (defun gnus-remove-text-properties-when
1142   (property value start end properties &optional object)
1143   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1144   (let (point)
1145     (while (and start
1146                 (< start end)
1147                 (setq point (text-property-not-all start end property value)))
1148       (remove-text-properties start point properties object)
1149       (setq start (text-property-any point end property value)))
1150     (if start
1151         (remove-text-properties start end properties object))
1152     t))
1153
1154 ;; This might use `compare-strings' to reduce consing in the
1155 ;; case-insensitive case, but it has to cope with null args.
1156 ;; (`string-equal' uses symbol print names.)
1157 (defun gnus-string-equal (x y)
1158   "Like `string-equal', except it compares case-insensitively."
1159   (and (= (length x) (length y))
1160        (or (string-equal x y)
1161            (string-equal (downcase x) (downcase y)))))
1162
1163 (defcustom gnus-use-byte-compile t
1164   "If non-nil, byte-compile crucial run-time code.
1165 Setting it to nil has no effect after the first time `gnus-byte-compile'
1166 is run."
1167   :type 'boolean
1168   :version "21.4"
1169   :group 'gnus-various)
1170
1171 (defun gnus-byte-compile (form)
1172   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1173   (if gnus-use-byte-compile
1174       (progn
1175         (condition-case nil
1176             ;; Work around a bug in XEmacs 21.4
1177             (require 'byte-optimize)
1178           (error))
1179         (require 'bytecomp)
1180         (defalias 'gnus-byte-compile
1181           (lambda (form)
1182             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1183               (byte-compile form))))
1184         (gnus-byte-compile form))
1185     form))
1186
1187 (defun gnus-remassoc (key alist)
1188   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1189 The modified LIST is returned.  If the first member
1190 of LIST has a car that is `equal' to KEY, there is no way to remove it
1191 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1192 sure of changing the value of `foo'."
1193   (when alist
1194     (if (equal key (caar alist))
1195         (cdr alist)
1196       (setcdr alist (gnus-remassoc key (cdr alist)))
1197       alist)))
1198
1199 (defun gnus-update-alist-soft (key value alist)
1200   (if value
1201       (cons (cons key value) (gnus-remassoc key alist))
1202     (gnus-remassoc key alist)))
1203
1204 (defun gnus-create-info-command (node)
1205   "Create a command that will go to info NODE."
1206   `(lambda ()
1207      (interactive)
1208      ,(concat "Enter the info system at node " node)
1209      (Info-goto-node ,node)
1210      (setq gnus-info-buffer (current-buffer))
1211      (gnus-configure-windows 'info)))
1212
1213 (defun gnus-not-ignore (&rest args)
1214   t)
1215
1216 (defvar gnus-directory-sep-char-regexp "/"
1217   "The regexp of directory separator character.
1218 If you find some problem with the directory separator character, try
1219 \"[/\\\\\]\" for some systems.")
1220
1221 (defun gnus-url-unhex (x)
1222   (if (> x ?9)
1223       (if (>= x ?a)
1224           (+ 10 (- x ?a))
1225         (+ 10 (- x ?A)))
1226     (- x ?0)))
1227
1228 ;; Fixme: Do it like QP.
1229 (defun gnus-url-unhex-string (str &optional allow-newlines)
1230   "Remove %XX, embedded spaces, etc in a url.
1231 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1232 decoding of carriage returns and line feeds in the string, which is normally
1233 forbidden in URL encoding."
1234   (let ((tmp "")
1235         (case-fold-search t))
1236     (while (string-match "%[0-9a-f][0-9a-f]" str)
1237       (let* ((start (match-beginning 0))
1238              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1239              (code (+ (* 16 ch1)
1240                       (gnus-url-unhex (elt str (+ start 2))))))
1241         (setq tmp (concat
1242                    tmp (substring str 0 start)
1243                    (cond
1244                     (allow-newlines
1245                      (char-to-string code))
1246                     ((or (= code ?\n) (= code ?\r))
1247                      " ")
1248                     (t (char-to-string code))))
1249               str (substring str (match-end 0)))))
1250     (setq tmp (concat tmp str))
1251     tmp))
1252
1253 (defun gnus-make-predicate (spec)
1254   "Transform SPEC into a function that can be called.
1255 SPEC is a predicate specifier that contains stuff like `or', `and',
1256 `not', lists and functions.  The functions all take one parameter."
1257   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1258
1259 (defun gnus-make-predicate-1 (spec)
1260   (cond
1261    ((symbolp spec)
1262     `(,spec elem))
1263    ((listp spec)
1264     (if (memq (car spec) '(or and not))
1265         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1266       (error "Invalid predicate specifier: %s" spec)))))
1267
1268 (defun gnus-completing-read (prompt table &optional predicate require-match
1269                                     history)
1270   (when (and history
1271              (not (boundp history)))
1272     (set history nil))
1273   (completing-read
1274    (if (symbol-value history)
1275        (concat prompt " (" (car (symbol-value history)) "): ")
1276      (concat prompt ": "))
1277    table
1278    predicate
1279    require-match
1280    nil
1281    history
1282    (car (symbol-value history))))
1283
1284 (defun gnus-graphic-display-p ()
1285   (or (and (fboundp 'display-graphic-p)
1286            (display-graphic-p))
1287       ;;;!!!This is bogus.  Fixme!
1288       (and (featurep 'xemacs)
1289            t)))
1290
1291 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1292 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1293
1294 (defmacro gnus-parse-without-error (&rest body)
1295   "Allow continuing onto the next line even if an error occurs."
1296   `(while (not (eobp))
1297      (condition-case ()
1298          (progn
1299            ,@body
1300            (goto-char (point-max)))
1301        (error
1302         (gnus-error 4 "Invalid data on line %d"
1303                     (count-lines (point-min) (point)))
1304         (forward-line 1)))))
1305
1306 (defun gnus-cache-file-contents (file variable function)
1307   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1308   (let ((time (nth 5 (file-attributes file)))
1309         contents value)
1310     (if (or (null (setq value (symbol-value variable)))
1311             (not (equal (car value) file))
1312             (not (equal (nth 1 value) time)))
1313         (progn
1314           (setq contents (funcall function file))
1315           (set variable (list file time contents))
1316           contents)
1317       (nth 2 value))))
1318
1319 (defun gnus-multiple-choice (prompt choice &optional idx)
1320   "Ask user a multiple choice question.
1321 CHOICE is a list of the choice char and help message at IDX."
1322   (let (tchar buf)
1323     (save-window-excursion
1324       (save-excursion
1325         (while (not tchar)
1326           (message "%s (%s): "
1327                    prompt
1328                    (concat
1329                     (mapconcat (lambda (s) (char-to-string (car s)))
1330                                choice ", ") ", ?"))
1331           (setq tchar (read-char))
1332           (when (not (assq tchar choice))
1333             (setq tchar nil)
1334             (setq buf (get-buffer-create "*Gnus Help*"))
1335             (pop-to-buffer buf)
1336             (fundamental-mode)          ; for Emacs 20.4+
1337             (buffer-disable-undo)
1338             (erase-buffer)
1339             (insert prompt ":\n\n")
1340             (let ((max -1)
1341                   (list choice)
1342                   (alist choice)
1343                   (idx (or idx 1))
1344                   (i 0)
1345                   n width pad format)
1346               ;; find the longest string to display
1347               (while list
1348                 (setq n (length (nth idx (car list))))
1349                 (unless (> max n)
1350                   (setq max n))
1351                 (setq list (cdr list)))
1352               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1353               (setq n (/ (1- (window-width)) max)) ; items per line
1354               (setq width (/ (1- (window-width)) n)) ; width of each item
1355               ;; insert `n' items, each in a field of width `width'
1356               (while alist
1357                 (if (< i n)
1358                     ()
1359                   (setq i 0)
1360                   (delete-char -1)              ; the `\n' takes a char
1361                   (insert "\n"))
1362                 (setq pad (- width 3))
1363                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1364                 (insert (format format (caar alist) (nth idx (car alist))))
1365                 (setq alist (cdr alist))
1366                 (setq i (1+ i))))))))
1367     (if (buffer-live-p buf)
1368         (kill-buffer buf))
1369     tchar))
1370
1371 (defun gnus-select-frame-set-input-focus (frame)
1372   "Select FRAME, raise it, and set input focus, if possible."
1373   (cond ((featurep 'xemacs)
1374          (raise-frame frame)
1375          (select-frame frame)
1376          (focus-frame frame))
1377         ;; The function `select-frame-set-input-focus' won't set
1378         ;; the input focus under Emacs 21.2 and X window system.
1379         ;;((fboundp 'select-frame-set-input-focus)
1380         ;; (defalias 'gnus-select-frame-set-input-focus
1381         ;;   'select-frame-set-input-focus)
1382         ;; (select-frame-set-input-focus frame))
1383         (t
1384          (raise-frame frame)
1385          (select-frame frame)
1386          (cond ((and (eq window-system 'x)
1387                      (fboundp 'x-focus-frame))
1388                 (x-focus-frame frame))
1389                ((eq window-system 'w32)
1390                 (w32-focus-frame frame)))
1391          (when focus-follows-mouse
1392            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1393
1394 (defun gnus-frame-or-window-display-name (object)
1395   "Given a frame or window, return the associated display name.
1396 Return nil otherwise."
1397   (if (featurep 'xemacs)
1398       (device-connection (dfw-device object))
1399     (if (or (framep object)
1400             (and (windowp object)
1401                  (setq object (window-frame object))))
1402         (let ((display (frame-parameter object 'display)))
1403           (if (and (stringp display)
1404                    ;; Exclude invalid display names.
1405                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1406                                  display))
1407               display)))))
1408
1409 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1410 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1411   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1412 If there are several sequences, FUNCTION is called with that many arguments,
1413 and mapping stops as soon as the shortest sequence runs out.  With just one
1414 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1415 `mapcar' function extended to arbitrary sequence types."
1416
1417   (if seqs2_n
1418       (let* ((seqs (cons seq1 seqs2_n))
1419              (cnt 0)
1420              (heads (mapcar (lambda (seq)
1421                               (make-symbol (concat "head"
1422                                                    (int-to-string
1423                                                     (setq cnt (1+ cnt))))))
1424                             seqs))
1425              (result (make-symbol "result"))
1426              (result-tail (make-symbol "result-tail")))
1427         `(let* ,(let* ((bindings (cons nil nil))
1428                        (heads heads))
1429                   (nconc bindings (list (list result '(cons nil nil))))
1430                   (nconc bindings (list (list result-tail result)))
1431                   (while heads
1432                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1433                   (cdr bindings))
1434            (while (and ,@heads)
1435              (setcdr ,result-tail (cons (funcall ,function
1436                                                  ,@(mapcar (lambda (h) (list 'car h))
1437                                                            heads))
1438                                         nil))
1439              (setq ,result-tail (cdr ,result-tail)
1440                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1441            (cdr ,result)))
1442     `(mapcar ,function ,seq1)))
1443
1444 (if (fboundp 'merge)
1445     (defalias 'gnus-merge 'merge)
1446   ;; Adapted from cl-seq.el
1447   (defun gnus-merge (type list1 list2 pred)
1448     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1449 Argument TYPE is for compatibility and ignored.
1450 Ordering of the elements is preserved according to PRED, a `less-than'
1451 predicate on the elements."
1452     (let ((res nil))
1453       (while (and list1 list2)
1454         (if (funcall pred (car list2) (car list1))
1455             (push (pop list2) res)
1456           (push (pop list1) res)))
1457       (nconc (nreverse res) list1 list2))))
1458
1459 (eval-when-compile
1460   (defvar xemacs-codename))
1461
1462 (defun gnus-emacs-version ()
1463   "Stringified Emacs version."
1464   (let ((system-v
1465          (cond
1466           ((eq gnus-user-agent 'emacs-gnus-config)
1467            system-configuration)
1468           ((eq gnus-user-agent 'emacs-gnus-type)
1469            (symbol-name system-type))
1470           (t nil))))
1471     (cond
1472      ((eq gnus-user-agent 'gnus)
1473       nil)
1474      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1475       (concat "Emacs/" (match-string 1 emacs-version)
1476               (if system-v
1477                   (concat " (" system-v ")")
1478                 "")))
1479      ((string-match
1480        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1481        emacs-version)
1482       (concat
1483        (match-string 1 emacs-version)
1484        (format "/%d.%d" emacs-major-version emacs-minor-version)
1485        (if (match-beginning 3)
1486            (match-string 3 emacs-version)
1487          "")
1488        (if (boundp 'xemacs-codename)
1489            (concat
1490             " (" xemacs-codename
1491             (if system-v
1492                 (concat ", " system-v ")")
1493               ")"))
1494          "")))
1495      (t emacs-version))))
1496
1497 (defun gnus-rename-file (old-path new-path &optional trim)
1498   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1499 empty directories from OLD-PATH."
1500   (when (file-exists-p old-path)
1501     (let* ((old-dir (file-name-directory old-path))
1502            (old-name (file-name-nondirectory old-path))
1503            (new-dir (file-name-directory new-path))
1504            (new-name (file-name-nondirectory new-path))
1505            temp)
1506       (gnus-make-directory new-dir)
1507       (rename-file old-path new-path t)
1508       (when trim
1509         (while (progn (setq temp (directory-files old-dir))
1510                       (while (member (car temp) '("." ".."))
1511                         (setq temp (cdr temp)))
1512                       (= (length temp) 0))
1513           (delete-directory old-dir)
1514           (setq old-dir (file-name-as-directory 
1515                          (file-truename 
1516                           (concat old-dir "..")))))))))
1517
1518 (defun gnus-set-file-modes (filename mode)
1519   "Wrapper for set-file-modes."
1520   (ignore-errors
1521     (set-file-modes filename mode)))
1522
1523 (provide 'gnus-util)
1524
1525 ;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
1526 ;;; gnus-util.el ends here