;; -*- emacs-lisp -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; $Id: gnus.el,v 1.19 2005/08/02 19:19:10 ole Exp $
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Gnus setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(require 'gnus)

;; set files
(eval-after-load "gnus"
  '(progn
     (setq gnus-init-file (expand-file-name ".gnus" gnus-directory))
     (require 'spam)
     (require 'message-x)
     (require 'mailcrypt)
     (load-library "spook")
     ))

(setq gnus-directory (expand-file-name "~/News/"))

(defun switch-to-gnus ()
  (interactive)
  (if (or (not (fboundp 'gnus-alive-p))
	  (not (gnus-alive-p)))
      (gnus)
    ;; gnus is running
    (let (candidate priority in-gnus (tests '(("\\*Group" . 3))))
      ;; move down in priorities if we're already at a high priority
      (when (not (member mode-name '("Message" "Summary")))
	(setq tests (cons '("^\\*\\(mail\\|\\(wide \\)?reply\\)" . 1)
			  tests)))
      (when (not (string= mode-name "Summary"))
	(setq tests (cons '("\\*Summary" . 2) tests)))
      ;; if we're not in a gnus buffer, just switch to our gnus screen, thus
      ;; returning us to where we were previously. otherwise determine what we
      ;; should switch to
      (dolist (buf (buffer-list))
	(dolist (test tests)
	  (when (and (string-match (car test) (buffer-name buf))
		     (or (not priority) (< (cdr test) priority))
		     (> (buffer-size buf) 0))
	    (setq candidate buf
	    priority (cdr test)))))
      (if (buffer-live-p candidate)
	  (if (eq candidate (current-buffer))
	      (gnus-group-get-new-news)
	    (switch-to-buffer candidate))
	(error "unlive buffer!")))))
    
;; quit gnus properly instead of leaving auto-save files around
(defadvice save-buffers-kill-emacs (before quit-gnus (&rest args) activate)
  (let (buf)
    (when (and (fboundp 'gnus-alive-p)
	       (gnus-alive-p)
	       (bufferp (setq buf (get-buffer "*Group*"))))
      (with-current-buffer buf
	(gnus-group-exit)))))
    
;; i'm in the habit of quitting when i don't really need to
(add-hook 'gnus-group-mode-hook
	  (lambda ()
	    (local-set-key (kbd "q") 'gnus-group-suspend)
	    (local-set-key (kbd "Q") 'gnus-group-exit)))

(define-key goto-keymap [?g] 'switch-to-gnus)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dired support
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'gnus-dired)
(add-hook 'dired-mode-hook 'turn-on-gnus-dired-mode)

