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