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