Sync up with Pterodactyl Gnus 0.40.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996,97,98 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    ((not (listp funs)) funs)
488    ((null funs) funs)
489    ((cdr funs)
490     `(lambda (t1 t2)
491        ,(gnus-make-sort-function-1 (reverse funs))))
492    (t
493     (car funs))))
494
495 (defun gnus-make-sort-function-1 (funs)
496   "Return a composite sort condition based on the functions in FUNC."
497   (if (cdr funs)
498       `(or (,(car funs) t1 t2)
499            (and (not (,(car funs) t2 t1))
500                 ,(gnus-make-sort-function-1 (cdr funs))))
501     `(,(car funs) t1 t2)))
502
503 (defun gnus-turn-off-edit-menu (type)
504   "Turn off edit menu in `gnus-TYPE-mode-map'."
505   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
506     [menu-bar edit] 'undefined))
507
508 (defun gnus-prin1 (form)
509   "Use `prin1' on FORM in the current buffer.
510 Bind `print-quoted' and `print-readably' to t while printing."
511   (let ((print-quoted t)
512         (print-readably t)
513         (print-escape-multibyte nil)
514         print-level print-length)
515     (prin1 form (current-buffer))))
516
517 (defun gnus-prin1-to-string (form)
518   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
519   (let ((print-quoted t)
520         (print-readably t))
521     (prin1-to-string form)))
522
523 (defun gnus-make-directory (directory)
524   "Make DIRECTORY (and all its parents) if it doesn't exist."
525   (when (and directory
526              (not (file-exists-p directory)))
527     (make-directory directory t))
528   t)
529
530 (defun gnus-write-buffer (file)
531   "Write the current buffer's contents to FILE."
532   ;; Make sure the directory exists.
533   (gnus-make-directory (file-name-directory file))
534   ;; Write the buffer.
535   (write-region (point-min) (point-max) file nil 'quietly))
536
537 (defun gnus-delete-file (file)
538   "Delete FILE if it exists."
539   (when (file-exists-p file)
540     (delete-file file)))
541
542 (defun gnus-strip-whitespace (string)
543   "Return STRING stripped of all whitespace."
544   (while (string-match "[\r\n\t ]+" string)
545     (setq string (replace-match "" t t string)))
546   string)
547
548 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
549   "The same as `put-text-property', but don't put this prop on any newlines in the region."
550   (save-match-data
551     (save-excursion
552       (save-restriction
553         (goto-char beg)
554         (while (re-search-forward "[ \t]*\n" end 'move)
555           (gnus-put-text-property beg (match-beginning 0) prop val)
556           (setq beg (point)))
557         (gnus-put-text-property beg (point) prop val)))))
558
559 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
560                                                                    prop val)
561   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
562   (let ((b beg))
563     (while (/= b end)
564       (when (get-text-property b 'gnus-face)
565         (setq b (next-single-property-change b 'gnus-face nil end)))
566       (when (/= b end)
567         (gnus-put-text-property
568          b (setq b (next-single-property-change b 'gnus-face nil end))
569          prop val)))))
570   
571 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
572 ;;; The primary idea here is to try to protect internal datastructures
573 ;;; from becoming corrupted when the user hits C-g, or if a hook or
574 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
575 ;;; updated at the same time, or information can be lost.
576
577 (defvar gnus-atomic-be-safe t
578   "If t, certain operations will be protected from interruption by C-g.")
579
580 (defmacro gnus-atomic-progn (&rest forms)
581   "Evaluate FORMS atomically, which means to protect the evaluation
582 from being interrupted by the user.  An error from the forms themselves
583 will return without finishing the operation.  Since interrupts from
584 the user are disabled, it is recommended that only the most minimal
585 operations are performed by FORMS.  If you wish to assign many
586 complicated values atomically, compute the results into temporary
587 variables and then do only the assignment atomically."
588   `(let ((inhibit-quit gnus-atomic-be-safe))
589      ,@forms))
590
591 (put 'gnus-atomic-progn 'lisp-indent-function 0)
592
593 (defmacro gnus-atomic-progn-assign (protect &rest forms)
594   "Evaluate FORMS, but insure that the variables listed in PROTECT
595 are not changed if anything in FORMS signals an error or otherwise
596 non-locally exits.  The variables listed in PROTECT are updated atomically.
597 It is safe to use gnus-atomic-progn-assign with long computations.
598
599 Note that if any of the symbols in PROTECT were unbound, they will be
600 set to nil on a sucessful assignment.  In case of an error or other
601 non-local exit, it will still be unbound."
602   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
603                                                   (concat (symbol-name x)
604                                                           "-tmp"))
605                                                  x))
606                                protect))
607          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
608                                temp-sym-map))
609          (temp-sym-let (mapcar (lambda (x) (list (car x)
610                                                  `(and (boundp ',(cadr x))
611                                                        ,(cadr x))))
612                                temp-sym-map))
613          (sym-temp-let sym-temp-map)
614          (temp-sym-assign (apply 'append temp-sym-map))
615          (sym-temp-assign (apply 'append sym-temp-map))
616          (result (make-symbol "result-tmp")))
617     `(let (,@temp-sym-let
618            ,result)
619        (let ,sym-temp-let
620          (setq ,result (progn ,@forms))
621          (setq ,@temp-sym-assign))
622        (let ((inhibit-quit gnus-atomic-be-safe))
623          (setq ,@sym-temp-assign))
624        ,result)))
625
626 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
627 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
628
629 (defmacro gnus-atomic-setq (&rest pairs)
630   "Similar to setq, except that the real symbols are only assigned when
631 there are no errors.  And when the real symbols are assigned, they are
632 done so atomically.  If other variables might be changed via side-effect,
633 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
634 with potentially long computations."
635   (let ((tpairs pairs)
636         syms)
637     (while tpairs
638       (push (car tpairs) syms)
639       (setq tpairs (cddr tpairs)))
640     `(gnus-atomic-progn-assign ,syms
641        (setq ,@pairs))))
642
643 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
644
645
646 ;;; Functions for saving to babyl/mail files.
647
648 (defvar rmail-default-rmail-file)
649 (defun gnus-output-to-rmail (filename &optional ask)
650   "Append the current article to an Rmail file named FILENAME."
651   (require 'rmail)
652   ;; Most of these codes are borrowed from rmailout.el.
653   (setq filename (expand-file-name filename))
654   (setq rmail-default-rmail-file filename)
655   (let ((artbuf (current-buffer))
656         (tmpbuf (get-buffer-create " *Gnus-output*")))
657     (save-excursion
658       (or (get-file-buffer filename)
659           (file-exists-p filename)
660           (if (or (not ask)
661                   (gnus-yes-or-no-p
662                    (concat "\"" filename "\" does not exist, create it? ")))
663               (let ((file-buffer (create-file-buffer filename)))
664                 (save-excursion
665                   (set-buffer file-buffer)
666                   (rmail-insert-rmail-file-header)
667                   (let ((require-final-newline nil))
668                     (gnus-write-buffer filename)))
669                 (kill-buffer file-buffer))
670             (error "Output file does not exist")))
671       (set-buffer tmpbuf)
672       (erase-buffer)
673       (insert-buffer-substring artbuf)
674       (gnus-convert-article-to-rmail)
675       ;; Decide whether to append to a file or to an Emacs buffer.
676       (let ((outbuf (get-file-buffer filename)))
677         (if (not outbuf)
678             (append-to-file (point-min) (point-max) filename)
679           ;; File has been visited, in buffer OUTBUF.
680           (set-buffer outbuf)
681           (let ((buffer-read-only nil)
682                 (msg (and (boundp 'rmail-current-message)
683                           (symbol-value 'rmail-current-message))))
684             ;; If MSG is non-nil, buffer is in RMAIL mode.
685             (when msg
686               (widen)
687               (narrow-to-region (point-max) (point-max)))
688             (insert-buffer-substring tmpbuf)
689             (when msg
690               (goto-char (point-min))
691               (widen)
692               (search-backward "\n\^_")
693               (narrow-to-region (point) (point-max))
694               (rmail-count-new-messages t)
695               (when (rmail-summary-exists)
696                 (rmail-select-summary
697                  (rmail-update-summary)))
698               (rmail-count-new-messages t)
699               (rmail-show-message msg))
700             (save-buffer)))))
701     (kill-buffer tmpbuf)))
702
703 (defun gnus-output-to-mail (filename &optional ask)
704   "Append the current article to a mail file named FILENAME."
705   (setq filename (expand-file-name filename))
706   (let ((artbuf (current-buffer))
707         (tmpbuf (get-buffer-create " *Gnus-output*")))
708     (save-excursion
709       ;; Create the file, if it doesn't exist.
710       (when (and (not (get-file-buffer filename))
711                  (not (file-exists-p filename)))
712         (if (or (not ask)
713                 (gnus-y-or-n-p
714                  (concat "\"" filename "\" does not exist, create it? ")))
715             (let ((file-buffer (create-file-buffer filename)))
716               (save-excursion
717                 (set-buffer file-buffer)
718                 (let ((require-final-newline nil)
719                       (coding-system-for-write 'binary))
720                   (gnus-write-buffer filename)))
721               (kill-buffer file-buffer))
722           (error "Output file does not exist")))
723       (set-buffer tmpbuf)
724       (erase-buffer)
725       (insert-buffer-substring artbuf)
726       (goto-char (point-min))
727       (if (looking-at "From ")
728           (forward-line 1)
729         (insert "From nobody " (current-time-string) "\n"))
730       (let (case-fold-search)
731         (while (re-search-forward "^From " nil t)
732           (beginning-of-line)
733           (insert ">")))
734       ;; Decide whether to append to a file or to an Emacs buffer.
735       (let ((outbuf (get-file-buffer filename)))
736         (if (not outbuf)
737             (let ((buffer-read-only nil)
738                   (coding-system-for-write 'binary))
739               (save-excursion
740                 (goto-char (point-max))
741                 (forward-char -2)
742                 (unless (looking-at "\n\n")
743                   (goto-char (point-max))
744                   (unless (bolp)
745                     (insert "\n"))
746                   (insert "\n"))
747                 (goto-char (point-max))
748                 (append-to-file (point-min) (point-max) filename)))
749           ;; File has been visited, in buffer OUTBUF.
750           (set-buffer outbuf)
751           (let ((buffer-read-only nil))
752             (goto-char (point-max))
753             (unless (eobp)
754               (insert "\n"))
755             (insert "\n")
756             (insert-buffer-substring tmpbuf)))))
757     (kill-buffer tmpbuf)))
758
759 (defun gnus-convert-article-to-rmail ()
760   "Convert article in current buffer to Rmail message format."
761   (let ((buffer-read-only nil))
762     ;; Convert article directly into Babyl format.
763     (goto-char (point-min))
764     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
765     (while (search-forward "\n\^_" nil t) ;single char
766       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
767     (goto-char (point-max))
768     (insert "\^_")))
769
770 (defun gnus-map-function (funs arg)
771   "Applies the result of the first function in FUNS to the second, and so on.
772 ARG is passed to the first function."
773   (let ((myfuns funs))
774     (while myfuns
775       (setq arg (funcall (pop myfuns) arg)))
776     arg))
777
778 (defun gnus-run-hooks (&rest funcs)
779   "Does the same as `run-hooks', but saves excursion."
780   (let ((buf (current-buffer)))
781     (unwind-protect
782         (apply 'run-hooks funcs)
783       (set-buffer buf))))
784   
785 ;;;
786 ;;; .netrc and .authinforc parsing
787 ;;;
788
789 (defvar gnus-netrc-syntax-table
790   (let ((table (copy-syntax-table text-mode-syntax-table)))
791     (modify-syntax-entry ?@ "w" table)
792     (modify-syntax-entry ?- "w" table)
793     (modify-syntax-entry ?_ "w" table)
794     (modify-syntax-entry ?! "w" table)
795     (modify-syntax-entry ?. "w" table)
796     (modify-syntax-entry ?, "w" table)
797     (modify-syntax-entry ?: "w" table)
798     (modify-syntax-entry ?\; "w" table)
799     (modify-syntax-entry ?% "w" table)
800     (modify-syntax-entry ?) "w" table)
801     (modify-syntax-entry ?( "w" table)
802     table)
803   "Syntax table when parsing .netrc files.")
804
805 (defun gnus-parse-netrc (file)
806   "Parse FILE and return an list of all entries in the file."
807   (if (not (file-exists-p file))
808       ()
809     (save-excursion
810       (let ((tokens '("machine" "default" "login"
811                       "password" "account" "macdef" "force"))
812             alist elem result pair)
813         (nnheader-set-temp-buffer " *netrc*")
814         (unwind-protect
815             (progn
816               (set-syntax-table gnus-netrc-syntax-table)
817               (insert-file-contents file)
818               (goto-char (point-min))
819               ;; Go through the file, line by line.
820               (while (not (eobp))
821                 (narrow-to-region (point) (gnus-point-at-eol))
822                 ;; For each line, get the tokens and values.
823                 (while (not (eobp))
824                   (skip-chars-forward "\t ")
825                   (unless (eobp)
826                     (setq elem (buffer-substring
827                                 (point) (progn (forward-sexp 1) (point))))
828                     (cond
829                      ((equal elem "macdef")
830                       ;; We skip past the macro definition.
831                       (widen)
832                       (while (and (zerop (forward-line 1))
833                                   (looking-at "$")))
834                       (narrow-to-region (point) (point)))
835                      ((member elem tokens)
836                       ;; Tokens that don't have a following value are ignored,
837                       ;; except "default".
838                       (when (and pair (or (cdr pair)
839                                           (equal (car pair) "default")))
840                         (push pair alist))
841                       (setq pair (list elem)))
842                      (t
843                       ;; Values that haven't got a preceding token are ignored.
844                       (when pair
845                         (setcdr pair elem)
846                         (push pair alist)
847                         (setq pair nil))))))
848                 (if alist
849                     (push (nreverse alist) result))
850                 (setq alist nil
851                       pair nil)
852                 (widen)
853                 (forward-line 1))
854               (nreverse result))
855           (kill-buffer " *netrc*"))))))
856
857 (defun gnus-netrc-machine (list machine)
858   "Return the netrc values from LIST for MACHINE or for the default entry."
859   (let ((rest list))
860     (while (and list
861                 (not (equal (cdr (assoc "machine" (car list))) machine)))
862       (pop list))
863     (car (or list
864              (progn (while (and rest (not (assoc "default" (car rest))))
865                       (pop rest))
866                     rest)))))
867
868 (defun gnus-netrc-get (alist type)
869   "Return the value of token TYPE from ALIST."
870   (cdr (assoc type alist)))
871
872 ;;; Various
873
874 (defvar gnus-group-buffer) ; Compiler directive
875 (defun gnus-alive-p ()
876   "Say whether Gnus is running or not."
877   (and (boundp 'gnus-group-buffer)
878        (get-buffer gnus-group-buffer)
879        (save-excursion
880          (set-buffer gnus-group-buffer)
881          (eq major-mode 'gnus-group-mode))))
882
883 (defun gnus-remove-duplicates (list)
884   (let (new (tail list))
885     (while tail
886       (or (member (car tail) new)
887           (setq new (cons (car tail) new)))
888       (setq tail (cdr tail)))
889     (nreverse new)))
890
891 (defun gnus-delete-if (predicate list)
892   "Delete elements from LIST that satisfy PREDICATE."
893   (let (out)
894     (while list
895       (unless (funcall predicate (car list))
896         (push (car list) out))
897       (pop list))
898     (nreverse out)))
899
900 (defun gnus-delete-alist (key alist)
901   "Delete all entries in ALIST that have a key eq to KEY."
902   (let (entry)
903     (while (setq entry (assq key alist))
904       (setq alist (delq entry alist)))
905     alist))
906
907 (defmacro gnus-pull (key alist)
908   "Modify ALIST to be without KEY."
909   (unless (symbolp alist)
910     (error "Not a symbol: %s" alist))
911   `(setq ,alist (delq (assq ,key ,alist) ,alist)))
912
913 (defun gnus-globalify-regexp (re)
914   "Returns a regexp that matches a whole line, iff RE matches a part of it."
915   (concat (unless (string-match "^\\^" re) "^.*")
916           re
917           (unless (string-match "\\$$" re) ".*$")))
918
919 (defun gnus-set-window-start (&optional point)
920   "Set the window start to POINT, or (point) if nil."
921   (let ((win (get-buffer-window (current-buffer) t)))
922     (when win
923       (set-window-start win (or point (point))))))
924
925 (provide 'gnus-util)
926
927 ;;; gnus-util.el ends here