8b4f68741f21ab3b8a317f4c3d8f595d481bcdfe
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
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., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, 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 ;;; Code:
34
35 (eval-when-compile
36   (require 'cl)
37   ;; Fixme: this should be a gnus variable, not nnmail-.
38   (defvar nnmail-pathname-coding-system))
39 (eval-when-compile (require 'static))
40
41 (require 'custom)
42 (require 'nnheader)
43 (require 'time-date)
44
45 (eval-and-compile
46   (autoload 'message-fetch-field "message")
47   (autoload 'rmail-insert-rmail-file-header "rmail")
48   (autoload 'rmail-count-new-messages "rmail")
49   (autoload 'rmail-show-message "rmail"))
50
51 (eval-and-compile
52   (cond
53    ((fboundp 'replace-in-string)
54     (defalias 'gnus-replace-in-string 'replace-in-string))
55    ((fboundp 'replace-regexp-in-string)
56     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
57       (replace-regexp-in-string regexp newtext string nil literal)))
58    (t
59     (defun gnus-replace-in-string (string regexp newtext &optional literal)
60       (let ((start 0) tail)
61         (while (string-match regexp string start)
62           (setq tail (- (length string) (match-end 0)))
63           (setq string (replace-match newtext nil literal string))
64           (setq start (- (length string) tail))))
65       string))))
66
67 (defun gnus-boundp (variable)
68   "Return non-nil if VARIABLE is bound and non-nil."
69   (and (boundp variable)
70        (symbol-value variable)))
71
72 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
73   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
74   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
75         (w (make-symbol "w"))
76         (buf (make-symbol "buf"))
77         (frame (make-symbol "frame")))
78     `(let* ((,tempvar (selected-window))
79             (,buf ,buffer)
80             (,w (get-buffer-window ,buf 'visible))
81             ,frame)
82        (unwind-protect
83            (progn
84              (if ,w
85                  (progn
86                    (select-window ,w)
87                    (set-buffer (window-buffer ,w)))
88                (pop-to-buffer ,buf))
89              ,@forms)
90          (setq ,frame (selected-frame))
91          (select-window ,tempvar)
92          (select-frame ,frame)))))
93
94 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
95 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
96
97 (defmacro gnus-intern-safe (string hashtable)
98   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
99   `(let ((symbol (intern ,string ,hashtable)))
100      (or (boundp symbol)
101          (set symbol nil))
102      symbol))
103
104 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
105 ;; to limit the length of a string.  This function is necessary since
106 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
107 (defsubst gnus-limit-string (str width)
108   (if (> (length str) width)
109       (substring str 0 width)
110     str))
111
112 (defsubst gnus-functionp (form)
113   "Return non-nil if FORM is funcallable."
114   (or (and (symbolp form) (fboundp form))
115       (and (listp form) (eq (car form) 'lambda))
116       (byte-code-function-p form)))
117
118 (defsubst gnus-goto-char (point)
119   (and point (goto-char point)))
120
121 (defmacro gnus-buffer-exists-p (buffer)
122   `(let ((buffer ,buffer))
123      (when buffer
124        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
125                 buffer))))
126
127 (defmacro gnus-kill-buffer (buffer)
128   `(let ((buf ,buffer))
129      (when (gnus-buffer-exists-p buf)
130        (kill-buffer buf))))
131
132 (static-cond
133  ((fboundp 'point-at-bol)
134   (defalias 'gnus-point-at-bol 'point-at-bol))
135  ((fboundp 'line-beginning-position)
136   (defalias 'gnus-point-at-bol 'line-beginning-position))
137  (t
138   (defun gnus-point-at-bol ()
139     "Return point at the beginning of the line."
140     (let ((p (point)))
141       (beginning-of-line)
142       (prog1
143           (point)
144         (goto-char p))))
145   ))
146 (static-cond
147  ((fboundp 'point-at-eol)
148   (defalias 'gnus-point-at-eol 'point-at-eol))
149  ((fboundp 'line-end-position)
150   (defalias 'gnus-point-at-eol 'line-end-position))
151  (t
152   (defun gnus-point-at-eol ()
153     "Return point at the end of the line."
154     (let ((p (point)))
155       (end-of-line)
156       (prog1
157           (point)
158         (goto-char p))))
159   ))
160
161 (defun gnus-delete-first (elt list)
162   "Delete by side effect the first occurrence of ELT as a member of LIST."
163   (if (equal (car list) elt)
164       (cdr list)
165     (let ((total list))
166       (while (and (cdr list)
167                   (not (equal (cadr list) elt)))
168         (setq list (cdr list)))
169       (when (cdr list)
170         (setcdr list (cddr list)))
171       total)))
172
173 ;; Delete the current line (and the next N lines).
174 (defmacro gnus-delete-line (&optional n)
175   `(delete-region (progn (beginning-of-line) (point))
176                   (progn (forward-line ,(or n 1)) (point))))
177
178 (defun gnus-byte-code (func)
179   "Return a form that can be `eval'ed based on FUNC."
180   (let ((fval (indirect-function func)))
181     (if (byte-code-function-p fval)
182         (let ((flist (append fval nil)))
183           (setcar flist 'byte-code)
184           flist)
185       (cons 'progn (cddr fval)))))
186
187 (defun gnus-extract-address-components (from)
188   (let (name address)
189     ;; First find the address - the thing with the @ in it.  This may
190     ;; not be accurate in mail addresses, but does the trick most of
191     ;; the time in news messages.
192     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
193       (setq address (substring from (match-beginning 0) (match-end 0))))
194     ;; Then we check whether the "name <address>" format is used.
195     (and address
196          ;; Linear white space is not required.
197          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
198          (and (setq name (substring from 0 (match-beginning 0)))
199               ;; Strip any quotes from the name.
200               (string-match "\".*\"" name)
201               (setq name (substring name 1 (1- (match-end 0))))))
202     ;; If not, then "address (name)" is used.
203     (or name
204         (and (string-match "(.+)" from)
205              (setq name (substring from (1+ (match-beginning 0))
206                                    (1- (match-end 0)))))
207         (and (string-match "()" from)
208              (setq name address))
209         ;; XOVER might not support folded From headers.
210         (and (string-match "(.*" from)
211              (setq name (substring from (1+ (match-beginning 0))
212                                    (match-end 0)))))
213     (list (if (string= name "") nil name) (or address from))))
214
215
216 (defun gnus-fetch-field (field)
217   "Return the value of the header FIELD of current article."
218   (save-excursion
219     (save-restriction
220       (let ((case-fold-search t)
221             (inhibit-point-motion-hooks t))
222         (nnheader-narrow-to-headers)
223         (message-fetch-field field)))))
224
225 (defun gnus-goto-colon ()
226   (beginning-of-line)
227   (let ((eol (gnus-point-at-eol)))
228     (goto-char (or (text-property-any (point) eol 'gnus-position t)
229                    (search-forward ":" eol t)
230                    (point)))))
231
232 (defun gnus-decode-newsgroups (newsgroups group &optional method)
233   (let ((method (or method (gnus-find-method-for-group group))))
234     (mapconcat (lambda (group)
235                  (gnus-group-name-decode group (gnus-group-name-charset
236                                                 method group)))
237                (message-tokenize-header newsgroups)
238                ",")))
239
240 (defun gnus-remove-text-with-property (prop)
241   "Delete all text in the current buffer with text property PROP."
242   (save-excursion
243     (goto-char (point-min))
244     (while (not (eobp))
245       (while (get-text-property (point) prop)
246         (delete-char 1))
247       (goto-char (next-single-property-change (point) prop nil (point-max))))))
248
249 (require 'nnheader)
250 (defun gnus-newsgroup-directory-form (newsgroup)
251   "Make hierarchical directory name from NEWSGROUP name."
252   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
253          (idx (string-match ":" newsgroup)))
254     (concat
255      (if idx (substring newsgroup 0 idx))
256      (if idx "/")
257      (nnheader-replace-chars-in-string
258       (if idx (substring newsgroup (1+ idx)) newsgroup)
259       ?. ?/))))
260
261 (defun gnus-newsgroup-savable-name (group)
262   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
263   ;; with dots.
264   (nnheader-replace-chars-in-string group ?/ ?.))
265
266 (defun gnus-string> (s1 s2)
267   (not (or (string< s1 s2)
268            (string= s1 s2))))
269
270 ;;; Time functions.
271
272 (defun gnus-file-newer-than (file date)
273   (let ((fdate (nth 5 (file-attributes file))))
274     (or (> (car fdate) (car date))
275         (and (= (car fdate) (car date))
276              (> (nth 1 fdate) (nth 1 date))))))
277
278 ;;; Keymap macros.
279
280 (defmacro gnus-local-set-keys (&rest plist)
281   "Set the keys in PLIST in the current keymap."
282   `(gnus-define-keys-1 (current-local-map) ',plist))
283
284 (defmacro gnus-define-keys (keymap &rest plist)
285   "Define all keys in PLIST in KEYMAP."
286   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
287
288 (defmacro gnus-define-keys-safe (keymap &rest plist)
289   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
290   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
291
292 (put 'gnus-define-keys 'lisp-indent-function 1)
293 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
294 (put 'gnus-local-set-keys 'lisp-indent-function 1)
295
296 (defmacro gnus-define-keymap (keymap &rest plist)
297   "Define all keys in PLIST in KEYMAP."
298   `(gnus-define-keys-1 ,keymap (quote ,plist)))
299
300 (put 'gnus-define-keymap 'lisp-indent-function 1)
301
302 (defun gnus-define-keys-1 (keymap plist &optional safe)
303   (when (null keymap)
304     (error "Can't set keys in a null keymap"))
305   (cond ((symbolp keymap)
306          (setq keymap (symbol-value keymap)))
307         ((keymapp keymap))
308         ((listp keymap)
309          (set (car keymap) nil)
310          (define-prefix-command (car keymap))
311          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
312          (setq keymap (symbol-value (car keymap)))))
313   (let (key)
314     (while plist
315       (when (symbolp (setq key (pop plist)))
316         (setq key (symbol-value key)))
317       (if (or (not safe)
318               (eq (lookup-key keymap key) 'undefined))
319           (define-key keymap key (pop plist))
320         (pop plist)))))
321
322 (defun gnus-completing-read (default prompt &rest args)
323   ;; Like `completing-read', except that DEFAULT is the default argument.
324   (let* ((prompt (if default
325                      (concat prompt " (default " default ") ")
326                    (concat prompt " ")))
327          (answer (apply 'completing-read prompt args)))
328     (if (or (null answer) (zerop (length answer)))
329         default
330       answer)))
331
332 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
333 ;; the echo area.
334 (defun gnus-y-or-n-p (prompt)
335   (prog1
336       (y-or-n-p prompt)
337     (message "")))
338
339 (defun gnus-yes-or-no-p (prompt)
340   (prog1
341       (yes-or-no-p prompt)
342     (message "")))
343
344 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
345 ;; age-depending date representations. (e.g. just the time if it's
346 ;; from today, the day of the week if it's within the last 7 days and
347 ;; the full date if it's older)
348 (defun gnus-seconds-today ()
349   "Returns the number of seconds passed today"
350   (let ((now (decode-time (current-time))))
351     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
352
353 (defun gnus-seconds-month ()
354   "Returns the number of seconds passed this month"
355   (let ((now (decode-time (current-time))))
356     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
357        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
358
359 (defun gnus-seconds-year ()
360   "Returns the number of seconds passed this year"
361   (let ((now (decode-time (current-time)))
362         (days (format-time-string "%j" (current-time))))
363     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
364        (* (- (string-to-number days) 1) 3600 24))))
365
366 (defvar gnus-user-date-format-alist
367   '(((gnus-seconds-today) . "%k:%M")
368     (604800 . "%a %k:%M")                   ;;that's one week
369     ((gnus-seconds-month) . "%a %d")
370     ((gnus-seconds-year) . "%b %d")
371     (t . "%b %m '%y"))                      ;;this one is used when no other does match
372   "Alist of time in seconds and format specification used to display dates not older.
373 The first element must be a number or a function returning a
374 number. The second element is a format-specification as described in
375 the documentation for format-time-string.  The list must be ordered
376 smallest number up. When there is an element, which is not a number,
377 the corresponding format-specification will be used, disregarding any
378 following elements.  You can use the functions gnus-seconds-today,
379 gnus-seconds-month, gnus-seconds-year which will return the number of
380 seconds which passed today/this month/this year.")
381
382 (defun gnus-user-date (messy-date)
383   "Format the messy-date acording 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 (safe-date-to-time messy-date))
388              (now (current-time))
389              ;;If we don't find something suitable we'll use this one
390              (my-format "%b %m '%y")
391              (high (lsh (- (car now) (car messy-date)) 16)))
392         (if (and (> high -1) (= (logand high 65535) 0))
393             ;;overflow and bad input
394             (let* ((difference (+ high (- (car (cdr now))
395                                           (car (cdr messy-date)))))
396                    (templist gnus-user-date-format-alist)
397                    (top (eval (caar templist))))
398               (while (if (numberp top) (< top difference) (not top))
399                 (progn
400                   (setq templist (cdr templist))
401                   (setq top (eval (caar templist)))))
402               (if (stringp (cdr (car templist)))
403                   (setq my-format (cdr (car templist))))))
404         (format-time-string (eval my-format) messy-date))
405     (error "  ?   ")))
406 ;;end of Frank's code
407
408 (defun gnus-dd-mmm (messy-date)
409   "Return a string like DD-MMM from a big messy string."
410   (condition-case ()
411       (format-time-string "%d-%b" (safe-date-to-time messy-date))
412     (error "  -   ")))
413
414 (defmacro gnus-date-get-time (date)
415   "Convert DATE string to Emacs time.
416 Cache the result as a text property stored in DATE."
417   ;; Either return the cached value...
418   `(let ((d ,date))
419      (if (equal "" d)
420          '(0 0)
421        (or (get-text-property 0 'gnus-time d)
422            ;; or compute the value...
423            (let ((time (safe-date-to-time d)))
424              ;; and store it back in the string.
425              (put-text-property 0 1 'gnus-time time d)
426              time)))))
427
428 (defsubst gnus-time-iso8601 (time)
429   "Return a string of TIME in YYYYMMDDTHHMMSS format."
430   (format-time-string "%Y%m%dT%H%M%S" time))
431
432 (defun gnus-date-iso8601 (date)
433   "Convert the DATE to YYYYMMDDTHHMMSS."
434   (condition-case ()
435       (gnus-time-iso8601 (gnus-date-get-time date))
436     (error "")))
437
438 (defun gnus-mode-string-quote (string)
439   "Quote all \"%\"'s in STRING."
440   (gnus-replace-in-string string "%" "%%"))
441
442 ;; Make a hash table (default and minimum size is 256).
443 ;; Optional argument HASHSIZE specifies the table size.
444 (defun gnus-make-hashtable (&optional hashsize)
445   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
446
447 ;; Make a number that is suitable for hashing; bigger than MIN and
448 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
449 ;; hardware modulo operation, so they implement it in software.  On
450 ;; many sparcs over 50% of the time to intern is spent in the modulo.
451 ;; Yes, it's slower than actually computing the hash from the string!
452 ;; So we use powers of 2 so people can optimize the modulo to a mask.
453 (defun gnus-create-hash-size (min)
454   (let ((i 1))
455     (while (< i min)
456       (setq i (* 2 i)))
457     i))
458
459 (defcustom gnus-verbose 7
460   "*Integer that says how verbose Gnus should be.
461 The higher the number, the more messages Gnus will flash to say what
462 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
463 display most important messages; and at ten, Gnus will keep on
464 jabbering all the time."
465   :group 'gnus-start
466   :type 'integer)
467
468 ;; Show message if message has a lower level than `gnus-verbose'.
469 ;; Guideline for numbers:
470 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
471 ;; for things that take a long time, 7 - not very important messages
472 ;; on stuff, 9 - messages inside loops.
473 (defun gnus-message (level &rest args)
474   (if (<= level gnus-verbose)
475       (apply 'message args)
476     ;; We have to do this format thingy here even if the result isn't
477     ;; shown - the return value has to be the same as the return value
478     ;; from `message'.
479     (apply 'format args)))
480
481 (defun gnus-error (level &rest args)
482   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
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         ids)
496     (while (string-match "<[^> \t]+>" references beg)
497       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
498             ids))
499     (nreverse ids)))
500
501 (defsubst gnus-parent-id (references &optional n)
502   "Return the last Message-ID in REFERENCES.
503 If N, return the Nth ancestor instead."
504   (when references
505     (let ((ids (inline (gnus-split-references references))))
506       (while (nthcdr (or n 1) ids)
507         (setq ids (cdr ids)))
508       (car ids))))
509
510 (defun gnus-buffer-live-p (buffer)
511   "Say whether BUFFER is alive or not."
512   (and buffer
513        (get-buffer buffer)
514        (buffer-name (get-buffer buffer))))
515
516 (defun gnus-horizontal-recenter ()
517   "Recenter the current buffer horizontally."
518   (if (< (current-column) (/ (window-width) 2))
519       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
520     (let* ((orig (point))
521            (end (window-end (get-buffer-window (current-buffer) t)))
522            (max 0))
523       (when end
524         ;; Find the longest line currently displayed in the window.
525         (goto-char (window-start))
526         (while (and (not (eobp))
527                     (< (point) end))
528           (end-of-line)
529           (setq max (max max (current-column)))
530           (forward-line 1))
531         (goto-char orig)
532         ;; Scroll horizontally to center (sort of) the point.
533         (if (> max (window-width))
534             (set-window-hscroll
535              (get-buffer-window (current-buffer) t)
536              (min (- (current-column) (/ (window-width) 3))
537                   (+ 2 (- max (window-width)))))
538           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
539         max))))
540
541 (defun gnus-read-event-char ()
542   "Get the next event."
543   (let ((event (read-event)))
544     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
545     (cons (and (numberp event) event) event)))
546
547 (defun gnus-sortable-date (date)
548   "Make string suitable for sorting from DATE."
549   (gnus-time-iso8601 (date-to-time date)))
550
551 (defun gnus-copy-file (file &optional to)
552   "Copy FILE to TO."
553   (interactive
554    (list (read-file-name "Copy file: " default-directory)
555          (read-file-name "Copy file to: " default-directory)))
556   (unless to
557     (setq to (read-file-name "Copy file to: " default-directory)))
558   (when (file-directory-p to)
559     (setq to (concat (file-name-as-directory to)
560                      (file-name-nondirectory file))))
561   (copy-file file to))
562
563 (defvar gnus-work-buffer " *gnus work*")
564
565 (defun gnus-set-work-buffer ()
566   "Put point in the empty Gnus work buffer."
567   (if (get-buffer gnus-work-buffer)
568       (progn
569         (set-buffer gnus-work-buffer)
570         (erase-buffer))
571     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
572     (kill-all-local-variables)))
573
574 (defmacro gnus-group-real-name (group)
575   "Find the real name of a foreign newsgroup."
576   `(let ((gname ,group))
577      (if (string-match "^[^:]+:" gname)
578          (substring gname (match-end 0))
579        gname)))
580
581 (defun gnus-make-sort-function (funs)
582   "Return a composite sort condition based on the functions in FUNC."
583   (cond
584    ;; Just a simple function.
585    ((gnus-functionp funs) funs)
586    ;; No functions at all.
587    ((null funs) funs)
588    ;; A list of functions.
589    ((or (cdr funs)
590         (listp (car funs)))
591     (gnus-byte-compile
592      `(lambda (t1 t2)
593         ,(gnus-make-sort-function-1 (reverse funs)))))
594    ;; A list containing just one function.
595    (t
596     (car funs))))
597
598 (defun gnus-make-sort-function-1 (funs)
599   "Return a composite sort condition based on the functions in FUNC."
600   (let ((function (car funs))
601         (first 't1)
602         (last 't2))
603     (when (consp function)
604       (cond
605        ;; Reversed spec.
606        ((eq (car function) 'not)
607         (setq function (cadr function)
608               first 't2
609               last 't1))
610        ((gnus-functionp function)
611         ;; Do nothing.
612         )
613        (t
614         (error "Invalid sort spec: %s" function))))
615     (if (cdr funs)
616         `(or (,function ,first ,last)
617              (and (not (,function ,last ,first))
618                   ,(gnus-make-sort-function-1 (cdr funs))))
619       `(,function ,first ,last))))
620
621 (defun gnus-turn-off-edit-menu (type)
622   "Turn off edit menu in `gnus-TYPE-mode-map'."
623   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
624     [menu-bar edit] 'undefined))
625
626 (defun gnus-prin1 (form)
627   "Use `prin1' on FORM in the current buffer.
628 Bind `print-quoted' and `print-readably' to t while printing."
629   (let ((print-quoted t)
630         (print-readably t)
631         (print-escape-multibyte nil)
632         print-level print-length)
633     (prin1 form (current-buffer))))
634
635 (defun gnus-prin1-to-string (form)
636   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
637   (let ((print-quoted t)
638         (print-readably t))
639     (prin1-to-string form)))
640
641 (defun gnus-make-directory (directory)
642   "Make DIRECTORY (and all its parents) if it doesn't exist."
643   (require 'nnmail)
644   (let ((file-name-coding-system nnmail-pathname-coding-system)
645         (pathname-coding-system nnmail-pathname-coding-system))
646     (when (and directory
647                (not (file-exists-p directory)))
648       (make-directory directory t)))
649   t)
650
651 (defun gnus-write-buffer (file)
652   "Write the current buffer's contents to FILE."
653   ;; Make sure the directory exists.
654   (gnus-make-directory (file-name-directory file))
655   (let ((file-name-coding-system nnmail-pathname-coding-system)
656         (pathname-coding-system nnmail-pathname-coding-system))
657     ;; Write the buffer.
658     (write-region (point-min) (point-max) file nil 'quietly)))
659
660 (defun gnus-write-buffer-as-binary (file)
661   "Write the current buffer's contents to FILE without code conversion."
662   ;; Make sure the directory exists.
663   (gnus-make-directory (file-name-directory file))
664   ;; Write the buffer.
665   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
666
667 (defun gnus-write-buffer-as-coding-system (coding-system file)
668   "Write the current buffer's contents to FILE with code conversion."
669   ;; Make sure the directory exists.
670   (gnus-make-directory (file-name-directory file))
671   ;; Write the buffer.
672   (write-region-as-coding-system
673    coding-system (point-min) (point-max) file nil 'quietly))
674
675 (defun gnus-delete-file (file)
676   "Delete FILE if it exists."
677   (when (file-exists-p file)
678     (delete-file file)))
679
680 (defun gnus-strip-whitespace (string)
681   "Return STRING stripped of all whitespace."
682   (while (string-match "[\r\n\t ]+" string)
683     (setq string (replace-match "" t t string)))
684   string)
685
686 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
687   "The same as `put-text-property', but don't put this prop on any newlines in the region."
688   (save-match-data
689     (save-excursion
690       (save-restriction
691         (goto-char beg)
692         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
693           (gnus-put-text-property beg (match-beginning 0) prop val)
694           (setq beg (point)))
695         (gnus-put-text-property beg (point) prop val)))))
696
697 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
698                                                                    prop val)
699   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
700   (let ((b beg))
701     (while (/= b end)
702       (when (get-text-property b 'gnus-face)
703         (setq b (next-single-property-change b 'gnus-face nil end)))
704       (when (/= b end)
705         (gnus-put-text-property
706          b (setq b (next-single-property-change b 'gnus-face nil end))
707          prop val)))))
708
709 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
710 ;;; The primary idea here is to try to protect internal datastructures
711 ;;; from becoming corrupted when the user hits C-g, or if a hook or
712 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
713 ;;; updated at the same time, or information can be lost.
714
715 (defvar gnus-atomic-be-safe t
716   "If t, certain operations will be protected from interruption by C-g.")
717
718 (defmacro gnus-atomic-progn (&rest forms)
719   "Evaluate FORMS atomically, which means to protect the evaluation
720 from being interrupted by the user.  An error from the forms themselves
721 will return without finishing the operation.  Since interrupts from
722 the user are disabled, it is recommended that only the most minimal
723 operations are performed by FORMS.  If you wish to assign many
724 complicated values atomically, compute the results into temporary
725 variables and then do only the assignment atomically."
726   `(let ((inhibit-quit gnus-atomic-be-safe))
727      ,@forms))
728
729 (put 'gnus-atomic-progn 'lisp-indent-function 0)
730
731 (defmacro gnus-atomic-progn-assign (protect &rest forms)
732   "Evaluate FORMS, but insure that the variables listed in PROTECT
733 are not changed if anything in FORMS signals an error or otherwise
734 non-locally exits.  The variables listed in PROTECT are updated atomically.
735 It is safe to use gnus-atomic-progn-assign with long computations.
736
737 Note that if any of the symbols in PROTECT were unbound, they will be
738 set to nil on a sucessful assignment.  In case of an error or other
739 non-local exit, it will still be unbound."
740   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
741                                                   (concat (symbol-name x)
742                                                           "-tmp"))
743                                                  x))
744                                protect))
745          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
746                                temp-sym-map))
747          (temp-sym-let (mapcar (lambda (x) (list (car x)
748                                                  `(and (boundp ',(cadr x))
749                                                        ,(cadr x))))
750                                temp-sym-map))
751          (sym-temp-let sym-temp-map)
752          (temp-sym-assign (apply 'append temp-sym-map))
753          (sym-temp-assign (apply 'append sym-temp-map))
754          (result (make-symbol "result-tmp")))
755     `(let (,@temp-sym-let
756            ,result)
757        (let ,sym-temp-let
758          (setq ,result (progn ,@forms))
759          (setq ,@temp-sym-assign))
760        (let ((inhibit-quit gnus-atomic-be-safe))
761          (setq ,@sym-temp-assign))
762        ,result)))
763
764 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
765 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
766
767 (defmacro gnus-atomic-setq (&rest pairs)
768   "Similar to setq, except that the real symbols are only assigned when
769 there are no errors.  And when the real symbols are assigned, they are
770 done so atomically.  If other variables might be changed via side-effect,
771 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
772 with potentially long computations."
773   (let ((tpairs pairs)
774         syms)
775     (while tpairs
776       (push (car tpairs) syms)
777       (setq tpairs (cddr tpairs)))
778     `(gnus-atomic-progn-assign ,syms
779        (setq ,@pairs))))
780
781 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
782
783
784 ;;; Functions for saving to babyl/mail files.
785
786 (defvar rmail-default-rmail-file)
787 (defun gnus-output-to-rmail (filename &optional ask)
788   "Append the current article to an Rmail file named FILENAME."
789   (require 'rmail)
790   ;; Most of these codes are borrowed from rmailout.el.
791   (setq filename (expand-file-name filename))
792   (setq rmail-default-rmail-file filename)
793   (let ((artbuf (current-buffer))
794         (tmpbuf (get-buffer-create " *Gnus-output*")))
795     (save-excursion
796       (or (get-file-buffer filename)
797           (file-exists-p filename)
798           (if (or (not ask)
799                   (gnus-yes-or-no-p
800                    (concat "\"" filename "\" does not exist, create it? ")))
801               (let ((file-buffer (create-file-buffer filename)))
802                 (save-excursion
803                   (set-buffer file-buffer)
804                   (rmail-insert-rmail-file-header)
805                   (let ((require-final-newline nil))
806                     (gnus-write-buffer-as-coding-system
807                      nnheader-text-coding-system filename)))
808                 (kill-buffer file-buffer))
809             (error "Output file does not exist")))
810       (set-buffer tmpbuf)
811       (erase-buffer)
812       (insert-buffer-substring artbuf)
813       (gnus-convert-article-to-rmail)
814       ;; Decide whether to append to a file or to an Emacs buffer.
815       (let ((outbuf (get-file-buffer filename)))
816         (if (not outbuf)
817             (let ((file-name-coding-system nnmail-pathname-coding-system)
818                   (pathname-coding-system nnmail-pathname-coding-system))
819               (write-region-as-binary (point-min) (point-max)
820                                       filename 'append))
821           ;; File has been visited, in buffer OUTBUF.
822           (set-buffer outbuf)
823           (let ((buffer-read-only nil)
824                 (msg (and (boundp 'rmail-current-message)
825                           (symbol-value 'rmail-current-message))))
826             ;; If MSG is non-nil, buffer is in RMAIL mode.
827             (when msg
828               (widen)
829               (narrow-to-region (point-max) (point-max)))
830             (insert-buffer-substring tmpbuf)
831             (when msg
832               (goto-char (point-min))
833               (widen)
834               (search-backward "\n\^_")
835               (narrow-to-region (point) (point-max))
836               (rmail-count-new-messages t)
837               (when (rmail-summary-exists)
838                 (rmail-select-summary
839                  (rmail-update-summary)))
840               (rmail-count-new-messages t)
841               (rmail-show-message msg))
842             (save-buffer)))))
843     (kill-buffer tmpbuf)))
844
845 (defun gnus-output-to-mail (filename &optional ask)
846   "Append the current article to a mail file named FILENAME."
847   (setq filename (expand-file-name filename))
848   (let ((artbuf (current-buffer))
849         (tmpbuf (get-buffer-create " *Gnus-output*")))
850     (save-excursion
851       ;; Create the file, if it doesn't exist.
852       (when (and (not (get-file-buffer filename))
853                  (not (file-exists-p filename)))
854         (if (or (not ask)
855                 (gnus-y-or-n-p
856                  (concat "\"" filename "\" does not exist, create it? ")))
857             (let ((file-buffer (create-file-buffer filename)))
858               (save-excursion
859                 (set-buffer file-buffer)
860                 (let ((require-final-newline nil))
861                   (gnus-write-buffer-as-coding-system
862                    nnheader-text-coding-system filename)))
863               (kill-buffer file-buffer))
864           (error "Output file does not exist")))
865       (set-buffer tmpbuf)
866       (erase-buffer)
867       (insert-buffer-substring artbuf)
868       (goto-char (point-min))
869       (if (looking-at "From ")
870           (forward-line 1)
871         (insert "From nobody " (current-time-string) "\n"))
872       (let (case-fold-search)
873         (while (re-search-forward "^From " nil t)
874           (beginning-of-line)
875           (insert ">")))
876       ;; Decide whether to append to a file or to an Emacs buffer.
877       (let ((outbuf (get-file-buffer filename)))
878         (if (not outbuf)
879             (let ((buffer-read-only nil))
880               (save-excursion
881                 (goto-char (point-max))
882                 (forward-char -2)
883                 (unless (looking-at "\n\n")
884                   (goto-char (point-max))
885                   (unless (bolp)
886                     (insert "\n"))
887                   (insert "\n"))
888                 (goto-char (point-max))
889                 (let ((file-name-coding-system nnmail-pathname-coding-system)
890                       (pathname-coding-system nnmail-pathname-coding-system))
891                   (write-region-as-binary (point-min) (point-max)
892                                           filename 'append))))
893           ;; File has been visited, in buffer OUTBUF.
894           (set-buffer outbuf)
895           (let ((buffer-read-only nil))
896             (goto-char (point-max))
897             (unless (eobp)
898               (insert "\n"))
899             (insert "\n")
900             (insert-buffer-substring tmpbuf)))))
901     (kill-buffer tmpbuf)))
902
903 (defun gnus-convert-article-to-rmail ()
904   "Convert article in current buffer to Rmail message format."
905   (let ((buffer-read-only nil))
906     ;; Convert article directly into Babyl format.
907     (goto-char (point-min))
908     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
909     (while (search-forward "\n\^_" nil t) ;single char
910       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
911     (goto-char (point-max))
912     (insert "\^_")))
913
914 (defun gnus-map-function (funs arg)
915   "Applies the result of the first function in FUNS to the second, and so on.
916 ARG is passed to the first function."
917   (let ((myfuns funs))
918     (while myfuns
919       (setq arg (funcall (pop myfuns) arg)))
920     arg))
921
922 (defun gnus-run-hooks (&rest funcs)
923   "Does the same as `run-hooks', but saves excursion."
924   (let ((buf (current-buffer)))
925     (unwind-protect
926         (apply 'run-hooks funcs)
927       (set-buffer buf))))
928
929 ;;;
930 ;;; .netrc and .authinforc parsing
931 ;;;
932
933 (defun gnus-parse-netrc (file)
934   "Parse FILE and return an list of all entries in the file."
935   (when (file-exists-p file)
936     (with-temp-buffer
937       (let ((tokens '("machine" "default" "login"
938                       "password" "account" "macdef" "force"
939                       "port"))
940             alist elem result pair)
941         (insert-file-contents file)
942         (goto-char (point-min))
943         ;; Go through the file, line by line.
944         (while (not (eobp))
945           (narrow-to-region (point) (gnus-point-at-eol))
946           ;; For each line, get the tokens and values.
947           (while (not (eobp))
948             (skip-chars-forward "\t ")
949             ;; Skip lines that begin with a "#".
950             (if (eq (char-after) ?#)
951                 (goto-char (point-max))
952               (unless (eobp)
953                 (setq elem
954                       (if (= (following-char) ?\")
955                           (read (current-buffer))
956                         (buffer-substring
957                          (point) (progn (skip-chars-forward "^\t ")
958                                         (point)))))
959                 (cond
960                  ((equal elem "macdef")
961                   ;; We skip past the macro definition.
962                   (widen)
963                   (while (and (zerop (forward-line 1))
964                               (looking-at "$")))
965                   (narrow-to-region (point) (point)))
966                  ((member elem tokens)
967                   ;; Tokens that don't have a following value are ignored,
968                   ;; except "default".
969                   (when (and pair (or (cdr pair)
970                                       (equal (car pair) "default")))
971                     (push pair alist))
972                   (setq pair (list elem)))
973                  (t
974                   ;; Values that haven't got a preceding token are ignored.
975                   (when pair
976                     (setcdr pair elem)
977                     (push pair alist)
978                     (setq pair nil)))))))
979           (when alist
980             (push (nreverse alist) result))
981           (setq alist nil
982                 pair nil)
983           (widen)
984           (forward-line 1))
985         (nreverse result)))))
986
987 (defun gnus-netrc-machine (list machine &optional port defaultport)
988   "Return the netrc values from LIST for MACHINE or for the default entry.
989 If PORT specified, only return entries with matching port tokens.
990 Entries without port tokens default to DEFAULTPORT."
991   (let ((rest list)
992         result)
993     (while list
994       (when (equal (cdr (assoc "machine" (car list))) machine)
995         (push (car list) result))
996       (pop list))
997     (unless result
998       ;; No machine name matches, so we look for default entries.
999       (while rest
1000         (when (assoc "default" (car rest))
1001           (push (car rest) result))
1002         (pop rest)))
1003     (when result
1004       (setq result (nreverse result))
1005       (while (and result
1006                   (not (equal (or port defaultport "nntp")
1007                               (or (gnus-netrc-get (car result) "port")
1008                                   defaultport "nntp"))))
1009         (pop result))
1010       (car result))))
1011
1012 (defun gnus-netrc-get (alist type)
1013   "Return the value of token TYPE from ALIST."
1014   (cdr (assoc type alist)))
1015
1016 ;;; Various
1017
1018 (defvar gnus-group-buffer)              ; Compiler directive
1019 (defun gnus-alive-p ()
1020   "Say whether Gnus is running or not."
1021   (and (boundp 'gnus-group-buffer)
1022        (get-buffer gnus-group-buffer)
1023        (save-excursion
1024          (set-buffer gnus-group-buffer)
1025          (eq major-mode 'gnus-group-mode))))
1026
1027 (defun gnus-remove-duplicates (list)
1028   (let (new (tail list))
1029     (while tail
1030       (or (member (car tail) new)
1031           (setq new (cons (car tail) new)))
1032       (setq tail (cdr tail)))
1033     (nreverse new)))
1034
1035 (defun gnus-delete-if (predicate list)
1036   "Delete elements from LIST that satisfy PREDICATE."
1037   (let (out)
1038     (while list
1039       (unless (funcall predicate (car list))
1040         (push (car list) out))
1041       (pop list))
1042     (nreverse out)))
1043
1044 (if (fboundp 'assq-delete-all)
1045     (defalias 'gnus-delete-alist 'assq-delete-all)
1046   (defun gnus-delete-alist (key alist)
1047     "Delete from ALIST all elements whose car is KEY.
1048 Return the modified alist."
1049     (let (entry)
1050       (while (setq entry (assq key alist))
1051         (setq alist (delq entry alist)))
1052       alist)))
1053
1054 (defmacro gnus-pull (key alist &optional assoc-p)
1055   "Modify ALIST to be without KEY."
1056   (unless (symbolp alist)
1057     (error "Not a symbol: %s" alist))
1058   (let ((fun (if assoc-p 'assoc 'assq)))
1059     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1060
1061 (defun gnus-globalify-regexp (re)
1062   "Returns a regexp that matches a whole line, iff RE matches a part of it."
1063   (concat (unless (string-match "^\\^" re) "^.*")
1064           re
1065           (unless (string-match "\\$$" re) ".*$")))
1066
1067 (defun gnus-set-window-start (&optional point)
1068   "Set the window start to POINT, or (point) if nil."
1069   (let ((win (get-buffer-window (current-buffer) t)))
1070     (when win
1071       (set-window-start win (or point (point))))))
1072
1073 (defun gnus-annotation-in-region-p (b e)
1074   (if (= b e)
1075       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1076     (text-property-any b e 'gnus-undeletable t)))
1077
1078 (defun gnus-or (&rest elems)
1079   "Return non-nil if any of the elements are non-nil."
1080   (catch 'found
1081     (while elems
1082       (when (pop elems)
1083         (throw 'found t)))))
1084
1085 (defun gnus-and (&rest elems)
1086   "Return non-nil if all of the elements are non-nil."
1087   (catch 'found
1088     (while elems
1089       (unless (pop elems)
1090         (throw 'found nil)))
1091     t))
1092
1093 (defun gnus-write-active-file (file hashtb &optional full-names)
1094   (let ((output-coding-system nnmail-active-file-coding-system)
1095         (coding-system-for-write nnmail-active-file-coding-system))
1096     (with-temp-file file
1097       (mapatoms
1098        (lambda (sym)
1099          (when (and sym
1100                     (boundp sym)
1101                     (symbol-value sym))
1102            (insert (format "%S %d %d y\n"
1103                            (if full-names
1104                                sym
1105                              (intern (gnus-group-real-name (symbol-name sym))))
1106                            (or (cdr (symbol-value sym))
1107                                (car (symbol-value sym)))
1108                            (car (symbol-value sym))))))
1109        hashtb)
1110       (goto-char (point-max))
1111       (while (search-backward "\\." nil t)
1112         (delete-char 1)))))
1113
1114 (if (fboundp 'union)
1115     (defalias 'gnus-union 'union)
1116   (defun gnus-union (l1 l2)
1117     "Set union of lists L1 and L2."
1118     (cond ((null l1) l2)
1119           ((null l2) l1)
1120           ((equal l1 l2) l1)
1121           (t
1122            (or (>= (length l1) (length l2))
1123                (setq l1 (prog1 l2 (setq l2 l1))))
1124            (while l2
1125              (or (member (car l2) l1)
1126                  (push (car l2) l1))
1127              (pop l2))
1128            l1))))
1129
1130 (defun gnus-add-text-properties-when
1131   (property value start end properties &optional object)
1132   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1133   (let (point)
1134     (while (and start
1135                 (< start end) ;; XEmacs will loop for every when start=end.
1136                 (setq point (text-property-not-all start end property value)))
1137       (gnus-add-text-properties start point properties object)
1138       (setq start (text-property-any point end property value)))
1139     (if start
1140         (gnus-add-text-properties start end properties object))))
1141
1142 (defun gnus-remove-text-properties-when
1143   (property value start end properties &optional object)
1144   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1145   (let (point)
1146     (while (and start
1147                 (< start end)
1148                 (setq point (text-property-not-all start end property value)))
1149       (remove-text-properties start point properties object)
1150       (setq start (text-property-any point end property value)))
1151     (if start
1152         (remove-text-properties start end properties object))
1153     t))
1154
1155 (defun gnus-string-equal (x y)
1156   "Like `string-equal', except it compares case-insensitively."
1157   (and (= (length x) (length y))
1158        (or (string-equal x y)
1159            (string-equal (downcase x) (downcase y)))))
1160
1161 (defcustom gnus-use-byte-compile t
1162   "If non-nil, byte-compile crucial run-time codes."
1163   :type 'boolean
1164   :version "21.1"
1165   :group 'gnus-various)
1166
1167 (defun gnus-byte-compile (form)
1168   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1169   (if gnus-use-byte-compile
1170       (progn
1171         (require 'bytecomp)
1172         (defalias 'gnus-byte-compile 'byte-compile)
1173         (byte-compile form))
1174     form))
1175
1176 (defun gnus-remassoc (key alist)
1177   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1178 The modified LIST is returned.  If the first member
1179 of LIST has a car that is `equal' to KEY, there is no way to remove it
1180 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1181 sure of changing the value of `foo'."
1182   (when alist
1183     (if (equal key (caar alist))
1184         (cdr alist)
1185       (setcdr alist (gnus-remassoc key (cdr alist)))
1186       alist)))
1187
1188 (defun gnus-update-alist-soft (key value alist)
1189   (if value
1190       (cons (cons key value) (gnus-remassoc key alist))
1191     (gnus-remassoc key alist)))
1192
1193 (defun gnus-create-info-command (node)
1194   "Create a command that will go to info NODE."
1195   `(lambda ()
1196      (interactive)
1197      ,(concat "Enter the info system at node " node)
1198      (Info-goto-node ,node)
1199      (setq gnus-info-buffer (current-buffer))
1200      (gnus-configure-windows 'info)))
1201
1202 (defun gnus-not-ignore (&rest args)
1203   t)
1204
1205 (defvar gnus-directory-sep-char-regexp "/"
1206   "The regexp of directory separator character.
1207 If you find some problem with the directory separator character, try
1208 \"[/\\\\\]\" for some systems.")
1209
1210 (provide 'gnus-util)
1211
1212 ;;; gnus-util.el ends here