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