;; -*- Mode: Emacs-Lisp -*-
;; ===================================================================
;;                      Tell Gnus, where to live
;; ===================================================================
;; MOVED: this must live in .emacs/init.el because this file gets read
;; too late!
;(setq gnus-directory (expand-file-name "~/contact/gnus/"))
;(setq message-directory (expand-file-name "~/contact/gnus/"))
;; the following are derived from message-directory
;(setq nnfolder-directory "~/contact/gnus")
;(setq nnml-directory "~/contact/gnus")
;(setq gnus-article-save-directory "~/contact/News/")

;; ===================================================================
;;                             Start/End
;; ===================================================================

(add-hook 'gnus-startup-hook
          ;; Get Toolbar back
          '(lambda () 
;         (when (featurep 'toolbar)
;            (set-specifier default-toolbar-visible-p t))
             (bbdb-insinuate-gnus)
             ))

(add-hook 'gnus-exit-gnus-hook
          '(lambda () 
;         (when (featurep 'toolbar)
;         (set-specifier default-toolbar-visible-p nil)))
             (condition-case nil
                 (progn
                   (bbdb-save-db)
                   (kill-buffer (get-buffer "bbdb"))
                   (kill-buffer (get-buffer "*BBDB*"))
                   (bbdb-bury-buffer))
               (error nil))
          ))


;; ===================================================================
;;                         Receiving News/Mails
;; ===================================================================
;; Newsserver
;; where to get news from
(setq gnus-select-method '(nnml ""))

(add-hook 'nntp-server-opened-hook 'nntp-send-authinfo)
;; init mail
;(setq nnimap-debug t)
(require 'nnimap)
(setq gnus-secondary-select-methods
      '(
        (nntp "news.friendlynewsprovider.example")
        (nnimap "local-mailserver"
                ;; somehow these settings don't show up?
                (nnimap-address "local-mailserver")
                (nnimap-authinfo-file "~/.imap-a-separate-account")
                ;; hopefully these do...
                (nnimap-list-pattern ("INBOX.*"))
                (nnimap-expunge-on-close never)
         )))


;; IMAP as POP++
(eval-after-load "mail-source"
  '(setq mail-sources
         '(
           (imap
            :server "local-mailserver"
            :user "my-user-name"
            :password "my-password"
;;            :fetchflag "\\Seen" ;; don't delete
            ))))


;; Indexed By swish-e
;; see http://www.emacswiki.org/cgi-bin/wiki/IndexMail
(require 'nnir)
(setq nnir-search-engine 'swish-e)
(setq nnir-swish-e-index-file "~/contact/gnus/index.swish")

;; I know what groups to subscribe, no need to tell me
(setq gnus-read-active-file nil)
;; could set this to 'ask-server, too
(setq gnus-check-new-newsgroups nil)
;; actually I don't need this anymore, but then....
;;(setq gnus-subscribe-newsgroup-method 'gnus-subscribe-hierarchically)
(setq gnus-subscribe-newsgroup-method 'gnus-subscribe-topics)
(setq gnus-save-killed-list nil)
(setq mail-user-agent 'gnus-user-agent)

;; I want no expiration
(setq gnus-agent-enable-expiration 'DISABLE)

;; There is no news other than Gnus
(setq gnus-save-newsrc-file nil)
(setq gnus-read-newsrc-file nil)

;; Broadband connection...
(setq gnus-large-newsgroup 1000)

;; RSS feeds should not use url.el
(setq mm-url-use-external t)

;; ===================================================================
;;                          Group-Buffer
;; ===================================================================
(add-hook 'gnus-group-mode-hook
          ;; Sorting Groups
          '(lambda () 
             (gnus-topic-mode)
             ))


(setq gnus-group-sort-function 'gnus-group-sort-by-alphabet)

;; this should subscribe new mail-"groups" every time I hit 'g'
;; doesn't work, though
(setq gnus-parameters
      '(("^nnml.*"
         (gnus-show-threads nil)
         (gnus-check-new-newsgroups . 'always))
        ("^nnimap.*"
         (gnus-show-threads nil)
         (gnus-message-archive-group "nnimap+local-mailserver:Gesendete Objekte")
         (nnimap-expunge-on-close never))
        ))

(setq gnus-auto-select-next nil)
;(setq gnus-group-line-format
;      "%M%S%p%5y: %(%~(pad-right 60)g%) Last read on %6,6~(cut 2)d\n")

;; ===================================================================
;;                        Mail Splitting
;; ===================================================================
(setq nnmail-split-methods 'nnmail-split-fancy)
;; not only one group in splitting (t), but I use '&' in the list
(setq nnmail-crosspost t)
;; handling of word boundaries around mail adresses
(setq nnmail-split-fancy-match-partial-words nil)
;; take care of SKamphausen@... and skamphausen@...
(setq nnmail-split-lowercase-expanded t)
(setq nnmail-split-fancy
      '(&
        ;; LOADs of filtering rules, just show some excerpts
        (from "agoodfriend@example\\.example" "mail.private.thegoodfriend")
        ("subject" ".*ebay.*" "mail.private.ebay")
        (to ".*@skamphausen\\.de" "mail.private.misc")
        (to ".* <\\(.+\\)@skamphausen.de" "mail.private.\\1")
        (from ".* <?\\(.+\\)@\\(paco.\\)?\\(local.\\)?myworkdomain.example.*" "mail.business.\\1")
        (from ".*noreply@freshmeat.net.*" "mail.www.freshmeat")
        "mail.inbox"
        ))


;; ===================================================================
;;                        Rading Articles
;; ===================================================================
(add-hook 'gnus-article-mode-hook
          '(lambda ()
             (ska-article-keys))
          )

;;
;; Firefox Konfiguration
;;
;;  (defun browse-url-firefox-new-tab (url &optional new-window) "Open URL in a new tab in Firefox."
;;    (interactive (browse-url-interactive-arg "URL: ")) (unless
;;      (string= "" (shell-command-to-string (concat "firefox -remote 'openURL(" url ",new-tab)'")))
;;      (message "Starting Firefox...")
;;      (start-process (concat "firefox " url) nil "/bin/sh" "-c" (concat "firefox " url " || true"))
;;      (message "Starting Firefox...done")))
;;  (setq browse-url-browser-function 'browse-url-firefox-new-tab browse-url-netscape-program "firefox")

;; ===================================================================
;;                        Writing Articles
;; ===================================================================

(add-hook 'message-mode-hook
          '(lambda ()
             (ska-message-keys)))

;; ask when replying by mail to news:
(setq gnus-confirm-mail-reply-to-news t)

;; local saving of messages
(setq gnus-message-archive-group t)
;; create one mail archive per month
(setq gnus-message-archive-group
      '((if (message-news-p)
            "nnml:saved-news"
          (concat "nnml:mail." (format-time-string "%Y-%m")))))
(setq gnus-gcc-mark-as-read t)

;; leave threads intact
(setq gnus-fetch-old-headers 'some)

;; for creating message IDs
(setq message-user-fqdn "usenet.my.skamphausen.de")
;(setq message-user-fqdn "mailman.local.businessdomain.example")

;; those nice boxes with info nodes in them :-)
(autoload 'rs-info-insert-current-node "rs-info"
  "Insert reference to current Info node using STYPE in buffer." t nil)
(autoload 'rs-info-boxquote "rs-info"
  "Yank text (from an info node), box it and use current info node as title."
  t nil)
(autoload 'rs-info-reload "rs-info" "Reload current info node." t nil)
(autoload 'rs-info-insert-node-for-variable "rs-info"
  "Insert a custom style info node for the top level form at point." t nil)
(defalias 'boxquote-info 'rs-info-boxquote)



;; ===================================================================
;;                            Identities
;; ===================================================================
;;
;; whitelist solution from
;;
;; http://groups-beta.google.com/group/de.comm.software.gnus/msg/b817d12c43b9bc61
;; I don't add my default addres here, because that's written below
;; and can only get mangled by stupid outlookers to SKamphausen@...
(setq ska-mail-addresses
      (list "skampi@gmx.de"
            "skampi@gmx.net"
            ;; more mail addresses here...
            ))

(defun ska-message-get-from-address ()
  (save-excursion
    (if (and (boundp 'gnus-article-buffer)
               (gnus-buffer-live-p gnus-article-buffer))
        (progn
          (set-buffer gnus-article-buffer)
          ;; fixme: this doesn't work when I'm cc'ed
          (let ((address (message-fetch-field "to")))
            (if (and address
                     (string-match (regexp-opt ska-mail-addresses)
                                   address))
                (let ((matched-address (match-string 0 address)))
                  (cond
                   (t
                    (concat "Stefan Kamphausen <" matched-address ">"))))
              "Stefan Kamphausen <skamphausen@myworkdomain.example>")))
      "Stefan Kamphausen <skamphausen@myworkdomain.example>")))

(setq gnus-posting-styles
      '((".*"  ;;default
         (name "Stefan Kamphausen")
         (organization "My Employer")
         (signature-file "~/.signature")
         (address "skamphausen@myworkdomain.example")
         ;; for debugging:(eval (message "NEWS %s" (message-news-p)))
         )
        ((message-news-p)  ;;Usenet news?
         (organization "")
         (signature-file "~/.signature-priv")
         (address "skampi@gmx.de")
         )
        ("mail\\.private.*"
         (organization "")
         (address "my-main-private-address")
         (signature-file "~/.signature-priv")
         )
        ("nnimap\\+local-mailserver.*"
         (name "A Team Identity")
         (organization "My Employer")
         (address "team-adress@myworkdomain.example")
         )
        ("nnml:.*" ;; dynamically detect address using functions above
         (From (ska-message-get-from-address))
         )
        ))


;; ===================================================================
;;                            Cryptography
;; ===================================================================
(require 'pgg)
(setq mml2015-use 'pgg)
(setq pgg-scheme 'gpg
      pgg-cache-passphrase t
      pgg-passphrase-cache-expiry 900
      pgg-gpg-user-id "6C9E6D21")

(setq smime-CA-directory "~/.smime/CA/"
;      smime-CA-file "~/.smime/trusted-CAs.pem"
      smime-certificate-directory "~/.smime/certs/"
      smime-keys
      '(("skamphausen@myworkdomain.example" "~/.smime/certs/skamphausen-private-key.pem"))
      )



;; ===================================================================
;;                               BBDB
;; ===================================================================
(bbdb-initialize 'gnus 'message)
;; more stuff is in personal.el

;; ===================================================================
;;                               Daemon
;; ===================================================================
;; demon while idling our time
;(gnus-demon-add-handler 'gnus-group-get-new-news 2 t)
;(gnus-demon-init)

;; ===================================================================
;;                               Display
;; ===================================================================
;; no HTML rendering:
(setq mm-automatic-display (remove "text/html" mm-automatic-display))
(eval-after-load "mm-decode"
  '(progn 
     (add-to-list 'mm-discouraged-alternatives "text/html")
     (add-to-list 'mm-discouraged-alternatives "text/richtext")))

;; always show MIME buttons
(setq gnus-inhibit-mime-unbuttonizing t)

;; Group Buffer
;; ============
;; from http://my.gnus.org/node/39
;;(setq gnus-group-line-format
;; "%1(%1{%4i %}%)%{ %}%2(%2{%7U %}%)%{ %}%3(%3{%7y %}%)%{%* %}%4(%B%-45G%)\n")

;; Summary Buffer
;; ==============
;; I used different formats for a while but, no, thanks
(setq gnus-user-date-format-alist
      '(
;        ((gnus-seconds-today) . "     %H:%M")
;        (604800 . " %a %H:%M")
;        ((gnus-seconds-month) . "  %a, %d.")
;        ((gnus-seconds-year) . " %b %m-%d")
        (t . "%Y-%m-%d %H:%M")))

;; insert a reasonable date to the default line:
(setq gnus-summary-line-format
      "%U%R%z %&user-date; %I%(%[%-23,23f%]%) %s\n")


;; ===================================================================
;;                           Old/Misc Stuff
;; ===================================================================
;; Von Kai Grossjohann
(defun mark-region-as-included (b e)
  (interactive "r")
  (goto-char (- e 1))
  (if (looking-at "\n") () (forward-char 1))
  (if (eobp) (progn (insert "\n") (backward-char 1)))
  ;; we are at the end of the line
  (setq e (point))
  (forward-char 1)
  (insert "`-----\n")
  (string-rectangle b e "| ")
  (goto-char b)
  (insert ",-----\n")
  )
