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