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