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