*** empty log message ***
[bpt/emacs.git] / lisp / gnus / gnus-util.el
CommitLineData
eec82323 1;;; gnus-util.el --- utility functions for Gnus
23f87bed 2;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
16409b0b 3;; 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
10;; GNU Emacs is free software; you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
12;; the Free Software Foundation; either version 2, or (at your option)
13;; any later version.
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
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
21;; along with GNU Emacs; see the file COPYING. If not, write to the
22;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23;; Boston, MA 02111-1307, USA.
24
25;;; Commentary:
26
27;; Nothing in this file depends on any other parts of Gnus -- all
28;; functions and macros in this file are utility functions that are
29;; used by Gnus and may be used by any other package without loading
30;; Gnus first.
31
23f87bed
MB
32;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
33;; autoloads below...]
34
eec82323
LMI
35;;; Code:
36
37(require 'custom)
5eee36fa
DL
38(eval-when-compile
39 (require 'cl)
40 ;; Fixme: this should be a gnus variable, not nnmail-.
54506618
MB
41 (defvar nnmail-pathname-coding-system)
42
43 ;; Inappropriate references to other parts of Gnus.
44 (defvar gnus-emphasize-whitespace-regexp)
45 )
16409b0b 46(require 'time-date)
23f87bed 47(require 'netrc)
eec82323
LMI
48
49(eval-and-compile
c4fedaa0 50 (autoload 'message-fetch-field "message")
23f87bed 51 (autoload 'gnus-get-buffer-window "gnus-win")
6748645f
LMI
52 (autoload 'rmail-insert-rmail-file-header "rmail")
53 (autoload 'rmail-count-new-messages "rmail")
23f87bed
MB
54 (autoload 'rmail-show-message "rmail")
55 (autoload 'nnheader-narrow-to-headers "nnheader")
56 (autoload 'nnheader-replace-chars-in-string "nnheader"))
57
58(eval-and-compile
59 (cond
60 ((fboundp 'replace-in-string)
61 (defalias 'gnus-replace-in-string 'replace-in-string))
62 ((fboundp 'replace-regexp-in-string)
ad136a7c
MB
63 (defun gnus-replace-in-string (string regexp newtext &optional literal)
64 "Replace all matches for REGEXP with NEWTEXT in STRING.
65If LITERAL is non-nil, insert NEWTEXT literally. Return a new
66string containing the replacements.
67
68This is a compatibility function for different Emacsen."
23f87bed
MB
69 (replace-regexp-in-string regexp newtext string nil literal)))
70 (t
71 (defun gnus-replace-in-string (string regexp newtext &optional literal)
ad136a7c
MB
72 "Replace all matches for REGEXP with NEWTEXT in STRING.
73If LITERAL is non-nil, insert NEWTEXT literally. Return a new
74string containing the replacements.
75
76This is a compatibility function for different Emacsen."
23f87bed
MB
77 (let ((start 0) tail)
78 (while (string-match regexp string start)
79 (setq tail (- (length string) (match-end 0)))
80 (setq string (replace-match newtext nil literal string))
81 (setq start (- (length string) tail))))
82 string))))
83
84;;; bring in the netrc functions as aliases
85(defalias 'gnus-netrc-get 'netrc-get)
86(defalias 'gnus-netrc-machine 'netrc-machine)
87(defalias 'gnus-parse-netrc 'netrc-parse)
eec82323
LMI
88
89(defun gnus-boundp (variable)
90 "Return non-nil if VARIABLE is bound and non-nil."
91 (and (boundp variable)
92 (symbol-value variable)))
93
94(defmacro gnus-eval-in-buffer-window (buffer &rest forms)
95 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
96 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
23f87bed
MB
97 (w (make-symbol "w"))
98 (buf (make-symbol "buf")))
eec82323 99 `(let* ((,tempvar (selected-window))
23f87bed
MB
100 (,buf ,buffer)
101 (,w (gnus-get-buffer-window ,buf 'visible)))
eec82323 102 (unwind-protect
23f87bed
MB
103 (progn
104 (if ,w
105 (progn
106 (select-window ,w)
107 (set-buffer (window-buffer ,w)))
108 (pop-to-buffer ,buf))
109 ,@forms)
110 (select-window ,tempvar)))))
eec82323
LMI
111
112(put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
113(put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
114
115(defmacro gnus-intern-safe (string hashtable)
116 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
117 `(let ((symbol (intern ,string ,hashtable)))
118 (or (boundp symbol)
119 (set symbol nil))
120 symbol))
121
eec82323
LMI
122;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
123;; to limit the length of a string. This function is necessary since
124;; `(substr "abc" 0 30)' pukes with "Args out of range".
23f87bed 125;; Fixme: Why not `truncate-string-to-width'?
eec82323
LMI
126(defsubst gnus-limit-string (str width)
127 (if (> (length str) width)
128 (substring str 0 width)
129 str))
130
eec82323
LMI
131(defsubst gnus-goto-char (point)
132 (and point (goto-char point)))
133
134(defmacro gnus-buffer-exists-p (buffer)
135 `(let ((buffer ,buffer))
136 (when buffer
137 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
138 buffer))))
139
16409b0b
GM
140(defalias 'gnus-point-at-bol
141 (if (fboundp 'point-at-bol)
142 'point-at-bol
143 'line-beginning-position))
144
145(defalias 'gnus-point-at-eol
146 (if (fboundp 'point-at-eol)
147 'point-at-eol
148 'line-end-position))
eec82323 149
23f87bed
MB
150;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
151;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
152;; It's harmless, though, so the main purpose of this alias is to shut
153;; up the byte compiler.
154(defalias 'gnus-make-local-hook
155 (if (eq (get 'make-local-hook 'byte-compile)
156 'byte-compile-obsolete)
157 'ignore ; Emacs
158 'make-local-hook)) ; XEmacs
159
eec82323
LMI
160(defun gnus-delete-first (elt list)
161 "Delete by side effect the first occurrence of ELT as a member of LIST."
162 (if (equal (car list) elt)
163 (cdr list)
164 (let ((total list))
165 (while (and (cdr list)
166 (not (equal (cadr list) elt)))
167 (setq list (cdr list)))
168 (when (cdr list)
169 (setcdr list (cddr list)))
170 total)))
171
172;; Delete the current line (and the next N lines).
173(defmacro gnus-delete-line (&optional n)
23f87bed 174 `(delete-region (gnus-point-at-bol)
eec82323
LMI
175 (progn (forward-line ,(or n 1)) (point))))
176
177(defun gnus-byte-code (func)
178 "Return a form that can be `eval'ed based on FUNC."
6748645f
LMI
179 (let ((fval (indirect-function func)))
180 (if (byte-code-function-p fval)
eec82323
LMI
181 (let ((flist (append fval nil)))
182 (setcar flist 'byte-code)
183 flist)
184 (cons 'progn (cddr fval)))))
185
186(defun gnus-extract-address-components (from)
23f87bed
MB
187 "Extract address components from a From header.
188Given an RFC-822 address FROM, extract full name and canonical address.
189Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
190solution than `mail-extract-address-components', which works much better, but
191is slower."
eec82323
LMI
192 (let (name address)
193 ;; First find the address - the thing with the @ in it. This may
194 ;; not be accurate in mail addresses, but does the trick most of
195 ;; the time in news messages.
196 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
197 (setq address (substring from (match-beginning 0) (match-end 0))))
198 ;; Then we check whether the "name <address>" format is used.
199 (and address
eec82323
LMI
200 ;; Linear white space is not required.
201 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
202 (and (setq name (substring from 0 (match-beginning 0)))
203 ;; Strip any quotes from the name.
23f87bed 204 (string-match "^\".*\"$" name)
eec82323
LMI
205 (setq name (substring name 1 (1- (match-end 0))))))
206 ;; If not, then "address (name)" is used.
207 (or name
208 (and (string-match "(.+)" from)
209 (setq name (substring from (1+ (match-beginning 0))
210 (1- (match-end 0)))))
211 (and (string-match "()" from)
212 (setq name address))
eec82323
LMI
213 ;; XOVER might not support folded From headers.
214 (and (string-match "(.*" from)
215 (setq name (substring from (1+ (match-beginning 0))
216 (match-end 0)))))
16409b0b
GM
217 (list (if (string= name "") nil name) (or address from))))
218
eec82323
LMI
219
220(defun gnus-fetch-field (field)
221 "Return the value of the header FIELD of current article."
222 (save-excursion
223 (save-restriction
224 (let ((case-fold-search t)
225 (inhibit-point-motion-hooks t))
226 (nnheader-narrow-to-headers)
227 (message-fetch-field field)))))
228
23f87bed
MB
229(defun gnus-fetch-original-field (field)
230 "Fetch FIELD from the original version of the current article."
231 (with-current-buffer gnus-original-article-buffer
232 (gnus-fetch-field field)))
233
234
eec82323
LMI
235(defun gnus-goto-colon ()
236 (beginning-of-line)
23f87bed
MB
237 (let ((eol (gnus-point-at-eol)))
238 (goto-char (or (text-property-any (point) eol 'gnus-position t)
239 (search-forward ":" eol t)
240 (point)))))
241
242(defun gnus-decode-newsgroups (newsgroups group &optional method)
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."
252 (save-excursion
253 (goto-char (point-min))
254 (while (not (eobp))
255 (while (get-text-property (point) prop)
256 (delete-char 1))
257 (goto-char (next-single-property-change (point) prop nil (point-max))))))
258
259(defun gnus-newsgroup-directory-form (newsgroup)
260 "Make hierarchical directory name from NEWSGROUP name."
23f87bed
MB
261 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
262 (idx (string-match ":" newsgroup)))
263 (concat
264 (if idx (substring newsgroup 0 idx))
265 (if idx "/")
266 (nnheader-replace-chars-in-string
267 (if idx (substring newsgroup (1+ idx)) newsgroup)
268 ?. ?/))))
eec82323
LMI
269
270(defun gnus-newsgroup-savable-name (group)
271 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
272 ;; with dots.
273 (nnheader-replace-chars-in-string group ?/ ?.))
274
275(defun gnus-string> (s1 s2)
276 (not (or (string< s1 s2)
277 (string= s1 s2))))
278
279;;; Time functions.
280
eec82323
LMI
281(defun gnus-file-newer-than (file date)
282 (let ((fdate (nth 5 (file-attributes file))))
283 (or (> (car fdate) (car date))
284 (and (= (car fdate) (car date))
285 (> (nth 1 fdate) (nth 1 date))))))
286
287;;; Keymap macros.
288
289(defmacro gnus-local-set-keys (&rest plist)
290 "Set the keys in PLIST in the current keymap."
291 `(gnus-define-keys-1 (current-local-map) ',plist))
292
293(defmacro gnus-define-keys (keymap &rest plist)
294 "Define all keys in PLIST in KEYMAP."
295 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
296
297(defmacro gnus-define-keys-safe (keymap &rest plist)
298 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
299 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
300
301(put 'gnus-define-keys 'lisp-indent-function 1)
302(put 'gnus-define-keys-safe 'lisp-indent-function 1)
303(put 'gnus-local-set-keys 'lisp-indent-function 1)
304
305(defmacro gnus-define-keymap (keymap &rest plist)
306 "Define all keys in PLIST in KEYMAP."
307 `(gnus-define-keys-1 ,keymap (quote ,plist)))
308
309(put 'gnus-define-keymap 'lisp-indent-function 1)
310
311(defun gnus-define-keys-1 (keymap plist &optional safe)
312 (when (null keymap)
313 (error "Can't set keys in a null keymap"))
314 (cond ((symbolp keymap)
315 (setq keymap (symbol-value keymap)))
316 ((keymapp keymap))
317 ((listp keymap)
318 (set (car keymap) nil)
319 (define-prefix-command (car keymap))
320 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
321 (setq keymap (symbol-value (car keymap)))))
322 (let (key)
323 (while plist
324 (when (symbolp (setq key (pop plist)))
325 (setq key (symbol-value key)))
326 (if (or (not safe)
327 (eq (lookup-key keymap key) 'undefined))
328 (define-key keymap key (pop plist))
329 (pop plist)))))
330
23f87bed 331(defun gnus-completing-read-with-default (default prompt &rest args)
eec82323
LMI
332 ;; Like `completing-read', except that DEFAULT is the default argument.
333 (let* ((prompt (if default
334 (concat prompt " (default " default ") ")
335 (concat prompt " ")))
336 (answer (apply 'completing-read prompt args)))
337 (if (or (null answer) (zerop (length answer)))
338 default
339 answer)))
340
341;; Two silly functions to ensure that all `y-or-n-p' questions clear
342;; the echo area.
343(defun gnus-y-or-n-p (prompt)
344 (prog1
345 (y-or-n-p prompt)
346 (message "")))
347
348(defun gnus-yes-or-no-p (prompt)
349 (prog1
350 (yes-or-no-p prompt)
351 (message "")))
352
23f87bed
MB
353;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
354;; age-depending date representations. (e.g. just the time if it's
355;; from today, the day of the week if it's within the last 7 days and
356;; the full date if it's older)
357
358(defun gnus-seconds-today ()
359 "Return the number of seconds passed today."
360 (let ((now (decode-time (current-time))))
361 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
362
363(defun gnus-seconds-month ()
364 "Return the number of seconds passed this month."
365 (let ((now (decode-time (current-time))))
366 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
367 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
368
369(defun gnus-seconds-year ()
370 "Return the number of seconds passed this year."
371 (let ((now (decode-time (current-time)))
372 (days (format-time-string "%j" (current-time))))
373 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
374 (* (- (string-to-number days) 1) 3600 24))))
375
376(defvar gnus-user-date-format-alist
377 '(((gnus-seconds-today) . "%k:%M")
378 (604800 . "%a %k:%M") ;;that's one week
379 ((gnus-seconds-month) . "%a %d")
380 ((gnus-seconds-year) . "%b %d")
381 (t . "%b %d '%y")) ;;this one is used when no
382 ;;other does match
383 "Specifies date format depending on age of article.
384This is an alist of items (AGE . FORMAT). AGE can be a number (of
385seconds) or a Lisp expression evaluating to a number. When the age of
386the article is less than this number, then use `format-time-string'
387with the corresponding FORMAT for displaying the date of the article.
388If AGE is not a number or a Lisp expression evaluating to a
389non-number, then the corresponding FORMAT is used as a default value.
390
391Note that the list is processed from the beginning, so it should be
392sorted by ascending AGE. Also note that items following the first
393non-number AGE will be ignored.
394
395You can use the functions `gnus-seconds-today', `gnus-seconds-month'
396and `gnus-seconds-year' in the AGE spec. They return the number of
397seconds passed since the start of today, of this month, of this year,
398respectively.")
399
400(defun gnus-user-date (messy-date)
401 "Format the messy-date according to gnus-user-date-format-alist.
402Returns \" ? \" if there's bad input or if an other error occurs.
403Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
404 (condition-case ()
405 (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
406 (now (time-to-seconds (current-time)))
407 ;;If we don't find something suitable we'll use this one
408 (my-format "%b %d '%y"))
409 (let* ((difference (- now messy-date))
410 (templist gnus-user-date-format-alist)
411 (top (eval (caar templist))))
412 (while (if (numberp top) (< top difference) (not top))
413 (progn
414 (setq templist (cdr templist))
415 (setq top (eval (caar templist)))))
416 (if (stringp (cdr (car templist)))
417 (setq my-format (cdr (car templist)))))
418 (format-time-string (eval my-format) (seconds-to-time messy-date)))
419 (error " ? ")))
420
eec82323 421(defun gnus-dd-mmm (messy-date)
6748645f 422 "Return a string like DD-MMM from a big messy string."
16409b0b
GM
423 (condition-case ()
424 (format-time-string "%d-%b" (safe-date-to-time messy-date))
425 (error " - ")))
eec82323
LMI
426
427(defmacro gnus-date-get-time (date)
428 "Convert DATE string to Emacs time.
429Cache the result as a text property stored in DATE."
430 ;; Either return the cached value...
431 `(let ((d ,date))
432 (if (equal "" d)
433 '(0 0)
434 (or (get-text-property 0 'gnus-time d)
435 ;; or compute the value...
16409b0b 436 (let ((time (safe-date-to-time d)))
eec82323
LMI
437 ;; and store it back in the string.
438 (put-text-property 0 1 'gnus-time time d)
439 time)))))
440
441(defsubst gnus-time-iso8601 (time)
8b93df01 442 "Return a string of TIME in YYYYMMDDTHHMMSS format."
eec82323
LMI
443 (format-time-string "%Y%m%dT%H%M%S" time))
444
6748645f 445(defun gnus-date-iso8601 (date)
8b93df01 446 "Convert the DATE to YYYYMMDDTHHMMSS."
eec82323 447 (condition-case ()
6748645f 448 (gnus-time-iso8601 (gnus-date-get-time date))
eec82323
LMI
449 (error "")))
450
451(defun gnus-mode-string-quote (string)
452 "Quote all \"%\"'s in STRING."
23f87bed 453 (gnus-replace-in-string string "%" "%%"))
eec82323
LMI
454
455;; Make a hash table (default and minimum size is 256).
456;; Optional argument HASHSIZE specifies the table size.
457(defun gnus-make-hashtable (&optional hashsize)
458 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
459
460;; Make a number that is suitable for hashing; bigger than MIN and
461;; equal to some 2^x. Many machines (such as sparcs) do not have a
462;; hardware modulo operation, so they implement it in software. On
463;; many sparcs over 50% of the time to intern is spent in the modulo.
464;; Yes, it's slower than actually computing the hash from the string!
465;; So we use powers of 2 so people can optimize the modulo to a mask.
466(defun gnus-create-hash-size (min)
467 (let ((i 1))
468 (while (< i min)
469 (setq i (* 2 i)))
470 i))
471
472(defcustom gnus-verbose 7
473 "*Integer that says how verbose Gnus should be.
474The higher the number, the more messages Gnus will flash to say what
475it's doing. At zero, Gnus will be totally mute; at five, Gnus will
476display most important messages; and at ten, Gnus will keep on
477jabbering all the time."
478 :group 'gnus-start
479 :type 'integer)
480
eec82323 481(defun gnus-message (level &rest args)
23f87bed
MB
482 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
483
484Guideline for numbers:
4851 - error messages, 3 - non-serious error messages, 5 - messages for things
486that take a long time, 7 - not very important messages on stuff, 9 - messages
487inside loops."
eec82323
LMI
488 (if (<= level gnus-verbose)
489 (apply 'message args)
490 ;; We have to do this format thingy here even if the result isn't
491 ;; shown - the return value has to be the same as the return value
492 ;; from `message'.
493 (apply 'format args)))
494
495(defun gnus-error (level &rest args)
496 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
497 (when (<= (floor level) gnus-verbose)
498 (apply 'message args)
499 (ding)
500 (let (duration)
501 (when (and (floatp level)
502 (not (zerop (setq duration (* 10 (- level (floor level)))))))
503 (sit-for duration))))
504 nil)
505
506(defun gnus-split-references (references)
507 "Return a list of Message-IDs in REFERENCES."
508 (let ((beg 0)
509 ids)
23f87bed 510 (while (string-match "<[^<]+[^< \t]" references beg)
eec82323
LMI
511 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
512 ids))
513 (nreverse ids)))
514
16409b0b 515(defsubst gnus-parent-id (references &optional n)
eec82323
LMI
516 "Return the last Message-ID in REFERENCES.
517If N, return the Nth ancestor instead."
23f87bed
MB
518 (when (and references
519 (not (zerop (length references))))
520 (if n
521 (let ((ids (inline (gnus-split-references references))))
522 (while (nthcdr n ids)
523 (setq ids (cdr ids)))
524 (car ids))
525 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
526 (match-string 1 references)))))
527
528(defun gnus-buffer-live-p (buffer)
eec82323
LMI
529 "Say whether BUFFER is alive or not."
530 (and buffer
531 (get-buffer buffer)
532 (buffer-name (get-buffer buffer))))
533
534(defun gnus-horizontal-recenter ()
535 "Recenter the current buffer horizontally."
536 (if (< (current-column) (/ (window-width) 2))
23f87bed 537 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
eec82323 538 (let* ((orig (point))
23f87bed 539 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
eec82323 540 (max 0))
6748645f
LMI
541 (when end
542 ;; Find the longest line currently displayed in the window.
543 (goto-char (window-start))
544 (while (and (not (eobp))
545 (< (point) end))
546 (end-of-line)
547 (setq max (max max (current-column)))
548 (forward-line 1))
549 (goto-char orig)
550 ;; Scroll horizontally to center (sort of) the point.
551 (if (> max (window-width))
552 (set-window-hscroll
23f87bed 553 (gnus-get-buffer-window (current-buffer) t)
6748645f
LMI
554 (min (- (current-column) (/ (window-width) 3))
555 (+ 2 (- max (window-width)))))
23f87bed 556 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
6748645f 557 max))))
eec82323 558
23f87bed 559(defun gnus-read-event-char (&optional prompt)
eec82323 560 "Get the next event."
23f87bed 561 (let ((event (read-event prompt)))
eec82323
LMI
562 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
563 (cons (and (numberp event) event) event)))
564
565(defun gnus-sortable-date (date)
16409b0b
GM
566 "Make string suitable for sorting from DATE."
567 (gnus-time-iso8601 (date-to-time date)))
eec82323
LMI
568
569(defun gnus-copy-file (file &optional to)
570 "Copy FILE to TO."
571 (interactive
572 (list (read-file-name "Copy file: " default-directory)
573 (read-file-name "Copy file to: " default-directory)))
574 (unless to
575 (setq to (read-file-name "Copy file to: " default-directory)))
576 (when (file-directory-p to)
577 (setq to (concat (file-name-as-directory to)
578 (file-name-nondirectory file))))
579 (copy-file file to))
580
eec82323
LMI
581(defvar gnus-work-buffer " *gnus work*")
582
583(defun gnus-set-work-buffer ()
584 "Put point in the empty Gnus work buffer."
585 (if (get-buffer gnus-work-buffer)
586 (progn
587 (set-buffer gnus-work-buffer)
588 (erase-buffer))
6748645f 589 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
eec82323 590 (kill-all-local-variables)
16409b0b 591 (mm-enable-multibyte)))
eec82323
LMI
592
593(defmacro gnus-group-real-name (group)
594 "Find the real name of a foreign newsgroup."
595 `(let ((gname ,group))
596 (if (string-match "^[^:]+:" gname)
597 (substring gname (match-end 0))
598 gname)))
599
600(defun gnus-make-sort-function (funs)
23f87bed 601 "Return a composite sort condition based on the functions in FUNS."
eec82323 602 (cond
16409b0b 603 ;; Just a simple function.
23f87bed 604 ((functionp funs) funs)
16409b0b 605 ;; No functions at all.
eec82323 606 ((null funs) funs)
16409b0b
GM
607 ;; A list of functions.
608 ((or (cdr funs)
609 (listp (car funs)))
23f87bed
MB
610 (gnus-byte-compile
611 `(lambda (t1 t2)
612 ,(gnus-make-sort-function-1 (reverse funs)))))
16409b0b 613 ;; A list containing just one function.
eec82323
LMI
614 (t
615 (car funs))))
616
617(defun gnus-make-sort-function-1 (funs)
23f87bed 618 "Return a composite sort condition based on the functions in FUNS."
16409b0b
GM
619 (let ((function (car funs))
620 (first 't1)
621 (last 't2))
622 (when (consp function)
623 (cond
624 ;; Reversed spec.
625 ((eq (car function) 'not)
626 (setq function (cadr function)
627 first 't2
628 last 't1))
23f87bed 629 ((functionp function)
16409b0b
GM
630 ;; Do nothing.
631 )
632 (t
633 (error "Invalid sort spec: %s" function))))
634 (if (cdr funs)
635 `(or (,function ,first ,last)
636 (and (not (,function ,last ,first))
637 ,(gnus-make-sort-function-1 (cdr funs))))
638 `(,function ,first ,last))))
eec82323
LMI
639
640(defun gnus-turn-off-edit-menu (type)
641 "Turn off edit menu in `gnus-TYPE-mode-map'."
642 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
643 [menu-bar edit] 'undefined))
644
23f87bed
MB
645(defmacro gnus-bind-print-variables (&rest forms)
646 "Bind print-* variables and evaluate FORMS.
647This macro is used with `prin1', `pp', etc. in order to ensure printed
648Lisp objects are loadable. Bind `print-quoted' and `print-readably'
649to t, and `print-escape-multibyte', `print-escape-newlines',
650`print-escape-nonascii', `print-length', `print-level' and
651`print-string-length' to nil."
652 `(let ((print-quoted t)
653 (print-readably t)
654 ;;print-circle
655 ;;print-continuous-numbering
656 print-escape-multibyte
657 print-escape-newlines
658 print-escape-nonascii
659 ;;print-gensym
660 print-length
661 print-level
662 print-string-length)
663 ,@forms))
664
eec82323
LMI
665(defun gnus-prin1 (form)
666 "Use `prin1' on FORM in the current buffer.
23f87bed
MB
667Bind `print-quoted' and `print-readably' to t, and `print-length' and
668`print-level' to nil. See also `gnus-bind-print-variables'."
669 (gnus-bind-print-variables (prin1 form (current-buffer))))
eec82323
LMI
670
671(defun gnus-prin1-to-string (form)
23f87bed
MB
672 "The same as `prin1'.
673Bind `print-quoted' and `print-readably' to t, and `print-length' and
674`print-level' to nil. See also `gnus-bind-print-variables'."
675 (gnus-bind-print-variables (prin1-to-string form)))
676
677(defun gnus-pp (form)
678 "Use `pp' on FORM in the current buffer.
679Bind `print-quoted' and `print-readably' to t, and `print-length' and
680`print-level' to nil. See also `gnus-bind-print-variables'."
681 (gnus-bind-print-variables (pp form (current-buffer))))
682
683(defun gnus-pp-to-string (form)
684 "The same as `pp-to-string'.
685Bind `print-quoted' and `print-readably' to t, and `print-length' and
686`print-level' to nil. See also `gnus-bind-print-variables'."
687 (gnus-bind-print-variables (pp-to-string form)))
eec82323
LMI
688
689(defun gnus-make-directory (directory)
690 "Make DIRECTORY (and all its parents) if it doesn't exist."
5eee36fa 691 (require 'nnmail)
16409b0b
GM
692 (let ((file-name-coding-system nnmail-pathname-coding-system))
693 (when (and directory
694 (not (file-exists-p directory)))
695 (make-directory directory t)))
eec82323
LMI
696 t)
697
698(defun gnus-write-buffer (file)
699 "Write the current buffer's contents to FILE."
700 ;; Make sure the directory exists.
701 (gnus-make-directory (file-name-directory file))
16409b0b
GM
702 (let ((file-name-coding-system nnmail-pathname-coding-system))
703 ;; Write the buffer.
704 (write-region (point-min) (point-max) file nil 'quietly)))
eec82323 705
eec82323
LMI
706(defun gnus-delete-file (file)
707 "Delete FILE if it exists."
708 (when (file-exists-p file)
709 (delete-file file)))
710
aa0a8561
MB
711(defun gnus-delete-directory (directory)
712 "Delete files in DIRECTORY. Subdirectories remain.
713If there's no subdirectory, delete DIRECTORY as well."
714 (when (file-directory-p directory)
715 (let ((files (directory-files
716 directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
717 file dir)
718 (while files
719 (setq file (pop files))
720 (if (eq t (car (file-attributes file)))
721 ;; `file' is a subdirectory.
722 (setq dir t)
723 ;; `file' is a file or a symlink.
724 (delete-file file)))
725 (unless dir
726 (delete-directory directory)))))
727
eec82323
LMI
728(defun gnus-strip-whitespace (string)
729 "Return STRING stripped of all whitespace."
730 (while (string-match "[\r\n\t ]+" string)
731 (setq string (replace-match "" t t string)))
732 string)
733
16409b0b 734(defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
eec82323
LMI
735 "The same as `put-text-property', but don't put this prop on any newlines in the region."
736 (save-match-data
737 (save-excursion
738 (save-restriction
739 (goto-char beg)
16409b0b 740 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
6748645f 741 (gnus-put-text-property beg (match-beginning 0) prop val)
eec82323 742 (setq beg (point)))
6748645f
LMI
743 (gnus-put-text-property beg (point) prop val)))))
744
23f87bed
MB
745(defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
746 "The same as `put-text-property', but don't put this prop on any newlines in the region."
747 (save-match-data
748 (save-excursion
749 (save-restriction
750 (goto-char beg)
751 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
752 (gnus-overlay-put
753 (gnus-make-overlay beg (match-beginning 0))
754 prop val)
755 (setq beg (point)))
756 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
757
6748645f
LMI
758(defun gnus-put-text-property-excluding-characters-with-faces (beg end
759 prop val)
760 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
761 (let ((b beg))
762 (while (/= b end)
763 (when (get-text-property b 'gnus-face)
764 (setq b (next-single-property-change b 'gnus-face nil end)))
765 (when (/= b end)
23f87bed
MB
766 (inline
767 (gnus-put-text-property
768 b (setq b (next-single-property-change b 'gnus-face nil end))
769 prop val))))))
770
771(defmacro gnus-faces-at (position)
772 "Return a list of faces at POSITION."
773 (if (featurep 'xemacs)
774 `(let ((pos ,position))
775 (mapcar-extents 'extent-face
776 nil (current-buffer) pos pos nil 'face))
777 `(let ((pos ,position))
778 (delq nil (cons (get-text-property pos 'face)
779 (mapcar
780 (lambda (overlay)
781 (overlay-get overlay 'face))
782 (overlays-at pos)))))))
eec82323
LMI
783
784;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
785;;; The primary idea here is to try to protect internal datastructures
786;;; from becoming corrupted when the user hits C-g, or if a hook or
787;;; similar blows up. Often in Gnus multiple tables/lists need to be
788;;; updated at the same time, or information can be lost.
789
790(defvar gnus-atomic-be-safe t
791 "If t, certain operations will be protected from interruption by C-g.")
792
793(defmacro gnus-atomic-progn (&rest forms)
794 "Evaluate FORMS atomically, which means to protect the evaluation
795from being interrupted by the user. An error from the forms themselves
796will return without finishing the operation. Since interrupts from
797the user are disabled, it is recommended that only the most minimal
798operations are performed by FORMS. If you wish to assign many
799complicated values atomically, compute the results into temporary
800variables and then do only the assignment atomically."
801 `(let ((inhibit-quit gnus-atomic-be-safe))
802 ,@forms))
803
804(put 'gnus-atomic-progn 'lisp-indent-function 0)
805
806(defmacro gnus-atomic-progn-assign (protect &rest forms)
807 "Evaluate FORMS, but insure that the variables listed in PROTECT
808are not changed if anything in FORMS signals an error or otherwise
809non-locally exits. The variables listed in PROTECT are updated atomically.
810It is safe to use gnus-atomic-progn-assign with long computations.
811
812Note that if any of the symbols in PROTECT were unbound, they will be
8f688cb0 813set to nil on a successful assignment. In case of an error or other
eec82323
LMI
814non-local exit, it will still be unbound."
815 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
816 (concat (symbol-name x)
817 "-tmp"))
818 x))
819 protect))
820 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
821 temp-sym-map))
822 (temp-sym-let (mapcar (lambda (x) (list (car x)
823 `(and (boundp ',(cadr x))
824 ,(cadr x))))
825 temp-sym-map))
826 (sym-temp-let sym-temp-map)
827 (temp-sym-assign (apply 'append temp-sym-map))
828 (sym-temp-assign (apply 'append sym-temp-map))
829 (result (make-symbol "result-tmp")))
830 `(let (,@temp-sym-let
831 ,result)
832 (let ,sym-temp-let
833 (setq ,result (progn ,@forms))
834 (setq ,@temp-sym-assign))
835 (let ((inhibit-quit gnus-atomic-be-safe))
836 (setq ,@sym-temp-assign))
837 ,result)))
838
839(put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
840;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
841
842(defmacro gnus-atomic-setq (&rest pairs)
843 "Similar to setq, except that the real symbols are only assigned when
844there are no errors. And when the real symbols are assigned, they are
845done so atomically. If other variables might be changed via side-effect,
846see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
847with potentially long computations."
848 (let ((tpairs pairs)
849 syms)
850 (while tpairs
851 (push (car tpairs) syms)
852 (setq tpairs (cddr tpairs)))
853 `(gnus-atomic-progn-assign ,syms
854 (setq ,@pairs))))
855
856;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
857
858
859;;; Functions for saving to babyl/mail files.
860
23f87bed
MB
861(eval-when-compile
862 (condition-case nil
863 (progn
864 (require 'rmail)
865 (autoload 'rmail-update-summary "rmailsum"))
866 (error
867 (define-compiler-macro rmail-select-summary (&rest body)
868 ;; Rmail of the XEmacs version is supplied by the package, and
869 ;; requires tm and apel packages. However, there may be those
870 ;; who haven't installed those packages. This macro helps such
871 ;; people even if they install those packages later.
872 `(eval '(rmail-select-summary ,@body)))
873 ;; If there's rmail but there's no tm (or there's apel of the
874 ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
875 ;; version fails halfway, however it provides the rmail-select-summary
876 ;; macro which uses the following functions:
877 (autoload 'rmail-summary-displayed "rmail")
878 (autoload 'rmail-maybe-display-summary "rmail")))
879 (defvar rmail-default-rmail-file)
880 (defvar mm-text-coding-system))
881
eec82323
LMI
882(defun gnus-output-to-rmail (filename &optional ask)
883 "Append the current article to an Rmail file named FILENAME."
884 (require 'rmail)
23f87bed 885 (require 'mm-util)
eec82323
LMI
886 ;; Most of these codes are borrowed from rmailout.el.
887 (setq filename (expand-file-name filename))
888 (setq rmail-default-rmail-file filename)
889 (let ((artbuf (current-buffer))
890 (tmpbuf (get-buffer-create " *Gnus-output*")))
891 (save-excursion
892 (or (get-file-buffer filename)
893 (file-exists-p filename)
894 (if (or (not ask)
895 (gnus-yes-or-no-p
896 (concat "\"" filename "\" does not exist, create it? ")))
897 (let ((file-buffer (create-file-buffer filename)))
898 (save-excursion
899 (set-buffer file-buffer)
900 (rmail-insert-rmail-file-header)
16409b0b
GM
901 (let ((require-final-newline nil)
902 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
903 (gnus-write-buffer filename)))
904 (kill-buffer file-buffer))
905 (error "Output file does not exist")))
906 (set-buffer tmpbuf)
907 (erase-buffer)
908 (insert-buffer-substring artbuf)
909 (gnus-convert-article-to-rmail)
910 ;; Decide whether to append to a file or to an Emacs buffer.
911 (let ((outbuf (get-file-buffer filename)))
912 (if (not outbuf)
47e77e9f
SZ
913 (let ((file-name-coding-system nnmail-pathname-coding-system))
914 (mm-append-to-file (point-min) (point-max) filename))
eec82323
LMI
915 ;; File has been visited, in buffer OUTBUF.
916 (set-buffer outbuf)
917 (let ((buffer-read-only nil)
918 (msg (and (boundp 'rmail-current-message)
919 (symbol-value 'rmail-current-message))))
920 ;; If MSG is non-nil, buffer is in RMAIL mode.
921 (when msg
922 (widen)
923 (narrow-to-region (point-max) (point-max)))
924 (insert-buffer-substring tmpbuf)
925 (when msg
926 (goto-char (point-min))
927 (widen)
23f87bed
MB
928 (search-backward "\n\^_")
929 (narrow-to-region (point) (point-max))
930 (rmail-count-new-messages t)
931 (when (rmail-summary-exists)
6748645f
LMI
932 (rmail-select-summary
933 (rmail-update-summary)))
eec82323 934 (rmail-count-new-messages t)
6748645f
LMI
935 (rmail-show-message msg))
936 (save-buffer)))))
eec82323
LMI
937 (kill-buffer tmpbuf)))
938
939(defun gnus-output-to-mail (filename &optional ask)
940 "Append the current article to a mail file named FILENAME."
941 (setq filename (expand-file-name filename))
942 (let ((artbuf (current-buffer))
943 (tmpbuf (get-buffer-create " *Gnus-output*")))
944 (save-excursion
945 ;; Create the file, if it doesn't exist.
946 (when (and (not (get-file-buffer filename))
947 (not (file-exists-p filename)))
948 (if (or (not ask)
949 (gnus-y-or-n-p
950 (concat "\"" filename "\" does not exist, create it? ")))
951 (let ((file-buffer (create-file-buffer filename)))
952 (save-excursion
953 (set-buffer file-buffer)
16409b0b
GM
954 (let ((require-final-newline nil)
955 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
956 (gnus-write-buffer filename)))
957 (kill-buffer file-buffer))
958 (error "Output file does not exist")))
959 (set-buffer tmpbuf)
960 (erase-buffer)
961 (insert-buffer-substring artbuf)
962 (goto-char (point-min))
963 (if (looking-at "From ")
964 (forward-line 1)
965 (insert "From nobody " (current-time-string) "\n"))
966 (let (case-fold-search)
967 (while (re-search-forward "^From " nil t)
968 (beginning-of-line)
969 (insert ">")))
970 ;; Decide whether to append to a file or to an Emacs buffer.
971 (let ((outbuf (get-file-buffer filename)))
972 (if (not outbuf)
973 (let ((buffer-read-only nil))
974 (save-excursion
975 (goto-char (point-max))
976 (forward-char -2)
977 (unless (looking-at "\n\n")
978 (goto-char (point-max))
979 (unless (bolp)
980 (insert "\n"))
981 (insert "\n"))
982 (goto-char (point-max))
47e77e9f
SZ
983 (let ((file-name-coding-system nnmail-pathname-coding-system))
984 (mm-append-to-file (point-min) (point-max) filename))))
eec82323
LMI
985 ;; File has been visited, in buffer OUTBUF.
986 (set-buffer outbuf)
987 (let ((buffer-read-only nil))
988 (goto-char (point-max))
989 (unless (eobp)
990 (insert "\n"))
991 (insert "\n")
992 (insert-buffer-substring tmpbuf)))))
993 (kill-buffer tmpbuf)))
994
995(defun gnus-convert-article-to-rmail ()
996 "Convert article in current buffer to Rmail message format."
997 (let ((buffer-read-only nil))
998 ;; Convert article directly into Babyl format.
999 (goto-char (point-min))
1000 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1001 (while (search-forward "\n\^_" nil t) ;single char
1002 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
1003 (goto-char (point-max))
1004 (insert "\^_")))
1005
6748645f 1006(defun gnus-map-function (funs arg)
23f87bed 1007 "Apply the result of the first function in FUNS to the second, and so on.
6748645f 1008ARG is passed to the first function."
23f87bed
MB
1009 (while funs
1010 (setq arg (funcall (pop funs) arg)))
1011 arg)
6748645f
LMI
1012
1013(defun gnus-run-hooks (&rest funcs)
23f87bed
MB
1014 "Does the same as `run-hooks', but saves the current buffer."
1015 (save-current-buffer
1016 (apply 'run-hooks funcs)))
6748645f 1017
b4e8a25b 1018(defun gnus-run-mode-hooks (&rest funcs)
cfcd5c91
MB
1019 "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1020This function saves the current buffer."
b4e8a25b 1021 (if (fboundp 'run-mode-hooks)
cfcd5c91
MB
1022 (save-current-buffer (apply 'run-mode-hooks funcs))
1023 (save-current-buffer (apply 'run-hooks funcs))))
b4e8a25b 1024
6748645f
LMI
1025;;; Various
1026
16409b0b 1027(defvar gnus-group-buffer) ; Compiler directive
6748645f
LMI
1028(defun gnus-alive-p ()
1029 "Say whether Gnus is running or not."
1030 (and (boundp 'gnus-group-buffer)
1031 (get-buffer gnus-group-buffer)
1032 (save-excursion
1033 (set-buffer gnus-group-buffer)
1034 (eq major-mode 'gnus-group-mode))))
1035
1036(defun gnus-remove-duplicates (list)
23f87bed
MB
1037 (let (new)
1038 (while list
1039 (or (member (car list) new)
1040 (setq new (cons (car list) new)))
1041 (setq list (cdr list)))
6748645f
LMI
1042 (nreverse new)))
1043
23f87bed
MB
1044(defun gnus-remove-if (predicate list)
1045 "Return a copy of LIST with all items satisfying PREDICATE removed."
6748645f
LMI
1046 (let (out)
1047 (while list
1048 (unless (funcall predicate (car list))
1049 (push (car list) out))
23f87bed 1050 (setq list (cdr list)))
6748645f
LMI
1051 (nreverse out)))
1052
23f87bed
MB
1053(if (fboundp 'assq-delete-all)
1054 (defalias 'gnus-delete-alist 'assq-delete-all)
1055 (defun gnus-delete-alist (key alist)
1056 "Delete from ALIST all elements whose car is KEY.
1057Return the modified alist."
1058 (let (entry)
1059 (while (setq entry (assq key alist))
1060 (setq alist (delq entry alist)))
1061 alist)))
6748645f 1062
16409b0b 1063(defmacro gnus-pull (key alist &optional assoc-p)
6748645f
LMI
1064 "Modify ALIST to be without KEY."
1065 (unless (symbolp alist)
1066 (error "Not a symbol: %s" alist))
16409b0b
GM
1067 (let ((fun (if assoc-p 'assoc 'assq)))
1068 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
6748645f
LMI
1069
1070(defun gnus-globalify-regexp (re)
23f87bed 1071 "Return a regexp that matches a whole line, iff RE matches a part of it."
6748645f
LMI
1072 (concat (unless (string-match "^\\^" re) "^.*")
1073 re
1074 (unless (string-match "\\$$" re) ".*$")))
1075
16409b0b
GM
1076(defun gnus-set-window-start (&optional point)
1077 "Set the window start to POINT, or (point) if nil."
23f87bed 1078 (let ((win (gnus-get-buffer-window (current-buffer) t)))
16409b0b
GM
1079 (when win
1080 (set-window-start win (or point (point))))))
1081
1082(defun gnus-annotation-in-region-p (b e)
1083 (if (= b e)
1084 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1085 (text-property-any b e 'gnus-undeletable t)))
1086
1087(defun gnus-or (&rest elems)
1088 "Return non-nil if any of the elements are non-nil."
1089 (catch 'found
1090 (while elems
1091 (when (pop elems)
1092 (throw 'found t)))))
1093
1094(defun gnus-and (&rest elems)
1095 "Return non-nil if all of the elements are non-nil."
1096 (catch 'found
1097 (while elems
1098 (unless (pop elems)
1099 (throw 'found nil)))
1100 t))
1101
1102(defun gnus-write-active-file (file hashtb &optional full-names)
1103 (let ((coding-system-for-write nnmail-active-file-coding-system))
1104 (with-temp-file file
1105 (mapatoms
1106 (lambda (sym)
1107 (when (and sym
1108 (boundp sym)
1109 (symbol-value sym))
1110 (insert (format "%S %d %d y\n"
1111 (if full-names
1112 sym
1113 (intern (gnus-group-real-name (symbol-name sym))))
1114 (or (cdr (symbol-value sym))
1115 (car (symbol-value sym)))
1116 (car (symbol-value sym))))))
1117 hashtb)
1118 (goto-char (point-max))
1119 (while (search-backward "\\." nil t)
1120 (delete-char 1)))))
1121
23f87bed
MB
1122;; Fixme: Why not use `with-output-to-temp-buffer'?
1123(defmacro gnus-with-output-to-file (file &rest body)
1124 (let ((buffer (make-symbol "output-buffer"))
1125 (size (make-symbol "output-buffer-size"))
1126 (leng (make-symbol "output-buffer-length"))
1127 (append (make-symbol "output-buffer-append")))
1128 `(let* ((,size 131072)
1129 (,buffer (make-string ,size 0))
1130 (,leng 0)
1131 (,append nil)
1132 (standard-output
1133 (lambda (c)
1134 (aset ,buffer ,leng c)
bf247b6e 1135
23f87bed
MB
1136 (if (= ,size (setq ,leng (1+ ,leng)))
1137 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1138 (setq ,leng 0
1139 ,append t))))))
1140 ,@body
1141 (when (> ,leng 0)
1142 (let ((coding-system-for-write 'no-conversion))
1143 (write-region (substring ,buffer 0 ,leng) nil ,file
1144 ,append 'no-msg))))))
1145
1146(put 'gnus-with-output-to-file 'lisp-indent-function 1)
1147(put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1148
1149(if (fboundp 'union)
1150 (defalias 'gnus-union 'union)
1151 (defun gnus-union (l1 l2)
1152 "Set union of lists L1 and L2."
1153 (cond ((null l1) l2)
1154 ((null l2) l1)
1155 ((equal l1 l2) l1)
1156 (t
1157 (or (>= (length l1) (length l2))
1158 (setq l1 (prog1 l2 (setq l2 l1))))
1159 (while l2
1160 (or (member (car l2) l1)
1161 (push (car l2) l1))
1162 (pop l2))
1163 l1))))
1164
520aa572
SZ
1165(defun gnus-add-text-properties-when
1166 (property value start end properties &optional object)
1167 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1168 (let (point)
3d8c35d3 1169 (while (and start
23f87bed 1170 (< start end) ;; XEmacs will loop for every when start=end.
520aa572
SZ
1171 (setq point (text-property-not-all start end property value)))
1172 (gnus-add-text-properties start point properties object)
1173 (setq start (text-property-any point end property value)))
1174 (if start
1175 (gnus-add-text-properties start end properties object))))
1176
1177(defun gnus-remove-text-properties-when
1178 (property value start end properties &optional object)
1179 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1180 (let (point)
3d8c35d3 1181 (while (and start
23f87bed 1182 (< start end)
520aa572
SZ
1183 (setq point (text-property-not-all start end property value)))
1184 (remove-text-properties start point properties object)
1185 (setq start (text-property-any point end property value)))
1186 (if start
4481aa98
SZ
1187 (remove-text-properties start end properties object))
1188 t))
520aa572 1189
23f87bed
MB
1190;; This might use `compare-strings' to reduce consing in the
1191;; case-insensitive case, but it has to cope with null args.
1192;; (`string-equal' uses symbol print names.)
1193(defun gnus-string-equal (x y)
1194 "Like `string-equal', except it compares case-insensitively."
1195 (and (= (length x) (length y))
1196 (or (string-equal x y)
1197 (string-equal (downcase x) (downcase y)))))
1198
1199(defcustom gnus-use-byte-compile t
1200 "If non-nil, byte-compile crucial run-time code.
1201Setting it to nil has no effect after the first time `gnus-byte-compile'
1202is run."
1203 :type 'boolean
bf247b6e 1204 :version "22.1"
23f87bed
MB
1205 :group 'gnus-various)
1206
1207(defun gnus-byte-compile (form)
1208 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1209 (if gnus-use-byte-compile
1210 (progn
1211 (condition-case nil
1212 ;; Work around a bug in XEmacs 21.4
1213 (require 'byte-optimize)
1214 (error))
1215 (require 'bytecomp)
1216 (defalias 'gnus-byte-compile
1217 (lambda (form)
1218 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1219 (byte-compile form))))
1220 (gnus-byte-compile form))
1221 form))
1222
1223(defun gnus-remassoc (key alist)
1224 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1225The modified LIST is returned. If the first member
1226of LIST has a car that is `equal' to KEY, there is no way to remove it
54506618 1227by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
23f87bed
MB
1228sure of changing the value of `foo'."
1229 (when alist
1230 (if (equal key (caar alist))
1231 (cdr alist)
1232 (setcdr alist (gnus-remassoc key (cdr alist)))
1233 alist)))
1234
1235(defun gnus-update-alist-soft (key value alist)
1236 (if value
1237 (cons (cons key value) (gnus-remassoc key alist))
1238 (gnus-remassoc key alist)))
1239
1240(defun gnus-create-info-command (node)
1241 "Create a command that will go to info NODE."
1242 `(lambda ()
1243 (interactive)
1244 ,(concat "Enter the info system at node " node)
1245 (Info-goto-node ,node)
1246 (setq gnus-info-buffer (current-buffer))
1247 (gnus-configure-windows 'info)))
1248
1249(defun gnus-not-ignore (&rest args)
1250 t)
1251
47b63dfa
SZ
1252(defvar gnus-directory-sep-char-regexp "/"
1253 "The regexp of directory separator character.
1254If you find some problem with the directory separator character, try
1255\"[/\\\\\]\" for some systems.")
1256
23f87bed
MB
1257(defun gnus-url-unhex (x)
1258 (if (> x ?9)
1259 (if (>= x ?a)
1260 (+ 10 (- x ?a))
1261 (+ 10 (- x ?A)))
1262 (- x ?0)))
1263
1264;; Fixme: Do it like QP.
1265(defun gnus-url-unhex-string (str &optional allow-newlines)
1266 "Remove %XX, embedded spaces, etc in a url.
1267If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1268decoding of carriage returns and line feeds in the string, which is normally
1269forbidden in URL encoding."
1270 (let ((tmp "")
1271 (case-fold-search t))
1272 (while (string-match "%[0-9a-f][0-9a-f]" str)
1273 (let* ((start (match-beginning 0))
1274 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1275 (code (+ (* 16 ch1)
1276 (gnus-url-unhex (elt str (+ start 2))))))
1277 (setq tmp (concat
1278 tmp (substring str 0 start)
1279 (cond
1280 (allow-newlines
1281 (char-to-string code))
1282 ((or (= code ?\n) (= code ?\r))
1283 " ")
1284 (t (char-to-string code))))
1285 str (substring str (match-end 0)))))
1286 (setq tmp (concat tmp str))
1287 tmp))
1288
1289(defun gnus-make-predicate (spec)
1290 "Transform SPEC into a function that can be called.
1291SPEC is a predicate specifier that contains stuff like `or', `and',
1292`not', lists and functions. The functions all take one parameter."
1293 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1294
1295(defun gnus-make-predicate-1 (spec)
1296 (cond
1297 ((symbolp spec)
1298 `(,spec elem))
1299 ((listp spec)
1300 (if (memq (car spec) '(or and not))
1301 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1302 (error "Invalid predicate specifier: %s" spec)))))
1303
1304(defun gnus-local-map-property (map)
1305 "Return a list suitable for a text property list specifying keymap MAP."
1306 (cond
1307 ((featurep 'xemacs)
1308 (list 'keymap map))
1309 ((>= emacs-major-version 21)
1310 (list 'keymap map))
1311 (t
1312 (list 'local-map map))))
1313
1314(defmacro gnus-completing-read-maybe-default (prompt table &optional predicate
1315 require-match initial-contents
1316 history default)
1317 "Like `completing-read', allowing for non-existent 7th arg in older XEmacsen."
1318 `(completing-read ,prompt ,table ,predicate ,require-match
1319 ,initial-contents ,history
1320 ,@(if (and (featurep 'xemacs) (< emacs-minor-version 2))
1321 ()
1322 (list default))))
1323
1324(defun gnus-completing-read (prompt table &optional predicate require-match
1325 history)
1326 (when (and history
1327 (not (boundp history)))
1328 (set history nil))
1329 (gnus-completing-read-maybe-default
1330 (if (symbol-value history)
1331 (concat prompt " (" (car (symbol-value history)) "): ")
1332 (concat prompt ": "))
1333 table
1334 predicate
1335 require-match
1336 nil
1337 history
1338 (car (symbol-value history))))
1339
1340(defun gnus-graphic-display-p ()
1341 (or (and (fboundp 'display-graphic-p)
1342 (display-graphic-p))
1343 ;;;!!!This is bogus. Fixme!
1344 (and (featurep 'xemacs)
1345 t)))
1346
1347(put 'gnus-parse-without-error 'lisp-indent-function 0)
1348(put 'gnus-parse-without-error 'edebug-form-spec '(body))
1349
1350(defmacro gnus-parse-without-error (&rest body)
1351 "Allow continuing onto the next line even if an error occurs."
1352 `(while (not (eobp))
1353 (condition-case ()
1354 (progn
1355 ,@body
1356 (goto-char (point-max)))
1357 (error
1358 (gnus-error 4 "Invalid data on line %d"
1359 (count-lines (point-min) (point)))
1360 (forward-line 1)))))
1361
1362(defun gnus-cache-file-contents (file variable function)
1363 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1364 (let ((time (nth 5 (file-attributes file)))
1365 contents value)
1366 (if (or (null (setq value (symbol-value variable)))
1367 (not (equal (car value) file))
1368 (not (equal (nth 1 value) time)))
1369 (progn
1370 (setq contents (funcall function file))
1371 (set variable (list file time contents))
1372 contents)
1373 (nth 2 value))))
1374
1375(defun gnus-multiple-choice (prompt choice &optional idx)
1376 "Ask user a multiple choice question.
1377CHOICE is a list of the choice char and help message at IDX."
1378 (let (tchar buf)
1379 (save-window-excursion
1380 (save-excursion
1381 (while (not tchar)
1382 (message "%s (%s): "
1383 prompt
1384 (concat
1385 (mapconcat (lambda (s) (char-to-string (car s)))
1386 choice ", ") ", ?"))
1387 (setq tchar (read-char))
1388 (when (not (assq tchar choice))
1389 (setq tchar nil)
1390 (setq buf (get-buffer-create "*Gnus Help*"))
1391 (pop-to-buffer buf)
1392 (fundamental-mode) ; for Emacs 20.4+
1393 (buffer-disable-undo)
1394 (erase-buffer)
1395 (insert prompt ":\n\n")
1396 (let ((max -1)
1397 (list choice)
1398 (alist choice)
1399 (idx (or idx 1))
1400 (i 0)
1401 n width pad format)
1402 ;; find the longest string to display
1403 (while list
1404 (setq n (length (nth idx (car list))))
1405 (unless (> max n)
1406 (setq max n))
1407 (setq list (cdr list)))
1408 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1409 (setq n (/ (1- (window-width)) max)) ; items per line
1410 (setq width (/ (1- (window-width)) n)) ; width of each item
1411 ;; insert `n' items, each in a field of width `width'
1412 (while alist
1413 (if (< i n)
1414 ()
1415 (setq i 0)
1416 (delete-char -1) ; the `\n' takes a char
1417 (insert "\n"))
1418 (setq pad (- width 3))
1419 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1420 (insert (format format (caar alist) (nth idx (car alist))))
1421 (setq alist (cdr alist))
1422 (setq i (1+ i))))))))
1423 (if (buffer-live-p buf)
1424 (kill-buffer buf))
1425 tchar))
1426
1427(defun gnus-select-frame-set-input-focus (frame)
1428 "Select FRAME, raise it, and set input focus, if possible."
1429 (cond ((featurep 'xemacs)
1430 (raise-frame frame)
1431 (select-frame frame)
1432 (focus-frame frame))
1433 ;; The function `select-frame-set-input-focus' won't set
1434 ;; the input focus under Emacs 21.2 and X window system.
1435 ;;((fboundp 'select-frame-set-input-focus)
1436 ;; (defalias 'gnus-select-frame-set-input-focus
1437 ;; 'select-frame-set-input-focus)
1438 ;; (select-frame-set-input-focus frame))
1439 (t
1440 (raise-frame frame)
1441 (select-frame frame)
1442 (cond ((and (eq window-system 'x)
1443 (fboundp 'x-focus-frame))
1444 (x-focus-frame frame))
1445 ((eq window-system 'w32)
1446 (w32-focus-frame frame)))
1447 (when focus-follows-mouse
1448 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1449
1450(defun gnus-frame-or-window-display-name (object)
1451 "Given a frame or window, return the associated display name.
1452Return nil otherwise."
1453 (if (featurep 'xemacs)
1454 (device-connection (dfw-device object))
1455 (if (or (framep object)
1456 (and (windowp object)
1457 (setq object (window-frame object))))
1458 (let ((display (frame-parameter object 'display)))
1459 (if (and (stringp display)
1460 ;; Exclude invalid display names.
1461 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1462 display))
1463 display)))))
1464
1465;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1466(defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1467 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1468If there are several sequences, FUNCTION is called with that many arguments,
1469and mapping stops as soon as the shortest sequence runs out. With just one
1470sequence, this is like `mapcar'. With several, it is like the Common Lisp
1471`mapcar' function extended to arbitrary sequence types."
1472
1473 (if seqs2_n
1474 (let* ((seqs (cons seq1 seqs2_n))
1475 (cnt 0)
1476 (heads (mapcar (lambda (seq)
1477 (make-symbol (concat "head"
1478 (int-to-string
1479 (setq cnt (1+ cnt))))))
1480 seqs))
1481 (result (make-symbol "result"))
1482 (result-tail (make-symbol "result-tail")))
1483 `(let* ,(let* ((bindings (cons nil nil))
1484 (heads heads))
1485 (nconc bindings (list (list result '(cons nil nil))))
1486 (nconc bindings (list (list result-tail result)))
1487 (while heads
1488 (nconc bindings (list (list (pop heads) (pop seqs)))))
1489 (cdr bindings))
1490 (while (and ,@heads)
1491 (setcdr ,result-tail (cons (funcall ,function
1492 ,@(mapcar (lambda (h) (list 'car h))
1493 heads))
1494 nil))
1495 (setq ,result-tail (cdr ,result-tail)
1496 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1497 (cdr ,result)))
1498 `(mapcar ,function ,seq1)))
1499
1500(if (fboundp 'merge)
1501 (defalias 'gnus-merge 'merge)
1502 ;; Adapted from cl-seq.el
1503 (defun gnus-merge (type list1 list2 pred)
1504 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1505Argument TYPE is for compatibility and ignored.
1506Ordering of the elements is preserved according to PRED, a `less-than'
1507predicate on the elements."
1508 (let ((res nil))
1509 (while (and list1 list2)
1510 (if (funcall pred (car list2) (car list1))
1511 (push (pop list2) res)
1512 (push (pop list1) res)))
1513 (nconc (nreverse res) list1 list2))))
1514
1515(eval-when-compile
1516 (defvar xemacs-codename))
1517
1518(defun gnus-emacs-version ()
1519 "Stringified Emacs version."
1520 (let ((system-v
1521 (cond
1522 ((eq gnus-user-agent 'emacs-gnus-config)
1523 system-configuration)
1524 ((eq gnus-user-agent 'emacs-gnus-type)
1525 (symbol-name system-type))
1526 (t nil))))
1527 (cond
1528 ((eq gnus-user-agent 'gnus)
1529 nil)
1530 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1531 (concat "Emacs/" (match-string 1 emacs-version)
1532 (if system-v
1533 (concat " (" system-v ")")
1534 "")))
1535 ((string-match
1536 "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1537 emacs-version)
1538 (concat
1539 (match-string 1 emacs-version)
1540 (format "/%d.%d" emacs-major-version emacs-minor-version)
1541 (if (match-beginning 3)
1542 (match-string 3 emacs-version)
1543 "")
1544 (if (boundp 'xemacs-codename)
1545 (concat
1546 " (" xemacs-codename
1547 (if system-v
1548 (concat ", " system-v ")")
1549 ")"))
1550 "")))
1551 (t emacs-version))))
1552
54506618
MB
1553(defun gnus-rename-file (old-path new-path &optional trim)
1554 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1555empty directories from OLD-PATH."
1556 (when (file-exists-p old-path)
1557 (let* ((old-dir (file-name-directory old-path))
1558 (old-name (file-name-nondirectory old-path))
1559 (new-dir (file-name-directory new-path))
1560 (new-name (file-name-nondirectory new-path))
1561 temp)
1562 (gnus-make-directory new-dir)
1563 (rename-file old-path new-path t)
1564 (when trim
1565 (while (progn (setq temp (directory-files old-dir))
1566 (while (member (car temp) '("." ".."))
1567 (setq temp (cdr temp)))
1568 (= (length temp) 0))
1569 (delete-directory old-dir)
bf247b6e
KS
1570 (setq old-dir (file-name-as-directory
1571 (file-truename
54506618
MB
1572 (concat old-dir "..")))))))))
1573
1574
eec82323
LMI
1575(provide 'gnus-util)
1576
ab5796a9 1577;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
eec82323 1578;;; gnus-util.el ends here