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