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