;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;>
;;;;; ISR - Time-stamp: <2012-03-26 00:12:06 inigo>

(defconst my-elisp-dir "~/.emacsmine/")
(add-to-list 'load-path my-elisp-dir)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; OS-dependant values
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(cond
 ;; ((string-match "i686-pc-linux-gnu" (emacs-version)) ; my laptop eeePC 900 running ArchLinux
 ((string-match (system-name) "xxx") ; my laptop eeePC 900 running ArchLinux
  (defconst FRAMESIZE '((width . 124) (height . 38)))
  (defconst FONTSLIST
    '(list
      "DejaVu Sans Mono 10"
      "-xos4-terminus-medium-r-normal--12-120-72-72-c-60-iso10646-1"
      "-xos4-terminus-medium-r-normal--14-140-72-72-c-80-iso10646-1"
      "-xos4-terminus-medium-r-normal--16-160-72-72-c-80-iso10646-1"
      "-xos4-terminus-medium-r-normal--20-200-72-72-c-100-iso10646-1"
      "-schumacher-clean-medium-r-normal--12-*-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--13-130-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--14-*-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--15-*-75-75-c-90-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--16-*-75-75-c-80-iso646.1991-irv"))
  (setq default-font-zoom-index 2)
  )
 ((string-match (system-name) "inigo.katxi.org") ; my linux desktop running Fedora 16
  ;; (setq x-alt-keysym 'meta)
  ;; (setq x-meta-keysym 'alt)
  (defconst FRAMESIZE '((width . 107) (height . 58)))
  (defconst FONTSLIST
    '(list
      "Droid Sans Mono 10"
      "DejaVu Sans Mono 10"
      "-windows-dina-medium-r-normal--13-80-96-96-c-70-iso8859-1"
      "-windows-dina-medium-r-normal--15-90-96-96-c-70-iso8859-1"
      "-windows-dina-medium-r-normal--16-100-96-96-c-80-iso8859-1"
      "-xos4-terminus-medium-r-normal--12-120-72-72-c-60-iso10646-1"
      "-xos4-terminus-medium-r-normal--14-140-72-72-c-80-iso10646-1"
      "-xos4-terminus-medium-r-normal--16-160-72-72-c-80-iso10646-1"
      "-xos4-terminus-medium-r-normal--20-200-72-72-c-100-iso10646-1"
      "-schumacher-clean-medium-r-normal--12-*-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--13-130-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--14-*-75-75-c-80-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--15-*-75-75-c-90-iso646.1991-irv"
      "-schumacher-clean-medium-r-normal--16-*-75-75-c-80-iso646.1991-irv"
      "-windows-proggyclean-medium-r-normal--13-80-96-96-c-70-iso8859-1"
      "-windows-speedy-medium-r-normal--11-80-96-96-c-70-iso8859-1"
      "-windows-speedy-medium-r-normal--12-90-96-96-c-70-iso8859-1"
      "-adobe-symbol-medium-r-normal--12-120-75-75-p-74-adobe-fontspecific"
      "-adobe-symbol-medium-r-normal--14-100-100-100-p-85-adobe-fontspecific"
      "-adobe-symbol-medium-r-normal--17-120-100-100-p-95-adobe-fontspecific"
      "-adobe-symbol-medium-r-normal--18-180-75-75-p-107-adobe-fontspecific"))
  (setq default-font-zoom-index 1)
  )
 ;; ((string-match "nt5" (emacs-version)) ; my work winxp laptop
 ((string-match (system-name) "NB002-SW-MAD")  ; my work winxp laptop
  (defconst FRAMESIZE '((width . 86) (height . 51)))
  (defconst FONTSLIST
    '(list
      "-outline-Monaco-normal-r-normal-normal-10-*-96-96-c-*-iso10646-1"
      "-outline-Monaco-normal-r-normal-normal-12-*-96-96-c-*-iso10646-1"
      "-outline-Monaco-normal-r-normal-normal-14-*-96-96-c-*-iso10646-1"
      "-outline-Monaco-normal-r-normal-normal-16-*-96-96-c-*-iso10646-1"
      "-outline-Andale Mono-normal-r-normal-normal-10-*-96-96-c-*-iso10646-1"
      "-outline-Andale Mono-normal-r-normal-normal-12-*-96-96-c-*-iso10646-1"
      "-outline-Andale Mono-normal-r-normal-normal-14-*-96-96-c-*-iso10646-1"
      "-outline-Andale Mono-normal-r-normal-normal-16-*-96-96-c-*-iso10646-1"
      "-outline-ProggyCleanTT CE-normal-r-normal-normal-14-*-96-96-c-*-iso10646-1"
      "-outline-ProggyCleanTT CE-normal-r-normal-normal-16-*-96-96-c-*-iso10646-1"
      "-outline-ProggyCleanTT CE-normal-r-normal-normal-18-*-96-96-c-*-iso10646-1"
      "-outline-ProggyCleanTT CE-normal-r-normal-normal-20-*-96-96-c-*-iso10646-1"
      "-outline-Terminus Re33-bold-r-normal-normal-14-*-96-96-c-*-iso10646-1"
      "-outline-Terminus Re33-bold-r-normal-normal-16-*-96-96-c-*-iso10646-1"
      "-outline-Terminus Re33-bold-r-normal-normal-18-*-96-96-c-*-iso10646-1"
      "-outline-Terminus Re33-bold-r-normal-normal-20-*-96-96-c-*-iso10646-1"))
  (setq default-font-zoom-index 2)
  )
 )


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Custom variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(abbrev-file-name "~/.emacs.d/.abbrev_defs")
 '(add-log-time-format (quote current-time-string))
 '(bookmark-default-file "~/.emacs.d/.emacs.bmk")
 '(cal-tex-diary t)
 '(cua-enable-cua-keys nil) ; (quote shift)
 '(cua-mode t nil (cua-base))
 '(cua-rectangle-mark-key [C-S-return])
 '(default-frame-alist FRAMESIZE)
 '(desktop-dirname "~/.emacs.d")
 '(desktop-base-file-name "~/.emacs.d/.emacs.desktop")
 '(desktop-base-lock-name "~/.emacs.d/.emacs.desktop.lock")
 '(desktop-save-mode t)
 '(ecb-options-version "2.40")
 '(recentf-save-file "~/.emacs.d/.recentf")
 '(save-place t nil (saveplace))
 '(save-place-file "~/.emacs.d/.emacs-places")
 '(tab-width 4)
 '(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 88 96 104 112 120)))
;  '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify)))
)

(setq user-full-name "Inigo Serna")
(setq user-mail-address "my@email.com")

;; (setq message-log-max nil)
;; (kill-buffer "*Messages*")  ; Switch off the message buffer
(setq debug-on-error nil)    ; don't create a backtrace report
(setq inhibit-startup-message t)

;; (set-input-method "catalan-prefix")
(prefer-coding-system 'utf-8)
(set-language-environment "utf-8")

(setq display-time-24hr-format t
      display-time-day-and-date t
      european-calendar-style t
      calendar-week-start-day 1
      mark-diary-entries-in-calendar t
      all-christian-calendar-holidays t)
(setq diary-file "~/personal/agenda/diary")
;(icalendar-import-file "~/.evolution/calendar/local/system/calendar.ics" "~/ical-diary2")

(fset 'yes-or-no-p 'y-or-n-p)
(setq use-file-dialog nil)
(delete-selection-mode nil)
(icomplete-mode t)
(reveal-mode 1)
(recentf-mode t)
(setq recentf-max-saved-items 100
      recentf-exclude '("semantic.cache" "xhtml-loader.rnc" ".ido.last" "*.fb2"))
(setq case-fold-search t)
(setq completion-tooltip-delay 0
      completion-ignore-case t
      read-file-name-completion-ignore-case t)
(setq dabbrev-abbrev-skip-leading-regexp "[^ ]*[<>=*]")
;; (setq tab-always-indent 'complete)      ; like smarttab
(setq ediff-custom-diff-options "-u")
(setq ediff-window-setup-function 'ediff-setup-windows-plain)
(setq-default indent-tabs-mode nil)
(setq indent-region-mode t)
;; (setq kill-whole-line t)
(setq mark-even-if-inactive t)
(setq kill-ring-max 1024)
(setq outline-minor-mode-prefix ".")
(setq skeleton-pair t)
(windmove-default-keybindings 'meta)
;; (setq x-select-enable-clipboard t)

(add-hook 'before-save-hook 'time-stamp)
;(add-hook 'before-save-hook 'delete-trailing-whitespace)
(add-hook 'text-mode-hook 'auto-fill-mode)  ;auto-fill
; from http://www.zafar.se/bkz/Articles/EmacsTips
(defconst use-backup-dir t)
(setq make-backup-files t
      backup-directory-alist (quote ((".*" . "~/.emacs.d/backups/")))
      version-control t                ; Use version numbers for backups
      kept-new-versions 10             ; Number of newest versions to keep
      kept-old-versions 2              ; Number of oldest versions to keep
      delete-old-versions t            ; Ask to delete excess backup versions?
      backup-by-copying t
      backup-by-copying-when-linked t  ; Copy linked files, don't rename.
      vc-make-backup-files t)          ; Make backups of VC controlled files too

(setq delete-by-moving-to-trash t)     ; Use system trash (for emacs 23)

(setq dired-recursive-deletes 'top
      dired-recursive-copies 'top
      dired-copy-preserve-time t
      dired-dwim-target t
      dired-listing-switches "-al --group-directories-first"
      dired-bind-jump t ; bind C-xC-j to dired-jump
      wdired-allow-to-change-permissions t)
(add-hook 'dired-mode-hook (lambda ()
                             (local-set-key "\C-c\C-s" 'find-name-dired)
                             (local-set-key "\C-c\C-t" 'find-grep-dired)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Look & Feel, Colors, Fonts and Themes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(setq column-number-mode t)
(setq size-indication-mode t)
;; (display-time-mode t)

(tool-bar-mode -1)
(set-fringe-mode '(6 6))
(scroll-bar-mode -1)
;; (set-scroll-bar-mode (quote right))
(setq scroll-preserve-screen-position t
      scroll-step 0
      scroll-conservatively 10000
      scroll-margin 0)
;; (setq scroll-up-aggressively 0.01
;;       scroll-down-aggressively 0.01)

(setq-default truncate-lines t)
(global-font-lock-mode 1)
(setq font-lock-maximum-decoration t)
(setq font-use-system-font t)
(blink-cursor-mode nil)
(show-paren-mode t)                     ; match parenthesis
;; (setq-default show-trailing-whitespace t)
;; (setq transient-mark-mode t)            ; highlights selections, not needed for emacs >= 23.1
(setq visible-bell t)
;; (mouse-avoidance-mode 'animate)  ; not needed on v23.2+
;; (setq make-pointer-invisible nil)
(setq mouse-autoselect-window t)

; BEST ones: ld-dark, clarity-and-beauty, deep-blue, taylor
; arjen, charcoal-black, hober, infodoc, midnight, resolve, subtle hacker
; taming mr..., WordPerfect
(require 'color-theme)
(color-theme-initialize)
(defun color-theme-inigo ()
  "based on deep-blue"
  (interactive)
  ;; (color-theme-deep-blue)
  ;; (color-theme-ld-dark)
  ;; (let ((color-theme-is-cumulative t))
  (let ((color-theme-is-cumulative t))
    (color-theme-install
     '(color-theme-inigo
       ((background-color . "black")
        (background-mode . dark)
        (foreground-color . "gray95")
        (border-color . "black")
        (cursor-color . "#f0dfaf")) ; yellow
       (toolbar ((t (:background "#405060" :foreground "Grey"))))
       (menu ((t (:background "#405060" :foreground "Grey"))))
       (mode-line ((t (:background "#181818" :foreground "grey50" :box (:line-width 1 :style released-button)))))
       (mode-line-inactive ((t (:background "black" :foreground "grey50" :box (:line-width 1 :style released-button)))))
       (mode-line-buffer-id ((t (:background "black" :foreground "wheat")))) ; = #f5deb3
       (diff-file-header ((t (:foreground "#f0f0f0" :background "#bc7373"))))
       (diff-header ((t (:background "aquamarine4"))))
       (diff-hunk-header ((t (:foreground "#666666" :background "#8cd0d3"))))
       (diff-added ((t (:foreground "aquamarine3"))))
       (diff-removed ((t (:foreground "#bc7373"))))
       (diff-refine-change ((t (:background "#101018"))))
       (font-lock-builtin-face ((t (:foreground "#8cd0d3")))) ; LightSteelBlue
       (font-lock-comment-face ((t (:italic t :foreground "SlateGrey"))))
       (font-lock-constant-face ((t (:foreground "aquamarine"))))
       (font-lock-doc-face ((t (:foreground "aquamarine4"))))
       (font-lock-doc-string-face ((t (:foreground "DarkOrange"))))
       (font-lock-exit-face ((t (:foreground "green"))))
       (font-lock-function-name-face ((t (:italic t :foreground "#bc7373")))) ; tomato
       (font-lock-keyword-face ((t (:foreground "LightSkyBlue"))))
       (font-lock-other-emphasized-face ((t (:foreground "gold1"))))
       (font-lock-other-type-face ((t (:foreground "gold1"))))
       (font-lock-preprocessor-face ((t (:foreground "Aquamarine"))))
       (font-lock-pseudo-keyword-face ((t (:foreground "SteelBlue")))) ;; does it exist?
       (font-lock-reference-face ((t (:foreground "SlateBlue"))))
       (font-lock-string-face ((t (:foreground "#6ca0a3")))) ; SteelBlue
       (font-lock-type-face ((t (:foreground "#ffc9a4")))) ; DarkOrange
       ;; (font-lock-variable-name-face ((t (:foreground "#bfebbf")))) ; darkseagreen
       (font-lock-variable-name-face ((t (:foreground "#93e0e3")))) ; darkseagreen
       (font-lock-warning-face ((t (:foreground "Yellow")))) ; :underline "red"
       (fringe ((t (:background "black"))))
       (highlight-changes ((t (:foreground nil :background "#382f2f"))))
       (highlight-changes-delete ((t (:foreground nil :background "#916868"))))
       (hl-line ((t (:foreground nil :background "#1B1000"))))
       (html-helper-builtin-face ((t (:foreground "CadetBlue" :underline nil))))
       (region ((t (:foreground "PeachPuff" :background "DimGrey"))))
       (py-builtins-face ((t (:foreground "LightSkyBlue"))))
       (py-decorators-face ((t (:foreground "Orange"))))
       (py-pseudo-keyword-face ((t (:foreground "LightSkyBlue"))))
       (ecb-mode-line-data-face ((t (:background "grey20"))))
       (ecb-default-highlight-face  ((t (:background "DimGrey"))))
       (tabbar-default ((t (:background "#181818" :color "#181818") :height 0.85)))
       (tabbar-button ((t (:inherit tabbar-default :box (:color "#181818") :background "#181818"))))
       (tabbar-selected ((t (:inherit tabbar-default :box (:color "#181818") :foreground "#cc9393")))) ; wheat
       (tabbar-unselected ((t (:inherit tabbar-default :box (:color "#181818") :foreground "grey50"))))
       ;; (pinbar-default-face ((t (:foreground "grey50" :background "#181818" :height 0.85))))
       ;; (pinbar-button-face ((t (:inherit pinbar-default-face :foreground "grey50" :background "#181818"))))
       ;; (pinbar-selected-face ((t (:inherit pinbar-default-face :box (:color "#181818") :foreground "#cc9393")))) ; wheat
       ;; (pinbar-unselected-face ((t (:inherit pinbar-default-face :box (:color "#181818") :foreground "grey50"))))
       (linum ((t (:inherit shadow :background "#181818" :slant normal :height 0.8))))
       (hs-face ((t (:background "#485858" :slant normal :height 0.8 :box nil))))
))))
(add-to-list 'color-themes '(color-theme-inigo  "inigo" "Inigo Serna"))

;; add colors for some special words and modes
(defvar special-keywords '(("\\<\\(FIXME\\|TODO\\|HACK\\|\\NOTE|XXX\\|BUG\\|WARNING\\):"
                            1 font-lock-warning-face t)))
(font-lock-add-keywords 'python-mode special-keywords)
(font-lock-add-keywords 'c-mode special-keywords)
(font-lock-add-keywords 'js-mode special-keywords)
(font-lock-add-keywords 'lua-mode special-keywords)
(font-lock-add-keywords 'vala-mode special-keywords)
(font-lock-add-keywords 'emacs-lisp-mode special-keywords)
(font-lock-add-keywords 'outline-mode special-keywords)

;;;;; mode-line
(setq-default mode-line-format
   (list
    "  "
    ;; tabbar group
    '(:eval (when (tabbar-mode-on-p)
              (concat (propertize (car (funcall tabbar-buffer-groups-function)) 'face 'font-lock-string-face)
                      " > ")))
    ;; the buffer name; the file name as a tool tip
    '(:eval (propertize "%b" 'face 'font-lock-function-name-face
                        'help-echo (buffer-file-name)))
    ; narrow [default -- keep?]
    " %n "
    ;; line and column
    "(" ;; '%02' to set to 2 chars at least; prevents flickering
    (propertize "%02l" 'face 'font-lock-builtin-face) ","
    (propertize "%02c" 'face 'font-lock-builtin-face)
    ") "
    ;; relative position, size of file
    "["
    (propertize "%p" 'face 'font-lock-doc-face) ;; % above top
    "/"
    (propertize "%I" 'face 'font-lock-doc-face) ;; size
    "] "
    "[" ;; insert vs overwrite mode, input-method in a tooltip
    '(:eval (propertize (if overwrite-mode "Ovr" "Ins") 'face 'font-lock-preprocessor-face
                        'help-echo (concat "Buffer is in "
                                           (if overwrite-mode "overwrite" "insert") " mode")))
    ;; was this buffer modified since the last save?
    '(:eval (when (buffer-modified-p)
              (concat ","  (propertize "Mod" 'face 'font-lock-preprocessor-face
                                       'help-echo "Buffer has been modified"))))
    ;; is this buffer read-only?
    '(:eval (when buffer-read-only
              (concat ","  (propertize "RO" 'face 'font-lock-other-type-face
                                       'help-echo "Buffer is read-only"))))
    "]  "
    ;; the current major mode for the buffer.
    "["
    '(:eval (propertize "%m" 'face 'font-lock-comment-face
                        'help-echo buffer-file-coding-system))
    minor-mode-alist  ;; list of minor modes
    "-] "
    '(:eval (propertize (if vc-mode vc-mode "") 'face 'font-lock-keyword-face))
    ;; ;; add the time, with the date and the emacs uptime in the tooltip
    ;; '(:eval (propertize (format-time-string " -- %H:%M ")
    ;;           'help-echo
    ;;           (concat (format-time-string "%c; ")
    ;;                   (emacs-uptime "Uptime:%hh"))))
    ;; "%-" ;; fill with '-'
))

(defun my-win-look ()
  (interactive)
  ;; (set-background-color "#000000")
  ;; (set-foreground-color "gray95")
  ;; (set-cursor-color "yellow")
  (set-default-font (nth default-font-zoom-index FONTSLIST))
  (set-fringe-mode '(6 6))
  (global-hl-line-mode 1)
  (global-highlight-changes-mode t)       ; highlights changes. Requires X
  (setq highlight-changes-visibility-initial-state nil) ; disabled by default
  (menu-bar-mode -99)
  (tool-bar-mode -1)
  (set-fringe-mode '(6 6))
  (scroll-bar-mode -1)
  (setq show-paren-style 'expression)
  (set-face-background 'show-paren-match-face "#333333")
  (set-face-attribute 'show-paren-match-face nil
                      :weight 'normal :underline nil :overline nil :slant 'normal)
  (color-theme-inigo))

(defun my-console-look ()
  (interactive)
  (set-background-color "#000000")
  (set-foreground-color "gray95")
  (set-cursor-color "yellow")
  (set-fringe-mode '(0 0))
  (global-hl-line-mode -1)
  ;; (menu-bar-mode -1)
  (setq show-paren-style 'parenthesis)
  (color-theme-tty-dark))

; from Steve Purcell's comment on http://emacs-fu.blogspot.com/2009/03/color-theming.html
; and next blog entry http://www.bennee.com/~alex/news.php?wl_mode=more&wl_eid=1295
(set-variable 'color-theme-is-global nil)
(set-variable 'color-theme-is-cumulative nil)

(defvar after-make-console-frame-hooks '()
  "Hooks to run after creating a new TTY frame")
(defvar after-make-window-system-frame-hooks '()
  "Hooks to run after creating a new window-system frame")

(defun run-after-make-frame-hooks (frame)
  "Selectively run either `after-make-console-frame-hooks' or
   `after-make-window-system-frame-hooks'"
  (select-frame frame)
  (run-hooks (if window-system
                 'after-make-window-system-frame-hooks
               'after-make-console-frame-hooks)))

(add-hook 'after-init-hook (lambda ()
                             (run-after-make-frame-hooks (selected-frame))))
(add-hook 'after-make-frame-functions 'run-after-make-frame-hooks)

(add-hook 'after-make-window-system-frame-hooks 'my-win-look)
(add-hook 'after-make-console-frame-hooks 'my-console-look)


; from http://www.emacswiki.org/emacs/AngryFruitSalad
(defun egoge-wash-out-colour (colour &optional degree)
  "Return a colour string specifying a washed-out version of COLOUR."
  (let ((basec (color-values
                (face-attribute 'default :foreground)))
        (col (color-values colour))
        (list nil))
    (unless degree (setq degree 2))
    (while col
      (push (/ (/ (+ (pop col)
                     (* degree (pop basec)))
                  (1+ degree))
               256)
            list))
    (apply 'format "#%02x%02x%02x" (nreverse list))))

(defun egoge-wash-out-face (face &optional degree)
  "Make the foreground colour of FACE appear a bit more pale."
  (let ((colour (face-attribute face :foreground)))
    (unless (eq colour 'unspecified)
      (set-face-attribute face nil
                          :foreground (egoge-wash-out-colour colour degree)))))

(defun egoge-find-faces (regexp)
  "Return a list of all faces whose names match REGEXP."
  (delq nil
        (mapcar (lambda (face)
                  (and (string-match regexp
                                     (symbol-name face))
                       face))
                (face-list))))

(defun egoge-wash-out-fontlock-faces (&optional degree)
  (mapc (lambda (elt)
          (egoge-wash-out-face elt degree))
        (delq 'font-lock-warning-face
              (egoge-find-faces "^font-lock"))))

(defun washout-face-colors()
  (interactive)
  (when (> (length (defined-colors)) 16)
    (egoge-wash-out-fontlock-faces 1)))


;;;;;;;;;;;;;;;;;;;;;;;; Good Fonts ;;;;;;;;;;;;;;;;;;;;;;;
;; -windows-dina-medium-r-normal--13-80-96-96-c-70-iso8859-1
;; -xos4-terminus-medium-r-normal--12-120-72-72-c-60-iso10646-1
;; -schumacher-clean-medium-r-normal--13-130-75-75-c-80-iso646.1991-irv
;; -lfp-bright-medium-r-normal--9-90-75-75-c-60-iso10646-1
;; -lfp-gamow-medium-r-normal--9-90-75-75-c-90-iso10646-1
;; -lfp-gamow-medium-r-semicondensed--8-80-75-75-c-70-iso10646-1
;; -lfp-lomonosov v-medium-r-normal--10-100-75-75-p-90-iso8859-1
;; -lfp-vizing-medium-r-normal--12-120-75-75-p-50-iso10646-1
;; -lfp-asimov-medium-r-normal--8-80-75-75-c-80-iso10646-1
;; -lfp-artsie-medium-r-normal--9-90-75-75-c-60-iso10646-1
;; -lfp-bright-medium-r-normal--9-90-75-75-c-60-iso10646-1
;; -lfp-feynman-medium-r-normal--10-100-75-75-c-90-iso10646-1
;; -lfp-lucidaterminal-medium-r-normal--10-100-75-75-c-90-iso10646-1
;; -lfp-ocr-medium-r-normal--10-100-75-75-c-60-iso10646-1
;; -lfp-thin-medium-r-normal--9-90-75-75-c-90-iso10646-1
;; -lfp-trachtenberg-medium-r-normal--11-110-75-75-c-90-iso10646-1
;; -lfp-test-medium-r-normal--10-100-75-75-c-80-iso10646-1
;; -lfp-uniread-medium-r-normal--10-100-75-75-c-80-iso10646-1
;; -lfp-zin-medium-r-normal--9-90-75-75-c-80-iso10646-1
;; -lfp-zin-thin-r-normal--9-90-75-75-c-80-iso10646-1
;; -windows-proggyclean-medium-r-normal--13-80-96-96-c-70-iso8859-1
;; -windows-speedy-medium-r-normal--11-80-96-96-c-70-iso8859-1
;; -adobe-symbol-medium-r-normal--12-120-75-75-p-74-adobe-fontspecific
;; -mplus-fxd-medium-r-normal--10-100-75-75-c-60-iso8859-15
;; -mplus-gothic-medium-r-normal--12-120-75-75-c-120-jisx0208.1990-0
;; -mplus-hlv-medium-r-normal--12-120-75-75-p-60-iso8859-15
;; -mplus-sys-medium-r-normal--10-100-75-75-p-60-iso8859-15
;; -sun-open look cursor-----12-120-75-75-p-160-sunolcursor-1
;; -sun-open look glyph-----12-120-75-75-p-113-sunolglyph-1
;; lucidasanstypewriter-12
;; -adobe-helvetica-medium-r-normal--12-120-75-75-p-67-iso10646-1
;; -b&h-lucidatypewriter-medium-r-normal-sans-12-120-75-75-m-70-iso10646-1
;; -misc-fixed-bold-r-normal--14-130-75-75-c-70-iso10646-1


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Custom macros & functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;; macros  ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; custom macros
(fset 'set_bookmark
      [?\M-x ?p ?o ?i ?n ?t ?- ?t ?o ?- ?r ?e ?g ?i ?s ?t ?e ?r return ?0])

(fset 'goto_bookmark
      [?\M-x ?r ?e ?g ?i ?s ?t ?e ?r ?- ?t ?o ?- ?p ?o ?i ?n ?t return ?0])


;;;;;;;;;;;;;;;;;;;;;;;;; files   ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; from http://splash-of-open-sauce.blogspot.com/2009/03/opening-file-as-root.html
(defun find-alternative-file-with-sudo ()
  "Open current buffer as root!"
  (interactive)
  (when buffer-file-name
    (find-alternate-file
     (concat "/su:root@localhost:"
             buffer-file-name))))

(defface find-file-root-header-face
  '((t (:foreground "white" :background "red3")))
  "*Face use to display header-lines for files opened as root.")

(defun find-file-root-header-warning ()
  "*Display a warning in header line of the current buffer.
   This function is suitable to add to `find-file-root-hook'."
  (let* ((warning "WARNING: EDITING FILE AS ROOT!")
         (space (+ 6 (- (window-width) (length warning))))
         (bracket (make-string (/ space 2) ?-))
         (warning (concat bracket warning bracket)))
    (setq header-line-format
          (propertize warning 'face 'find-file-root-header-face))))

(defun find-file-hook-root-header-warning ()
  (when (and buffer-file-name (string-match "root@localhost" buffer-file-name))
    (find-file-root-header-warning)))

(add-hook 'find-file-hook 'find-file-hook-root-header-warning)

;;;;; from http://nflath.com/2009/10/emacs-settings/
(defun google (query)
  "googles a query"
  (interactive "sQuery:")
  (browse-url (concat "http://www.google.com/search?q=" query)))


;;;;;;;;;;;;;;;;;;;;;;;;; buffers ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; ISR. buffers
(defun my-kill-current-buffer ()
  "kill current buffer, don't destroy window"
  (interactive)
  (kill-buffer (current-buffer)))

(defun my-kill-current-buffer-destroy ()
  "kill current buffer, and destroy window"
  (interactive)
  (kill-buffer (current-buffer))
  (delete-window))

(defun my-kill-other-buffer ()
  "kill other buffer, don't destroy window"
  (interactive)
  (if (not (one-window-p))
      (kill-buffer (window-buffer (next-window)))))

(defun my-kill-other-buffer-destroy ()
  "kill other buffer, and destroy window"
  (interactive)
  (if (not (one-window-p))
      (let ((nw (next-window)))
        (kill-buffer (window-buffer nw))
        (delete-window nw))))

(defun my-buffers-equal ()
  "Show same buffer in both windows"
  (interactive)
  (if (not (one-window-p))
      ((lambda ()
         (switch-to-buffer-other-window (current-buffer))
         (other-window 1)))))

(defun my-switch-buffers ()
  "Switch windows buffers"
  (interactive)
  (if (not (one-window-p))
      (let ((ob (window-buffer (next-window))))
        (set-window-buffer (next-window) (current-buffer))
        (set-window-buffer (selected-window) ob))))

;;;;; my own defined functions for buffers movement -> NOT USED
(defun get-buffers-list ()
  """get filtered and alphabetically sorted list of buffers"
  (let ((bufferlist (mapcar (function buffer-name) (buffer-list)))
        list)
    (dolist (b bufferlist)
      (let ((fc (substring b 0 1)))
        (if (and (not (string-equal fc "*")) (not (string-equal fc " ")))
            (push b list))))
    (sort list 'string<)))

(defun my-next-buffer ()
  "My own version of next-buffer. Don't show internal buffers"
  (interactive)
  (let ((buffername (buffer-name (current-buffer)))
        (bufferlist (get-buffers-list)))
    (setq list2 (cdr (member buffername bufferlist)))
    ;; (if list2
    ;;     (setq nextbuffer (car list2))
    ;;   (setq nextbuffer (car bufferlist)))
    (setq nextbuffer (or (car list2) (car bufferlist)))
    (switch-to-buffer nextbuffer)))

(defun my-previous-buffer ()
  "My own version of previous-buffer. Don't show internal buffers"
  (interactive)
  (let ((buffername (buffer-name (current-buffer)))
        (bufferlist (reverse (get-buffers-list))))
    (setq list2 (cdr (member buffername bufferlist)))
    ;; (if list2
    ;;     (setq prevbuffer (car list2))
    ;;   (setq prevbuffer (car bufferlist)))
    (setq prevbuffer (or (car list2) (car bufferlist)))
    (switch-to-buffer prevbuffer)))


;;;;;;;;;;;;;;;;;;;;;  movement  ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; from http://www.masteringemacs.org/articles/2011/01/14/effective-editing-movement/
(defvar smart-use-extended-syntax nil
  "If t the smart symbol functionality will consider extended
syntax in finding matches, if such matches exist.")

(defvar smart-last-symbol-name ""
  "Contains the current symbol name.

This is only refreshed when `last-command' does not contain
either `smart-symbol-go-forward' or `smart-symbol-go-backward'")

(make-local-variable 'smart-use-extended-syntax)

(defvar smart-symbol-old-pt nil
  "Contains the location of the old point")

(defun smart-symbol-goto (name direction)
  "Jumps to the next NAME in DIRECTION in the current buffer.

DIRECTION must be either `forward' or `backward'; no other option
is valid."

  ;; if `last-command' did not contain
  ;; `smart-symbol-go-forward/backward' then we assume it's a
  ;; brand-new command and we re-set the search term.
  (unless (memq last-command '(smart-symbol-go-forward
                               smart-symbol-go-backward))
    (setq smart-last-symbol-name name))
  (setq smart-symbol-old-pt (point))
  (message (format "%s scan for symbol \"%s\""
                   (capitalize (symbol-name direction))
                   smart-last-symbol-name))
  (unless (catch 'done
            (while (funcall (cond
                             ((eq direction 'forward) ; forward
                              'search-forward)
                             ((eq direction 'backward) ; backward
                              'search-backward)
                             (t (error "Invalid direction"))) ; all others
                            smart-last-symbol-name nil t)
              (unless (memq (syntax-ppss-context
                             (syntax-ppss (point))) '(string comment))
                (throw 'done t))))
    (goto-char smart-symbol-old-pt)))

(defun smart-symbol-go-forward ()
  "Jumps forward to the next symbol at point"
  (interactive)
  (smart-symbol-goto (smart-symbol-at-pt 'end) 'forward))

(defun smart-symbol-go-backward ()
  "Jumps backward to the previous symbol at point"
  (interactive)
  (smart-symbol-goto (smart-symbol-at-pt 'beginning) 'backward))

(defun smart-symbol-at-pt (&optional dir)
  "Returns the symbol at point and moves point to DIR (either `beginning' or `end') of the symbol.

If `smart-use-extended-syntax' is t then that symbol is returned
instead."
  (with-syntax-table (make-syntax-table)
    (if smart-use-extended-syntax
        (modify-syntax-entry ?. "w"))
    (modify-syntax-entry ?_ "w")
    (modify-syntax-entry ?- "w")
    ;; grab the word and return it
    (let ((word (thing-at-point 'word))
          (bounds (bounds-of-thing-at-point 'word)))
      (if word
          (progn
            (cond
             ((eq dir 'beginning) (goto-char (car bounds)))
             ((eq dir 'end) (goto-char (cdr bounds)))
             (t (error "Invalid direction")))
            word)
        (error "No symbol found")))))


;;;;;;;;;;;;;;;;;;;;;;;;;  edit  ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; copy & comment, by Rob Walker
;;;;; from http://www.tenfoot.org.uk/emacs/snippets.html
(defun duplicate-region (beg end &optional sep)
  "Duplicate the region"
  (interactive "*r")
  (let ((p (point)))
    (copy-region-as-kill beg end)
    (message "%d" (point))
    (goto-char end)
    (if (stringp sep) (insert sep))
    (yank)
    (goto-char p)))

(defun duplicate-line-or-region ()
  "duplicate the region if active otherwise the current line"
  (interactive)
  (if mark-active
      (duplicate-region (point) (mark))
    (duplicate-region (point-at-bol) (point-at-eol) "\n")))

(defvar comment-insert-block-on-empty-line t
  "Wether to insert block comments on empty lines in comment-insert")

(defun comment-insert ()
  "Insert a new comment on current line"
  (interactive)
  (let ((empty-line (save-excursion (beginning-of-line) (looking-at "\\s-*$"))))
    (if (and (not (equal (point) (point-at-bol)))
             (save-excursion (backward-char) (looking-at "\\S-")))
        ;; insert space if immediately preceding char not whitespace
        (insert " "))
    (insert comment-start)
    (if (and empty-line comment-insert-block-on-empty-line)
        (comment-indent-new-line))
    (save-excursion
      (if (and empty-line comment-insert-block-on-empty-line)
          (insert-and-inherit ?\n))
      (insert comment-end)
      (indent-for-tab-command))
    (indent-for-tab-command)))

(defun comment-line-or-region (&optional comment-eol)
  "comment the region if active otherwise comment the current line"
  (interactive "P")
  (if mark-active
      (comment-region (point) (mark))
    (if (or comment-eol
            (save-excursion (beginning-of-line) (looking-at "\\s-*$")))
        (comment-insert)
      (comment-region (point-at-bol) (point-at-eol)))))

(defun uncomment-line-or-region ()
  "uncomment the region if active otherwise comment the current line"
  (interactive)
  (if mark-active
      (uncomment-region (point) (mark))
    (uncomment-region (point-at-bol) (point-at-eol))))

(defun copy-and-comment-region (beg end &optional sep)
  "Duplicate the region and comment out the original"
  (interactive "*r")
  (duplicate-region beg end sep)
  (comment-region beg end))

(defun copy-and-comment-line-or-region ()
  "duplicate & comment the region if active otherwise the current line"
  (interactive)
  (if mark-active
      (copy-and-comment-region (point) (mark))
    (copy-and-comment-region (point-at-bol) (point-at-eol) "\n")))

;; from http://ifaedi.insa-lyon.fr/~atollenaere/emacs.html
(defun comment-or-uncomment-line (&optional lines)
  "Comment current line. Argument gives the number of lines
   forward to comment"
  (interactive "P")
  (comment-or-uncomment-region (point-at-bol) (point-at-eol)))

;; on gnu.emacs.help 2008/08/20, by Andreas Politz
(defun move-text-internal (arg)
  (cond
   ((and mark-active transient-mark-mode)
    (if (> (point) (mark))
        (exchange-point-and-mark))
    (let ((column (current-column))
          (text (delete-and-extract-region (point) (mark))))
      (forward-line arg)
      (move-to-column column t)
      (set-mark (point))
      (insert text)
      (exchange-point-and-mark)
      (setq deactivate-mark nil)))
   (t
    (beginning-of-line)
    (when (or (> arg 0) (not (bobp)))
      (forward-line)
      (when (or (< arg 0) (not (eobp)))
        (transpose-lines arg))
      (forward-line -1)))))

(defun move-text-down (arg)
  "Move region (transient-mark-mode active) or current line
  arg lines down."
  (interactive "*p")
  (move-text-internal arg))

(defun move-text-up (arg)
  "Move region (transient-mark-mode active) or current line
  arg lines up."
  (interactive "*p")
  (move-text-internal (- arg)))

;; from basic-edit-toolkit.el, by Andy Stewart
(defun delete-chars-hungry-forward (&optional reverse)
  "Delete chars forward use `hungry' style.
Optional argument REVERSE default is delete forward, if reverse is non-nil delete backward."
  (interactive)
  (delete-region
   (point)
   (progn
     (if reverse
         (skip-chars-backward " \t\n\r")
       (skip-chars-forward " \t\n\r"))
     (point))))

(defun delete-chars-hungry-backward ()
  "Delete chars backward use `hungry' style."
  (interactive)
  (delete-chars-hungry-forward t))

(defun underline-line-with (char)
  "Insert some char below at current line."
  (interactive "cType one char: ")
  (save-excursion
    (let ((length (- (point-at-eol) (point-at-bol))))
      (end-of-line)
      (insert "\n")
      (insert (make-string length char)))))

(defun goto-column (number)
  "Untabify, and go to a column NUMBER within the current line (0 is beginning of the line)."
  (interactive "nColumn number: ")
  (move-to-column number t))

;; from http://xahlee.org/emacs/emacs_kill-ring.html
(defun my-delete-word (arg)
  "Delete characters forward until encountering the end of a word.
With argument, do this that many times.
This command does not push erased text to kill-ring."
  (interactive "p")
  (delete-region (point) (progn (forward-word arg) (point))))

(defun my-backward-delete-word (arg)
  "Delete characters backward until encountering the beginning of a word.
With argument, do this that many times.
This command does not push erased text to kill-ring."
  (interactive "p")
  (my-delete-word (- arg)))

;;;;; ISR, comment/uncomment
(defun my-comment-or-uncomment-region-or-line ()
  "Comment or uncomment region or line"
  (interactive)
  (if (and mark-active transient-mark-mode)
      (comment-or-uncomment-region (region-beginning) (region-end))
    (comment-or-uncomment-line)))

;; from http://www.emacswiki.org/emacs-en/CopyingWholeLines
(defadvice kill-ring-save (before slick-copy activate compile)
  "When called interactively with no active region, copy a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (message "Copied line")
     (list (line-beginning-position)
           (line-beginning-position 2)))))

(defadvice kill-region (before slick-cut activate compile)
  "When called interactively with no active region, kill a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
           (line-beginning-position 2)))))

;; from http://www.emacswiki.org/emacs-en/AutoIndentation
(defun back-to-indentation-or-beginning ()
  (interactive)
  (if (= (point) (progn (back-to-indentation) (point)))
      (beginning-of-line)))

(defun kill-and-join-forward (&optional arg)
  "If at end of line, join with following; otherwise kill line.
   Deletes whitespace at join."
  (interactive "POINT")
  (if (and (eolp) (not (bolp)))
      (delete-indentation t)
    (kill-line arg)))

;; zap-back-to-char
(defun zap-back-to-char (&optional arg char)
  (interactive "p\ncZap to char: ")
  (zap-to-char (- arg) char))

(defun clean-up-buffer-or-region ()
  "Untabifies, indents and deletes trailing whitespace from buffer or region."
  (interactive)
  (save-excursion
    (unless (region-active-p)
      (mark-whole-buffer))
    (untabify (region-beginning) (region-end))
    (indent-region (region-beginning) (region-end))
    (save-restriction
      (narrow-to-region (region-beginning) (region-end))
      (delete-trailing-whitespace))))

(defun smart-tab ()
  "This smart tab is minibuffer compliant: it acts as usual in
   the minibuffer. Else, if mark is active, indents region. Else if
   point is at the end of a symbol, expands it. Else indents the
   current line."
  (interactive)
  (if (minibufferp)
      (unless (minibuffer-complete)
        (dabbrev-expand nil))
    (if mark-active
        (indent-region (region-beginning)
                       (region-end))
      (if (looking-at "\\_>")
          ;; (hippie-expand nil)
          (dabbrev-expand nil)
        (indent-for-tab-command)))))

;;;;; from http://www.emacswiki.org/cgi-bin/wiki/TabCompletion
;; (defun indent-or-complete ()
;;       "Complete if point is at end of line, and indent line."
;;       (interactive)
;;       (if (looking-at "$")
;;           (hippie-expand nil))
;;       (indent-for-tab-command))

;; not needed anymore
;; (defun my-copy-line-as-kill (&optional arg)
;;   "Copy current line/s to kill ring."
;;   (interactive "p")
;;   (kill-ring-save (line-beginning-position)
;;                   (line-beginning-position (+ 1 arg))))

;; ISR, mark
(defun my-mark-word (&optional arg)
  "Marks the whole word/s the cursor is placed on"
  (interactive "p")
  (skip-chars-backward "-_A-Za-z0-9")
  (mark-word arg))

(defun my-mark-line (&optional arg)
  "Marks the whole line/s the cursor is placed on"
  (interactive "p")
  (unless arg (setq arg 1))
  (forward-line arg)
  (push-mark nil t t)
  (forward-line (- arg)))

(defun my-mark-line2 (&optional arg)
  "Marks the whole line/s the cursor is placed on"
  (interactive "p")
  (unless arg (setq arg 1))
  (forward-line (- arg 1))
  (end-of-line)
  (push-mark nil t t)
  (forward-line (- 1 arg))
  (back-to-indentation))

(defun my-mark-sexp (&optional arg)
  "Marks the whole expresion"
  (interactive "p")
  (backward-sexp)
  (mark-sexp))


;;;;;;;;;;;;;;;;;;;;;;;;;  zoom  ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Cycle font sizes - http://www.emacswiki.org/cgi-bin/wiki/CycleFontSizes
; Firefox-like zooming of fonts.
(setq font-zoom-index default-font-zoom-index)

(defun set-font (font-idx)
  (set-frame-font (nth font-idx FONTSLIST))
  (message (nth font-zoom-index FONTSLIST)))

(defun font-zoom-increase-font-size ()
  (interactive)
  (setq font-zoom-index (min (- (length FONTSLIST) 1)
                             (+ font-zoom-index 1)))
  (set-font font-zoom-index))

(defun font-zoom-decrease-font-size ()
  (interactive)
  (setq font-zoom-index (max 1
                             (- font-zoom-index 1)))
  (set-font font-zoom-index))

(defun font-zoom-reset-font-size ()
  (interactive)
  (setq font-zoom-index default-font-zoom-index)
  (set-font font-zoom-index))

;; (set-frame-font (nth font-zoom-index FONTSLIST))
(set-font font-zoom-index)


;;;;;;;;;;;;;;;;;;;;;;;;;  devel ;;;;;;;;;;;;;;;;;;;;;;;;;
(defun grep-todofixme ()
  (interactive)
  (rgrep "\\(TODO\\|FIXME\\|XXX\\|BUG\\|NOTE\\|HACK\\|WARNING\\)" "*" "."))

;;;;; from http://orestis.gr/en/blog/2008/02/28/emacs-goals/
(defun find-tag-noconfirm ()
  (interactive)
  (find-tag (find-tag-default)))
;; TODO: if no tags are found, try and run ctags -Rne in the source root

;;;;; from http://blog.printf.net/articles/2007/10/15/productivity-a-year-on
(defun find-tag-at-point ()
  "*Find tag whose name contains TAGNAME.
  Identical to `find-tag' but does not prompt for
  tag when called interactively;  instead, uses
  tag around or before point."
  (interactive)
  (find-tag-at-point (if current-prefix-arg
                         (find-tag-tag "Find tag: "))
                     (find-tag (find-tag-default))))


;;;;; from http://www.emacswiki.org/emacs-en/SeanO
(defun find-thing-at-point (&optional always-ask)
  (interactive "P")
  (let* ((at-point (thing-at-point 'symbol))
         (s (and at-point (intern at-point)))
         (v (or (variable-at-point)
                (and s (boundp s) s)))
         (f (or (function-called-at-point)
                (and s (fboundp s) s))))
    (push-mark (point) t)
    (cond
     (always-ask (call-interactively 'find-function))
     ((and v (not (numberp v)))
      (find-variable v))
     ((and f (subrp (symbol-function f)))
      (let ((buf-pos (find-function-search-for-symbol
                      f nil (help-C-file-name (symbol-function f) 'subr))))
        (and (car buf-pos) (pop-to-buffer (car buf-pos)))))
     (f (find-function f))
     (t (call-interactively 'find-function)))))

(defun hash-table-keys (hash)
  (let ((ret nil))
    (maphash (lambda (k v) (push k ret)) hash)
    ret))

(defun my-semanticdb-minor-mode-p ()
  "Query if the current buffer has Semanticdb mode enabled."
  (condition-case blah
      (and (semanticdb-minor-mode-p)
           (eq imenu-create-index-function
               'semantic-create-imenu-index))
    (error nil)))

(defun my-icompleting-read (prompt choices)
  (flet ((ido-make-buffer-list (default)
                               (setq ido-temp-list choices)))
    (ido-read-buffer prompt)))

(defun my-jump-to-function ()
  "Jump to a function found by either Semantic or Imenu within then
  current buffer."
  (interactive)
  (cond
   ((my-semanticdb-minor-mode-p) (my-semantic-jump-to-function))
   ((boundp 'imenu-create-index-function) (my-imenu-jump-to-function))))

(defun my-imenu-jump-to-function ()
  "Jump to a function found by Semantic within the current buffer
  with ido-style completion."
  (interactive)
  (save-excursion
    (setq imenu--index-alist (funcall imenu-create-index-function)))
  (let ((thing (assoc
                (my-icompleting-read "Go to: "
                                     (mapcar #'car imenu--index-alist))
                imenu--index-alist)))
    (when thing
      (funcall imenu-default-goto-function (car thing) (cdr thing))
      (recenter))))

(defun my-semantic-jump-to-function ()
  "Jump to a function found by Semantic within the current buffer
  with ido-style completion."
  (interactive)
  (let ((tags
         (remove-if
          (lambda (x)
            (or (getf (semantic-tag-attributes x) :prototype-flag)
                (not (member (cadr x) '(function variable type)))))
          (semanticdb-file-stream (buffer-file-name (current-buffer)))))
        (names (make-hash-table :test 'equal)))
    (dolist (tag tags)
      (let ((sn (semantic-tag-name tag)))
        (when (gethash sn names)
          (setq sn
                (loop for i = 1 then (1+ i)
                      for name = (format "%s<%d>" sn i)
                      while (gethash name names)
                      finally return name)))
        (puthash sn tag names)))
    (goto-char (semantic-tag-start
                (gethash
                 (my-icompleting-read "Go to: " (hash-table-keys names))
                 names)))
    (recenter)))


;;;;;;;;;;;;;;;;;;;;;;;;;  misc  ;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; ISR, useful functions
(defvar my-narrow-toggle-state nil
  "List of wide/narrow states of buffers")
;; (make-variable-buffer-local 'my-narrow-toggle-state)
(defun my-narrow-toggle ()
  "Narrow/wide defun"
  (interactive)
  (let ((cb (current-buffer)))
    (if (memq cb my-narrow-toggle-state)
        (progn
          (widen)
          (recenter)
          (setq my-narrow-toggle-state (delq cb my-narrow-toggle-state)))
      (progn
        (if mark-active
            (progn
              (narrow-to-region (point) (mark))
              (pop-mark))
          (narrow-to-defun)
          (add-to-list 'my-narrow-toggle-state cb))))))

(defun insert-date-es ()
  "Insert date at the current cursor position in the current buffer."
  (interactive "*")
  (insert (format-time-string "%a %b %d %T %Y"))) ;"%d.%m.%Y %H:%M"

(defun insert-date-en ()
  "Insert date at the current cursor position in the current buffer."
  (interactive "*")
  (insert (current-time-string)))

(defun ascii-table ()
  "Print an ASCII table. Based on a defun by Alex Schroeder <asc@bsiag.com>"
  (interactive)
  (switch-to-buffer "*ASCII*")  (erase-buffer)
  (insert (format "ASCII characters up to number %d.\n" 255))
  (let ((i 0))
    (while (<= i 127)
      (setq j (+ i 128))
      (insert (format "%4d | o%03o | 0x%02x | %c     %4d | o%03o | 0x%02x | %c\n" i i i i j j j j))
      (setq i (+ i 1))
      ))
  (beginning-of-buffer))

;;;;; from http://stormcoders.blogspot.com/2007/09/elisp-functions-for-emacs.html
(defun ascii-table2 (&optional extended)
  "Print the ascii table (up to char 127). Given an optional argument, print up to char 255."
  (interactive "P")
  (defvar col)
  (defvar limit)
  (setq limit 127)
  (if (null extended)
      (setq limit 255))
  (setq col (/ (+ 1 limit) 4))
  (switch-to-buffer "*ASCII*")
  (erase-buffer)
  (insert (format "ASCII characters up to %d. (00 is NULL character)\n\n" limit))
  (insert " DEC OCT HEX CHAR\t DEC OCT HEX CHAR\t DEC OCT HEX CHAR\t DEC OCT HEX CHAR\n")
  (insert " ----------------\t ----------------\t ----------------\t ----------------\n")
  (let ((i 0) (right 0) (tab-width 4))
    (while (< i col)
      (setq col2 (+ i col))
      (setq col3 (+ i (* col 2)))
      (setq col4 (+ i (* col 3)))
      ; special condition to insert a <TAB> instead of an actual tab
      (cond
       ((= i 9)
        (insert (format "%4d%4o%4x  <TAB>\t%4d%4o%4x%4c\t%4d%4o%4x%4c\t%4d%4o%4x%4c\n"
                        i i i  col2 col2 col2 col2 col3 col3 col3 col3 col4 col4 col4 col4)))
       ; special conditon to insert a <LF> instead of an actual line feed
       ((= i 10)
        (insert (format "%4d%4o%4x  <LF>\t%4d%4o%4x%4c\t%4d%4o%4x%4c\t%4d%4o%4x%4c\n"
                        i i i  col2 col2 col2 col2 col3 col3 col3 col3 col4 col4 col4 col4)))
       (t
        ; insert the actual character
        (insert (format "%4d%4o%4x%4c>\t%4d%4o%4x%4c\t%4d%4o%4x%4c\t%4d%4o%4x%4c\n"
                        i i i i col2 col2 col2 col2 col3 col3 col3 col3 col4 col4 col4 col4))))
      (setq i (+ i 1))))
  (beginning-of-buffer)
  (local-set-key "q" (quote bury-buffer)))

;;;;; tip of the day
;;;;; http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/1a8dfab1a41b60/05a4fb2c0ef61ab3?lnk=st&q=emacs+function+of+the+day&rnum=3&hl=en#05a4fb2c0ef61ab3
(defun totd ()
  (interactive)
  (with-output-to-temp-buffer "*Tip of the day*"
    (let* ((commands (loop for s being the symbols
                           when (commandp s) collect s))
           (command (nth (random (length commands)) commands)))
      (princ
       (concat "Your tip for the day is:\n========================\n\n"
               (describe-function command)
               "\n\nInvoke with:\n\n"
               (with-temp-buffer
                 (where-is command t)
                 (buffer-string)))))))

(defun minimap-toggle ()
  "Show minimap if hidden, hide if present."
  (interactive)
  (if (and minimap-bufname
	       (get-buffer minimap-bufname)
	       (get-buffer-window (get-buffer minimap-bufname)))
      (minimap-kill)
    (minimap-create)))

;;;;; from http://pocoo.org/~gbrandl/dotemacs
(defun fullscreen ()
  (interactive)
  (set-frame-parameter nil 'fullscreen
                       (if (frame-parameter nil 'fullscreen) nil 'fullboth)))

;;;;; from http://journal.dedasys.com/2009/11/16/emacs-fiddling-show-the-menu-bar-when-the-mouse-is-near-the-top-of-the-frame
(defun menu-bar-show-hide-helper ()
  (if (< (cddr (mouse-pixel-position)) 50)
      (menu-bar-mode 1)
    (menu-bar-mode 0)))

(defun menu-bar-show-hide ()
  (interactive)
  (run-with-idle-timer 0.1 t 'menu-bar-show-hide-helper))

;; (defconst animate-n-steps 5)
;; (defun emacs-reloaded ()
;;   (interactive)
;;   (animate-string (concat ";; Initialization successful, welcome to "
;;     (substring (emacs-version) 0 16)
;;   ".")
;;   0 0)
;;   (newline-and-indent)  (newline-and-indent))
;; (add-hook 'after-init-hook 'emacs-reloaded)

;;;;; from http://osdir.com/ml/emacs.help/2002-12/msg00642.html
;; .bashrc:   ve () { emacsclient -t -e "(eless \"$*\")" }
(defun eless (&rest args)
  "Invoke `view-file' on the file.
   \"less +42 foo\" also goes to line 42 in the buffer."
  (interactive)
  (while args
    (if (string-match "\\`\\+\\([0-9]+\\)\\'" (car args))
        (let* ((line (string-to-number (match-string 1 (pop args))))
               (file (pop args)))
          (view-file file)
          (goto-line line))
      (view-file (pop args)))))

;; (defun eless (&rest args)
;;   "Invoke `view-file' on the given file(s)."
;;   (interactive)
;;   (while args (view-file (pop args))))

;;;;; from basic-edit-toolkit.el, by Andy Stewart
(defvar point-stack nil)

(defun point-stack-push ()
  "Push current point in stack."
  (interactive)
  (message "Location marked.")
  (setq point-stack (cons (list (current-buffer) (point)) point-stack)))

(defun point-stack-pop ()
  "Pop point from stack."
  (interactive)
  (if (null point-stack)
      (message "Stack is empty.")
    (switch-to-buffer (caar point-stack))
    (goto-char (cadar point-stack))
    (setq point-stack (cdr point-stack))))

;;;;; from http://stackoverflow.com/questions/7398216/how-can-i-apply-a-hook-to-multiple-emacs-modes-at-once
(defun my-add-to-multiple-hooks (function hooks)
  (mapc (lambda (hook)
          (add-hook hook function))
        hooks))

;;;;; from
(defun shorten-directory (dir max-length)
  "Show up to `max-length' characters of a directory name `dir'."
  (let ((path (reverse (split-string (abbreviate-file-name dir) "/")))
        (output ""))
    (when (and path (equal "" (car path)))
      (setq path (cdr path)))
    (while (and path (< (length output) (- max-length 4)))
      (setq output (concat (car path) "/" output))
      (setq path (cdr path)))
    (when path
      (setq output (concat ".../" output)))
    output))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Python
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'python)
(setq python-shell-interpreter "ipython"
      python-shell-interpreter-args ""
      python-shell-prompt-regexp "In \\[[0-9]+\\]: "
      python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
      python-shell-completion-setup-code ""
      python-shell-completion-string-code "';'.join(__IP.complete('''%s'''))\n")

;; ; for python-mode.el, python.el detection is automatic
;; (autoload 'python-mode "python-mode" "Python Mode." t)
;; (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
;; (add-to-list 'interpreter-mode-alist '("python" . python-mode))

(add-hook 'python-mode-hook
          '(lambda ()
             (setq-default indent-tabs-mode nil)
             ;; (setq python-mode-abbrev-table nil)  ; don't want default python templates/skeleton
             ;; ; python-mode.el
             ;; (set (make-variable-buffer-local 'beginning-of-defun-function)
             ;;      'py-beginning-of-def-or-class)
             ;; (setq outline-regexp "def\\|class ")
             ;; (outline-minor-mode t)               ; use hide/show mode instead
             ;; (imenu-add-menubar-index)
             ;; (eldoc-mode 1)
             ;; (turn-on-eldoc-mode)
             ;; (local-set-key (kbd "<tab>") 'indent-or-complete)
             ;; (local-set-key '[A-tab] 'symbol-complete) ; default M-tab
                                        ; python.el
             (local-set-key "\C-m" 'newline-and-indent) ; py-newline-and-indent
             (local-unset-key "\C-c\C-f")                         ; defined as C-ch
             (local-unset-key "\C-c\C-p")
             (local-unset-key "\C-c\C-n")                         ; collide with nav
             (local-unset-key "\C-c\C-d")                         ; my-org-journal-add-entry
             ;; ; python-mode.el
             ;; (local-unset-key "\C-c\C-h")                         ; defined as C-ch
             ;; (local-set-key "\C-ch" 'py-help-at-point)            ; default C-cC-h
             ;; (local-set-key '[?\C-c up] 'py-beginning-of-def-or-class)
             ;; (local-set-key '[?\C-c down] 'py-end-of-def-or-class)
                                        ; flymake
             (flymake-mode)
             ;; (python-flymake "pylint")
             (python-flymake "pyflakes")
             ))

(defun my-python-describe-symbol ()
  (interactive)
  (let ((symbol (with-syntax-table python-dotty-syntax-table (current-word))))
    (if (eq symbol nil)
        (python-describe-symbol "")
      (python-describe-symbol symbol))))

;;;;; IPython
;; (require 'ipython)
;; (setq python-python-command "ipython")
;; (setq python-python-command-args '( "-colors" "Linux"))
;; (setq py-python-command "ipython")
;; (setq py-python-command-args '( "-colors" "Linux"))
;; (setq ipython-completion-command-string "print(';'.join(__IP.Completer.all_completions('%s')))\n")

;; ;;;;; pyrex mode
;; (autoload 'pyrex-mode "pyrex-mode" "Pyrex mode" t)
;; (setq auto-mode-alist
;;    (cons '("\\.pyx$" . pyrex-mode) auto-mode-alist))

;; ;;;;; pymacs
;; (require 'pymacs)

;; ;;;;; gpycomplete
;; (setq pymacs-load-path (append pymacs-load-path '("/home/inigo/.emacsmine/pymacs_dir/")))
;; (require 'gpycomplete)

;; ;;;;; pysmell
;; (require 'pysmell)
;; (add-hook 'python-mode-hook (lambda () (pysmell-mode 1)))

;; ;;;;; ropemacs
;; (pymacs-load "ropemacs" "rope-")
;; (setq ropemacs-guess-project t
;;       ropemacs-enable-shortcuts nil)

;;;;; pychecker, pylint, pyflakes
(setq pychecker-regexp-alist
      '(("\\([a-zA-Z]?:?[^:(\t\n]+\\)[:( \t]+\\([0-9]+\\)[:) \t]" 1 2)))

(defun python-check-program (program args)
  "Run 'cmd' against the file behind the current buffer after
  checking if unsaved buffers should be saved."
  (let* ((file (buffer-file-name (current-buffer)))
         (command (concat program " " args " \"" file "\"")))
    (save-some-buffers (not compilation-ask-about-save) nil) ; save  files.
    (compile-internal command "No more errors or warnings" program
                      nil pychecker-regexp-alist)))

(defun pychecker ()
  (interactive)
  (python-check-program "pychecker" "-t9vgna"))

(defun pylint ()
  (interactive)
  (python-check-program "pylint" "--output-format=parseable"))

(defun pyflakes ()
  (interactive)
  (python-check-program "pyflakes" ""))

;;;;; flymake-pylint, flymake-pyflakes; from PythonMode emacs wiki
(defun flymake-prog-init (program)
  (let* ((temp-file (flymake-init-create-temp-buffer-copy
                     'flymake-create-temp-inplace))
         (local-file (file-relative-name
                      temp-file
                      (file-name-directory buffer-file-name))))
    (list program (list local-file))))

(defun flymake-pylint-init ()
  (flymake-prog-init "epylint"))

(defun flymake-pyflakes-init ()
  (flymake-prog-init "pyflakes"))

(defun python-flymake (program)
  "Activate flymake with python lint program specified as argument"
  (when (load "flymake" t)
    (message program)
    (cond
     ((string= program "pylint")
      (add-to-list 'flymake-allowed-file-name-masks
                   '("\\.py\\'" flymake-pylint-init)))
     ((string= program "pyflakes")
      (add-to-list 'flymake-allowed-file-name-masks
                   '("\\.py\\'" flymake-pyflakes-init))))))

;;;;; pylookup: http://taesoo.org/Opensource/Pylookup
;(setq pylookup-dir "/home/inigo/.emacsmine/pylook/")
;(add-to-list 'load-path pylookup-dir)
;(eval-when-compile (require 'pylookup))
;(setq pylookup-program (concat pylookup-dir "/pylookup.py"))
;(setq pylookup-db-file (concat pylookup-dir "/pylookup.db"))
;(autoload 'pylookup-lookup "pylookup"
;  "Lookup SEARCH-TERM in the Python HTML indexes." t)
;(autoload 'pylookup-update "pylookup"
;  "Run pylookup-update and create the database at `pylookup-db-file'." t)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Development
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;; Customizations for all of c-mode, c++-mode, and objc-mode
(defconst my-c-style
  '((c-tab-always-indent        . nil)
    (c-comment-only-line-offset . 4)
    (c-hanging-braces-alist     . ((substatement-open after)
                                   (brace-list-open)))
    (c-hanging-colons-alist     . ((member-init-intro before)
                                   (inher-intro)
                                   (case-label after)
                                   (label after)
                                   (access-label after)))
    (c-cleanup-list             . (scope-operator
                                   empty-defun-braces
                                   defun-close-semi))
    (c-offsets-alist            . ((arglist-close . c-lineup-arglist)
                                   (substatement-open . 4)
                                   (case-label        . 4)
                                   (block-open        . 4)
                                   (knr-argdecl-intro . -)))
    (c-echo-syntactic-information-p . t)
    (setq c-font-lock-extra-types (quote ("FILE" "\\sw+_t" "Gdk\\sw*" "Gtk\\sw*" "Gnome\\sw*" "GLIB\\sw*" "GDK\\sw*" "GTK\\sw*" "GNOME\\sw*" "gint" "guint" "glong" "gulong" "gfloat" "gdouble" "gchar" "guchar" "gpointer" "GL\\sw*" "g_\\sw*" "gdk_\\sw*" "gtk_\\sw*" "gnome_\\sw*" "gl\\sw*")))
    )
  "My C Programming Style")

(add-hook 'c-mode-common-hook
          (lambda()
            (c-set-style "bsd") (setq c-basic-offset 4)
            ;; add my personal style and set it for the current buffer
            (c-add-style "PERSONAL" my-c-style t)
            ;; offset customizations not in my-c-stylex
            (c-set-offset 'member-init-intro '++)
            ;; we like auto-newline and hungry-delete
            (c-toggle-auto-hungry-state -1)
            ;; keybindings for all supported languages.  We can put these in
            ;; c-mode-base-map because c-mode-map, c++-mode-map, objc-mode-map,
            ;; java-mode-map, and idl-mode-map inherit from it.
            (define-key c-mode-base-map "\C-m" 'newline-and-indent)))

;;;;; js
(setq js-basic-offset 4
      js-use-font-lock-faces t)

;;;;; lua-mode
(setq auto-mode-alist (cons '("\\.lua$" . lua-mode) auto-mode-alist))
(autoload 'lua-mode "lua-mode" "Lua editing mode." t)
(add-hook 'lua-mode-hook
          (lambda()
            (local-unset-key "\C-c\C-f")                         ; defined as C-ch
            (local-set-key "\C-ch" 'lua-search-documentation)))

;;;;; vala
(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))
(add-hook 'vala-mode-hook #'wisent-csharp-default-setup)

;;;;; common devel -modes settings
(defun my-devel-modes-common-settings()
  (setq show-trailing-whitespace t)
  (hs-minor-mode 1)
  (linum-mode 1)
  (local-set-key '[tab] 'smart-tab))

(my-add-to-multiple-hooks
 'my-devel-modes-common-settings
 '(c-mode-common-hook
   python-mode-hook
   js-mode-hook
   emacs-lisp-mode-hook
   lua-mode-hook
   vala-mode-hook))

;;;;; nxhtml
(load "nxhtml/autostart.el")
(setq mumamo-chunk-coloring (quote no-chunks-colored))
(setq mumamo-global-mode t)
(setq nxhtml-global-minor-mode t)
(setq nxhtml-global-validation-header-mode t)
(setq nxhtml-skip-welcome t)

;;;;; rst package
(autoload 'rst "rst-mode" "reStructuredText mode" t)

;;;;; changelog
(add-hook 'change-log-mode-hook
          (lambda()
            (setq tab-width 4
                  left-margin 4
                  fill-column 78)))

;;;;; devel-notes
(require 'devel-notes)

;; ;;;;; dvc
;; (add-to-list 'load-path (concat my-elisp-dir "dvc"))
;; (require 'dvc-autoloads)

;;;;; aHg
(require 'ahg)

;;;;; eldoc
(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
(add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)
(add-hook 'ielm-mode-hook 'turn-on-eldoc-mode)

;;;;; devhelp, gtk-look
(require 'devhelp)
(require 'gtk-look)

(defun my-devhelp-search()
  (interactive)
  (let* ((query (read-from-minibuffer "Query? " (current-word))))
    (start-process-shell-command "devhelp" nil "devhelp" "-s" query)
    (set-process-query-on-exit-flag (get-process "devhelp") nil)))

(defun ido-gtk-lookup-search()
  (interactive)
  (let* ((query (read-from-minibuffer "Query? " (current-word)))
         (symbol (ido-completing-read "Choose: "
                                      (gtk-lookup-symbol-method-candidates query)))
         (entry (or (assoc symbol gtk-lookup-cache) ;; exact match preferred
                    (gtk-lookup-assoc-string-ignore-case
                     symbol gtk-lookup-cache))))    ;; otherwise case-fold
    (or entry
        (error "Unknown symbol %s" symbol))
    ;; (gtk-lookup-browse-url-other-window (concat "file://"
    (w3m-browse-url (concat "file://"
                            (nth 2 entry)     ;; dir
                            (nth 1 entry))))) ;; link

;; ;;;;; msf-abbrevs
;; (require 'msf-abbrev)
;; (setq-default abbrev-mode t)
;; (setq save-abbrevs nil)
;; (setq msf-abbrev-verbose t) ;; optional
;; (setq msf-abbrev-root (concat my-elisp-dir "mode-abbrevs"))
;; ;; (global-set-key (kbd "C-c l") 'msf-abbrev-goto-root)
;; ;; (global-set-key (kbd "C-c a") 'msf-abbrev-define-new-abbrev-this-mode)
;; ;; (msf-abbrev-load)
;; (defun load-abbrevs ()
;;   (interactive)
;;   (msf-abbrev-load))

;;;;; yasnippets
(require 'yasnippet)
(yas/initialize)
(yas/load-directory (concat my-elisp-dir "snippets"))
(setq yas/trigger-key (kbd "SPC"))
(define-key yas/keymap [tab] 'yas/next-field-group)
;; (setq yas/fallback-behaviour 'smart-tab)
;; (require 'dropdown-list)
;; (setq yas/prompt-functions '(yas/dropdown-prompt
;;                              yas/ido-prompt
;;                              yas/completing-prompt))

;;;;; eproject
(require 'eproject)
(require 'eproject-extras)
(require 'eproject-tags)

(define-project-type python (generic) (look-for "setup.py")
  :irrelevant-files ("\\.py[co]$"))
(define-project-type generic-hg (generic) (look-for ".hg")
  :irrelevant-files ("^[#]" ".hg/"))
(setq eproject-completing-read-function 'eproject--ido-completing-read
      eproject-tags-verbose nil
      eproject-todo-expressions '("TODO" "XXX" "FIXME" "NOTE" "BUG" "WARNING"))

(defun my-eproject-ido-buffer ()
  (interactive)
  (if (not eproject-root)
      (error "Buffer is not an eproject buffer!"))
  (switch-to-buffer
   (ido-completing-read "Buffer: "
                        (remove nil (mapcar (lambda (buffer)
                                              (let ((buffname (buffer-file-name buffer)))
                                                (if (and buffname (string-match eproject-root buffname))
                                                    (buffer-name buffer))))
                                            (buffer-list)))
                        nil t)))

;;;;; cedet package
(load-file "~/.emacsmine/cedet-1.0/common/cedet.el") ; not needed in v23.2+
(setq semanticdb-default-save-directory "~/.emacs.d/semanticdb"
      ede-project-placeholder-cache-file "~/.emacs.d/.projects.ede")
;; Emacs 23.2+ includes a limited version of cedet
;; (semantic-load-enable-excessive-code-helpers) ; not needed in v23.2+
;; (global-semantic-stickyfunc-mode -1)          ; not needed in v23.2+
;; (global-semantic-decoration-mode -1)          ; not needed in v23.2+
;; (global-ede-mode 1)                           ; don't use EDE
(semantic-load-enable-gaudy-code-helpers)
(semantic-toggle-decoration-style 'semantic-decoration-on-includes)
(global-semantic-stickyfunc-mode nil)
(global-semantic-decoration-mode nil)
(require 'semantic-ia)

;;;;; ecb package
(add-to-list 'load-path (concat my-elisp-dir "ecb-20100831"))
(require 'ecb-autoloads)                ; faster loading than (require 'ecb)
;; (set-face-font 'ecb-default-general-face "lucidasans-10")
(setq ecb-tip-of-the-day nil)
(setq ecb-layout-name "right2")
;; (setq ecb-layout-window-sizes '(("right2"
;;                                  (0.18 . 0.4915254237288136)
;;                                  (0.18 . 0.4915254237288136))
;;                                 ("right1"
;;                                  (0.18 . 0.2465753424657534)
;;                                  (0.18 . 0.3013698630136986)
;;                                  (0.18 . 0.4383561643835616))))
(setq ecb-layout-window-sizes nil)
(setq ecb-source-file-regexps '((".*" ("\\(^\\(\\.\\|#\\)\\|\\(~$\\|\\.\\(elc\\|obj\\|o\\|class\\|lib\\|dll\\|a\\|so\\|cache\\|pyc\\)$\\)\\)") ("^\\.\\(emacs\\|gnus\\)$"))))
(setq ecb-show-sources-in-directories-buffer (quote ("left7" "left13" "left14" "left15" "right2")))

;; ;;;;; load gnome-doc-mode
;; (load-library "gnome-doc")

;; ;;;;; load sad mode
;; (autoload 'sad "sad" "Disassemble HP48 memory" t)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; ido
(require 'ido)
(ido-mode t)
(setq ido-save-directory-list-file "~/.emacs.d/.ido.last"
      ido-enable-flex-matching t
      ido-everywhere t
      ido-create-new-buffer 'always
      ido-use-filename-at-point 'guess
      ido-use-url-at-point t
      ido-use-virtual-buffers nil) ;; new in emacs 24.x
;; to avoid problems with smarttab
;; from http://www.emacsblog.org/2008/05/19/giving-ido-mode-a-second-chance/
(add-hook 'ido-setup-hook
          (lambda ()
            (define-key ido-completion-map [tab] 'ido-complete)))

;; from http://www.emacswiki.org/emacs/InteractivelyDoThings
(defun my-ido-find-tag ()
  "Find a tag using ido"
  (interactive)
  (tags-completion-table)
  (let (tag-names)
    (mapc (lambda (x)
            (unless (integerp x)
              (push (prin1-to-string x t) tag-names)))
          tags-completion-table)
    (find-tag (ido-completing-read "Tag: " tag-names))))

(defun ido-find-file-in-tag-files ()
  (interactive)
  (save-excursion
    (let ((enable-recursive-minibuffers t))
      (visit-tags-table-buffer))
    (find-file
     (expand-file-name
      (ido-completing-read
       "Project file: " (tags-table-files) nil t)))))

(setq enable-recursive-minibuffers t)
(define-key ido-file-dir-completion-map [(meta control ?b)] 'ido-goto-bookmark)

(defun ido-goto-bookmark (bookmark)
  (interactive
   (list (bookmark-completing-read "Jump to bookmark"
                                   bookmark-current-bookmark)))
  (unless bookmark
    (error "No bookmark specified"))
  (let ((filename (bookmark-get-filename bookmark)))
    (ido-set-current-directory
     (if (file-directory-p filename)
         filename
       (file-name-directory filename)))
    (setq ido-exit        'refresh
          ido-text-init   ido-text
          ido-rotate-temp t)
    (exit-minibuffer)))

(defun ido-goto-symbol (&optional symbol-list)
  "Refresh imenu and jump to a place in the buffer using Ido."
  (interactive)
  (unless (featurep 'imenu)
    (require 'imenu nil t))
  (cond
   ((not symbol-list)
    (let ((ido-mode ido-mode)
          (ido-enable-flex-matching
           (if (boundp 'ido-enable-flex-matching)
               ido-enable-flex-matching t))
          name-and-pos symbol-names position)
      (unless ido-mode
        (ido-mode 1)
        (setq ido-enable-flex-matching t))
      (while (progn
               (imenu--cleanup)
               (setq imenu--index-alist nil)
               (ido-goto-symbol (imenu--make-index-alist))
               (setq selected-symbol
                     (ido-completing-read "Symbol? " symbol-names))
               (string= (car imenu--rescan-item) selected-symbol)))
      (unless (and (boundp 'mark-active) mark-active)
        (push-mark nil t nil))
      (setq position (cdr (assoc selected-symbol name-and-pos)))
      (cond
       ((overlayp position)
        (goto-char (overlay-start position)))
       (t
        (goto-char position)))))
   ((listp symbol-list)
    (dolist (symbol symbol-list)
      (let (name position)
        (cond
         ((and (listp symbol) (imenu--subalist-p symbol))
          (ido-goto-symbol symbol))
         ((listp symbol)
          (setq name (car symbol))
          (setq position (cdr symbol)))
         ((stringp symbol)
          (setq name symbol)
          (setq position
                (get-text-property 1 'org-imenu-marker symbol))))
        (unless (or (null position) (null name)
                    (string= (car imenu--rescan-item) name))
          (add-to-list 'symbol-names name)
          (add-to-list 'name-and-pos (cons name position))))))))

                                        ; from http://www.masteringemacs.org/articles/2011/01/27/find-files-faster-recent-files-package/
(defun ido-recentf-open ()
  "Use `ido-completing-read' to \\[find-file] a recent file"
  (interactive)
  (if (find-file (ido-completing-read "Find recent file: " recentf-list))
      (message "Opening file...")
    (message "Aborting")))

;; ;;;;; lusty-explorer
;; (require 'lusty-explorer)
;; (add-hook 'lusty-setup-hook 'my-lusty-hook)
;; (defun my-lusty-hook ()
;;        (define-key lusty-mode-map '[left] 'lusty-highlight-previous)
;;        (define-key lusty-mode-map '[right] 'lusty-highlight-next)
;;        (define-key lusty-mode-map '[prior] 'lusty-highlight-previous-column)
;;        (define-key lusty-mode-map '[next] 'lusty-highlight-next-column)
;;        (define-key lusty-mode-map '[\C-j] 'lusty-launch-dired))
;; (global-set-key (kbd "C-x C-f") 'lusty-file-explorer)
;; (global-set-key (kbd "C-x b")   'lusty-buffer-explorer)

;;;;; file-journal
(require 'file-journal)
(setq fj-journal-file "~/.emacs.d/.file-journal"
      fj-journal-size 30
      fj-exclude-files '(".fb2"))

;;;;; nav
(add-to-list 'load-path (concat my-elisp-dir "nav"))
(require 'nav)
(setq nav-quickdir-list '("~/personal/Help Files" "~/.emacsmine" "/home/devel/mine/lfm/lfm")
      nav-quickfile-list '("~/.emacsmine/.emacs" "~/personal/agenda/todo.org" "~/.lfmrc"))

;; ;;;;; "backups-mode"
;; (require 'backups-mode)

;;;;; abook
(require 'abook)
(setq abook-file "~/personal/agenda/abook.vcard")

;;;;; printing
(require 'printing)
(pr-update-menus)
(setq pr-gv-command "evince")       ; not in win32
(setq ps-paper-type (quote a4))

;;;;; visual bookmarks
(require 'bm)
(setq bm-cycle-all-buffers nil
      bm-electric-show t
      bm-highlight-style 'bm-highlight-only-fringe) ; bm-highlight-line-and-fringe

;; ;;;;; ipa - in-place annotations
;; (require 'ipa)
;; (setq ipa-file "~/.emacs.d/.ipa"
;;       ipa-annotation-face 'hi-yellow
;;       ipa-file-face 'hi-blue)

;;;;; line numbers
;; (require 'setnu+)
(require 'linum)
(setq linum-format "%4d ")
;; (setq linum-format 'dynamic)
;; (global-linum-mode 1)
;; (load-library "linemark") ; eieio's linemark.el: viss-bookmark-...

;;;;; hide/show
(require 'hideshow-fringe)
(setq hs-isearch-open 'both)

(defvar my-hs-all-next nil
  "Keeps the state of how the buffer was last toggled.")
(make-variable-buffer-local 'my-hs-all-next)
(defun my-hs-toggle-hiding-all()
  "Toggle hideshow-all."
  (interactive)
  (if my-hs-all-next
      (hs-show-all)
    (hs-hide-all))
  (setq my-hs-all-next (not my-hs-all-next)))

;;;;; minimap
(require 'minimap)
(setq minimap-width-fraction 0.15
      minimap-dedicated-window t)

;;;;; uniquify
(require 'uniquify)
(setq uniquify-buffer-name-style 'reverse
      uniquify-separator "|"
      uniquify-after-kill-buffer-p t     ; rename after killing uniquified
      uniquify-ignore-buffers-re "^\\*") ; don't muck with special buffers

;;;;; crypt
(require 'epa)
(epa-file-enable)

;;;;; all
(require 'all) ; to be removed with emacs 24

;;;;; rfringe
(require 'rfringe)

;;:;;; rebound
(require 'rebound)
(rebound-mode)

;;;;; w3m
;; (setq browse-url-browser-function 'w3m-browse-url)
(add-to-list 'load-path (concat my-elisp-dir "w3m"))
(require 'w3m-load)
;; (require 'w3m)
(setq browse-url-browser-function 'browse-url-generic
      browse-url-generic-program "firefox")

(defun choose-browser (url &rest args)
  (interactive "sURL: ")
  (if (y-or-n-p "Use external browser? ")
      (browse-url-generic url)
    (w3m-browse-url url)))

(setq browse-url-browser-function 'choose-browser)

;;;;; mail-mode for mutt
(add-to-list 'auto-mode-alist '("/mutt" . mail-mode))

;; ;;;;; pinbar
;; (require'pinbar)
;; (pinbar-mode t)

;;;;; multi-term
;; (require 'multi-term)
(add-hook 'term-mode-hook (lambda () (global-unset-key '[tab])))
(setq multi-term-dedicated-select-after-open-p t)
;; (defun it-multi-term-dedicated-toggle ()
;;   "jump back to previous location after toggling ded term off"
;;   (interactive)
;;   (if (multi-term-dedicated-exist-p)
;;       (progn
;;         (multi-term-dedicated-toggle)
;;         (switch-to-buffer-other-window old-buf))
;;     (progn
;;       (setq old-buf (current-buffer))
;;       (multi-term-dedicated-toggle))))

;;;;; tabbar
(require 'tabbar)
;; (require 'tabbar-ruler)
(tabbar-mode 1)
(setq tabbar-buffer-groups-function 'my-tabbar-buffer-groups)

;; (setq tabbar-buffer-groups-function
;;       (lambda (b) (list "All Buffers")))

;; (setq tabbar-buffer-list-function
;;       (lambda ()
;;         (remove-if
;;          (lambda(buffer)
;;            (find (aref (buffer-name buffer) 0) " *")) (buffer-list))))

(defun my-tabbar-buffer-groups ()
  "Return the list of group names BUFFER belongs to.
  Return only one group for each buffer."
  (let ((projname (my-buffer-eproject-name)))
    (cond
     ((or (get-buffer-process (current-buffer)) (memq major-mode '(comint-mode compilation-mode))) '("Term"))
     ((or (string-equal "*hg" (substring (buffer-name) 0 3))
          (string-equal "*aHg" (substring (buffer-name) 0 4))) '("hg"))
     ((string-equal "*" (substring (buffer-name) 0 1)) '("Misc"))
     ((member (buffer-name) '(".ipa")) '("Misc"))
     (projname (list projname))
     ((memq major-mode '(tags-table-mode Custom-mode)) '("Misc"))
     ((memq major-mode '(help-mode apropos-mode Info-mode Man-mode)) '("Help"))
     ((memq major-mode '(emacs-lisp-mode)) '("Elisp"))
     ((memq major-mode '(python-mode emacs-lisp-mode c-mode c++-mode makefile-mode lua-mode vala-mode)) '("Coding"))
     ((memq major-mode '(javascript-mode js-mode nxhtml-mode html-mode css-mode)) '("HTML"))
     ((memq major-mode '(org-mode calendar-mode diary-mode)) '("Org"))
     ((memq major-mode '(dired-mode)) '("Dir"))
     (t '("Main")))))

(defun my-buffer-eproject-name ()
  "Return name of eproject for current buffer or nil."
  (when eproject-root
    (catch 'loop
      (let ((lst (eproject-projects)))
        (while lst
          (let ((proj (pop lst)))
            (if (string= eproject-root (cdr proj))
                (throw 'loop (car proj)))))))))

;;;;; auto-complete
(add-to-list 'load-path (concat my-elisp-dir "auto-complete"))
(require 'auto-complete-config)
(add-to-list 'ac-dictionary-directories "~/.emacsmine/auto-complete/dict")
(ac-config-default)
;; (ac-set-trigger-key '[S-iso-lefttab])
(define-key ac-mode-map '[S-iso-lefttab] 'auto-complete)
(define-key ac-menu-map '[tab] 'ac-complete)
(define-key ac-complete-mode-map [escape] 'keyboard-quit)
(setq ac-auto-start nil        ; number of chars, nil to not show automatically
      ac-auto-show-menu 1.0    ; time
      ac-ignore-case 'smart
      ac-candidate-max 15
      ac-candidate-menu-height 15
      ac-candidate-menu-width 30
      ac-sources (append '(ac-source-semantic ac-source-dabbrev ac-sources-etags) ac-sources))
(add-to-list 'ac-modes 'vala-mode)

;; (defvar ac-source-pysmell
;;   '((candidates
;;      . (lambda ()
;;          (require 'pysmell)
;;          (pysmell-get-all-completions))))
;;   "Source for PySmell")

;; (add-hook 'python-mode-hook
;;           '(lambda ()
;;              (set (make-local-variable 'ac-sources) (append ac-sources '(ac-source-pysmell)))))

;; ;;;;; predictive
;; (add-to-list 'load-path (concat my-elisp-dir "predictive"))
;; (add-to-list 'load-path (concat my-elisp-dir "predictive/html"))
;; (autoload 'predictive-mode "predictive" "predictive" t)
;; (require 'predictive)
;; (setq predictive-dict-autosave-on-kill-buffer nil
;;       predictive-dict-autosave-on-mode-disable nil
;;       predictive-auto-learn t)

;; ;;;;; company-mode
;; (require 'company-mode)
;; (require 'company-bundled-completions)
;; (company-install-bundled-completions-rules)

;; (add-hook 'newsticker-mode-hook 'imenu-add-menubar-index)

;; ;;;;; load festl mode
;; (autoload 'say-minor-mode "festival" "Menu for using Festival" t)
;; (say-minor-mode t)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Org
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (setq load-path (cons (concat my-elisp-dir "org-X.Y) load-path)) ;; also done at beggining of file
(require 'org-install)
(setq org-directory "~/personal/agenda"
      org-startup-folded 'showall
      org-startup-indented t
      org-cycle-separator-lines 1
      org-log-done 'time
      org-completion-use-ido t
      org-outline-path-complete-in-steps nil)
;; (setq org-hide-leading-stars t
;;       org-odd-levels-only t
;;       org-reverse-note-order t)
(setq org-todo-keywords
      '((sequence "TODO" "STARTED" "WAITING" "SOMEDAY" "|" "DONE" "CANCELLED")))

(add-hook 'org-mode-hook
          (lambda ()
            (auto-fill-mode -1)
            (local-set-key '[C-tab] 'other-window)
            ;; (local-set-key "\C-c\C-n" 'nav)
            ;; (local-set-key "\C-c\C-j" 'my-org-journal-add-entry)))
            ;; (local-set-key '[?\C-c S-up] 'hide-sublevels)
            ;; (local-set-key '[?\C-c S-down] 'show-all)
            (local-set-key '[C-up]   'org-backward-same-level)
            (local-set-key '[C-down] 'org-forward-same-level)
            (local-set-key '[C-S-iso-lefttab] 'org-force-cycle-archived)))

;;;;; agenda
(setq org-agenda-files (list
                        (concat org-directory "/todo.org")
                        (concat org-directory "/todo.org_archive")
                        (concat org-directory "/work.org")
                        ;; (concat org-directory "/work.org_archive")
                        ;; (concat org-directory "/journal.org")
                        ;; (concat org-directory "/android.org")
                        (concat org-directory "/contacts.org")))
(setq org-agenda-include-diary t
      org-agenda-show-all-dates t
      org-agenda-skip-deadline-if-done t
      org-agenda-skip-scheduled-if-done t
      org-agenda-start-with-log-mode t)
;; org-agenda-span 15) ; 'week
(setq org-agenda-custom-commands
      '(("f" todo "DONE|CANCELLED")
        ;; ("F" occur-tree "\\<DONE\\>")
        ("y" "My agenda"      ((org-agenda-list) (tags "")))
        ("x" "Agenda PENDING" ((agenda) (todo "TODO|STARTED|WAITING|SOMEDAY")))
        ;; ("o" "Agenda and Office-related tasks" ((agenda) (tags-todo "work") (tags "office"))
        ))

;;;;; org-mobile
(setq org-mobile-directory "~/tmp/org/"
      org-mobile-force-id-on-agenda-items nil
      org-mobile-inbox-for-pull "~/tmp/org/from-mobile.org")

;;;;; org-babel
(setq org-src-fontify-natively t)
(org-babel-do-load-languages
 'org-babel-load-languages '((sh . t) (python . t)))

;;;;; org-contacts
(require 'org-contacts)
(setq org-contacts-files '("~/personal/agenda/contacts.org"))
(org-contacts-gnus-insinuate)



;;;;; org-search-goto
(require 'org-search-goto)

;;;;; journal
;; from http://metajack.im/2009/01/01/journaling-with-emacs-orgmode/
;; modified by ISR, 2009/01/05: add time subheading
(defvar org-journal-file "~/personal/agenda/journal.org"
  "Path to OrgMode journal file.")

(defvar org-journal-date-format "%Y/%m/%d"
  "Date format string for journal headings.")

(defvar org-journal-time-format "%H:%M"
  "Time format string for journal subheadings.")

(defun my-org-journal-add-entry ()
  "Create a new diary entry for today or append to an existing one."
  (interactive)
  (switch-to-buffer (find-file org-journal-file))
  (widen)
  (let ((today (format-time-string org-journal-date-format))
        (now (format-time-string org-journal-time-format))
        (first-entry-in-day nil)
        (isearch-forward t))
    (beginning-of-buffer)
    (unless (org-goto-local-search-headings today nil t)
      ((lambda ()
         (setq first-entry-in-day t)
         (org-insert-heading)
         (insert today)
         (insert "\n"))))
    (beginning-of-buffer)
    (org-show-subtree)
    (org-narrow-to-subtree)
    (end-of-buffer)
    (widen)
    (if first-entry-in-day
        (org-insert-subheading 1)
      (org-insert-heading-after-current))
    (insert now)
    (insert "\n    ")))

(defun make-journal-frame ()
  "Create a new frame and run my-org-journal-add-entry."
  (interactive)
  (make-frame '((name . "journal.org") (width . 80) (height . 15)))
  (select-frame-by-name "journal.org")
  (my-org-journal-add-entry)
  (set-foreground-color "gray95"))

;;;;; org-capture
;; (setq org-default-notes-file (concat org-directory "/todo.org"))
(setq org-capture-templates
      ;; '(("t" "Todo" entry (file+headline "~/personal/agenda/todo.org" "Tasks") "* TODO %?\n  %t")
      '(("t" "Todo" entry (file+headline "~/personal/agenda/todo.org" "Tareas") "* TODO %?\n %i %U")
        ("w" "Work" entry (file+headline "~/personal/agenda/work.org" "Tareas") "* TODO %?\n %i %U")
        ("p" "Clipboard" entry (file+headline "~/personal/agenda/todo.org" "Ideas") "* %U %?\n %i %x")
        ("j" "Journal" entry (file+headline "~/personal/agenda/journal.org") "* %U %?\n\n %i\n")
        ("c" "Contacts" entry (file "~/personal/agenda/contacts.org") "* %(mu4e-view-snarf-from 'name)\n:PROPERTIES:\n:EMAIL: %(mu4e-view-snarf-from 'email)\n:NICK:\n:BIRTHDAY:\n:END:\n\n")
        ))

;; emacsclient -e '(make-capture-frame)'
(defun make-capture-frame ()
  "Create a new frame and run org-capture."
  (interactive)
  (make-frame '((name . "capture") (width . 80) (height . 20)))
  (select-frame-by-name "capture")
  (org-capture)
  (set-foreground-color "gray95"))

;; ;;;;; Remember mode
;; (org-remember-insinuate)

;; (add-hook 'remember-mode-hook 'org-remember-apply-template)
;; (setq org-remember-store-without-prompt t)
;; (setq org-remember-templates
;;       '(("Clipboard" ?c "* %U %?\n %i %x" "~/personal/agenda/todo.org" "Ideas")
;;         ("Todo" ?t "* TODO %?\n %i %U" "~/personal/agenda/todo.org" "Tareas")
;;         ("Work" ?w "* WORK %?\n %i %U" "~/personal/agenda/work.org" "Tareas")
;;         ("Journal" ?j "* %U %?\n\n %i\n" "~/personal/agenda/journal.org" bottom)))
;; (setq remember-annotation-functions (quote (org-remember-annotation))
;;       remember-handler-functions (quote (org-remember-handler)))

;; ;; emacsclient -e '(make-remember-frame)'
;; (defadvice remember-finalize (after delete-remember-frame activate)
;;   "Advise remember-finalize to close the frame if it is the remember frame"
;;   (if (equal "remember" (frame-parameter nil 'name))
;;       (delete-frame)))

;; (defadvice remember-destroy (after delete-remember-frame activate)
;;   "Advise remember-destroy to close the frame if it is the rememeber frame"
;;   (if (equal "remember" (frame-parameter nil 'name))
;;       (delete-frame)))

;; ;; make the frame contain a single window. by default org-remember splits the window
;; (add-hook 'remember-mode-hook 'delete-other-windows)

;; (defun make-remember-frame ()
;;   "Create a new frame and run org-remember."
;;   (interactive)
;;   (make-frame '((name . "remember") (width . 80) (height . 15)))
;;   (select-frame-by-name "remember")
;;   (org-remember)
;;   (set-foreground-color "gray95"))

; outline defined:
;     C-cC-a (show all), C-cC-t (hide body=hide all)
;     C-cC-d (show current subtree), C-cC-s (hide current subtree)
;     C-cC-e (show current entry), C-cC-c (hide current entry)
;     C-cC-o (hide other)
; outline: TAB, S-TAB,
; move: C-C C-j, C-c C-{npfb}
; insert: C-c C-{tsd}, C-c C-x C-a, C-c ,
; insert date/time: C-c {.!}, C-u C-c {.!}, C-c C-y, C-c C-x C-t
; tags: C-c C-c, C-c C-v, C-c \
; agenda: C-c a {ta}
; links: C-c C-o, C-c C-l, C-c l


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; email
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq message-kill-buffer-on-exit t)

;;;;; mu4e
(add-to-list 'load-path (concat my-elisp-dir "mu4e"))
(require 'mu4e)
(require 'org-mu4e)
; personal information
(setq mu4e-user-mail-address-regexp  "my@email\.com\\|other@email\.org"
      mail-reply-to     "my@email.com"
      user-mail-address "my@email.com"
      user-full-name    "Inigo Serna"
      message-signature (concat "--\nInigo Serna\nKatxijasotzaileak\n"))
(setq mu4e-html2text-command "html2text"
      mu4e-get-mail-command "offlineimap"
      mu4e-search-results-limit 1000 ; default 500, -1 unlimited
      mu4e-headers-fields
      '( (:date          .  25)
         (:flags         .   6)
         (:from          .  22)
         (:subject       .  nil)))
                                        ; local maildir
(setq mu4e-maildir "/zzz/Mail.inigo/local"
      mu4e-drafts-folder "/.Drafts"
      mu4e-sent-folder   "/.Sent"
      mu4e-trash-folder  "/.Bin")
(setq mu4e-maildir-shortcuts
      '(("/INBOX"               . ?i)
        ("/_unread"             . ?u)
        ("/_personal"           . ?p)
        ("/.Sent"               . ?s)
        ("/[Gmail].Sent Mail"   . ?S)
        ("/.Bin"                . ?t)
        ("/[Gmail].Trash"       . ?T)))
;; ("/[Gmail].All Mail"    . ?a)))
(setq mu4e-bookmarks
      '( ("flag:unread AND NOT flag:trashed" "Unread messages"	?u)
         ("date:today..now"                  "Today's messages"     ?t)
         ("date:7d..now"                     "Last 7 days"          ?w)
         ("date:31d..now"                    "Last month"           ?m)))
;; ("mime:image/*"                     "Messages with images" ?p)))
;; (setq message-send-mail-function 'smtpmail-send-it  ;; tell message-mode how to send mail
;;       smtpmail-smtp-server "localhost"              ;; if our mail server lives at smtp.example.org; if you have a local mail-server, simply use 'localhost' here
;;       smtpmail-queue-mail  nil                      ;; start in non-queuing mode
;;       smtpmail-queue-dir   "/zzz/Mail.inigo/local/queue/cur")
;; ; gmail maildir
;; (setq mu4e-maildir "/zzz/Mail.inigo/GMail.maildir"
;;       mu4e-drafts-folder "/[Gmail].Drafts"
;;       mu4e-sent-folder   "/[Gmail].Sent Mail"
;;       mu4e-trash-folder  "/[Gmail].Bin")
;; (setq mu4e-maildir-shortcuts
;;     '(("/INBOX"               . ?i)
;;       ("/_unread"             . ?u)
;;       ("/_personal"           . ?p)
;;       ("/[Gmail].Sent Mail"   . ?s)
;;       ("/[Gmail].Trash"       . ?t)
;;       ("/[Gmail].All Mail"    . ?a)))
(require 'smtpmail)
(setq message-send-mail-function 'smtpmail-send-it
      starttls-use-gnutls t
      smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
      smtpmail-auth-credentials '(("smtp.gmail.com" 587 "my@email.com" nil))
      smtpmail-default-smtp-server "smtp.gmail.com"
      smtpmail-smtp-server "smtp.gmail.com"
      smtpmail-smtp-service 587)

;; ;;;;; notmuch
;; (add-to-list 'load-path (concat my-elisp-dir "notmuch"))
;; (require 'notmuch)

;; ;;;;; wanderlust
;; (add-to-list 'load-path "~/.emacsmine/wl-pkgs/")
;; (add-to-list 'load-path "~/.emacsmine/wl-pkgs/apel/")
;; (add-to-list 'load-path "~/.emacsmine/wl-pkgs/emu/")
;; (add-to-list 'load-path "~/.emacsmine/wl-pkgs/flim/")
;; (add-to-list 'load-path "~/.emacsmine/wl-pkgs/semi/")
;; (add-to-list 'load-path "~/.emacsmine/wl/")
;; (autoload 'wl "wl" "Wanderlust" t)
;; (autoload 'wl-other-frame "wl" "Wanderlust on new frame." t)
;; (autoload 'wl-draft "wl-draft" "Write draft with Wanderlust." t)
;; (autoload 'wl-user-agent-compose "wl-draft" "Compose with Wanderlust." t)
;; (setq wl-init-file "~/.emacsmine/.wl")

;; ;;;;; mew
;; (add-to-list 'load-path "~/.emacsmine/mew/")
;; (autoload 'mew "mew" nil t)
;; (autoload 'mew-send "mew" nil t)
;; (setq mew-rc-file "~/.emacsmine/.mew")
;; ;; Optional setup (e.g. C-xm for sending a message):
;; (autoload 'mew-user-agent-compose "mew" nil t)
;; (if (boundp 'mail-user-agent)
;;     (setq mail-user-agent 'mew-user-agent))
;; (if (fboundp 'define-mail-user-agent)
;;     (define-mail-user-agent
;;       'mew-user-agent
;;       'mew-user-agent-compose
;;       'mew-draft-send-message
;;       'mew-draft-kill
;;       'mew-send-hook))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Key Bindings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;; function keys
(global-set-key '[f1]     'info-emacs-manual)
(global-set-key '[f2]     'toggle-truncate-lines)
(global-set-key '[f3]     (lambda () (interactive) (if window-system (my-win-look) (my-console-look))))
(global-set-key '[f4]     'query-replace)
(global-set-key '[f5]     'minimap-toggle)
(global-set-key '[C-f6]   'bm-toggle)
(global-set-key '[f6]     'bm-next)
(global-set-key '[S-f6]   'bm-previous)
(global-set-key '[C-S-f6] 'bm-show-all)
(global-set-key '[f7]     'hs-toggle-hiding)
(global-set-key '[S-f7]   'my-hs-toggle-hiding-all)
;; (global-set-key '[C-f8]   'ipa-insert)
;; (global-set-key '[f8]     'ipa-next)
;; (global-set-key '[S-f8]   'ipa-previous)
;; (global-set-key '[M-f8]   'ipa-show)
;; (global-set-key '[C-S-f8] 'ipa-edit)
;; (global-set-key '[M-S-f8] 'ipa-toggle)
;; (global-set-key '[f9]     'server-edit) ; default C-x #
;; (global-set-key '[S-f9]   'new-frame) ; default C-x 5 2
;; (global-set-key '[C-f9]   'delete-frame) ; default C-x 5 0
(global-set-key '[f10]    'multi-term-dedicated-toggle)
(global-set-key '[S-f10]  'multi-term)
(global-set-key '[C-f10]  '(lambda () (interactive) (term "ipython")))
(global-set-key '[f11]    'my-kill-other-buffer)
(global-set-key '[C-f11]  'my-kill-other-buffer-destroy)
(global-set-key '[S-f11]  'delete-other-windows) ; C-x 1
(global-set-key '[f12]    'my-kill-current-buffer)
(global-set-key '[C-f12]  'my-kill-current-buffer-destroy)
(global-set-key '[S-f12]  'delete-window)        ; C-x 0

(global-set-key (kbd "\C-c <return>") 'tmm-menubar)

;;;;; buffers, windows, and files
(global-unset-key "\C-x\C-z") ; disable suspend-frame
(global-set-key '[?\C-=]     'my-buffers-equal)
(global-set-key '[?\C-#]     'my-switch-buffers)
(global-set-key '[C-tab]     'other-window)
;; (global-set-key '[C-prior]   'my-previous-buffer)
;; (global-set-key '[C-next]    'my-next-buffer)
;; (global-set-key '[C-S-prior] 'previous-buffer) ; default C-x left
;; (global-set-key '[C-S-next]  'next-buffer)     ; default C-x right
;; (global-set-key "\M-0"       'pinbar-add)
;; (global-set-key "\M-="       'pinbar-del)
(global-set-key '[C-M-return] 'tabbar-press-home)
(global-set-key '[C-prior]    'tabbar-backward-tab)
(global-set-key '[C-next]     'tabbar-forward-tab)
(global-set-key '[C-S-prior]  'tabbar-backward-group) ; default C-c C-up
(global-set-key '[C-S-next]   'tabbar-forward-group)  ; default C-c C-down
(global-set-key "\C-x\C-b" 'ibuffer) ; electric-buffer-list, bs-show, default is list-buffers
(global-set-key "\C-x\C-r" 'find-alternative-file-with-sudo)
(global-set-key "\C-x\C-j" 'dired-jump) ; default? doesn't work always
(global-set-key "\C-x\C-h" 'fj-show)
(global-set-key "\C-c\C-h" 'recentf-open-files)
(global-set-key "\C-c\C-j" 'ido-recentf-open)
(global-set-key "\C-c\C-n" 'nav)
(global-set-key "\C-c\C-fe" '(lambda () (interactive) (find-file "~/.emacsmine/.emacs")))
(global-set-key "\C-c\C-ft" '(lambda () (interactive) (find-file "~/personal/agenda/todo.org")))
(global-set-key "\C-c\C-fw" '(lambda () (interactive) (find-file "~/personal/agenda/work.org")))
(global-set-key "\C-c\C-fj" '(lambda () (interactive) (find-file "~/personal/agenda/journal.org")))
(global-set-key "\C-c\C-fa" '(lambda () (interactive) (find-file "~/personal/agenda/android.org")))
(global-set-key "\C-c\C-fo" '(lambda () (interactive) (find-file "~/personal/agenda/other.org.gpg")))
(global-set-key "\C-c\C-ph" '(lambda () (interactive) (dired "~")))
(global-set-key "\C-c\C-pe" '(lambda () (interactive) (dired "~/.emacsmine")))
(global-set-key "\C-c\C-pd" '(lambda () (interactive) (dired "/home/_download")))
(global-set-key "\C-c\C-pl" '(lambda () (interactive) (dired "/home/devel/mine/lfm/lfm")))
(global-set-key "\C-c\C-pm" '(lambda () (interactive) (dired "/home/devel/mine/mynewspaper3")))

;;;;; movement
; C-cursors defined by default
(global-set-key '[home]         'beginning-of-line) ; back-to-indentation-or-beginning
(global-set-key '[end]          'end-of-line)
(global-set-key '[C-home]       'beginning-of-buffer) ; default M-<
(global-set-key '[C-end]        'end-of-buffer)       ; default M->
(global-set-key '[?\C-x C-up]   'beginning-of-defun)  ; default C-M-a
(global-set-key '[?\C-x C-down] 'end-of-defun)        ; default C-M-e
(global-set-key '[A-up]         '(lambda () (interactive) (scroll-down 1)))
(global-set-key '[A-down]       '(lambda () (interactive) (scroll-up 1)))
(global-set-key '[C-A-up]       '(lambda () (interactive) (scroll-down 5)))
(global-set-key '[C-A-down]     '(lambda () (interactive) (scroll-up 5)))
(global-set-key (kbd "M-n")     'smart-symbol-go-forward)
(global-set-key (kbd "M-p")     'smart-symbol-go-backward)

;;;;; edit
; c-delete, C-backspace defined by default
(global-set-key "\C-x(" 'kmacro-start-macro-or-insert-counter)
(global-set-key "\C-x)" 'kmacro-end-or-call-macro)
(global-unset-key "\C-z") (global-set-key "\C-z" 'advertised-undo)
(global-set-key "\C-k"               'kill-and-join-forward) ; kill-whole-line
(global-set-key "\C-m"               'newline-and-indent)
(global-set-key "\C-\M-z"            'zap-back-to-char)      ; zap back to char
(global-set-key '[C-delete]          'my-delete-word)        ; don't save to kill-ring
(global-set-key '[C-backspace]       'my-backward-delete-word) ; don't save to kill-ring
(global-set-key '[?\C-c backspace]   'delete-chars-hungry-backward)
(global-set-key '[?\C-c C-backspace] 'delete-chars-hungry-backward)
(global-set-key '[?\C-c delete]      'delete-chars-hungry-forward)   ; fixup-whitespace ;just-one-space
(global-set-key '[?\C-c C-delete]    'delete-chars-hungry-forward) ; fixup-whitespace ;just-one-space
(global-set-key "\C-cc"              'my-comment-or-uncomment-region-or-line)
;; (global-set-key "\C-cC"              'comment-or-uncomment-region) ; C-u C-cc
(global-set-key "\C-cv"              'copy-and-comment-line-or-region)
(global-set-key "\C-cb"              'duplicate-line-or-region)
;; (global-set-key "\C-cx"              'my-copy-line-as-kill) ; not needed anymore
(global-set-key '[?\C-c tab]         'indent-for-comment)
(global-set-key "\C-cP"              '(lambda () (interactive) (popup-menu 'yank-menu)))
(global-set-key '[M-S-up]            'move-text-up)
(global-set-key '[M-S-down]          'move-text-down)
(global-set-key "\C-c-"              'underline-line-with)
(global-set-key '[?\C-c S-C-delete]  'delete-trailing-whitespace)

;;;;; mark
(global-set-key '[escape ?w] 'my-mark-word)   ; default M-@
(global-set-key '[escape ?l] 'my-mark-line)
(global-set-key '[escape ?c] 'my-mark-line2)
(global-set-key '[escape ?p] 'mark-paragraph) ; default M-h
(global-set-key '[escape ?f] 'mark-defun)     ; default C-M-h
(global-set-key '[escape ?s] 'my-mark-sexp)   ; C-M-spc: mark-sexp

;;;;; font size
(global-set-key '[?\C-c ?\C--] 'font-zoom-decrease-font-size) ; C-x C--: text-scale-decrease
(global-set-key '[?\C-c ?\C-=] 'font-zoom-increase-font-size) ; C-x C-=
(global-set-key '[?\C-c ?\C-+] 'font-zoom-increase-font-size) ; C-x C-+: text-scale-increase
(global-set-key '[?\C-c ?\C-0] 'font-zoom-reset-font-size)    ; C-x C-0: text-scale-adjust

;;;;; helpers
(global-set-key "\C-cV"  'view-mode)
(global-set-key "\C-cn"  'linum-mode)
(global-set-key "\C-cN"  'ruler-mode)
(global-set-key "\C-cga" 'highlight-changes-visible-mode)
(global-set-key "\C-cgp" 'highlight-changes-previous-change)
(global-set-key "\C-cgn" 'highlight-changes-next-change)
(global-set-key "\C-ci"  'flyspell-mode) ; default C-, flyspell-goto-next-error
(global-set-key "\C-co"  'occur)
(global-set-key "\C-cO"  'multi-occur)
(global-set-key "\C-cm"  'highlight-lines-matching-regexp) ; default M-s h l
(global-set-key "\C-cM"  'unhighlight-regexp)              ; default M-s h u

;;;;; misc
(global-set-key "\C-cde" 'insert-date-en)
(global-set-key "\C-cds" 'insert-date-es)

;;;;; completion
(global-set-key '[S-iso-lefttab] 'ac-start) ; auto-complete
(global-set-key '[A-tab] 'hippie-expand) ; dabbrev-expand
;; (global-set-key '[tab]   'smart-tab) ; only for devel modes

;;;;; programming
(global-set-key "\C-cl"    'add-change-log-entry-other-window)
(global-set-key "\C-chl"   'ido-gtk-lookup-search)
(global-set-key "\C-chd"   'my-devhelp-search)
(global-set-key "\C-chp"   'pylookup-lookup)
(global-set-key "\C-cw"    'my-narrow-toggle)
(global-set-key "\C-cf"    'my-jump-to-function)
(global-set-key "\C-cy"    'ido-goto-symbol)
(global-set-key "\C-cka"   'flymake-mode)
(global-set-key "\C-ckp"   'flymake-goto-prev-error)
(global-set-key "\C-ckn"   'flymake-goto-next-error)
(global-set-key "\C-cke"   'flymake-display-err-menu-for-current-line)
;; (global-set-key "\C-c:"    'find-thing-at-point)
(global-set-key "\C-c\C-t" 'grep-todofixme)
(global-set-key "\C-czv"   'develnotes-visit-file)
(global-set-key "\C-cza"   'develnotes-add-annotation)
(global-set-key "\C-czt"   'develnotes-add-TODO)
(global-set-key "\C-czf"   'develnotes-add-FIXME)

;;;;; tags
; find . -type f -iname "*.[ch]" | etags [-a] -           ctags -Rne
; visit-tags-table, tags-reset-tags-tables
; next tag -> C-u M-. or M-0 M-., prev tag -> C-u - M-.
; tags-search, tags-query-replace, tags-loop-continue (M-,)
; find-tag-regex (C-M-.), complete-tag
; list-tags FILE, tags-apropos
(global-set-key "\C-ct" 'find-tag-noconfirm) ; find-tag: M-.
(global-set-key "\C-cT" 'pop-tag-mark)       ; default M-*
(global-set-key "\C-cr" 'tags-search)        ; next: M-,
(global-set-key "\C-cR" 'tags-query-replace) ; next: M-,
(global-set-key "\C-cu" 'tags-apropos)
(global-set-key "\C-xt" 'my-ido-find-tag)

;;;;; eproject
(global-set-key "\C-cpv" 'eproject-revisit-project)
(global-set-key "\C-cpk" 'eproject-kill-project-buffers)
(global-set-key "\C-cpf" 'eproject-find-file)     ; ido-find-file-in-tag-files)
(global-set-key "\C-cpb" 'my-eproject-ido-buffer) ; eproject-ibuffer
(global-set-key "\C-cpt" 'eproject-tags)
(global-set-key "\C-cpg" 'eproject-grep)
(global-set-key "\C-cpo" 'eproject-todo)
(global-set-key "\C-cps" 'eproject-multi-isearch-buffers)
(global-set-key "\C-cpc" 'eproject-compile)
(global-set-key "\C-cpa" 'eproject-open-all-project-files)

;;;;; semantic
;; enable-visual-studio-bookmarks, cogre-uml-quick-class
;; semantic-speedbar-analysis, semantic-cb-speedbar-mode
;; semantic-complete-analyze-inline. senator-narrow-to-defun
;; senator-next-tag/token, senator-previous-tag/token
;; semantic-stickyfunc-mode, semantic-decoration-mode, semantic-mru-bookmark-mode
;; semantic-highlight-edits-mode, semantic-show-unmatched-syntax-mode
(global-set-key "\C-cj" 'semantic-ia-fast-jump)     ; semantic-complete-jump
(global-set-key "\C-cJ" 'semantic-mrub-switch-tags) ; C-xB
(global-set-key "\C-c " 'senator-fold-tag-toggle)
(global-set-key "\C-cs" 'semantic-decoration-mode)

;;;;; ecb
(global-set-key "\C-ces" 'ecb-toggle-ecb-windows)
(global-set-key "\C-cee" 'ecb-goto-window-edit-last)
(global-set-key "\C-cea" 'ecb-goto-window-methods)
(global-set-key "\C-cef" 'ecb-goto-window-sources)
(global-set-key "\C-ced" 'ecb-goto-window-directories)
(global-set-key "\C-cec" 'ecb-toggle-compile-window)
(global-set-key "\C-cen" 'ecb-nav-goto-next)     ; default C-c . n
(global-set-key "\C-cep" 'ecb-nav-goto-previous) ; default C-c . p

;; ;;;;; other, from http://www.zafar.se/bkz/Articles/EmacsTips
(global-set-key "["     'skeleton-pair-insert-maybe)
(global-set-key "("     'skeleton-pair-insert-maybe)
(global-set-key "{"     'skeleton-pair-insert-maybe)
;; (global-set-key "'"     'skeleton-pair-insert-maybe)
;; (global-set-key "\""    'skeleton-pair-insert-maybe)
(global-set-key "\M-'"  'insert-pair)
(global-set-key "\M-\"" 'insert-pair)
;; (global-set-key "\M-["  'insert-pair)    ; causes problems in xterm
;; (global-set-key "\M-{"   'insert-pair)
;; (global-set-key "\M-("  'insert-pair) ; default
(global-set-key "\M--"  'delete-pair)

;;;;; registers
; [C-u] C-x r s reg: move/copy region to reg
; C-x r i reg: insert text from reg
; C-x r SPC reg: store cursor position to reg
; C-x r w reg: store window configuration to reg
; C-x r f reg: store frame configuration to reg
; C-x r j reg: restore cursor_pos/window/frame configuration
; C-1 M-w/C-w, C-1 C-y: copy/cut selection to reg 1, paste reg 1
; select columns -> picture-mode: C-x r [kdyoc...ri] /// C-ret
; view-register, list-registers
(global-set-key '[escape left]   'point-to-register)  ; C-x r SPC reg
(global-set-key '[escape right]  'register-to-point)  ; C-x r j reg
(global-set-key '[escape up]     'copy-to-register)   ; C-x r s reg
(global-set-key '[escape down]   'insert-register)    ; C-x r i reg
(global-set-key '[escape return] 'list-registers)
(global-set-key '[escape S-up]   'window-configuration-to-register) ; C-x r w reg
(global-set-key '[escape S-down] 'jump-to-register)   ; C-x r j reg

(global-set-key '[?\C-c left]    'point-stack-push)
(global-set-key '[?\C-c right]   'point-stack-pop)

;;;;; bookmarks
; C-x r l: list bookmarks
; C-x r m [bookmark_name]: save bookmark
; C-x r b [bookmark_name]: jump to bookmark
; bookmarks-load, bookmarks-save
(global-set-key '[escape C-left]   'bookmark-set)        ; C-x r m
(global-set-key '[escape C-right]  'bookmark-jump)       ; C-x r b
(global-set-key '[escape C-return] 'bookmark-bmenu-list) ; C-x r l

;;;;; org
(global-set-key "\C-ca"    'org-agenda)
(global-set-key "\C-cA"    'org-contacts)
(global-set-key "\C-cr"    'org-insert-link)
(global-set-key "\C-cR"    'org-store-link)
(global-set-key "\C-c\C-r" 'org-capture) ; org-remember
(global-set-key "\C-c\C-j" 'my-org-journal-add-entry)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; Other predefined keys and functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;; movement
; C-u C-spc -> move to last edition spots (pop-to-mark-command)
; C-x C-spc -> same for other buffer (pop-global-mark))
; C-x C-x -> exchange-point-and-mark
; M-home M-end -> beginning|end-of-buffer-other-window
; M-next M-prev, C-M-v C-M-S-v -> scroll-other-window forward, backward
; M-a, M-e -> backward-sentence, forward-sentence
; C-M-home / C-M-a, C-M-end / C-M-e -> beginning-of-defun, end-of-defun
; C-M-up / C-M-u, C-M-down / C-M-d -> backward-up-list, down-list
; C-M-left & C-M-b, C-M-right & C-M-f -> backward-sexp, forward-sexp
; M-m -> back-to-indentation
; M-r -> move-to-window-line-top-bottom
; C-x[, C-x] -> move previous, next page
; C-x C-n, C-u C-x C-n -> enable/disable goal column

;;;;; visual
; C-x n d, C-x n n, C-x n w -> defun-narrow, narrow region, wide buffer
; C-x C-+, C-x C--, C-x C-0 -> zoom
; C-l -> recenter-top-bottom
; C-M-l -> reposition-window
; M-r -> move-to-window-line
; [M-1 C-x $] -> set-selective-display

;;;;; edit
; M-z -> zap (delete) to char
; M-k -> kill sentence
; C-s C-w -> search work under cursor
; C-x C-l, C-x C-u, M-l, M-u, M-c -> region/word lower/upper/capitalize case
; C-x h -> mark whole buffer
; C-x C-p -> mark page
; C-xrt, C-xrk -> string-rectangle, kill-rectangle
; C-M-SPC -> mark-sexp: mark balanced expresion
; C-M-k -> kill-sexp: kill balanced expresion
; join-line
; C-x a g -> create abbrev with last word
; C-x a e -> expand abbrev
; C-x C-q -> toggle-read-only
; C-x C-n -> set-goal-column
; C-x 8 RET snowman RET
; C-x q -> set-fill-colum
; M-o M-s -> center line
; comment-box

; view-file, view-mode
; clean-buffer-list
; M-!, M-| -> shell command, shell-command-on-region
; C-u M-! -> insert output from shell command
; C-x z repeat
; C-x ESC ESC -> repeat-complex-command
; C-x = -> what-cursor-position
; C-x l -> count lines in buffer
; C-h l -> view-lossage

; macros -> C-x (  C-x )  C-x e
; searches: lgrep, rgrep
; goto-line -> M-g g
; compilation: next-error, previous-error -> M-g n M-g p
; diff-buffer-with-file, highlight-compare-with-file
; M-mouse1, M-mouse2 -> secondary selection
; M-! -> shell-command, C-u M-! ->... and insert output at point
; M-| -> shell-command-on-region
; C-M-x -> eval-defun

;;;;; dired
; S -> sort by name / date
; w, M-0w, C-uw -> copy filenames, absolute path, relative path to kill ring
; i, C-uk -> insert, remove directory
; C-x C-j -> dired-jump
; C-x C-q -> wdired-change-to-wdired-mode
; find-name-dired, find-dired, find-grep-dired
; dired-do-query-replace-regexp

; MODES: artist-mode, picture-mode, enriched-mode, po-mode, hexl-mode,
;        predictive-mode, auto-image-file-mode, image-dired, winner-mode
; UTILS: proced, ispell, longlines-mode, re-builder, scroll-all-mode,
;        tumme, message-mode, ielm, repeat-complex-command (C-x ESC ESC),
;        list-colors-display, list-faces-display,
;        (prin1-to-string (x-list-fonts "*"))
;        visible-mode, calculator, calc-dispatch
; EDIT: flush-lines, keep-lines, delete-trailing-whitespace
;       fixup-whitespace, just-one-space,
;       delete-horizontal-spaces, delete-blank-lines (C-xC-o)
;       un/tabify, whitespace-mode
;       align, align-regexp
; not used keys: C-c{r}
; infraused keys: C-{fbnpt}, M-{ijkmrst}


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; My menu
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(easy-menu-define inigo-menu global-map "Inigo"
  '("Inigo"
    ;; ("TeXDrive"  :visible (string= major-mode "html-helper-mode")
    ;;   ["Insert formula"   texdrive-insert-formula :help "Insert some formula"]
    ;;   ["Generate images"  texdrive-generate-images :help "(Re)generate images for formulae"])
    ("Windows and buffers"
     ["Kill other buffer"           my-kill-other-buffer]
     ["Kill other buffer destroy"   my-kill-other-buffer-destroy]
     ["Delete other windows"        delete-other-windows]
     ["Kill current buffer"         my-kill-current-buffer]
     ["Kill current buffer destroy" my-kill-current-buffer-destroy]
     ["Delete window"               delete-window])
    ("Files and directories"
     ["Find with sudo"   find-alternative-file-with-sudo]
     ["Dired jump"       dired-jump]
     ["File journal"     fj-show]
     ["Recent files"     recentf-open-files]
     ["Ido recent files" ido-recentf-open]
     ["Nav"              nav])
    ("Select"
     ["Mark word"      my-mark-word]
     ["Mark line"      my-mark-line]
     ["Mark line2"     my-mark-line2]
     ["Mark paragraph" mark-paragraph]
     ["Mark function"  mark-defun]
     ["Mark sexp"      my-mark-sexp])
    ("Helpers"
     ["View mode"      view-mode]
     ["Toggle linum"   linum-mode]
     ["Toggle ruler"   ruler-mode]
     ["Flyspell"       flyspell-mode]
     ["Occur"          occur]
     ["Multi occur"    multi-occur]
     ("Changes"
      ["Highlight changes"     highlight-changes-visible-mode]
      ["Highlight prev change" highlight-changes-previous-change]
      ["Highlight next change" highlight-changes-next-change])
     ("Highlight"
      ["Highlight lines"       highlight-lines-matching-regexp]
      ["Unhighlight lines"     unhighlight-regexp]))
    ("Programming"
     ["Changelog"           add-change-log-entry-other-window]
     ["Describe symbol"     describe-symbol]
     ["Toggle narrow"       my-narrow-toggle]
     ["Jump to function"    my-jump-to-function]
     ["Goto symbol (ido)"   ido-goto-symbol]
     ["Find thing at point" find-thing-at-point]
     ["Python lookup"       pylookup-lookup]
     ("Flymake"
      ["Toggle flymake"       flymake-mode]
      ["Flymake prev error"   flymake-goto-prev-error]
      ["Flymake next error"   flymake-goto-next-error]
      ["Display err for line" flymake-display-err-menu-for-current-line])
     ("Tags"
      ["Find tag"           find-tag-noconfirm]
      ["Pop tag mark"       pop-tag-mark]
      ["Tags search"        tags-search]
      ["Tags query replace" tags-query-replace]
      ["Tags apropos"       tags-apropos]
      ["Tag find (ido)"     my-ido-find-tag])
     ("TODOs"
      ["Visit TODOs"    develnotes-visit-file]
      ["Add annotation" develnotes-add-annotation]
      ["Add TODO"       develnotes-add-TODO]
      ["Add FIXME"      develnotes-add-FIXME]
      ["Grep TODOs"     grep-todofixme])
     ("Semantic"
      ["Fast jump"         semantic-ia-fast-jump]
      ["Swicth tags"       semantic-mrub-switch-tags]
      ["Toggle fold"       senator-fold-tag-toggle]
      ["Toggle decoration" semantic-decoration-mode])
     ("ECB"
      ["Toogle windows"       ecb-toggle-ecb-windows]
      ["Goto win last"        ecb-goto-window-edit-last]
      ["Goto win methods"     ecb-goto-window-methods]
      ["Goto win sources"     ecb-goto-window-sources]
      ["Goto win directories" ecb-goto-window-directories]
      ["Toggle compile win"   ecb-toggle-compile-window]
      ["Nav next"             ecb-nav-goto-next]
      ["Nav prev"             ecb-nav-goto-previous]))
    ("Registers"
     ["Point -> reg"     point-to-register]
     ["Reg -> point"     register-to-point]
     ["Copy -> reg"      copy-to-register]
     ["Reg -> insert"    insert-register]
     ["List registers"   list-registers]
     ["Wins -> ref"      window-configuration-to-register]
     ["Reg -> wins"      jump-to-register]
     ["Point stack push" point-stack-push]
     ["Point stack pop"  point-stack-pop])
    ("Bookmarks"
     ["Bookmark set"   bookmark-set]
     ["Bookmark jump"  bookmark-jump]
     ["Bookmarls list" bookmark-bmenu-list])
    ("Org"
     ["Agenda"      org-agenda]
     ["Remember"    org-remember]
     ["Journal add" my-org-journal-add-entry])
    ("Programs"
     ["Term"    (term "bash")]
     ["iPython" (term "ipython")]
     ["Process" proced])
    ("Misc"
     ["Google"         google]
     ["Underline with" underline-line-with]
     ["ASCII table"    ascii-table]
     ["ASCII table 2"  ascii-table2]
     ["Tip of the day" totd])
    ))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; End
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(server-start)
;; (add-hook 'server-switch-hook
;;           (lambda ()
;;             ;; (call-process
;;             ;;  "wmctrl" nil nil nil "-i" "-R"
;;             ;;  (frame-parameter (or frame (selected-frame)) 'outer-window-id))
;;             (color-theme-inigo)))

(message ".emacs loaded")

;; (set-frame-position (selected-frame) 0 0)
;; (set-frame-width (selected-frame) 86)
;; (set-frame-height (selected-frame) 72)
;; (setq default-frame-alist FRAMESIZE)
;; (set-frame-size (selected-frame) (car FRAMESIZE) (car (cdr FRAMESIZE)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; laptop$        xhost +maincomputer
;; laptop$        ssh -X myself@maincomputer
;; maincomputer$  emacsclient --eval "(make-frame-on-display \"$DISPLAY\")"

;; emacsclient --eval "(progn (save-some-buffers t t) (kill-emacs))"


;; (progn
;;   (setq x-alt-keysym 'meta)
;;   (setq x-meta-keysym 'meta)
;;   (setq x-super-keysym 'alt))


;;;;; make CapsLock M-x
;; ;; from http://sachachua.com/wp/2008/08/04/emacs-caps-lock-as-m-x/
;; (if (eq window-system 'x)
;;   (shell-command "xmodmap -e 'clear Lock' -e 'keycode 66 = F13'")) ;  "xsxmodmap -e 'add Lock = Caps_Lock'"
;; (global-set-key [f13] 'execute-extended-command)
;; ;; from http://groups.google.com/group/gnu.emacs.help/msg/5196ae31694b6052
;; (if (eq system-type 'windows-nt))
;;   (setq w32-enable-caps-lock nil))
;; (global-set-key [capslock] 'execute-extended-command)


;;;;; Buttons
;; (format "Button [%s]" (button-label button))

;; (defun myfun (button)
;;   (message (format "Button [%s]" (button-label button))))

;; (define-button-type 'my-button
;;   'action 'myfun
;;   'follow-link t
;;   'help-echo "Click button")

;; (insert-text-button "xyz" :type 'my-button)


;;;;; Dialogs
;; It is possible and I'll give you some examples. First a graphical
;; dialog:
;;   (x-popup-dialog t '("How about making a choice?"
;;                       ("Choice1" . value1)
;;                       ("Choice2" . value2))
;;                   nil)
;;
;; Text dialog (a menu actually):
;;   (let ((tmm-completion-prompt "How about making a choice?\n\n"))
;;     (tmm-prompt '("" ("" ("Choice1" . value1) ("Choice2" . value2)))))
;;
;; Now, if you want to abstract the implementation between graphical and
;; text interface it could be a function like this:
;;   (defun my-dialog (title item-alist)
;;     (if (display-popup-menus-p)
;;         (x-popup-dialog t (cons title item-alist) nil)
;;       (let ((tmm-completion-prompt (concat title "\n\n")))
;;         (tmm-prompt (list "" (cons "" item-alist))))))
;;
;; Example:
;;   (my-dialog "How about making a choice?"
;;              '(("Choice1" . value1)
;;                ("Choice2" . value2)))


;; (setq default-indicate-buffer-boundaries 'left)


;; ;;;;; from http://www.florian-diesch.de/doc/emacs/add-to-gnomes-recently-used-documents/
;; (defun fd-add-file-to-recent ()
;;   (when buffer-file-name
;;     (start-process "addtorecent" nil "addtorecent"
;;                    (concat "file://" buffer-file-name)
;;                    "text/plain"
;;                    "Emacs"
;;                    "emacsclient %F")))

;; (add-hook 'find-file-hook 'fd-add-file-to-recent)


;; (require 'autopair)
;; (autopair-global-mode 1)
;; (setq autopair-autowrap t)


;; (setq elscreen-mode-to-nickname-alist
;;         '(("[Ss]hell" . "shell")
;;           ("compilation" . "compile")
;;           ("python" . "Python")
;;           ("lisp" . "Emacs")
;;           ("html" . "Web")
;;           ("javascript" . "Web")
;; ))


;; (add-to-list 'auto-mode-alist '("logcat" . android-logcat-mode))
;; ...
;; (defvar android-logcat-font-lock-keywords
;;   (list '("^V/.*$"
;; 	  . font-lock-comment-face)
;; 	'("^W/.*$"
;; 	  . font-lock-constant-face)
;; 	'("^E/.*$"
;; 	  . font-lock-warning-face)))

;; (define-derived-mode android-logcat-mode text-mode "Android-Logcat"
;;   "Major mode for looking at Android logcat output."
;;   (interactive)
;;   (auto-revert-tail-mode)
;;   (goto-char (point-max))
;;   (set (make-local-variable 'font-lock-defaults)
;;        '(android-logcat-font-lock-keywords))
;;   (font-lock-mode 1))


;; ;; emacs 24.x
;; (setq package-archives '(("ELPA" . "http://tromey.com/elpa/")
;;                          ("gnu" . "http://elpa.gnu.org/packages/")
;;                          ("marmalade" . "http://marmalade-repo.org/packages/")))