;;----------------------------------------------------------------------------
;; Manuel López-Ibáñez .emacs file
;; <http://iridia.ulb.ac.be/~manuel/>
;;
;; I don't claim that anything in this file is correct, efficient or
;; good style.  Send comments and suggestions to
;; <manuel.lopez-ibanez@ulb.ac.be>
;;
;; Download the text version from:
;;  <http://iridia.ulb.ac.be/~manuel/files/dotemacs.txt>
;;
;; The latest version can be found at:
;;  <http://iridia.ulb.ac.be/~manuel/dotemacs.html>
;;----------------------------------------------------------------------------
;; TODO
;; * How to show whether the current buffer is a symlink in the modeline?
;; * How to show the file pointed by the symlink?
;; * I think Xlaunch is obsolete. How to remove it?

;; Set the debug option when there is trouble...
;;(setq debug-on-error t)

(require 'cl) ;; turn on Common Lisp support
(defvar *emacs-load-start* (current-time))

;;-----------------------------------------------------------------
;; Byte-compile .emacs everytime is saved.
;;-----------------------------------------------------------------
(defun byte-compile-user-init-file ()
  (let ((byte-compile-warnings '(unresolved)))
    ;; in case compilation fails, don't leave the old .elc around:
    (when (file-exists-p (concat user-init-file ".elc"))
      (delete-file (concat user-init-file ".elc")))
    (byte-compile-file user-init-file)
    (message "%s compiled" user-init-file)
    ))

(defun my-emacs-lisp-mode-hook ()
  (when (equal buffer-file-name user-init-file)
    (add-hook 'after-save-hook 'byte-compile-user-init-file t t)))

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

;;-----------------------------------------------------------------
;; try-require: attempt to load a feature/library, failing silently
;;-----------------------------------------------------------------
(defvar missing-packages-list nil
  "List of packages that `try-require' can't find.")

(defun try-require (feature)
  "Attempt to load a library or module. Return true if the
library given as argument is successfully loaded. If not, instead
of an error, just add the package to a list of missing packages."
  (condition-case err
      ;; protected form
      (progn
        (message "Checking for library `%s'..." feature)
        (if (stringp feature)
            (load-library feature)
          (require feature))
        (message "Checking for library `%s'... Found" feature))
    ;; error handler
    (file-error  ; condition
     (progn
       (message "Checking for library `%s'... Missing" feature)
       (add-to-list 'missing-packages-list feature))
     nil)))
;;-----------------------------------------------------------------

;;-----------------------------------------------------------------
;; CUSTOM first to override it later.
;;-----------------------------------------------------------------
(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.
 '(LaTeX-command "latex -shell-escape")
 '(LaTeX-indent-environment-list (quote (("verbatim" current-indentation) ("verbatim*" current-indentation) ("array") ("displaymath") ("eqnarray") ("eqnarray*") ("equation") ("equation*") ("picture") ("tabbing") ("table") ("table*") ("tabular" ignore) ("tabular*"))))
 '(TeX-PDF-mode t)
 '(TeX-output-view-style (quote (("^dvi$" ("^landscape$" "^pstricks$\\|^pst-\\|^psfrag$") "%(o?)dvips -t landscape %d -o && gv %f") ("^dvi$" "^pstricks$\\|^pst-\\|^psfrag$" "%(o?)dvips %d -o && gv %f") ("^dvi$" ("^a4\\(?:dutch\\|paper\\|wide\\)\\|sem-a4$" "^landscape$") "%(o?)xdvi %dS -paper a4r -s 0 %d") ("^dvi$" "^a4\\(?:dutch\\|paper\\|wide\\)\\|sem-a4$" "%(o?)xdvi %dS -paper a4 %d") ("^dvi$" ("^a5\\(?:comb\\|paper\\)$" "^landscape$") "%(o?)xdvi %dS -paper a5r -s 0 %d") ("^dvi$" "^a5\\(?:comb\\|paper\\)$" "%(o?)xdvi %dS -paper a5 %d") ("^dvi$" "^b5paper$" "%(o?)xdvi %dS -paper b5 %d") ("^dvi$" "^letterpaper$" "%(o?)xdvi %dS -paper us %d") ("^dvi$" "^legalpaper$" "%(o?)xdvi %dS -paper legal %d") ("^dvi$" "^executivepaper$" "%(o?)xdvi %dS -paper 7.25x10.5in %d") ("^dvi$" "." "%(o?)xdvi %dS %d") ("^pdf$" "." "okular %o") ("^html?$" "." "netscape %o"))))
 '(TeX-view-program-list (quote (("okular" "okular %o"))))
 '(TeX-view-program-selection (quote (((output-dvi style-pstricks) "dvips and gv") (output-dvi "xdvi") (output-pdf "okular") (output-html "xdg-open"))))
 '(blink-cursor-mode nil)
 '(browse-url-browser-function (quote browse-url-default-browser))
 '(c-default-style (quote ((c-mode . "K&R") (java-mode . "java") (other . "gnu"))))
 '(case-fold-search t)
 '(case-replace t)
 '(column-number-mode t)
 '(compilation-scroll-output t)
 '(diff-default-read-only t)
 '(ecb-options-version "2.32")
 '(ediff-window-setup-function (quote ediff-setup-windows-plain))
 '(ess-execute-in-process-buffer t)
 '(ess-language "R")
 '(font-latex-fontify-script nil)
 '(font-latex-fontify-sectioning (quote color))
 '(font-latex-title-fontify (quote color) t)
 '(frame-title-format "Emacs: %b %+%+ %f" t)
 '(gc-cons-threshold 1600000)
 '(highlight-nonselected-windows t)
 '(icon-title-format "Emacs - %b" t)
 '(inhibit-startup-screen t)
 '(initial-frame-alist (quote ((top . 1) (height . 100))))
 '(line-number-mode 1)
 '(mouse-wheel-mode t nil (mwheel))
 '(pc-select-meta-moves-sexps t)
 '(pc-select-selection-keys-only t)
 '(pc-selection-mode t nil (pc-select))
 '(reftex-extra-bindings t)
 '(ring-bell-function (quote ignore) t)
 '(safe-local-variable-values (quote ((ispell-dictionary . "british") (auto-fill-mode) (TeX-master . race-test) (ess-indent-level . 2) (ess-continued-statement-offset . 2) (ess-brace-offset . 0) (ess-expression-offset . 4) (ess-else-offset . 0) (ess-brace-imaginary-offset . 0) (ess-continued-brace-offset . 0) (ess-arg-function-offset . 2) (ess-close-brace-offset . 0) (ispell-current-dictionary . british) (LocalWords . parallelized) (TeX-master . automoaco\.tex) (TeX-master . beamaco-csa) (ess-style . DEFAULT) (ess-fancy-comments) (ispell-local-dictionary . british) (Local . british) (bibtex-sort-ignore-string-entries))))
 '(scroll-step 1)
 '(search-whitespace-regexp "[  
]+")
 '(show-paren-mode t)
 '(smerge-command-prefix "ñ")
 '(speedbar-frame-parameters (quote ((minibuffer) (width . 20) (border-width . 0) (menu-bar-lines . 0) (tool-bar-lines . 0) (unsplittable . t) (set-background-color "black"))))
 '(suggest-key-bindings 10)
 '(tool-bar-mode nil)
 '(track-eol t)
 '(transient-mark-mode t)
 '(undo-limit 200000)
 '(undo-strong-limit 300000)
 '(vc-follow-symlinks nil)
 '(whitespace-modes (quote (ada-mode asm-mode autoconf-mode awk-mode c-mode c++-mode cc-mode change-log-mode cperl-mode electric-nroff-mode emacs-lisp-mode f90-mode fortran-mode html-mode html3-mode java-mode jde-mode ksh-mode latex-mode LaTeX-mode lisp-mode m4-mode makefile-mode modula-2-mode nroff-mode objc-mode pascal-mode perl-mode prolog-mode python-mode scheme-mode sgml-mode sh-mode shell-script-mode simula-mode tcl-mode tex-mode texinfo-mode vrml-mode xml-mode bibtex-mode))))

(custom-set-faces
  ;; custom-set-faces 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.
 '(diff-added ((t (:foreground "#44DD11"))))
 '(diff-context ((t nil)))
 '(diff-file-header ((((class color) (min-colors 88) (background dark)) (:foreground "gray"))))
 '(diff-function ((t (:foreground "gray"))))
 '(diff-header ((((class color) (min-colors 88) (background dark)) (:foreground "gray"))))
 '(diff-hunk-header ((t (:foreground "gray"))))
 '(diff-nonexistent ((t (:inherit diff-file-header :strike-through nil))))
 '(diff-refine-change ((((class color) (min-colors 88) (background dark)) (:background "#182042"))))
 '(diff-removed ((t (:foreground "#FF3300")))))
;;-----------------------------------------------------------------

;;-------------------------------------------
;;  DISPLAY
;;-------------------------------------------
;; Macro to detect if we are under X.
(if (not (fboundp 'Xlaunch))
    (defmacro Xlaunch (&rest x)
      (list 'if (eq window-system 'x)(cons 'progn x)))
  (message ".emacs: Xlaunch already defined!"))
(Xlaunch
 (setq default-frame-alist
       '(
;;      Use Emacs.menuBar: on
;       (menu-bar-lines . 1)
;;       Use Emacs.geometry:    80x25+0+10
;        (width . 80) (height . 25) (top . 10) (left . 0)
;;       Use Emacs.horizontalScrollBars: off
;         (horizontal-scroll-bars . nil)
;;       Use Emacs.scrollBarWidth: 12
;         (scroll-bar-width . 12)
;;        Use Emacs.verticalScrollBars: right
;         (vertical-scroll-bars . right)
;;        Use Emacs*bitmapIcon: on
         (icon-type . t)
;         use xlsfonts -fn and xfd -fn
;         .Xdefaults: Emacs*fon
(font . "-xos4-terminus-medium-r-normal--16-160-72-72-c-80-iso10646-1")
;;        (font . "-xos4-terminus-medium-r-normal--20-200-72-72-c-100-iso10646-1")
;;        (font . "terminus-20")
;;        (font . "Terminus-20")
;;      (font . "9x15")
;;       Use emacs*cursorColor: Orchid
         (cursor-color . "Orchid")
;;       Use Emacs*pointerColor:        Orange ??
         (mouse-color . "Orchid")
         (foreground-color . "Wheat")
         (background-color . "DarkSlateGray")
         ))
)
(set-face-foreground 'modeline "black")
(set-face-background 'modeline "gray")

(if (not window-system) (menu-bar-mode nil))
(if (not window-system) 
    (progn 
      (require 'color-theme)
      (color-theme-initialize)
      (color-theme-dark-laptop)))

(which-function-mode t)       ; Show function name in modeline
(setq which-func-maxout 0)    ; No limit
(fset 'yes-or-no-p 'y-or-n-p) ; Make all "yes or no" prompts show "y
                              ; or n" instead


;; Set up WindMove to be able to move between windows with control-arrow
(when (fboundp 'windmove-default-keybindings)
  (windmove-default-keybindings 'control))

;;-----------------------------------------------------------------

;;-----------------------------------------------------------------
; Color and Fonts.
;;-----------------------------------------------------------------

;(when (try-require 'color-theme)
  ;(color-theme-initialize)
  ;(color-theme-robin-hood))

(require 'font-lock)
(if (fboundp 'global-font-lock-mode) 
    (global-font-lock-mode t))        ; By default turn on colorization.
(setq font-lock-mode-maximum-decoration t)
;(setq frame-background-mode 'dark)

(prefer-coding-system 'utf-8);; Enable UTF-8 by default
;; Emacs < 23 sometimes require setting these directly. 
;; Now they cause more problems than they solve.
;; (setq locale-coding-system 'utf-8)
;; (set-terminal-coding-system 'utf-8)
;; (set-keyboard-coding-system 'utf-8)
;; (set-selection-coding-system 'utf-8)

; If images are supported than display them when visiting them
;(if (fboundp 'auto-image-file-mode)
;    (auto-image-file-mode 1))
;;-----------------------------------------------------------------

;;-----------------------------------------------------------
;;      SERVER MODE
;;-----------------------------------------------------------
;; FIXME: I never got this to work correctly.
;;
;; Using server mode means that after starting emacs, eg from an
;; icon, there is an always-running process, which handles editing
;; requests.
;;
;; Client:
;;   alias emacs='emacsclient --alternate-editor emacs '
;; in $HOME/.bashrc. You can get this startup file re-read without
;; re-starting a terminal window, by a command such as
;;    % . .bashrc
;;
;(when (try-require 'server)
;(server-start)
;; Do not repeat custom-set-variables
;; (custom-set-variables
;;  '(server-done-hook (quote ((lambda nil (kill-buffer nil)) delete-frame)))
;;  '(server-switch-hook (quote ((lambda nil (let (server-buf)
;;                    (setq server-buf (current-buffer))
;;                    (bury-buffer)
;;                    (switch-to-buffer-other-frame server-buf))))))
;;  )

;; A function to wrap up editing of a buffer, saving it first if edited.
;; Below, this is attached to a function key. This function is only useful
;; if you are using server mode.
;;(defun wrap-up ()
;;  (interactive)
;;  (save-buffer)
;;  (server-edit))
;; (add-hook 'server-done-hook (lambda nil (kill-buffer nil)) t)
;; (add-hook 'server-visit-hook 'raise-frame t)


;;-----------------------------------------------------------------
;;  KEYS
;;-----------------------------------------------------------------
; Under X to get the suppr key working.
(Xlaunch (define-key global-map [(delete)] "\C-d"))
;;Delete does deletion like ctrl-D:
;;(define-key global-map [(delete)]    "\C-d")

;; Make shifted direction keys work on the Linux console or in an xterm
 (when (member (getenv "TERM") '("linux" "xterm"))
   (dolist (prefix '("\eO" "\eO1;" "\e[1;"))
     (dolist (m '(("2" . "S-") ("3" . "M-") ("4" . "S-M-") ("5" . "C-")
                  ("6" . "S-C-") ("7" . "C-M-") ("8" . "S-C-M-")))
       (dolist (k '(("A" . "<up>") ("B" . "<down>") ("C" . "<right>")
                    ("D" . "<left>") ("H" . "<home>") ("F" . "<end>")))
         (define-key function-key-map
                     (concat prefix (car m) (car k))
                     (read-kbd-macro (concat (cdr m) (cdr k))))))))

; X selection manipulation
(if (not (fboundp 'x-own-selection))
    (defun x-own-selection (s) (x-set-selection `PRIMARY s))
  (message ".emacs: x-own-selection already defined!"))

(global-set-key [(shift insert)] '(lambda () (interactive)
       (insert (x-get-selection))))
(global-set-key [(control insert)] '(lambda () (interactive)
       (x-own-selection (buffer-substring (point) (mark)))))

;;; XEmacs compatibility
(global-set-key [(control tab)] `other-window)
(global-set-key [(meta g)] `goto-line)
(defun switch-to-other-buffer () 
  (interactive) (switch-to-buffer (other-buffer) 1))
(global-set-key [(meta control ?l)] `switch-to-other-buffer)
(global-set-key [(meta O) ?H] 'beginning-of-line)
(global-set-key [(meta O) ?F] 'end-of-line)


;;;(global-set-key [f3] 'ps-print-buffer-with-faces)
(define-key global-map [f5] 'font-lock-fontify-buffer)
(define-key global-map [f6] 'isearch-repeat-forward)
(define-key global-map [f10] 'wrap-up)
(global-set-key [home] 'beginning-of-line)
(global-set-key [end] 'end-of-line)
(global-set-key [(control home)] 'beginning-of-buffer)
(global-set-key [(control end)] 'end-of-buffer)
;; Make control+pageup/down scroll the other buffer
(global-set-key [(control next)] 'scroll-other-window)
(global-set-key [(control prior)] 'scroll-other-window-down)
;; I do this by accident too often
;;(global-set-key [(control z)]       'undo)
(global-set-key [(control shift z)] 'redo)
;;(global-unset-key "\C-z")
(global-unset-key "\C-x\C-z")
; Replace buffer-list (if we're not going to use ibuffer.el):
(global-set-key "\C-x\C-b" 'electric-buffer-list)
;;(global-set-key "\C-x\C-b" 'buffer-menu)

;(global-set-key "\C-c\C-c" 'compile)
;(global-set-key "\C-cc" 'comment-region)
(defun swap-compile-comment-keys ()
 "Swap compile and commen-region keybindings"
 (local-unset-key "\C-c\C-c")
 (local-unset-key "\C-cc")
 (local-set-key "\C-c\C-c" 'compile)
 (local-set-key "\C-cc" 'comment-region)
)
(add-hook 'makefile-mode-hook 'swap-compile-comment-keys)

(global-set-key "\C-cg" 'goto-line)
(global-set-key "\C-x\C-r" 'revert-buffer)
;; This runs mark-sexp which is not useful. Better give it another
;; purpose outside Emacs.
(global-unset-key (read-kbd-macro "C-M-SPC"))

;; DEPRECATED: This is already the default in recent emacs
;; (defun centerer ()
;;    "Repositions current line: once middle, twice top, thrice bottom"
;;    (interactive)
;;    (cond ((eq last-command 'centerer2)  ; 3 times pressed = bottom
;;        (recenter -1))
;;       ((eq last-command 'centerer1)  ; 2 times pressed = top
;;        (recenter 0)
;;        (setq this-command 'centerer2))
;;       (t                             ; 1 time pressed = middle
;;        (recenter)
;;        (setq this-command 'centerer1))))
;;(global-set-key "\C-l"             'centerer)

(defun shuffle-lines (beg end)
  "Scramble all the lines in region defined by BEG END
If region contains less than 2 lines, lines are left untouched."
  (interactive "*r")
  (catch 'cancel
    (save-restriction
      (narrow-to-region beg end)
      ;;   Exit when there is not enough lines in region
      (if (< (- (point-max) (point-min)) 3)
      (throw 'cancel t))

      ;;    Prefix lines with a random number and a space
      (goto-char (point-min))
      (while (not (eobp))
        (insert (int-to-string (random 32000)) " ")
        (forward-line 1))

      ;;  Sort lines according to first field (random number)
      (sort-numeric-fields 1 (point-min) (point-max))

      (goto-char (point-min))  ;Remove the prefix fields
      (while (not (eobp))
        (delete-region (point) (progn (forward-word 1) (+ (point) 1)))
        (forward-line 1))
      )))


;; ISearch mods
;; Always use regexps
(global-set-key [(control s)]               'isearch-forward-regexp)
(global-set-key [(control r)]               'isearch-backward-regexp)
(global-set-key [(control c)(meta %)]       'query-replace-regexp)

;; Not really key-bindings.  These just rename a few commonly used
;; functions
(defalias 'cr 'comment-region)
(defalias 'ucr 'uncomment-region)
(defalias 'rr 'replace-rectangle)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Moving lines up & down with <M-up> & <M-down>
(defun move-line (&optional n)
  "Move current line N (1) lines up/down leaving point in place."
  (interactive "p")
  (when (null n)
    (setq n 1))
  (let ((col (current-column)))
    (beginning-of-line)
    (forward-line)
    (transpose-lines n)
    (forward-line -1)
    (forward-char col))
  (indent-according-to-mode))

(defun move-line-up (n)
  "Moves current line N (1) lines up leaving point in place."
  (interactive "p")
  (move-line (if (null n) -1 (- n))))

(defun move-line-down (n)
  "Moves current line N (1) lines down leaving point in place."
  (interactive "p")
  (move-line (if (null n) 1 n)))

(defun move-region (start end n)
  "Move the current region up or down by N lines."
  (interactive "r\np")
  (let ((line-text (delete-and-extract-region start end)))
    (forward-line n)
    (let ((start (point)))
      (insert line-text)
      (setq deactivate-mark nil)
      (set-mark start))))

(defun move-region-up (start end n)
  "Move the current region up by N lines."
  (interactive "r\np")
  (move-region start end (if (null n) -1 (- n))))

(defun move-region-down (start end n)
  "Move the current region down by N lines."
  (interactive "r\np")
  (move-region start end (if (null n) 1 n)))

;; http://www.emacswiki.org/emacs/MoveLineRegion
;; These, in combination with MoveLine and MoveRegion, provide
;; behavior similar to Eclipse’s Alt-Up/Down. They use MoveLine if
;; there is no active region, MoveRegion if there is. Note that unlike
;; in Eclipse, the region will not expand to the beginning of the
;; first line or the end of the last line.
(defun move-line-region-up (start end n)
  (interactive "r\np")
  (if (region-active-p) (move-region-up start end n) (move-line-up n)))

(defun move-line-region-down (start end n)
  (interactive "r\np")
  (if (region-active-p) (move-region-down start end n) (move-line-down n)))

;;(global-set-key (kbd "M-p") 'move-line-region-up)
;;(global-set-key (kbd "M-n") 'move-line-region-down)
(global-set-key [(meta up)]   'move-line-region-up)
(global-set-key [(meta down)] 'move-line-region-down)


;; Rectangle
(when (try-require 'rect)
  (defun copy-rectangle-as-kill (start end)
    "Copy rectangle with corners at point and mark; save as last
killed one.  Calling from program, supply two args START and END,
buffer positions.  But in programs you might prefer to use
`extract-rectangle'."
    (interactive "r")
    (setq killed-rectangle (extract-rectangle start end))
    (message "Rectangle saved."))
  (global-set-key "\C-xrw"           'copy-rectangle-as-kill)
)

(defun insert-date-string ()
  "Insert a nicely formated date string."
  (interactive)
  (insert (format-time-string "%Y-%m-%d")))

(defun delete-horizontal-space-forward ()
  ;; adapted from `delete-horizontal-space'
  "*Delete all spaces and tabs after point."
  (interactive "*")
  (delete-region (point) (progn (skip-chars-forward " \t") (point))))
(global-set-key "\M- " 'delete-horizontal-space-forward)

;;-----------------------------------------------------------------


;;-----------------------------------------------------------------
;; PACKAGES CONF
;;-----------------------------------------------------------------
;(dynamic-completion-mode) ; Use alt-enter
;; By default start in TEXT mode.
(setq default-major-mode (lambda () (text-mode) (font-lock-mode t)))
;; One may want to disable auto-fill through 
;(remove-hook 'text-mode-hook 'turn-on-auto-fill)
(add-hook 'text-mode-hook 'turn-on-auto-fill)
(add-hook 'text-mode-hook 'turn-on-flyspell);; flyspell is ispell on-the-fly
;(setq fill-column 79)

; Don't add lines on the end of lines unless we want.
(setq next-line-add-newlines nil)
;; Indentation can insert tabs if this is non-nil.
(setq-default indent-tabs-mode nil)

; Don't ask to revert for TAGS
(setq revert-without-query (cons "TAGS" revert-without-query))

;; turn on auto (de)compression
(auto-compression-mode t)

(put 'downcase-region 'disabled nil)

;; Adjust load path to include $HOME/lib/emacs/, etc
(setq load-path
      (cons (concat (getenv "HOME") "/.emacs.d/")
            (cons "/usr/local/share/emacs/site-lisp/" load-path)))
;;      (cons (concat (getenv "HOME") "/.ESS/ess/lisp/") load-path))

;; Does not trigger error if we do not have the following
(when (try-require 'ess-site)
  ; Turn off annoying comment behaviour
  (setq ess-fancy-comments nil)
  ; Bug in ESS, very slow eval-and-go
  (setq ess-eval-visibly-p nil)
  ; http://code.google.com/p/ess-tracebug
  (when (try-require 'ess-tracebug)
    (add-hook 'ess-post-run-hook 'ess-tracebug t)
    )
  )

; FIXME: use try-require
;(load "$HOME/.emacs.d/comet-mode")

;;;  Jonas.Jarnestrom<at>ki.ericsson.se A smarter               
;;;  find-tag that automagically reruns etags when it cant find a               
;;;  requested item and then makes a new try to locate it.                      
;;;  Fri Mar 15 09:52:14 2002    
(defadvice find-tag (around refresh-etags activate)
  "Rerun etags and reload tags if tag not found and redo find-tag.              
   If buffer is modified, ask about save before running etags."
  (let ((extension (file-name-extension (buffer-file-name))))
    (condition-case err
        ad-do-it
      (error (and (buffer-modified-p)
                  (not (ding))
                  (y-or-n-p "Buffer is modified, save it? ")
                  (save-buffer))
             (refresh-etags extension)
             ad-do-it))))

(defun refresh-etags (&optional extension)
  "Run etags on all peer files in current dir and reload them silently."
  (interactive)
  (shell-command (format "etags *.%s" (or extension "el")))
  (let ((tags-revert-without-query t))  ; don't query, revert silently          
    (visit-tags-table default-directory nil)))

;;------------------------
;; ISPELL / ASPELL
;;------------------------
;; Switch to using aspell, it's much cleverer than ispell:
(setq-default ispell-program-name "aspell")
;; (setq ispell-local-dictionary-alist
;;       '(
;;      ("spanish"
;;       "[A-Za-zÁÉÍÓÚÜÑáéíóúüñ]" "[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ]" "[']" t
;;       ("-d" "spanish" "-T" "latin1") "~latin1" iso-latin-9)
;;      ("spanish-html"
;;       "[A-Za-zÁÉÍÓÚÜÑáéíóúüñ]" "[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ]" "" nil
;;       ("-B" "-H" "-d" "spanish" "-T" "latin1") "~latin1" iso-latin-9)
;;      )
;; )




;;---------------------------------------------------
;; WHITESPACE Deletes trailing whitespace in email/files when save/send
;; See: http://www.splode.com/~friedman/software/emacs-lisp/
;;---------------------------------------------------
;; (if (require 'whitespace "whitespace" t)
;;     (progn (add-hook 'write-file-hooks 'whitespace-write-file-hook)
;;            (setq whitespace-auto-cleanup t)
;;            (setq whitespace-display-in-modeline nil) )
;;   (message "Warning: .emacs: whitespace.el not available!"))

;; (if (and (require 'nuke-trailing-whitespace "nuke-trailing-whitespace" t)
;;          (fboundp 'nuke-trailing-whitespace))
;;     (progn  (autoload 'nuke-trailing-whitespace "nuke-trailing-whitespace" nil t)
;;             (message "OK: .emacs: nuke-trailing-whitespace in  nuke-trailing-whitespace.el!"))
;;   ;;   (if (and (require 'whitespace "whitespace" t)
;;   ;;            (fboundp 'whitespace-cleanup))
;;   ;;       (progn  (autoload 'whitespace-cleanup "whitespace" nil t)
;;   ;;               (defun nuke-trailing-whitespace () (delete-trailing-whitespace))
;;   ;;               (message "OK: .emacs: whitespace-cleanup in whitespace.el!"))
;;   (if (and (require 'whitespace "whitespace" t)
;;            (fboundp 'nuke-trailing-whitespace))
;;       (progn  (autoload 'nuke-trailing-whitespace "whitespace" nil t)
;;               (message "OK: .emacs: nuke-trailing-whitespace in whitespace.el!"))
;;     (if (fboundp 'delete-trailing-whitespace)
;;         (progn (defun nuke-trailing-whitespace () (delete-trailing-whitespace))
;;                (message "Warning: .emacs: nuke-trailing-whitespace not available, using delete-trailing-whitespace!"))
;;       (message "Warning: .emacs: nuke-trailing-whitespace not available!"))
;;     ))
;;(setq whitespace-modes (cons 'bibtex-mode (cons 'bibtex-mode
;;                                                whitespace-modes)))

;; ;;(add-hook 'mail-send-hook 'nuke-trailing-whitespace)
;(add-hook 'write-file-hooks 'nuke-trailing-whitespace)

;Show path info in otherwise identical filenames
(when (try-require 'uniquify)
  (setq uniquify-buffer-name-style 'post-forward)
  (setq uniquify-after-kill-buffer-p t)
)

;; -----------------------------------------------------
;; iswitchb -- switch buffers
;; -----------------------------------------------------
(iswitchb-mode t)
(setq iswitchb-buffer-ignore '("^ " "*Buffer"))
(add-hook
 'iswitchb-define-mode-map-hook
 '(lambda ()
    (define-key iswitchb-mode-map [up] 'iswitchb-next-match)
    (define-key iswitchb-mode-map [down] 'iswitchb-prev-match)
    (define-key iswitchb-mode-map [right] 'iswitchb-next-match)
    (define-key iswitchb-mode-map [left] 'iswitchb-prev-match)))

(defadvice iswitchb-kill-buffer (after rescan-after-kill activate)
  "*Regenerate the list of matching buffer names after a kill.
    Necessary if using `uniquify' with `uniquify-after-kill-buffer-p'
    set to non-nil."
  (setq iswitchb-buflist iswitchb-matches)
  (iswitchb-rescan))

(defun iswitchb-rescan ()
  "*Regenerate the list of matching buffer names."
  (interactive)
  (iswitchb-make-buflist iswitchb-default)
  (setq iswitchb-rescan t))
;; -----------------------------------------------------

;;I never use this
;;Make a "recent file list"
;; (if (require 'recentf "recentf" t)
;;     (recentf-mode 1)
;;   (message "Warning: .emacs: recentf file list not available!"))


(when (try-require 'ffap) ; Enhace C-x C-f to open file from text.
  ;; rebind C-x C-f and others to the ffap bindings (see variable ffap-bindings)
  (ffap-bindings)
  ;; C-u C-x C-f finds the file at point
  ;;(setq ffap-require-prefix t)
  ;; browse urls at point via w3m
  (setq ffap-url-fetcher 'w3m-browse-url)
  )

;; Save minibuffer history between sessions
(when (fboundp 'savehist-mode)
  (savehist-mode 1))


(autoload 'tidy-buffer "tidy" "Run Tidy HTML parser on current buffer" t)
(autoload 'tidy-parse-config-file "tidy" "Parse the `tidy-config-file'" t)
(autoload 'tidy-save-settings "tidy" "Save settings to `tidy-config-file'" t)
(autoload 'tidy-build-menu  "tidy" "Install an options menu for HTML Tidy." t)
(defun my-html-helper-mode-hook () "Customize my html-helper-mode."
  (tidy-build-menu html-helper-mode-map)
  (local-set-key [(control c) (control c)] 'tidy-buffer)
  (setq sgml-validate-command "tidy")
  (tidy-build-menu))
(add-hook 'html-helper-mode-hook 'my-html-helper-mode-hook)
(add-hook 'html-mode-hook 'my-html-helper-mode-hook)

(defun html-helper-custom-insert-timestamp ()
  "Custom timestamp insertion function."
  (insert "Last modified: ")
  (insert (format-time-string "%e %B %Y")))
(setq html-helper-timestamp-hook 'html-helper-custom-insert-timestamp)

;; CSS-mode
(setq cssm-indent-level 4)
(setq cssm-newline-before-closing-bracket t)
(setq cssm-indent-function 'cssm-c-style-indenter)
(setq cssm-mirror-mode nil)

;; (add-hook 'html-helper-mode-hook
;;           (lambda ()
;;             (defun tidy-html ()
;;               "Run Tidy HTML parser on current region."
;;               (interactive)
;;               (let ((start (mark))
;;                     (end (point))
;;                     (command "tidy -i -q --tidy-mark n --gnu-emacs y --indent-spaces 1 --wrap 80 --replace-color y"))
;;                 (shell-command-on-region start end command t t
;;                                          "tidy-errors")))
;;             (define-key html-helper-mode-map [(meta q)] 'tidy-html)))


;; auto-raise and -lower. If mouse moves into/out of the emacs frame it gets
;; raised/lowered automatically:
;; IT DOES NOT WORK FOR ME
;(auto-raise-mode 1)
;(auto-lower-mode 1)

;;----------------
;; AUTO-SAVE
;;----------------
(setq
 auto-save-interval 300 ;auto-save every 5 minutes
 auto-save-timeout nil
; version-control 'never
)

;; Save positions in files between sessions
(when (try-require 'saveplace)
  (setq-default save-place t)
  ;; For server
  (add-hook 'server-visit-hook 'save-place-find-file-hook t)
)

;;----------------
;;  AucTeX
;;----------------
(when (try-require 'tex-site)
  ;; some basic customizations
  (setq TeX-auto-save t)
  (setq TeX-parse-self t)
  (setq-default TeX-master nil) ; Query for master file.
  ;; default Style and Options.
  (setq LaTeX-default-options "a4paper")
  ;; don't modify font size
  (setq font-latex-title-fontify 'color)
  ;; some small but handy macros
  (defun LaTeX-insert-footnote ()
    "Insert a \\footnote{} macro in a LaTeX-document."
    (interactive)
    (TeX-insert-macro "footnote"))
  (defun LaTeX-insert-note ()
    "Insert a \\note{} macro in a LaTeX-document."
    (interactive)
    (TeX-insert-macro "note"))
  (defun LaTeX-insert-index ()
    "Insert a \\index{} macro in a LaTeX-document."
    (interactive)
    (TeX-insert-macro "index"))
  (defun my-auctex-settings ()
    "Some local modifications to AucTeX variables."
    (setq TeX-master nil) ; Query for master file.
    )
  (defvar LaTeX-mode-setup-hook nil
    "Hook for things to do before LaTeX-mode is defined.")
  (defadvice latex-mode (before latex-mode-setup-advice)
    (run-hooks 'LaTeX-mode-setup-hook))
  (add-hook 'LaTeX-mode-setup-hook 'my-auctex-settings t)
  
  (defun my-auctex-keys ()
    "Some local modifications to AucTeX keybindings."
    ;; Local Functions above
    (local-set-key "\C-cf" 'LaTeX-insert-footnote)
    (local-set-key "\C-cn" 'LaTeX-insert-note)
    (setq search-whitespace-regexp "[ \t\r\n]+")
    (local-set-key [(control s)] 'isearch-forward-regexp)
    (local-set-key [(control meta s)] 'isearch-forward)
    (local-set-key [(control r)] 'isearch-backward-regexp)
    (local-set-key [(control meta r)] 'isearch-backward)
    ;;  (local-set-key "\C-s" 'word-search-forward)
    ;;  (local-set-key "\C-r" 'word-search-backward)
    ;; use latex-help
    (define-key LaTeX-mode-map "\C-ci" 'latex-help)
    )


  (defun my-latex-add-ons ()
    "Anything you ever wanted in LaTeX-mode."
    ;; load some additional packages
    (try-require 'bib-cite)
    (try-require 'font-latex)
    
    ;; modify keys and vars
    (my-auctex-keys)
    (local-set-key [mouse-3] 'reftex-mode-menu)

    ;;----------------------------------------
    ;; RefTeX handling of \ref, \label, \cite
    ;;----------------------------------------
    ;; configure RefTeX before loading it.
    (setq
     reftex-enable-partial-scans t ; only parse current file
     reftex-save-parse-info t      ; save parsing results
     reftex-use-multiple-selection-buffers t ; diff buffs for label select.
     reftex-plug-into-AUCTeX t     ; interact with AucTeX, of course
     reftex-extra-bindings t       ; use additional C-c bindings
     )
   ;;  (when (try-require 'reftex)
   ;;    (autoload 'reftex-mode "reftex" "RefTeX minor mode" t)
   ;;    (autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" t)
   ;;  )
    ;; now really use RefTeX
    (turn-on-reftex)

    
    ;; ensure auto-fill is done, enable outline and don't do func-menu
    (turn-off-auto-fill)
    ;;(outline-minor-mode 1)
    ;; (remove-func-menu-auto-rescan)


    (defvar LaTeX-align-current-environments
      (mapcar 'car LaTeX-indent-environment-list)
      "List of LaTeX environments to do align.")

    (defun LaTeX-align-or-fill-function (&optional justify)
      "Variant of 'fill-paragraph-function' based on current
environment. In tabular-like environments, align
columns. Otherwise, fill as normal."
      (interactive "P")
      (if (member (LaTeX-current-environment)
                  LaTeX-align-current-environments)
          (save-excursion
            (LaTeX-mark-environment)
            (align-current) t)
        (LaTeX-fill-paragraph)))

    (setq fill-paragraph-function 'LaTeX-align-or-fill-function)
    (message "Making private modifications ..."))
  
  (add-hook 'LaTeX-mode-hook 'my-latex-add-ons)
  (add-hook 'TeX-mode-hook   'turn-off-auto-fill)
  )
         

;;---------------------------
;;  JavaScript MODE
;;  http://www.brgeight.se/downloads/emacs/javascript.el
;;---------------------------
(add-to-list 'auto-mode-alist '("\\.js\\'" . javascript-mode))
(autoload 'javascript-mode "javascript" nil t)
(setq javascript-indent-level 8)

;;---------------------------
;;  C/C++  MODE
;;---------------------------
(c-add-style
 "my-c-common-style"
 '("k&r"
   ;;    (setq tab-width 3
   ;; make sure spaces are used instead of tabs
   ;;            indent-tabs-mode nil)
   (c-basic-offset . 4)
   ))

(defun my-c-mode-common-hook ()
 "C/C++ mode with adjusted defaults."
 (c-set-style "my-c-common-style")
 (setq c++-tab-always-indent t)
 (setq c-backslash-column 79)
 (setq c-backslash-max-column 79)
 (c-set-offset 'inextern-lang '0) ; Do not indent extern "C" blocks.
 (message "Loading my-c-common-mode-hook...")
 (swap-compile-comment-keys)
 ;; (setq fill-column 79)
 )

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

(defun linux-c-mode ()
  "C mode with adjusted defaults for use with the Linux kernel."
  (interactive)
  (c-mode)
  (c-set-style "k&r")
  (setq c-basic-offset 3)
  (swap-compile-comment-keys)
  (message "Loading linux-c-mode...")
)

(defun gcc-c-mode-hook ()
  "C mode for GCC development."
  (which-function-mode t)       ; Show function name in modeline
  (setq which-func-maxout 0)  ; No limit
  (c-set-style "gnu")
  (c-set-offset 'inline-open 0)
  (swap-compile-comment-keys)
  (message "Loading gcc-c-mode...")
  )

(defun gcc-c-mode ()
  "C mode for GCC development."
  (interactive)
  (remove-hook 'c-mode-common-hook 'my-c-mode-common-hook)
;  (c-set-style "gnu")
;  (c-set-offset 'inline-open 0)
  (add-hook 'c-mode-common-hook 'gcc-c-mode-hook)
  (text-mode)
  (c-mode)
  )

;; -------------------------------------------
;; gnuplot mode
;; -------------------------------------------
(eval-after-load "gnuplot"
  (add-hook 'gnuplot-mode-hook
            '(lambda ()
               (define-key gnuplot-mode-map "\C-c\C-c" 'gnuplot-send-buffer-to-gnuplot)))
)

(eval-after-load "flyspell"
  '(local-set-key [(control ?\;)] 'flyspell-auto-correct-word)
  )

;;----------------------
;; PERL MODE
;;----------------------
;; Use cperl-mode instead of the default perl-mode
(add-to-list 'auto-mode-alist '("\\.\\([pP][Llm]\\|al\\)\\'" . cperl-mode))
(add-to-list 'interpreter-mode-alist '("perl" . cperl-mode))
(add-to-list 'interpreter-mode-alist '("perl5" . cperl-mode))
(add-to-list 'interpreter-mode-alist '("miniperl" . cperl-mode))
;;
(defun n-cperl-mode-hook ()
  "cPerl mode with adjusted defaults."
  (setq cperl-indent-level 4)
  (setq cperl-continued-statement-offset 0)
  (setq cperl-extra-newline-before-brace t)
  (set-face-background 'cperl-array-face "dark slate gray")
  (set-face-background 'cperl-hash-face "dark slate gray")
  )
(add-hook 'cperl-mode-hook 'n-cperl-mode-hook t)
;;(setq cperl-auto-newline t)
(setq cperl-invalid-face (quote off))
;; expands for keywords such as foreach, while, etc...
;;(setq cperl-electric-keywords t)


;;------------------------------------------------------------------------
;; Save a buffer in a specified EOL format with the C-x RET f
;;------------------------------------------------------------------------
;; For example, to save a buffer with Unix EOL format, type:
;;     C-x RET f unix RET C-x C-s.
;; To save it as DOS EOL format, type:  C-x RET f dos RET C-x C-s.
;;------------------------------------------------------------------------
(defun find-non-ascii ()
  "Find any non-ascii characters in the current buffer."
  (interactive)
  (occur "[^[:ascii:]]"))


(defun count-words-region (beginning end)
  "Print number of words in the region."
  (interactive "r")
  (message "Counting words in region ... ")
;;; 1. Set up appropriate conditions.
  (save-excursion
    (let ((count 0))
      (goto-char beginning)
;;; 2. Run the while loop.
      (while (and (< (point) end)
                  (re-search-forward "\\w+\\W*" end t))
        (setq count (1+ count)))
;;; 3. Send a message to the user.
      (cond ((zerop count)
             (message
              "The region does NOT have any words."))
            ((= 1 count)
             (message
              "The region has 1 word."))
            (t
             (message
              "The region has %d words." count)))))
  )

;; This is a macro I use in my research but it is useless for anyone else.
(fset 'pump_replace
   [?\C-  C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right C-right ?\C-w down C-right ?  ?\C-y ?\C-k ?\C-  home ?\C-w delete up return up ?\C-y home down])

;; Unset the debug option when there is trouble...
;;(setq debug-on-error nil)

;; warn that some packages were missing
(if missing-packages-list
    (progn (message "Packages not found: %S"
                    (nreverse missing-packages-list))))

(message "My .emacs loaded in %ds" (destructuring-bind (hi lo ms) (current-time)
                             (- (+ hi lo) (+ (first *emacs-load-start*) (second
                             *emacs-load-start*)))))
;; More information with the info file (Control-h i)
;;
;;--------------------------------------------
;;  END of .emacs $Revision: 278 $
;;--------------------------------------------