; -*- emacs-lisp -*-
;

(message "checking for local setup and loading..")
(if (file-exists-p "/local/skel/all.emacs")
    (load "/local/skel/all.emacs" nil t t))

(message "loading .emacs-standard")
(load "~/.emacs-standard")

(setq vc-follow-symlinks t
      custom-file (expand-file-name "~/.emacs-custom"))

(cw/requiring-forms nil
  (message "checking for local setup and loading..")
  (if (file-exists-p "/local/skel/all.emacs")
      (load "/local/skel/all.emacs" nil t t))
  (if (file-exists-p custom-file)
      (load custom-file nil t t)))

(setq tfheen-color-preference 'dark) ; light or dark
(require 'jka-compr)
(auto-compression-mode t)

(cw/for-emacs
 (if (string-match "[Uu][Tt][Ff]-?8" (or (getenv "LC_ALL")
                                         (getenv "LANG")
                                         (format ""))) 
     (progn
       (set-language-environment "UTF-8") ; UTF-8 mode
       (if (not window-system)
           (progn
             (set-keyboard-coding-system 'utf-8)
             (set-terminal-coding-system 'utf-8))))
   (set-language-environment "Latin-1")))

;(prefer-coding-system "utf-8")

(add-to-list 'Info-default-directory-list (expand-file-name "~/usr/info"))

(add-to-list 'load-path (expand-file-name "~/data/emacs/lisp"))
(add-to-list 'load-path (expand-file-name "~/svn/elisp"))

(cw/requiring-package (eweouz)
  (add-hook 'gnus-startup-hook 'eweouz-insinuate-gnus)
  (add-hook 'mail-setup-hook 'eweouz-insinuate-sendmail)
  (add-hook 'message-setup-hook 'eweouz-insinuate-message))

;;;(cw/requiring-package (bbdb)
;;;   (cw/not-for-host ".*ntnu.no"
;;;                    (bbdb-initialize 'gnus 'message 'w3))
;;;   (setq bbdb-use-pop-up nil
;;;         bbdb-quiet-about-name-mismatches t
;;;         bbdb-default-area-code nil
;;;         bbdb-north-american-phone-numbers-p nil
;;;         bbdb-user-mail-names "\(tollef|tfheen\)"
;;;         bbdb-offer-save 1
;;;         bbdb-use-pop-up nil
;;;         mail-setup-hook 'bbdb-insinuate-sendmail
;;; 	bbdb-dwim-net-address-allow-redundancy t
;;; 	bbdb-complete-name-allow-cycling t)
;;;   (add-hook 'gnus-startup-hook 'bbdb-insinuate-gnus)
;;;   (add-hook mail-setup-hook 'bbdb-define-all-aliases))

(setq default-major-mode 'text-mode
      mail-user-agent 'gnus-user-agent
      read-mail-command 'gnus)

(add-hook 'text-mode-hook 'turn-on-auto-fill)
(add-hook 'debian-changelog-mode-hook 'turn-on-auto-fill)

(fset 'yes-or-no-p 'y-or-n-p)

(cw/requiring-package (mailcrypt)
  (cw/not-for-host ".*ntnu.no"
                   (mc-setversion "gpg") )
  (autoload 'mc-install-write-mode "mailcrypt" nil t)
  (autoload 'mc-install-read-mode "mailcrypt" nil t)
  (add-hook 'mail-mode-hook 'mc-install-write-mode)
  (add-hook 'mail-setup-hook 'mc-install-write-mode)
  (add-hook 'gnus-summary-mode-hook 'mc-install-read-mode)
  (add-hook 'news-reply-mode-hook 'mc-install-write-mode)
  (setq mc-temp-directory (expand-file-name "~/tmp")
        mc-encrypt-for-me t
        mc-gpg-user-id "tfheen@opera.no"
        mc-passwd-timeout 600))

(global-set-key "\M-n" 'browse-url-at-point)
;(global-set-key (kbd "C-x C-c")
;#'(lambda () (interactive)
;    (if (and window-system (string-match "yiwaz\\|thosu" system-name))
;        (message "you must be kidding")
;      (save-buffers-kill-emacs))))

(global-set-key [(control backspace)] 'undo)
(global-set-key [(control return)] 'find-tag)

(cw/requiring-package (w3-auto))

(setq browse-url-browser-function 'browse-url-generic
      browse-url-new-window-p t
      browse-url-mozilla-program (or (executable-find "firefox-3.0") "firefox")
      browse-url-generic-program "chromium")

;; File modes

(autoload 'php-mode "php-mode" "PHP editing mode" t)
(autoload 'css-mode "css-mode")
(autoload 'pov-mode "pov-mode" "PoVray scene file mode" t)
(autoload 'jde-mode "jde" "Java Development Environment" t)
(autoload 'dtml-mode "dtml-mode" "Document Template Markup Language" t)
(autoload 'vcl-mode "vcl-mode")

(add-to-list 'auto-mode-alist '("\\.php3$" . php-mode))
(add-to-list 'auto-mode-alist '("\\.css$" . css-mode))
(add-to-list 'auto-mode-alist '("\\.pov$" . pov-mode))
(add-to-list 'auto-mode-alist '("\\.jl$" . lisp-mode))
(add-to-list 'auto-mode-alist '("\\.java$" . jde-mode))
(add-to-list 'auto-mode-alist '("\\.vcl$" . vcl-mode))

;; Set up autoloading and auto-mode
(autoload 'ps-mode "ps-mode"
  "Major mode for editing PostScript" t)
(setq auto-mode-alist
      (append
       '(("\\.[eE]?[pP][sS]$" . ps-mode))
       auto-mode-alist))

;; Various programming settings and languages
; K&R
(setq perl-indent-level 8
      perl-continued-statement-offset 8
      perl-continued-brace-offset 0
      perl-brace-offset -8
      perl-brace-imaginary-offset 0
      perl-label-offset -8)

(setq next-line-add-newlines nil
      compilation-window-height 10
      european-calendar-style t
      diff-switches "-u")

(defun reverse-list-in-list (reverse-list)
  (require 'cl)
  (let '(bar (copy-list reverse-list))
    (setq liste (list))
       (while (car bar)
	 (let '(elem (car bar))
	   (add-to-list 'liste (reverse elem)))
	 (setq bar (cdr bar)))
       (reverse liste)))

(setq py-honor-comment-indentation nil)

(add-hook 'sgml-mode-hook '(lambda()(local-set-key "\C-c>" 'sgml-insert-end-tag)))
;(add-hook 'emacs-lisp-mode-hook '(lambda()(local-set-key "\C-j" 'find-function)))
;(require 'template)
;(add-hook 'c-mode-common-hook 'tmpl-init)
;(add-hook 'c-mode-common-hook 'auto-insert-file-header)
(add-hook 'c-mode-common-hook (lambda() (local-set-key "\M-\C-x" 'compile)))
(add-hook 'c-mode-common-hook (lambda() (local-set-key "\M-\C-z" 'next-error)))

(cw/requiring-package (auto-header))

(setq header-full-name "Tollef Fog Heen"
      header-email-address "tollef@err.no"
      add-log-mailing-address "tfheen@err.no"
      debian-changelog-mailing-address "tfheen@debian.org"
      tags-table-list '("~/varnish" "~/usr/include/"))

(setq sgml-local-catalogs (list "~/usr/lib/sgml/sgml.catalog"))

;; Find-file hooks
; Stolen from Jan Ingvoldstad
(add-hook 'find-file-hooks
	  '(lambda ()
	  ;; Invoke proper modes when we don't know file extensions
	  (cond ((looking-at "#!.*/perl") (perl-mode))
		((looking-at "#!.*/tclsh") (tcl-mode))
		((looking-at "#!.*/wish") (tcl-mode))
		((looking-at "#!.*/make") (makefile-mode)))))

;; Visual fluff.

(cw/for-emacs
 (if (functionp 'toggle-scroll-bar)
     (progn
       (toggle-scroll-bar -1)
       (setq scrollbars-visible-p nil))))

(setq scroll-bar-mode nil)
; (set-default-font "fixed")

;      show-paren-style 'expression)

; Highlight matching/nonmatching parens
;(if (not xemacsp)
;    (show-paren-mode t)) ; show-paren-mode takes too much cpu
(cw/for-emacs
 (global-font-lock-mode t)
 (font-lock-mode 1))

;; Multiple mode

(cw/requiring-package
 (mmm-auto)
 (setq mmm-global-mode 'maybe)
 (set-face-background 'mmm-default-submode-face "White"))

(cw/requiring-package
    (font-lock)
  (cw/requiring-package
      (poe)
    (set-face-foreground (find-face font-lock-string-face) "Blue")))

(cw/requiring-package (tramp)
  (setq tramp-auto-save-directory (expand-file-name "~/tmp")
        tramp-default-method "rsync"))

;;         (setq tramp-multi-file-name-structure (quote ("\\`/r:\\(\\([a-z0-9]+\\)\\)?\\(\\(%s\\)+\\):\\(.*\\)\\'" 2 3 -1))
;;                             tramp-make-tramp-file-format "/r:%m/%u@%h:%p"
;;                             tramp-file-name-regexp "\\`/r:"
;;                             tramp-make-multi-tramp-file-format (quote ("/r:%m" "/%m:%u@%h" ":%p"))
;;                             tramp-make-tramp-file-user-nil-format "/r:%m/%h:%p"
;;                             tramp-file-name-structure '("\\`/r:\\(\\([a-zA-Z0-9]+\\)/\\)?\\(\\([-a-zA-Z0-9_#/:]+\\)@\\)?\\([-a-zA-Z0-9_#/:@.]+\\):\\(.*\\)\\'" 2 4 5 6)))


(cw/for-emacs-21-and-later
 (blink-cursor-mode 0)
 (if window-system
     (tooltip-mode 0))
 (if window-system
     (tool-bar-mode 0))
 (global-set-key [home] 'beginning-of-buffer)
 (global-set-key [end] 'end-of-buffer)
 (menu-bar-mode 0)
 (setq cursor-in-non-selected-windows nil))

(defun tfheen-complete (&optional x)
  (interactive)
  (if (eq major-mode 'jde-mode)
      (jde-complete-at-point)
    (hippie-expand x)))

(global-set-key [C-tab] 'dabbrev-expand)
(global-set-key "\M- " 'tfheen-complete)


;(add-hook 'diary-hook 'appt-make-list)
;(add-hook 'diary-hook 'appt-make-list)
;(diary 0)

; Mode line
(display-time)

(cw/for-emacs-22-and-later
 (setq inhibit-splash-screen t)
 (setq inhibit-startup-echo-area-message "tfheen")
)

(cw/for-emacs-23-and-later
 (setq line-move-visual nil))

;(cw/for-emacs-21
; (display-battery))
;(cw/for-emacs-22
; (display-battery-mode))
(setq display-time-format "%H:%M"
      display-time-string-forms '(24-hours ":" minutes))

(setq show-trailing-whitespace t)
;(setq-default indent-tabs-mode nil)
(cw/for-emacs-21-and-later
 (define-coding-system-alias 'iso885915 'iso-8859-15)
 (define-coding-system-alias 'utf8 'utf-8)
 (define-coding-system-alias 'iso-8859-15 'iso-8859-1))

(setq add-log-full-name "Tollef Fog Heen"
      add-log-time-format 'tfheen-dpkg-changelog-time)

(defun tfheen-dpkg-changelog-time ()
  (let* ((time (decode-time))
        (sec (first time))
        (minute (second time))
        (hour (third time))
        (day (fourth time))
        (month (fifth time))
        (year (sixth time))
        (dow (seventh time))
        (dst (eighth time))
        (zone (second (current-time-zone)))
        (daynames '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
        (monthnames '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
        (dayname nil)
        (monthname nil))
    (setq dayname (nth (- dow 1) daynames)
          monthname (nth (- month 1) monthnames))
    (format "%s %s %d %2d:%2d:%2d %s %d" dayname monthname day hour minute sec zone year)))

(add-to-list 'load-path (expand-file-name "~/external/slime"))
(cw/requiring-package (slime)
    (add-hook 'lisp-mode-hook (lambda () (slime-mode t)))
    (add-hook 'inferior-lisp-mode-hook (lambda () (inferior-slime-mode t)))
    (setq inferior-lisp-program "sbcl-mt"))

(setq mouse-yank-at-point t)

;: WL setup

(setq elmo-imap4-default-stream-type 'ssl
      elmo-imap4-default-server "mail.raw.no"
      elmo-imap4-default-port 993)
;      wl-folder-access-subscribe-alist '(("^%" . (t . "."))))
(setq elmo-imap4-default-authenticate-type 'clear
      elmo-default-authenticate-type 'clear)

(put 'downcase-region 'disabled nil)

(defun linux-c-mode ()
  "C mode with adjusted defaults for use with the Linux kernel."
  (interactive)
  (c-mode)
  (c-set-style "K&R")
  (setq tab-width 8)
  (setq indent-tabs-mode t)
  (setq c-basic-offset 8))

(cw/for-emacs-22-and-later
 (setq org-remember-templates
       '((?t "* TODO %?\n  %i\n  %a" "~/svn/plans/todo.org")
	 (?a "* Appointment: %?\n%^T\n%i\n  %a" "~/svn/plans/todo.org")))
 (setq remember-annotation-functions '(org-remember-annotation)
       remember-handler-functions '(org-remember-handler)
       org-return-follows-link t
       org-todo-keywords '("TODO" "STARTED" "WAITING" "DONE")
       org-agenda-include-diary t
       org-agenda-include-all-todo t
       org-tags-column (* -1 (- (frame-width) 10))
       org-agenda-align-tags-to-column (- (frame-width) 10)
       org-hide-leading-stars nil
       org-agenda-files '("~/svn/plans/todo.org")
       org-stuck-projects '("+LEVEL=2-neverstuck/-DONE" ("TODO" "NEXT" "NEXTACTION" "") ("APPOINTMENT") "")
       org-clock-out-when-done nil
       org-clock-persist t
       org-clock-into-drawer t)
 (org-clock-persistence-insinuate))


 (eval-after-load 'remember
   '(add-hook 'remember-mode-hook 'org-remember-apply-template))
 (global-set-key (kbd "C-c r") 'remember)

 (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
 (global-set-key (kbd "C-c a") 'org-agenda)
 (setq org-agenda-custom-commands
       '(("w" todo
	  #("WAITING" 0 7
	    (face org-warning)))
	 ("h" tags-todo "@hjemme")
	 ("j" tags-todo "@jobb")))

(add-to-list 'window-size-change-functions
	     (lambda (frame) (setq org-tags-column (* -1 (- (frame-width) 10))
				   org-agenda-align-tags-to-column (- (frame-width) 10))))

(cw/for-host "qurzaw\\|thosu"
  (setq gnus-home-directory "~/.emacs.d/gnus"
	gnus-init-file "~/.gnus"
	message-directory (concat gnus-home-directory "/Mail")))


(cw/for-emacs-23-and-later
 (cw/not-for-os 'darwin
		;; Firefox-like zooming of fonts.
		(setq tfheen-base-size 8
		      tfheen-base-font "DejaVu Sans Mono"
		      tfheen-current-size tfheen-base-size)

		(defun font-zoom-increase-font-size ()
		  (interactive)
		  (setq tfheen-current-size (+ tfheen-current-size 2))
		  (let ((font-name (format "%s-%d" tfheen-base-font tfheen-current-size)))
		    (set-frame-font font-name)))

		(defun font-zoom-decrease-font-size ()
		  (interactive)
		  (setq tfheen-current-size (- tfheen-current-size 2))
		  (let ((font-name (format "%s-%d" tfheen-base-font tfheen-current-size)))
		    (set-frame-font font-name)))

		(defun font-zoom-reset-font-size ()
		  (interactive)
		  (let ((font-name (format "%s-%d" tfheen-base-font tfheen-base-size)))
		    (set-frame-font font-name)))

		(define-key global-map (read-kbd-macro "C--") 'font-zoom-decrease-font-size)
		(define-key global-map (read-kbd-macro "C-+") 'font-zoom-increase-font-size)
		(define-key global-map (read-kbd-macro "C-=") 'font-zoom-reset-font-size)
		(font-zoom-reset-font-size)))

(defun minutes-to-hours (minutes)
  (when minutes
    (/ (* 1.0 minutes) 60)))

(defun minutes-to-seconds (minutes)
  (* 60 minutes))

(defun weekend-p (time)
  (> (string-to-number (format-time-string "%u" time)) 5))

(defun org-dblock-write:timebalance (params)
  "Display day-by-day summary, giving a balance"
  (let* ((ts (plist-get params :tstart))
         (te (plist-get params :tend))
	 (ins (make-marker))
         (start (time-to-seconds
                 (apply 'encode-time (org-parse-time-string ts))))
         (end (time-to-seconds
               (apply 'encode-time (org-parse-time-string te))))
	 tbl sum)

    (setq params (plist-put params :tstart nil))
    (setq params (plist-put params :end nil))
    (move-marker ins (point))
    (while (<= start end)
      (save-excursion
	(let ((sum 0))
	  (org-clock-sum start (+ start 86400))
	  (goto-char (point-min))
	  (setq st t)
	  (while (or (and (bobp) (prog1 st (setq st nil))
			  (get-text-property (point) :org-clock-minutes)
			  (setq p (point-min)))
		     (setq p (next-single-property-change (point) :org-clock-minutes)))
	    (goto-char p)
	    (message (format "pre: %s %d %d %s" (format-time-string "%Y-%m-%d" (seconds-to-time start)) sum start (point)))
	    (if (= 1 (car (org-heading-components)))
		(setq sum (+ sum (or (get-text-property p :org-clock-minutes) 0)))))
	  (push (list start sum) tbl)))
      (setq start (+ 86400 start)))
    (setq tbl (nreverse tbl))
    (goto-char ins)
    (setq sum 0)
    (while tbl
      (let* ((line (car tbl))
	     (ts (seconds-to-time (first line)))
	     (minutes (second line))
	     (hours (minutes-to-hours minutes)))
	(setq sum (+ sum hours))
	(if (not (weekend-p ts))
	    (setq sum (- sum 7.5)))
	(if (> minutes 0)
	    (insert-before-markers
	     (format-time-string "%Y-%m-%d" ts)
	     (format " %f %f\n" hours sum))))
	(setq tbl (cdr tbl)))))

(defun tfheen-round-invoice-hours (hours)
  (when hours
    (/ (ceiling (* hours 4)) 4.0)))

(defun tfheen-round-invoice-minutes (minutes)
  (when minutes
    (* 15 (ceiling minutes 15))))

(defun org-dblock-write:invoicerounding (params)
  "Grab hours in a format suitable for an invoice, rounding all times to a full hour"
  (let* ((ts (plist-get params :tstart))
         (te (plist-get params :tend))
	 (ins (make-marker))
         (start (time-to-seconds
                 (apply 'encode-time (org-parse-time-string ts))))
         (end (time-to-seconds
               (apply 'encode-time (org-parse-time-string te))))
	 tbl sum)

    (setq params (plist-put params :tstart nil))
    (setq params (plist-put params :end nil))
    (move-marker ins (point))
    (while (<= start end)
      (save-excursion
	(let ((sum 0))
	  (org-clock-sum start (+ start 86400))
	  (goto-char (point-min))
	  (setq st t)
	  (while (or (and (bobp) (prog1 st (setq st nil))
			  (get-text-property (point) :org-clock-minutes)
			  (setq p (point-min)))
		     (setq p (next-single-property-change (point) :org-clock-minutes)))
	    (goto-char p)
	    (if (= 1 (car (org-heading-components)))
		(setq sum (+ sum (or (get-text-property p :org-clock-minutes) 0)))))
	  (push (list start sum) tbl)))
      (setq start (+ 86400 start)))
    (setq tbl (nreverse tbl))
    (goto-char ins)
    (setq sum 0)
    (while tbl
      (let* ((line (car tbl))
	     (ts (seconds-to-time (first line)))
	     (minutes (second line))
	     (hours (tfheen-round-invoice-hours (minutes-to-hours minutes))))
	(setq sum (+ sum hours))
	(if (> minutes 0)
	    (insert-before-markers
	     (format-time-string "%Y-%m-%d" ts)
	     (format " %.2f\n" hours))))
	(setq tbl (cdr tbl)))
    (insert-before-markers "---------------\n")
    (insert-before-markers (format "Sum %11.2f" sum))))

(defun org-dblock-write:gtimelog (params)
  "Display day-by-day time reports in gtimelog format."
  (let* ((ts (plist-get params :tstart))
         (te (plist-get params :tend))
	 (ins (make-marker))
         (maxlevel (plist-get params :maxlevel))
         (start (time-to-seconds
                 (apply 'encode-time (org-parse-time-string ts))))
         (end (time-to-seconds
               (apply 'encode-time (org-parse-time-string te))))
	 tbl day-numbers heading1-label)

    (setq params (plist-put params :tstart nil))
    (setq params (plist-put params :end nil))
    (move-marker ins (point))
    (while (<= start end)
      (save-excursion
	(org-clock-sum start (+ start 86400))
	(goto-char (point-min))
	(setq st t)
	(while (or (and (bobp) (prog1 st (setq st nil))
			(get-text-property (point) :org-clock-minutes)
			(setq p (point-min)))
		   (setq p (next-single-property-change (point) :org-clock-minutes)))
	  (goto-char p)
	  (when (setq time (tfheen-round-invoice-minutes (get-text-property p :org-clock-minutes)))
	    (save-excursion
	      (message "time '%s'" (get-text-property p :org-clock-minutes))
	      (beginning-of-line 1)
	      (when (and (looking-at (org-re "^\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
			 (setq level (org-reduced-level
				      (- (match-end 1) (match-beginning 1))))
			 (<= level maxlevel))
		(if (= level 1)
		    (setq heading1-label (match-string 2))
		  (push (list
		       start
		       (concat heading1-label ": " (match-string 2))
		       time) tbl)))))))
      (setq start (+ 86400 start)))
    (setq tbl (nreverse tbl))
    (goto-char ins)
    (setq ts 0)
    (while tbl
      (let ((line (car tbl)))
	(if (< ts (car line))
	    ; New day
	    (progn
	      (insert-before-markers
	       (format-time-string "%Y-%m-%d %H:%M %z"
				   (seconds-to-time (first line)))
	       ": Arrive\n")
	      (setq ts (first line))))

	(insert-before-markers
	 (format-time-string "%Y-%m-%d %H:%M %z"
			     (seconds-to-time (+ ts (* 60 (third line)))))
	 ": "
	 (format "%s" (second line))
	 "\n")
	(setq ts (+ ts (* 60 (third line))))
	(setq tbl (cdr tbl))))))

;(defadvice current-time (after tfheen-floor-current-time activate disable)
;  (setq ad-return-value (seconds-to-time (* 900 (floor (time-to-seconds ad-return-value) 900)))))
;(defadvice org-clock-in (around tfheen-round-clock activate)
;  (ad-enable-advice 'current-time 'after 'tfheen-floor-current-time)
;  (ad-activate 'current-time)
;  ad-do-it
;  (ad-disable-advice 'current-time 'after 'tfheen-floor-current-time)
;  (ad-activate 'current-time))

;(defadvice current-time (after tfheen-ceiling-current-time activate disable)
;  (setq ad-return-value (seconds-to-time (* 900 (ceiling (time-to-seconds ad-return-value) 900)))))
;(defadvice org-clock-out (around tfheen-round-clock activate)
;  (ad-enable-advice 'current-time 'after 'tfheen-ceiling-current-time)
;  (ad-activate 'current-time)
;  ad-do-it
;  (ad-disable-advice 'current-time 'after 'tfheen-ceiling-current-time)
;  (ad-activate 'current-time))

(autoload 'vala-mode "vala-mode" "Major mode for editing Vala code." t)
(add-to-list 'auto-mode-alist '("\\.vala$" . vala-mode))
(add-to-list 'auto-mode-alist '("\\.vapi$" . vala-mode))
(add-to-list 'file-coding-system-alist '("\\.vala$" . utf-8))
(add-to-list 'file-coding-system-alist '("\\.vapi$" . utf-8))

(cw/for-host "qurzaw"
  (require 'twittering-mode))

(defun unfill-paragraph ()
  (interactive)
  (let ((fill-column (point-max)))
    (fill-paragraph nil)))

(defun unfill-region ()
  (interactive)
  (let ((fill-column (point-max)))
    (fill-region (region-beginning) (region-end) nil)))

(define-key global-map "\M-Q" 'unfill-paragraph)
(define-key global-map "\C-\M-q" 'unfill-region)

(setq twittering-use-native-retweet t
      twittering-use-icon-storage t
      twittering-icon-mode t)

(setq tfheen-twittering-filter-blacklist
      '((text . "#oslo #planking")
	(text . "#WEBELIEBE")
       (user-screen-name . "\\(Oslo_HitHot\\|Map_Game\\|anbud1\\)")))

(defun tfheen-twitter-filter-search ()
  (interactive)
  (let ((non-matching-statuses ()))
    (dolist (status twittering-new-tweets-statuses)
      (if (eq (cadr (assoc 'source-spec status)) 'search)
	  (let ((matched-tweets 0))
	    (dolist (item tfheen-twittering-filter-blacklist)
	      (let* ((type (car item))
		     (pat (cdr item)))
		(if (string-match pat (cdr (assoc type status)))
		    (setq matched-tweets (+ 1 matched-tweets)))))
	    (if (= 0 matched-tweets)
		(setq non-matching-statuses (append non-matching-statuses `(,status)))))
	(setq non-matching-statuses (append non-matching-statuses `(,status)))))
    (setq new-statuses non-matching-statuses)))

(add-hook 'twittering-new-tweets-hook 'tfheen-twitter-filter-search)

(setq twittering-initial-timeline-spec-string
      '(":home"
	":replies"
	":direct_messages"
	":search/#oslo/"
	":search/#varnish/"))

(define-key org-mode-map [home] 'beginning-of-buffer)
(define-key org-mode-map [end]  'end-of-buffer)

(defun tfheen/weekday-p ()
  (let ((wday (nth 6 (decode-time))))
    (and (< wday 6)
	 (> wday 0))))

(defun tfheen/working-p ()
  (let ((hour (nth 2 (decode-time))))
    (and (tfheen/weekday-p)
	 (and (>= hour 7) (<= hour 15)))))

(defun tfheen/org-auto-exclude-function (tag)
  "Automatic task exclusion in the agenda with / RET"
  (and (cond
	((string= tag "@farm")
         t)
        (t
         (if (tfheen/working-p)
             (setq tag "@hjemme")
           (setq tag "@jobb"))
         (unless (member (concat "-" tag) org-agenda-filter)
           tag)))
       (concat "-" tag)))

(setq org-agenda-auto-exclude-function 'tfheen/org-auto-exclude-function)

(defun mw-to-mdwn ()
  (interactive)
  (save-excursion
    (replace-regexp "^==== \\(.*\\) ====" "#### \\1" nil (point-min) (point-max))
    (replace-regexp "^=== \\(.*\\) ===" "### \\1" nil (point-min) (point-max))
    (replace-regexp "^== \\(.*\\) ==" "## \\1" nil (point-min) (point-max))
    (replace-regexp "^= \\(.*\\) =" "# \\1" nil (point-min) (point-max))
   ))
