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