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