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