* lisp/subr.el (make-local-hook): Remove function obsolete since 21.1.
[bpt/emacs.git] / lisp / gnus / gnus-util.el
CommitLineData
eec82323 1;;; gnus-util.el --- utility functions for Gnus
e84b4b86 2
88e6695f 3;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
114f9c96 4;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
eec82323 5
6748645f 6;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
eec82323
LMI
7;; Keywords: news
8
9;; This file is part of GNU Emacs.
10
5e809f55 11;; GNU Emacs is free software: you can redistribute it and/or modify
eec82323 12;; it under the terms of the GNU General Public License as published by
5e809f55
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
eec82323
LMI
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
5e809f55 18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
eec82323
LMI
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
5e809f55 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
eec82323
LMI
23
24;;; Commentary:
25
26;; Nothing in this file depends on any other parts of Gnus -- all
27;; functions and macros in this file are utility functions that are
28;; used by Gnus and may be used by any other package without loading
29;; Gnus first.
30
23f87bed 31;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
01c52d31 32;; autoloads and defvars below...]
23f87bed 33
eec82323
LMI
34;;; Code:
35
88bfa2e4
GM
36;; For Emacs < 22.2.
37(eval-and-compile
38 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
5eee36fa 39(eval-when-compile
9efa445f 40 (require 'cl))
5cc79e5a
KY
41
42(eval-when-compile
43 (unless (fboundp 'with-no-warnings)
44 (defmacro with-no-warnings (&rest body)
45 `(progn ,@body))))
46
870409d4
G
47(defcustom gnus-completing-read-function 'gnus-emacs-completing-read
48 "Function use to do completing read."
967f57dc 49 :version "24.1"
229b59da 50 :group 'gnus-meta
870409d4
G
51 :type '(radio (function-item
52 :doc "Use Emacs standard `completing-read' function."
53 gnus-emacs-completing-read)
54 (function-item
55 :doc "Use `ido-completing-read' function."
56 gnus-ido-completing-read)
57 (function-item
58 :doc "Use iswitchb based completing-read function."
59 gnus-iswitchb-completing-read)))
229b59da
G
60
61(defcustom gnus-completion-styles
62 (if (and (boundp 'completion-styles-alist)
63 (boundp 'completion-styles))
64 (append (when (and (assq 'substring completion-styles-alist)
65 (not (memq 'substring completion-styles)))
66 (list 'substring))
67 completion-styles)
68 nil)
69 "Value of `completion-styles' to use when completing."
70 :version "24.1"
71 :group 'gnus-meta
72 :type 'list)
73
9efa445f
DN
74;; Fixme: this should be a gnus variable, not nnmail-.
75(defvar nnmail-pathname-coding-system)
76(defvar nnmail-active-file-coding-system)
77
78;; Inappropriate references to other parts of Gnus.
79(defvar gnus-emphasize-whitespace-regexp)
80(defvar gnus-original-article-buffer)
81(defvar gnus-user-agent)
82
dbb6c370 83(autoload 'gnus-get-buffer-window "gnus-win")
dbb6c370
GM
84(autoload 'nnheader-narrow-to-headers "nnheader")
85(autoload 'nnheader-replace-chars-in-string "nnheader")
09aece0b 86(autoload 'mail-header-remove-comments "mail-parse")
23f87bed
MB
87
88(eval-and-compile
89 (cond
f67d6742 90 ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
4b4f6dc8 91 ;; SXEmacs 22.1.4) over `replace-in-string'. The latter leads to inf-loops
f67d6742
MB
92 ;; on empty matches:
93 ;; (replace-in-string "foo" "/*$" "/")
94 ;; (replace-in-string "xe" "\\(x\\)?" "")
23f87bed 95 ((fboundp 'replace-regexp-in-string)
01c52d31 96 (defun gnus-replace-in-string (string regexp newtext &optional literal)
ad136a7c
MB
97 "Replace all matches for REGEXP with NEWTEXT in STRING.
98If LITERAL is non-nil, insert NEWTEXT literally. Return a new
99string containing the replacements.
100
101This is a compatibility function for different Emacsen."
23f87bed 102 (replace-regexp-in-string regexp newtext string nil literal)))
f67d6742 103 ((fboundp 'replace-in-string)
01c52d31 104 (defalias 'gnus-replace-in-string 'replace-in-string))))
eec82323
LMI
105
106(defun gnus-boundp (variable)
107 "Return non-nil if VARIABLE is bound and non-nil."
108 (and (boundp variable)
109 (symbol-value variable)))
110
111(defmacro gnus-eval-in-buffer-window (buffer &rest forms)
112 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
113 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
23f87bed
MB
114 (w (make-symbol "w"))
115 (buf (make-symbol "buf")))
eec82323 116 `(let* ((,tempvar (selected-window))
23f87bed
MB
117 (,buf ,buffer)
118 (,w (gnus-get-buffer-window ,buf 'visible)))
eec82323 119 (unwind-protect
23f87bed
MB
120 (progn
121 (if ,w
122 (progn
123 (select-window ,w)
124 (set-buffer (window-buffer ,w)))
125 (pop-to-buffer ,buf))
126 ,@forms)
127 (select-window ,tempvar)))))
eec82323
LMI
128
129(put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
130(put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
131
132(defmacro gnus-intern-safe (string hashtable)
815b81c8 133 "Get hash value. Arguments are STRING and HASHTABLE."
eec82323
LMI
134 `(let ((symbol (intern ,string ,hashtable)))
135 (or (boundp symbol)
136 (set symbol nil))
137 symbol))
138
eec82323
LMI
139(defsubst gnus-goto-char (point)
140 (and point (goto-char point)))
141
142(defmacro gnus-buffer-exists-p (buffer)
143 `(let ((buffer ,buffer))
144 (when buffer
145 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
146 buffer))))
147
23f87bed
MB
148;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
149;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
150;; It's harmless, though, so the main purpose of this alias is to shut
151;; up the byte compiler.
922ad43e
GM
152(defalias 'gnus-make-local-hook (if (featurep 'xemacs)
153 'make-local-hook
154 'ignore)
23f87bed 155
eec82323
LMI
156(defun gnus-delete-first (elt list)
157 "Delete by side effect the first occurrence of ELT as a member of LIST."
158 (if (equal (car list) elt)
159 (cdr list)
160 (let ((total list))
161 (while (and (cdr list)
162 (not (equal (cadr list) elt)))
163 (setq list (cdr list)))
164 (when (cdr list)
165 (setcdr list (cddr list)))
166 total)))
167
168;; Delete the current line (and the next N lines).
169(defmacro gnus-delete-line (&optional n)
01c52d31 170 `(delete-region (point-at-bol)
eec82323
LMI
171 (progn (forward-line ,(or n 1)) (point))))
172
173(defun gnus-byte-code (func)
174 "Return a form that can be `eval'ed based on FUNC."
6748645f
LMI
175 (let ((fval (indirect-function func)))
176 (if (byte-code-function-p fval)
eec82323
LMI
177 (let ((flist (append fval nil)))
178 (setcar flist 'byte-code)
179 flist)
180 (cons 'progn (cddr fval)))))
181
182(defun gnus-extract-address-components (from)
23f87bed
MB
183 "Extract address components from a From header.
184Given an RFC-822 address FROM, extract full name and canonical address.
185Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
186solution than `mail-extract-address-components', which works much better, but
187is slower."
eec82323
LMI
188 (let (name address)
189 ;; First find the address - the thing with the @ in it. This may
190 ;; not be accurate in mail addresses, but does the trick most of
191 ;; the time in news messages.
4573e0df
MB
192 (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
193 ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
194 ;; correctly.
195 (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
196 (setq address (substring from (match-beginning 1) (match-end 1))))
197 ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
198 (setq address (substring from (match-beginning 0) (match-end 0)))))
eec82323
LMI
199 ;; Then we check whether the "name <address>" format is used.
200 (and address
eec82323
LMI
201 ;; Linear white space is not required.
202 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
203 (and (setq name (substring from 0 (match-beginning 0)))
204 ;; Strip any quotes from the name.
23f87bed 205 (string-match "^\".*\"$" name)
eec82323
LMI
206 (setq name (substring name 1 (1- (match-end 0))))))
207 ;; If not, then "address (name)" is used.
208 (or name
209 (and (string-match "(.+)" from)
210 (setq name (substring from (1+ (match-beginning 0))
211 (1- (match-end 0)))))
212 (and (string-match "()" from)
213 (setq name address))
eec82323
LMI
214 ;; XOVER might not support folded From headers.
215 (and (string-match "(.*" from)
216 (setq name (substring from (1+ (match-beginning 0))
217 (match-end 0)))))
16409b0b
GM
218 (list (if (string= name "") nil name) (or address from))))
219
0ab5c2be
MB
220(defun gnus-extract-address-component-name (from)
221 "Extract name from a From header.
222Uses `gnus-extract-address-components'."
223 (nth 0 (gnus-extract-address-components from)))
224
225(defun gnus-extract-address-component-email (from)
226 "Extract e-mail address from a From header.
227Uses `gnus-extract-address-components'."
228 (nth 1 (gnus-extract-address-components from)))
eec82323 229
aa8f8277
GM
230(declare-function message-fetch-field "message" (header &optional not-all))
231
eec82323
LMI
232(defun gnus-fetch-field (field)
233 "Return the value of the header FIELD of current article."
aa8f8277 234 (require 'message)
eec82323
LMI
235 (save-excursion
236 (save-restriction
01c52d31 237 (let ((inhibit-point-motion-hooks t))
eec82323
LMI
238 (nnheader-narrow-to-headers)
239 (message-fetch-field field)))))
240
23f87bed
MB
241(defun gnus-fetch-original-field (field)
242 "Fetch FIELD from the original version of the current article."
243 (with-current-buffer gnus-original-article-buffer
244 (gnus-fetch-field field)))
245
246
eec82323
LMI
247(defun gnus-goto-colon ()
248 (beginning-of-line)
01c52d31 249 (let ((eol (point-at-eol)))
23f87bed
MB
250 (goto-char (or (text-property-any (point) eol 'gnus-position t)
251 (search-forward ":" eol t)
252 (point)))))
253
5ec7fe1b 254(declare-function gnus-find-method-for-group "gnus" (group &optional info))
aa8f8277 255(declare-function gnus-group-name-decode "gnus-group" (string charset))
5ec7fe1b
GM
256(declare-function gnus-group-name-charset "gnus-group" (method group))
257;; gnus-group requires gnus-int which requires message.
258(declare-function message-tokenize-header "message"
259 (header &optional separator))
260
23f87bed 261(defun gnus-decode-newsgroups (newsgroups group &optional method)
aa8f8277 262 (require 'gnus-group)
23f87bed
MB
263 (let ((method (or method (gnus-find-method-for-group group))))
264 (mapconcat (lambda (group)
265 (gnus-group-name-decode group (gnus-group-name-charset
266 method group)))
267 (message-tokenize-header newsgroups)
268 ",")))
eec82323
LMI
269
270(defun gnus-remove-text-with-property (prop)
271 "Delete all text in the current buffer with text property PROP."
01c52d31
MB
272 (let ((start (point-min))
273 end)
274 (unless (get-text-property start prop)
275 (setq start (next-single-property-change start prop)))
276 (while start
277 (setq end (text-property-any start (point-max) prop nil))
278 (delete-region start (or end (point-max)))
279 (setq start (when end
280 (next-single-property-change start prop))))))
eec82323
LMI
281
282(defun gnus-newsgroup-directory-form (newsgroup)
283 "Make hierarchical directory name from NEWSGROUP name."
23f87bed
MB
284 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
285 (idx (string-match ":" newsgroup)))
286 (concat
287 (if idx (substring newsgroup 0 idx))
288 (if idx "/")
289 (nnheader-replace-chars-in-string
290 (if idx (substring newsgroup (1+ idx)) newsgroup)
291 ?. ?/))))
eec82323
LMI
292
293(defun gnus-newsgroup-savable-name (group)
294 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
295 ;; with dots.
296 (nnheader-replace-chars-in-string group ?/ ?.))
297
298(defun gnus-string> (s1 s2)
299 (not (or (string< s1 s2)
300 (string= s1 s2))))
301
b4fde39f
MB
302(defun gnus-string< (s1 s2)
303 "Return t if first arg string is less than second in lexicographic order.
304Case is significant if and only if `case-fold-search' is nil.
305Symbols are also allowed; their print names are used instead."
306 (if case-fold-search
307 (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
308 (downcase (if (symbolp s2) (symbol-name s2) s2)))
309 (string-lessp s1 s2)))
310
eec82323
LMI
311;;; Time functions.
312
eec82323
LMI
313(defun gnus-file-newer-than (file date)
314 (let ((fdate (nth 5 (file-attributes file))))
315 (or (> (car fdate) (car date))
316 (and (= (car fdate) (car date))
317 (> (nth 1 fdate) (nth 1 date))))))
318
de0bdfe7
KY
319(eval-and-compile
320 (if (and (fboundp 'float-time)
321 (subrp (symbol-function 'float-time)))
322 (defalias 'gnus-float-time 'float-time)
323 (defun gnus-float-time (&optional time)
324 "Convert time value TIME to a floating point number.
c506adde 325TIME defaults to the current time."
de0bdfe7 326 (with-no-warnings (time-to-seconds (or time (current-time)))))))
feefd9f3 327
eec82323
LMI
328;;; Keymap macros.
329
330(defmacro gnus-local-set-keys (&rest plist)
331 "Set the keys in PLIST in the current keymap."
332 `(gnus-define-keys-1 (current-local-map) ',plist))
333
334(defmacro gnus-define-keys (keymap &rest plist)
335 "Define all keys in PLIST in KEYMAP."
336 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
337
338(defmacro gnus-define-keys-safe (keymap &rest plist)
339 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
340 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
341
342(put 'gnus-define-keys 'lisp-indent-function 1)
343(put 'gnus-define-keys-safe 'lisp-indent-function 1)
344(put 'gnus-local-set-keys 'lisp-indent-function 1)
345
346(defmacro gnus-define-keymap (keymap &rest plist)
347 "Define all keys in PLIST in KEYMAP."
348 `(gnus-define-keys-1 ,keymap (quote ,plist)))
349
350(put 'gnus-define-keymap 'lisp-indent-function 1)
351
352(defun gnus-define-keys-1 (keymap plist &optional safe)
353 (when (null keymap)
354 (error "Can't set keys in a null keymap"))
355 (cond ((symbolp keymap)
356 (setq keymap (symbol-value keymap)))
357 ((keymapp keymap))
358 ((listp keymap)
359 (set (car keymap) nil)
360 (define-prefix-command (car keymap))
361 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
362 (setq keymap (symbol-value (car keymap)))))
363 (let (key)
364 (while plist
365 (when (symbolp (setq key (pop plist)))
366 (setq key (symbol-value key)))
367 (if (or (not safe)
368 (eq (lookup-key keymap key) 'undefined))
369 (define-key keymap key (pop plist))
370 (pop plist)))))
371
eec82323
LMI
372;; Two silly functions to ensure that all `y-or-n-p' questions clear
373;; the echo area.
bbbe940b 374;;
52bec650
MB
375;; Do we really need these functions? Workarounds for bugs in the corresponding
376;; Emacs functions? Maybe these bugs are no longer present in any supported
bbbe940b 377;; (X)Emacs version? Alias them to the original functions and see if anyone
52bec650
MB
378;; reports a problem. If not, replace with original functions. --rsteib,
379;; 2007-12-14
bbbe940b 380;;
52bec650
MB
381;; All supported Emacsen clear the echo area after `yes-or-no-p', so we can
382;; remove `yes-or-no-p'. RMS says that not clearing after `y-or-n-p' is
383;; intentional (see below), so we could remove `gnus-y-or-n-p' too.
384;; Objections? --rsteib, 2008-02-16
385;;
386;; ,----[ http://thread.gmane.org/gmane.emacs.gnus.general/65099/focus=66070 ]
387;; | From: Richard Stallman
388;; | Subject: Re: Do we need gnus-yes-or-no-p and gnus-y-or-n-p?
389;; | To: Katsumi Yamaoka [...]
390;; | Cc: emacs-devel@[...], xemacs-beta@[...], ding@[...]
391;; | Date: Mon, 07 Jan 2008 12:16:05 -0500
392;; | Message-ID: <E1JBva1-000528-VY@fencepost.gnu.org>
393;; |
394;; | The behavior of `y-or-n-p' that it doesn't clear the question
395;; | and the answer is not serious of course, but I feel it is not
396;; | cool.
397;; |
398;; | It is intentional.
399;; |
400;; | Currently, it is commented out in the trunk by Reiner Steib. He
401;; | also wrote the benefit of leaving the question and the answer in
402;; | the echo area as follows:
403;; |
404;; | (http://article.gmane.org/gmane.emacs.gnus.general/66061)
405;; | > In contrast to yes-or-no-p it is much easier to type y, n,
406;; | > SPC, DEL, etc accidentally, so it might be useful for the user
407;; | > to see what he has typed.
408;; |
409;; | Yes, that is the reason.
410;; `----
411
bbbe940b
MB
412;; (defun gnus-y-or-n-p (prompt)
413;; (prog1
414;; (y-or-n-p prompt)
415;; (message "")))
416;; (defun gnus-yes-or-no-p (prompt)
417;; (prog1
418;; (yes-or-no-p prompt)
419;; (message "")))
420
421(defalias 'gnus-y-or-n-p 'y-or-n-p)
422(defalias 'gnus-yes-or-no-p 'yes-or-no-p)
eec82323 423
23f87bed
MB
424;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
425;; age-depending date representations. (e.g. just the time if it's
426;; from today, the day of the week if it's within the last 7 days and
427;; the full date if it's older)
428
429(defun gnus-seconds-today ()
430 "Return the number of seconds passed today."
431 (let ((now (decode-time (current-time))))
432 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
433
434(defun gnus-seconds-month ()
435 "Return the number of seconds passed this month."
436 (let ((now (decode-time (current-time))))
437 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
438 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
439
440(defun gnus-seconds-year ()
441 "Return the number of seconds passed this year."
442 (let ((now (decode-time (current-time)))
443 (days (format-time-string "%j" (current-time))))
444 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
445 (* (- (string-to-number days) 1) 3600 24))))
446
89a13959
RF
447(defmacro gnus-date-get-time (date)
448 "Convert DATE string to Emacs time.
449Cache the result as a text property stored in DATE."
450 ;; Either return the cached value...
451 `(let ((d ,date))
452 (if (equal "" d)
453 '(0 0)
454 (or (get-text-property 0 'gnus-time d)
455 ;; or compute the value...
456 (let ((time (safe-date-to-time d)))
457 ;; and store it back in the string.
458 (put-text-property 0 1 'gnus-time time d)
459 time)))))
460
23f87bed
MB
461(defvar gnus-user-date-format-alist
462 '(((gnus-seconds-today) . "%k:%M")
463 (604800 . "%a %k:%M") ;;that's one week
464 ((gnus-seconds-month) . "%a %d")
465 ((gnus-seconds-year) . "%b %d")
466 (t . "%b %d '%y")) ;;this one is used when no
467 ;;other does match
468 "Specifies date format depending on age of article.
469This is an alist of items (AGE . FORMAT). AGE can be a number (of
470seconds) or a Lisp expression evaluating to a number. When the age of
471the article is less than this number, then use `format-time-string'
472with the corresponding FORMAT for displaying the date of the article.
473If AGE is not a number or a Lisp expression evaluating to a
474non-number, then the corresponding FORMAT is used as a default value.
475
476Note that the list is processed from the beginning, so it should be
477sorted by ascending AGE. Also note that items following the first
478non-number AGE will be ignored.
479
480You can use the functions `gnus-seconds-today', `gnus-seconds-month'
481and `gnus-seconds-year' in the AGE spec. They return the number of
482seconds passed since the start of today, of this month, of this year,
483respectively.")
484
485(defun gnus-user-date (messy-date)
486 "Format the messy-date according to gnus-user-date-format-alist.
3d6e7a43 487Returns \" ? \" if there's bad input or if another error occurs.
23f87bed
MB
488Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
489 (condition-case ()
3d6e7a43 490 (let* ((messy-date (gnus-float-time (gnus-date-get-time messy-date)))
1a727c75 491 (now (gnus-float-time))
23f87bed
MB
492 ;;If we don't find something suitable we'll use this one
493 (my-format "%b %d '%y"))
494 (let* ((difference (- now messy-date))
495 (templist gnus-user-date-format-alist)
496 (top (eval (caar templist))))
497 (while (if (numberp top) (< top difference) (not top))
498 (progn
499 (setq templist (cdr templist))
500 (setq top (eval (caar templist)))))
501 (if (stringp (cdr (car templist)))
502 (setq my-format (cdr (car templist)))))
503 (format-time-string (eval my-format) (seconds-to-time messy-date)))
504 (error " ? ")))
505
eec82323 506(defun gnus-dd-mmm (messy-date)
6748645f 507 "Return a string like DD-MMM from a big messy string."
16409b0b 508 (condition-case ()
3d6e7a43 509 (format-time-string "%d-%b" (gnus-date-get-time messy-date))
16409b0b 510 (error " - ")))
eec82323 511
eec82323 512(defsubst gnus-time-iso8601 (time)
8b93df01 513 "Return a string of TIME in YYYYMMDDTHHMMSS format."
eec82323
LMI
514 (format-time-string "%Y%m%dT%H%M%S" time))
515
6748645f 516(defun gnus-date-iso8601 (date)
8b93df01 517 "Convert the DATE to YYYYMMDDTHHMMSS."
eec82323 518 (condition-case ()
6748645f 519 (gnus-time-iso8601 (gnus-date-get-time date))
eec82323
LMI
520 (error "")))
521
522(defun gnus-mode-string-quote (string)
523 "Quote all \"%\"'s in STRING."
23f87bed 524 (gnus-replace-in-string string "%" "%%"))
eec82323
LMI
525
526;; Make a hash table (default and minimum size is 256).
527;; Optional argument HASHSIZE specifies the table size.
528(defun gnus-make-hashtable (&optional hashsize)
529 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
530
531;; Make a number that is suitable for hashing; bigger than MIN and
532;; equal to some 2^x. Many machines (such as sparcs) do not have a
533;; hardware modulo operation, so they implement it in software. On
534;; many sparcs over 50% of the time to intern is spent in the modulo.
535;; Yes, it's slower than actually computing the hash from the string!
536;; So we use powers of 2 so people can optimize the modulo to a mask.
537(defun gnus-create-hash-size (min)
538 (let ((i 1))
539 (while (< i min)
540 (setq i (* 2 i)))
541 i))
542
543(defcustom gnus-verbose 7
544 "*Integer that says how verbose Gnus should be.
545The higher the number, the more messages Gnus will flash to say what
546it's doing. At zero, Gnus will be totally mute; at five, Gnus will
547display most important messages; and at ten, Gnus will keep on
548jabbering all the time."
549 :group 'gnus-start
550 :type 'integer)
551
01c52d31
MB
552(defcustom gnus-add-timestamp-to-message nil
553 "Non-nil means add timestamps to messages that Gnus issues.
554If it is `log', add timestamps to only the messages that go into the
555\"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
556If it is neither nil nor `log', add timestamps not only to log messages
557but also to the ones displayed in the echo area."
330f707b 558 :version "23.1" ;; No Gnus
01c52d31
MB
559 :group 'gnus-various
560 :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
561 (const :tag "Logged messages only" log)
562 (sexp :tag "All messages"
563 :match (lambda (widget value) value)
564 :value t)
565 (const :tag "No timestamp" nil)))
566
567(eval-when-compile
568 (defmacro gnus-message-with-timestamp-1 (format-string args)
569 (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
570 "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
571 (if (featurep 'xemacs)
572 `(let (str time)
573 (if (or (and (null ,format-string) (null ,args))
574 (progn
575 (setq str (apply 'format ,format-string ,args))
576 (zerop (length str))))
577 (prog1
578 (and ,format-string str)
579 (clear-message nil))
580 (cond ((eq gnus-add-timestamp-to-message 'log)
581 (setq time (current-time))
582 (display-message 'no-log str)
583 (log-message 'message (concat ,@timestamp str)))
584 (gnus-add-timestamp-to-message
585 (setq time (current-time))
586 (display-message 'message (concat ,@timestamp str)))
587 (t
588 (display-message 'message str))))
589 str)
590 `(let (str time)
591 (cond ((eq gnus-add-timestamp-to-message 'log)
592 (setq str (let (message-log-max)
593 (apply 'message ,format-string ,args)))
594 (when (and message-log-max
595 (> message-log-max 0)
596 (/= (length str) 0))
597 (setq time (current-time))
598 (with-current-buffer (get-buffer-create "*Messages*")
599 (goto-char (point-max))
600 (insert ,@timestamp str "\n")
601 (forward-line (- message-log-max))
602 (delete-region (point-min) (point))
603 (goto-char (point-max))))
604 str)
605 (gnus-add-timestamp-to-message
606 (if (or (and (null ,format-string) (null ,args))
607 (progn
608 (setq str (apply 'format ,format-string ,args))
609 (zerop (length str))))
610 (prog1
611 (and ,format-string str)
612 (message nil))
613 (setq time (current-time))
614 (message "%s" (concat ,@timestamp str))
615 str))
616 (t
617 (apply 'message ,format-string ,args))))))))
618
4478e074
G
619(defvar gnus-action-message-log nil)
620
01c52d31
MB
621(defun gnus-message-with-timestamp (format-string &rest args)
622 "Display message with timestamp. Arguments are the same as `message'.
623The `gnus-add-timestamp-to-message' variable controls how to add
624timestamp to message."
625 (gnus-message-with-timestamp-1 format-string args))
626
eec82323 627(defun gnus-message (level &rest args)
23f87bed
MB
628 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
629
630Guideline for numbers:
6311 - error messages, 3 - non-serious error messages, 5 - messages for things
632that take a long time, 7 - not very important messages on stuff, 9 - messages
633inside loops."
eec82323 634 (if (<= level gnus-verbose)
4478e074
G
635 (let ((message
636 (if gnus-add-timestamp-to-message
637 (apply 'gnus-message-with-timestamp args)
638 (apply 'message args))))
639 (when (and (consp gnus-action-message-log)
640 (<= level 3))
641 (push message gnus-action-message-log))
642 message)
eec82323
LMI
643 ;; We have to do this format thingy here even if the result isn't
644 ;; shown - the return value has to be the same as the return value
645 ;; from `message'.
646 (apply 'format args)))
647
4478e074
G
648(defun gnus-final-warning ()
649 (when (and (consp gnus-action-message-log)
650 (setq gnus-action-message-log
651 (delete nil gnus-action-message-log)))
652 (message "Warning: %s"
653 (mapconcat #'identity gnus-action-message-log "; "))))
654
eec82323 655(defun gnus-error (level &rest args)
6203370b
MB
656 "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
657ARGS are passed to `message'."
eec82323
LMI
658 (when (<= (floor level) gnus-verbose)
659 (apply 'message args)
660 (ding)
661 (let (duration)
662 (when (and (floatp level)
663 (not (zerop (setq duration (* 10 (- level (floor level)))))))
664 (sit-for duration))))
665 nil)
666
667(defun gnus-split-references (references)
668 "Return a list of Message-IDs in REFERENCES."
669 (let ((beg 0)
521c4a23 670 (references (mail-header-remove-comments (or references "")))
eec82323 671 ids)
23f87bed 672 (while (string-match "<[^<]+[^< \t]" references beg)
eec82323
LMI
673 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
674 ids))
675 (nreverse ids)))
676
01c52d31
MB
677(defun gnus-extract-references (references)
678 "Return a list of Message-IDs in REFERENCES (in In-Reply-To
679 format), trimmed to only contain the Message-IDs."
680 (let ((ids (gnus-split-references references))
681 refs)
682 (dolist (id ids)
683 (when (string-match "<[^<>]+>" id)
684 (push (match-string 0 id) refs)))
685 refs))
686
16409b0b 687(defsubst gnus-parent-id (references &optional n)
eec82323
LMI
688 "Return the last Message-ID in REFERENCES.
689If N, return the Nth ancestor instead."
23f87bed
MB
690 (when (and references
691 (not (zerop (length references))))
692 (if n
693 (let ((ids (inline (gnus-split-references references))))
694 (while (nthcdr n ids)
695 (setq ids (cdr ids)))
696 (car ids))
521c4a23
AS
697 (let ((references (mail-header-remove-comments references)))
698 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
699 (match-string 1 references))))))
23f87bed
MB
700
701(defun gnus-buffer-live-p (buffer)
eec82323
LMI
702 "Say whether BUFFER is alive or not."
703 (and buffer
704 (get-buffer buffer)
705 (buffer-name (get-buffer buffer))))
706
707(defun gnus-horizontal-recenter ()
708 "Recenter the current buffer horizontally."
709 (if (< (current-column) (/ (window-width) 2))
23f87bed 710 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
eec82323 711 (let* ((orig (point))
23f87bed 712 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
eec82323 713 (max 0))
6748645f
LMI
714 (when end
715 ;; Find the longest line currently displayed in the window.
716 (goto-char (window-start))
717 (while (and (not (eobp))
718 (< (point) end))
719 (end-of-line)
720 (setq max (max max (current-column)))
721 (forward-line 1))
722 (goto-char orig)
723 ;; Scroll horizontally to center (sort of) the point.
724 (if (> max (window-width))
725 (set-window-hscroll
23f87bed 726 (gnus-get-buffer-window (current-buffer) t)
6748645f
LMI
727 (min (- (current-column) (/ (window-width) 3))
728 (+ 2 (- max (window-width)))))
23f87bed 729 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
6748645f 730 max))))
eec82323 731
23f87bed 732(defun gnus-read-event-char (&optional prompt)
eec82323 733 "Get the next event."
23f87bed 734 (let ((event (read-event prompt)))
eec82323
LMI
735 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
736 (cons (and (numberp event) event) event)))
737
738(defun gnus-sortable-date (date)
16409b0b
GM
739 "Make string suitable for sorting from DATE."
740 (gnus-time-iso8601 (date-to-time date)))
eec82323
LMI
741
742(defun gnus-copy-file (file &optional to)
743 "Copy FILE to TO."
744 (interactive
745 (list (read-file-name "Copy file: " default-directory)
746 (read-file-name "Copy file to: " default-directory)))
747 (unless to
748 (setq to (read-file-name "Copy file to: " default-directory)))
749 (when (file-directory-p to)
750 (setq to (concat (file-name-as-directory to)
751 (file-name-nondirectory file))))
752 (copy-file file to))
753
eec82323
LMI
754(defvar gnus-work-buffer " *gnus work*")
755
5ec7fe1b
GM
756(declare-function gnus-get-buffer-create "gnus" (name))
757;; gnus.el requires mm-util.
758(declare-function mm-enable-multibyte "mm-util")
759
eec82323
LMI
760(defun gnus-set-work-buffer ()
761 "Put point in the empty Gnus work buffer."
762 (if (get-buffer gnus-work-buffer)
763 (progn
764 (set-buffer gnus-work-buffer)
765 (erase-buffer))
6748645f 766 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
eec82323 767 (kill-all-local-variables)
16409b0b 768 (mm-enable-multibyte)))
eec82323
LMI
769
770(defmacro gnus-group-real-name (group)
771 "Find the real name of a foreign newsgroup."
772 `(let ((gname ,group))
773 (if (string-match "^[^:]+:" gname)
774 (substring gname (match-end 0))
775 gname)))
776
6c5d6b6c
MB
777(defmacro gnus-group-server (group)
778 "Find the server name of a foreign newsgroup.
779For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
780yield \"nnimap:yxa\"."
781 `(let ((gname ,group))
782 (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
783 (format "%s:%s" (match-string 1 gname) (or
784 (match-string 2 gname)
785 ""))
786 (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
787
eec82323 788(defun gnus-make-sort-function (funs)
23f87bed 789 "Return a composite sort condition based on the functions in FUNS."
eec82323 790 (cond
16409b0b 791 ;; Just a simple function.
23f87bed 792 ((functionp funs) funs)
16409b0b 793 ;; No functions at all.
eec82323 794 ((null funs) funs)
16409b0b
GM
795 ;; A list of functions.
796 ((or (cdr funs)
797 (listp (car funs)))
23f87bed
MB
798 (gnus-byte-compile
799 `(lambda (t1 t2)
800 ,(gnus-make-sort-function-1 (reverse funs)))))
16409b0b 801 ;; A list containing just one function.
eec82323
LMI
802 (t
803 (car funs))))
804
805(defun gnus-make-sort-function-1 (funs)
23f87bed 806 "Return a composite sort condition based on the functions in FUNS."
16409b0b
GM
807 (let ((function (car funs))
808 (first 't1)
809 (last 't2))
810 (when (consp function)
811 (cond
812 ;; Reversed spec.
813 ((eq (car function) 'not)
814 (setq function (cadr function)
815 first 't2
816 last 't1))
23f87bed 817 ((functionp function)
16409b0b
GM
818 ;; Do nothing.
819 )
820 (t
821 (error "Invalid sort spec: %s" function))))
822 (if (cdr funs)
823 `(or (,function ,first ,last)
824 (and (not (,function ,last ,first))
825 ,(gnus-make-sort-function-1 (cdr funs))))
826 `(,function ,first ,last))))
eec82323
LMI
827
828(defun gnus-turn-off-edit-menu (type)
829 "Turn off edit menu in `gnus-TYPE-mode-map'."
830 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
831 [menu-bar edit] 'undefined))
832
23f87bed
MB
833(defmacro gnus-bind-print-variables (&rest forms)
834 "Bind print-* variables and evaluate FORMS.
835This macro is used with `prin1', `pp', etc. in order to ensure printed
836Lisp objects are loadable. Bind `print-quoted' and `print-readably'
837to t, and `print-escape-multibyte', `print-escape-newlines',
838`print-escape-nonascii', `print-length', `print-level' and
839`print-string-length' to nil."
840 `(let ((print-quoted t)
841 (print-readably t)
842 ;;print-circle
843 ;;print-continuous-numbering
844 print-escape-multibyte
845 print-escape-newlines
846 print-escape-nonascii
847 ;;print-gensym
848 print-length
849 print-level
850 print-string-length)
851 ,@forms))
852
eec82323
LMI
853(defun gnus-prin1 (form)
854 "Use `prin1' on FORM in the current buffer.
23f87bed
MB
855Bind `print-quoted' and `print-readably' to t, and `print-length' and
856`print-level' to nil. See also `gnus-bind-print-variables'."
857 (gnus-bind-print-variables (prin1 form (current-buffer))))
eec82323
LMI
858
859(defun gnus-prin1-to-string (form)
23f87bed
MB
860 "The same as `prin1'.
861Bind `print-quoted' and `print-readably' to t, and `print-length' and
862`print-level' to nil. See also `gnus-bind-print-variables'."
863 (gnus-bind-print-variables (prin1-to-string form)))
864
01c52d31 865(defun gnus-pp (form &optional stream)
23f87bed
MB
866 "Use `pp' on FORM in the current buffer.
867Bind `print-quoted' and `print-readably' to t, and `print-length' and
868`print-level' to nil. See also `gnus-bind-print-variables'."
01c52d31 869 (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
23f87bed
MB
870
871(defun gnus-pp-to-string (form)
872 "The same as `pp-to-string'.
873Bind `print-quoted' and `print-readably' to t, and `print-length' and
874`print-level' to nil. See also `gnus-bind-print-variables'."
875 (gnus-bind-print-variables (pp-to-string form)))
eec82323
LMI
876
877(defun gnus-make-directory (directory)
878 "Make DIRECTORY (and all its parents) if it doesn't exist."
5eee36fa 879 (require 'nnmail)
16409b0b
GM
880 (let ((file-name-coding-system nnmail-pathname-coding-system))
881 (when (and directory
882 (not (file-exists-p directory)))
883 (make-directory directory t)))
eec82323
LMI
884 t)
885
886(defun gnus-write-buffer (file)
887 "Write the current buffer's contents to FILE."
16409b0b 888 (let ((file-name-coding-system nnmail-pathname-coding-system))
01c52d31
MB
889 ;; Make sure the directory exists.
890 (gnus-make-directory (file-name-directory file))
16409b0b
GM
891 ;; Write the buffer.
892 (write-region (point-min) (point-max) file nil 'quietly)))
eec82323 893
eec82323
LMI
894(defun gnus-delete-file (file)
895 "Delete FILE if it exists."
896 (when (file-exists-p file)
897 (delete-file file)))
898
aa0a8561
MB
899(defun gnus-delete-directory (directory)
900 "Delete files in DIRECTORY. Subdirectories remain.
901If there's no subdirectory, delete DIRECTORY as well."
902 (when (file-directory-p directory)
903 (let ((files (directory-files
904 directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
905 file dir)
906 (while files
907 (setq file (pop files))
908 (if (eq t (car (file-attributes file)))
909 ;; `file' is a subdirectory.
910 (setq dir t)
911 ;; `file' is a file or a symlink.
912 (delete-file file)))
913 (unless dir
914 (delete-directory directory)))))
915
996aa8c1
MB
916;; The following two functions are used in gnus-registry.
917;; They were contributed by Andreas Fuchs <asf@void.at>.
918(defun gnus-alist-to-hashtable (alist)
919 "Build a hashtable from the values in ALIST."
920 (let ((ht (make-hash-table
921 :size 4096
922 :test 'equal)))
923 (mapc
924 (lambda (kv-pair)
925 (puthash (car kv-pair) (cdr kv-pair) ht))
926 alist)
927 ht))
928
929(defun gnus-hashtable-to-alist (hash)
930 "Build an alist from the values in HASH."
931 (let ((list nil))
932 (maphash
933 (lambda (key value)
934 (setq list (cons (cons key value) list)))
935 hash)
936 list))
937
eec82323
LMI
938(defun gnus-strip-whitespace (string)
939 "Return STRING stripped of all whitespace."
940 (while (string-match "[\r\n\t ]+" string)
941 (setq string (replace-match "" t t string)))
942 string)
943
5ec7fe1b
GM
944(declare-function gnus-put-text-property "gnus"
945 (start end property value &optional object))
946
16409b0b 947(defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
eec82323
LMI
948 "The same as `put-text-property', but don't put this prop on any newlines in the region."
949 (save-match-data
950 (save-excursion
951 (save-restriction
952 (goto-char beg)
16409b0b 953 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
6748645f 954 (gnus-put-text-property beg (match-beginning 0) prop val)
eec82323 955 (setq beg (point)))
6748645f
LMI
956 (gnus-put-text-property beg (point) prop val)))))
957
5ec7fe1b
GM
958(declare-function gnus-overlay-put "gnus" (overlay prop value))
959(declare-function gnus-make-overlay "gnus"
960 (beg end &optional buffer front-advance rear-advance))
961
23f87bed
MB
962(defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
963 "The same as `put-text-property', but don't put this prop on any newlines in the region."
964 (save-match-data
965 (save-excursion
966 (save-restriction
967 (goto-char beg)
968 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
969 (gnus-overlay-put
970 (gnus-make-overlay beg (match-beginning 0))
971 prop val)
972 (setq beg (point)))
973 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
974
6748645f
LMI
975(defun gnus-put-text-property-excluding-characters-with-faces (beg end
976 prop val)
977 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
978 (let ((b beg))
979 (while (/= b end)
980 (when (get-text-property b 'gnus-face)
981 (setq b (next-single-property-change b 'gnus-face nil end)))
982 (when (/= b end)
23f87bed
MB
983 (inline
984 (gnus-put-text-property
985 b (setq b (next-single-property-change b 'gnus-face nil end))
986 prop val))))))
987
988(defmacro gnus-faces-at (position)
989 "Return a list of faces at POSITION."
990 (if (featurep 'xemacs)
991 `(let ((pos ,position))
992 (mapcar-extents 'extent-face
993 nil (current-buffer) pos pos nil 'face))
994 `(let ((pos ,position))
995 (delq nil (cons (get-text-property pos 'face)
996 (mapcar
997 (lambda (overlay)
998 (overlay-get overlay 'face))
999 (overlays-at pos)))))))
eec82323 1000
770d9a1f
KY
1001(if (fboundp 'invisible-p)
1002 (defalias 'gnus-invisible-p 'invisible-p)
1003 ;; for Emacs < 22.2, and XEmacs.
1004 (defun gnus-invisible-p (pos)
1005 "Return non-nil if the character after POS is currently invisible."
1006 (let ((prop (get-char-property pos 'invisible)))
1007 (if (eq buffer-invisibility-spec t)
1008 prop
1009 (or (memq prop buffer-invisibility-spec)
1010 (assq prop buffer-invisibility-spec))))))
1011
1012;; Note: the optional 2nd argument has a different meaning between
1013;; Emacs and XEmacs.
1014;; (next-char-property-change POSITION &optional LIMIT)
1015;; (next-extent-change POS &optional OBJECT)
1016(defalias 'gnus-next-char-property-change
1017 (if (fboundp 'next-extent-change)
1018 'next-extent-change 'next-char-property-change))
1019
1020(defalias 'gnus-previous-char-property-change
1021 (if (fboundp 'previous-extent-change)
1022 'previous-extent-change 'previous-char-property-change))
1023
eec82323 1024;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
d346bf7e
SM
1025;; The primary idea here is to try to protect internal datastructures
1026;; from becoming corrupted when the user hits C-g, or if a hook or
1027;; similar blows up. Often in Gnus multiple tables/lists need to be
1028;; updated at the same time, or information can be lost.
eec82323
LMI
1029
1030(defvar gnus-atomic-be-safe t
1031 "If t, certain operations will be protected from interruption by C-g.")
1032
1033(defmacro gnus-atomic-progn (&rest forms)
1034 "Evaluate FORMS atomically, which means to protect the evaluation
1035from being interrupted by the user. An error from the forms themselves
1036will return without finishing the operation. Since interrupts from
1037the user are disabled, it is recommended that only the most minimal
1038operations are performed by FORMS. If you wish to assign many
1039complicated values atomically, compute the results into temporary
1040variables and then do only the assignment atomically."
1041 `(let ((inhibit-quit gnus-atomic-be-safe))
1042 ,@forms))
1043
1044(put 'gnus-atomic-progn 'lisp-indent-function 0)
1045
1046(defmacro gnus-atomic-progn-assign (protect &rest forms)
d346bf7e 1047 "Evaluate FORMS, but ensure that the variables listed in PROTECT
eec82323
LMI
1048are not changed if anything in FORMS signals an error or otherwise
1049non-locally exits. The variables listed in PROTECT are updated atomically.
1050It is safe to use gnus-atomic-progn-assign with long computations.
1051
1052Note that if any of the symbols in PROTECT were unbound, they will be
8f688cb0 1053set to nil on a successful assignment. In case of an error or other
eec82323
LMI
1054non-local exit, it will still be unbound."
1055 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
1056 (concat (symbol-name x)
1057 "-tmp"))
1058 x))
1059 protect))
1060 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
1061 temp-sym-map))
1062 (temp-sym-let (mapcar (lambda (x) (list (car x)
1063 `(and (boundp ',(cadr x))
1064 ,(cadr x))))
1065 temp-sym-map))
1066 (sym-temp-let sym-temp-map)
1067 (temp-sym-assign (apply 'append temp-sym-map))
1068 (sym-temp-assign (apply 'append sym-temp-map))
1069 (result (make-symbol "result-tmp")))
1070 `(let (,@temp-sym-let
1071 ,result)
1072 (let ,sym-temp-let
1073 (setq ,result (progn ,@forms))
1074 (setq ,@temp-sym-assign))
1075 (let ((inhibit-quit gnus-atomic-be-safe))
1076 (setq ,@sym-temp-assign))
1077 ,result)))
1078
1079(put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
1080;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
1081
1082(defmacro gnus-atomic-setq (&rest pairs)
1083 "Similar to setq, except that the real symbols are only assigned when
1084there are no errors. And when the real symbols are assigned, they are
1085done so atomically. If other variables might be changed via side-effect,
1086see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
1087with potentially long computations."
1088 (let ((tpairs pairs)
1089 syms)
1090 (while tpairs
1091 (push (car tpairs) syms)
1092 (setq tpairs (cddr tpairs)))
1093 `(gnus-atomic-progn-assign ,syms
1094 (setq ,@pairs))))
1095
1096;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
1097
1098
1099;;; Functions for saving to babyl/mail files.
1100
23f87bed 1101(eval-when-compile
62fe59e7
KY
1102 (if (featurep 'xemacs)
1103 ;; Don't load tm and apel XEmacs packages that provide some
1104 ;; Emacs emulating functions and variables.
1105 (let ((features features))
1106 (provide 'tm-view)
1107 (unless (fboundp 'set-alist) (defalias 'set-alist 'ignore))
1108 (require 'rmail)) ;; It requires tm-view that loads apel.
1109 (require 'rmail))
1110 (autoload 'rmail-update-summary "rmailsum"))
9efa445f 1111
9efa445f 1112(defvar mm-text-coding-system)
23f87bed 1113
88bfa2e4
GM
1114(declare-function mm-append-to-file "mm-util"
1115 (start end filename &optional codesys inhibit))
1116
eec82323 1117(defun gnus-output-to-rmail (filename &optional ask)
e38658c4
GM
1118 "Append the current article to an Rmail file named FILENAME.
1119In Emacs 22 this writes Babyl format; in Emacs 23 it writes mbox unless
1120FILENAME exists and is Babyl format."
eec82323 1121 (require 'rmail)
23f87bed 1122 (require 'mm-util)
e38658c4 1123 ;; Some of this codes is borrowed from rmailout.el.
eec82323 1124 (setq filename (expand-file-name filename))
e38658c4
GM
1125 ;; FIXME should we really be messing with this defcustom?
1126 ;; It is not needed for the operation of this function.
1127 (if (boundp 'rmail-default-rmail-file)
1128 (setq rmail-default-rmail-file filename) ; 22
1129 (setq rmail-default-file filename)) ; 23
eec82323 1130 (let ((artbuf (current-buffer))
e38658c4
GM
1131 (tmpbuf (get-buffer-create " *Gnus-output*"))
1132 ;; Babyl rmail.el defines this, mbox does not.
1133 (babyl (fboundp 'rmail-insert-rmail-file-header)))
eec82323 1134 (save-excursion
e38658c4
GM
1135 ;; Note that we ignore the possibility of visiting a Babyl
1136 ;; format buffer in Emacs 23, since Rmail no longer supports that.
1137 (or (get-file-buffer filename)
1138 (progn
1139 ;; In case someone wants to write to a Babyl file from Emacs 23.
1140 (when (file-exists-p filename)
1141 (setq babyl (mail-file-babyl-p filename))
1142 t))
eec82323
LMI
1143 (if (or (not ask)
1144 (gnus-yes-or-no-p
1145 (concat "\"" filename "\" does not exist, create it? ")))
1146 (let ((file-buffer (create-file-buffer filename)))
20a673b2 1147 (with-current-buffer file-buffer
e38658c4
GM
1148 (if (fboundp 'rmail-insert-rmail-file-header)
1149 (rmail-insert-rmail-file-header))
16409b0b
GM
1150 (let ((require-final-newline nil)
1151 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
1152 (gnus-write-buffer filename)))
1153 (kill-buffer file-buffer))
1154 (error "Output file does not exist")))
1155 (set-buffer tmpbuf)
1156 (erase-buffer)
1157 (insert-buffer-substring artbuf)
e38658c4
GM
1158 (if babyl
1159 (gnus-convert-article-to-rmail)
1160 ;; Non-Babyl case copied from gnus-output-to-mail.
1161 (goto-char (point-min))
1162 (if (looking-at "From ")
1163 (forward-line 1)
1164 (insert "From nobody " (current-time-string) "\n"))
1165 (let (case-fold-search)
1166 (while (re-search-forward "^From " nil t)
1167 (beginning-of-line)
1168 (insert ">"))))
eec82323
LMI
1169 ;; Decide whether to append to a file or to an Emacs buffer.
1170 (let ((outbuf (get-file-buffer filename)))
1171 (if (not outbuf)
e38658c4
GM
1172 (progn
1173 (unless babyl ; from gnus-output-to-mail
1174 (let ((buffer-read-only nil))
1175 (goto-char (point-max))
1176 (forward-char -2)
1177 (unless (looking-at "\n\n")
1178 (goto-char (point-max))
1179 (unless (bolp)
1180 (insert "\n"))
1181 (insert "\n"))))
1182 (let ((file-name-coding-system nnmail-pathname-coding-system))
1183 (mm-append-to-file (point-min) (point-max) filename)))
eec82323
LMI
1184 ;; File has been visited, in buffer OUTBUF.
1185 (set-buffer outbuf)
1186 (let ((buffer-read-only nil)
1187 (msg (and (boundp 'rmail-current-message)
1188 (symbol-value 'rmail-current-message))))
1189 ;; If MSG is non-nil, buffer is in RMAIL mode.
e38658c4 1190 ;; Compare this with rmail-output-to-rmail-buffer in Emacs 23.
eec82323 1191 (when msg
e38658c4
GM
1192 (unless babyl
1193 (rmail-swap-buffers-maybe)
1194 (rmail-maybe-set-message-counters))
1195 (widen)
1196 (narrow-to-region (point-max) (point-max)))
eec82323
LMI
1197 (insert-buffer-substring tmpbuf)
1198 (when msg
e38658c4
GM
1199 (when babyl
1200 (goto-char (point-min))
1201 (widen)
1202 (search-backward "\n\^_")
1203 (narrow-to-region (point) (point-max)))
23f87bed
MB
1204 (rmail-count-new-messages t)
1205 (when (rmail-summary-exists)
6748645f
LMI
1206 (rmail-select-summary
1207 (rmail-update-summary)))
6748645f
LMI
1208 (rmail-show-message msg))
1209 (save-buffer)))))
eec82323
LMI
1210 (kill-buffer tmpbuf)))
1211
1212(defun gnus-output-to-mail (filename &optional ask)
1213 "Append the current article to a mail file named FILENAME."
1214 (setq filename (expand-file-name filename))
1215 (let ((artbuf (current-buffer))
1216 (tmpbuf (get-buffer-create " *Gnus-output*")))
1217 (save-excursion
1218 ;; Create the file, if it doesn't exist.
1219 (when (and (not (get-file-buffer filename))
1220 (not (file-exists-p filename)))
1221 (if (or (not ask)
1222 (gnus-y-or-n-p
1223 (concat "\"" filename "\" does not exist, create it? ")))
1224 (let ((file-buffer (create-file-buffer filename)))
20a673b2 1225 (with-current-buffer file-buffer
16409b0b
GM
1226 (let ((require-final-newline nil)
1227 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
1228 (gnus-write-buffer filename)))
1229 (kill-buffer file-buffer))
1230 (error "Output file does not exist")))
1231 (set-buffer tmpbuf)
1232 (erase-buffer)
1233 (insert-buffer-substring artbuf)
1234 (goto-char (point-min))
1235 (if (looking-at "From ")
1236 (forward-line 1)
1237 (insert "From nobody " (current-time-string) "\n"))
1238 (let (case-fold-search)
1239 (while (re-search-forward "^From " nil t)
1240 (beginning-of-line)
1241 (insert ">")))
1242 ;; Decide whether to append to a file or to an Emacs buffer.
1243 (let ((outbuf (get-file-buffer filename)))
1244 (if (not outbuf)
1245 (let ((buffer-read-only nil))
1246 (save-excursion
1247 (goto-char (point-max))
1248 (forward-char -2)
1249 (unless (looking-at "\n\n")
1250 (goto-char (point-max))
1251 (unless (bolp)
1252 (insert "\n"))
1253 (insert "\n"))
1254 (goto-char (point-max))
47e77e9f
SZ
1255 (let ((file-name-coding-system nnmail-pathname-coding-system))
1256 (mm-append-to-file (point-min) (point-max) filename))))
eec82323
LMI
1257 ;; File has been visited, in buffer OUTBUF.
1258 (set-buffer outbuf)
1259 (let ((buffer-read-only nil))
1260 (goto-char (point-max))
1261 (unless (eobp)
1262 (insert "\n"))
1263 (insert "\n")
1264 (insert-buffer-substring tmpbuf)))))
1265 (kill-buffer tmpbuf)))
1266
1267(defun gnus-convert-article-to-rmail ()
1268 "Convert article in current buffer to Rmail message format."
1269 (let ((buffer-read-only nil))
1270 ;; Convert article directly into Babyl format.
1271 (goto-char (point-min))
1272 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1273 (while (search-forward "\n\^_" nil t) ;single char
1274 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
1275 (goto-char (point-max))
1276 (insert "\^_")))
1277
6748645f 1278(defun gnus-map-function (funs arg)
23f87bed 1279 "Apply the result of the first function in FUNS to the second, and so on.
6748645f 1280ARG is passed to the first function."
23f87bed
MB
1281 (while funs
1282 (setq arg (funcall (pop funs) arg)))
1283 arg)
6748645f
LMI
1284
1285(defun gnus-run-hooks (&rest funcs)
23f87bed
MB
1286 "Does the same as `run-hooks', but saves the current buffer."
1287 (save-current-buffer
1288 (apply 'run-hooks funcs)))
6748645f 1289
b4e8a25b 1290(defun gnus-run-mode-hooks (&rest funcs)
cfcd5c91
MB
1291 "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1292This function saves the current buffer."
b4e8a25b 1293 (if (fboundp 'run-mode-hooks)
cfcd5c91
MB
1294 (save-current-buffer (apply 'run-mode-hooks funcs))
1295 (save-current-buffer (apply 'run-hooks funcs))))
b4e8a25b 1296
6748645f
LMI
1297;;; Various
1298
16409b0b 1299(defvar gnus-group-buffer) ; Compiler directive
6748645f
LMI
1300(defun gnus-alive-p ()
1301 "Say whether Gnus is running or not."
1302 (and (boundp 'gnus-group-buffer)
1303 (get-buffer gnus-group-buffer)
20a673b2 1304 (with-current-buffer gnus-group-buffer
6748645f
LMI
1305 (eq major-mode 'gnus-group-mode))))
1306
23f87bed
MB
1307(defun gnus-remove-if (predicate list)
1308 "Return a copy of LIST with all items satisfying PREDICATE removed."
6748645f
LMI
1309 (let (out)
1310 (while list
1311 (unless (funcall predicate (car list))
1312 (push (car list) out))
23f87bed 1313 (setq list (cdr list)))
6748645f
LMI
1314 (nreverse out)))
1315
23f87bed
MB
1316(if (fboundp 'assq-delete-all)
1317 (defalias 'gnus-delete-alist 'assq-delete-all)
1318 (defun gnus-delete-alist (key alist)
1319 "Delete from ALIST all elements whose car is KEY.
1320Return the modified alist."
1321 (let (entry)
1322 (while (setq entry (assq key alist))
1323 (setq alist (delq entry alist)))
1324 alist)))
6748645f 1325
77154961
KY
1326(defun gnus-grep-in-list (word list)
1327 "Find if a WORD matches any regular expression in the given LIST."
1328 (when (and word list)
1329 (catch 'found
1330 (dolist (r list)
1331 (when (string-match r word)
1332 (throw 'found r))))))
1333
16409b0b 1334(defmacro gnus-pull (key alist &optional assoc-p)
6748645f
LMI
1335 "Modify ALIST to be without KEY."
1336 (unless (symbolp alist)
1337 (error "Not a symbol: %s" alist))
16409b0b
GM
1338 (let ((fun (if assoc-p 'assoc 'assq)))
1339 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
6748645f
LMI
1340
1341(defun gnus-globalify-regexp (re)
e7f767c2 1342 "Return a regexp that matches a whole line, if RE matches a part of it."
6748645f
LMI
1343 (concat (unless (string-match "^\\^" re) "^.*")
1344 re
1345 (unless (string-match "\\$$" re) ".*$")))
1346
16409b0b
GM
1347(defun gnus-set-window-start (&optional point)
1348 "Set the window start to POINT, or (point) if nil."
23f87bed 1349 (let ((win (gnus-get-buffer-window (current-buffer) t)))
16409b0b
GM
1350 (when win
1351 (set-window-start win (or point (point))))))
1352
1353(defun gnus-annotation-in-region-p (b e)
1354 (if (= b e)
1355 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1356 (text-property-any b e 'gnus-undeletable t)))
1357
1358(defun gnus-or (&rest elems)
1359 "Return non-nil if any of the elements are non-nil."
1360 (catch 'found
1361 (while elems
1362 (when (pop elems)
1363 (throw 'found t)))))
1364
1365(defun gnus-and (&rest elems)
1366 "Return non-nil if all of the elements are non-nil."
1367 (catch 'found
1368 (while elems
1369 (unless (pop elems)
1370 (throw 'found nil)))
1371 t))
1372
5ec7fe1b
GM
1373;; gnus.el requires mm-util.
1374(declare-function mm-disable-multibyte "mm-util")
1375
16409b0b 1376(defun gnus-write-active-file (file hashtb &optional full-names)
01c52d31 1377 ;; `coding-system-for-write' should be `raw-text' or equivalent.
16409b0b
GM
1378 (let ((coding-system-for-write nnmail-active-file-coding-system))
1379 (with-temp-file file
01c52d31
MB
1380 ;; The buffer should be in the unibyte mode because group names
1381 ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1382 (mm-disable-multibyte)
16409b0b
GM
1383 (mapatoms
1384 (lambda (sym)
1385 (when (and sym
1386 (boundp sym)
1387 (symbol-value sym))
1388 (insert (format "%S %d %d y\n"
1389 (if full-names
1390 sym
1391 (intern (gnus-group-real-name (symbol-name sym))))
1392 (or (cdr (symbol-value sym))
1393 (car (symbol-value sym)))
1394 (car (symbol-value sym))))))
1395 hashtb)
1396 (goto-char (point-max))
1397 (while (search-backward "\\." nil t)
1398 (delete-char 1)))))
1399
23f87bed
MB
1400;; Fixme: Why not use `with-output-to-temp-buffer'?
1401(defmacro gnus-with-output-to-file (file &rest body)
1402 (let ((buffer (make-symbol "output-buffer"))
1403 (size (make-symbol "output-buffer-size"))
1404 (leng (make-symbol "output-buffer-length"))
1405 (append (make-symbol "output-buffer-append")))
1406 `(let* ((,size 131072)
1407 (,buffer (make-string ,size 0))
1408 (,leng 0)
1409 (,append nil)
1410 (standard-output
1411 (lambda (c)
1412 (aset ,buffer ,leng c)
bf247b6e 1413
23f87bed
MB
1414 (if (= ,size (setq ,leng (1+ ,leng)))
1415 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1416 (setq ,leng 0
1417 ,append t))))))
1418 ,@body
1419 (when (> ,leng 0)
1420 (let ((coding-system-for-write 'no-conversion))
1421 (write-region (substring ,buffer 0 ,leng) nil ,file
1422 ,append 'no-msg))))))
1423
1424(put 'gnus-with-output-to-file 'lisp-indent-function 1)
1425(put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1426
1427(if (fboundp 'union)
1428 (defalias 'gnus-union 'union)
1429 (defun gnus-union (l1 l2)
1430 "Set union of lists L1 and L2."
1431 (cond ((null l1) l2)
1432 ((null l2) l1)
1433 ((equal l1 l2) l1)
1434 (t
1435 (or (>= (length l1) (length l2))
1436 (setq l1 (prog1 l2 (setq l2 l1))))
1437 (while l2
1438 (or (member (car l2) l1)
1439 (push (car l2) l1))
1440 (pop l2))
1441 l1))))
1442
5ec7fe1b
GM
1443(declare-function gnus-add-text-properties "gnus"
1444 (start end properties &optional object))
1445
520aa572
SZ
1446(defun gnus-add-text-properties-when
1447 (property value start end properties &optional object)
1448 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1449 (let (point)
3d8c35d3 1450 (while (and start
23f87bed 1451 (< start end) ;; XEmacs will loop for every when start=end.
520aa572
SZ
1452 (setq point (text-property-not-all start end property value)))
1453 (gnus-add-text-properties start point properties object)
1454 (setq start (text-property-any point end property value)))
1455 (if start
1456 (gnus-add-text-properties start end properties object))))
1457
1458(defun gnus-remove-text-properties-when
1459 (property value start end properties &optional object)
1460 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1461 (let (point)
3d8c35d3 1462 (while (and start
23f87bed 1463 (< start end)
520aa572
SZ
1464 (setq point (text-property-not-all start end property value)))
1465 (remove-text-properties start point properties object)
1466 (setq start (text-property-any point end property value)))
1467 (if start
4481aa98
SZ
1468 (remove-text-properties start end properties object))
1469 t))
520aa572 1470
01c52d31
MB
1471(defun gnus-string-remove-all-properties (string)
1472 (condition-case ()
1473 (let ((s string))
1474 (set-text-properties 0 (length string) nil string)
1475 s)
1476 (error string)))
1477
23f87bed
MB
1478;; This might use `compare-strings' to reduce consing in the
1479;; case-insensitive case, but it has to cope with null args.
1480;; (`string-equal' uses symbol print names.)
1481(defun gnus-string-equal (x y)
1482 "Like `string-equal', except it compares case-insensitively."
1483 (and (= (length x) (length y))
1484 (or (string-equal x y)
1485 (string-equal (downcase x) (downcase y)))))
1486
1487(defcustom gnus-use-byte-compile t
1488 "If non-nil, byte-compile crucial run-time code.
1489Setting it to nil has no effect after the first time `gnus-byte-compile'
1490is run."
1491 :type 'boolean
bf247b6e 1492 :version "22.1"
23f87bed
MB
1493 :group 'gnus-various)
1494
1495(defun gnus-byte-compile (form)
1496 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1497 (if gnus-use-byte-compile
1498 (progn
1499 (condition-case nil
1500 ;; Work around a bug in XEmacs 21.4
1501 (require 'byte-optimize)
1502 (error))
1503 (require 'bytecomp)
1504 (defalias 'gnus-byte-compile
1505 (lambda (form)
1506 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1507 (byte-compile form))))
1508 (gnus-byte-compile form))
1509 form))
1510
1511(defun gnus-remassoc (key alist)
1512 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1513The modified LIST is returned. If the first member
1514of LIST has a car that is `equal' to KEY, there is no way to remove it
54506618 1515by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
23f87bed
MB
1516sure of changing the value of `foo'."
1517 (when alist
1518 (if (equal key (caar alist))
1519 (cdr alist)
1520 (setcdr alist (gnus-remassoc key (cdr alist)))
1521 alist)))
1522
1523(defun gnus-update-alist-soft (key value alist)
1524 (if value
1525 (cons (cons key value) (gnus-remassoc key alist))
1526 (gnus-remassoc key alist)))
1527
1528(defun gnus-create-info-command (node)
1529 "Create a command that will go to info NODE."
1530 `(lambda ()
1531 (interactive)
1532 ,(concat "Enter the info system at node " node)
1533 (Info-goto-node ,node)
1534 (setq gnus-info-buffer (current-buffer))
1535 (gnus-configure-windows 'info)))
1536
1537(defun gnus-not-ignore (&rest args)
1538 t)
1539
47b63dfa
SZ
1540(defvar gnus-directory-sep-char-regexp "/"
1541 "The regexp of directory separator character.
1542If you find some problem with the directory separator character, try
1543\"[/\\\\\]\" for some systems.")
1544
23f87bed
MB
1545(defun gnus-url-unhex (x)
1546 (if (> x ?9)
1547 (if (>= x ?a)
1548 (+ 10 (- x ?a))
1549 (+ 10 (- x ?A)))
1550 (- x ?0)))
1551
1552;; Fixme: Do it like QP.
1553(defun gnus-url-unhex-string (str &optional allow-newlines)
1554 "Remove %XX, embedded spaces, etc in a url.
1555If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1556decoding of carriage returns and line feeds in the string, which is normally
1557forbidden in URL encoding."
1558 (let ((tmp "")
1559 (case-fold-search t))
1560 (while (string-match "%[0-9a-f][0-9a-f]" str)
1561 (let* ((start (match-beginning 0))
1562 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1563 (code (+ (* 16 ch1)
1564 (gnus-url-unhex (elt str (+ start 2))))))
1565 (setq tmp (concat
1566 tmp (substring str 0 start)
1567 (cond
1568 (allow-newlines
1569 (char-to-string code))
1570 ((or (= code ?\n) (= code ?\r))
1571 " ")
1572 (t (char-to-string code))))
1573 str (substring str (match-end 0)))))
1574 (setq tmp (concat tmp str))
1575 tmp))
1576
1577(defun gnus-make-predicate (spec)
1578 "Transform SPEC into a function that can be called.
1579SPEC is a predicate specifier that contains stuff like `or', `and',
1580`not', lists and functions. The functions all take one parameter."
1581 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1582
1583(defun gnus-make-predicate-1 (spec)
1584 (cond
1585 ((symbolp spec)
1586 `(,spec elem))
1587 ((listp spec)
1588 (if (memq (car spec) '(or and not))
1589 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1590 (error "Invalid predicate specifier: %s" spec)))))
1591
229b59da
G
1592(defun gnus-completing-read (prompt collection &optional require-match
1593 initial-input history def)
870409d4
G
1594 "Call `gnus-completing-read-function'."
1595 (funcall gnus-completing-read-function
1596 (concat prompt (when def
1597 (concat " (default " def ")"))
1598 ": ")
1599 collection require-match initial-input history def))
1600
1601(defun gnus-emacs-completing-read (prompt collection &optional require-match
1602 initial-input history def)
1603 "Call standard `completing-read-function'."
229b59da 1604 (let ((completion-styles gnus-completion-styles))
870409d4
G
1605 (completing-read prompt collection nil require-match initial-input history def)))
1606
1607(defun gnus-ido-completing-read (prompt collection &optional require-match
1608 initial-input history def)
1609 "Call `ido-completing-read-function'."
1610 (require 'ido)
1611 (ido-completing-read prompt collection nil require-match initial-input history def))
1612
1613(defun gnus-iswitchb-completing-read (prompt collection &optional require-match
1614 initial-input history def)
1615 "`iswitchb' based completing-read function."
1616 (require 'iswitchb)
1617 (let ((iswitchb-make-buflist-hook
1618 (lambda ()
1619 (setq iswitchb-temp-buflist
1620 (let ((choices (append
1621 (when initial-input (list initial-input))
1622 (symbol-value history) collection))
1623 filtered-choices)
1624 (dolist (x choices)
1625 (setq filtered-choices (adjoin x filtered-choices)))
1626 (nreverse filtered-choices))))))
1627 (unwind-protect
1628 (progn
1629 (when (not iswitchb-mode)
1630 (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
1631 (iswitchb-read-buffer prompt def require-match))
1632 (when (not iswitchb-mode)
1633 (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
23f87bed
MB
1634
1635(defun gnus-graphic-display-p ()
73137971
KY
1636 (if (featurep 'xemacs)
1637 (device-on-window-system-p)
1638 (display-graphic-p)))
23f87bed
MB
1639
1640(put 'gnus-parse-without-error 'lisp-indent-function 0)
1641(put 'gnus-parse-without-error 'edebug-form-spec '(body))
1642
1643(defmacro gnus-parse-without-error (&rest body)
1644 "Allow continuing onto the next line even if an error occurs."
1645 `(while (not (eobp))
1646 (condition-case ()
1647 (progn
1648 ,@body
1649 (goto-char (point-max)))
1650 (error
1651 (gnus-error 4 "Invalid data on line %d"
1652 (count-lines (point-min) (point)))
1653 (forward-line 1)))))
1654
1655(defun gnus-cache-file-contents (file variable function)
1656 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1657 (let ((time (nth 5 (file-attributes file)))
1658 contents value)
1659 (if (or (null (setq value (symbol-value variable)))
1660 (not (equal (car value) file))
1661 (not (equal (nth 1 value) time)))
1662 (progn
1663 (setq contents (funcall function file))
1664 (set variable (list file time contents))
1665 contents)
1666 (nth 2 value))))
1667
1668(defun gnus-multiple-choice (prompt choice &optional idx)
1669 "Ask user a multiple choice question.
1670CHOICE is a list of the choice char and help message at IDX."
1671 (let (tchar buf)
1672 (save-window-excursion
1673 (save-excursion
1674 (while (not tchar)
1675 (message "%s (%s): "
1676 prompt
1677 (concat
1678 (mapconcat (lambda (s) (char-to-string (car s)))
1679 choice ", ") ", ?"))
1680 (setq tchar (read-char))
1681 (when (not (assq tchar choice))
1682 (setq tchar nil)
1683 (setq buf (get-buffer-create "*Gnus Help*"))
1684 (pop-to-buffer buf)
1685 (fundamental-mode) ; for Emacs 20.4+
1686 (buffer-disable-undo)
1687 (erase-buffer)
1688 (insert prompt ":\n\n")
1689 (let ((max -1)
1690 (list choice)
1691 (alist choice)
1692 (idx (or idx 1))
1693 (i 0)
1694 n width pad format)
1695 ;; find the longest string to display
1696 (while list
1697 (setq n (length (nth idx (car list))))
1698 (unless (> max n)
1699 (setq max n))
1700 (setq list (cdr list)))
1701 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1702 (setq n (/ (1- (window-width)) max)) ; items per line
1703 (setq width (/ (1- (window-width)) n)) ; width of each item
1704 ;; insert `n' items, each in a field of width `width'
1705 (while alist
1706 (if (< i n)
1707 ()
1708 (setq i 0)
1709 (delete-char -1) ; the `\n' takes a char
1710 (insert "\n"))
1711 (setq pad (- width 3))
1712 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1713 (insert (format format (caar alist) (nth idx (car alist))))
1714 (setq alist (cdr alist))
1715 (setq i (1+ i))))))))
1716 (if (buffer-live-p buf)
1717 (kill-buffer buf))
1718 tchar))
1719
5843126b
KY
1720(if (fboundp 'select-frame-set-input-focus)
1721 (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
1722 ;; XEmacs 21.4, SXEmacs
1723 (defun gnus-select-frame-set-input-focus (frame)
1724 "Select FRAME, raise it, and set input focus, if possible."
1725 (raise-frame frame)
1726 (select-frame frame)
1727 (focus-frame frame)))
23f87bed
MB
1728
1729(defun gnus-frame-or-window-display-name (object)
1730 "Given a frame or window, return the associated display name.
1731Return nil otherwise."
1732 (if (featurep 'xemacs)
1733 (device-connection (dfw-device object))
1734 (if (or (framep object)
1735 (and (windowp object)
1736 (setq object (window-frame object))))
1737 (let ((display (frame-parameter object 'display)))
1738 (if (and (stringp display)
1739 ;; Exclude invalid display names.
1740 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1741 display))
1742 display)))))
1743
9efa445f 1744(defvar tool-bar-mode)
531bedc3 1745
85fd8002
RS
1746(defun gnus-tool-bar-update (&rest ignore)
1747 "Update the tool bar."
1748 (when (and (boundp 'tool-bar-mode)
1749 tool-bar-mode)
1750 (let* ((args nil)
1751 (func (cond ((featurep 'xemacs)
1752 'ignore)
1753 ((fboundp 'tool-bar-update)
1754 'tool-bar-update)
1755 ((fboundp 'force-window-update)
1756 'force-window-update)
1757 ((fboundp 'redraw-frame)
1758 (setq args (list (selected-frame)))
1759 'redraw-frame)
1760 (t 'ignore))))
1761 (apply func args))))
1762
23f87bed
MB
1763;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1764(defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1765 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1766If there are several sequences, FUNCTION is called with that many arguments,
1767and mapping stops as soon as the shortest sequence runs out. With just one
1768sequence, this is like `mapcar'. With several, it is like the Common Lisp
1769`mapcar' function extended to arbitrary sequence types."
1770
1771 (if seqs2_n
1772 (let* ((seqs (cons seq1 seqs2_n))
1773 (cnt 0)
1774 (heads (mapcar (lambda (seq)
1775 (make-symbol (concat "head"
1776 (int-to-string
1777 (setq cnt (1+ cnt))))))
1778 seqs))
1779 (result (make-symbol "result"))
1780 (result-tail (make-symbol "result-tail")))
1781 `(let* ,(let* ((bindings (cons nil nil))
1782 (heads heads))
1783 (nconc bindings (list (list result '(cons nil nil))))
1784 (nconc bindings (list (list result-tail result)))
1785 (while heads
1786 (nconc bindings (list (list (pop heads) (pop seqs)))))
1787 (cdr bindings))
1788 (while (and ,@heads)
1789 (setcdr ,result-tail (cons (funcall ,function
1790 ,@(mapcar (lambda (h) (list 'car h))
1791 heads))
1792 nil))
1793 (setq ,result-tail (cdr ,result-tail)
1794 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1795 (cdr ,result)))
1796 `(mapcar ,function ,seq1)))
1797
1798(if (fboundp 'merge)
1799 (defalias 'gnus-merge 'merge)
1800 ;; Adapted from cl-seq.el
1801 (defun gnus-merge (type list1 list2 pred)
1802 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1803Argument TYPE is for compatibility and ignored.
1804Ordering of the elements is preserved according to PRED, a `less-than'
1805predicate on the elements."
1806 (let ((res nil))
1807 (while (and list1 list2)
1808 (if (funcall pred (car list2) (car list1))
1809 (push (pop list2) res)
1810 (push (pop list1) res)))
1811 (nconc (nreverse res) list1 list2))))
1812
9efa445f
DN
1813(defvar xemacs-codename)
1814(defvar sxemacs-codename)
1815(defvar emacs-program-version)
23f87bed
MB
1816
1817(defun gnus-emacs-version ()
1818 "Stringified Emacs version."
4a2358e9
MB
1819 (let* ((lst (if (listp gnus-user-agent)
1820 gnus-user-agent
1821 '(gnus emacs type)))
1822 (system-v (cond ((memq 'config lst)
1823 system-configuration)
1824 ((memq 'type lst)
1825 (symbol-name system-type))
1826 (t nil)))
1827 codename emacsname)
1828 (cond ((featurep 'sxemacs)
1829 (setq emacsname "SXEmacs"
1830 codename sxemacs-codename))
1831 ((featurep 'xemacs)
1832 (setq emacsname "XEmacs"
1833 codename xemacs-codename))
1834 (t
1835 (setq emacsname "Emacs")))
23f87bed 1836 (cond
4a2358e9 1837 ((not (memq 'emacs lst))
23f87bed
MB
1838 nil)
1839 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
4a2358e9 1840 ;; Emacs:
23f87bed
MB
1841 (concat "Emacs/" (match-string 1 emacs-version)
1842 (if system-v
1843 (concat " (" system-v ")")
1844 "")))
4a2358e9
MB
1845 ((or (featurep 'sxemacs) (featurep 'xemacs))
1846 ;; XEmacs or SXEmacs:
1847 (concat emacsname "/" emacs-program-version
01c52d31
MB
1848 (let (plst)
1849 (when (memq 'codename lst)
1850 (push codename plst))
1851 (when system-v
1852 (push system-v plst))
1853 (unless (featurep 'mule)
1854 (push "no MULE" plst))
1855 (when (> (length plst) 0)
1856 (concat
1857 " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
23f87bed
MB
1858 (t emacs-version))))
1859
54506618
MB
1860(defun gnus-rename-file (old-path new-path &optional trim)
1861 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1862empty directories from OLD-PATH."
1863 (when (file-exists-p old-path)
1864 (let* ((old-dir (file-name-directory old-path))
1865 (old-name (file-name-nondirectory old-path))
1866 (new-dir (file-name-directory new-path))
1867 (new-name (file-name-nondirectory new-path))
1868 temp)
1869 (gnus-make-directory new-dir)
1870 (rename-file old-path new-path t)
1871 (when trim
1872 (while (progn (setq temp (directory-files old-dir))
1873 (while (member (car temp) '("." ".."))
1874 (setq temp (cdr temp)))
1875 (= (length temp) 0))
1876 (delete-directory old-dir)
bf247b6e
KS
1877 (setq old-dir (file-name-as-directory
1878 (file-truename
54506618
MB
1879 (concat old-dir "..")))))))))
1880
01c52d31
MB
1881(defun gnus-set-file-modes (filename mode)
1882 "Wrapper for set-file-modes."
1883 (ignore-errors
1884 (set-file-modes filename mode)))
1885
4a43ee9b
MB
1886(if (fboundp 'set-process-query-on-exit-flag)
1887 (defalias 'gnus-set-process-query-on-exit-flag
1888 'set-process-query-on-exit-flag)
1889 (defalias 'gnus-set-process-query-on-exit-flag
1890 'process-kill-without-query))
54506618 1891
996aa8c1
MB
1892(if (fboundp 'with-local-quit)
1893 (defalias 'gnus-with-local-quit 'with-local-quit)
1894 (defmacro gnus-with-local-quit (&rest body)
1895 "Execute BODY, allowing quits to terminate BODY but not escape further.
1896When a quit terminates BODY, `gnus-with-local-quit' returns nil but
1897requests another quit. That quit will be processed as soon as quitting
1898is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
1899 ;;(declare (debug t) (indent 0))
1900 `(condition-case nil
1901 (let ((inhibit-quit nil))
1902 ,@body)
1903 (quit (setq quit-flag t)
1904 ;; This call is to give a chance to handle quit-flag
1905 ;; in case inhibit-quit is nil.
1906 ;; Without this, it will not be handled until the next function
1907 ;; call, and that might allow it to exit thru a condition-case
1908 ;; that intends to handle the quit signal next time.
1909 (eval '(ignore nil))))))
1910
d346bf7e
SM
1911(defalias 'gnus-read-shell-command
1912 (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
1913
2b968687
MB
1914(defmacro gnus-put-display-table (range value display-table)
1915 "Set the value for char RANGE to VALUE in DISPLAY-TABLE. "
1916 (if (featurep 'xemacs)
1917 (progn
1918 `(if (fboundp 'put-display-table)
1919 (put-display-table ,range ,value ,display-table)
1920 (if (sequencep ,display-table)
1921 (aset ,display-table ,range ,value)
1922 (put-char-table ,range ,value ,display-table))))
1923 `(aset ,display-table ,range ,value)))
1924
1925(defmacro gnus-get-display-table (character display-table)
1926 "Find value for CHARACTER in DISPLAY-TABLE. "
1927 (if (featurep 'xemacs)
1928 `(if (fboundp 'get-display-table)
1929 (get-display-table ,character ,display-table)
1930 (if (sequencep ,display-table)
1931 (aref ,display-table ,character)
1932 (get-char-table ,character ,display-table)))
1933 `(aref ,display-table ,character)))
1934
eec82323
LMI
1935(provide 'gnus-util)
1936
1937;;; gnus-util.el ends here