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