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