(mm-codepage-setup): New helper function.
[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-if (predicate list)
1034   "Return a copy of LIST with all items satisfying PREDICATE removed."
1035   (let (out)
1036     (while list
1037       (unless (funcall predicate (car list))
1038         (push (car list) out))
1039       (setq list (cdr list)))
1040     (nreverse out)))
1041
1042 (if (fboundp 'assq-delete-all)
1043     (defalias 'gnus-delete-alist 'assq-delete-all)
1044   (defun gnus-delete-alist (key alist)
1045     "Delete from ALIST all elements whose car is KEY.
1046 Return the modified alist."
1047     (let (entry)
1048       (while (setq entry (assq key alist))
1049         (setq alist (delq entry alist)))
1050       alist)))
1051
1052 (defmacro gnus-pull (key alist &optional assoc-p)
1053   "Modify ALIST to be without KEY."
1054   (unless (symbolp alist)
1055     (error "Not a symbol: %s" alist))
1056   (let ((fun (if assoc-p 'assoc 'assq)))
1057     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1058
1059 (defun gnus-globalify-regexp (re)
1060   "Return a regexp that matches a whole line, iff RE matches a part of it."
1061   (concat (unless (string-match "^\\^" re) "^.*")
1062           re
1063           (unless (string-match "\\$$" re) ".*$")))
1064
1065 (defun gnus-set-window-start (&optional point)
1066   "Set the window start to POINT, or (point) if nil."
1067   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1068     (when win
1069       (set-window-start win (or point (point))))))
1070
1071 (defun gnus-annotation-in-region-p (b e)
1072   (if (= b e)
1073       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1074     (text-property-any b e 'gnus-undeletable t)))
1075
1076 (defun gnus-or (&rest elems)
1077   "Return non-nil if any of the elements are non-nil."
1078   (catch 'found
1079     (while elems
1080       (when (pop elems)
1081         (throw 'found t)))))
1082
1083 (defun gnus-and (&rest elems)
1084   "Return non-nil if all of the elements are non-nil."
1085   (catch 'found
1086     (while elems
1087       (unless (pop elems)
1088         (throw 'found nil)))
1089     t))
1090
1091 (defun gnus-write-active-file (file hashtb &optional full-names)
1092   (let ((coding-system-for-write nnmail-active-file-coding-system))
1093     (with-temp-file file
1094       (mapatoms
1095        (lambda (sym)
1096          (when (and sym
1097                     (boundp sym)
1098                     (symbol-value sym))
1099            (insert (format "%S %d %d y\n"
1100                            (if full-names
1101                                sym
1102                              (intern (gnus-group-real-name (symbol-name sym))))
1103                            (or (cdr (symbol-value sym))
1104                                (car (symbol-value sym)))
1105                            (car (symbol-value sym))))))
1106        hashtb)
1107       (goto-char (point-max))
1108       (while (search-backward "\\." nil t)
1109         (delete-char 1)))))
1110
1111 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1112 (defmacro gnus-with-output-to-file (file &rest body)
1113   (let ((buffer (make-symbol "output-buffer"))
1114         (size (make-symbol "output-buffer-size"))
1115         (leng (make-symbol "output-buffer-length"))
1116         (append (make-symbol "output-buffer-append")))
1117     `(let* ((,size 131072)
1118             (,buffer (make-string ,size 0))
1119             (,leng 0)
1120             (,append nil)
1121             (standard-output
1122              (lambda (c)
1123                (aset ,buffer ,leng c)
1124
1125                (if (= ,size (setq ,leng (1+ ,leng)))
1126                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1127                           (setq ,leng 0
1128                                 ,append t))))))
1129        ,@body
1130        (when (> ,leng 0)
1131          (let ((coding-system-for-write 'no-conversion))
1132          (write-region (substring ,buffer 0 ,leng) nil ,file
1133                        ,append 'no-msg))))))
1134
1135 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1136 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1137
1138 (if (fboundp 'union)
1139     (defalias 'gnus-union 'union)
1140   (defun gnus-union (l1 l2)
1141     "Set union of lists L1 and L2."
1142     (cond ((null l1) l2)
1143           ((null l2) l1)
1144           ((equal l1 l2) l1)
1145           (t
1146            (or (>= (length l1) (length l2))
1147                (setq l1 (prog1 l2 (setq l2 l1))))
1148            (while l2
1149              (or (member (car l2) l1)
1150                  (push (car l2) l1))
1151              (pop l2))
1152            l1))))
1153
1154 (defun gnus-add-text-properties-when
1155   (property value start end properties &optional object)
1156   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1157   (let (point)
1158     (while (and start
1159                 (< start end) ;; XEmacs will loop for every when start=end.
1160                 (setq point (text-property-not-all start end property value)))
1161       (gnus-add-text-properties start point properties object)
1162       (setq start (text-property-any point end property value)))
1163     (if start
1164         (gnus-add-text-properties start end properties object))))
1165
1166 (defun gnus-remove-text-properties-when
1167   (property value start end properties &optional object)
1168   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1169   (let (point)
1170     (while (and start
1171                 (< start end)
1172                 (setq point (text-property-not-all start end property value)))
1173       (remove-text-properties start point properties object)
1174       (setq start (text-property-any point end property value)))
1175     (if start
1176         (remove-text-properties start end properties object))
1177     t))
1178
1179 ;; This might use `compare-strings' to reduce consing in the
1180 ;; case-insensitive case, but it has to cope with null args.
1181 ;; (`string-equal' uses symbol print names.)
1182 (defun gnus-string-equal (x y)
1183   "Like `string-equal', except it compares case-insensitively."
1184   (and (= (length x) (length y))
1185        (or (string-equal x y)
1186            (string-equal (downcase x) (downcase y)))))
1187
1188 (defcustom gnus-use-byte-compile t
1189   "If non-nil, byte-compile crucial run-time code.
1190 Setting it to nil has no effect after the first time `gnus-byte-compile'
1191 is run."
1192   :type 'boolean
1193   :version "22.1"
1194   :group 'gnus-various)
1195
1196 (defun gnus-byte-compile (form)
1197   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1198   (if gnus-use-byte-compile
1199       (progn
1200         (condition-case nil
1201             ;; Work around a bug in XEmacs 21.4
1202             (require 'byte-optimize)
1203           (error))
1204         (require 'bytecomp)
1205         (defalias 'gnus-byte-compile
1206           (lambda (form)
1207             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1208               (byte-compile form))))
1209         (gnus-byte-compile form))
1210     form))
1211
1212 (defun gnus-remassoc (key alist)
1213   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1214 The modified LIST is returned.  If the first member
1215 of LIST has a car that is `equal' to KEY, there is no way to remove it
1216 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1217 sure of changing the value of `foo'."
1218   (when alist
1219     (if (equal key (caar alist))
1220         (cdr alist)
1221       (setcdr alist (gnus-remassoc key (cdr alist)))
1222       alist)))
1223
1224 (defun gnus-update-alist-soft (key value alist)
1225   (if value
1226       (cons (cons key value) (gnus-remassoc key alist))
1227     (gnus-remassoc key alist)))
1228
1229 (defun gnus-create-info-command (node)
1230   "Create a command that will go to info NODE."
1231   `(lambda ()
1232      (interactive)
1233      ,(concat "Enter the info system at node " node)
1234      (Info-goto-node ,node)
1235      (setq gnus-info-buffer (current-buffer))
1236      (gnus-configure-windows 'info)))
1237
1238 (defun gnus-not-ignore (&rest args)
1239   t)
1240
1241 (defvar gnus-directory-sep-char-regexp "/"
1242   "The regexp of directory separator character.
1243 If you find some problem with the directory separator character, try
1244 \"[/\\\\\]\" for some systems.")
1245
1246 (defun gnus-url-unhex (x)
1247   (if (> x ?9)
1248       (if (>= x ?a)
1249           (+ 10 (- x ?a))
1250         (+ 10 (- x ?A)))
1251     (- x ?0)))
1252
1253 ;; Fixme: Do it like QP.
1254 (defun gnus-url-unhex-string (str &optional allow-newlines)
1255   "Remove %XX, embedded spaces, etc in a url.
1256 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1257 decoding of carriage returns and line feeds in the string, which is normally
1258 forbidden in URL encoding."
1259   (let ((tmp "")
1260         (case-fold-search t))
1261     (while (string-match "%[0-9a-f][0-9a-f]" str)
1262       (let* ((start (match-beginning 0))
1263              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1264              (code (+ (* 16 ch1)
1265                       (gnus-url-unhex (elt str (+ start 2))))))
1266         (setq tmp (concat
1267                    tmp (substring str 0 start)
1268                    (cond
1269                     (allow-newlines
1270                      (char-to-string code))
1271                     ((or (= code ?\n) (= code ?\r))
1272                      " ")
1273                     (t (char-to-string code))))
1274               str (substring str (match-end 0)))))
1275     (setq tmp (concat tmp str))
1276     tmp))
1277
1278 (defun gnus-make-predicate (spec)
1279   "Transform SPEC into a function that can be called.
1280 SPEC is a predicate specifier that contains stuff like `or', `and',
1281 `not', lists and functions.  The functions all take one parameter."
1282   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1283
1284 (defun gnus-make-predicate-1 (spec)
1285   (cond
1286    ((symbolp spec)
1287     `(,spec elem))
1288    ((listp spec)
1289     (if (memq (car spec) '(or and not))
1290         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1291       (error "Invalid predicate specifier: %s" spec)))))
1292
1293 (defun gnus-completing-read (prompt table &optional predicate require-match
1294                                     history)
1295   (when (and history
1296              (not (boundp history)))
1297     (set history nil))
1298   (completing-read
1299    (if (symbol-value history)
1300        (concat prompt " (" (car (symbol-value history)) "): ")
1301      (concat prompt ": "))
1302    table
1303    predicate
1304    require-match
1305    nil
1306    history
1307    (car (symbol-value history))))
1308
1309 (defun gnus-graphic-display-p ()
1310   (or (and (fboundp 'display-graphic-p)
1311            (display-graphic-p))
1312       ;;;!!!This is bogus.  Fixme!
1313       (and (featurep 'xemacs)
1314            t)))
1315
1316 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1317 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1318
1319 (defmacro gnus-parse-without-error (&rest body)
1320   "Allow continuing onto the next line even if an error occurs."
1321   `(while (not (eobp))
1322      (condition-case ()
1323          (progn
1324            ,@body
1325            (goto-char (point-max)))
1326        (error
1327         (gnus-error 4 "Invalid data on line %d"
1328                     (count-lines (point-min) (point)))
1329         (forward-line 1)))))
1330
1331 (defun gnus-cache-file-contents (file variable function)
1332   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1333   (let ((time (nth 5 (file-attributes file)))
1334         contents value)
1335     (if (or (null (setq value (symbol-value variable)))
1336             (not (equal (car value) file))
1337             (not (equal (nth 1 value) time)))
1338         (progn
1339           (setq contents (funcall function file))
1340           (set variable (list file time contents))
1341           contents)
1342       (nth 2 value))))
1343
1344 (defun gnus-multiple-choice (prompt choice &optional idx)
1345   "Ask user a multiple choice question.
1346 CHOICE is a list of the choice char and help message at IDX."
1347   (let (tchar buf)
1348     (save-window-excursion
1349       (save-excursion
1350         (while (not tchar)
1351           (message "%s (%s): "
1352                    prompt
1353                    (concat
1354                     (mapconcat (lambda (s) (char-to-string (car s)))
1355                                choice ", ") ", ?"))
1356           (setq tchar (read-char))
1357           (when (not (assq tchar choice))
1358             (setq tchar nil)
1359             (setq buf (get-buffer-create "*Gnus Help*"))
1360             (pop-to-buffer buf)
1361             (fundamental-mode)          ; for Emacs 20.4+
1362             (buffer-disable-undo)
1363             (erase-buffer)
1364             (insert prompt ":\n\n")
1365             (let ((max -1)
1366                   (list choice)
1367                   (alist choice)
1368                   (idx (or idx 1))
1369                   (i 0)
1370                   n width pad format)
1371               ;; find the longest string to display
1372               (while list
1373                 (setq n (length (nth idx (car list))))
1374                 (unless (> max n)
1375                   (setq max n))
1376                 (setq list (cdr list)))
1377               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1378               (setq n (/ (1- (window-width)) max)) ; items per line
1379               (setq width (/ (1- (window-width)) n)) ; width of each item
1380               ;; insert `n' items, each in a field of width `width'
1381               (while alist
1382                 (if (< i n)
1383                     ()
1384                   (setq i 0)
1385                   (delete-char -1)              ; the `\n' takes a char
1386                   (insert "\n"))
1387                 (setq pad (- width 3))
1388                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1389                 (insert (format format (caar alist) (nth idx (car alist))))
1390                 (setq alist (cdr alist))
1391                 (setq i (1+ i))))))))
1392     (if (buffer-live-p buf)
1393         (kill-buffer buf))
1394     tchar))
1395
1396 (defun gnus-select-frame-set-input-focus (frame)
1397   "Select FRAME, raise it, and set input focus, if possible."
1398   (cond ((featurep 'xemacs)
1399          (raise-frame frame)
1400          (select-frame frame)
1401          (focus-frame frame))
1402         ;; The function `select-frame-set-input-focus' won't set
1403         ;; the input focus under Emacs 21.2 and X window system.
1404         ;;((fboundp 'select-frame-set-input-focus)
1405         ;; (defalias 'gnus-select-frame-set-input-focus
1406         ;;   'select-frame-set-input-focus)
1407         ;; (select-frame-set-input-focus frame))
1408         (t
1409          (raise-frame frame)
1410          (select-frame frame)
1411          (cond ((and (eq window-system 'x)
1412                      (fboundp 'x-focus-frame))
1413                 (x-focus-frame frame))
1414                ((eq window-system 'w32)
1415                 (w32-focus-frame frame)))
1416          (when focus-follows-mouse
1417            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1418
1419 (defun gnus-frame-or-window-display-name (object)
1420   "Given a frame or window, return the associated display name.
1421 Return nil otherwise."
1422   (if (featurep 'xemacs)
1423       (device-connection (dfw-device object))
1424     (if (or (framep object)
1425             (and (windowp object)
1426                  (setq object (window-frame object))))
1427         (let ((display (frame-parameter object 'display)))
1428           (if (and (stringp display)
1429                    ;; Exclude invalid display names.
1430                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1431                                  display))
1432               display)))))
1433
1434 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1435 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1436   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1437 If there are several sequences, FUNCTION is called with that many arguments,
1438 and mapping stops as soon as the shortest sequence runs out.  With just one
1439 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1440 `mapcar' function extended to arbitrary sequence types."
1441
1442   (if seqs2_n
1443       (let* ((seqs (cons seq1 seqs2_n))
1444              (cnt 0)
1445              (heads (mapcar (lambda (seq)
1446                               (make-symbol (concat "head"
1447                                                    (int-to-string
1448                                                     (setq cnt (1+ cnt))))))
1449                             seqs))
1450              (result (make-symbol "result"))
1451              (result-tail (make-symbol "result-tail")))
1452         `(let* ,(let* ((bindings (cons nil nil))
1453                        (heads heads))
1454                   (nconc bindings (list (list result '(cons nil nil))))
1455                   (nconc bindings (list (list result-tail result)))
1456                   (while heads
1457                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1458                   (cdr bindings))
1459            (while (and ,@heads)
1460              (setcdr ,result-tail (cons (funcall ,function
1461                                                  ,@(mapcar (lambda (h) (list 'car h))
1462                                                            heads))
1463                                         nil))
1464              (setq ,result-tail (cdr ,result-tail)
1465                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1466            (cdr ,result)))
1467     `(mapcar ,function ,seq1)))
1468
1469 (if (fboundp 'merge)
1470     (defalias 'gnus-merge 'merge)
1471   ;; Adapted from cl-seq.el
1472   (defun gnus-merge (type list1 list2 pred)
1473     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1474 Argument TYPE is for compatibility and ignored.
1475 Ordering of the elements is preserved according to PRED, a `less-than'
1476 predicate on the elements."
1477     (let ((res nil))
1478       (while (and list1 list2)
1479         (if (funcall pred (car list2) (car list1))
1480             (push (pop list2) res)
1481           (push (pop list1) res)))
1482       (nconc (nreverse res) list1 list2))))
1483
1484 (eval-when-compile
1485   (defvar xemacs-codename)
1486   (defvar sxemacs-codename)
1487   (defvar emacs-program-version))
1488
1489 (defun gnus-emacs-version ()
1490   "Stringified Emacs version."
1491   (let* ((lst (if (listp gnus-user-agent)
1492                   gnus-user-agent
1493                 '(gnus emacs type)))
1494          (system-v (cond ((memq 'config lst)
1495                           system-configuration)
1496                          ((memq 'type lst)
1497                           (symbol-name system-type))
1498                          (t nil)))
1499          codename emacsname)
1500     (cond ((featurep 'sxemacs)
1501            (setq emacsname "SXEmacs"
1502                  codename sxemacs-codename))
1503           ((featurep 'xemacs)
1504            (setq emacsname "XEmacs"
1505                  codename xemacs-codename))
1506           (t
1507            (setq emacsname "Emacs")))
1508     (cond
1509      ((not (memq 'emacs lst))
1510       nil)
1511      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1512       ;; Emacs:
1513       (concat "Emacs/" (match-string 1 emacs-version)
1514               (if system-v
1515                   (concat " (" system-v ")")
1516                 "")))
1517      ((or (featurep 'sxemacs) (featurep 'xemacs))
1518       ;; XEmacs or SXEmacs:
1519       (concat emacsname "/" emacs-program-version
1520               " ("
1521               (when (and (memq 'codename lst)
1522                          codename)
1523                 (concat codename
1524                         (when system-v ", ")))
1525               (when system-v system-v)
1526               ")"))
1527      (t emacs-version))))
1528
1529 (defun gnus-rename-file (old-path new-path &optional trim)
1530   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1531 empty directories from OLD-PATH."
1532   (when (file-exists-p old-path)
1533     (let* ((old-dir (file-name-directory old-path))
1534            (old-name (file-name-nondirectory old-path))
1535            (new-dir (file-name-directory new-path))
1536            (new-name (file-name-nondirectory new-path))
1537            temp)
1538       (gnus-make-directory new-dir)
1539       (rename-file old-path new-path t)
1540       (when trim
1541         (while (progn (setq temp (directory-files old-dir))
1542                       (while (member (car temp) '("." ".."))
1543                         (setq temp (cdr temp)))
1544                       (= (length temp) 0))
1545           (delete-directory old-dir)
1546           (setq old-dir (file-name-as-directory
1547                          (file-truename
1548                           (concat old-dir "..")))))))))
1549
1550 (defun gnus-set-file-modes (filename mode)
1551   "Wrapper for set-file-modes."
1552   (ignore-errors
1553     (set-file-modes filename mode)))
1554
1555 (if (fboundp 'set-process-query-on-exit-flag)
1556     (defalias 'gnus-set-process-query-on-exit-flag
1557       'set-process-query-on-exit-flag)
1558   (defalias 'gnus-set-process-query-on-exit-flag
1559     'process-kill-without-query))
1560
1561 (provide 'gnus-util)
1562
1563 ;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
1564 ;;; gnus-util.el ends here