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