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