Mention new var `hs-set-up-overlay'.
[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
711(defun gnus-strip-whitespace (string)
712 "Return STRING stripped of all whitespace."
713 (while (string-match "[\r\n\t ]+" string)
714 (setq string (replace-match "" t t string)))
715 string)
716
16409b0b 717(defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
eec82323
LMI
718 "The same as `put-text-property', but don't put this prop on any newlines in the region."
719 (save-match-data
720 (save-excursion
721 (save-restriction
722 (goto-char beg)
16409b0b 723 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
6748645f 724 (gnus-put-text-property beg (match-beginning 0) prop val)
eec82323 725 (setq beg (point)))
6748645f
LMI
726 (gnus-put-text-property beg (point) prop val)))))
727
23f87bed
MB
728(defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
729 "The same as `put-text-property', but don't put this prop on any newlines in the region."
730 (save-match-data
731 (save-excursion
732 (save-restriction
733 (goto-char beg)
734 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
735 (gnus-overlay-put
736 (gnus-make-overlay beg (match-beginning 0))
737 prop val)
738 (setq beg (point)))
739 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
740
6748645f
LMI
741(defun gnus-put-text-property-excluding-characters-with-faces (beg end
742 prop val)
743 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
744 (let ((b beg))
745 (while (/= b end)
746 (when (get-text-property b 'gnus-face)
747 (setq b (next-single-property-change b 'gnus-face nil end)))
748 (when (/= b end)
23f87bed
MB
749 (inline
750 (gnus-put-text-property
751 b (setq b (next-single-property-change b 'gnus-face nil end))
752 prop val))))))
753
754(defmacro gnus-faces-at (position)
755 "Return a list of faces at POSITION."
756 (if (featurep 'xemacs)
757 `(let ((pos ,position))
758 (mapcar-extents 'extent-face
759 nil (current-buffer) pos pos nil 'face))
760 `(let ((pos ,position))
761 (delq nil (cons (get-text-property pos 'face)
762 (mapcar
763 (lambda (overlay)
764 (overlay-get overlay 'face))
765 (overlays-at pos)))))))
eec82323
LMI
766
767;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
768;;; The primary idea here is to try to protect internal datastructures
769;;; from becoming corrupted when the user hits C-g, or if a hook or
770;;; similar blows up. Often in Gnus multiple tables/lists need to be
771;;; updated at the same time, or information can be lost.
772
773(defvar gnus-atomic-be-safe t
774 "If t, certain operations will be protected from interruption by C-g.")
775
776(defmacro gnus-atomic-progn (&rest forms)
777 "Evaluate FORMS atomically, which means to protect the evaluation
778from being interrupted by the user. An error from the forms themselves
779will return without finishing the operation. Since interrupts from
780the user are disabled, it is recommended that only the most minimal
781operations are performed by FORMS. If you wish to assign many
782complicated values atomically, compute the results into temporary
783variables and then do only the assignment atomically."
784 `(let ((inhibit-quit gnus-atomic-be-safe))
785 ,@forms))
786
787(put 'gnus-atomic-progn 'lisp-indent-function 0)
788
789(defmacro gnus-atomic-progn-assign (protect &rest forms)
790 "Evaluate FORMS, but insure that the variables listed in PROTECT
791are not changed if anything in FORMS signals an error or otherwise
792non-locally exits. The variables listed in PROTECT are updated atomically.
793It is safe to use gnus-atomic-progn-assign with long computations.
794
795Note that if any of the symbols in PROTECT were unbound, they will be
8f688cb0 796set to nil on a successful assignment. In case of an error or other
eec82323
LMI
797non-local exit, it will still be unbound."
798 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
799 (concat (symbol-name x)
800 "-tmp"))
801 x))
802 protect))
803 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
804 temp-sym-map))
805 (temp-sym-let (mapcar (lambda (x) (list (car x)
806 `(and (boundp ',(cadr x))
807 ,(cadr x))))
808 temp-sym-map))
809 (sym-temp-let sym-temp-map)
810 (temp-sym-assign (apply 'append temp-sym-map))
811 (sym-temp-assign (apply 'append sym-temp-map))
812 (result (make-symbol "result-tmp")))
813 `(let (,@temp-sym-let
814 ,result)
815 (let ,sym-temp-let
816 (setq ,result (progn ,@forms))
817 (setq ,@temp-sym-assign))
818 (let ((inhibit-quit gnus-atomic-be-safe))
819 (setq ,@sym-temp-assign))
820 ,result)))
821
822(put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
823;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
824
825(defmacro gnus-atomic-setq (&rest pairs)
826 "Similar to setq, except that the real symbols are only assigned when
827there are no errors. And when the real symbols are assigned, they are
828done so atomically. If other variables might be changed via side-effect,
829see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
830with potentially long computations."
831 (let ((tpairs pairs)
832 syms)
833 (while tpairs
834 (push (car tpairs) syms)
835 (setq tpairs (cddr tpairs)))
836 `(gnus-atomic-progn-assign ,syms
837 (setq ,@pairs))))
838
839;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
840
841
842;;; Functions for saving to babyl/mail files.
843
23f87bed
MB
844(eval-when-compile
845 (condition-case nil
846 (progn
847 (require 'rmail)
848 (autoload 'rmail-update-summary "rmailsum"))
849 (error
850 (define-compiler-macro rmail-select-summary (&rest body)
851 ;; Rmail of the XEmacs version is supplied by the package, and
852 ;; requires tm and apel packages. However, there may be those
853 ;; who haven't installed those packages. This macro helps such
854 ;; people even if they install those packages later.
855 `(eval '(rmail-select-summary ,@body)))
856 ;; If there's rmail but there's no tm (or there's apel of the
857 ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
858 ;; version fails halfway, however it provides the rmail-select-summary
859 ;; macro which uses the following functions:
860 (autoload 'rmail-summary-displayed "rmail")
861 (autoload 'rmail-maybe-display-summary "rmail")))
862 (defvar rmail-default-rmail-file)
863 (defvar mm-text-coding-system))
864
eec82323
LMI
865(defun gnus-output-to-rmail (filename &optional ask)
866 "Append the current article to an Rmail file named FILENAME."
867 (require 'rmail)
23f87bed 868 (require 'mm-util)
eec82323
LMI
869 ;; Most of these codes are borrowed from rmailout.el.
870 (setq filename (expand-file-name filename))
871 (setq rmail-default-rmail-file filename)
872 (let ((artbuf (current-buffer))
873 (tmpbuf (get-buffer-create " *Gnus-output*")))
874 (save-excursion
875 (or (get-file-buffer filename)
876 (file-exists-p filename)
877 (if (or (not ask)
878 (gnus-yes-or-no-p
879 (concat "\"" filename "\" does not exist, create it? ")))
880 (let ((file-buffer (create-file-buffer filename)))
881 (save-excursion
882 (set-buffer file-buffer)
883 (rmail-insert-rmail-file-header)
16409b0b
GM
884 (let ((require-final-newline nil)
885 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
886 (gnus-write-buffer filename)))
887 (kill-buffer file-buffer))
888 (error "Output file does not exist")))
889 (set-buffer tmpbuf)
890 (erase-buffer)
891 (insert-buffer-substring artbuf)
892 (gnus-convert-article-to-rmail)
893 ;; Decide whether to append to a file or to an Emacs buffer.
894 (let ((outbuf (get-file-buffer filename)))
895 (if (not outbuf)
47e77e9f
SZ
896 (let ((file-name-coding-system nnmail-pathname-coding-system))
897 (mm-append-to-file (point-min) (point-max) filename))
eec82323
LMI
898 ;; File has been visited, in buffer OUTBUF.
899 (set-buffer outbuf)
900 (let ((buffer-read-only nil)
901 (msg (and (boundp 'rmail-current-message)
902 (symbol-value 'rmail-current-message))))
903 ;; If MSG is non-nil, buffer is in RMAIL mode.
904 (when msg
905 (widen)
906 (narrow-to-region (point-max) (point-max)))
907 (insert-buffer-substring tmpbuf)
908 (when msg
909 (goto-char (point-min))
910 (widen)
23f87bed
MB
911 (search-backward "\n\^_")
912 (narrow-to-region (point) (point-max))
913 (rmail-count-new-messages t)
914 (when (rmail-summary-exists)
6748645f
LMI
915 (rmail-select-summary
916 (rmail-update-summary)))
eec82323 917 (rmail-count-new-messages t)
6748645f
LMI
918 (rmail-show-message msg))
919 (save-buffer)))))
eec82323
LMI
920 (kill-buffer tmpbuf)))
921
922(defun gnus-output-to-mail (filename &optional ask)
923 "Append the current article to a mail file named FILENAME."
924 (setq filename (expand-file-name filename))
925 (let ((artbuf (current-buffer))
926 (tmpbuf (get-buffer-create " *Gnus-output*")))
927 (save-excursion
928 ;; Create the file, if it doesn't exist.
929 (when (and (not (get-file-buffer filename))
930 (not (file-exists-p filename)))
931 (if (or (not ask)
932 (gnus-y-or-n-p
933 (concat "\"" filename "\" does not exist, create it? ")))
934 (let ((file-buffer (create-file-buffer filename)))
935 (save-excursion
936 (set-buffer file-buffer)
16409b0b
GM
937 (let ((require-final-newline nil)
938 (coding-system-for-write mm-text-coding-system))
eec82323
LMI
939 (gnus-write-buffer filename)))
940 (kill-buffer file-buffer))
941 (error "Output file does not exist")))
942 (set-buffer tmpbuf)
943 (erase-buffer)
944 (insert-buffer-substring artbuf)
945 (goto-char (point-min))
946 (if (looking-at "From ")
947 (forward-line 1)
948 (insert "From nobody " (current-time-string) "\n"))
949 (let (case-fold-search)
950 (while (re-search-forward "^From " nil t)
951 (beginning-of-line)
952 (insert ">")))
953 ;; Decide whether to append to a file or to an Emacs buffer.
954 (let ((outbuf (get-file-buffer filename)))
955 (if (not outbuf)
956 (let ((buffer-read-only nil))
957 (save-excursion
958 (goto-char (point-max))
959 (forward-char -2)
960 (unless (looking-at "\n\n")
961 (goto-char (point-max))
962 (unless (bolp)
963 (insert "\n"))
964 (insert "\n"))
965 (goto-char (point-max))
47e77e9f
SZ
966 (let ((file-name-coding-system nnmail-pathname-coding-system))
967 (mm-append-to-file (point-min) (point-max) filename))))
eec82323
LMI
968 ;; File has been visited, in buffer OUTBUF.
969 (set-buffer outbuf)
970 (let ((buffer-read-only nil))
971 (goto-char (point-max))
972 (unless (eobp)
973 (insert "\n"))
974 (insert "\n")
975 (insert-buffer-substring tmpbuf)))))
976 (kill-buffer tmpbuf)))
977
978(defun gnus-convert-article-to-rmail ()
979 "Convert article in current buffer to Rmail message format."
980 (let ((buffer-read-only nil))
981 ;; Convert article directly into Babyl format.
982 (goto-char (point-min))
983 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
984 (while (search-forward "\n\^_" nil t) ;single char
985 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
986 (goto-char (point-max))
987 (insert "\^_")))
988
6748645f 989(defun gnus-map-function (funs arg)
23f87bed 990 "Apply the result of the first function in FUNS to the second, and so on.
6748645f 991ARG is passed to the first function."
23f87bed
MB
992 (while funs
993 (setq arg (funcall (pop funs) arg)))
994 arg)
6748645f
LMI
995
996(defun gnus-run-hooks (&rest funcs)
23f87bed
MB
997 "Does the same as `run-hooks', but saves the current buffer."
998 (save-current-buffer
999 (apply 'run-hooks funcs)))
6748645f
LMI
1000
1001;;; Various
1002
16409b0b 1003(defvar gnus-group-buffer) ; Compiler directive
6748645f
LMI
1004(defun gnus-alive-p ()
1005 "Say whether Gnus is running or not."
1006 (and (boundp 'gnus-group-buffer)
1007 (get-buffer gnus-group-buffer)
1008 (save-excursion
1009 (set-buffer gnus-group-buffer)
1010 (eq major-mode 'gnus-group-mode))))
1011
1012(defun gnus-remove-duplicates (list)
23f87bed
MB
1013 (let (new)
1014 (while list
1015 (or (member (car list) new)
1016 (setq new (cons (car list) new)))
1017 (setq list (cdr list)))
6748645f
LMI
1018 (nreverse new)))
1019
23f87bed
MB
1020(defun gnus-remove-if (predicate list)
1021 "Return a copy of LIST with all items satisfying PREDICATE removed."
6748645f
LMI
1022 (let (out)
1023 (while list
1024 (unless (funcall predicate (car list))
1025 (push (car list) out))
23f87bed 1026 (setq list (cdr list)))
6748645f
LMI
1027 (nreverse out)))
1028
23f87bed
MB
1029(if (fboundp 'assq-delete-all)
1030 (defalias 'gnus-delete-alist 'assq-delete-all)
1031 (defun gnus-delete-alist (key alist)
1032 "Delete from ALIST all elements whose car is KEY.
1033Return the modified alist."
1034 (let (entry)
1035 (while (setq entry (assq key alist))
1036 (setq alist (delq entry alist)))
1037 alist)))
6748645f 1038
16409b0b 1039(defmacro gnus-pull (key alist &optional assoc-p)
6748645f
LMI
1040 "Modify ALIST to be without KEY."
1041 (unless (symbolp alist)
1042 (error "Not a symbol: %s" alist))
16409b0b
GM
1043 (let ((fun (if assoc-p 'assoc 'assq)))
1044 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
6748645f
LMI
1045
1046(defun gnus-globalify-regexp (re)
23f87bed 1047 "Return a regexp that matches a whole line, iff RE matches a part of it."
6748645f
LMI
1048 (concat (unless (string-match "^\\^" re) "^.*")
1049 re
1050 (unless (string-match "\\$$" re) ".*$")))
1051
16409b0b
GM
1052(defun gnus-set-window-start (&optional point)
1053 "Set the window start to POINT, or (point) if nil."
23f87bed 1054 (let ((win (gnus-get-buffer-window (current-buffer) t)))
16409b0b
GM
1055 (when win
1056 (set-window-start win (or point (point))))))
1057
1058(defun gnus-annotation-in-region-p (b e)
1059 (if (= b e)
1060 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1061 (text-property-any b e 'gnus-undeletable t)))
1062
1063(defun gnus-or (&rest elems)
1064 "Return non-nil if any of the elements are non-nil."
1065 (catch 'found
1066 (while elems
1067 (when (pop elems)
1068 (throw 'found t)))))
1069
1070(defun gnus-and (&rest elems)
1071 "Return non-nil if all of the elements are non-nil."
1072 (catch 'found
1073 (while elems
1074 (unless (pop elems)
1075 (throw 'found nil)))
1076 t))
1077
1078(defun gnus-write-active-file (file hashtb &optional full-names)
1079 (let ((coding-system-for-write nnmail-active-file-coding-system))
1080 (with-temp-file file
1081 (mapatoms
1082 (lambda (sym)
1083 (when (and sym
1084 (boundp sym)
1085 (symbol-value sym))
1086 (insert (format "%S %d %d y\n"
1087 (if full-names
1088 sym
1089 (intern (gnus-group-real-name (symbol-name sym))))
1090 (or (cdr (symbol-value sym))
1091 (car (symbol-value sym)))
1092 (car (symbol-value sym))))))
1093 hashtb)
1094 (goto-char (point-max))
1095 (while (search-backward "\\." nil t)
1096 (delete-char 1)))))
1097
23f87bed
MB
1098;; Fixme: Why not use `with-output-to-temp-buffer'?
1099(defmacro gnus-with-output-to-file (file &rest body)
1100 (let ((buffer (make-symbol "output-buffer"))
1101 (size (make-symbol "output-buffer-size"))
1102 (leng (make-symbol "output-buffer-length"))
1103 (append (make-symbol "output-buffer-append")))
1104 `(let* ((,size 131072)
1105 (,buffer (make-string ,size 0))
1106 (,leng 0)
1107 (,append nil)
1108 (standard-output
1109 (lambda (c)
1110 (aset ,buffer ,leng c)
1111
1112 (if (= ,size (setq ,leng (1+ ,leng)))
1113 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1114 (setq ,leng 0
1115 ,append t))))))
1116 ,@body
1117 (when (> ,leng 0)
1118 (let ((coding-system-for-write 'no-conversion))
1119 (write-region (substring ,buffer 0 ,leng) nil ,file
1120 ,append 'no-msg))))))
1121
1122(put 'gnus-with-output-to-file 'lisp-indent-function 1)
1123(put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1124
1125(if (fboundp 'union)
1126 (defalias 'gnus-union 'union)
1127 (defun gnus-union (l1 l2)
1128 "Set union of lists L1 and L2."
1129 (cond ((null l1) l2)
1130 ((null l2) l1)
1131 ((equal l1 l2) l1)
1132 (t
1133 (or (>= (length l1) (length l2))
1134 (setq l1 (prog1 l2 (setq l2 l1))))
1135 (while l2
1136 (or (member (car l2) l1)
1137 (push (car l2) l1))
1138 (pop l2))
1139 l1))))
1140
520aa572
SZ
1141(defun gnus-add-text-properties-when
1142 (property value start end properties &optional object)
1143 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1144 (let (point)
3d8c35d3 1145 (while (and start
23f87bed 1146 (< start end) ;; XEmacs will loop for every when start=end.
520aa572
SZ
1147 (setq point (text-property-not-all start end property value)))
1148 (gnus-add-text-properties start point properties object)
1149 (setq start (text-property-any point end property value)))
1150 (if start
1151 (gnus-add-text-properties start end properties object))))
1152
1153(defun gnus-remove-text-properties-when
1154 (property value start end properties &optional object)
1155 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1156 (let (point)
3d8c35d3 1157 (while (and start
23f87bed 1158 (< start end)
520aa572
SZ
1159 (setq point (text-property-not-all start end property value)))
1160 (remove-text-properties start point properties object)
1161 (setq start (text-property-any point end property value)))
1162 (if start
4481aa98
SZ
1163 (remove-text-properties start end properties object))
1164 t))
520aa572 1165
23f87bed
MB
1166;; This might use `compare-strings' to reduce consing in the
1167;; case-insensitive case, but it has to cope with null args.
1168;; (`string-equal' uses symbol print names.)
1169(defun gnus-string-equal (x y)
1170 "Like `string-equal', except it compares case-insensitively."
1171 (and (= (length x) (length y))
1172 (or (string-equal x y)
1173 (string-equal (downcase x) (downcase y)))))
1174
1175(defcustom gnus-use-byte-compile t
1176 "If non-nil, byte-compile crucial run-time code.
1177Setting it to nil has no effect after the first time `gnus-byte-compile'
1178is run."
1179 :type 'boolean
a08b59c9 1180 :version "21.4"
23f87bed
MB
1181 :group 'gnus-various)
1182
1183(defun gnus-byte-compile (form)
1184 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1185 (if gnus-use-byte-compile
1186 (progn
1187 (condition-case nil
1188 ;; Work around a bug in XEmacs 21.4
1189 (require 'byte-optimize)
1190 (error))
1191 (require 'bytecomp)
1192 (defalias 'gnus-byte-compile
1193 (lambda (form)
1194 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1195 (byte-compile form))))
1196 (gnus-byte-compile form))
1197 form))
1198
1199(defun gnus-remassoc (key alist)
1200 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1201The modified LIST is returned. If the first member
1202of LIST has a car that is `equal' to KEY, there is no way to remove it
54506618 1203by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
23f87bed
MB
1204sure of changing the value of `foo'."
1205 (when alist
1206 (if (equal key (caar alist))
1207 (cdr alist)
1208 (setcdr alist (gnus-remassoc key (cdr alist)))
1209 alist)))
1210
1211(defun gnus-update-alist-soft (key value alist)
1212 (if value
1213 (cons (cons key value) (gnus-remassoc key alist))
1214 (gnus-remassoc key alist)))
1215
1216(defun gnus-create-info-command (node)
1217 "Create a command that will go to info NODE."
1218 `(lambda ()
1219 (interactive)
1220 ,(concat "Enter the info system at node " node)
1221 (Info-goto-node ,node)
1222 (setq gnus-info-buffer (current-buffer))
1223 (gnus-configure-windows 'info)))
1224
1225(defun gnus-not-ignore (&rest args)
1226 t)
1227
47b63dfa
SZ
1228(defvar gnus-directory-sep-char-regexp "/"
1229 "The regexp of directory separator character.
1230If you find some problem with the directory separator character, try
1231\"[/\\\\\]\" for some systems.")
1232
23f87bed
MB
1233(defun gnus-url-unhex (x)
1234 (if (> x ?9)
1235 (if (>= x ?a)
1236 (+ 10 (- x ?a))
1237 (+ 10 (- x ?A)))
1238 (- x ?0)))
1239
1240;; Fixme: Do it like QP.
1241(defun gnus-url-unhex-string (str &optional allow-newlines)
1242 "Remove %XX, embedded spaces, etc in a url.
1243If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1244decoding of carriage returns and line feeds in the string, which is normally
1245forbidden in URL encoding."
1246 (let ((tmp "")
1247 (case-fold-search t))
1248 (while (string-match "%[0-9a-f][0-9a-f]" str)
1249 (let* ((start (match-beginning 0))
1250 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1251 (code (+ (* 16 ch1)
1252 (gnus-url-unhex (elt str (+ start 2))))))
1253 (setq tmp (concat
1254 tmp (substring str 0 start)
1255 (cond
1256 (allow-newlines
1257 (char-to-string code))
1258 ((or (= code ?\n) (= code ?\r))
1259 " ")
1260 (t (char-to-string code))))
1261 str (substring str (match-end 0)))))
1262 (setq tmp (concat tmp str))
1263 tmp))
1264
1265(defun gnus-make-predicate (spec)
1266 "Transform SPEC into a function that can be called.
1267SPEC is a predicate specifier that contains stuff like `or', `and',
1268`not', lists and functions. The functions all take one parameter."
1269 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1270
1271(defun gnus-make-predicate-1 (spec)
1272 (cond
1273 ((symbolp spec)
1274 `(,spec elem))
1275 ((listp spec)
1276 (if (memq (car spec) '(or and not))
1277 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1278 (error "Invalid predicate specifier: %s" spec)))))
1279
1280(defun gnus-local-map-property (map)
1281 "Return a list suitable for a text property list specifying keymap MAP."
1282 (cond
1283 ((featurep 'xemacs)
1284 (list 'keymap map))
1285 ((>= emacs-major-version 21)
1286 (list 'keymap map))
1287 (t
1288 (list 'local-map map))))
1289
1290(defmacro gnus-completing-read-maybe-default (prompt table &optional predicate
1291 require-match initial-contents
1292 history default)
1293 "Like `completing-read', allowing for non-existent 7th arg in older XEmacsen."
1294 `(completing-read ,prompt ,table ,predicate ,require-match
1295 ,initial-contents ,history
1296 ,@(if (and (featurep 'xemacs) (< emacs-minor-version 2))
1297 ()
1298 (list default))))
1299
1300(defun gnus-completing-read (prompt table &optional predicate require-match
1301 history)
1302 (when (and history
1303 (not (boundp history)))
1304 (set history nil))
1305 (gnus-completing-read-maybe-default
1306 (if (symbol-value history)
1307 (concat prompt " (" (car (symbol-value history)) "): ")
1308 (concat prompt ": "))
1309 table
1310 predicate
1311 require-match
1312 nil
1313 history
1314 (car (symbol-value history))))
1315
1316(defun gnus-graphic-display-p ()
1317 (or (and (fboundp 'display-graphic-p)
1318 (display-graphic-p))
1319 ;;;!!!This is bogus. Fixme!
1320 (and (featurep 'xemacs)
1321 t)))
1322
1323(put 'gnus-parse-without-error 'lisp-indent-function 0)
1324(put 'gnus-parse-without-error 'edebug-form-spec '(body))
1325
1326(defmacro gnus-parse-without-error (&rest body)
1327 "Allow continuing onto the next line even if an error occurs."
1328 `(while (not (eobp))
1329 (condition-case ()
1330 (progn
1331 ,@body
1332 (goto-char (point-max)))
1333 (error
1334 (gnus-error 4 "Invalid data on line %d"
1335 (count-lines (point-min) (point)))
1336 (forward-line 1)))))
1337
1338(defun gnus-cache-file-contents (file variable function)
1339 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1340 (let ((time (nth 5 (file-attributes file)))
1341 contents value)
1342 (if (or (null (setq value (symbol-value variable)))
1343 (not (equal (car value) file))
1344 (not (equal (nth 1 value) time)))
1345 (progn
1346 (setq contents (funcall function file))
1347 (set variable (list file time contents))
1348 contents)
1349 (nth 2 value))))
1350
1351(defun gnus-multiple-choice (prompt choice &optional idx)
1352 "Ask user a multiple choice question.
1353CHOICE is a list of the choice char and help message at IDX."
1354 (let (tchar buf)
1355 (save-window-excursion
1356 (save-excursion
1357 (while (not tchar)
1358 (message "%s (%s): "
1359 prompt
1360 (concat
1361 (mapconcat (lambda (s) (char-to-string (car s)))
1362 choice ", ") ", ?"))
1363 (setq tchar (read-char))
1364 (when (not (assq tchar choice))
1365 (setq tchar nil)
1366 (setq buf (get-buffer-create "*Gnus Help*"))
1367 (pop-to-buffer buf)
1368 (fundamental-mode) ; for Emacs 20.4+
1369 (buffer-disable-undo)
1370 (erase-buffer)
1371 (insert prompt ":\n\n")
1372 (let ((max -1)
1373 (list choice)
1374 (alist choice)
1375 (idx (or idx 1))
1376 (i 0)
1377 n width pad format)
1378 ;; find the longest string to display
1379 (while list
1380 (setq n (length (nth idx (car list))))
1381 (unless (> max n)
1382 (setq max n))
1383 (setq list (cdr list)))
1384 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1385 (setq n (/ (1- (window-width)) max)) ; items per line
1386 (setq width (/ (1- (window-width)) n)) ; width of each item
1387 ;; insert `n' items, each in a field of width `width'
1388 (while alist
1389 (if (< i n)
1390 ()
1391 (setq i 0)
1392 (delete-char -1) ; the `\n' takes a char
1393 (insert "\n"))
1394 (setq pad (- width 3))
1395 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1396 (insert (format format (caar alist) (nth idx (car alist))))
1397 (setq alist (cdr alist))
1398 (setq i (1+ i))))))))
1399 (if (buffer-live-p buf)
1400 (kill-buffer buf))
1401 tchar))
1402
1403(defun gnus-select-frame-set-input-focus (frame)
1404 "Select FRAME, raise it, and set input focus, if possible."
1405 (cond ((featurep 'xemacs)
1406 (raise-frame frame)
1407 (select-frame frame)
1408 (focus-frame frame))
1409 ;; The function `select-frame-set-input-focus' won't set
1410 ;; the input focus under Emacs 21.2 and X window system.
1411 ;;((fboundp 'select-frame-set-input-focus)
1412 ;; (defalias 'gnus-select-frame-set-input-focus
1413 ;; 'select-frame-set-input-focus)
1414 ;; (select-frame-set-input-focus frame))
1415 (t
1416 (raise-frame frame)
1417 (select-frame frame)
1418 (cond ((and (eq window-system 'x)
1419 (fboundp 'x-focus-frame))
1420 (x-focus-frame frame))
1421 ((eq window-system 'w32)
1422 (w32-focus-frame frame)))
1423 (when focus-follows-mouse
1424 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1425
1426(defun gnus-frame-or-window-display-name (object)
1427 "Given a frame or window, return the associated display name.
1428Return nil otherwise."
1429 (if (featurep 'xemacs)
1430 (device-connection (dfw-device object))
1431 (if (or (framep object)
1432 (and (windowp object)
1433 (setq object (window-frame object))))
1434 (let ((display (frame-parameter object 'display)))
1435 (if (and (stringp display)
1436 ;; Exclude invalid display names.
1437 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1438 display))
1439 display)))))
1440
1441;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1442(defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1443 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1444If there are several sequences, FUNCTION is called with that many arguments,
1445and mapping stops as soon as the shortest sequence runs out. With just one
1446sequence, this is like `mapcar'. With several, it is like the Common Lisp
1447`mapcar' function extended to arbitrary sequence types."
1448
1449 (if seqs2_n
1450 (let* ((seqs (cons seq1 seqs2_n))
1451 (cnt 0)
1452 (heads (mapcar (lambda (seq)
1453 (make-symbol (concat "head"
1454 (int-to-string
1455 (setq cnt (1+ cnt))))))
1456 seqs))
1457 (result (make-symbol "result"))
1458 (result-tail (make-symbol "result-tail")))
1459 `(let* ,(let* ((bindings (cons nil nil))
1460 (heads heads))
1461 (nconc bindings (list (list result '(cons nil nil))))
1462 (nconc bindings (list (list result-tail result)))
1463 (while heads
1464 (nconc bindings (list (list (pop heads) (pop seqs)))))
1465 (cdr bindings))
1466 (while (and ,@heads)
1467 (setcdr ,result-tail (cons (funcall ,function
1468 ,@(mapcar (lambda (h) (list 'car h))
1469 heads))
1470 nil))
1471 (setq ,result-tail (cdr ,result-tail)
1472 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1473 (cdr ,result)))
1474 `(mapcar ,function ,seq1)))
1475
1476(if (fboundp 'merge)
1477 (defalias 'gnus-merge 'merge)
1478 ;; Adapted from cl-seq.el
1479 (defun gnus-merge (type list1 list2 pred)
1480 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1481Argument TYPE is for compatibility and ignored.
1482Ordering of the elements is preserved according to PRED, a `less-than'
1483predicate on the elements."
1484 (let ((res nil))
1485 (while (and list1 list2)
1486 (if (funcall pred (car list2) (car list1))
1487 (push (pop list2) res)
1488 (push (pop list1) res)))
1489 (nconc (nreverse res) list1 list2))))
1490
1491(eval-when-compile
1492 (defvar xemacs-codename))
1493
1494(defun gnus-emacs-version ()
1495 "Stringified Emacs version."
1496 (let ((system-v
1497 (cond
1498 ((eq gnus-user-agent 'emacs-gnus-config)
1499 system-configuration)
1500 ((eq gnus-user-agent 'emacs-gnus-type)
1501 (symbol-name system-type))
1502 (t nil))))
1503 (cond
1504 ((eq gnus-user-agent 'gnus)
1505 nil)
1506 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1507 (concat "Emacs/" (match-string 1 emacs-version)
1508 (if system-v
1509 (concat " (" system-v ")")
1510 "")))
1511 ((string-match
1512 "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1513 emacs-version)
1514 (concat
1515 (match-string 1 emacs-version)
1516 (format "/%d.%d" emacs-major-version emacs-minor-version)
1517 (if (match-beginning 3)
1518 (match-string 3 emacs-version)
1519 "")
1520 (if (boundp 'xemacs-codename)
1521 (concat
1522 " (" xemacs-codename
1523 (if system-v
1524 (concat ", " system-v ")")
1525 ")"))
1526 "")))
1527 (t emacs-version))))
1528
54506618
MB
1529(defun gnus-rename-file (old-path new-path &optional trim)
1530 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1531empty directories from OLD-PATH."
1532 (when (file-exists-p old-path)
1533 (let* ((old-dir (file-name-directory old-path))
1534 (old-name (file-name-nondirectory old-path))
1535 (new-dir (file-name-directory new-path))
1536 (new-name (file-name-nondirectory new-path))
1537 temp)
1538 (gnus-make-directory new-dir)
1539 (rename-file old-path new-path t)
1540 (when trim
1541 (while (progn (setq temp (directory-files old-dir))
1542 (while (member (car temp) '("." ".."))
1543 (setq temp (cdr temp)))
1544 (= (length temp) 0))
1545 (delete-directory old-dir)
1546 (setq old-dir (file-name-as-directory
1547 (file-truename
1548 (concat old-dir "..")))))))))
1549
1550
eec82323
LMI
1551(provide 'gnus-util)
1552
ab5796a9 1553;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
eec82323 1554;;; gnus-util.el ends here