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