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