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