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