unofficial mirror of emacs-devel@gnu.org 
 help / color / mirror / code / Atom feed
* ECB configuration
@ 2012-07-05  6:37 Sajid Hussain
  0 siblings, 0 replies; only message in thread
From: Sajid Hussain @ 2012-07-05  6:37 UTC (permalink / raw)
  To: help-gnu-emacs; +Cc: bug-gnu-emacs, xemacs-patches, emacs-devel


[-- Attachment #1.1: Type: text/plain, Size: 621 bytes --]

Hi,

I am new to Emacs editor and also in this forum.
I am using Fedora 16, Emacs 23.3.1 and installed ECB through yum install
emacs-ecb.noarch. I have not made any changes in .emacs file. .emacs file
is attached.

I don't know how to use ECB, I just open files in a traditional way, after
opening the first file, every time I open a file the following error pop
up.

ssh: Could not resolve hostname C: Name or service not known
Process *tramp/ssh fni@C* exited abnormally with code 255

Could somebody guide me, how to resolve this problem. If possible kindly
refer me some good tutorial for using ECB.

Regards,
\sajid

[-- Attachment #1.2: Type: text/html, Size: 2947 bytes --]

[-- Attachment #2: .emacs --]
[-- Type: application/octet-stream, Size: 419853 bytes --]


;;; emacs-config-fni.el --- my Emacs config file

;; Copyright (C) 1999-2012 Fabrice Niessen

;; Author: Fabrice Niessen <(concat "fni" at-symbol "mygooglest.com")>
;; Time-stamp: <2012-07-03 Tue 13:02 opensilicon on ospakhmc04>
;; $Date: 2012-06-05 11:43:03 +0200 (Tue, 05 Jun 2012) $
;; $Revision: 7593 $
;; Keywords: emacs, dotfile, config

;;
;;    ___ _ __ ___   __ _  ___ ___
;;   / _ \ '_ ` _ \ / _` |/ __/ __|
;;  |  __/ | | | | | (_| | (__\__ \
;; (_)___|_| |_| |_|\__,_|\___|___/
;;

;; This file is NOT part of GNU Emacs.

;; This file is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this file. If not, see <http://www.gnu.org/licenses/>.


;;* Commentary

;; - Install for Windows users
;;
;;   + HOME variable
;;
;;     Don't put a trailing backslash at the end of your `HOME' variable (if
;;     you have any). Otherwise, `~/emacs.d/server' gets (for example)
;;     translated to `z://emacs.d/server' (double slash)!
;;
;;   + PATH variable
;;
;;     Put `c:\cygwin\bin' in the first place, in order to select the correct
;;     `find' command (for searches).
;;
;; - Citations
;;
;;   + "Show me your ~/.emacs and I will tell you who you are."
;;                                                         [Bogdan Maryniuk]
;;
;;   + "Emacs is like a laser guided missile. It only has to be slightly
;;      mis-configured to ruin your whole day."
;;                                                            [Sean McGrath]
;;
;;   + "While any text editor can save your files, only Emacs can save your
;;      soul."
;;                                                          [Per Abrahamsen]
;;
;; - Operating System
;;
;;   This is supposed to work both for Windows and for Linux.
;;
;; - Help
;;
;;   For help on The Emacs Editor, see
;;       (info "(emacs)")  <== `C-x C-e' here!
;;
;; - News
;;
;;   Emacs 23 has a daemon mode for starting Emacs in background (without
;;   opening any frames) and connect to it via emacsclient.
;;
;; - Emacs Tour
;;
;;   http://www.gnu.org/software/emacs/tour/

;;* Code

;; This file is only provided as an example. Customize it to your own taste!

(message "%sStarting up Emacs..." (format-time-string "[%Y-%m-%d %a %T] "))

(defvar my/load-verbose t)

;; uptimes
(when (string-match "XEmacs" (version))
  ;; XEmacs doesn't have `float-time'
  (defun float-time ()
    "Convert `current-time' to a floating point number."
    (multiple-value-bind (s0 s1 s2) (current-time)
      (+ (* (float (ash 1 16)) s0) (float s1) (* 0.0000001 s2)))))

(defconst my/emacs-load-time-start (float-time))

;; Identify what parts of your `.emacs' take so long. You can do
;; this e.g. by starting Emacs with "emacs -q", set up your
;; `load-path', and then evaluate
;;
;; (benchmark-run
;;   (require 'package))
;;
;; The first number appearing in the echo area will be the time needed to run
;; that command.
;;
;; Use autoloads, which delay the loading of the complete package until one of
;; the interactive functions is used.
;;
;; If you want to set options which need to be evaluated after a package is
;; loaded, you can use `eval-after-load'.

;; Load user specific config if we find it
(let* ((file "~/.emacs-pre-init-file")
       (gpg (concat file ".gpg")) ;; to keep secrets secret
       (el (concat file ".el")))
  (cond ((file-readable-p gpg) (load-file gpg))
        ((file-readable-p el) (load-file el))))

(message "* --[ Loading Emacs Config Fni ]--")

;; turn on Common Lisp support
(require 'cl)  ; provides useful things like `loop' and `setf'

;; allow quick include/exclude of setup parts -- DO NOT EDIT the DEFVAR!
(defvar chapter-0-environment t)  ; required
(defvar chapter-0-loading-libraries t)  ; required
(defvar chapter-0-debugging nil)
(defvar chapter-1-screen nil)
(defvar chapter-7-basic nil)
(defvar chapter-8-minibuffer nil)
(defvar chapter-10-help nil)
(defvar chapter-11-mark nil)
(defvar chapter-12-killing nil)
(defvar chapter-13-yanking nil)
(defvar chapter-15-rectangles nil)
(defvar chapter-16-cua-bindings nil)
(defvar chapter-17-registers nil)
(defvar chapter-18-display nil)
(defvar chapter-19-search nil)
(defvar chapter-20-fixit nil)
(defvar chapter-21-keyboard-macros nil)
(defvar chapter-22-files nil)
(defvar chapter-23-buffers nil)
(defvar chapter-24-windows nil)
(defvar chapter-25-frames nil)
(defvar chapter-26-international nil)
(defvar chapter-27-major-modes nil)
(defvar chapter-28-indentation nil)
(defvar chapter-29-text nil)
(defvar chapter-30-programs nil)
(defvar chapter-31-building nil)
(defvar chapter-32-maintaining nil)
(defvar chapter-33-abbrevs nil)
(defvar chapter-37-dired nil)
(defvar chapter-38-calendar-diary nil)
(defvar chapter-39-document-view nil)
(defvar chapter-40-gnus nil)
(defvar chapter-41-shell nil)
(defvar chapter-42-emacs-server nil)
(defvar chapter-43-printing nil)
(defvar chapter-47-sorting nil)
(defvar chapter-48-narrowing nil)
(defvar chapter-51-saving-emacs-sessions nil)
(defvar chapter-54-hyperlinking nil)
(defvar chapter-56-amusements nil)
(defvar chapter-57-customization nil)
(defvar chapter-AppG-ms-dos nil)
(defvar chapter-XX-emacs-display nil)
(defvar chapter-99-debugging nil)

;; EDIT HERE
(setq chapter-0-debugging t)
(setq chapter-1-screen t)
(setq chapter-7-basic t)
(setq chapter-8-minibuffer t)
(setq chapter-10-help t)
(setq chapter-11-mark t)
(setq chapter-12-killing t)
(setq chapter-13-yanking t)
(setq chapter-15-rectangles t)
(setq chapter-16-cua-bindings t)
(setq chapter-17-registers t)
(setq chapter-18-display t)
(setq chapter-19-search t)
(setq chapter-20-fixit t)
(setq chapter-21-keyboard-macros t)
(setq chapter-22-files t)
(setq chapter-23-buffers t)
(setq chapter-24-windows t)
(setq chapter-25-frames t)
(setq chapter-26-international t)
(setq chapter-27-major-modes t)
(setq chapter-28-indentation t)
(setq chapter-29-text t)
(setq chapter-30-programs t)
(setq chapter-31-building t)
(setq chapter-32-maintaining t)
(setq chapter-33-abbrevs t)
(setq chapter-37-dired t)
(setq chapter-38-calendar-diary t)
(setq chapter-39-document-view t)
(setq chapter-40-gnus t)
(setq chapter-41-shell t)
(setq chapter-42-emacs-server t)
(setq chapter-43-printing t)
(setq chapter-47-sorting t)
(setq chapter-48-narrowing t)
(setq chapter-51-saving-emacs-sessions t)
(setq chapter-54-hyperlinking t)
(setq chapter-56-amusements t)
(setq chapter-57-customization t)
(setq chapter-AppG-ms-dos t)
(setq chapter-XX-emacs-display t)
(setq chapter-99-debugging t)

(defvar my/load-times-list nil
  "List of chapters and time to load them.")

(defmacro chapter (chapterid chaptername &rest body)
  `(when ,chapterid
     (let (chapter-load-time-start this-chapter-load-time)
       (message "** %s" ,chaptername)
       (setq chapter-load-time-start (float-time))
       (progn ,@body)
       (setq this-chapter-load-time
             (concat "| " ,chaptername " | "
                     (message "%.2f" (- (float-time) chapter-load-time-start))
                     " |"))
       (add-to-list 'my/load-times-list this-chapter-load-time))))

(defun section (sectionname)
  (message "*** %s" sectionname))

(defun subsection (subsectionname)
  (message "**** %s" subsectionname))

;;* Environment

(chapter chapter-0-environment "0 Environment"

;;** Type of OS

      (section "Type of OS")

      (defconst running-ms-windows
        (eq system-type 'windows-nt)
        "Running a native Microsoft Windows version of Emacs.")

      (defconst running-cygwin
        (eq system-type 'cygwin)
        "Running a Cygwin version of Emacs.")

      (defconst running-gnu-linux
        (eq system-type 'gnu/linux)
        "Running a GNU/Linux version of Emacs.")

      (defmacro MSWindows (&rest body)
        (list 'if running-ms-windows
              (cons 'progn body)))

      (defmacro GNULinux (&rest body)
        (list 'if running-gnu-linux
              (cons 'progn body)))

;;** Window system

      (section "Window system")

      (defconst running-x-window
        (eq window-system 'x)
        "Running X Window System.")

      (defmacro XWindow (&rest body)
        "Execute any number of forms if running X Window System."
        (list 'if running-x-window
              (cons 'progn body)))

;;** MS Windows

      ;; FIXME The path is not correct under Cygwin Emacs (gsprint.exe not found)
      (defconst windows-program-files-dir
        (concat (getenv "PROGRAMFILES") "/")
        "Defines the default Windows Program Files folder.")

;;** Emacs version

      (section "Emacs version")

      (defconst running-gnu-emacs
        (string-match "GNU Emacs" (version))
        "Running GNU Emacs.")

      (defconst running-xemacs
        (string-match "XEmacs" (version))
        "Running XEmacs.")

      (defmacro GNUEmacs (&rest body)
        "Execute any number of forms if running GNU Emacs."
        (list 'if running-gnu-emacs
              (cons 'progn body)))

      (defmacro GNUEmacs23 (&rest body)
        (list 'if (string-match "GNU Emacs 23" (version))
              (cons 'progn body)))

      (defmacro GNUEmacs24 (&rest body)
        (list 'if (string-match "GNU Emacs 24" (version))
              (cons 'progn body)))

      (defmacro XEmacs (&rest body)
        "Execute any number of forms if running XEmacs."
        (list 'if running-xemacs
              (cons 'progn body)))

;;** Init

      (section "Init")

      (XEmacs
       ;; don't load init file from `~/.xemacs/init.el' (and don't offer its
       ;; migration)
       (setq load-home-init-file t))

      (when running-gnu-linux
        (modify-all-frames-parameters
         '((height . 32))))

      )

;;* Loading Libraries of Lisp Code for Emacs

(chapter chapter-0-loading-libraries "0 Loading Libraries"

      ;; You have to put the `load-path' stuff as early as you can...

      ;; This is a list of directories where Emacs Lisp libraries (`.el' and
      ;; `.elc' files) are installed.

      ;; The most important directories are the last!

      ;; load-path enhancement
      ;; TODO Check that added directories do have a trailing slash
      ;; The GNU Emacs FAQ includes a trailing slash in the instructions
      ;; on how to add directories to one's load path via .emacs [1]:
      ;; (add-to-list 'load-path "/dir/subdir/")
      ;; [1] See 5.17 here: http://www.gnu.org/software/emacs/emacs-faq.html
      (defun my/add-to-load-path (this-directory
                                   &optional add-subdirs recursive)
        "Add THIS-DIRECTORY at the beginning of the load-path, if it exists.
      Add all its subdirectories not starting with a '.' if the
      optional argument ADD-SUBDIRS is not nil.
      Do it recursively if the third argument is not nil."
        (when (and this-directory
                   (file-directory-p this-directory))
          ;; TODO Add warning if directory does not exist
          (let* ((this-directory (expand-file-name this-directory))
                 (files (directory-files this-directory t "^[^\\.]"))
                 (dir-or-file nil))

            ;; directories containing a `.nosearch' file (such as
            ;; `auctex-11.86\style') should not made part of `load-path'.
            ;; TODO `RCS' and `CVS' directories should also be excluded.
            (unless (file-exists-p (concat this-directory "/.nosearch"))
              (add-to-list 'load-path this-directory)
              (message "(info) Added `%s' to `load-path'" this-directory)

              (when add-subdirs
                (while files
                  (setq dir-or-file (car files))
                  (when (file-directory-p dir-or-file)
                    (if recursive
                        (my/add-to-load-path dir-or-file
                                             'add-subdirs 'recursive)
                      (my/add-to-load-path dir-or-file)))
                  (setq files (cdr files))))))))

;;*** Site-lisp

      ;; TODO Specify variables using `defcustom'

      ;; 1.
      (defvar my/local-site-lisp-directory "~/Downloads/emacs/site-lisp/"
        "Directory containing additional Emacs Lisp packages (from the Internet).")

      (my/add-to-load-path my/local-site-lisp-directory
                           'add-subdirs 'recursive)

      ;; 2.
      (defvar my/site-lisp-directory "~/emacs/site-lisp/"
        "Directory containing my personal additional Emacs Lisp packages.")

      (my/add-to-load-path my/site-lisp-directory
                           'add-subdirs)

;;*** Development code

      ;; ;; fuzzy matching utilities for GNU Emacs
      ;; (my/add-to-load-path "~/src/fuzzy-el")

      ;; ;; No Gnus (unstable Gnus branch)
      ;; (my/add-to-load-path "~/src/gnus/lisp")
      ;; ;; this must be the very first thing in your `.emacs' file, and make
      ;; ;; sure that you're not picking up bits and pieces from old Gnus files
      ;; ;; later (if other packages -- such as helm, tramp or org-agenda --
      ;; ;; load Gnus before the new path is set).

      ;; ;; BBDB 3
      ;; (my/add-to-load-path "~/src/bbdb/lisp")

      ;; ;; open helm
      ;; (my/add-to-load-path "~/src/helm/" 'add-subdirs)
      ;; ;; Take care that `helm/doc/auto/helm.el' does not HIDE
      ;; ;; `helm/helm.el' by being first in the `load-path'.
      ;; ;; Otherwise, you get the error that `TeX-add-style-hook' is not yet
      ;; ;; defined (it will be defined when loading `auctex-11.86/tex.el').

      ;; (my/add-to-load-path "~/src/redshank")

      ;; (my/add-to-load-path "~/src/asp-mode")

      ;; ;; YASnippet
      ;; (my/add-to-load-path "~/src/yasnippet")
      ;; (my/add-to-load-path "~/src/yas-jit.el")

      ;; Org-mode
      (my/add-to-load-path "~/src/org-mode/lisp")
      (my/add-to-load-path "~/src/org-mode/contrib/lisp")
      (my/add-to-load-path "~/src/org-mode/testing")

      ;; (my/add-to-load-path "~/src/deft/")

      ;; ;; https://github.com/kiwanami/emacs-calfw
      ;; (my/add-to-load-path "~/src/emacs-calfw/")

      ;; (my/add-to-load-path "~/src/emacs-w3m" 'add-subdirs 'recursive)

      ;; (my/add-to-load-path "~/src/babel" 'add-subdirs 'recursive)

      ;; ;; ;; Handle auto-load'ing iswitchb
      ;; ;; (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)
      ;; ;; (eval-after-load "iswitchb" '(iswitchb-default-keybindings))

      ;; ;; ;; Handle autoload'ing slime
      ;; ;; (eval-after-load "slime"

      (defvar my/local-yasnippet-directory
        "~/src/yasnippet/snippets"
        "Directory containing additional YASnippets (from the Internet).")

      (defvar my/yasnippet-directory
        (concat my/site-lisp-directory "yasnippet/snippets")
        "Directory containing my personal additional YASnippets.")

      (defun my/make-directory-yes-or-no (dir)
        "Ask user to create the DIR, if it does not already exist."
        (if dir
            (if (not (file-directory-p dir))
                (if (yes-or-no-p
                     (concat "The directory `" dir
                             "' does not exist currently. Create it? "))
                    (make-directory dir t)
                  (error
                   (concat "Cannot continue without directory `" dir "'"))))
          (error "my/make-directory-yes-or-no: missing operand")))

      (defun my/file-exists-and-executable-p (file)
        "Make sure the file FILE exists and is executable."
        (if file
            (if (file-executable-p file)
                file
              (message "(warning) Can't find executable `%s'" file)
              ;; sleep 1 s so that you can read the warning
              (sit-for 1))
          (error "my/file-exists-and-executable-p: missing operand")))

)

;;* Debugging

(chapter chapter-0-debugging "0 Debugging"

      ;; get the backtrace when uncaught errors occur
      (setq debug-on-error t) ;; will be unset at the end

      (XEmacs
       (setq stack-trace-on-error t))

      ;; hit `C-g' while it's frozen to get an ELisp backtrace
      (setq debug-on-quit nil)

)

      ;; make loaded files give a message
      (GNUEmacs
        (defadvice load (before debug-log activate)
          (message "(info) Loading %s..." (locate-library (ad-get-arg 0))))

        (defadvice load-library (before debug-log activate)
          (message "(info) Loading Library `%s'..." (locate-library (ad-get-arg 0))))

        (defadvice load-file (before debug-log activate)
          (message "(info) Loading File `%s'..." (locate-library (ad-get-arg 0))))

        (defadvice find-file (around debug-log activate)
          "Open FILENAME and report time spent."
          (let ((filename (ad-get-arg 0))
                (find-file-time-start (float-time)))
            (message "(info) Loading %s..." filename)
            ad-do-it
            (message "(info) Loaded %s in %.2f seconds." filename
                     (- (float-time) find-file-time-start))))


         ;; REPLACES ORIGINAL in `C source code' (dumped)
         ;; redefine require to leave a trace of packages being loaded
         (if (not (fboundp 'orig-require))
             (fset 'orig-require (symbol-function 'require))
           (message
            "The code to redefine `require' should not be loaded twice"))

         (defvar my/require-depth 0)

         (defun require (feature &optional filename noerror)
           "Leave a trace of packages being loaded."
           (cond ((featurep feature)
                  (message "(info) %sRequiring `%s'... already loaded"
                           (concat (make-string (* 2 my/require-depth) ? )
                                   "+-> ")
                           feature))
                 (t
                  (message "(info) %sRequiring `%s'..."
                           (concat (make-string (* 2 my/require-depth) ? )
                                   "+-> ")
                           feature)
                  (let ((my/require-depth (+ 1 my/require-depth)))
                    (orig-require feature filename noerror))
                  (message "(info) %sRequiring `%s'... done"
                           (concat (make-string (* 2 my/require-depth) ? )
                                   "+-> ")
                           feature)))))

      (defvar missing-packages-list nil
        "List of packages that `try-require' can't find.")

      ;; require a feature/library if available; if not, fail silently
      (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."
        (let (my/time-start)
          (condition-case err
              ;; protected form
              (progn
                (message "(info) Checking for `%s'..." feature)
                (if (stringp feature)
                    (load-library feature)
                  (setq my/time-start (float-time))
                  (require feature))
                (message "(info) Checking for `%s'... %s (loaded in %.2f s)"
                         feature
                         (locate-library (symbol-name feature))
                         (- (float-time) my/time-start))
                )
            ;; error handler
            (file-error ;; condition
             (progn
               (message "(info) Checking for `%s'... missing" feature)
               (add-to-list 'missing-packages-list feature 'append))
             nil))))

(when (try-require 'elp-XXX)
  ;; the most important ones
  (elp-instrument-package "org")
  (elp-instrument-package "outline")
  (elp-instrument-package "font-lock")
  (elp-instrument-package "flyspell")

  ;; others
  (elp-instrument-package "bytecomp")
  (elp-instrument-package "color-theme")
  (elp-instrument-package "company")
  (elp-instrument-package "custom")
  (elp-instrument-package "files")
  (elp-instrument-package "filladapt")
  (elp-instrument-package "help-fns")
  (elp-instrument-package "ispell")
  (elp-instrument-package "outline-mode-easy-bindings"))

;; ;; set default face (Emacs 23+)
;; (if (font-info "Consolas")
;;     (set-default-font "Consolas-8")
;;   (set-default-font "Courier New-8"))

;; set default font for all frames (Emacs 23+)
(when window-system
  ;; detect if Emacs is running in a terminal; otherwise, in terminal: "X
  ;; windows are not in use or not initialized"
  (GNUEmacs
   (cond
         ;; ((font-info "Courier")
         ;;  (modify-all-frames-parameters '((font . "Courier-8"))))
         ;; ((font-info "Consolas")
         ;;  (modify-all-frames-parameters '((font . "Consolas-8"))))
         ((font-info "DejaVu Sans Mono")
          (modify-all-frames-parameters '((font . "DejaVu Sans Mono-11"))))
         ((font-info "Lucida Sans Typewriter")
          (modify-all-frames-parameters '((font . "Lucida Sans Typewriter-8"))))
         ((font-info "Lucida Console")
          (modify-all-frames-parameters '((font . "Lucida Console-9")))))))

;; FIXME Moved color-theme section temporarily here!
;; It should go back to the chapter `Emacs Display'
(section "color-theme (emacs-goodies-el)")

;; avoid Emacs hanging for a while changing default font
(modify-frame-parameters nil '((wait-for-wm . nil)))

;; the real color theme functions
(when (try-require 'color-theme-autoloads)

  ;; `color-theme-print' allows to keep what you see

  ;; initialize the color theme package
  (if (fboundp 'color-theme-initialize)
      (color-theme-initialize))

  ;; color themes will be installed for all frames
  (setq color-theme-is-global t)

  ;; set my default color theme
  (when (try-require 'color-theme-leuven)
    (color-theme-leuven)))

;; (GNUEmacs24
;;   (add-to-list 'custom-theme-load-path "~/src/solarized/emacs-colors-solarized")
;;   (load-theme 'solarized-light t)
;;   (color-theme-solarized-light))

(XEmacs
 (setq options-save-faces t))

;;* 1 The Organization of the (info "(emacs)Screen")

(chapter chapter-1-screen "1 The Organization of the Screen"

;;** 1.2 The (info "(emacs)Echo Area")

      (section "1.2 (emacs) The Echo Area")

      ;; don't truncate the message log buffer when it becomes large
      (setq message-log-max t)

      ;; The `*Messages*' buffer is called the ` *Message-Log*' on XEmacs
      ;; (note the initial space). To display the message log, execute the
      ;; command `M-x show-message-log'


      ;; get timestamps
      (defadvice message (before when-was-that activate)
        "Add timestamps to `message' output."
        (ad-set-arg 0 (concat (format-time-string "[%Y-%m-%d %a %T] ")
                              (ad-get-arg 0)) ))

)

;;* 7 (info "(emacs)Basic") Editing Commands

(chapter chapter-7-basic "7 Basic Editing Commands"

;;** 7.1 (info "(emacs)Inserting Text")

      (section "7.1 (emacs)Inserting Text")

      ;; use octal (not decimal) for `C-q'
      (setq read-quoted-char-radix 8) ;; 16 for hexadecimal (for Unicode char)

;;** 7.2 (info "(emacs)Moving Point") Location

      (section "7.2 (emacs)Moving Point Location")

      ;; don't add newlines to end of buffer when scrolling
      (setq next-line-add-newlines nil)

      ;; XEmacs default for moving point to a given line number
      (GNUEmacs
       (global-set-key (kbd "M-g") 'goto-line))

      (global-set-key (kbd "M-G") 'what-line)

      ;; move (shift) a line of text up or down like you would do in Eclipse
      ;; pressing `M-up' (or `M-down')
      (defun move-line (n)
        "Move the current line up or down by N lines."
        (interactive "p")
        (let ((col (current-column))
              start
              end)
          (beginning-of-line)
          (setq start (point))
          (end-of-line)
          (forward-char)
          (setq end (point))
          (let ((line-text (delete-and-extract-region start end)))
            (forward-line n)
            (insert line-text)
            ;; restore point to original column in moved line
            (forward-line -1)
            (forward-char col))))

      (defun move-line-up (n)
        "Move the current line up by N lines."
        (interactive "p")
        (move-line (if (null n) -1 (- n))))

      (defun move-line-down (n)
        "Move the current line down by N lines."
        (interactive "p")
        (move-line (if (null n) 1 n)))

      ;; ;; XXX `M-up' and `M-down' are bound multiple times (to different
      ;; things)!
      ;; (global-set-key (kbd "<M-up>") 'move-line-up)
      ;; (global-set-key (kbd "<M-down>") 'move-line-down)

;;** 7.4 (info "(emacs)Basic Undo")ing Changes

      (section "7.4 (emacs)Basic Undoing Changes")

      ;; undo some previous changes
      (global-set-key (kbd "<f11>") 'undo)

      ;; redo the most recent undo
      (autoload 'redo "redo.el" nil t)
      (global-set-key (kbd "<S-f11>") 'redo)

;;** 7.8 (info "(emacs)Continuation Lines")

      (section "7.8 (emacs)Continuation Lines")

      ;; switch wrap mode from "wrap long lines to next line" to "non-wrap",
      ;; or vice-versa
      (global-set-key (kbd "C-c t") 'toggle-truncate-lines)

;;** 7.9 (info "(emacs)Position Info")

(GNUEmacs
(autoload 'show-point-mode "show-point-mode" nil t)
(add-hook 'emacs-lisp-mode-hook
          (lambda () (show-point-mode))))

)

;;* 8 The (info "(emacs)Minibuffer")

(chapter chapter-8-minibuffer "8 The Minibuffer"

;;** 8.1 (info "(emacs)Minibuffer File") Names

      (section "8.1 (emacs)The Minibuffer")

      ;; ignore case when reading a file name completion
      (setq read-file-name-completion-ignore-case t)

      ;; dim the ignored part of the file name
      (GNUEmacs
       (file-name-shadow-mode 1))

;;** 8.2 (info "(emacs)Minibuffer Edit")ing

      (section "8.2 (emacs)Minibuffer Editing")

      ;; minibuffer window expands vertically as necessary to hold the text
      ;; that you put in the minibuffer
      (setq resize-mini-windows t)

      ;; From Babel.el: "If the output is short enough to display in the echo
      ;; area (which is determined by the variables `resize-mini-windows' and
      ;; `max-mini-window-height'), it is shown in echo area."

;;** 8.3 (info "(emacs)Completion")

      (section "8.3 (emacs)Completion")

      ;; minibuffer completion incremental feedback
      (GNUEmacs
       (icomplete-mode))

      ;; ignore case when reading a buffer name
      (setq read-buffer-completion-ignore-case t)

      ;; do not consider case significant in completion (GNU Emacs default)
      (setq completion-ignore-case t)
)

;;* 10 (info "(emacs)Help")

(chapter chapter-10-help "10 Help"

      ;; `catman' create the database files that are used by `apropos' or
      ;; `man -k'.

      ;; You can read the instructions of a file by typing `M-x
      ;; finder-commentary RET file RET'

      ;; You might want to check out electric-help (ehelp.el). There is
      ;; nothing more satisfying than the window disappearing when you think
      ;; it should!

;;** 10.1 (info "(emacs)Help Summary")

      (section "10.1 (emacs)Help Summary")

      ;; find convenient unbound keystrokes (undefined key bindings)
      (autoload 'describe-unbound-keys "unbound" nil t)

      ;; avoid the description of all minor modes
      (defun describe-major-mode ()
        "Describe only `major-mode'."
        (interactive)
        (describe-function major-mode))

      ;; look up topic in the indices of the Emacs Lisp Reference Manual
      (global-set-key (kbd "C-h E") 'elisp-index-search)

;;** 10.4 (info "(emacs)Apropos")

      (section "10.4 (emacs)Apropos")

      ;; You can ask what pertains to a given topic by typing
      ;; `M-x apropos RET pattern RET'

      (eval-after-load "apropos"

        ;; check all variables and non-interactive functions as well
        '(setq apropos-do-all t))

      ;; add apropos help about variables (bind `C-h A' to `apropos-variable')
      (GNUEmacs
       (define-key help-map (kbd "A") 'apropos-variable))

;;** 10.8 (info "(emacs)Misc Help")

      (section "10.8 (emacs)Misc Help")

      ;; ls -l /usr/share/info/dir*
      ;; update-info-dir

      ;; The utility `install-info' is used to maintain the `info/dir' file.

      ;; `C-h K' goes to the node in the Emacs manual describing the command
      ;; bound to a key.


      ;; enter Info documentation browser
      (global-set-key (kbd "<f1>") 'info)

      ;; display symbol definitions, as found in the relevant manual
      ;; (for C, Lisp, and other languages that have documentation in Info)
      (global-set-key (kbd "<C-f1>") 'info-lookup-symbol)

      (eval-after-load "info"
        '(progn
           ;; Don't play with `Info-directory-list', it's not intended to be
           ;; settable by the user. When `info' is called, this variable is
           ;; populated from:
           ;; 1. the `INFOPATH' environment variable and/or
           ;; 2. the `Info-default-directory-list' variable

           ;; list of directories to search for Info documentation files (in
           ;; the order they are listed) -- non-existent directories will be
           ;; removed when copied to `Info-directory-list'
           (setq Info-default-directory-list
                 (cond (running-ms-windows
                        ;; EmacsW32 doesn't see `INFOPATH'...
                        `(
                          ,(expand-file-name
                            (concat (file-name-directory (locate-library "org.el"))
                                    "../doc/"))
                          "~/src/emacs-w3m/doc/"
                          "~/src/gnus/texi/"
                          "~/Downloads/emacs/site-lisp/auctex-11.86/doc/"
                          "c:/cygwin/usr/share/info/"
                          ,@Info-default-directory-list))
                       (t
                        ;; best to set the `INFOPATH' environment variable
                        ;; (outside of Emacs, in the same shell from which you
                        ;; invoke Emacs)
                        nil)))

           (GNUEmacs
            (try-require 'info+-XXX))  ;; error finding dir file
           ;; with `info+.el', you can merge an Info node with its subnodes
           ;; into the same buffer, by calling `Info-merge-subnodes' (bound to
           ;; `+')
           ))

      ;; dictem (dict protocol and dictem for a documentation)

      ;; get a Unix manual page and put it in a buffer
      (global-set-key (kbd "<S-f1>") 'man-follow)

      ;; (defun jump-man-page ()
      ;;   (interactive)
      ;;   (manual-entry (current-word)))

      ;; behavior when manpage is ready
      (setq Man-notify-method 'pushy)

      ;; alias man to woman
      (defalias 'man 'woman)

      ;; decode and browse Unix man-pages "W.o. (without) Man"
      (eval-after-load "woman"
        '(defalias 'man 'woman))

)

;;* 11 The (info "(emacs)Mark") and the Region

(chapter chapter-11-mark "11 The Mark and the Region"

;;** 11.7 (info "(emacs)Persistent Mark")s

      (section "11.7 (emacs)Persistent Marks")

      ;; when the mark is active, the *region is highlighted*
      ;; (enabled by default in Emacs 23)
      (GNUEmacs
       (when window-system
         (transient-mark-mode 1)))

)

;;* 12 (info "(emacs)Killing") and Moving Text

(chapter chapter-12-killing "12 Killing and Moving Text"

;;** 12.3 (info "(emacs)Other Kill Commands")

      (section "12.3 (emacs)Other Kill Commands")

      (GNUEmacs
      ;; add the ability to copy or cut the current line without marking it
      ;; (no active region) -- idea stolen from Slickedit
      (defadvice kill-ring-save (before slickcopy activate compile)
        "When called interactively with no active region, copy the current
      line instead."
        (interactive
         (if mark-active (list (region-beginning) (region-end))
           (message "Copied the current line")
           (list (line-beginning-position)
                 (line-beginning-position 2)))))

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

)

;;* 13 (info "(emacs)Yanking")

(chapter chapter-13-yanking "13 Yanking"

;;** 13.1 The (info "(emacs)Kill Ring")

      (section "13.1 (emacs)Yanking")

      ;; auto-indentation of pasted code in the listed programming modes (fall
      ;; back to default, non-indented yanking by preceding the yanking
      ;; command `C-y' with `C-u')
      (dolist (command '(yank yank-pop))
        (eval `(defadvice ,command (after indent-region activate)
                 (and (not current-prefix-arg)
                      (member major-mode '(c++-mode
                                           c-mode
                                           ;; clojure-mode
                                           emacs-lisp-mode
                                           ;; haskell-mode
                                           latex-mode
                                           lisp-mode
                                           objc-mode
                                           plain-tex-mode
                                           python-mode
                                           ;; rspec-mode
                                           ;; ruby-mode
                                           scheme-mode))
                      (let ((mark-even-if-inactive transient-mark-mode))
                        (indent-region (region-beginning) (region-end) nil))))))


;;** 13.3 Yanking (info "(emacs)Earlier Kills")

      (section "13.3 (emacs)Yanking Earlier Kills")

      ;; interactively insert items from kill ring
      (when (try-require 'browse-kill-ring)

        ;; string separating entries in the `separated' style
        (setq browse-kill-ring-separator
              "\n--separator-------------------------------")

        ;; temporarily highlight the inserted `kill-ring' entry
        (setq browse-kill-ring-highlight-inserted-item t)

        ;; face in which to highlight the `browse-kill-ring-separator'
        (defface separator-face
          '((t (:foreground "blue violet" :weight bold))) nil)
        (setq browse-kill-ring-separator-face 'separator-face)

        ;; use `M-y' to invoke `browse-kill-ring'
        (browse-kill-ring-default-keybindings))

)

;;* 15 (info "(emacs)Rectangles")

(chapter chapter-15-rectangles "15 Rectangles"

      ;; `kill-rectangle' (C-x r k) and `yank-rectangle' (C-x r y) can be very
      ;; useful for shifting cells up/down within a column while leaving
      ;; remaining columns intact.

)

;;* 16 (info "(emacs)CUA Bindings")

(chapter chapter-16-cua-bindings "16 CUA Bindings"

      ;; ;; activate CUA mode
      ;; (cua-mode t)

      ;; standard Windows behavior
      (setq cua-keep-region-after-copy t) ;; XXX currently unbound symbol

      ;; fix funny things of cursor moving commands
      (add-hook 'cua-mode-hook
                (lambda ()
                  (dolist (cmd '(forward-char
                                 backward-char
                                 previous-line
                                 next-line
                                 forward-paragraph
                                 backward-paragraph
                                 beginning-of-buffer
                                 end-of-buffer))
                    (put cmd 'CUA nil))))
)

;;* 17 (info "(emacs)Registers")

(chapter chapter-17-registers "17 Registers"

      ;; ;; Enable position saving through shortcuts.
      ;; ;; Save current position with  Ctrl-F1 Ctrl-F2 Ctrl-F3 and Ctrl-F4
      ;; (global-set-key [C-f1] '(lambda () (interactive) (point-to-register ?1)))
      ;; (global-set-key [C-f2] '(lambda () (interactive) (point-to-register ?2)))
      ;; (global-set-key [C-f3] '(lambda () (interactive) (point-to-register ?3)))
      ;; (global-set-key [C-f4] '(lambda () (interactive) (point-to-register ?4)))

      ;; (defun jump-to-register-other (reg)
      ;; (other-window 1)
      ;; (jump-to-register reg)
      ;; (hilit-recenter (/ (window-height) 2)))

      ;; (defun jump-to-register-here (reg)
      ;; (jump-to-register reg)
      ;; (hilit-recenter (/ (window-height) 2)))

      ;; ;; Move to saved position with F1 F2 F3 and F4
      ;; (global-set-key [f1] '(lambda () (interactive) (jump-to-register-here ?1)))
      ;; (global-set-key [f2] '(lambda () (interactive) (jump-to-register-here ?2)))
      ;; (global-set-key [f3] '(lambda () (interactive) (jump-to-register-here ?3)))
      ;; (global-set-key [f4] '(lambda () (interactive) (jump-to-register-here ?4)))


;;** 17.7 (info "(emacs)Bookmarks")

      (section "17.7 (emacs)Bookmarks")

      ;; Bookmarks are persistent and they have names; not markers. Bookmarked
      ;; positions can also be relocated (found) if they move slightly because
      ;; of text changes.

      ;; To navigate to a bookmark (linking to a file or directory), just
      ;; press `C-x r b'. You'll be prompted for the bookmark name, and it
      ;; will open that file or directory.

      ;; where to save the bookmarks
      (setq bookmark-default-file "~/.emacs.d/bookmarks.txt")

      ;; each command that sets a bookmark will also save your bookmarks
      (setq bookmark-save-flag 1)



      ;; I have just added a key "O" to filter only these two bookmarks in
      ;; bookmark-extensions.el
      ;; http://mercurial.intuxication.org/hg/emacs-bookmark-extension/
      ;; So when you hit "O" from the bookmark list (C-x r l) you have that:
      ;; ,----
      ;; | % Bookmark Last Org Stored
      ;; | - ------------------------
      ;; |   org-refile-last-stored
      ;; |   org-capture-last-stored
      ;; `----



      ;; TODO Check for bookmark+ instead of bm...

      ;; visible bookmarks in buffer
      (GNUEmacs

       ;; use `M-x bm-show-all' to list all bookmarks in all buffers

       ;; breadcrump

       (when (locate-library "bm")

         ;; key setup
         (global-set-key (kbd "<C-f2>") 'bm-toggle)
         (global-set-key (kbd "<S-f2>") 'bm-next)
         (global-set-key (kbd "<M-f2>") 'bm-show)
         (global-set-key (kbd "<S-f2>") 'bm-previous)

         ;; (global-set-key [f5] 'bm-toggle-bookmark)
         ;; (global-set-key [C-f5] 'bm-delete-all)
         ;; (global-set-key [f6] 'bm-goto-bookmark)
         ;; (global-set-key [C-f6] 'bm-goto-bookmark-previous)

         (autoload 'bm-toggle "bm"
           "Toggle bookmark in current buffer." t)
         (autoload 'bm-next "bm"
           "Goto bookmark." t)
         (autoload 'bm-previous "bm"
           "Goto previous bookmark." t)

         (autoload 'bm-repository-load "bm" nil t)

         ;; loading the repository from file when on start up
         (add-hook' after-init-hook 'bm-repository-load)

         (eval-after-load "bm"
           '(progn

           ;; repository should be restored when loading `bm'
           (setq bm-restore-repository-on-load t)

           (when (fboundp 'define-fringe-bitmap)

             (setq bm-highlight-style 'bm-highlight-line-and-fringe)

             ;; toggle bookmarks by clicking in the fringe
             (global-set-key
              (kbd "<left-fringe> <mouse-1>") #'(lambda(event)
                                                  (interactive "e")
                                                  (save-excursion
                                                    (mouse-set-point event)
                                                    (bm-toggle))))

             ;; buffer should be recentered around the bookmark
             (setq bm-recenter t)

             ;; make bookmarks persistent as default
             (setq-default bm-buffer-persistence t)

             ;; restoring bookmarks when on file find
             (add-hook 'find-file-hooks 'bm-buffer-restore)

             ;; saving bookmark data on killing a buffer
             (add-hook 'kill-buffer-hook 'bm-buffer-save)

             ;; saving the repository to file when on exit
             ;; `kill-buffer-hook' is not called when emacs is killed, so we
             ;; must save all bookmarks first
             (add-hook 'kill-emacs-hook '(lambda nil
                                           (bm-buffer-save-all)
                                           (bm-repository-save)))

             ;; update bookmark repository when saving the file
             (add-hook 'after-save-hook 'bm-buffer-save))))))

)

;;* 18 Controlling the (info "(emacs)Display")

(chapter chapter-18-display "18 Controlling the Display"

;;** 18.1 (info "(emacs)Scrolling")

      (section "18.1 (emacs)Scrolling")

      ;; scroll line by line
      (setq scroll-step 1)

      ;; better scrolling in Emacs (doing a `Pg Up' followed by a `Pg Dn' will
      ;; place the point at the same place)
      (when (try-require 'pager)
        (global-set-key (kbd "<prior>") 'pager-page-up)
        (global-set-key (kbd "<next>") 'pager-page-down)
        (global-set-key (kbd "<M-up>") 'pager-row-up)
        (global-set-key (kbd "<M-down>") 'pager-row-down))


;;** 18.8 (info "(emacs)Font Lock")

      (section "18.8 (emacs)Font Lock")

      ;; make buffer size irrelevant for fontification
      (setq font-lock-maximum-size nil)

      (XEmacs
       ;; stop showing that annoying progress bar when fontifying
       (setq progress-feedback-use-echo-area nil)

       ;; enable Font Lock mode
       (font-lock-mode))

      ;; fix absurd fontification delays in Org code blocks (on OSX)
      (setq font-lock-verbose nil)

      ;; highlight non-breaking spaces
      (GNUEmacs
       (require 'disp-table)
       (aset standard-display-table
             (make-char 'latin-iso8859-1 (- ?\240 128))
             (vector (+ ?\267 (* 524288 (face-id 'nobreak-space))))))

      ;; highlight alert or warning words
      (defvar my/keywords-error-pattern
        "\\(BUG\\|FIXME\\|XXX\\|TODO\\|[Ee]rror\\|ERROR\\|[Ww]arning\\|[Mm]issing\\|[Ii]nvalid\\|[Ff]ailed\\|[Cc]orrupted\\|[Ff]atal\\|FATAL\\|[Uu]ndefined\\|[Dd]enied\\|[Rr]ejected\\)"
        "Keywords to highlight in error.")

      (make-face 'my/keywords-error-face)
      (set-default-font "Monospace-11")
      (GNUEmacs (set-face-attribute 'my/keywords-error-face nil :height 110
                                    ;; :family "Serif"
                                    ;; :height 0.9
                                    :weight 'normal :slant 'normal
                                    :box '(:line-width 1 :color "#CC0000")
                                    :foreground "#CC0000"
                                    :background "#FFFF88"
                                    ))

      (defvar my/keywords-org-error-pattern
        "\\(BUG\\|FIXME\\|XXX\\|[^*] TODO\\|[Ee]rror\\|[Ww]arning\\|[Mm]issing\\|[Ii]nvalid\\|[Ff]ailed\\|[Cc]orrupted\\|[Ff]atal\\|[Uu]ndefined\\|[Rr]ejected\\)"
        "Keywords to highlight in error (for Org mode only).")
                                        ; smaller subset of keywords for
                                        ; ensuring no conflict with Org mode
                                        ; TODO keywords
      ;; FIXME Highlighting all special keywords but "TODO" in Org mode is
      ;; already a good step. Though, a nicer integration would be that "TODO"
      ;; strings in the headings are not touched by this code, and that only
      ;; "TODO" strings in the text body would be. Don't know (yet) how to do
      ;; that...

      ;; FIXME TODO should be highlighted in Org, even when at beginning of
      ;; line -- of course, without * in front of it.

      ;; set up highlighting of special words for proper selected major modes
      ;; only
      (dolist (mode '(fundamental-mode
                      svn-log-view-mode
                      text-mode))
                                        ; no interference with Org mode (which
                                        ; derives from text-mode)
        (font-lock-add-keywords mode
         `((,my/keywords-error-pattern 1 'my/keywords-error-face prepend))))

      ;; set up highlighting of special words for Org mode only
      (dolist (mode '(org-mode))
        (font-lock-add-keywords mode
         `((,my/keywords-org-error-pattern 1 'my/keywords-error-face prepend))))

      ;; add fontification patterns (even in comments) to a selected major
      ;; mode *and* all major modes derived from it
      (defun fontify-keywords ()
        (interactive)
        ;;   (font-lock-mode -1)
        ;;   (font-lock-mode 1)
        (font-lock-add-keywords nil
         `((,my/keywords-error-pattern 1 'my/keywords-error-face prepend))))
      ;; FIXME                         0                          t

      ;; set up highlighting of special words for selected major modes *and*
      ;; all major modes derived from them
      (dolist (hook '(c++-mode-hook
                      c-mode-hook
                      change-log-mode-hook
                      cperl-mode-hook
                      css-mode-hook
                      emacs-lisp-mode-hook
                      html-mode-hook
                      java-mode-hook
                      latex-mode-hook
                      lisp-mode-hook
                      makefile-mode-hook
                      message-mode-hook
                      php-mode-hook
                      python-mode-hook
                      sh-mode-hook
                      shell-mode-hook ;; works in *shell* buffers!
                      ssh-config-mode-hook))
        (add-hook hook 'fontify-keywords))

      ;; stealth fontification should show status messages
      (setq jit-lock-stealth-verbose t)


      ;; 2010-11-05 All my colors in Gnus disappear when this is enabled...
      ;; ;; add a new face in my config file so that all the numbers will have
      ;; ;; different color
      ;; (make-face 'font-lock-number-face)
      ;; (set-face-foreground 'font-lock-number-face "DodgerBlue4")
      ;; (setq font-lock-number-face 'font-lock-number-face)
      ;; (defvar font-lock-number "[0-9]+\\([eE][+-]?[0-9]*\\)?")
      ;; (defvar font-lock-hexnumber "0[xX][0-9a-fA-F]+")
      ;;
      ;; (add-hook 'font-lock-mode-hook
      ;;           #'(lambda ()
      ;;               (setq font-lock-keywords
      ;;                     (append font-lock-keywords
      ;;                             (list
      ;;                              (list (concat "\\<\\(" font-lock-number "\\)\\>" )
      ;;                                    (list 0 font-lock-number-face))
      ;;                              (list (concat "\\<\\(" font-lock-hexnumber "\\)\\>" )
      ;;                                    (list 0 font-lock-number-face)))))))


;;** 18.9 (info "(emacs)Highlight Interactively") by Matching

      (section "18.9 (emacs)Highlight Interactively by Matching")

      ;; You can use `hi-lock-mode' to highlight words:
      ;;     `M-x hi-lock-mode RET'
      ;;     `C-x w h <match> RET hi-blue RET'
      ;; You can also write your settings to the buffer you're using with
      ;; `C-x w b', and read them back in again next time with `C-x w i'.


      ;; TODO Have a look at http://www.emacswiki.org/emacs/color-moccur.el
      ;; for searching regexp in buffer

      (GNUEmacs
       ;; "identical token highlighting" commands

       (autoload 'hlt-highlight-regexp-region "highlight"
         "Highlight regular expression REGEXP in region." t)

       (defun my/hlt-highlight-current-word ()
         (interactive)
         (let ((cword (current-word t)))
           (when cword
             (save-excursion
               (hlt-highlight-regexp-region (point-min) (point-max)
                                            (regexp-quote cword))))))

       ;; emulation of Vim's `*' search
       (global-set-key (kbd "C-*") 'my/hlt-highlight-current-word)

       (eval-after-load "highlight"
         '(progn

            (defface hlt-1 '((t (:background "#FFFFA0"))) nil)
            (defface hlt-2 '((t (:background "#A0FFFF"))) nil)
            (defface hlt-3 '((t (:background "#A0FFA0"))) nil)
            (defface hlt-4 '((t (:background "#FFA0A0"))) nil)
            (defface hlt-5 '((t (:background "#FFA0FF"))) nil)
            (defface hlt-6 '((t (:background "#FFFFA0"))) nil)
            (defface hlt-7 '((t (:background "#A0FFFF"))) nil)
            (defface hlt-8 '((t (:background "#A0FFA0"))) nil)
            (defface hlt-9 '((t (:background "#FFA0A0"))) nil)
            (defface hlt-10 '((t (:background "#FFA0FF"))) nil)

            (global-set-key (kbd "C-S-p") 'hlt-previous-highlight)
            (global-set-key (kbd "C-S-n") 'hlt-next-highlight))))

      ;; ;; bind the hi-lock commands to more finger-friendly sequences
      ;; (define-key hi-lock-map (kbd "C-z i") 'hi-lock-find-patterns)
      ;; (define-key hi-lock-map (kbd "C-z p") 'highlight-phrase)
      ;; (define-key hi-lock-map (kbd "C-z r") 'unhighlight-regexp)

      ;; (define-key hi-lock-map (kbd "C-z h") 'highlight-regexp)
      ;; (define-key hi-lock-map (kbd "C-z C-h") 'highlight-lines-matching-regexp)
      ;; (define-key hi-lock-map (kbd "C-z b") 'hi-lock-write-interactive-patterns)

      ;; See M-s h r for highlight-regexp!

      ;; ;; Highlight based on regexps
      ;; (global-set-key [M-f1] 'highlight-regexp)
      ;; (global-set-key [M-f2] 'highlight-lines-matching-regexp)
      ;; (global-set-key [M-f3] 'hi-lock-mode)
      ;; (global-set-key [M-f4] 'hi-lock-write-interactive-patterns)


      ;; highlight current symbol
      (setq highlight-symbol-idle-delay 0.5)
      (when (try-require 'highlight-symbol)
        ;; (defun highlight-symbol-settings ()
        ;;   "Settings for `highlight-symbol'."
        ;;   (setq highlight-symbol-idle-delay 0.5)

        (defun turn-on-highlight-symbol-mode ()
          "Turn on `highlight-symbol-mode'."
          (interactive)
          (if window-system
              (highlight-symbol-mode 1)))

        (define-globalized-minor-mode global-highlight-symbol-mode
          highlight-symbol-mode
          turn-on-highlight-symbol-mode)

        ;; (when window-system
        ;;   (am-add-hooks
        ;;    '(emacs-lisp-mode-hook
        ;;      lisp-interaction-mode-hook
        ;;      java-mode-hook
        ;;      c-mode-common-hook
        ;;      text-mode-hook
        ;;      ruby-mode-hook
        ;;      html-mode-hook
        ;;      sh-mode-hook
        ;;      Info-mode-hook)
        ;;    'highlight-symbol-mode-on))
        ;; OR
        ;; turn on highlight-symbol-mode in all major modes
        ;;  (global-highlight-symbol-mode 1)
        )


;;** 18.11 (info "(emacs)Displaying Boundaries")

      (section "18.11 (emacs)Displaying Boundaries")

      ;; visually indicate buffer boundaries and scrolling
      (setq indicate-buffer-boundaries t)


;;** 18.12 (info "(emacs)Useless Whitespace")

      (section "18.12 (emacs)Useless Whitespace")

      ;; highlight trailing whitespaces in all modes
      (setq-default show-trailing-whitespace t)

      ;; ;; show zero-width spaces
      ;; (font-lock-add-keywords nil
      ;;  `((,(format "\\(%c\\)" ?\u200b) ; #\ZERO_WIDTH_SPACE
      ;;     (1 (progn (compose-region (match-beginning 1) (match-end 1)
      ;;                               ?\u2b1b ; #\BLACK_LARGE_SQUARE
      ;;                               'decompose-region)
      ;;               nil)))))

      ;; delete all the trailing whitespaces and TABs across the current
      ;; buffer
      (defun my/delete-trailing-whitespaces-and-untabify ()
        "Delete all the trailing white spaces, and convert all TABs to
      multiple spaces across the current buffer."
        (interactive "*")
        (delete-trailing-whitespace)
        (untabify (point-min) (point-max)))

      ;; Problem with .bbdb
      ;; ATTENTION: This deletes trailing ^M as well (visible in Unix files)
      ;; ;; ensure that your files have no trailing whitespace
      ;; (add-hook 'before-save-hook 'delete-trailing-whitespace)

      ;; visually indicate empty lines after the buffer end
      (setq-default indicate-empty-lines t)


;;** 18.14 (info "(emacs)Optional Mode Line") Features

      (section "18.14 (emacs)Optional Mode Line Features")

      ;; show the line number in each mode line
      (line-number-mode 1)

      ;; show the column number in each mode line
      (column-number-mode 1)

      ;; use inactive face for mode-line in non-selected windows
      (setq mode-line-in-non-selected-windows t)

      ;; (GNUEmacs
      ;;  ;; code for including abbreviated file paths in mode line
      ;;  (when (try-require 'mode-line)
      ;;    (mode-line-toggle-display nil)))


;;** 18.15 How (info "(emacs)Text Display")ed

      (section "18.15 (emacs)How Text Displayed")

      ;; convert a buffer from DOS `^M' end of lines to Unix end of lines
      (defun my/dos2unix ()
        "Cut all visible ^M from the current buffer."
        (interactive)
        (save-excursion
          (goto-char (point-min))
          (while (search-forward "\r" nil t)
            (replace-match ""))))

      ;; convert a buffer from Unix end of lines to DOS `^M' end of lines
      (defun my/unix2dos ()
        (interactive)
        (save-excursion
          (goto-char (point-min))
          (while (search-forward "\n" nil t)
            (replace-match "\r\n"))))

;; declare PDF files as binary
(if (boundp 'file-name-buffer-file-type-alist)
    (setq file-name-buffer-file-type-alist
          (cons '("\\.pdf$" . t)
                file-name-buffer-file-type-alist)))

      ;; Remove or convert trailing ^M
      (defun remove-trailing-ctrl-M ()
        "Propose to remove trailing ^M from a file."
        (interactive)
        (save-excursion
          (goto-char (point-min))
          (if (and
               (not (string-match ".gz$" (buffer-file-name)))
               (not (string-match ".pdf$" (buffer-file-name)))
               (search-forward-regexp "\015$" nil t))
              ;; a ^M is found
              (if (or (= (preceding-char) ?\^J)
                      (= (following-char) ?\^J) )
                  (if (yes-or-no-p (format "Remove trailing ^M from %s? "
                                           (buffer-file-name)))
                      (progn (goto-char (point-min))
                             (perform-replace "\015" "" nil nil nil)
                             (pop-mark)
                             (save-buffer))
                    (message "No transformation."))))))
      (add-hook 'find-file-hooks 'remove-trailing-ctrl-M)

;;** 18.16 The (info "(emacs)Cursor Display")

      (section "18.16 (emacs)The Cursor Display")

      ;; cursor of the selected window blinks
      (XEmacs (blink-cursor-mode))

      (GNUEmacs
       ;; using cursor color to indicate some modes (read-only, insert and
       ;; overwrite modes)
       (setq my/set-cursor-color-color "")
       (setq my/set-cursor-color-buffer "")

       (defun my/set-cursor-color-according-to-mode ()
         "Change cursor color according to some minor modes."
         (let ((color
                (if buffer-read-only "purple1"
                  (if overwrite-mode "red"
                    "#15FF00"))))  ; insert mode
           (unless (and (string= color my/set-cursor-color-color)
                        (string= (buffer-name) my/set-cursor-color-buffer))
             (set-cursor-color (setq my/set-cursor-color-color color))
             (setq my/set-cursor-color-buffer (buffer-name)))))

       (add-hook 'post-command-hook 'my/set-cursor-color-according-to-mode))

      ;; highlight columns 78 to 80 in some modes
      (autoload 'column-marker-1 "column-marker"
        "Highlight a column." t)

      (dolist (hook '(emacs-lisp-mode-hook
                      cperl-mode-hook
                      shell-mode-hook
                      ;; text-mode-hook
                      ;; cause of Org-mode slowness (for agenda-list: 0.3 s
                      ;; per Org file)
                      change-log-mode-hook
                      makefile-mode-hook
                      message-mode-hook
                      texinfo-mode-hook))
        (add-hook hook (lambda ()
                         (interactive)
                         (column-marker-1 78)
                         ;; (column-marker-2 79)
                         ;; (column-marker-3 80)
			 )))

;;** 18.17 (info "(emacs)Line Truncation")

      (section "18.17 (emacs)Line Truncation")

      ;; respect the value of `truncate-lines' in all windows less than the
      ;; full width of the frame
      (setq truncate-partial-width-windows nil)

;;** 18.19 (info "(emacs)Display Custom")ization

      (section "18.19 (emacs)Display Customization")

      ;; see what I'm typing *immediately*
      (setq echo-keystrokes 0.1)

;;** Unsorted

      ;; M-x rainbow-mode
      (GNUEmacs (autoload 'rainbow-mode "rainbow-mode" nil t))

)

;;* 19 (info "(emacs)Search")ing and Replacement

(chapter chapter-19-search "19 Searching and Replacement"

;;** 19.1 (info "(emacs)Incremental Search")

      (section "19.1 (emacs)Incremental Search")

      ;; Have a look at the "Standard Isearch Keys" on
      ;; http://www.emacswiki.org/emacs/IncrementalSearch

      ;; FIXME Error when selecting search string from kill ring (`M-p')
      ;; ;; always exit searches at the beginning of the expression found
      ;; (add-hook 'isearch-mode-end-hook 'custom-goto-match-beginning)
      ;;
      ;; (defun custom-goto-match-beginning ()
      ;;   "Use with isearch hook to end search at first char of match."
      ;;   (when isearch-forward (goto-char isearch-other-end)))

      ;; incremental search will open the contents
      (setq search-invisible 'open)

      ;; re-hide an invisible match right away
      (setq isearch-hide-immediately nil)

      ;; scrolling commands are allowed during incremental search
      (setq isearch-allow-scroll t)

      (GNUEmacs
       ;; fuzzy matching utilities (a must-have)
       (when (try-require 'fuzzy)
         (turn-on-fuzzy-isearch)))


;;** 19.4 (info "(emacs)Regexp Search")

      (section "19.4 (emacs)Regexp Search")

      ;; ;; use regexps by default (allows searching across line breaks)
      ;; (global-set-key (kbd "C-s") 'isearch-forward-regexp)
      ;; (global-set-key (kbd "C-r") 'isearch-backward-regexp)
      ;;
      ;; ;; shift the meaning of `C-M-s/r'
      ;; (global-set-key (kbd "C-M-s") 'isearch-forward)
      ;; (global-set-key (kbd "C-M-r") 'isearch-backward)

      ;; You can build regexps with visual feedback by using:
      ;; - `M-x re-builder' or
      ;; - `M-x regex-tool' (by John Wiegley, get it from
      ;;   http://www.newartisans.com/downloads_files/regex-tool.el)

      ;; Optimize regexps with `regexp-opt.el'

      ;; list the input line, followed by the first nine substrings matches,
      ;; to debug regexp searches (in IELM)
      ;; example: ELISP> (save-excursion (set-buffer "BUFFER")
      ;;                                 (re-search-forward "REGEXP" nil t)
      ;;                                 (my/buffer-matched-strings))
      (defun my/buffer-matched-strings ()
        (interactive)
        (mapcar 'my/buffer-matched-string-nth '(0 1 2 3 4 5 6 7 8 9)))

      (defun my/buffer-matched-string-nth (n)
        "Return the Nth pattern-matched string from the current buffer."
        (if (and (match-beginning n) (match-end n))
            (if (> (match-end n) (match-beginning n))
                (buffer-substring (match-beginning n) (match-end n))
              "")
          nil))


;;** 19.8 (info "(emacs)Search Case")

      (section "19.8 (emacs)Search Case")

      ;; make searches case sensitive by default (in all buffers that do not
      ;; override this)
      (setq-default case-fold-search t)

;;** 19.9 (info "(emacs)Replace")ment Commands

      (section "19.9 (emacs)Replacement Commands")

      ;; ;; `query-replace' uses the last search string, which becomes the
      ;; ;; "string to replace"
      ;; (setq query-replace-interactive t)
      ;; Then: how do you make a replace for something you've not searched?

;;** 19.10 (info "(emacs)Other Repeating Search") Commands

      (section "19.10 (emacs)Other Repeating Search Commands")

      (defun my/isearch-occur ()
        "Invoke `occur' from within isearch."
        (interactive)
        (let ((case-fold-search isearch-case-fold-search))
          (occur
           (if isearch-regexp isearch-string (regexp-quote isearch-string)))))

      ;; activate occur easily inside isearch
      (define-key isearch-mode-map
        (kbd "C-o") 'my/isearch-occur)

      ;; activate occur easily globally
      (global-set-key (kbd "C-o") 'occur) ;; `M-s o' by default
)

;;* 20 Commands for (info "(emacs)Fixit") Typos

(chapter chapter-20-fixit "20 Commands for Fixing Typos"

;;** 20.4 Checking and Correcting (info "(emacs)Spelling")

      (section "20.4 (emacs)Checking and Correcting Spelling")

      ;; `aspell' is better than `ispell': for example, it does recognize
      ;; words with apostrophes (l'avion)... but it is slower.

      (defvar windows-spell
        (concat windows-program-files-dir "Aspell/bin/aspell.exe")
        "Defines the Windows path to the spell executable.")

      (defvar my/aspell-french-dictionary
        (cond ((file-exists-p "/usr/lib/aspell/fr_FR")
               "/usr/lib/aspell/fr_FR")
              ((file-exists-p "/usr/lib/aspell/francais.alias")
               "/usr/lib/aspell/francais.alias")
              ((file-exists-p
                (concat windows-program-files-dir "Aspell/dict/francais.alias"))
               (concat windows-program-files-dir "Aspell/dict/francais.alias"))
              )
      "Defines the path to the Aspell french dictionary.")

      ;; program invoked by `ispell-word' and `ispell-region' commands
      (setq ispell-program-name
            ;; use Hunspell or GNU Aspell instead of `ispell'
            (cond (running-ms-windows windows-spell)
                  ((executable-find "hunspell") "hunspell")
                  ((executable-find "aspell") "aspell")
                  (t "ispell")))

      (when (executable-find ispell-program-name)
        (try-require 'ispell)  ;; `ispell.el' is already loaded at this stage

        (eval-after-load "ispell"
          ;; so that following modifications won't be lost when `ispell' is
          ;; loaded
          '(progn

             ;; default dictionary to use (if `ispell-local-dictionary' is nil)
             (setq ispell-dictionary "en_US")

             ;; save the personal dictionary without confirmation
             (setq ispell-silently-savep t)

             ;; extensions and extra switches to pass to the `ispell' program
             (cond
              ((equal ispell-program-name "hunspell")
               (setq ispell-really-hunspell t)
               (setq ispell-really-aspell nil)
               (setq ispell-extra-args '()))

              ;; XXX Rewrite this, so that we identify correctly which program
              ;; is used. Maybe a substring search?
              (
               (or running-ms-windows
                   (equal ispell-program-name "aspell")
                   )
               (setq ispell-really-hunspell nil)
               (setq ispell-really-aspell t)
               (setq ispell-extra-args '("--sug-mode=ultra" "-C")))
              ;; tell `aspell' to speed up, though this reduces somewhat the
              ;; quality of its suggestions. According to the `aspell'
              ;; documentation:
              ;;
              ;; - "ultra" is the fastest suggestion mode, which is still
              ;;   twice as slow as `ispell'.
              ;;
              ;; - If your machine is fast enough, a better option might be to
              ;;   try "fast" mode, which is twice as slow as "ultra", but
              ;;   more accurate.
              ;;
              ;; - The "normal" mode, which is the `aspell' default, is even
              ;;   more accurate, but is reportedly 10 times slower than
              ;;   "fast" mode.
              ;;
              ;; Use the `-C' option which will ConsiderCamelCaseToBeCorrect

              ((equal ispell-program-name "ispell")
               (setq ispell-really-hunspell nil)
               (setq ispell-really-aspell nil)))

             ;; redefine the list of installed dictionaries
             ;; customize to ("-B" "-d" "spanish") or ("-C" "-d" "dutch") if
             ;; aliases are needed for the file names
             ;; FIXME This variable is reset once latter in this .emacs
             ;; file!!!
             ;; FIXME See `ispell-dictionary-base-alist' and
             ;; `ispell-base-dicts-override-alist'
             (setq ispell-dictionary-base-alist
                   ;; those not here will result in "undefined dictionary"
                   '(
                     ;; default
                     (nil
                      "[A-Za-z]" "[^A-Za-z]"
                      "[']" nil ("-B") nil iso-8859-1)

                     ;; Yankee English
                     ("en_US"
                      "[A-Za-z]" "[^A-Za-z]"
                      "[']" nil ("-B") nil utf-8)))

             ;; standard French
             (when my/aspell-french-dictionary
                                        ; file can be opened for reading
               (add-to-list 'ispell-dictionary-base-alist
                            '("fr_FR"
                              "[a-zàâäéèêëîïôöùûüçA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ]"
                              "[^a-zàâäéèêëîïôöùûüçA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ]"
                              "[-']" t nil "~list" iso-8859-1)
                            'append))

             ;; Spanish (espanol)
             (when (file-exists-p "/usr/lib/aspell/es_ES")
               (add-to-list 'ispell-dictionary-base-alist
                            '("es_ES"
                              "[a-zñáàéèíìóòúùüA-ZÑÁÀÉÈÍÌÓÒÚÙÜ]"
                              "[^a-zñáàéèíìóòúùüA-ZÑÁÀÉÈÍÌÓÒÚÙÜ]"
                              "[-]" nil ("-B") "~tex" iso-8859-1)
                            'append))

             ;; Dutch (Nederlands)
             (when (file-exists-p "/usr/lib/aspell/nl_NL")
               (add-to-list 'ispell-dictionary-base-alist
                            '("nl_NL"
                              "[a-zàâçëîïôùûüA-ZÀÂÇËÎÏÔÙÛÜ]" "[^a-zàâçëîïôùûüA-ZÀÂÇËÎÏÔÙÛÜ]"
                              "[']" t ("-C") nil iso-8859-1)
                            'append))

             ;; ;; solve the problem of words separated by `-' flagged as
             ;; ;; erroneous by removing the `-' from the value of otherchars

             ;; (if (fboundp 'ispell-get-decoded-string)
             ;;     (defun ispell-get-otherchars ()
             ;;       (replace-regexp-in-string "-" "" (ispell-get-decoded-string 3))))


             ;; don't use `M-TAB' to auto-correct the current word (only use
             ;; `C-.')
             (setq flyspell-use-meta-tab nil)
             ;; FIXME M-TAB is still bound to `flyspell-auto-correct-word'
             ;; when this chunk of code is placed within (eval-after-load "flyspell"...)

             (eval-after-load "flyspell"
               '(progn

               ;; don't consider that a word repeated twice is an error
               (setq flyspell-mark-duplications-flag nil)

               ;; enable the likeness criteria
               (setq flyspell-sort-corrections nil)

               ;; this fixes the "enabling flyspell mode gave an error" bug
               (setq flyspell-issue-welcome-flag nil)

               ;; ;; don't print messages for every word (when checking the
               ;; ;; entire buffer) as it causes an enormous slowdown
               ;; (setq flyspell-issue-message-flag nil)

               ;; dash character (`-') is considered as a word delimiter
               (setq flyspell-consider-dash-as-word-delimiter-flag t)

               ;; `flyspell-auto-correct-word' is bound to `C-.'
               ;; Press it one time to correct the word under the cursor.
               ;; If several spellings are possible, they appear in the
               ;; minibuffer. Just keep hitting `C-.' to replace the word with
               ;; the successive suggestions.

               ;; from Alex Schroeder
               (defun my/flyspell-toggle-dictionary ()
                 "Change the dictionary."
                 (interactive)
                 (let ((dict (or ispell-local-dictionary ispell-dictionary)))
                   (setq dict (if (string= dict "fr_FR") "en_US" "fr_FR"))
                   (message "Switched to %S" dict)
                   (sit-for 0.4)
                   (ispell-change-dictionary dict)
                   (when flyspell-mode
                     (flyspell-delete-all-overlays)
                     (flyspell-buffer))))

               ;; my default key bindings
               (global-set-key (kbd "<M-f10>") 'my/flyspell-toggle-dictionary)

               (defun my/flyspell-french ()
                 "Unconditionally turn on flyspell-mode (in French) and call
               `flyspell-buffer'."
                 (interactive)
                 (flyspell-mode 1) ;; instead of just toggling the mode
                 (ispell-change-dictionary "fr_FR")
                 (flyspell-buffer))

               (defun my/flyspell-english ()
                 "Unconditionally turn on flyspell-mode (in American English)
               and call `flyspell-buffer'."
                 (interactive)
                 (flyspell-mode 1)
                 (ispell-change-dictionary "en_US")
                 (flyspell-buffer))

               ;; turn on `flyspell' when changing a buffer which is
               ;; unmodified
               (when my/aspell-french-dictionary
                 ;; check that the French dictionary can be opened for reading
                 (defvar my/flyspell-major-mode-list
                   '(
                     ;; html-mode ;; XXX this makes Org publish check the generated files
                     ;; latex-mode   ; FIXME commented by FPZ
                     message-mode
                     ;; nxml-mode
                     ;; org-mode  ; FIXME Problem with flyspell (.emacs is *completely* screened...)
                     text-mode))

                 (add-hook 'first-change-hook
                           #'(lambda ()
                               (when (and (memq major-mode my/flyspell-major-mode-list)
                                          (not flyspell-mode))
                                 (my/flyspell-french)))))

               ;; Org mode is derived from outline-mode, which is derived from
               ;; text mode. A derived mode runs all the hooks from the parent
               ;; modes.
               ;;
               ;; I don't know how to turn this off, but you can work around
               ;; this by changing the function you put into the
               ;; text-mode-hook:
               ;;
               ;; (defun my/turn-on-flyspell-not-in-org-though ()
               ;;   (or (eq major-mode 'org-mode) (turn-on-flyspell)))

               ;; flyspell comments and strings in programming modes
               ;; (preventing it from finding mistakes in the code, which is
               ;; pretty cool)
               (defcustom to-spell-langs
                 '(c-mode-hook
                   emacs-lisp-mode-hook
                   haskell-mode-hook
                   java-mode-hook
                   jde-mode-hook
                   makefile-mode-hook
                   nxml-mode-hook
                   python-mode-hook
                   sh-mode-hook)
                 "Set of programming modes for which I want to enable spelling
               in comments and strings."
                 :type 'list)

               (dolist (lang-hook to-spell-langs)
                 (add-hook lang-hook 'flyspell-prog-mode))


               ;; spell-check your XHTML
               (add-to-list 'flyspell-prog-text-faces 'nxml-text-face)

               ))

        ))

        )



      ;; TODO Have a look at `diction' (style and grammar for English)

;;*** Define words

      (subsection "Define words")

      ;; pull definitions from Google and display them in a buffer
      (when (locate-library "google-define")
        (global-set-key (kbd "C-c D") 'google-define)
        (autoload 'google-define "google-define" nil t))

      (defun google-define-word-or-phrase (query)
        (interactive "sInsert word or phrase to search: ")
        (require 'mm-url)
        (let* ((url (concat "http://www.google.com.pe/search?hl=en&q=define%3A"
                            (replace-regexp-in-string " " "+" query)))
               (definition
                 (save-excursion
                   (with-temp-buffer
                     (mm-url-insert url)
                     (goto-char (point-min))
                     (if (search-forward "No definitions found of " nil t)
                         "No definitions found"
                       (buffer-substring (search-forward "<li>")
                                         (- (search-forward "<") 1)))))))
          (message "%s: %s" query definition)))
      (global-set-key (kbd "C-c d") 'google-define-word-or-phrase)
      ;; TODO This seems to be the first definition of the list returned by
      ;; `google-define'

      (when (locate-library "dictionary-init")
         (load-library "dictionary-init")

         ;; ask for a new word to search
         (global-set-key (kbd "C-c s") 'dictionary-search)

         ;; ask for a pattern and list all matching words
         (global-set-key (kbd "C-c m") 'dictionary-match-words))

      (eval-after-load "dictionary"
        '(progn

           (global-dictionary-tooltip-mode 1)

        ;; server contacted for searching the dictionary
        ;;    (setq dictionary-server "localhost")

        ;; ;; connect via a HTTP proxy (using the CONNECT command)
        ;; (setq dictionary-use-http-proxy t)
        ;;
        ;; ;; name of the HTTP proxy to use
        ;; (setq dictionary-proxy-server "hellman") ; XXX
        ;;
        ;; ;; port of the proxy server
        ;; (setq dictionary-proxy-port 8080) ; XXX

;; use proxy
(setq url-proxy-services
      `(("http"     . ,(getenv "http_proxy"))
	("ftp"      . ,(getenv "http_proxy"))
	("no_proxy" . "^.*example.com") ;; disable proxy for some hosts
        ))
))

)

;;* 21 (info "(emacs)Keyboard Macros")

(chapter chapter-21-keyboard-macros "21 Keyboard Macros"

;;** 21.1 (info "(emacs)Basic Keyboard Macro") Use

      (section "21.1 (emacs)Basic Keyboard Macro Use")

      ;; If you want to check the result each time before repeating, then
      ;; `C-x e e e...'.
      ;; If you want to repeat only <N> times, then `C-u <N> C-x e'.
      ;; If you want to repeat forever or until error, then `C-u 0 C-x e'.

      ;; <shift>-<F8>  to start recording
      ;; <shift>-<F8>  again to stop recording
      ;; <F8>          to call it

      (defun my/toggle-kbd-macro-recording-on ()
        "Start recording a keyboard macro and toggle functionality of key
      binding."
        (interactive)
        (global-set-key (kbd "<S-f8>") 'my/toggle-kbd-macro-recording-off)
        (start-kbd-macro nil))

      (defun my/toggle-kbd-macro-recording-off ()
        "Stop recording a keyboard macro and toggle functionality of key
      binding."
        (interactive)
        (global-set-key (kbd "<S-f8>") 'my/toggle-kbd-macro-recording-on)
        (end-kbd-macro))

      ;; start/stop recording a keyboard macro
      (global-set-key (kbd "<S-f8>") 'my/toggle-kbd-macro-recording-on)

      ;; execute the most recent keyboard macro
      (global-set-key (kbd "<f8>") 'call-last-kbd-macro)


;;** 21.5 Name and (info "(emacs)Save Keyboard Macro")s

      (section "21.5 (emacs)Name and Save Keyboard Macros")

      ;; assign a name to the last keyboard macro defined
      (global-set-key (kbd "<C-f8>") 'name-last-kbd-macro)

)

;;* 22 (info "(emacs)Files") Handling

(chapter chapter-22-files "22 Files Handling"

;;** 22.2 (info "(emacs)Visiting") Files

      (section "22.2 (emacs)Visiting Files")

      ;; visit a file
      (global-set-key (kbd "<f3>") 'find-file)

      ;; open my Emacs init file
      (defun my/open-dot-emacs ()
        "Opening Emacs startup file."
        (interactive)
        (find-file user-init-file))
      (global-set-key (kbd "<S-f3>") 'my/open-dot-emacs)

      ;; open my Timeclock file
      (defun my/open-timeclock ()
        "Switch to my timeclock file, or switch to the previous buffer."
        (interactive)
        (let ((timeclock-file "~/Projects/Work.org"))
          (when (file-exists-p timeclock-file)
            (if (and (buffer-file-name)
                     (string= (expand-file-name timeclock-file)
                              (expand-file-name (buffer-file-name))))
                (bury-buffer)
              (find-file timeclock-file)))))
      (global-set-key (kbd "<C-f4>") 'my/open-timeclock)

;;** 22.3 (info "(emacs)Saving") Files

      (section "22.3 (emacs)Saving Files")

      ;; make your changes permanent
      (global-set-key (kbd "<f2>") 'save-buffer)

      ;; ensure a file ends in a newline when it is saved
      (setq require-final-newline t)
      ;; TODO Do this only for text and Fundamental modes, because I could
      ;; edit binary files (see `mode-require-final-newline')

      ;; directory used for temporary files
      (XEmacs
       (setq temporary-file-directory (or (getenv "TEMP") "/tmp/")))

      ;; update time stamps every time you save a buffer
      (add-hook 'before-save-hook 'time-stamp)

      ;; maintain last change time stamps (`Time-stamp: <>' occurring within
      ;; the first 8 lines) in files edited by Emacs
      (eval-after-load "time-stamp"
        '(progn
           ;; format of the string inserted by `M-x time-stamp'
           (setq time-stamp-format "%Y-%02m-%02d %3a %02H:%02M %u on %s")))
           ;; `YYYY-MM-DD Weekday HH:MM user on system'
           ;; (see `system-time-locale' for non-numeric formatted items of time)

      ;; insert a time stamp string
      (defun my/insert-time-stamp ()
        "Insert a time stamp."
        (interactive "*")
        (insert (format "%s %s %s %s"
                        comment-start
                        (format-time-string "%Y-%m-%d")
                        (user-login-name)
                        comment-end)))

      (defun insert-date (prefix)
        "Insert the current date in ISO format. With one PREFIX argument,
      add day of week. With two PREFIX arguments, add day of week and
      time."
        (interactive "P")
        (let ((format (cond ((not prefix) "%Y-%m-%d")
                            ((equal prefix '(4)) "%Y-%m-%d %a")
                            ((equal prefix '(16)) "%Y-%m-%d %a %H:%M"))))
          (insert (format-time-string format))))

      (global-set-key (kbd "C-c .") 'insert-date)

      (GNUEmacs
       ;; update the copyright notice in current buffer
       (add-hook 'before-save-hook 'copyright-update))

;;** 22.4 (info "(emacs)Reverting") a Buffer

      (section "22.4 (emacs)Reverting a Buffer")

      ;; replace current buffer text with the text of the visited file on disk
      (defun my/revert-buffer ()
        "Unconditionally revert current buffer."
        (interactive)
        (flet ((yes-or-no-p (msg) t))
          (revert-buffer)))

      ;; key binding
      (global-set-key (kbd "<C-f12>") 'my/revert-buffer)

;;** 22.6 (info "(emacs)Auto Save"): Protection Against Disasters

      (section "22.6 (emacs)Auto Save: Protection Against Disasters")

      ;; how to get Emacs to auto-save to your local disk [`#file#']

      ;; auto-save every 100 input events
      (setq auto-save-interval 100)

      ;; auto-save after 10 seconds idle time
      (setq auto-save-timeout 10)

      ;; Check out Kevin's `ebackup.el' for saving in a specified common
      ;; directory (not in local dir) and handling saving of buffers with
      ;; spaces in their name... (otherwise, problems when composing *mail
      ;; replies to ...* )

      ;; ;; The `auto-save.el' and `backup.el' packages collect files in one
      ;; ;; place
      ;; (try-require 'auto-save)
      ;; (try-require 'backup)

      ;; put backup files (i.e., `foo~' or `foo.~i~') in one place
      (GNUEmacs
       ;; filenames matching a regexp are backed up in the corresponding
       ;; directory
       (setq backup-directory-alist
             ;; Emacs will `make-directory' it, if necessary
             '((".*" . "~/.emacs.d/backups/")))) ;; regexp => directory mappings

      (XEmacs
       (when (try-require 'backup-dir)
         ;; FIXME Use a `set' construction, with `make-local-variable'
         (make-variable-buffer-local 'backup-inhibited)
         (setq bkup-backup-directory-info
               '((t "~/.saves" ok-create full-path prepend-name)))))

      ;; always use copying to create backup files (don't clobber symlinks)
      (setq backup-by-copying t)

      (setq backup-by-copying-when-linked t)

      ;; make numeric backup versions
      (setq version-control t)

      ;; ;; number of oldest versions to keep when a new numbered backup is made
      ;; (setq kept-old-versions 0) ;; 2

      ;; number of newest versions to keep when a new numbered backup is made
      (setq kept-new-versions 20) ;; 2

      ;; delete excess backup versions silently
      (setq delete-old-versions t)


      ;; make the message "FILE has auto save data" unmissable
      (defface my/recover-this-file-face '((t (:background "tomato")))
        "Face for buffers visiting files with auto save data."
        :group 'files)

      (defvar recover-this-file nil
        "If non-nil, an overlay indicating that the visited file has auto save
      data.")

      (defun recover-this-file-find-file-hook ()
        ;; see after-find-file
        (let ((warn (not buffer-read-only)))
          (when (and warn
                     ;; No need to warn if buffer is auto-saved
                     ;; under the name of the visited file.
                     (not (and buffer-file-name
                               auto-save-visited-file-name))
                     (file-newer-than-file-p (or buffer-auto-save-file-name
                                                 (make-auto-save-file-name))
                                             buffer-file-name))
            (set (make-local-variable 'recover-this-file)
                 (make-overlay (point-min) (point-max)))
            (overlay-put recover-this-file 'face 'my/recover-this-file-face))))

      (add-hook 'find-file-hook 'recover-this-file-find-file-hook)

;;** 22.9 (info "(emacs)Comparing Files")

      (section "22.9 (emacs)Comparing Files")

      ;; default to unified diffs
      (setq diff-switches "-u")

      ;; run Ediff on a pair of files
      (global-set-key (kbd "C-= e") 'ediff-files)

      ;; compare text in current window with text in next window
      (global-set-key (kbd "C-= w") 'compare-windows)

      ;; `M-x smerge-mode RET'
      ;; That does not automatically select regions but provides convenient
      ;; key bindings to navigate between conflicts and to choose the A or B
      ;; variant

;;** 22.10 (info "(emacs)Diff Mode")

      (section "22.10 (emacs)Diff Mode")

      ;; extensions to `diff-mode.el' ("*Diff*" buffer is highlighted
      ;; differently)
      (try-require 'diff-mode-)
      ;; this library should be loaded *before* library `diff-mode.el'

      ;; run `diff' in compilation-mode
      (autoload 'diff-mode "diff-mode"
        "Diff major mode" t)

      ;; ediff, a comprehensive visual interface to diff & patch
      ;; setup for Ediff's menus and autoloads
      (try-require 'ediff-hook)

      ;; (eval-after-load "ediff"
      ;;   '(progn
           ;; (setq-default ediff-ignore-similar-regions  t)

           ;; auto-refine only the regions of this size (in bytes) or less
           (setq-default ediff-auto-refine-limit (* 2 14000))

           (setq ediff-grab-mouse 'maybe)

           ;; do everything in one frame
           (setq ediff-window-setup-function 'ediff-setup-windows-plain)

           ;; ;; split the window depending on the frame width
           ;; (setq ediff-split-window-function (lambda (&optional arg)
           ;;                                     (if (> (frame-width) 160)
           ;;                                         (split-window-horizontally arg)
           ;;                                       (split-window-vertically
           ;;                                       arg))))
           ;; ))

;;** 22.12 Accessing (info "(emacs)Compressed Files")

(chapter t "22.12"
      ;; Using the Emacs Dired utility, you can compress or uncompress a file
      ;; by pressing `Z'

      (GNUEmacs
       ;; TODO See `archive-zip-extract'

       (when nil ;; running-ms-windows
         ;; Unfortunately, if you are trying to use gunzip to uncompress a
         ;; file under Dired, you will probably encounter a problem saying
         ;; "Failed to uncompress ..." or "spawning child process: exec format
         ;; error". The problem is due to that gunzip provided by Cygwin is
         ;; not an executable file. It is a symbolic link to gzip. (You can
         ;; verify this by "ls -l /usr/bin/gunzip". Since Gnu Emacs does not
         ;; understand Cygwin's symbolic link, it cannot execute gunzip. Here
         ;; is the solution.

         ;; (require 'dired-aux)

         (defun dired-call-process (program discard &rest arguments)
           ;; 09Feb02, sailor overwrite this function because Gnu Emacs cannot
           ;; recognize gunzip is a symbolic link to gzip. Thus, if the
           ;; program is "gunzip", replace it with "gzip" and add an option
           ;; "-d".

           ;; "Run PROGRAM with output to current buffer unless DISCARD is t.
           ;; Remaining arguments are strings passed as command arguments to
           ;; PROGRAM."
           ;; Look for a handler for default-directory in case it is a
           ;; remote file name.
           (let ((handler
                  (find-file-name-handler
                   (directory-file-name default-directory)
                   'dired-call-process)))
             (if handler (apply handler 'dired-call-process
                                program discard arguments)
               (progn
                 (if (string-equal program "gunzip")
                     (progn
                       (setq program "gzip")
                       (add-to-list 'arguments "-d")))
                 (apply 'call-process
                        program nil (not discard) nil arguments)))))))

)

;;*** Encryption

      (subsection "Encryption")

      ;; EasyPG (http://www.easypg.org/) is a GnuPG interface for Emacs. It
      ;; has two aspects:
      ;;
      ;; - convenient tools which allow to use GnuPG from Emacs (EasyPG
      ;;   Assistant), and
      ;;
      ;; - a fully functional interface library to GnuPG (EasyPG Library).

      ;; EasyPG (aka `epg') is the successor of `pgg' for encrypting and
      ;; signing.

      ;; What is PGP/MIME, what is OpenPGP, and how Gnus handles them.
      ;; - PGP/MIME is a standard, which mml2015* implements using ep[ag]-*.
      ;; - OpenPGP is a standard, which ep[ag]-* implements.

      ;; the EasyPG Assistant, transparent file encryption
      (eval-after-load "epa-file"
        '(progn
        ;; EasyPG allows you to encrypt/decrypt files within Emacs. When you
        ;; use `C-x C-f' to access an encrypted file, Emacs prompts you for
        ;; the passphrase and then decrypts the file before displaying it.
        ;; When you save the file, Emacs automatically encrypts it again with
        ;; that same key.

        ;; ;; enable EPA to get `.gpg' files to be automatically encrypted
        ;; (epa-file-enable) ;; not necessary anymore since Emacs 23?

	;; stop EasyPG from asking for the recipient used for encrypting files
	(setq epa-file-encrypt-to "fni@mygooglest.com")
	;; If no one is selected (""), symmetric encryption will be performed

	;; cache passphrase for symmetric encryption (VERY important)
	(setq epa-file-cache-passphrase-for-symmetric-encryption t)
	;; Not to sound paranoid. But if you want caching, it's recommended to
	;; use *public-key encryption* instead of symmetric encryption.
	;; `gpg-agent' is the preferred way to do this.

	;; prompt for the password in the Emacs minibuffer (instead of using a
	;; graphical password prompt for GPG)
	(setenv "GPG_AGENT_INFO" nil)))

      ;; to fetch the key automatically, set the `keyserver' entry in the
      ;; `~/.gnupg/gpg.conf' file properly

      (define-minor-mode sensitive-mode
        "For sensitive files like password lists.
      It disables backup creation and auto saving.

      With no argument, this command toggles the mode. Non-null
      prefix argument turns on the mode. Null prefix argument
      turns off the mode."

        ;; the initial value
        nil

        ;; the indicator for the mode line
        " Sensitive"

        ;; the minor mode bindings
        nil
        (if (symbol-value sensitive-mode)
            (progn
              ;; disable backups
              (set (make-local-variable 'backup-inhibited) t)
              ;; disable auto-save
              (if auto-save-default
                  (auto-save-mode -1)))
          ;; resort to default value of backup-inhibited
          (kill-local-variable 'backup-inhibited)
          ;; resort to default auto save setting
          (if auto-save-default
              (auto-save-mode 1))))

      ;; Once the above snippet has been evaluated in Emacs, `M-x sensitive'
      ;; will disable backups and auto-save in the current buffer. All other
      ;; buffers will continue to have these features.

      ;; I usually set sensitive mode to turn on by default for files having
      ;; the `.gpg' extension. The following code when put in your `.emacs'
      ;; does exactly that:
      (add-to-list 'auto-mode-alist '("\\.gpg\\'" . sensitive-mode))

)

;;** 22.14 (info "(emacs)Remote Files")

(chapter t "22.14"

      (section "22.14 (emacs)Remote Files")

;;*** Ange-FTP

      ;; transparent FTP support
      (eval-after-load "ange-ftp"

        ;; try to use passive mode in ftp, if the client program supports it
        '(setq ange-ftp-try-passive-mode t)) ;; needed for Ubuntu

;;*** TRAMP - Transparent Remote Access, Multiple Protocols

      (eval-after-load "tramp" ;; the autoloads are predefined
        '(progn

;;* 4 (info "(tramp)Configuration") of TRAMP for use

;;** 4.6 Selecting a (info "(tramp)Default Method")

         (section "4.6 (tramp)Configuration of TRAMP for use")

           ;; default transfer method
           (setq tramp-default-method  ; `scp' by default
                 (cond (running-ms-windows
                        ;; (issues with Cygwin `ssh' which does not cooperate
                        ;; with Emacs processes -> use `plink' from PuTTY, it
                        ;; definitely does work under Windows)
                        ;;
                        ;; `C-x C-f /plink:myuser@host:/some/directory/file'
                        "plink")
                       (t
                        "ssh")))

           ;; You might try out the `rsync' method, which saves the remote
           ;; files quite a bit faster than SSH. It's based on SSH, so it
           ;; works the same, just saves faster.

           ;; ;; 2011-07-25 New test on Windows XP
           ;; (setq tramp-default-method "ssh")
           ;;
           ;; (nconc (cadr (assq 'tramp-login-args (assoc "ssh" tramp-methods)))
           ;;        '(("bash" "-i")))
           ;; (setcdr (assq 'tramp-remote-sh (assoc "ssh" tramp-methods))
           ;;         '("bash -i"))


;;** 4.7 Selecting a (info "(tramp)Default User")

           ;; default user
           (setq tramp-default-user "fni")


;;** 4.9 Connecting to a remote host using (info "(tramp)Multi-hops")

           ;; new proxy system (introduced with Tramp 2.1, instead of the old
           ;; "multi-hop" filename syntax) to edit files on a remote server by
           ;; going via another server
           (when (boundp 'tramp-default-proxies-alist)
             (add-to-list 'tramp-default-proxies-alist
                          ;; "final host" "user" "proxy in the middle"
                          '("10.10.13.123" "\\`root\\'" "/ssh:%h:")))
           ;; Opening `/sudo:10.10.13.123:' would connect first `10.10.13.123'
           ;; via `ssh' under your account name, and perform `sudo -u root' on
           ;; that host afterwards. It is important to know that the given
           ;; method is applied on the host which has been reached so far. The
           ;; trick is to think from the end.


;;** 4.12 (info "(tramp)Password handling") for several connections

           ;; how many seconds passwords are cached
           (setq password-cache-expiry 60)  ; default is 16


;;** 4.15 (info "(tramp)Remote shell setup") hints

           ;; string used for end of line in rsh connections
           (setq tramp-rsh-end-of-line  ; `\n' by default
                 (cond (running-ms-windows
                        "\n")
                       (t
                        "\r")))


;;** 4.16 (info "(tramp)Auto-save and Backup") configuration

           ;; faster auto saves
           (setq tramp-auto-save-directory temporary-file-directory)

;;* 9 How to Customize (info "(tramp)Traces and Profiles")

           ;; debugging Tramp
           (setq tramp-verbose 6) ; 10
           ;; The usual way debugging Tramp is to set tramp-verbose to 6. This
           ;; will produce a debug buffer, which you can show at
           ;; tramp-devel@gnu.org. The best way to report a Tramp bug is to
           ;; call `M-x tramp-bug'; this prepares an email, including
           ;; information for analysis.

           ;; call `M-x tramp-submit-bug' to generate an email with several
           ;; trace information

           (setq tramp-debug-buffer t)

           ;; "turn off" the effect of `backup-directory-alist' for TRAMP
           ;; files
           (add-to-list 'backup-directory-alist
                        (cons tramp-file-name-regexp nil))

           ;; make Emacs beep after reading from or writing to the remote host
           (defadvice tramp-handle-write-region
             (after tramp-write-beep-advice activate)
             " make tramp beep after writing a file."
             (interactive)
             (beep))
           (defadvice tramp-handle-do-copy-or-rename-file
             (after tramp-copy-beep-advice activate)
             " make tramp beep after copying a file."
             (interactive)
             (beep))
           (defadvice tramp-handle-insert-file-contents
             (after tramp-copy-beep-advice activate)
             " make tramp beep after copying a file."
             (interactive)
             (beep))

           ;; define own abbreviation (for use with bookmarks)
           (add-to-list 'directory-abbrev-alist
                        (if (memq system-type '(cygwin windows-nt))
                            '("^/RUSSELL" . "//RUSSELL/Users")
                          '("^/RUSSELL" . "/smb:fni@RUSSELL:/Users")))

           ;; after adding:
           ;;     (setq coding-system-for-read 'utf-8)
           ;;     (setq coding-system-for-write 'utf-8)
           ;; to my `.emacs', TRAMP works correctly with UTF-8 files.

           (defun my/find-file-sudo-header-warning ()
             "*Display a warning in header line of the current buffer."
             (let* ((warning "WARNING: EDITING FILE WITH ROOT PRIVILEGES!")
                    (space (+ 6 (- (frame-width) (length warning))))
                    (bracket (make-string (/ space 2) ?-))
                    (warning (concat bracket warning bracket)))
               (setq header-line-format
                     (propertize warning 'face 'header-line))))

           (defun my/find-file-sudo (filename)
             "Open FILENAME with root privileges."
             (interactive "F")
             (set-buffer (find-file (concat "/sudo::" filename)))
             (my/find-file-sudo-header-warning))

           (defadvice find-file (around my/find-file activate)
             "Open FILENAME using tramp's sudo method if it's read-only."
             (if (and (file-exists-p (ad-get-arg 0))
                      (not (file-writable-p (ad-get-arg 0)))
                      (not (file-remote-p (ad-get-arg 0)))
                      (y-or-n-p (concat "File "
                                        (ad-get-arg 0)
                                        " is read-only.  Open it as root? ")))
                 (my/find-file-sudo (ad-get-arg 0))
               ad-do-it))

           ))
)

;;** 22.17 (info "(emacs)File Conveniences")

(chapter t "22.17"
      ;; setup a menu of recently opened files
      (try-require 'recentf)
      (eval-after-load "recentf"
        '(progn

           ;; save the whole list of items of the recent list
           (setq recentf-max-saved-items 200)

           ;; file to save the recent list into
           (setq recentf-save-file "~/.emacs.d/recentf.txt")

           ;; maximum number of items in the recentf menu
           (setq recentf-max-menu-items 200)

           ;; to protect from TRAMP -- FIXME not correctly supported (yet)
           ;; under Win32
           (setq recentf-auto-cleanup 'never)

           ;; save file names relative to my current home directory
           (setq recentf-filename-handlers '(abbreviate-file-name))

           ;; toggle `recentf' mode
           (recentf-mode 1)

           ;; add key binding
           (global-set-key (kbd "C-x C-r") 'recentf-open-files)))


      ;; visit a file
      (global-set-key (kbd "<f3>") 'find-file-at-point)

      ;; find file (or URL) at point
      (eval-after-load "ffap"
        '(progn
           ;; don't use default key bindings, as I want some of them to be
           ;; defined differently (`C-x C-r', for example)

           ;; function called to fetch an URL
           (setq ffap-url-fetcher 'browse-url)
           ;; could be `browse-url-emacs' or `w3m-browse-url'
           ))

      (GNUEmacs
       ;; open helm / QuickSilver-like candidate-selection framework
       (when (locate-library "helm")
         (autoload 'helm "helm" nil t)
         (global-set-key (kbd "M-X") 'helm)

         (autoload 'helm-for-files "helm" nil t)
         (global-set-key (kbd "<f3>") 'helm-for-files)

         ;; For my part, C-x b is helm-mini, which serves up a combination
         ;; of buffers and recent files. C-x C-i is helm-imenu, which is
         ;; awesome wearing a hat. C-x f is helm for recent files, and C-x
         ;; C-f is ido-find-file, which still trumps helm.el for navigating
         ;; about file systems.

         (autoload 'helm-M-x "helm" nil t)
         (global-set-key (kbd "M-x") 'helm-M-x)

         (autoload 'helm-mini "helm" nil t)
         (global-set-key (kbd "C-x b") 'helm-mini)
                                          ; or `helm-buffers-list' for just
                                          ; the existing buffers (no recent
                                          ; files)

         (autoload 'helm-imenu "helm" nil t)
         (global-set-key (kbd "<f4>") 'helm-imenu) ;; better than `org-toc'

         ;; (global-set-key (kbd "C-c o")       'helm-occur) ;; conflict with org-occur-goto
       )

       (eval-after-load "helm"
         '(progn

            ;; prefix key for all `helm-command-map' commands
            (setq helm-command-map-prefix-key "C-c C-f")

            (when (try-require 'helm-config)  ; loads `helm.el' too

              ;; Locate for Windows users:
              ;; You have to install Everything with his command line interface here:
              ;; http://www.voidtools.com/download.php

              ;; humane match plug-in for helm
              (try-require 'helm-match-plugin)

              ;; completion with helm
              (try-require 'helm-complete)

              ;; help messages for Helm
              (try-require 'helm-help) ;; for `helm-imenu'

              ;; uses the current window (no popup) to show the candidates
              (setq helm-samewindow t)

              ;; candidates separator of `multiline' source
              (setq helm-candidate-separator
                    (propertize "--separator-------------------------------"
                                'face 'separator-face))

              ;; suppress displaying sources which are out of screen at first
              (setq helm-quick-update t)

              ;; the user has to be idle for this many seconds, before candidates
              ;; from *delayed* sources are collected (useful for sources involving
              ;; heavy operations, so that candidates from the source are not
              ;; retrieved unnecessarily if the user keeps typing)
              (setq helm-idle-delay 0.1)

              ;; the user has to be idle for this many seconds, before ALL
              ;; candidates are collected (also effective for *non-delayed*
              ;; sources)
              (setq helm-input-idle-delay 0.1) ;; (1.2) >= `helm-idle-delay'

              ;; do not show more candidates than this limit from individual
              ;; sources
              (setq helm-candidate-number-limit 100) ;; more than one screen page

              ;; locate program with its list of arguments (case-insensitive)
              (setq helm-c-locate-command "locate -i -r %s")
              (when (executable-find "es.exe")
                (setq helm-c-locate-command "es -r %s"))

              ;;   (try-require 'helm-c-yasnippet)

              ;;   ;; ;; make helm minibuffer better input latency
              ;;   ;; (defadvice helm-check-minibuffer-input (around sit-for activate)
              ;;   ;;   (if (sit-for helm-idle-delay t)
              ;;   ;;       ad-do-it))

              ;;   ;; don't save history information to file
              ;;   (remove-hook 'kill-emacs-hook 'helm-c-adaptive-save-history)


              ;; show icons in `helm-find-files'
              (setq helm-c-find-files-show-icons t)

              ;; search etags candidates by regexp
              (setq helm-c-etags-use-regexp-search t)

              (defun helm-switch-to-log ()
                (interactive)
                (switch-to-buffer "*Helm Log*"))

              (defun helm-toggle-debug ()
                (interactive)
                (setq helm-debug (not helm-debug))
                (message "Helm Debug is now %s" (if helm-debug "Enabled" "Disabled")))

              ))
         ))

      ;; TODO Have a look at gpicker -- a solution for quickly choosing file
      ;; from (possibly large) projects!

      ;; show image files as images (not as semi-random bits)
      (GNUEmacs
       (auto-image-file-mode 1))

      ;; inline image minor mode
      (when (try-require 'iimage)

        ;; XXX Test me!

        ;; This allows for the viewing of images in-line in Org mode
        ;; documents.
        (setq iimage-mode-image-search-path (expand-file-name "~/"))

        ;; Match org file: links
        (add-to-list 'iimage-mode-image-regex-alist
                     (cons (concat "\\[\\[file:\\(~?"
                                   iimage-mode-image-filename-regex
                                   "\\)\\]")  1))

        (defun org-toggle-iimage-in-org ()
          (interactive)
          (let ((turning-on (not iimage-mode)))
            (set-face-underline-p 'org-link (not turning-on))
            (iimage-mode (or turning-on 0)))))

      )

;;* 23 Using Multiple (info "(emacs)Buffers")

(chapter chapter-23-buffers "23 Using Multiple Buffers"

;;** 23.2 (info "(emacs)List Buffers")

      (section "23.2 (emacs)List Buffers")

      ;; The C (current) column has a `.' for the buffer from which you came.
      ;; The R (read-only) column has a `%' if the buffer is read-only.
      ;; The M (modified) column has a `*' if it is modified.

      ;; rebind `C-x C-b'
      (global-set-key (kbd "C-x C-b") 'electric-buffer-list)
      ;; `buffer-menu' moves point in the window which lists your buffers
      ;; `electric-buffer-list' pops up a buffer describing the set of buffers

      ;; operate on buffers like Dired
      (global-set-key (kbd "C-x C-b") 'ibuffer)
      (eval-after-load "ibuffer"
        '(progn
        ;; completely replaces `list-buffer'
        (defalias 'ibuffer-list-buffers 'list-buffer)

        ;; ;; don't show the names of filter groups which are empty
        ;; (setq ibuffer-show-empty-filter-groups nil)

        ;; filtering groups
        (setq ibuffer-saved-filter-groups
              '(("default"
                 ("Chat" (or
                          (mode . garak-mode)
                          (name . "^\\*Garak\\*$")
                          (mode . circe-mode)))
                 ("Org" (or
                         (mode . diary-mode)
                         (mode . org-mode)
                         (mode . org-agenda-mode)))
                 ("LaTeX" (or (mode . latex-mode)
                              (mode . LaTeX-mode)
                              (mode . bibtex-mode)
                              (mode . reftex-mode)))
                 ("Gnus & News" (or
                                 (mode . message-mode)
                                 (mode . bbdb-mode)
                                 (mode . mail-mode)
                                 (mode . gnus-group-mode)
                                 (mode . gnus-summary-mode)
                                 (mode . gnus-article-mode)
                                 (name . "^\\(\\.bbdb\\|dot-bbdb\\)$")
                                 (name . "^\\.newsrc-dribble$")
                                 (mode . newsticker-mode)))
                 ("Files" (filename . ".*"))
                 ("Dired" (mode . dired-mode))
                 ("Shell" (mode . shell-mode))
                 ("Version Control" (or (mode . svn-status-mode)
                                        (mode . svn-log-edit-mode)
                                        (name . "^\\*svn-")
                                        (name . "^\\*vc\\*$")
                                        (name . "^\\*Annotate")
                                        (name . "^\\*git-")
                                        (name . "^\\*vc-")))
                 ("Emacs" (or (name . "^\\*scratch\\*$")
                              (name . "^\\*Messages\\*$")
                              (name . "^TAGS\\(<[0-9]+>\\)?$")
                              (name . "^\\*Occur\\*$")
                              (name . "^\\*grep\\*$")
                              (name . "^\\*Compile-Log\\*$")
                              (name . "^\\*Backtrace\\*$")
                              (name . "^\\*Process List\\*$")
                              (name . "^\\*gud\\*$")
                              (name . "^\\*Kill Ring\\*$")
                              (name . "^\\*Completions\\*$")
                              (name . "^\\*tramp")
                              (name . "^\\*compilation\\*$")))
                 ("Emacs Source" (or (mode . emacs-lisp-mode)))
                 ("Documentation" (or
                                   (mode . Info-mode)
                                   (mode . apropos-mode)
                                   (mode . woman-mode)
                                   (mode . help-mode)
                                   (mode . Man-mode))))))

        (add-hook 'ibuffer-mode-hook
                  (lambda ()
                    (ibuffer-switch-to-saved-filter-groups "default")))

        ;; Order the groups so the order is : [Default], [agenda], [emacs]
        (defadvice ibuffer-generate-filter-groups
          (after reverse-ibuffer-groups () activate)
          (setq ad-return-value (nreverse ad-return-value)))
        ))

      ;; put the current buffer at the end of the list of all buffers
      (global-set-key (kbd "<f12>") 'bury-buffer)


      ;; ;; Like standard Emacs 22 commands (bound to C-x left/right)
      ;; (define-key global-map [f11] 'previous-buffer) ;; my/buffer-prev
      ;; (define-key global-map [f12] 'next-buffer)     ;; my/buffer-next

      ;; ;; Like standard Emacs 22 commands (bound to M-g n/p)
      ;; (define-key global-map [(control f11)] 'previous-error)
      ;; (define-key global-map [(control f12)] 'next-error)
      ;; (define-key global-map [(control shift f11)] 'compilation-previous-file)
      ;; (define-key global-map [(control shift f12)] 'compilation-next-file)

;;** 23.4 (info "(emacs)Kill Buffer")

      (section "23.4 (emacs)Kill Buffer")

      ;; kill buffer without confirmation (if not modified)
      (defun my/kill-this-buffer ()
        "Kill the current buffer without confirmation (if not modified)."
        (interactive)
        (kill-buffer nil))

      ;; key binding
      (global-set-key (kbd "<S-f12>") 'my/kill-this-buffer)

;;** 23.7 (info "(emacs)Buffer Convenience") and Customization of Buffer Handling

      (section "23.7 (emacs)Buffer Convenience and Customization of Buffer Handling")

      ;; unique buffer names dependent on file name
      (try-require 'uniquify)
      (eval-after-load "uniquify"
        '(progn

           ;; style used for uniquifying buffer names with parts of directory
           ;; name
           (setq uniquify-buffer-name-style 'forward)

           ;; distinguish directories by adding extra separator
           (setq uniquify-trailing-separator-p t)))

;;* 24 Multiple (info "(emacs)Windows")

(chapter chapter-24-windows "24 Multiple Windows"

;;** 24.1 (info "(emacs)Basic Window")

      ;; turn off this horrible tab thingy in XEmacs
      (XEmacs
       (when (boundp 'default-gutter-visible-p)
         (set-specifier default-gutter-visible-p nil)))

;;** 24.3 (info "(emacs)Other Window")

      ;; cycle through all windows on current frame
      (global-set-key (kbd "<f6>") 'other-window)

;;** 24.4 (info "(emacs)Pop Up Window")

      ;; don't allow splitting windows vertically
      (setq split-height-threshold nil)

      ;; minimum width for splitting windows horizontally
      (setq split-width-threshold 160)


      ;; (GNUEmacs
      ;;
      ;;  (defun my/display-buffer (buffer force-other-window)
      ;;    "If BUFFER is visible, select it.
      ;;
      ;;  If it's not visible and there's only one window, split the
      ;;  current window and select BUFFER in the new window. If the
      ;;  current window (before the split) is more than 160 columns wide,
      ;;  split horizontally, else split vertically.
      ;;
      ;;  If the current buffer contains more than one window, select
      ;;  BUFFER in the least recently used window.
      ;;
      ;;  This function returns the window which holds BUFFER.
      ;;
      ;;  FORCE-OTHER-WINDOW is ignored."
      ;;    (or (get-buffer-window buffer)
      ;;        (if (one-window-p)
      ;;            (let ((new-win (if (> (window-width) 160)
      ;;                               (split-window-horizontally)
      ;;                             (split-window-vertically))))
      ;;              (set-window-buffer new-win buffer)
      ;;              new-win)
      ;;          (let ((new-win (get-lru-window)))
      ;;            (set-window-buffer new-win buffer)
      ;;            new-win))))
      ;;
      ;;  (setq display-buffer-function 'my/display-buffer))

)

;;** 24.6 (info "(emacs)Change Window")

      ;; delete all windows in the selected frame except the selected window
      (global-set-key (kbd "<f5>") 'delete-other-windows)

      ;; enlarge or shrink windows more easily than with `C-x {' and the like
      (global-set-key (kbd "<C-S-up>") 'enlarge-window)
      (global-set-key (kbd "<C-S-down>") 'shrink-window)
      (global-set-key (kbd "<C-S-left>") 'enlarge-window-horizontally)
      (global-set-key (kbd "<C-S-right>") 'shrink-window-horizontally)

      ;; make all visible windows the same height (approximately)
      (global-set-key (kbd "<C-f6>") 'balance-windows)

      ;; swap 2 windows
      (defun my/swap-windows ()
        "If you have 2 windows, it swaps them."
        (interactive)
        (cond ((not (= (count-windows) 2))
               (message "You need exactly 2 windows to do this."))
              (t
               (let* ((w1 (first (window-list)))
                      (w2 (second (window-list)))
                      (b1 (window-buffer w1))
                      (b2 (window-buffer w2))
                      (s1 (window-start w1))
                      (s2 (window-start w2)))
                 (set-window-buffer w1 b2)
                 (set-window-buffer w2 b1)
                 (set-window-start w1 s2)
                 (set-window-start w2 s1)))))

      (global-set-key (kbd "C-c ~") 'my/swap-windows)

      (defun my/toggle-window-split ()
        "Vertical split shows more of each line, horizontal split shows
      more lines. This code toggles between them. It only works for
      frames with exactly two windows."
        (interactive)
        (if (= (count-windows) 2)
            (let* ((this-win-buffer (window-buffer))
                   (next-win-buffer (window-buffer (next-window)))
                   (this-win-edges (window-edges (selected-window)))
                   (next-win-edges (window-edges (next-window)))
                   (this-win-2nd (not (and (<= (car this-win-edges)
                                               (car next-win-edges))
                                           (<= (cadr this-win-edges)
                                               (cadr next-win-edges)))))
                   (splitter
                    (if (= (car this-win-edges)
                           (car (window-edges (next-window))))
                        'split-window-horizontally
                      'split-window-vertically)))
              (delete-other-windows)
              (let ((first-win (selected-window)))
                (funcall splitter)
                (if this-win-2nd (other-window 1))
                (set-window-buffer (selected-window) this-win-buffer)
                (set-window-buffer (next-window) next-win-buffer)
                (select-window first-win)
                (if this-win-2nd (other-window 1))))))

      (global-set-key (kbd "C-c |") 'my/toggle-window-split)

;;  24.7 (info "(emacs)Window Convenience")

      ;; Use `M-x scroll-all-mode' to scroll all visible windows together in
      ;; parallel.

)

;;* 25 (info "(emacs)Frames") and Graphical Displays

(chapter chapter-25-frames "25 Frames and Graphical Displays"

;;** 25.1 (info "(emacs)Cut and Paste")

      (section "25.1 (emacs)Cut and Paste on Graphical Displays")

      ;; copy/paste with Gnome desktop
      (GNUEmacs
       ;; ;; cutting and pasting uses the clipboard
       ;; (setq x-select-enable-clipboard t) ;; default in Emacs 24

       ;; make cut, copy and paste (keys and menu bar items) use the clipboard
       (menu-bar-enable-clipboard)

       )

;;** 25.5 (info "(emacs)Creating Frames")

      (section "25.5 (emacs)Creating Frames")

      ;; put Emacs exactly where you want it, every time it starts up, by
      ;; auto-detecting the screen dimensions and computing where it should be
      (when window-system
        ;; list of default values for frame creation
        (GNUEmacs
         (add-to-list 'default-frame-alist
                      (cons 'height
                            (/ (- (x-display-pixel-height) 85)
                               (frame-char-height))))
         ;; (add-to-list 'default-frame-alist (cons 'top 0))
         ;; (add-to-list 'default-frame-alist (cons 'left 0))
         )

        ;; list of frame parameters for creating the initial frame
        (setq initial-frame-alist
              '((top . 0)
                (left . 0)))

        ;; default value of `vertical-scroll-bar' for buffers that don't
        ;; override it
        (setq default-vertical-scroll-bar 'right))

      (XEmacs
       (set-frame-width (buffer-dedicated-frame) 80)
       (set-frame-height (buffer-dedicated-frame) 42)
       (set-frame-position (buffer-dedicated-frame) 0 0))

      ;; title bar display of visible frames
      (setq frame-title-format "Emacs") ;; XXX for StumpWM?  Dunno anymore...

;;** 25.6 (info "(emacs)Frame Commands")

      (section "25.6 (emacs)Frame Commands")

      (XWindow
       (defun toggle-full-screen ()
         "Toggle between full screen and partial screen display on X11;
       courtesy of http://www.emacswiki.org/cgi-bin/wiki/FullScreen"
         (interactive)
         ;; WM must support EWMH
         ;; http://standards.freedesktop.org/wm-spec/wm-spec-latest.html
         (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
                                '(2 "_NET_WM_STATE_FULLSCREEN" 0)))

       (global-set-key (kbd "C-c z") 'toggle-full-screen))

      (GNUEmacs
       (when running-ms-windows
         (defun w32-maximize-frame ()
           "Maximize the current frame."
           (interactive)
           (w32-send-sys-command 61488)
           (global-set-key (kbd "C-c z") 'w32-restore-frame))

         (global-set-key (kbd "C-c z") 'w32-maximize-frame)

         (defun w32-restore-frame ()
           "Restore a minimized frame."
           (interactive)
           (w32-send-sys-command 61728)
           (global-set-key (kbd "C-c z") 'w32-maximize-frame))))

;;** 25.8 (info "(emacs)Speedbar")

      (section "25.8 (emacs)Speedbar Frames")

      ;; TODO don't bind F4 if already bound to helm... If helm not there, OK do it.
      ;; ;; jump to speedbar frame
      ;; (global-set-key (kbd "<f4>") 'speedbar-get-focus)

      ;; everything browser (into individual source files), or Dired on
      ;; steroids
      (eval-after-load "speedbar"
        '(progn

           ;; number of spaces used for indentation
           (setq speedbar-indentation-width 2)

           ;; expand/collapse LaTeX sections
           (speedbar-add-supported-extension
            '(".bib" ".css" ".jpg" ".js" ".nw" ".php" ".png" ".tex" ".txt" ".w"
              "README"))

           ;; bind the arrow keys in the speedbar tree
           ;; [http://www.uweb.ucsb.edu/~dreamtheorist/emacs.html]
           (define-key speedbar-key-map (kbd "<right>") 'speedbar-expand-line)
           (define-key speedbar-key-map (kbd "<left>") 'speedbar-contract-line)

           ;; parameters to use when creating the speedbar frame in Emacs
           (setq speedbar-frame-parameters '((width . 30)
                                             (height . 45)
                                             (foreground-color . "blue")
                                             (background-color . "white")))))

      ;; speedbar in the current frame (vs in a new frame)
      (when (locate-library "sr-speedbar")
        (autoload 'sr-speedbar-toggle "sr-speedbar" nil t)
        ;; TODO don't bind F4 if already bound to helm... If helm not there, OK do it.
        ;; (global-set-key (kbd "<f4>") 'sr-speedbar-toggle)
        )

;;** 25.16 (info "(emacs)Tool Bars")

      (section "25.16 Tool Bars")

      ;; turn tool bar off
      (GNUEmacs (tool-bar-mode -1))
      (XEmacs (set-specifier default-toolbar-visible-p nil))

;;** 25.17 Using (info "(emacs)Dialog Boxes")

      (section "25.17 Using Dialog Boxes")

      ;; don't use dialog boxes to ask questions
      (setq use-dialog-box nil)

      ;; don't use a file dialog to ask for files
      (setq use-file-dialog nil)

;;** 25.18 (info "(emacs)Tooltips")

      ;; use the echo area for help and GUD tooltips
      (setq tooltip-use-echo-area t)

;;** 25.19 (info "(emacs)Mouse Avoidance")

      (section "25.19 Mouse Avoidance")

      (when window-system
        ;; make mouse pointer stay out of the way of editing
        (mouse-avoidance-mode 'jump))


      ;; ;; Move the mouse to the screen corner on any keypress.
      ;; (when (and (display-mouse-p)
      ;;            (require 'avoid nil t))
      ;;   ;; ;; Move the mouse to the lower-right corner instead of default
      ;;   ;; ;; upper-right
      ;;   ;; (defun mouse-avoidance-banish-destination ()
      ;;   ;;   (cons (+ 3 (frame-width)) (frame-height)))
      ;;   (mouse-avoidance-mode 'banish))

)

;;* 26 (info "(emacs)International") Character Set Support

(chapter chapter-26-international "26 International Character Set Support"

;;** 26.3 (info "(emacs)Language Environments")

      (section "26.3 (emacs)Language Environments")

      ;; (describe-current-coding-system)
      ;; (set-buffer "*Help*")
      ;; (write-file "~/coding-system-before.txt")

      ;; specify your character-set locale
      (setenv "LANG" "en_US.utf8")
      ;; for svn not to report warnings

      ;; (describe-coding-system nil)
      ;; (set-buffer "*Help*")
      ;; (write-file "~/coding-system-after.txt")

      ;; system locale to use for formatting time values
      (setq system-time-locale "C") ;; make sure that timestamps in your
                                    ;; org-mode files appear in English

      ;; (setq system-time-locale "en_US.utf8") ;; I do get French timestamps

;;** 26.4 (info "(emacs)Input Methods")

      (section "26.4 (emacs)Input Methods")

      ;; get 8-bit characters in terminal mode (Cygwin)
      (set-input-mode (car (current-input-mode))
                      (nth 1 (current-input-mode))
                      0)

      ;; `M-x describe-coding-system RET RET'

      ;; ;; default input method for multilingual text
      ;; (setq default-input-method "latin-1-prefix")

      ;; To see all the non-ASCII characters you can type with the `C-x 8'
      ;; prefix, type `C-x 8 C-h'.

;;** 26.6 (info "(emacs)Coding Systems")

      (section "26.6 (emacs)Coding Systems")

      ;; For any user who needs symbols that are not in the 7-bit ASCII set,
      ;; our recommendation is to move to Unicode UTF-8. That is the only
      ;; encoding that is the same across all platforms and operating systems
      ;; that support it.

;;** 26.7 (info "(emacs)Recognize Coding") Systems

      (section "26.7 (emacs)Recognize Coding Systems")

      (add-to-list 'file-coding-system-alist
                   '("\\.owl\\'" utf-8 . utf-8))
      ;; and all the rest is utf-8:
      ;; '("" . utf-8)

      ;; In GNU Emacs, when you specify the coding explicitly in the file,
      ;; that overrides `file-coding-system-alist'. Not in XEmacs?

      ;; The variable `auto-coding-alist' is the strongest way to specify the
      ;; coding system for certain patterns of file names, or for files
      ;; containing certain patterns; this variable even overrides
      ;; `-*-coding:-*-' tags in the file itself.

      ;; default coding system (for new files),
      ;; also moved to the front of the priority list for automatic detection
      (GNUEmacs
       (cond
        (running-ms-windows
         (prefer-coding-system 'utf-8-unix)) ;; XXX unix flavor for script executing in Org-Babel
        ;; FIXME Prefer ISO Latin 1 (temporarily, for PFlow)
        (t
         (prefer-coding-system 'utf-8))))
      ;; or set environment variables like `LC_CTYPE', `LC_ALL' or `LANG'

;;** 26.8 (info "(emacs)Specify Coding") System of a File

      (section "26.8 (emacs)Specify Coding System of a File")

      (GNUEmacs
       ;; to copy and paste to and from Emacs through the clipboard (with
       ;; coding system conversion)
       (cond (running-ms-windows
              (set-selection-coding-system 'compound-text-with-extensions))
             (t
              (set-selection-coding-system 'utf-8))))

;;** 26.17 (info "(emacs)Undisplayable Characters")

      (section "26.17 (emacs)Undisplayable Characters")

      (GNUEmacs
       ;; display page delimiter character `^L' as an horizontal line
       ;; see autoloads file (gnus-load, bbdb-hooks, etc.)
       (when (locate-library "pp-c-l")

         ;; function to produce string displayed in place of each `C-l' char
         (setq pp^L-^L-string-function
               (lambda nil
                 (make-string (1- (window-width)) (string-to-char " "))))

         ;; string displayed just before `pp^L-^L-string'
         (setq pp^L-^L-string-pre "")

         ;; turn on pretty display of `^L'
         (eval-after-load "pp-c-l"
           '(pretty-control-l-mode 1))

	 (autoload 'refresh-pretty-control-l "pp-c-l" nil t)

         ;; normal hook run to initialize window system display
         (add-hook 'window-setup-hook
                   'refresh-pretty-control-l)

         ;; functions to call when window configuration changes
         (add-hook 'window-configuration-change-hook
                   'refresh-pretty-control-l)))

)

;;* 27 (info "(emacs)Major Modes")

(chapter chapter-27-major-modes "27 Major Modes"

;;** 27.1 (info "(emacs)Choosing Modes")

      (section "27.1 How Choosing Modes")

      (autoload 'ssh-config-mode "ssh-config-mode" t)


;;*** 1. Choice based on the file name

      ;; list of filename patterns
      ;; vs. corresponding major mode functions
      (setq auto-mode-alist
            (append '(("\\.log\\'"       . text-mode)
                      ("\\.[tT]e[xX]\\'" . latex-mode)
                      ;; ("\\.cls\\'"       . LaTeX-mode)
                      ("\\.cgi\\'"       . perl-mode)
                      ("[mM]akefile"     . makefile-mode)
                      (".ssh/config\\'"  . ssh-config-mode)
                      ("sshd?_config\\'" . ssh-config-mode)
                      ) auto-mode-alist))

      (autoload 'asp-mode "asp-mode" nil t)
      (setq auto-mode-alist
            (cons '("\\.asp\\'" . asp-mode) auto-mode-alist))

      ;; ledger
      (add-to-list 'auto-mode-alist '("\\.dat\\'" . ledger-mode))
      (autoload 'ledger-mode "ledger"
        "A mode for editing ledger data files.")

      ;; major mode for editing comma-separated value files
      (add-to-list 'auto-mode-alist '("\\.csv\\'" . csv-mode))
      (autoload 'csv-mode "csv-mode"
        "Major mode for editing comma-separated value files." t)
      (eval-after-load "csv-mode"
        ;; field separators: a list of *single-character* strings
        '(setq csv-separators '("," ";")))

      ;; For example, nxml-mode's instruction tells you to do:
      ;; (when (load-library
      ;;        "~/Downloads/emacs/site-lisp/nxml-1.33-20080630/autostart.el")
      ;;
      ;;     ;; always skip the nXhtml welcome message
      ;;     (setq nxhtml-skip-welcome t))
      ;;
      ;; (when running-ms-windows
      ;;   (when (file-exists-p (concat windows-program-files-dir
      ;;                                "Emacs-23/EmacsW32/nxhtml/autostart.el"))
      ;;     ;; (load (concat windows-program-files-dir "Emacs-23/EmacsW32/nxhtml/autostart.el"))
      ;;
      (add-to-list 'auto-mode-alist '("\\.s?html?\\'" . nxml-mode))
      ;;
      ;;     (add-to-list 'auto-mode-alist
      ;;                  '("\\.\\(xml\\|xsl\\|svg\\)\\'" . nxml-mode))
      ;;     (fset 'xml-mode 'nxml-mode)
      ;;
      ;;     ;; remove the binding of `C-c C-x', used by Org timeclocking commands
      ;;     (add-hook 'nxml-mode-hook
      ;;               (lambda ()
      ;;                 (define-key nxml-mode-map
      ;;                   (kbd "C-c C-x") nil)))))

      ;; instead of superseding the binding in `auto-mode-alist', you can
      ;; replace it (brute force) with
      ;; `(setcdr (rassq 'old-mode auto-mode-alist) 'new-mode)'

;;*** 2. Choice based on the interpreter name

      ;; list of interpreters specified in the first line (starts with `#!')
      ;; vs. corresponding major mode functions
      (push '("expect" . tcl-mode) interpreter-mode-alist)

;;*** 3. Choice based on the text at the start of the buffer

      ;; list of buffer beginnings
      ;; vs. corresponding major mode functions
      ;; see `magic-mode-alist'


      ;; ;; load generic modes which support e.g. batch files
      ;; (try-require 'generic-x)

)

;;* 28 (info "(emacs)Indentation")

(chapter chapter-28-indentation "28 Indentation"

;;** 28.1 (info "(emacs)Indentation Commands") and Techniques

      (section "28.1 (emacs)Indentation Commands and Techniques")

      ;; `C-M-\' runs the command `indent-region' (which does the job of
      ;; the imaginary command `unsuck-html-layout' in `html-mode')

      (defun indent-whole-buffer ()
        (interactive)
        (save-excursion
          (mark-whole-buffer)
          (indent-for-tab-command)))


;;** 28.3 TABs vs. (info "(emacs)Just Spaces")

      (section "28.3 TABs vs. (emacs)Just Spaces")

      ;; indentation can't insert TABs
      (setq-default indent-tabs-mode nil)

)

;;* 29 Commands for (info "(emacs)Text") Human Languages

(chapter chapter-29-text "29 Commands for Human Languages"

;;** 29.1 (info "(emacs)Words")

      (section "29.1 (emacs)Words")

      ;; GNU Emacs default for killing back to the beginning of a word
      (XEmacs
       (global-set-key (kbd "<C-backspace>") 'backward-kill-word))

;;** 29.2 (info "(emacs)Sentences")

      (section "29.2 (emacs)Sentences")

      ;; a single space does end a sentence
      (setq-default sentence-end-double-space nil)
      ;; FIXME When changing the ispell language, this should be changed
      ;; simultaneously.

      ;; See `sentence-end' and `(sentence-end)'

;;** 29.5 (info "(emacs)Filling") Text

      (section "29.5 (emacs)Filling Text")

      ;; line-wrapping beyond that column (when pressing `M-q')
      (setq-default fill-column 78)

      ;; `M-q' runs the command `fill-paragraph'. `C-u M-q' runs
      ;; "unfill-paragraph"
      (defun my/fill-paragraph (&optional arg)
        (interactive "P")
        (let ((fill-column (if arg
                               (point-max)
                             fill-column)))
          (fill-paragraph nil)))

      (global-set-key (kbd "M-q") 'my/fill-paragraph)


      ;; (add-hook 'fill-nobreak-predicate 'fill-french-nobreak-p)
      ;; (add-hook 'fill-nobreak-predicate 'fill-single-word-nobreak-p)

      ;; enable FillAdapt (does a better job than Emacs builtin Adaptative
      ;; Fill mode)
      (autoload 'turn-on-filladapt-mode "filladapt"
        "Unconditionally turn on Filladapt mode in the current buffer.")
      (autoload 'turn-off-filladapt-mode "filladapt"
        "Unconditionally turn off Filladapt mode in the current buffer.")

      (defun my/enable-filling ()
        "Enable AutoFill and FillAdapt minor modes."

        ;; when inserting text, *automatically* break line at a previous
        ;; space, if the current column number is greater than the value of
        ;; `fill-column'
        (turn-on-auto-fill)

        ;; turn on FillAdapt mode everywhere but in ChangeLog files
        (cond ((equal mode-name "Change Log") t)
              (t (turn-on-filladapt-mode))))

      ;; enable AutoFill and FillAdapt in Text and Org modes
      (add-hook 'text-mode-hook 'my/enable-filling)
      ;; (add-hook 'org-mode-hook 'my/enable-filling)

      ;; replace space by nobreak-space where it fits well
      (defun my/replace-space-before-colon ()
        "Replace space by nobreak-space in front of a colon."
        (interactive)
        (cond ((eq (char-before) ?\ ) ;; normal space
               (progn
                 (backward-delete-char 1)
                 (if (equal mode-name "PDFLaTeX")
                     (insert "~:")
                   (insert " :")))) ;; non-breaking space
              ;; remove nobreak-space if two colons are put one after the
              ;; other (for terms and definitions in Org)
              ((and (eq (char-before) ?\:)
                    (eq (char-before (- (point) 1)) ?\ ))
               (progn
                 (backward-delete-char 2)
                 (insert " ::"))) ;; normal space
              (t (insert ":"))))
      ;; FIXME Don't put a nobreak space when specifying Org Babel properties
      ;; (such as :exports both)

      (defun my/replace-space-before-question-mark ()
        "If any, replace space by nobreak-space in front of a question mark."
        (interactive)
        (if (eq (char-before) ?\ ) ; normal space
            (progn
              (backward-delete-char 1)
              (if (equal mode-name "PDFLaTeX")
                  (insert "~?")
                (insert " ?"))) ; non-breaking space
          (insert "?")))

      (defun my/replace-space-before-exclamation-mark ()
        "If any, replace space by nobreak-space in front of an exclamation
      mark."
        (interactive)
        (if (eq (char-before) ?\ ) ; normal space
            (progn
              (backward-delete-char 1)
              (if (equal mode-name "PDFLaTeX")
                  (insert "~!")
                (insert " !"))) ; non-breaking space
          (insert "!")))

      (defun my/replace-space-before-semi-colon ()
        "If any, replace space by nobreak-space in front of a semi-colon."
        (interactive)
        (if (eq (char-before) ?\ ) ; normal space
            (progn
              (backward-delete-char 1)
              (if (equal mode-name "PDFLaTeX")
                  (insert "~;")
                (insert " ;"))) ; non-breaking space
          (insert ";")))

      ;; French typography
      (defun my/nobreak-keys ()
        "If any, replace space in front of colons, question marks, exclamation
      marks, etc. to avoid line break problems."
        (interactive)
        (local-set-key ":" 'my/replace-space-before-colon)
        (local-set-key "?" 'my/replace-space-before-question-mark)
        (local-set-key "!" 'my/replace-space-before-exclamation-mark)
        (local-set-key ";" 'my/replace-space-before-semi-colon))

      (add-hook 'text-mode-hook 'my/nobreak-keys)
      (add-hook 'message-mode-hook 'my/nobreak-keys)

      (defun insert-one-quote-or-two ()
        (interactive)
        (cond
         ((or (bolp) (not (looking-back "'")))
          ;; insert just one '
          (self-insert-command 1))
         ((save-excursion
            (backward-char)
            ;; Skip symbol backwards.
            (and (not (zerop (skip-syntax-backward "w_")))
                 (not (looking-back "`"))
                 (or (insert-and-inherit "`") t))))
         (t
          ;; insert `' around following symbol
          (delete-backward-char 1)
          (unless (looking-back "`") (insert-and-inherit "`"))
          (save-excursion
            (skip-syntax-forward "w_")
            (unless (looking-at "'") (insert-and-inherit "'"))))))

      (global-set-key [39] 'insert-one-quote-or-two)

;;** 29.6 (info "(emacs)Case") Conversion Commands

      (section "29.6 (emacs)Case Conversion Commands")

      ;; enable the use of the commands `downcase-region' and `upcase-region'
      ;; without confirmation
      (put 'downcase-region 'disabled nil)
      (put 'upcase-region 'disabled nil)

;;** 29.8 (info "(emacs)Outline Mode")

      (section "29.8 (emacs)Outline Mode")

;;*** outline-minor-mode

      ;; you can use org-cycle in other modes, with outline-minor-mode

      ;; outline mode commands for Emacs
      (eval-after-load "outline"
        '(progn

        ;; bind the outline minor mode functions to an easy to remember prefix
        ;; key (more accessible than the horrible prefix `C-c @')
        (setq outline-minor-mode-prefix (kbd "M-o"))

        ;; ;; make other `outline-minor-mode' files (LaTeX, etc.) feel the Org
        ;; ;; mode outline navigation (written by Carsten Dominik)
        ;; (when (try-require 'outline-magic)
        ;;   (add-hook 'outline-minor-mode-hook
        ;;             (lambda ()
        ;;               (define-key outline-minor-mode-map
        ;;                 (kbd "<backtab>") 'outline-cycle)
        ;;
        ;;               (define-key outline-minor-mode-map
        ;;                 (kbd "<M-left>") 'outline-promote)
        ;;               (define-key outline-minor-mode-map
        ;;                 (kbd "<M-right>") 'outline-demote)
        ;;               (define-key outline-minor-mode-map
        ;;                 (kbd "<M-up>") 'outline-move-subtree-up)
        ;;               (define-key outline-minor-mode-map
        ;;                 (kbd "<M-down>") 'outline-move-subtree-down))))

        ;; ;; extra support for outline minor mode
        ;; (try-require 'out-xtra)


        ;; Org-style folding for a `.emacs' (and much more)

        ;; FIXME This should be in an `eval-after-load' of Org, so that
        ;; `org-level-N' are defined when used

        (defun my/outline-regexp ()
          "Calculate the outline regexp for the current mode."
          (let ((comment-starter (replace-regexp-in-string
                                  "[[:space:]]+" "" comment-start)))
            (when (string= comment-start ";")
              (setq comment-starter ";;"))
            ;; (concat "^" comment-starter "\\*+")))
            (concat "^" comment-starter "[*]+ ")))

        ;;??? don't fontify the whole line for headings
        (setq org-fontify-whole-heading-line t)

        (defun my/outline-minor-mode-hook ()
          (interactive)
          (setq outline-regexp (my/outline-regexp))

          ;; highlight the headings
          ;;
          ;; see http://www.gnu.org/software/emacs/manual/html_node/emacs/Font-Lock.html
          ;; use `M-x customize-apropos-faces' to customize faces to find the
          ;; corresponding face for each outline level, see `org-faces.el'

          ;; Added `\n?', after having read the following chunk of code (from
          ;; `org.el'):
          ;; `(,(if org-fontify-whole-heading-line
          ;;        "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
          ;;      "^\\(\\**\\)\\(\\* \\)\\(.*\\)")

          (let* ((org-fontify-whole-heading-line "") ; "\n?")
                 (heading-1-regexp
                  (concat (substring outline-regexp 0 -1)
                          "\\{1\\} \\(.*" org-fontify-whole-heading-line "\\)"))
                 (heading-2-regexp
                  (concat (substring outline-regexp 0 -1)
                          "\\{2\\} \\(.*" org-fontify-whole-heading-line "\\)"))
                 (heading-3-regexp
                  (concat (substring outline-regexp 0 -1)
                          "\\{3\\} \\(.*" org-fontify-whole-heading-line "\\)"))
                 (heading-4-regexp
                  (concat (substring outline-regexp 0 -1)
                          "\\{4,\\} \\(.*" org-fontify-whole-heading-line "\\)")))
            (font-lock-add-keywords nil
             `((,heading-1-regexp 1 'org-level-1 t)
               (,heading-2-regexp 1 'org-level-2 t)
               (,heading-3-regexp 1 'org-level-3 t)
               (,heading-4-regexp 1 'org-level-4 t)))))

        (add-hook 'outline-minor-mode-hook
                  'my/outline-minor-mode-hook)

        ;; Add the following as the top line of your `.emacs':
        ;;
        ;; ; -*- mode: emacs-lisp; eval: (outline-minor-mode 1); -*-
        ;;
        ;; Now you can add `;;' and `;;*', etc. as headings in your `.emacs'
        ;; and cycle using `M-TAB', `M-left' and `M-right' will collapse or
        ;; expand all headings respectively. I am guessing you mean to make
        ;; segments such as `;; SHORTCUTS' and `;; VARIABLES', this will do
        ;; that, but not too much more.
        ))


      ;; ;; Explorer-like bindings (`M-left/right/up/down' to navigate outlines)
      ;; ;; XXX check whether this is needed or useful
      ;; (when (locate-library "outline-mode-easy-bindings.el")
      ;;
      ;;   (add-hook 'outline-mode-hook
      ;;             '(lambda ()
      ;;                (require 'outline-mode-easy-bindings)))
      ;;
      ;;   (add-hook 'outline-minor-mode-hook
      ;;             '(lambda ()
      ;;                (require 'outline-mode-easy-bindings))))


      ;; I really like the following for outline-node based navigation.  It is
      ;; similar to the behavior of paredit-mode in lisp files.
      ;; Org mode hook
      (add-hook 'org-mode-hook
                (lambda ()
                  (local-set-key (kbd "\C-\M-n") 'outline-next-visible-heading)
                  (local-set-key (kbd "\C-\M-p") 'outline-previous-visible-heading)
                  (local-set-key (kbd "\C-\M-u") 'outline-up-heading)))



      (global-set-key (kbd "<S-tab>") 'org-cycle) ; that works (but on level 1+)
      ;; TODO Look at org-cycle-global and local below, they work better, but
      ;; still on level 1+
      ;; TODO Replace it by a function which alternatively does `hide-body' and
      ;; `show-all'

;;*** org-struct-mode

      ;; XXX 2010-06-21 Conflicts with outline-minor-mode bindings
      ;; ;; Use `orgstruct-mode' in `emacs-lisp-mode' buffers
      ;; (add-hook 'emacs-lisp-mode-hook 'orgstruct-mode)

      ;; > Experienced users use outline-minor-mode - It takes time to getting
      ;; > used to it (or any other such mode).
      ;;
      ;; You can also use orgstruct-mode, a minor mode that comes with
      ;; org-mode.

      ;; org-global-cycle now works fine in buffers using
      ;; orgstruct-mode.

;; ;; add a hook to use `orgstruct-mode' in emacs-lisp buffers
;; (add-hook 'emacs-lisp-mode-hook 'orgstruct-mode)

;; define a new `org-cycle-global' command
(defun org-cycle-global () (interactive) (org-cycle t))

;; set this keybinding
(global-set-key (kbd "<backtab>") 'org-cycle-global)

;;       > I have the following code in my ruby-mode-hook to enable code folding
;;       > using outline-minor-mode + outline-magic.
;;       >
;;       > (outline-minor-mode 1)
;;       > (set (make-local-variable 'outline-regexp) "^[ \t]*\\(?:def
;; > \\|class\\|module\\)\\|^[ \t]*###==")
;;
;;       Did you try the suggestion in the FAQ that I pointed to?
;;
;;       While in emacs-lisp-mode + outline-minor-mode + below mentioned-hook,
;;       `C-TAB' and `S-TAB' fold and unfold the defuns as expected. Note that for
;;       `C-TAB' to work, the cursor needs to be on a headline (the line where the
;;       ellipsis shows)
;;
;;       You don't have to do any additional settings for code folding to work.
;;
;;       ,----
;;       | Can I get the visibility-cycling features in outline-mode and
;;       | outline-minor-mode?
;;       |
;;       | Yes, these functions are written in a way that they are independent of
;;       | the outline setup. The following setup provides standard Org-mode
;;       | functionality in outline-mode on `TAB' and `S-TAB'. For outline-minor-mode,
;;       | we use `C-TAB' instead of `TAB', because `TAB' usually has mode-specific
;;       | tasks.
;;       |
;;       | (add-hook 'outline-minor-mode-hook
;;       |   (lambda ()
;;       |     (define-key outline-minor-mode-map [(control tab)] 'org-cycle)
;;       |     (define-key outline-minor-mode-map [(shift tab)] 'org-global-cycle)))
;;       |
;;       | (add-hook 'outline-mode-hook
;;       |   (lambda ()
;;       |     (define-key outline-mode-map [(tab)] 'org-cycle)
;;       |     (define-key outline-mode-map [(shift tab)] 'org-global-cycle)))
;;       |
;;       | Or check out outline-magic.el, which does this and also provides
;;       | promotion and demotion functionality. outline-magic.el is available at
;;       | Outline Magic.
;;       `----
;;
;;       > What's the equivalent in orgstruct?  org-outline-regexp seems
;;       > interesting but isn't documented.
;;
;;       orgstruct mode is for editing org-like text in other modes - like
;;       message mode etc. It has NOTHING to do with folding of code as
;;       such.
;;
;;       In summary, in a ruby buffer,
;;
;;       1. Add the above hook for folding and unfolding ruby functions.


      ;; from Bastien
      (defun org-cycle-global ()
        (interactive)
        (org-cycle t))

      (defun org-cycle-local ()
        (interactive)
        (save-excursion
          (move-beginning-of-line nil)
          (org-cycle)))

      (global-set-key (kbd "C-M-]") 'org-cycle-global)
                                        ; ok on Elisp, not on LaTeX

      (global-set-key (kbd "M-]") 'org-cycle-local)
                                        ; ok on Elisp, not on LaTeX


;;*** fold-dwim-org

      ;; unified user interface for Emacs folding modes, bound to org
      ;; key-strokes
      (GNUEmacs
       (try-require 'fold-dwim-org-XXX))

      (global-set-key (kbd "<M-f6>") 'visible-mode)

;;** 29.9 (info "(emacs)TeX Mode")

      (section "29.9 (emacs)TeX Mode")

;;** 1.2 (info "(auctex)Installation") of AUCTeX

      (when (locate-library "auctex.el")
        (load "auctex.el") t)

      ;; support for LaTeX documents
      (GNUEmacs
       (eval-after-load "latex"
       ;; if "tex", error when loading the TeX-mode, because we add-to-list in a LaTeX variable (not loaded yet)
         '(progn

            ;; TEST ??
            (add-hook 'tex-mode-hook 'imenu-add-menubar-index)


            ;; (try-require 'tex-site)
            ;; should not be used anymore with current AUCTeX releases


            ;; ;; LaTeX-sensitive spell checking
            ;; (add-hook 'tex-mode-hook
            ;;           (lambda ()
            ;;             (make-local-variable 'ispell-parser)
            ;;             (setq ispell-parser 'tex)))

;;** 1.3 (info "(auctex)Quick Start")

;;** 2.6 (info "(auctex)Completion")

            (section "2.6 (auctex)Completion")

            ;; if this is non-nil when AUCTeX is loaded, the TeX escape
            ;; character `\' will be bound to `TeX-electric-macro'
            (setq TeX-electric-escape t)

;;** 2.8 (info "(auctex)Indenting")

            (section "2.8 (auctex)Indenting")

            ;; leave the `tikzpicture' code unfilled when doing `M-q'
            (add-to-list 'LaTeX-indent-environment-list '("tikzpicture"))

            ;; ;; number of spaces to add to the indentation for each `\begin'
            ;; ;; not matched by a `\end'
            ;; (setq LaTeX-indent-level 4) ;; 2
            ;;
            ;; ;; number of spaces to add to the indentation for `\item''s in list
            ;; ;; environments
            ;; (setq LaTeX-item-indent 0) ;; -2
            ;;
            ;; ;; number of spaces to add to the indentation for each `{' not
            ;; ;; matched by a `}'
            ;; (setq TeX-brace-indent-level 0) ;; 2

            ;; auto-indentation (suggested by the AUCTeX manual -- instead of
            ;; adding a local key binding to `RET' in the `LaTeX-mode-hook')
            (setq TeX-newline-function 'newline-and-indent)

;;* 3 Controlling Screen (info "(auctex)Display")

;;** 3.1 (info "(auctex)Font Locking")

            (section "3.1 (auctex)Font Locking")

            ;; (for Org mode) add the `comment' environment to the variable
            ;; `LaTeX-verbatim-environments' so that, if the `#+TBLFM' line
            ;; contains an odd number of dollar characters, this does not
            ;; cause problems with font-lock in latex-mode
            (add-to-list 'LaTeX-verbatim-environments "comment")
            ;; (add-to-list 'LaTeX-verbatim-environments "mcnuweb")
            ;; ;; FIXME Does not work in .nw files

;;** 4.1 Executing (info "(auctex)Commands")

            (section "4.1 Executing (auctex)Commands")

            ;; add a command to execute on the LaTeX document
            (add-to-list 'TeX-command-list
                         '("XeLaTeX" "%`xelatex%(mode)%' %t" TeX-run-TeX nil t))

            (defun my/LaTeX-mode-hook ()
              ;; default command to run in the LaTeX buffer
              (setq TeX-command-default
                    (save-excursion
                      (save-restriction
                        (widen)
                        (goto-char (point-min))
                        (let ((re (concat
                                   "^\\s-*\\\\usepackage\\(?:\\[.*\\]\\)?"
                                   "{.*\\<\\(?:font\\|math\\)spec\\>.*}")))
                          (save-match-data
                            (if (re-search-forward re 3000 t)
                                "XeLaTeX"
                              "LaTeX")))))))

            (add-hook 'LaTeX-mode-hook 'my/LaTeX-mode-hook)

            ;; use PDF mode by default (instead of DVI)
            (setq-default TeX-PDF-mode t)

;;** 4.2 (info "(auctex)Viewing") the formatted output

            (section "4.2 (auctex)Viewing the formatted output")

            (defvar sumatrapdf-command
              (concat windows-program-files-dir "SumatraPDF/SumatraPDF.exe")
              "Path to the SumatraPDF executable.")

            ;; use a saner PDF viewer (evince, SumatraPDF)
            (setcdr (assoc "^pdf$" TeX-output-view-style)
                    (cond (running-ms-windows
                           `("." (concat "\"" ,sumatrapdf-command "\" %o")))
                          ;; under Windows, we could open the PDF file with
                          ;; `start "" xxx.pdf' (in a command prompt)
                          (t
                           '("." "evince %o"))))

            ;; A decent viewer reloads the PDF automatically when the file has
            ;; changed while staying on the same page (no need to close &
            ;; reopen).

            ;; Support for forward search with PDF files was added. That means
            ;; the viewer jumps to the page in the output file corresponding
            ;; to the position in the source file. Currently this only works
            ;; if you use the pdfsync LaTeX package and xpdf or SumatraPDF as
            ;; your PDF viewer.

            ;; for AUCTeX 11.86
            (when (boundp 'TeX-view-program-list)
              (add-to-list 'TeX-view-program-list
                           `("SumatraPDF"
                             (concat "\"" ,sumatrapdf-command "\" %o"))))

            (when running-ms-windows
              (setcdr (assoc 'output-pdf TeX-view-program-selection)
                      '("SumatraPDF")))

;;** 4.3 (info "(auctex)Debugging") Catching the errors

            (section "4.3 (auctex)Debugging Catching the errors")

            ;; don't show output of TeX compilation in other window
            (setq TeX-show-compilation nil)

;;** 4.5 Controlling the output

            (define-derived-mode latex-output-mode fundamental-mode "LaTeX-Output"
              "Simple mode for colorizing LaTeX output."
              (set (make-local-variable 'font-lock-defaults)
                   '((("^!.*" . compilation-error-face) ; LaTeX error
                      ("^-+$" . compilation-info-face) ; latexmk divider
                      ("^Package .* Warning: .*" . compilation-warning-face)
                      ("Reference .* undefined" . compilation-warning-face)
                      ("^\\(?:Overfull\\|Underfull\\|Tight\\|Loose\\).*" . font-lock-string-face)
                      ("^LaTeX Font Warning:" . font-lock-string-face)
                      ;; .....
                      ))))

            (defadvice TeX-recenter-output-buffer
              (after colorize-latex-output activate)
              (with-selected-window (get-buffer-window (TeX-active-buffer))
                (latex-output-mode)))

;;** 5.2 (info "(auctex)Multifile") Documents

            ;; AUCTeX will will assume the file is a master file itself
            (setq-default TeX-master t)

;;** 5.3 Automatic (info "(auctex)Parsing Files")

            ;; enable parse on load (if no style hook is found for the file)
            (setq TeX-parse-self t)

            ;; enable automatic save of parsed style information when saving
            ;; the buffer
            (setq TeX-auto-save t)

;;** 5.5 (info "(auctex)Automatic") Customization

            ;; TODO Add beamer.el to TeX-style-path

;;*** 5.5.1 (info "(auctex)Automatic Global") Customization for the Site

            (section "5.5.1 (auctex)Automatic Global Customization for the Site")

            ;; directory containing automatically generated TeX information
            (setq TeX-auto-global
                  ;; must end with a slash
                  "~/.emacs.d/auctex-auto-generated-info/")

;;*** 5.5.3 (info "(auctex)Automatic Local") Customization for a Directory

            (section "5.5.3 (auctex)Automatic Local Customization for a Directory")

            ;; directory containing automatically generated TeX information
            (setq TeX-auto-local
                  ;; must end with a slash
                  "~/.emacs.d/auctex-auto-generated-info/")

;;** (info "(preview-latex)Top")

            (section "(preview-latex)Top")

            (when (locate-library "preview-latex.el")
              (load "preview-latex.el") t)

            (eval-after-load "preview"
              '(progn

                 ;; path to gs command (for conversion from EPS)
                 (setq preview-gs-command
                   (cond (running-ms-windows
                          (concat windows-program-files-dir
                                  "gs/gs9.01/bin/gswin32c.exe"))
                         (t
                          "/usr/bin/gs")))
                 (my/file-exists-and-executable-p preview-gs-command)

                 ;; scale factor for included previews
                 (setq preview-scale-function 1.2)))

            (add-hook 'LaTeX-mode-hook 'turn-on-reftex)
                                      ; with AUCTeX LaTeX mode

            ;; minor mode with distinct support for `\label', `\ref', `\cite'
            ;; and `\index' in LaTeX
            (eval-after-load "reftex"
              '(progn
                 ;; turn all plug-ins on
                 (setq reftex-plug-into-AUCTeX t)

                 ;; use a separate selection buffer for each label type -- so the
                 ;; menu generally comes up faster
                 (setq reftex-use-multiple-selection-buffers t)))

            )))

;;** (info "(emacs-goodies-el)boxquote")

      (section "(emacs-goodies-el)boxquote")

      ;; quote text with a semi-box
      (autoload 'boxquote-region "boxquote" nil t)
      (eval-after-load "boxquote"
        '(progn
           ;; Unicode characters
           (setq boxquote-top-and-tail "━━━━")
           (setq boxquote-title-format "┫ %s ┃")

           ;; put spaces before my boxquotes
           (setq boxquote-top-corner    "    ┏")
           (setq boxquote-side          "    ┃ ")
           (setq boxquote-bottom-corner "    ┗")))

      ;; --8<---------------cut here---------------start------------->8---
      ;; In Gnus, you can mark some region with enclosing tags by pressing
      ;; `C-c M-m' (`message-mark-inserted-region') or by clicking on
      ;; `<menu-bar> <Message> <Insert Region Marked>'.
      ;; --8<---------------cut here---------------end--------------->8---


      ;; phonetic spelling
      (when (locate-library "phonetic")
        (autoload 'phonetize-region "phonetic" nil t))

)

;;* 30 Editing (info "(emacs)Programs")

(chapter chapter-30-programs "30 Editing Programs"

;;** 30.1 Major Modes for (info "(emacs)Program Modes")

      (section "30.1 Major Modes for (emacs)Program Modes")

      (autoload 'graphviz-dot-mode "graphviz-dot-mode" nil t)
      (add-to-list 'auto-mode-alist '("\\.dot\\'" . graphviz-dot-mode))

;;** 30.2 Top-Level Definitions, or (info "(emacs)Defuns")

      (section "30.2 Top-Level Definitions, or (emacs)Defuns")

      ;; making buffer indexes as menus (awesome!)
      (when (try-require 'imenu)

        ;; automatically add Imenu to the menu bar in /any/ mode that supports
        ;; it
        (defun try-to-add-imenu ()
          (condition-case nil
              (imenu-add-to-menubar "Imenu")
            (error nil)))
        (add-hook 'font-lock-mode-hook 'try-to-add-imenu)

        ;; show current function in mode line (based on Imenu)
        (which-func-mode 1)) ;; ~ Stickyfunc mode (in header line)

  ;;** 30.3 (info "(emacs)Program Indent")ation

        (section "30.3 (emacs)Program Indentation")

        ;; turn on auto-fill mode in Lisp modes
        (add-hook 'lisp-mode-hook 'turn-on-auto-fill)
        (add-hook 'emacs-lisp-mode-hook 'turn-on-auto-fill)

        ;; auto-indentation: automatically jump to the "correct" column when
        ;; the RET key is pressed while editing a program (act as if you
        ;; pressed `C-j')
        (GNUEmacs24
         (add-hook 'prog-mode-hook
                   '(lambda () (local-set-key (kbd "RET") 'newline-and-indent))))

        ;; (defun back-to-indentation-or-beginning ()
        ;;   (interactive)
        ;;   (if (/= (point) (line-beginning-position))
        ;;       (beginning-of-line)
        ;;     (back-to-indentation)))
        ;;
        ;; (defun align-with-spaces (beg end)
        ;;   "Align selected using only spaces for whitespace."
        ;;   (interactive "r")
        ;;   (let ((indent-tabs-mode nil))
        ;;     (align beg end)))

;;** 30.4 Commands for Editing with (info "(emacs)Parentheses")

      (section "30.4 Commands for Editing with (emacs)Parentheses")

      ;; find matching parenthesis (`%' command in vim)
      (defun match-paren (arg)
        "Go to the matching parenthesis, if on a parenthesis; otherwise,
      insert `%'."
        (interactive "p")
        (cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1))
              ((looking-at "\\s\)") (forward-char 1) (backward-list 1))
              (t (self-insert-command (or arg 1)))))

      ;; go to matching paren
      (global-set-key (kbd "%") 'match-paren)

      ;; highlight matching parenthesis
      (GNUEmacs
       (show-paren-mode t)
       (setq show-paren-ring-bell-on-mismatch t)
       (setq show-paren-style 'mixed))
      (XEmacs
       (paren-set-mode 'paren))

      ;; if the matching paren is offscreen, show the matching line in the
      ;; echo area + many other useful things
      (when window-system
        ;; advanced highlighting of matching parentheses
        (when (try-require 'mic-paren)

          ;; activating
          (paren-activate)))


      ;; highlight surrounding parentheses
      (GNUEmacs
      (autoload 'highlight-parentheses-mode "highlight-parentheses" nil t)
       (eval-after-load "highlight-parentheses"
       '(progn
        (define-globalized-minor-mode global-highlight-parentheses-mode
          highlight-parentheses-mode
          (lambda ()
            (highlight-parentheses-mode t)))
        (global-highlight-parentheses-mode t)

        (setq hl-paren-background-colors
              '("#FF993F" "#FFF33F" "#B0FF3F" "#4BFF4B"
                "#3FFFB0" "#3FF3FF" "#3F99FF" "#3F3FFF"))

        (setq hl-paren-colors
              '("black" "black" "black" "black" "black"
                "black" "black" "white")))))

;;** 30.5 (info "(emacs)Comments")

      ;; always comments out empty lines
      (setq comment-empty-lines t)

;;** 30.6 (info "(emacs)Documentation") Lookup

      (section "30.6 (emacs)Documentation Lookup")

      ;; show the function arglist or the variable docstring in the echo area
      (GNUEmacs
       (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))

;;** 30.7 (info "(emacs)Hideshow") minor mode

      (section "30.7 (emacs)Hideshow minor mode")

      ;; enable hideshow for programming
      (add-hook 'java-mode-hook       (lambda () (hs-minor-mode 1)))
      (add-hook 'perl-mode-hook       (lambda () (hs-minor-mode 1)))
      (add-hook 'emacs-lisp-mode-hook (lambda () (hs-minor-mode 1)))


      ;; Especially after changing a couple of those really awkward
      ;; key bindings with `@' in the middle.
      ;; Changing: C-c @ c-s  to C-c s  (hs-show-block)
      ;;           C-c @ c-h  to C-c h  (hs-hide-block)
      ;; Seems not to collide with anything when in cperl-mode at least.


      ;; (define-key hs-minor-mode-map
      ;;   [?\C-c ?\C-\M-h] 'hs-hide-all)
      ;; (define-key hs-minor-mode-map
      ;;   [?\C-c ?\C-\M-s] 'hs-show-all)


      ;; (global-set-key (kbd "C-c @ @") 'hs-hide-all)
      ;; (global-set-key (kbd "C-c @ @") 'hs-show-all)
      (global-set-key (kbd "C-c @ h") 'hs-hide-block)
      (global-set-key (kbd "C-c @ s") 'hs-show-block)
      (global-set-key (kbd "C-c @ SPC") 'hs-show-block) ; second binding

;;** 30.8 (info "(emacs)Symbol Completion")

      (section "30.8 (emacs)Symbol Completion")

  ;; when you hit `C-TAB', call the command normally bound to `M-TAB'
  (global-set-key
   (kbd "C-TAB") '(lambda ()
                    (interactive)
                    (call-interactively (key-binding (kbd "M-TAB")))))

;;** 30.9 (info "(emacs)Glasses") minor mode

      (section "30.9 (emacs)Glasses minor mode")

      ;; face to be put on capitals of an identifier looked through glasses
      (setq glasses-face 'bold)

      ;; string to be displayed as a visual separator in unreadable
      ;; identifiers
      (setq glasses-separator "")
)

;;* 31 (info "(emacs)Building") Compiling and Testing Programs

(chapter chapter-31-building "31 Compiling and Testing Programs"

      ;; > Is it possible to see a warning, while we are programming, if we
      ;; > did a mistake?
      ;; >
      ;; > There's a CWarn mode for C and C++, but I don't know about similar
      ;; > features for Java. Anyone?

      ;; flymake can compile in the background and colorize lines with
      ;; errors/warnings
      ;; http://flymake.sourceforge.net/
      ;; http://www.emacswiki.org/cgi-bin/wiki/JdeeFlymake

      (autoload 'flymake-mode "flymake" nil t)
      (eval-after-load "flymake"
        '(progn

           ;; Setting up flymake
           (defun activate-flymake ()
             "Activates flymake when real buffer and you have write access"
             (if (and (buffer-file-name) (file-writable-p buffer-file-name))
                 (flymake-mode t)))

           ;; Adding errors to modeline -- With this the error output of othe
           ;; current line will appear right below in the modeline
           (defun my/flymake-show-help ()
             (when (get-char-property (point) 'flymake-overlay)
               (let ((help (get-char-property (point) 'help-echo)))
                 (if help (message "%s" help)))))

           (add-hook 'post-command-hook 'my/flymake-show-help)))


      ;; my build command: `cd /path/to/Makefile && make -f Makefile'

;;** 31.1 Running (info "(emacs)Compilation")s under Emacs

      (section "31.1 Running (emacs)Compilations under Emacs")

      ;; http://www.emacswiki.org/emacs-en/eproject
      ;;
      ;; It allows to define projects, and in each project to define menu
      ;; commands and shortcut keys as you like. For example:
      ;;
      ;; make (f9)               : `-in src make' OR `make'
      ;; clean (C-f9)            : `rm -vf src/emacs-23.* etc/DOC* && make clean' OR `make clean'
      ;; run (f8)                : `src/emacs' OR `./my-program'
      ;; stop (C-f8)             : `-e kill-compilation'
      ;; ---
      ;; configure               : `./configure'
      ;; install                 : `echo root-pass | sudo -S make install'


      ;; You don't need a Makefile to perform simple tasks, because Make knows
      ;; a lot of built in rules out of the box. For example, to compile a
      ;; `.c' source file `foo.c' into a program `foo', all you need is say
      ;; "make -k foo", and Make will do it even without a Makefile.

      ;; invoke a compiler with the same command as in the last invocation of
      ;; `compile'
      (global-set-key (kbd "<f9>") 'recompile)

      ;; scroll the `*compilation*' buffer window to follow output as it
      ;; appears
      (setq compilation-scroll-output t)

      ;; number of lines in a compilation window
      (setq compilation-window-height (* 2 5))

      ;; ;; I also don't like that the compilation window sticks around after
      ;; ;; a successful compile. After all, most of the time, all I care
      ;; ;; about is that the compile completed cleanly. Here's how I make the
      ;; ;; compilation window go away, only if there was no compilation
      ;; ;; errors:
      ;; (setq compilation-finish-function
      ;;       (lambda (buf str)
      ;;         (if (string-match "exited abnormally" str)
      ;;             ;; there were errors
      ;;             (message "Compilation errors, press C-x ` to visit")
      ;;           ;; no errors, make compilation window go away in 0.5 sec
      ;;           (run-at-time 0.5 nil 'delete-windows-on buf)
      ;;           (message "NO COMPILATION ERRORS!"))))


      (GNUEmacs
       (defun cc-goto-first-error( buffer exit-condition )
         (with-current-buffer buffer
           (goto-char (point-min))
           (compilation-next-error 1)
           (beep)))

       (add-to-list 'compilation-finish-functions 'cc-goto-first-error))


      ;; (add-hook 'c-mode-hook
      ;; 	  (lambda ()
      ;; 	    (set (make-local-variable 'compile-command)
      ;; 		 (format "make %s"
      ;; 			 (file-name-sans-extension
      ;; 			  (file-name-nondirectory buffer-file-name))))))
      ;;
      ;; Just set the CC=gcc and CFLAGs="-Wall -O3" environment variables, and
      ;; voila!

      (defvar make-clean-command "make clean all"
        "*Command used by the `make-clean' function.")

      (defun make-clean (&optional arg)
        "Run a make clean."
        (interactive "P")
        (require 'compile) ;; needed for compile-internal
        (if arg
            (setq make-clean-command
                  (read-string "Command: " make-clean-command)))
        (save-some-buffers (not compilation-ask-about-save) nil)
        (compile-internal make-clean-command "No more errors"))

      (global-set-key (kbd "<S-f9>") 'make-clean)

;;** 31.2 (info "(emacs)Compilation Mode")

      (section "31.2 (emacs)Compilation Mode")

      ;; automatically jump to the first error during compilation
      (setq compilation-auto-jump-to-first-error t)

      ;; display the next compiler error message
      (global-set-key (kbd "<f10>") 'next-error)

      ;; display the previous compiler error message
      (global-set-key (kbd "<S-f10>") 'previous-error)

      ;; display the first compiler error message
      (global-set-key (kbd "<C-f10>") 'first-error)

      ;; highlight and parse the whole compilation output as soon as it
      ;; arrives
      (setq compile-auto-highlight t)

;;** 31.4 (info "(emacs)Grep Searching") under Emacs

      (section "31.4 (emacs)Grep Searching under Emacs")

      ;; ignore case distinctions in the default grep command
      ;;(if (my/file-exists-and-executable-p "~/bin/wcgrep")
      (setq grep-command "grep -n -i -e ")

      ;; grep + emacs 22 + cygwin does not follow file links
      ;; try adding "-nH" to your grep options.

      ;; The commands lgrep and rgrep are somehow more user-friendly than the
      ;; `M-x grep' command. The word at point can be captured using the
      ;; command (thing-at-point 'word). So you may try:

      (require 'thingatpt)
      (defun my/rgrep (term)
        "Look for word at point in all files recursively starting from the parent
        directory."
        (interactive
         (list (completing-read "Search Term: " nil nil nil (thing-at-point 'word))))
        (grep-compute-defaults)
        (rgrep term "*.*" "../"))

      ;; run grep via find, with user-specified arguments
      (global-set-key (kbd "C-c 4") 'my/rgrep)

;;** 31.6 Running (info "(emacs)Debuggers") Under Emacs

      (section "31.6 Running (emacs)Debuggers Under Emacs")

      ;; Gdb integration works quite well already
      ;; the only important parameter for gdb
      (setq gdb-many-windows t)

;;** Debugging Lisp programs

      (add-hook 'cl-load-hook
                (lambda ()
                  (add-hook 'edebug-setup-hook
                            (lambda ()
                              ;; edebug specs for cl.el
                              (load-library "cl-specs.el")))))

;;** 31.7 (info "(emacs)Executing Lisp") Expressions

      (section "31.7 (emacs)Executing Lisp Expressions")

      ;; (require 'lisp-mode)

      ;; nuke and reevaluate an elisp buffer
      (autoload 'nuke-and-eval "nukneval" nil t)

      (add-hook 'emacs-lisp-mode-hook 'my/elisp-extra-keys)
      (defun my/elisp-extra-keys ()
        (define-key emacs-lisp-mode-map
          "\C-cc" 'nuke-and-eval))

;;** 31.9 (info "(emacs)Lisp Eval") Expressions

      (section "31.9 (emacs)Lisp Eval Expressions")

      ;; enable the use of the command `eval-expression' without confirmation
      (put 'eval-expression 'disabled nil)

      ;; enhanced eval-expression command
      (when (try-require 'eval-expr)
        (eval-expr-install))

      ;; maximum depth of lists to print in the result of the evaluation
      ;; commands before abbreviating them: no limit
      (setq eval-expression-print-level 20)

      ;; maximum length of lists to print in the result of the evaluation
      ;; commands before abbreviating them: no limit
      (setq eval-expression-print-length 80)

;;** 31.11 Running an (info "(emacs)External Lisp")

      (section "31.11 Running an (emacs)External Lisp")

      ;; SLIME -- Superior Lisp Inferior Mode Extension
      (try-require 'slime-XXX)
      (eval-after-load "slime"
        '(progn

           ;; indentation
           (slime-setup)

           (mapc (lambda (x)
                   (if (file-exists-p (cadr x))
                       (add-to-list 'slime-lisp-implementations
                                    `(,(car x) (,@(cdr x)))
                                    t)))
                 '((openmcl "/Applications/OpenMCL/scripts/openmcl")
                   (clisp "/opt/local/bin/clisp")
                   (clisp "/usr/bin/clisp")
                   (cmucl "/usr/local/cmucl/bin/lisp")
                   (cmucl "/usr/bin/lisp")
                   (sbcl "/usr/local/bin/sbcl")
                   (sbcl "/usr/bin/sbcl")
                   (allegro-express "/usr/local/acl80_express/alisp")))


           (add-hook 'lisp-mode-hook
                     (lambda ()
                       (slime-mode t)))
           (add-hook 'inferior-lisp-mode-hook
                     (lambda ()
                       (inferior-slime-mode t)))

           ;; Gnu CLISP - Inferior Lisp Mode & ILISP (switches for ANSI & no
           ;; banner)
           ;; TODO Have a look at SBCL
           (defvar clisp-dir
             (cond (running-ms-windows
                    "e:/vmware-home/bin/win32/clisp-2.31/full/")
                   (t
                    "/usr/bin")))

           (defvar clisp-exe
             (cond (running-ms-windows
                    (concat clisp-dir "lisp.exe"))
                   (t
                    (concat clisp-dir "/" "clisp"))))

           ;; optionally, specify the Lisp program you are using. Default is
           ;; "lisp". include the full linking set with `-K full'
           (setq inferior-lisp-program
                 (cond (running-ms-windows
                        (concat clisp-exe
                                " -B " clisp-dir
                                " -M " clisp-dir "lispinit.mem"
                                " -ansi -q"))
                       (t
                        (concat clisp-exe
                                " -B " clisp-dir
                                " -ansi -q"))))  ;; "clisp -K full"

           ;; connect automatically to my Lisp when opening a Lisp file
           (defun cliki:start-slime ()
             (unless (slime-connected-p)
               (save-excursion (slime))))
           (add-hook 'slime-mode-hook 'cliki:start-slime)

           ;; automatically show documentation for code near the point
           (add-hook 'slime-mode-hook
                     (lambda ()
                       (slime-autodoc-mode t)))

           ;;   ;; GNU CLISP - http://clisp.cons.org/
           ;;   (defun clisp-start ()
           ;;     (interactive)
           ;;     (shell-command (concat "c:/bin/clisp-2.32/full/lisp.exe "
           ;;                            "-B c:/bin/clisp-2.32/full/ "
           ;;                            "-M c:/bin/clisp-2.32/full/lispinit.mem "
           ;;                            "-i c:/usr/home/.slime.lisp "
           ;;                            "-ansi -q&"))))


           ;; Functions and key bindings for getting Emacs to interact with
           ;; GCL. Thomas R. Ioerger, Dept of Computer Science, Texas A&M
           ;; University
           ;; see http://www.cs.tamu.edu/faculty/ioerger/emacs-gcl.html for
           ;; more details

           (global-set-key "\C-t" '(make-keymap))

           (defun run-gcl ()
             (interactive)
             (split-window)
             (other-window 1)
             (inferior-lisp "gcl"))

           (defun gcl-debug-quit ()
             (interactive)
             (comint-send-string "*inferior-lisp*" ":q\C-M"))

           (defun gcl-quit ()
             (interactive)
             (comint-send-string "*inferior-lisp*" "(bye)\C-M"))

           (defun gcl-eval-buffer ()
             (interactive)
             (set-mark 0)
             (goto-char (point-max))
             (lisp-eval-region 1 (point))
             (exchange-point-and-mark))

           (global-set-key "\C-tl" 'run-gcl)
           (global-set-key "\C-te" 'lisp-eval-defun)
           (global-set-key "\C-tw" 'switch-to-lisp) ; split screen!
           (global-set-key "\C-tq" 'gcl-debug-quit)
           (global-set-key "\C-tb" 'gcl-eval-buffer)
           (global-set-key "\C-tx" 'gcl-quit)

           ;; commands (after prefix of control-t)
           ;; l = start lisp
           ;; e = eval current expression
           ;; w = switch to lisp buffer
           ;; q = quit from debugger back to top-level
           ;; b = eval buffer
           ;; x = kill lisp process

           ))

)

(when (locate-library "diminish")
  (autoload 'diminish "diminish" nil t))


;;;_ * eldoc

(add-hook 'emacs-lisp-mode-hook (lambda () (require 'edebug)))

;;;_ * eldoc

;; (eval-after-load "eldoc"
;;   '(diminish 'eldoc-mode))

;;;_ * elint

(defun elint-current-buffer ()
  (interactive)
  (elint-initialize)
  (elint-current-buffer))

(eval-after-load "elint"
  '(progn
     (add-to-list 'elint-standard-variables 'current-prefix-arg)
     (add-to-list 'elint-standard-variables 'command-line-args-left)
     (add-to-list 'elint-standard-variables 'buffer-file-coding-system)
     (add-to-list 'elint-standard-variables 'emacs-major-version)
     (add-to-list 'elint-standard-variables 'window-system)))

;;;_ * emacs-lisp

(add-hook 'emacs-lisp-mode-hook 'turn-on-auto-fill)

;;; Alternative 1
;; (font-lock-add-keywords 'emacs-lisp-mode
;;                         '(("(\\(lambda\\)\\>"
;;                            (0 (ignore
;;                                (compose-region (match-beginning 1)
;;                                                (match-end 1) ?))))))

      ;;; Alternative 2
      ;; (defun pretty-lambdas ()
      ;;   (font-lock-add-keywords nil
      ;;    `(("(?\\(lambda\\>\\)"
      ;;           (0 (progn (compose-region (match-beginning 1) (match-end 1)
      ;;                                     ,(make-char 'greek-iso8859-7 107))
      ;;                     nil))))))
      ;; ;; (add-hook 'emacs-lisp-mode-hook 'pretty-lambdas)

;; (defun elisp-indent-or-complete (&optional arg)
;;   (interactive "p")
;;   (call-interactively 'lisp-indent-line)
;;   (unless (or (looking-back "^\\s-*")
;; 	      (bolp)
;; 	      (not (looking-back "[-A-Za-z0-9_*+/=<>!?]+")))
;;     (call-interactively 'lisp-complete-symbol)))
;;
;; (eval-after-load "lisp-mode"
;;   '(define-key emacs-lisp-mode-map
;;      [TAB] 'elisp-indent-or-complete))

;;;_  + highlight-parentheses

(autoload 'highlight-parentheses-mode "highlight-parentheses")

(add-hook 'emacs-lisp-mode-hook 'highlight-parentheses-mode)

;; (eval-after-load "highlight-parentheses"
;;   '(diminish 'highlight-parentheses-mode))

;;;_  + paredit

(autoload 'paredit-mode "paredit"
  "Minor mode for pseudo-structurally editing Lisp code." t)
(autoload 'enable-paredit-mode "paredit"
  "Minor mode for pseudo-structurally editing Lisp code." t)

;;;;;;;;;;;;;;(add-hook 'emacs-lisp-mode-hook 'enable-paredit-mode)

;; (eval-after-load "paredit"
;;   '(diminish 'paredit-mode))

;;;_  + redshank

;; XXX conflict about `C-x C-r'

(when (locate-library "redshank")
    (autoload 'redshank-mode "redshank"
      "Minor mode for restructuring Lisp code (i.e., refactoring)." t)

    (add-hook 'emacs-lisp-mode-hook #'(lambda () (redshank-mode 1)))

    ;; (eval-after-load "redshank"
    ;;   '(diminish 'redshank-mode))
)

;;; lang-emacs-lisp.el ends here

;;* 32 (info "(emacs)Maintaining") Programs

(chapter chapter-32-maintaining "32 Maintaining Programs"

;;** 32.1 (info "(emacs)Version Control")

      (section "32.1 (emacs)Version Control")

      ;; version control systems that interact with Emacs in a generic way

      (try-require 'vc) ;; for defining function `vc-switches' (XXX autoload?)

;;*** 32.1.2 (info "(emacs)VC Mode Line")

        ;; http://www.emacswiki.org/emacs/VcIcon
        (defun vc-icon ()
          "Display a colored icon indicating the vc status of the current
        file."
          (let ((icon (if (vc-workfile-unchanged-p (buffer-file-name))
                          (concat my/site-lisp-directory "Pictures/NormalIcon.png")
                        (concat my/site-lisp-directory "Pictures/ModifiedIcon.png")))
                (bg-colour (face-attribute 'mode-line :background)))
            (propertize
             "  "
             'display (find-image `((:type png ;; jpeg
                                     :file ,icon
                                     :ascent center
                                     :background ,bg-colour))))))

        ;; ;; This does not work. Why?
        ;; (setq-default mode-line-format
        ;;               (append
        ;;                '(vc-mode (:eval (vc-icon)))
        ;;                (default-value 'mode-line-format)))

        (setq-default mode-line-format
                      (push '(vc-mode (:eval (vc-icon))) mode-line-format))

;;*** 32.1.4 (info "(emacs)Log Buffer")

        ;; (defun my/vc-log-mode-setup ()
        ;;   (setq ispell-local-dictionary "en_US")
        ;;   ;; check if `ispell-program-name' seems correct
        ;;   (when (executable-find ispell-program-name)
        ;;     (flyspell-mode)))
        ;;
        ;; (add-hook 'vc-log-mode-hook 'my/vc-log-mode-setup)

;;*** 32.1.5 (info "(emacs)Old Revisions")

        ;; switches for diff under VC
        (setq vc-diff-switches diff-switches)

;;*** 32.1.6 (info "(emacs)Secondary VC Commands")

        ;; prompt for initial comment when a file is registered
        (setq vc-initial-comment t)

;;*** 32.1.7 (info "(emacs)VC Directory Mode")

        (defun my/vc-jump ()
          "Jump to VC status buffer."
          (interactive)
          (let* ((fname (buffer-file-name))
                 (dname (if fname
                            (if (file-directory-p fname)
                                fname
                              (file-name-directory fname))
                          default-directory)))
            (message "VC status for directory: %s" dname)
            (vc-dir dname)))

        ;; vc status without asking for a directory
        (global-set-key (kbd "<C-f9>") 'my/vc-jump)


        ;; hide up-to-date and unregistered files
        (add-hook  'vc-dir-mode-hook
                   (lambda nil
                     (define-key vc-dir-mode-map
                       "x" 'my/vc-dir-hide-up-to-date)
                     (define-key vc-dir-mode-map
                       "E" 'vc-ediff)))

        (defun my/vc-dir-hide-up-to-date ()
          (interactive)
          (vc-dir-hide-up-to-date)
          (vc-dir-hide-unregistered))

        (defun vc-dir-hide-unregistered ()
          "Hide unregistered items from display."
          (interactive)
          (let ((crt (ewoc-nth vc-ewoc -1))
                (first (ewoc-nth vc-ewoc 0)))
            ;; Go over from the last item to the first and remove the
            ;; unregistered files and directories with no child files.
            (while (not (eq crt first))
              (let* ((data (ewoc-data crt))
                     (dir (vc-dir-fileinfo->directory data))
                     (next (ewoc-next vc-ewoc crt))
                     (prev (ewoc-prev vc-ewoc crt))
                     ;; ewoc-delete does not work without this...
                     (inhibit-read-only t))
                (when (or
                       ;; Remove directories with no child files.
                       (and dir
                            (or
                             ;; Nothing follows this directory.
                             (not next)
                             ;; Next item is a directory.
                             (vc-dir-fileinfo->directory (ewoc-data next))))
                       ;; Remove files in the unregistered state.
                       (eq (vc-dir-fileinfo->state data) 'unregistered))
                  (ewoc-delete vc-ewoc crt))
                (setq crt prev)))))

;;*** 32.1.12 (info "(emacs)Customizing VC")

        ;; display run messages from back-end commands
        (setq vc-command-messages t) ;; default?

        ;; http://www.emacswiki.org/emacs/VcTopDirectory
        ;; For git
        (defadvice vc-dir-prepare-status-buffer (before my-vcs-goto-top-directory activate compile)
          (let* ((backend (ad-get-arg 2))
                 (vcs-dir (ad-get-arg 1))
                 (vcs-top-dir (vc-call-backend backend 'responsible-p vcs-dir)))
            (when (stringp vcs-top-dir)
              (ad-set-arg 1 vcs-top-dir))))

        (GNUEmacs
          (defun my/ediff-revision (file rev1 &optional rev2)
            "Run Ediff by comparing 'master' against the 'current'."
            (find-file file)
            (if (and (buffer-modified-p)
                     (y-or-n-p (format "Buffer %s is modified. Save buffer? "
                                       (buffer-name))))
                (save-buffer (current-buffer)))
            (ediff-load-version-control)
            (funcall
             (intern (format "ediff-%S-internal" ediff-version-control-package))
             rev1 rev2 nil))

          (defun my/vc-diff (&optional arg)
            (interactive "P")
            (call-interactively
             (cond (arg (lambda nil (interactive) (vc-diff nil)))
                   (t (lambda nil (interactive)
                        (my/ediff-revision (buffer-file-name)
                                           (read-string "revision? "
                                                        "HEAD" nil "HEAD")
                                           ""))))))

          (define-key vc-prefix-map "=" 'my/vc-diff)
)

;;** 32.2 (info "(emacs)Change Log")

      (section "32.2 (emacs)Change Logs")

      ;; don't make a new entry, when the last entry was made by you and on
      ;; the same date
      (setq add-log-always-start-new-record nil)

      ;; adds the file's version number to the change log entry
      (setq change-log-version-info-enabled t)

      (eval-after-load "add-log"
        '(add-hook 'change-log-mode-hook
                   (add-to-list
                    'change-log-font-lock-keywords
                    '("^[0-9-]+:? +\\|^\\(Sun\\|Mon\\|Tue\\|Wed\\|Thu\\|Fri\\|Sat\\) [A-z][a-z][a-z] [0-9:+ ]+"
                      (0 'change-log-date-face)
                      ("\\([^<(]+?\\)[   ]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]" nil nil
                       (1 'change-log-name)
                       (2 'change-log-email))))))

;;** 32.3 (info "(emacs)Tags")

      (section "32.3 (emacs)Tags Tables")

      (eval-after-load "etags"
        ;; tags enhancements
        '(try-require 'sure-tags-XXX))

      ;; list of file names of tags tables to search
      (setq tags-table-list
            '(
              "~/TAGS"
              "/usr/local/lib/emacs/src/TAGS"
              ;;         "/usr/share/texmf-texlive/tex/latex/TAGS"
              ))

      (defun find-next-tag ()
        (interactive)
        (find-tag nil t))

      (eval-after-load "etags"

        ;; select from multiple tags
        '(when (try-require 'etags-select-XXX)

          ;; do a `find-tag-at-point', and display all exact matches
          (global-set-key (kbd "M-?") 'etags-select-find-tag-at-point)))

      ;; find the definition of the Emacs Lisp function or variable near point
      (GNUEmacs
       (find-function-setup-keys))

;;** 32.4 (info "(emacs)EDE")

      (section "32.4 Emacs Development Environment")

(unless (string< emacs-version "23.2")
      ;; ;; enable global EDE (project management) features
      ;; (global-ede-mode 1)

      ;; enable parser features (Semantic mode)
      (semantic-mode 1)

      ;; turn Semantic DB mode on (Semantic parsers store the results of
      ;; parsing source code in a database file)
      (global-semanticdb-minor-mode 1)

      ;; the idle scheduler with automatically reparse buffers in idle time
      (global-semantic-idle-scheduler-mode 1) ;; [minimum-features]

      ;; display a summary of the symbol at point in the echo area (~ ElDoc)
      (global-semantic-idle-summary-mode 1) ;; [code-helpers]

      ;; display a tooltip with a list of possible completions near the cursor
      (global-semantic-idle-completions-mode 1) ;; [gaudy-code-helpers]

      ;; turn Semantic MRU Bookmarks on (keep track of the Most Recently Used
      ;; tags)
      (global-semantic-mru-bookmark-mode 1)

      ;; enable Semantic-Stickyfunc mode (display a header line that shows the
      ;; declaration line of the function or tag)
      (global-semantic-stickyfunc-mode 1) ;; [gaudy-code-helpers]

      ;; enable Semantic-Highlight-Func mode
      (global-semantic-highlight-func-mode 1) ;; [excessive-code-helpers]

      ;; turn on all active decorations
      (global-semantic-decoration-mode 1) ;; [gaudy-code-helpers]

      ;; (global-semantic-tag-folding-mode 1) ;; does not exist!

      ;; smart completion, and display of information for tags & classes
      (require 'semantic/ia)

      (require 'semantic/db)

      ;; enable Semantic DB mode (Semantic parsers store results in a
      ;; database, which can be saved for future Emacs sessions)
      (global-semanticdb-minor-mode 1)

      (defun my-cedet-hook ()
        ;; automatically complete whatever symbol you are typing
        (local-set-key "\C-c?" 'semantic-ia-complete-symbol) ;; better: `M-/'

        ;; jump to the definition of the symbol under cursor
        (local-set-key "\C-cj" 'semantic-ia-fast-jump) ;; where a symbol is declared

        ;; show the documentation of the symbol under cursor
        (local-set-key "\C-cq" 'semantic-ia-show-doc) ;; show javadoc of the right method

        ;; show a summary about the symbol under cursor
        (local-set-key "\C-cs" 'semantic-ia-show-summary)


        ;; show possible public member functions or data members (when at `.'
        ;; or `->' after an object name)
        (local-set-key "\C-c>" 'semantic-complete-analyze-inline)

        ;; toggle between the implementation and a prototype of symbol under
        ;; cursor
        (local-set-key "\C-cp" 'semantic-analyze-proto-impl-toggle)

        ;; visit the header file under cursor
        (local-set-key "\C-c=" 'semantic-decoration-include-visit)


        ;; unfold the block under cursor
        (local-set-key "\C-c+" 'semantic-tag-folding-show-block)

        ;; fold the block under cursor
        (local-set-key "\C-c-" 'semantic-tag-folding-fold-block)

        ;; unfold all
        (local-set-key "\C-c\C-c+" 'semantic-tag-folding-show-all)

        ;; fold all
        (local-set-key "\C-c\C-c-" 'semantic-tag-folding-fold-all))

      (add-hook 'c-mode-common-hook 'my-cedet-hook)
      (add-hook 'lisp-mode-hook 'my-cedet-hook)
      (add-hook 'emacs-lisp-mode-hook 'my-cedet-hook)

      (defun my-c-mode-cedet-hook ()
        "Completion on `.' or `->'."
       (local-set-key "." 'semantic-complete-self-insert)
       (local-set-key ">" 'semantic-complete-self-insert))
      (add-hook 'c-mode-common-hook 'my-c-mode-cedet-hook)

      ;; Hooks, specific for semantic
      (defun my-semantic-hook ()
        (imenu-add-to-menubar "TAGS"))
      (add-hook 'semantic-init-hooks 'my-semantic-hook)
)

      ;; Emacs Code Browser
      (custom-set-variables '(ecb-options-version "2.40"))
      (when (try-require 'ecb-autoloads-XXX)

        ;; trick for starting ECB 2.40 (with CEDET merged in Emacs since 23.2)
        (require 'semantic/analyze)
        (provide 'semantic-analyze)
        (provide 'semantic-ctxt)
        (provide 'semanticdb)
        (provide 'semanticdb-find)
        (provide 'semanticdb-mode)
        (provide 'semantic-load)
        (setq stack-trace-on-error t)

        ;; don't show tip of the day at start time of ECB
        (setq ecb-tip-of-the-day nil)

        ;; toggle activation of ECB (between `ecb-activate' and
        ;; `ecb-deactivate')
        (global-set-key (kbd "C-c e") 'ecb-minor-mode)

        ;; (global-set-key (kbd "<M-left>") 'ecb-goto-window-methods)
        ;; (global-set-key (kbd "<M-right>") 'ecb-goto-window-edit1)
        )

       (when (try-require 'eassist)

         (defun my/c-mode-cedet-hook ()
           (local-set-key "\C-ct" 'eassist-switch-h-cpp)
           (local-set-key "\C-xt" 'eassist-switch-h-cpp)
           (local-set-key "\C-ce" 'eassist-list-methods)
           (local-set-key "\C-c\C-r" 'semantic-symref))
         (add-hook 'c-mode-common-hook 'my/c-mode-cedet-hook))

)

;;* 33 (info "(emacs)Abbrevs")

(chapter chapter-33-abbrevs "33 Abbrevs"

      ;; See (info "(autotype)") as well

;;** 33.3 Controlling (info "(emacs)Expanding Abbrevs")

      (section "33.3 Controlling Expanding Abbrevs")

      ;; Yet Another Snippet extension for Emacs
      (GNUEmacs
       ;; you should use the "standard" package (NOT `yasnippet-bundle'!)
       (when (try-require 'yas-jit)

         ;; root directories that store the snippets
         (setq yas/root-directory nil)
         (let ((my-snippets
                my/yasnippet-directory)
               (org-snippets
                (concat "~/src/" "yasnippet-org-mode"))
               (latex-snippets
                (concat "~/src/" "yasnippets-latex"))
               (local-snippets
                my/local-yasnippet-directory))
           (when (file-directory-p local-snippets)
             (add-to-list 'yas/root-directory local-snippets))
           (when (file-directory-p latex-snippets)
             (add-to-list 'yas/root-directory latex-snippets))
           (when (file-directory-p org-snippets)
             (add-to-list 'yas/root-directory org-snippets))
           ;; the first element is always the user-created snippets directory
           (when (file-directory-p my-snippets)
             (add-to-list 'yas/root-directory my-snippets)))

         ;; (mapc 'yas/jit-compile-dir yas/root-directory)

         ;; load the snippets
         ;; (mapc 'yas/load-directory yas/root-directory)
         (yas/jit-load)

         ;; enable the YASnippet menu and tab-trigger expansion in *all*
         ;; buffers
         (yas/global-mode)

         ;; text that will be used in menu to represent the trigger
         (setq yas/trigger-symbol " <tab>")))

;;** 33.7 (info "(emacs)Dabbrev Customization")

      (section "33.7 Dabbrev Customization")

      ;; preserve case when expanding the abbreviation
      (setq dabbrev-case-replace nil)

      (global-set-key (kbd "M-/") 'hippie-expand)

      ;; expand text trying various ways to find its expansion
      (when (try-require 'hippie-exp)

        ;; list of expansion functions tried (in order) by `hippie-expand'
        ;; (completion strategy)
        (setq hippie-expand-try-functions-list
              '(try-expand-dabbrev ;; current buffer
                try-expand-dabbrev-visible ;; visible (parts of all) buffers
                try-expand-dabbrev-all-buffers ;; all opened buffers
                try-expand-dabbrev-from-kill ;; kill ring
                try-complete-file-name-partially ;; file names
                try-complete-file-name
                try-expand-all-abbrevs ;; abbreviations
                try-expand-list
                try-expand-line
                try-complete-lisp-symbol-partially
                try-complete-lisp-symbol
                try-expand-whole-kill))

        (setq hippie-expand-try-functions-list
              '(
                yas/hippie-try-expand ;; integrate YASnippet with `hippie-expand'
                try-complete-file-name-partially
                try-complete-file-name
                try-expand-all-abbrevs
                try-expand-dabbrev
                try-expand-dabbrev-all-buffers
                try-expand-dabbrev-from-kill))

        ;; expand-function
        (defun my/hippie-expand (arg)
          ;; called with a positive prefix `P', it jumps directly to the
          ;; `P'-th `try-function'
          (interactive "P")
          ;; `hippie-expand' does not have a customization-feature (like
          ;; `dabbrev-expand') to search case-sensitive for completions. So we
          ;; must set `case-fold-search' temporarily to nil!
          (let ((old-case-fold-search case-fold-search))
            (setq case-fold-search nil)
            (hippie-expand arg)
            (setq case-fold-search old-case-fold-search))))

;; Auto Completion
(when (try-require 'auto-complete-config)

  ;; avoid flyspell processes when auto completion is being started
  (ac-flyspell-workaround)

  ;; optimize sources to use
  (ac-config-default)

  ;; change default sources
  (setq-default ac-sources
                ;; buffers whom major-mode is same to of a current buffer
                '(ac-source-words-in-same-mode-buffers))

  ;; change sources for Emacs Lisp mode
  (add-hook 'emacs-lisp-mode-hook
            (lambda ()
              (setq ac-sources
                    '(ac-source-words-in-same-mode-buffers
                      ac-source-words-in-buffer
                      ac-source-symbols))))

  ;; enable auto-complete-mode automatically for Sword mode
  (add-to-list 'ac-modes 'sword-mode)

  ;; ;; change sources for Sword mode
  ;; (add-hook 'sword-mode-hook
  ;;           (lambda ()
  ;;             (setq ac-sources
  ;;                   '(
  ;;                     ;; ac-source-words-in-same-mode-buffers
  ;;                     ac-source-words-in-buffer))))

  (setq ac-delay 0.01)
  (setq ac-auto-show-menu 0.01)

  ;; start auto-completion at current point
  (define-key ac-mode-map (kbd "M-TAB") 'auto-complete)

  ;; try expand
  (define-key ac-complete-mode-map [tab] 'ac-expand)

)

      ;; predictive abbreviation expansion
      (when (try-require 'pabbrev-XXX)

        ;; don't print messages while scavenging on idle timer
        (setq pabbrev-idle-timer-verbose nil)

        ;; TAB completion with continual, as-you-type feedback
        (global-pabbrev-mode))

)

(autoload 'sword-mode "sword-mode"
  "Major mode for SWORD files" t)

(add-to-list 'auto-mode-alist '("\\.swd\\'" . sword-mode))

;;* 37 (info "(emacs)Dired"), the Directory Editor

(chapter chapter-37-dired "37 Dired, the Directory Editor"

      ;; FIXME Some people report sorting problems in Org agenda view because
      ;; of this package!
      ;; provide the same facility of `ls --color' inside Emacs
      (when (locate-library "dircolors")
        (autoload 'dircolors "dircolors" nil t)
        (add-hook 'completion-list-mode-hook 'dircolors)
        (add-hook 'buffer-menu-mode-hook 'dircolors))

      ;; `ls' emulation in Emacs Lisp (on MS Windows)
      (eval-after-load "ls-lisp"
        '(progn

           ;; disable the case sensitive sort of file names
           (setq ls-lisp-ignore-case t)

           ;; sort directories first (following Microsoft Windows Explorer)
           (setq ls-lisp-dirs-first t)

           ;; use ISO 8601 dates (on MS-Windows)
           (setq ls-lisp-format-time-list
                 '("%Y-%m-%d %H:%M"
                   "%Y-%m-%d %H:%M"))

           ;; use localized date/time format
           (setq ls-lisp-use-localized-time-format t)))

      ;; directory-browsing commands
      ;; (when (try-require 'dired)
      (eval-after-load "dired"
        '(progn

        (section "37.1 (emacs)Dired Enter")

        ;; switches passed to `ls' for Dired
        (setq dired-listing-switches "-alpF") ;; --time-style=long-iso

        (section "37.3 (emacs)Dired Deletion")

        ;; recursive deletes allowed, after asking for each directory at top
        ;; level
        (setq dired-recursive-deletes 'top)

;;** (info "(emacs)Dired Visiting")

        (section "37.5 (emacs)Dired Visiting")

        ;; reuse Dired buffers, by running the command
        ;; `dired-find-alternate-file' (bound to `a') on a directory
        (put 'dired-find-alternate-file 'disabled nil)

        ;; reuse the current Dired directory buffer to visit another directory
        ;; (limit Dired to 1 single buffer)
        (when (try-require 'dired-single)
          (define-key dired-mode-map
            [return] 'joc-dired-single-buffer)
          (define-key dired-mode-map
            [mouse-1] 'joc-dired-single-buffer-mouse)
          (define-key dired-mode-map
            "^"
            (function
             (lambda nil (interactive) (joc-dired-single-buffer ".."))))
          (define-key dired-mode-map
            (kbd "C-x C-j")
            (function
             (lambda nil (interactive) (joc-dired-single-buffer "..")))))

        ;; On top of the traditional ways, there's also an add-on called
        ;; Extview which opens files using outside programs, such as XPDF,
        ;; based on their extension. It does this both from Dired and with
        ;; `find-file'. One advantage is that using the traditional ! switch
        ;; with Dired locks up Emacs until you close the other program.
        ;; Extview does not and leaves Emacs free for continued used.

        ;; >> how to associate external programs to known file types
        ;; >> in Dired. For example, associating
        ;; >
        ;; > Hi, i use `extview.el', it's work fine.
        ;; > It reads in a `.mailcap' file.

        ;; If you need to open a file in Emacs that has an extension that
        ;; Extview will open in another viewer, like HTML, you use
        ;; `find-file-literally' to open it in Emacs.
        (when (try-require 'extview-XXX)
          (push '("\\.org$" . nil) extview-application-associations))

        ;; See news "Opening html-File in Dired with w3m" for extra info
        (when (executable-find "w3m")
          ;; add a binding "w" -> `dired-find-w3m' to Dired
          (defun dired-find-w3m () (interactive)
            "In Dired, visit (with find-w3m) the file named on this line."
            (w3m-find-file (file-name-sans-versions (dired-get-filename) t)))

          ;; FIXME This steals dired-copy-filename-as-kill
          (define-key dired-mode-map
            "w" 'dired-find-w3m))

      (defun my/browse-dir ()
        "Open the current directory in your OS's file manager."
        (interactive)
        (let ((dir-as-string
               (file-name-as-directory (expand-file-name ".")))
              (file-manager
               (cond (running-ms-windows "explorer")
                     (t "/usr/lib/kde4/bin/dolphin"))))
          ;; `nautilus --no-desktop', `gnome-open'
          ;; or `xdg-open' (in `xdg-utils')
          (start-process "browse" nil file-manager dir-as-string)))

      (defun dired-open-externally ()
        "Open the current directory in your OS's file manager (see `~/.mailcap')."
        (interactive)
        (let ((fileobject (dired-get-file-for-visit))
              (file-manager
               (cond (running-ms-windows "explorer")
                     (t "/usr/lib/kde4/bin/dolphin"))))
          (start-process "dired-external" nil file-manager fileobject)
          (message "Opening file %s" fileobject)))

      (define-key dired-mode-map
        (kbd "e") 'dired-open-externally)

      (defun open-in-desktop ()
        "Open the current file's folder in desktop."
        (interactive)
        (cond
         (running-ms-windows (w32-shell-execute "explore" "."))
         (t (shell-command "open ."))))


      (defun dired-open-file (arg)
        "Abuse org-open-file to open a file in Dired."
        (interactive "P")
        (require 'org)
        (if arg
            (org-open-file (dired-get-filename)
                           (equal arg '(16)))
          (dired-advertised-find-file)))

      (eval-after-load "dired"
      '(progn
        (defun w32-dired-open-explorer (arg)
          "Open a file in Dired mode by explorer.exe."
          (interactive "P")
          (let ((file-name (dired-get-filename)))
            (if arg
                (setq file-name (file-name-directory file-name)))
            (w32-shell-execute "open" file-name)))

        ;; bind it to M-RET in dired mode
        (define-key dired-mode-map
          (kbd "<M-return>") 'w32-dired-open-explorer)))

        ;; open files using Windows associations
        (GNUEmacs
         (when running-ms-windows
           (add-hook 'dired-mode-hook 'my/dired-mode-hook)

           (defun my/dired-mode-hook ()
             "Hook run when entering Dired mode."
             (define-key dired-mode-map
               (kbd "X") 'w32-dired-open-file))

           (defun w32-dired-open-file (&optional arg)
             "In Dired, open the file or directory name you press on."
             (interactive "P")
             (mapcar #'(lambda (file)
                         (w32-shell-execute
                          "open" (convert-standard-filename file)))
                     (dired-get-marked-files nil arg)))))

        (section "37.7 (emacs)Operating on Files")

        ;; try to guess a default target directory
        (setq dired-dwim-target t)

        ;; copy recursively without asking
        (setq dired-recursive-copies 'always)

;;** (info "(emacs)Dired Updating")

        (section "37.15 (emacs)Dired Updating")

        ;; Check this out as well:
        ;;     http://www.emacswiki.org/emacs/DiredSortMenu

        ;; press `s' then `s', `x', `t', `n' or `d' to sort by Size,
        ;; eXtension, Time, Name or name grouping Dirs
        (try-require 'dired-sort-map)

;;** 37.16 (info "(emacs)Dired and Find")

      (section "37.16 (emacs)Dired and Find")

      ;; For searches in Dired, see `dired-do-search' (`A').
      ;; Search through all marked files for a match for regexp.
      ;; Stops when a match is found.
      ;; To continue searching for next match, use command `M-,'.

      ;; TODO Make it case insensitive!
      ;; ;; quicker to collate the matches and then use `xargs' to run the
      ;; ;; command
      ;; (setq find-ls-option '("-print0 | xargs -0 ls -ld" . "-ld"))

      ;; ignore `.svn' and `CVS' directories
      (setq grep-find-command
            (concat
             "find . \\( -path '*/.svn' -o -path '*/CVS' \\) -prune -o -type f "
             "-print0 | "
             "xargs -0 -e grep -i -n -e "))

      ;; search for files with names matching a wild card pattern and Dired
      ;; the output
      (global-set-key (kbd "C-c 1") 'find-name-dired)

      ;; search for files with contents matching a wild card pattern and Dired
      ;; the output
      (global-set-key (kbd "C-c 2") 'find-grep-dired)

      ;; run grep via find, with user-specified arguments
      (global-set-key (kbd "C-c 3") 'grep-find)

;;** 37.17 (info "(emacs)Wdired")

      (section "37.17 Editing the (emacs)Wdired Buffer")

      ;; put a Dired buffer in a mode in which filenames are editable
      (eval-after-load "wdired"

        ;; permissions bits of the files are editable
        '(setq wdired-allow-to-change-permissions t))

;;** 37.18 (info "(emacs)Image-Dired")

      (eval-after-load "image-dired"
        '(progn

           (setq image-dired-show-all-from-dirm-dir-max-files 100)
           (setq image-dired-thumb-margin 4)
           (setq image-dired-thumb-relief 0)))

        ))

;;** Dired Extra

        (section "(dired-x)Top")

        ;; load `dired-x.el' when Dired is first invoked (for example, when
        ;; you first type `C-x d')
        (add-hook 'dired-load-hook
                  (lambda ()
                    (load "dired-x")))

;;** Dired+

        (section "Dired+")

        ;; extensions to Dired (provides fancy highlighting, etc.)
        (add-hook 'dired-load-hook
                  (lambda ()
                    (try-require 'dired+)))

)

      ;; (add-hook 'dired-load-hook
      ;;           (lambda ()
      ;;             (load "dired-column-widths.el")))

;;* Proced

;; current sort scheme for proced listing
(setq-default proced-sort 'start)

;; display of Proced buffer as process tree
(setq-default proced-tree-flag t)

;; Start proced in a similar manner to Dired
(global-set-key (kbd "C-x p") 'proced)

;;* 38 The (info "(emacs)Calendar/Diary")

(chapter chapter-38-calendar-diary "38 The Calendar and the Diary"

      ;; TODO All now being done within Org mode...

;;** 38.1 (info "(emacs)Calendar Motion")

      (section "38.1 (emacs)Calendar Motion")

      ;; years must be written in full
      (setq abbreviated-calendar-year nil)
      (setq diary-abbreviated-year-flag nil)

      ;; ;; interpret the date 1/2/1990 as February 1, 1990
      ;; (setq european-calendar-style t)  ; obsolete!

      ;; set the style of calendar and diary dates to ISO
      (setq calendar-date-style 'iso)

      ;; week in the calendar begins on Monday
      (setq calendar-week-start-day 1)

      ;; mark all visible dates that have diary entries
      (setq mark-diary-entries-in-calendar t)
      ;; (add-hook 'initial-calendar-window-hook 'mark-diary-entries)

      ;; marks the current date, by changing its face
      (add-hook 'today-visible-calendar-hook 'calendar-mark-today)

      ;; bind calendar to `C-c c'
      (global-set-key (kbd "C-c c") 'calendar)

;;** 38.2 (info "(emacs)Scroll Calendar")

      (section "38.2 (emacs)Scroll Calendar")

      ;; fix foolish calendar-mode scrolling
      (add-hook 'calendar-load-hook
                (lambda ()
                  (setq mark-holidays-in-calendar t)
                  (define-key calendar-mode-map
                    [(>)] 'scroll-calendar-left)
                  (define-key calendar-mode-map
                    [(<)] 'scroll-calendar-right)))

;;** 38.7 Times of (info "(emacs)Sunrise/Sunset")

      (section "38.7 Times of (emacs)Sunrise/Sunset")

      ;; calendar location
      (setq calendar-latitude [50 64 north])
      (setq calendar-longitude [3 05 east])
      (setq calendar-location-name "Lille, FR")

      (defun diary-sunrise ()
        (let ((dss (diary-sunrise-sunset)))
          (with-temp-buffer
            (insert dss)
            (goto-char (point-min))
            (search-forward ",")
            (buffer-substring (point-min) (match-beginning 0)))))

      (defun diary-sunset ()
        (let ((dss (diary-sunrise-sunset))
              start end)
          (with-temp-buffer
            (insert dss)
            (goto-char (point-min))
            (search-forward ", ")
            (setq start (match-end 0))
            (search-forward " at")
            (setq end (match-beginning 0))
            (goto-char start)
            (capitalize-word 1)
            (buffer-substring start end))))

;;** 38.11 (info "(emacs)Appointments")

      (section "38.11 (emacs)Appointments")

      ;; enable appointment notification, several minutes beforehand
      (add-hook 'diary-hook 'appt-make-list)

;;** 38.15 (info "(emacs)Advanced Calendar/Diary Usage")

      (section "38.15 (emacs)Advanced Calendar/Diary Usage")

      ;; ;; list of notable days
      ;; (setq calendar-holidays nil)

      ;; get rid of some holidays
      (setq holiday-bahai-holidays nil) ;; Baha'i holidays
      (setq holiday-general-holidays nil);; too U.S.-centric holidays
      (setq holiday-hebrew-holidays nil) ;; religious holidays
      (setq holiday-islamic-holidays nil) ;; religious holidays
      (setq holiday-oriental-holidays nil) ;; Oriental holidays
      (setq holiday-solar-holidays nil)

      ;; add some Belgian holidays
      (setq holiday-local-holidays
            '(
              (holiday-fixed 01 01 "New Year's Day")
              (holiday-fixed 02 14 "Valentine's Day")
              (holiday-fixed 05 01 "Labor Day")
              (holiday-fixed 07 21 "Independence Day")
              (holiday-fixed 08 15 "Assumption")
              (holiday-fixed 11 01 "Toussaint")
              (holiday-fixed 11 11 "Armistice 1918")

              ;; holidays with variable dates
              (holiday-float 5 0 2 "Mother's Day")
              (holiday-float 6 0 3 "Father's Day")))

      ;; user defined holidays
      (setq holiday-other-holidays nil)  ; default

      ;; mark dates of holidays in the calendar
      (setq mark-holidays-in-calendar t)

;;** Getting Things Done (with Org mode)

      (section "Getting Things Done (with Org mode)")
      ;; (info "(org)Top") outline-based notes management and organizer

      ;; After all the configuration has been done, you can easily manage your
      ;; daily work and tasks with Org mode.
      ;; Press `C-c a a' to jump you to this week's task page from anywhere.


;;* 1 (info "(org)Introduction")

;;** 1.2 (info "(org)Installation")

      ;; autoload functions
      (GNUEmacs (try-require 'org-install))

      ;; getting started
      (add-to-list 'auto-mode-alist '("\\.txt\\'" . org-mode))
      (add-to-list 'auto-mode-alist '("\\.org\\'" . org-mode))
      (add-to-list 'auto-mode-alist '("\\.org_archive\\'" . org-mode))
      (define-key global-map (kbd "C-c l") 'org-store-link)
      (define-key global-map (kbd "C-c r") 'org-capture)
      (define-key global-map (kbd "C-c b") 'org-switchb)
      (define-key global-map (kbd "C-c a") 'org-agenda)

      ;; using links outside Org
      (global-set-key "\C-c L" 'org-insert-link-global)
      (global-set-key "\C-c o" 'org-open-at-point-global)

      (defun org-switch-to-agenda ()
        (interactive)
        (let ((buffer (get-buffer "*Org Agenda*")))
          (if buffer
              (switch-to-buffer buffer))))
      (global-set-key (kbd "C-c C-b") 'org-switch-to-agenda)



      ;; This must be set before loading Org...


      ;; face to be used by `font-lock' for highlighting in Org-mode Emacs
      ;; buffers, and tags to be used to convert emphasis fontifiers for HTML
      ;; export
      (setq org-emphasis-alist ;; remove the strike-through emphasis
            '(("*" bold "<b>" "</b>")
              ("/" italic "<i>" "</i>")
              ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
              ("=" org-code "<code>" "</code>" verbatim)
              ("~" org-verbatim "<code>" "</code>" verbatim)))

      (defface my/org-alert-face
        '((t (:weight bold :foreground "black" :foreground "#FF0000")))
        "Face used to display alert'ed items.")

      (add-to-list 'org-emphasis-alist
                   '("@" my/org-alert-face "<span class=\"alert\">" "</span>"))


      (eval-after-load "org"
        '(progn


        ;; Unhiding edited areas
        ;;??? I like the idea of clustering undo but find it disconcerting
        (setf org-self-insert-cluster-for-undo nil)
        ;; somebody, I think Carsten, suggested this, and it might work for
        ;; you, but for some reason I commented it out. I don't remember what
        ;; the reason was. Maybe speed.
        '(defadvice undo (after org-undo-reveal activate)
           "Make point and context visible after an undo command in Org mode."
           (and (org-mode-p) (org-reveal)))
        ;;(ad-unadvise 'undo)


        (add-hook 'org-mode-hook
                  (lambda ()
                    ;; ;; display images in your Org files
                    ;; (turn-on-iimage-mode)
                    ;; PERFORMANCE PROBLEM!!!!! with some Org files, such as:
                    ;; '("~/Personal/capture.org"
                    ;;   "~/Public/Org-Babel-Reference-Card.txt"
                    ;;   "~/Public/tags-opening-it-is-sloooooooooow.org")

                    ;; TEMP for Emacs 24 (performance problem)
                    (GNUEmacs24
                     (setq bidi-display-reordering nil))


                    (local-set-key "\M-n" 'outline-next-visible-heading)
                    (local-set-key "\M-p" 'outline-previous-visible-heading)

                    ;; table
                    (local-set-key "\M-\C-w" 'org-table-copy-region)
                    (local-set-key "\M-\C-y" 'org-table-paste-rectangle)
                    (local-set-key "\M-\C-l" 'org-table-sort-lines)

                    ;; flyspell mode to spell check everywhere
                    (when (executable-find ispell-program-name)
                      ;; check if `ispell-program-name' seems correct
                      (flyspell-mode 1))
                    ))

;;** 1.3 (info "(org)Activation")

        (section "1.3 (org)Activation")

        ;; insert the first line setting Org mode in empty files
        (setq org-insert-mode-line-in-empty-file t)

        (when (boundp 'org-modules)

          ;; make sure to turn `org-info' on in order to link to info nodes

          ;;??? enable globally unique ID (for `org-store-link')
          ;; (takes care of automatically creating unique targets for internal
          ;; links, see `C-h v org-link-to-org-use-id RET')
          (add-to-list 'org-modules 'org-id)

          ;;???
          (add-to-list 'org-modules 'org-habit))

;;* 2 (info "(org)Document Structure")

        ;; ellipsis to use in the Org mode outline
        (setq org-ellipsis
              (if (char-displayable-p ?\u25B7) ;; white right-pointing triangle
                  " \u25B7" ;; string
                'org-ellipsis)) ;; face

        ;; RET follows links
        (setq org-return-follows-link t)

        ;; blank lines
        (setq org-blank-before-new-entry
              '(
                ;; insert  a blank line before new heading
                (heading . t)

                ;; try to make an intelligent decision whether to insert a
                ;; blank line or not before a new item
                (plain-list-item . auto)))

;;** 2.2 (info "(org)Headlines")

        (section "2.2 (org)Headlines")

        ;; ;; `C-a' and `C-e' behave specially in headlines and items
        (setq org-special-ctrl-a/e 'reversed)

        ;; ;; get back the standard behavior of `C-a/e'
        ;; (define-key org-mode-map
        ;;   "\C-a" 'beginning-of-line)
        ;; (define-key org-mode-map
        ;;   "\C-e" 'end-of-line)

;;** 2.3 (info "(org)Visibility cycling")

        (section "2.3 (org)Visibility cycling")

        ;; do not switch to OVERVIEW at startup
        (setq org-startup-folded nil) ;; default is `t'

;;** 2.4 (info "(org)Motion")

        (section "2.4 (org)Motion")

        ;; headlines in the current buffer are offered via completion
        ;; (interface also used by the `refile' command)
        (setq org-goto-interface 'outline-path-completion)


        ;; a new and easier way to navigate your Org files
        (when (try-require 'org-occur-goto)
          ;; keybinding for oog (`org-occur-goto') for quick navigation
          ;; (org-defkey org-mode-map
          ;;             (kbd "C-c g") 'oog)
          (org-defkey org-mode-map
                      (kbd "C-c o") 'oog))


        ;; + helm-imenu...
        ;; + C-u C-c C-j...

        ;; something like Notational Velocity for Org
        (autoload 'org-velocity "org-velocity" nil t)
        (global-set-key (kbd "C-c v") 'org-velocity)
        (eval-after-load "org-velocity"
          '(setq org-velocity-bucket (concat org-directory "/bucket.org")))


        (eval-after-load "deft"
          '(progn
             (setq deft-extension "org")
             (setq deft-directory "~/Projects")
             (setq deft-text-mode 'org-mode)))


        ;; jump quickly to first level headings in my Org mode files
        (defun my-org-global-goto ()
          (interactive)
          (let ((org-completion-use-ido t)
                (org-outline-path-complete-in-steps nil)
                (org-refile-use-outline-path nil)
                (org-refile-targets '((my/org-refile-targets :maxlevel . 1))))
            (org-refile t)
            (org-reveal '(64))))


(define-key org-mode-map
  (kbd "C-c C-r") 'my/org-reveal)
(defun my/org-reveal (&optional all-siblings)
  "For `C-u C-c C-r', it does the same as default org-mode --- shows all
hidden siblings, and for `C-c C-r' --- all siblings of current level."
  (interactive "P")
  (if all-siblings
      (org-reveal t)
    (org-show-siblings)))

;;** 2.5 (info "(org)Structure editing")

        (section "2.5 (org)Structure editing")

        ;; ;; FIXME Choose the right value!
        ;; (setq org-M-RET-may-split-line nil)


;;** 2.6 (info "(org)Sparse trees")

        (section "2.6 (org)Sparse trees")

        ;; show full hierarchy when revealing a location
        (setq org-show-hierarchy-above t)

        ;; don't show following heading when revealing a location
        (setq org-show-following-heading nil)

        ;; don't show all sibling headings when revealing a location
        (setq org-show-siblings nil)

        ;; show the entry below a headline when revealing a location
        (setq org-show-entry-below t)
        (setq org-show-entry-below '((org-goto . t)))

;;** 2.7 (info "(org)Plain lists")

        (section "2.7 (org)Plain lists")

        (try-require 'org-list)

        ;; don't make tab cycle visibility on plain list items
        (setq org-cycle-include-plain-lists nil)

        ;; an empty line does not end all plain list levels
        (setq org-empty-line-terminates-plain-lists nil)

;;* 3 (info "(org)Tables")

        (setq org-table-use-standard-references 'from)

;;** 3.1 The (info "(org)Built-in table editor")

        (section "3.1 The (org)Built-in table editor")

        ;; default export parameters for `org-table-export'
        (setq org-table-export-default-format "orgtbl-to-csv")


;;** 3.5 (info "(org)The spreadsheet")

        (section "3.5 (org)The spreadsheet")

        ;; FIXME Only set calc-internal-prec to 12 (instead of 8 by default)
        (setq org-calc-default-modes
              '(calc-internal-prec 12
                calc-float-format  (float 12)
                calc-angle-mode    deg
                calc-prefer-frac   nil
                calc-symbolic-mode nil
                calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
                calc-display-working-message t))

;;* 4 (info "(org)Hyperlinks")

        ;; create web links to Google groups or Gmane (instead of Gnus
        ;; messages)
        (setq org-gnus-prefer-web-links t)

        ;; open non-existing files
        (setq org-open-non-existing-files t)

        ;; 4.3 function and arguments to call for following `mailto' links
        (setq org-link-mailto-program '(compose-mail "%a" "%s"))

        ;; setup the frame configuration for following links
        (setq org-link-frame-setup '((vm   . vm-visit-folder)
                                     (gnus . org-gnus-no-new-news)
                                     (file . find-file-other-window)))

;;** 4.6 (info "(org)Link abbreviations")

        ;; 4.6 shortcut links
        (setq org-link-abbrev-alist
              '(("cache" .
                 "http://www.google.com/search?q=cache:%s")
                ("dictionary" .
                 "http://www.dict.org/bin/Dict?Database=*&Form=Dict1&Strategy=*&Query=%s")
                ("google" .
                 "http://www.google.com/search?q=%s")
                ("googlegroups" .
                 "http://groups.google.com/groups?q=%s")
                ("googlemaps" .
                 "http://maps.google.com/maps?q=%s")
                ("imdb" .
                 "http://us.imdb.com/Title?%s")
                ("openstreetmap" .
                 "http://nominatim.openstreetmap.org/search?q=%s&polygon=1")
                ("wpen" .
                 "http://en.wikipedia.org/wiki/%s")
                ("wpfr" .
                 "http://fr.wikipedia.org/wiki/%s")))

;;* 5 (info "(org)TODO Items")

;;** 5.1 (info "(org)TODO basics") functionality

        (section "5.1 (org)TODO basics functionality")

        ;; 5.1 select a TODO state and bypass any logging associated with that
        (setq org-treat-S-cursor-todo-selection-as-state-change nil)

;;** 5.2 Use of (info "(org)TODO extensions")

        (section "5.2 Use of (org)TODO extensions")

        ;; list of TODO entry keyword sequences and their interpretation (for
        ;; the different task states)
        (setq org-todo-keywords
              '((sequence "NEW(n!)"   ;; created, proposed
                          "TODO(t!)"
                          "STRT(s!)"  ;; in progress
                          "WAIT(w!)"  ;; feedback
                          "DLGT(l!)"  ;; assigned
                          "DFRD(f!)"  ;; future, someday
                          ;; DFRD is *not* a completion state (in order not to
                          ;; be stroked through)
                          "MAYB(m!)"  ;; maybe, perhaps, wish
                          ;; actions that may be undertaken in the future
                          "|"
                          "DONE(d!)"  ;; resolved, closed
                          "CANX(x!)") ;; rejected
                (sequence "QTE(q!)" "QTD(Q!)" "|"
                          "APP(A!)" "EXP(E!)" "REJ(R!)")
                (sequence "OPENPO(O!)" "|"
                          "CLSDPO(C!)")))

        ;; TODO Check coherence of the faces with the above defined states
        ;; faces for specific TODO keywords
        (GNUEmacs
         (setq org-todo-keyword-faces
               '(("NEW"  . my/org-created-kwd-face)
                 ("TODO" . org-todo)
                 ("STRT" . my/org-inprogress-kwd-face)
                 ("DLGT" . my/org-delegated-kwd-face)
                 ("WAIT" . my/org-delegated-kwd-face)
                 ("DFRD" . my/org-deferred-kwd-face)
                 ("MAYB" . my/org-deferred-kwd-face)
                 ("DONE" . org-done)
                 ("CANX" . org-done)

                 ("QTE" . my/org-quote-kwd-face)
                 ("QTD" . my/org-quoted-kwd-face)
                 ("APP" . my/org-approved-kwd-face)
                 ("EXP" . my/org-expired-kwd-face)
                 ("REJ" . my/org-rejected-kwd-face)

                 ("OPENPO" . my/org-openpo-kwd-face)
                 ("CLSDPO" . my/org-closedpo-kwd-face))))

        ;; Org non-standard faces
        (defface my/org-created-kwd-face
          '((t (:weight normal :box (:line-width 1 :color "#EEE9C3")
                :foreground "#1A1A1A" :background "#FDFCD8")))
          "Face used to display state NEW.")
        (defface my/org-inprogress-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#D9D14A")
                :foreground "#D9D14A" :background "#FCFCDC")))
          "Face used to display state STRT.")
        (defface my/org-delegated-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#89C58F")
                :foreground "#89C58F" :background "#E2FEDE")))
          "Face used to display state DLGT or WAIT.")
        (defface my/org-deferred-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#9EB6D4")
                :foreground "#9EB6D4" :background "#E0EFFF")))
          "Face used to display state DFRD or MAYB.")

        (defface my/org-quote-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#FC5158")
                :foreground "#FC5158" :background "#FED5D7")))
          "Face used to display .")
        (defface my/org-quoted-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#55BA80")
                :foreground "#55BA80" :background "#DFFFDF")))
          "Face used to display .")
        (defface my/org-approved-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#969696")
                :foreground "#969696" :background "#F2F2EE")))
          "Face used to display .")
        (defface my/org-expired-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#42B5FF")
                :foreground "#42B5FF" :background "#D3EEFF")))
          "Face used to display state EXPIRED.")
        (defface my/org-rejected-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#42B5FF")
                :foreground "#42B5FF" :background "#D3EEFF")))
          "Face used to display state REJECTED.")

        (defface my/org-openpo-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#FC5158")
                :foreground "#FC5158" :background "#FED5D7")))
          "Face used to display .")
        (defface my/org-closedpo-kwd-face
          '((t (:weight bold :box (:line-width 1 :color "#969696")
                :foreground "#969696" :background "#F2F2EE")))
          "Face used to display .")

        ;; block switching entries to DONE if
        ;; 1) there are undone child entries, or
        ;; 2) the parent has an `:ORDERED:' property and there are prior
        ;;    siblings not yet done
        (setq org-enforce-todo-dependencies t)

        ;;
        (setq org-agenda-dim-blocked-tasks nil) ; XXX not sure about this one

        ;; block switching the parent to DONE if
        ;; there are unchecked checkboxes
        (setq org-enforce-todo-checkbox-dependencies t)

;;** 5.3 (info "(org)Progress logging")

        (section "5.3 (org)Progress logging")

        ;; 5.3.1 insert a CLOSED time stamp each time a TODO entry is marked DONE
        (setq org-log-done nil)

        ;; 5.3.2 the notes will be ordered according to time
        (setq org-log-states-order-reversed nil)

        ;; 5.3.2 insert state change notes and time stamps into a drawer
        (setq org-log-into-drawer t) ;; should be the default

        ;; ~5.3.2 heading for state change added to entries
        (setcdr (assq 'state org-log-note-headings)
                "State %-12S  ->  %-12s %t")

;;** 5.5 (info "(org)Breaking down tasks")

        (section "5.5 (org)Breaking down tasks")

        ;; automatically change a TODO entry to DONE when all children are done
        (defun org-summary-todo (n-done n-not-done)
          "Switch entry to DONE when all subentries are done, to TODO otherwise."
          (let (org-log-done org-log-states) ;; turn off logging
            (org-todo (if (= n-not-done 0) "DONE" "TODO"))))

        (add-hook 'org-after-todo-statistics-hook 'org-summary-todo)

;;* 6 (info "(org)Tags")

        (setq org-tags-column -78)

        ;; 6.2 list of tags ("contexts") allowed in Org mode files
        (setq org-tag-alist '((:startgroup . nil)
                               ("home" . ?h)
                               ("work" . ?w)
                              (:endgroup . nil)
                              ("errands" . ?e)
                              ("computer" . ?c)
                              ("phone" . ?p)
                              ("mail" . ?m)

                              ("reading" . ?r)
                              ;; ("finance" . ?f)
                              ("bank" . ?b)
                              ("note" . ?n)
                              ("blog" . ?B)

                              ("ARCHIVE" . ?A)
                              ("crypt" . ?C)))

        ;; ("appt" . ?a)
        ;; ("next" . ?n)
        ;; ("PROJ" . ?P)

        ;; faces for specific tags
        ;; XXX This generates an error when C-x C-w'ing the agenda view
        (setq org-tag-faces-XXX
              '(("refile" .
                 (:weight normal :slant italic
                  :box (:line-width 1 :color "#A0A1A4")
                  :foreground "#A0A1A4" :background "#444444'"))
                ("home" .
                 (:weight normal :slant italic
                  :box (:line-width 1 :color "#4488BB")
                  :foreground "#5C88D3" :background "#BBDDFF"))
                ("work" .
                 (:weight normal :slant italic
                  :box (:line-width 1 :color "#44AA44")
                  :foreground "#44AA44" :background "#CCFFAA"))
                ("blog" .
                 (:weight normal :slant italic
                  :box (:line-width 1 :color "#A48CC4")
                  :foreground "#FFFFFF" :background "#A48CC4"))
                ("note" .
                 (:weight normal :slant italic
                  :box (:line-width 1 :color "#7F7F7F")
                  :foreground "#FFFFFF" :background "#989898"))))

        ;; 6.2 exit fast tag selection after first change (toggle this with `C-c')
        (setq org-fast-tag-selection-single-key t)

        ;; remove redundant tags of headlines (from David Maus)
        (defun my/org-remove-redundant-tags ()
          "Remove redundant tags of headlines in current buffer.
        A tag is considered redundant if it is local to a headline and
        inherited by a parent headline."
          (interactive)
          (when (eq major-mode 'org-mode)
            (save-excursion
              (org-map-entries
               '(lambda ()
                  (let ((alltags (split-string
                                  (or (org-entry-get (point) "ALLTAGS") "")
                                  ":"))
                        local inherited tag)
                    (dolist (tag alltags)
                      (if (get-text-property 0 'inherited tag)
                          (push tag inherited) (push tag local)))
                    (dolist (tag local)
                      (if (member tag inherited) (org-toggle-tag tag 'off)))))
               t nil))))

        ;; ;; always offer completion for all tags of all agenda files
        ;; (setq org-complete-tags-always-offer-all-agenda-tags t)

;;* 7 (info "(org)Properties and Columns")

;;** 7.1 (info "(org)Property syntax")

        (section "7.1 (org)Property syntax")

        ;; list of property/value pairs that can be inherited by any entry
        (setq org-global-properties
              '(("Effort_ALL" .
                 "0 0:10 0:30 1:00 2:00 3:00 4:00 5:00 6:00 8:00")))

;;* 8 (info "(org)Dates and Times")

        (section "* 8 (org)Dates and Times")

        ;; TODO Some of this should go back in section
        ;;** 38.11 (info "(emacs)Appointments")

        ;; Insinuate appt
        (require 'appt)
        (setq appt-time-msg-list nil)
        (org-agenda-to-appt)
        ;; when use 'r' (rebuild agenda) reload appt
        (add-hook 'org-agenda-mode-hook (lambda ()
                                          (setq appt-time-msg-list nil)
                                          (org-agenda-to-appt)))
        ;; update appt each time agenda opened
        (add-hook 'org-finalize-agenda-hook 'org-agenda-to-appt)

        ;; beep to indicate appointment
        (setq appt-audible t)

        ;; turn appointment checking on
        (GNUEmacs (appt-activate 1))
        (XEmacs (appt-initialize))

        ;; time in minutes before an appointment that the warning begins
        (setq appt-message-warning-time 60) ;; default: 12

        ;; number of minutes to wait between checking the appointment list
        (setq appt-display-interval 15) ;; default: 3

        (when window-system

          ;; use a separate window to display appointment reminders
          (setq appt-display-format 'window) ;; 'echo

          (defun my/appt-notify (min-to-app new-time notification)
            "Display an appointment reminder.
          Use libnotify if available, or fall back on a message in the echo
          area."
            (cond ((executable-find "notify-send")
                   (shell-command
                    (concat "notify-send "
                            "-i /usr/share/icons/gnome/32x32/status/appointment-soon.png "
                            "'Appointment' "
                            "'" notification "'")))
                  (t
                   (message "%s" notification))))

          (setq appt-disp-window-function (function my/appt-notify)))

;;** 8.2 (info "(org)Creating timestamps")

        (section "8.2 (org)Creating timestamps")

        ;; number of minutes to round time stamps to
        (setq org-time-stamp-rounding-minutes '(1 1))


        (setq org-time-clocksum-use-fractional t)

;;** 8.3 (info "(org)Deadlines and scheduling")

        (section "8.3 (org)Deadlines and scheduling")

        ;; information to record when the deadline date is modified
        (setq org-log-redeadline 'time)

        ;; information to record when the scheduling date is modified
        (setq org-log-reschedule 'time)

        ;; no. of days to display before expiration of a deadline
        (setq org-deadline-warning-days 14)

        ;; skip deadline prewarning (up to 7 days before the actual deadline)
        ;; when entry is also scheduled
        (setq org-agenda-skip-deadline-prewarning-if-scheduled 7)

        ;; don't show deadlines when the corresponding item is done
        (setq org-agenda-skip-deadline-if-done t)

        ;; skip scheduling line if same entry shows because of deadline
        (setq org-agenda-skip-scheduled-if-deadline-is-shown t)

        ;; don't show scheduled items in agenda when they are done
        (setq org-agenda-skip-scheduled-if-done t)

        ;; ~8.3 don't select item by timestamp or -range if it is DONE
        (setq org-agenda-skip-timestamp-if-done t)

;;** 8.4 (info "(org)Clocking work time")

        (section "8.4 (org)Clocking work time")

        ;; default language of HTML export (see `org-export-language-setup')
        ;; XXX I define it here, otherwise I get errors
        (setq org-export-default-language "en")

        (GNUEmacs
         ;; the time clocking code for Org mode
         (try-require 'org-clock) ;; needed for trying to automatically
                                  ;; re-clock at Emacs startup
         (eval-after-load "org-clock"
           '(progn

           ;; 8.4 save both the running clock and the entire clock history
           ;; when Emacs is closed, and resume it next time Emacs is started
           ;; up
           (setq org-clock-persist t)

           ;; number of clock tasks to remember in history: 1-9A-Z
           (setq org-clock-history-length 35)


           ;; include the current clocking task time in clock reports
           (setq org-clock-report-include-clocking-task t)


           ;; 8.4 set up hooks for clock persistence
           (org-clock-persistence-insinuate)

           ;; resume clocking task on clock-in if the clock is open
           (setq org-clock-in-resume t)



           (defun my/org-clock-in-task-by-id (id)
             "Start the clock on the entry with id ID."
             (require 'org-id)
             (save-restriction
               (widen)
               (org-with-point-at (org-id-find id 'marker)
                 (org-clock-in nil))))

           (defun my/org-clock-in-interrupted-task ()
             "Clock back into the task that has been interrupted, if there is one."
             (interactive)
             (if (and (not org-clock-resolving-clocks-due-to-idleness)
                      (marker-buffer org-clock-marker)
                      (marker-buffer org-clock-interrupted-task))
                 (org-with-point-at org-clock-interrupted-task
                   (org-clock-in nil))
               (org-clock-out)))

           (global-set-key (kbd "C-c C-x C-q") 'my/org-clock-in-interrupted-task)

           (global-set-key (kbd "C-c C-x C-j") 'org-clock-goto)
           (global-set-key (kbd "C-c C-x C-i") 'org-clock-in)
           (global-set-key (kbd "C-c C-x C-o") 'org-clock-out)

;;** 8.4.3 (info "(org)Resolving idle time")

           (section "8.5 (org)Resolving idle time")

           ;; 8.5 resolve open clocks if the user is idle more than 120
           ;; minutes
           (setq org-clock-idle-time 120)

           ;; 8.5 set task to todo state STRT while clocking it
           ;; (setq org-clock-in-switch-to-state "STRT")
           (setq org-clock-in-switch-to-state 'my/org-switch-to-started)

           ;; change task state to STRT
           (defun my/org-switch-to-started (kw)
             "Switch task to STRT.

           Skip normal headlines and capture tasks."
             (if (and kw
                      (not (string-equal kw "STRT"))
                      (not (and (boundp 'org-capture-mode) org-capture-mode)))
                 "STRT"
               nil))

           ;; clock won't be stopped when the clocked entry is marked DONE
           (setq org-clock-out-when-done nil)

           ;; time included for the modeline clock is all time clocked into
           ;; this task today
           (setq org-clock-modeline-total 'today)
           (setq org-clock-modeline-total 'all)

           ;; If you have an `Effort' property defined, its value is also
           ;; shown in the mode line, and you can configure `org-clock-sound'
           ;; to get an alert when your planned time for a particular item is
           ;; over.
           (setq org-clock-sound "~/Music/Sounds/alarm.wav")
                                        ; sound that will used for
                                        ; notifications

           ;; remove the clock line when the resulting time is 0:00
           (setq org-clock-out-remove-zero-time-clocks t)

           ;; ;; when clocking into a task with a clock entry which has not
           ;; ;; been closed, resume the clock from that point
           ;; (setq org-clock-in-resume t)

           )))




;; XXX ne pas charger Org pour poser la question, qd on ne fait que
;; rentrer/sortir de Emacs!

;; ask the user if they wish to clock out before killing Emacs
(defun my/org-clock-query-out ()
  "Ask the user before clocking out.
This is a useful function for adding to `kill-emacs-query-functions'."
  (if (and
           (featurep 'org-clock)
           (funcall 'org-clocking-p)
	   (y-or-n-p "You are currently clocking time, clock out? "))
      (org-clock-out)
    t)) ;; only fails on keyboard quit or error

;; timeclock.el puts this on the wrong hook!
(add-hook 'kill-emacs-query-functions 'my/org-clock-query-out)

;;** 8.5 (info "(org)Effort estimates")

        (section "8.5 (org)Effort estimates")

        ;; add an effort estimate on the fly when clocking in
        (defun my/org-mode-ask-effort ()
          "Ask for an effort estimate when clocking in."
          (unless (org-entry-get (point) "Effort")
            (let ((effort
                   (completing-read
                    "Time estimate (H:MM): "
                    (org-entry-get-multivalued-property (point) "Effort"))))
              (unless (equal effort "")
                (org-set-property "Effort" effort)))))

        (add-hook 'org-clock-in-prepare-hook
                  'my/org-mode-ask-effort)

        ;; ;; Pomodoro technique
        ;; (add-to-list 'org-modules 'org-timer)
        ;; (setq org-timer-default-timer 25)
 	;; (add-hook 'org-clock-in-hook
        ;;           '(lambda ()
        ;;              (if (not org-timer-current-timer)
        ;;                  (org-timer-set-timer '(16)))))
        ;; ;; ;; This seems to stop the current timer (maybe clock-in is done
        ;; ;; ;; before clock-out?)
        ;; ;; (add-hook 'org-clock-out-hook
        ;; ;;           '(lambda ()
        ;; ;;              (org-timer-stop)))

;;** Not sorted

        (section "Not sorted")

        ;; text preceding scheduled items in the agenda view
        (setq org-agenda-scheduled-leaders '("Scheduled: " "Scheduled: "))

        ;; text preceding deadline items in the agenda view
        ;; (setq org-agenda-deadline-leaders  '("Deadline:  " "%2d d left: "))
        ;; "xx days ago", "In xx days"

        ;; text preceding item pulled into the agenda by inactive time stamps
        ;; (setq org-agenda-inactive-leader ...)

        ;; file to which to add new entries with the `i' key in agenda and
        ;; calendar
        (setq org-agenda-diary-file "refile.org")


        ;; 8.5 format string for displaying dates in the daily/weekly agenda
        ;; and in the timeline
        (setq org-agenda-format-date
              (concat "\n" "%Y-%m-%d" " %a "
                      (make-string (window-width) ?_)))

        ;; faces for showing deadlines in the agenda
        (setq org-agenda-deadline-faces
              '((1.0001 . my/org-deadline-yesterday-or-before-face)
                (0.9999 . my/org-deadline-today-face)
                (0.0000 . my/org-deadline-tomorrow-or-later-face)))

        ;; Org non-standard faces
        (defface my/org-deadline-yesterday-or-before-face
          '((t (:weight bold :foreground "white" :background "#FF0000")))
          "Face used to highlight tasks whose deadline is in the past.")

        (defface my/org-deadline-today-face
          '((t (:weight bold :foreground "white" :background "#FFA500")))
          "Face used to highlight tasks whose deadline is today.")

        (defface my/org-deadline-tomorrow-or-later-face
          '((t (:weight bold :foreground "white" :background "#33CC00")))
          "Face used to highlight tasks whose deadline is for later.")

        ;; show all days between the first and the last date
        (setq org-timeline-show-empty-dates t)


        ;; duration of an appointment will not add to day effort
        (setq org-agenda-columns-add-appointments-to-effort-sum nil)

        ;; default duration for appointments that only have a starting time
        (setq org-agenda-default-appointment-duration nil)


        ;; enable sticky agenda: `q' key will bury agenda buffers (instead of
        ;; killing)
        (setq org-agenda-sticky t)




;; XXX Seems nice, but first solve problem with decrypt question (auto-save)
        ;; (setq org-agenda-start-with-follow-mode t)

        ;; get a compact view during follow mode in the agenda
        (defun my/compact-follow ()
          "Make the view compact, then show the necessary minimum."
          (ignore-errors
            (save-excursion
              (while (org-up-heading-safe))
              (hide-subtree)))
          (let ((org-show-siblings nil)
                (org-show-hierarchy-above t))
            (org-reveal))
          (save-excursion
            (org-back-to-heading t)
            (show-children)))

        (add-hook 'org-agenda-after-show-hook 'my/compact-follow)


        (setq org-agenda-block-separator
              ;; (concat (make-string 132 (string-to-char "_")) "\n\n"))
              ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

        ;; make the block agenda more compact (no agenda span name, no week
        ;; number, no separator line)
        (setq org-agenda-compact-blocks t)


        (when (try-require 'org-habit)

          (setq org-habit-show-habits-only-for-today nil)

          ;; use character "heavy check mark" to show completed days on which
          ;; a task was done
          (setq org-habit-completed-glyph ?\u2714)

          ;; use character "heavy quadruple dash vertical" to identify today
          (setq org-habit-today-glyph ?\u250B)

          ;; TODO state to which a repeater should return the repeating task
          (setq org-todo-repeat-to-state "TODO"))


        ;; format string for the total time cells
        (setq org-clock-total-time-cell-format "%s")

        ;; format string for the file time cells
        (setq org-clock-file-time-cell-format "%s")

;;* 9 (info "(org)Capture - Refile - Archive")

        ;; the ultimate capture tool

        ;; 9.1.2 directory with Org files
        (setq org-directory
              (directory-file-name ;; this function removes the final slash
               (cond ((file-directory-p "~/Personal/") "~/Personal/")
                     ((file-directory-p "~/org/") "~/org/")
                     (t "~/"))))

        ;; 9.1.2 default target for storing notes
        (setq org-default-notes-file
              (concat org-directory "/refile.org")) ;; Inbox for collecting

        ;; 9.1.2 templates for the creation of capture buffers

                ;; ("Receipt"   ?r "** %^{BriefDesc} %U %^g\n%?"   "~/Personal/finances.org")
                ;; ("Someday"   ?s "** %^{Someday Heading} %U\n%?\n"  "~/Personal/someday.org")

        ;; Unsorted
        ;; Temporary
        ;; To Do
        ;; Applications
        ;; Web Quotes
        ;; Documentations
        ;; People
        ;; Projects
        ;; Job Ads

        ;; Family
        ;; Friends
        ;; Future
        ;; Graphics
        ;; Languages
        ;; Linux
        ;; Magical Moments
        ;; Networks
        ;; Projects
        ;; Traveling

        ;; fast note taking in Org mode (the ultimate capture tool)
        (eval-after-load "org-capture"
          '(progn
          ;; Contacts, Calendar, Tasks, Notes, Journal

          (defun my/org-capture-template (keys description file headline)
            "Create template for captured elements."
            `(,keys ,description entry
                    (file+headline ,file ,headline)
                    "* %^{Title}
  :PROPERTIES:
  :Created: %:date-timestamp-inactive
  :END:
%?
%i

From %a"
                    :empty-lines 1))

          ;; - %a :: annotation (link)
          ;; - %i :: initial content (selected text)
          ;; - %? :: cursor position
          ;; - %^T :: prompt for a date and time
          ;; - %^G :: prompt for tags with completion on tags in all agenda files
          ;; - %t :: time stamp (date only)
          ;; - %^{prompt} :: prompt the user for a string
          ;; - %[file] :: insert the contents of the file
          ;; - %U :: inactive time stamp with date and time
          ;; - %& :: tell capture to jump to the note after storing it
          (setq org-capture-templates
                `(("t" "Task" entry
                   (file+headline ,org-default-notes-file "Tasks")
                   "* NEW %^{Task}%?

%i"
                   ;; The following is already part of "processing"; not here!
                   ;; DEADLINE: %^{Due?|}t
                   ;; :PROPERTIES:
                   ;; :Effort: %^{Time estimate|0|10|30|60|120}
                   ;; :END:
                   :empty-lines 1)

                  ("T" "Task in current file" entry
                   (file+headline (buffer-file-name
                   (org-capture-get :original-buffer)) "Tasks")
                   "* TODO %?
  %U %a %n"
                   :prepend t)

                  ("a" "Appt" entry
                   (file+headline ,org-default-notes-file "Appointments")
                   "* %^{Appointment}%?
  %^T

%i"
                   :empty-lines 1)
                  ;; TODO Prompt only for date, not time...

                  ("m" "Mail" entry
                   (file+headline ,org-default-notes-file "Tasks")
                   "* TODO %:subject%? (from %:fromname) :mail:
  SCHEDULED: %t
  %:date-timestamp-inactive

#+begin_verse
%i
#+end_verse

From %a"
                   :empty-lines 1 :immediate-finish t)
                  ;; `immediate-finish' = immediately store note without
                  ;; further prompt (skipping `C-c C-c'), which is very handy
                  ;; for quick storing of emails

                  ("M" "mailtodo" entry (file+datetree "~/Personal/mails.org")
                   "* TODO %^{Task} %^G\n   SCHEDULED: %t\n   - From :: %:from\n   - Subject :: %:subject\n   - Email :: %a\n   %?" :kill-buffer t)

                  ("p" "Phone call" entry
                   (file+headline ,org-default-notes-file "Phone calls")
                   "* %?"
                   :empty-lines 1 :clock-in t :clock-resume t)

                  ("i" "interruption" entry
                   (file "refile.org")
                   "A TEMPLATE HERE"
                   :clock-in t :clock-resume t)

                  ;; thought
                  ("n" "Note" entry
                   (file+headline ,org-default-notes-file "Notes")
                   "* %^{Thought}%?

%i"
                   :empty-lines 1)

                  ("b" "Buy" checkitem ;; Stuff to Buy
                   (file+headline ,org-default-notes-file "Shopping list"))

                  ;; add a note to the currently clocked task
                  ("c" "Clock sibling" entry
                   (clock)
                   "* %^{Title}\n %U\n %a\n\n %i")

                  ("j" "Journal" entry
                   (file+datetree ,(concat org-directory "/journal.org"))
                   "* %T %?  :blog:

%U

%i

From %a"
                                        ; "* %^{Title}  :blog:\n  :PROPERTIES:\n  :on: %T\n  :END:\n  %?\n  %x"
                   :empty-lines 1)

                  ("s" "Journal entry for Sarah" entry
                   (file+datetree+prompt ,(concat org-directory "/Home/Family/Sarah-journal.txt")))
                   ;; "* On %U\n %i%?\n%a")

                  ("S" "secure" entry
                   (file+datetree+prompt "~/git/notes/secure.org.gpg")
                   "* %(format-time-string \"%H:%M\") %^{Entry} %^G\n%i%?")

                  ;; notes
                  ("N" "Templates adding notes")
                  ,(my/org-capture-template
                    "Ne" "Emacs" "~/Public/Notes-on-Emacs.txt" "Notes")
                  ,(my/org-capture-template
                    "No" "Org" "~/Public/Notes-on-Org.txt" "Notes")
                  ,(my/org-capture-template
                    "NL" "Lisp" "~/Public/Notes-on-Lisp.txt" "Notes")
                  ,(my/org-capture-template
                    "Ng" "Gnus" "~/Public/Notes-on-Gnus.txt" "Notes")
                  ,(my/org-capture-template
                    "Nl" "LaTeX" "~/Public/Notes-on-LaTeX.txt" "Notes")
                  ,(my/org-capture-template
                    "NT" "TikZ" "~/Public/Notes-on-TikZ.txt" "Notes")
                  ,(my/org-capture-template
                    "Nb" "Beamer" "~/Public/Notes-on-Beamer.txt" "Notes")
                  ,(my/org-capture-template
                    "NS" "StumpWM" "~/Public/Notes-on-StumpWM.txt" "Notes")
                  ,(my/org-capture-template
                    "Nu" "Unix" "~/Public/Notes-on-Unix.txt" "Notes")
                  ,(my/org-capture-template
                    "Nc" "Ledger" "~/Public/Notes-on-Ledger.txt" "Notes")
                  ,(my/org-capture-template
                    "Nr" "RFID" "~/Public/Notes-on-RFID.txt" "Notes")
                  ,(my/org-capture-template
                    "Ns" "Security" "~/Public/Notes-on-Security.txt" "Notes")

                  ;;          ("w" "org-protocol" entry
                  ;;           (file ,org-default-notes-file)
                  ;;           "* TODO Review %c
                  ;; %U"
                  ;;           :immediate-finish t :clock-in t :clock-resume t)

                  ;; ("web-clippings" ?w
                  ;;  "* %^{Title} %^g \n  :PROPERTIES:\n  :date: %^t\n  :link: %^{link}\n  :END:\n\n %x %?"
                  ;;  "~/org/data.org" "Web Clippings")
                  ("w" "Default template" entry
                   ;; `org-protocol-default-template-key'
                   (file+headline ,(concat org-directory "/capture.org") "Notes")
                   "* %^{Title}%?
  %u

%i

From %c"
                   :empty-lines 1 :immediate-finish t)
                  ))

          ;; default `org-capture-templates' key to use
          (setq org-protocol-default-template-key "w")


          ;; (defun remove-ctrl-M ()
          ;;   "Remove ^M at end of line in the whole buffer."
          ;;   (interactive)
          ;;   (save-match-data
          ;;     (save-excursion
          ;;       (let ((remove-count 0))
          ;;         (goto-char (point-min))
          ;;         (point-max) t) ; so passt es nur am Ende der Zeile
          ;;       (while (re-search-forward (char-to-string 13) (point-max) t)
          ;;         (setq remove-count (+ remove-count 1))
          ;;         (replace-match "" nil nil))
          ;;       (message (format "%d ^M removed from buffer." remove-count)))))
          ;;
          ;; (add-hook 'org-capture-mode-hook 'remove-ctrl-M)


          ))
        ;; fni )

        ;; 9.4 capture from Firefox (to store links and text)
        ;; Have a look at "Store links in Emacs Org using org-protocol.el"
        ;; http://vimeo.com/5662410
        (when (try-require 'org-protocol)

          ;; map online URL to an existing working file
          (setq org-protocol-project-alist
                '(("Worg at http://orgmode.org/worg/"
                   :online-suffix ".html"
                   :working-suffix ".org"
                   :base-url "http://orgmode.org/worg/"
                   :working-directory "/home/sva/src/Worg/")
                  ("My public Org-notes at http://www.mygooglest.com/fni/"
                   :online-suffix ".html"
                   :working-suffix ".txt"
                   :base-url "http://www.mygooglest.com/fni/"
                   :working-directory
                   "/home/sva/Public/www.mygooglest.com/source/fni/"))))

        (defun make-capture-frame ()
          "Create a new frame and run `org-capture'."
          (interactive)
          (make-frame '((name . "capture")
                        (width . 80)
                        (height . 10)))
          (select-frame-by-name "capture")
          ;; ;; setup buffer to wrap
          ;; (setq truncate-lines nil
          ;;       word-wrap t)
          (org-capture))

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

        (defadvice org-capture-finalize
          (after delete-capture-frame activate)
          "Advise capture-finalize to close the frame (if it is the capture frame)."
          (if (equal "capture" (frame-parameter nil 'name))
              (delete-frame)))

        (defadvice org-capture-destroy
          (after delete-capture-frame activate)
          "Advise capture-destroy to close the frame (if it is the capture frame)."
          (if (equal "capture" (frame-parameter nil 'name))
              (delete-frame)))

(defun my/org-insert-image-or-take-screenshot (name)
  "Insert a link to an already existing image, or else to a screenshot.
The screenshot is either taken to the given non-existing file name,
or added into the given directory, defaulting to the current one."
  ;; FIXME: Should limit to '("pdf" "jpeg" "jpg" "png" "ps" "eps")
  ;; which is org-export-latex-inline-image-extensions.
  (interactive "GImage name? ")
  (when (file-directory-p name)
    (setq name (concat
                (make-temp-name
                 (expand-file-name
                  (concat (file-name-as-directory name)
                          (subst-char-in-string
                           "." "-"
                           (file-name-sans-extension
                            (file-name-nondirectory
                             (buffer-file-name)))))))
                ".png")))
  (unless (file-exists-p name)
    (if (file-writable-p name)
        (progn
          (message "Taking screenshot into %s" name)
          (call-process "import" nil nil nil name)
          (message "Taking screenshot...done"))
      (error "Cannot create image file")))
  (insert (concat "[[" name "]]"))
  (org-display-inline-images))

        ;; "Once a date has been scheduled, use cut and paste to move the task
        ;; to the appropriate category."
        ;;
        ;; I find it much easier to use the refile note command `C-c C-w'.
        ;; This lets me select (with completion) the header under which the
        ;; entry will be placed. By default, this only allows first-level
        ;; headers to be selected. But:

        ;; 9.1.4 any headline with level <= 2 is a target
        (setq my/org-refile-extra-files
              (if (file-exists-p "~/Public/")
                  (directory-files "~/Public/" t "^[^\\.#].*\\.\\(txt\\|org\\)$")
                nil))
        ;; 9.1.4 provide refile targets as paths, including the file name
        ;; (without directory) as level 1 of the path
        (setq org-refile-use-outline-path 'file)

        ;; 9.1.4 allow to create new nodes (must be confirmed by the user) as
        ;; refile targets
        (setq org-refile-allow-creating-parent-nodes 'confirm)

        ;; refile only within the current buffer
        (defun my/org-refile-within-current-buffer ()
          "Move the entry at point to another heading in the current buffer."
          (interactive)
          (let ((org-refile-targets '((nil :maxlevel . 8))))
            (org-refile)))
        ;; FIXME Add a smart key binding

        ;; 9.6.1 subtrees should be archived in the current file
        (setq org-archive-location "::* Archive")

        (setq org-archive-save-context-info '(time category itags))

;;* 10 (info "(org)Agenda Views")

        (defun my/org-current-time ()
          "Return current-time if date is today."
          (when (equal date (calendar-current-date))
            (format-time-string "%H:%M ——————" (current-time))))


        ;; multiple same-day timestamps in entry make multiple agenda lines
        (setq org-agenda-skip-additional-timestamps-same-entry nil)

        ;; show outline path in echo area after line motion (though, may bring
        ;; some slowness)
        (setq org-agenda-show-outline-path t)

        ;; 10.0 restore the window configuration when exiting the agenda
        (setq org-agenda-restore-windows-after-quit t)

;;** 10.1 (info "(org)Agenda files")

        ;; always start the overview on the current day
        (setq org-agenda-start-on-weekday nil)

        ;; 10.1 set which files to search for TODO entries and scheduled items
        ;; (avoiding hidden files)
        (setq org-agenda-files
              (append
               ;; org-agenda-files ;; if appending to themselves, they're doubled in agenda views with `org-reload'
               ;; org-directory
               (file-expand-wildcards "~/Personal/*.org")
               (file-expand-wildcards "~/Projects/*.org")
               (file-expand-wildcards "~/Projects/Institutions/Forem/Pfi/pfi/Specs/2010-DMFA-et-Autres/*.org")
               (file-expand-wildcards "~/Projects/Healthcare/Labco/Reports/*.org")
               (file-expand-wildcards "~/Projects/Healthcare/Isipharm/Leo-v200/admin/leo-v200-fni.org")
               (file-expand-wildcards "~/Projects/MCit/odase-platform/admin/*.org")
               ))
        ;; check that no `custom-set-variables' overrides this (at the end of
        ;; your `.emacs')!

        (message "(info) Found %s entries in `org-agenda-files'"
                 (length org-agenda-files))
        (sit-for 1)

        (setq org-refile-targets
              `((nil :maxlevel . 8) ;; current file
                (,(append org-agenda-files my/org-refile-extra-files) :maxlevel . 4)))

;;** 10.3 The (info "(org)Built-in agenda views")

        ;; ;; generate -- after all initialization -- the agenda buffer for
        ;; ;; this week
        ;; (add-hook 'after-init-hook 'org-agenda-list)

        ;; ;; 10.3.1 trigger agenda view (where the string is the key for that
        ;; ;; particular agenda view)
        ;; (org-agenda nil "dc") ;; today's calendar
        ;;
        ;; (delete-other-windows)

        ;; "C-c a t" should show *all* the TODO items... but...

        ;; don't show entries with a date in the global todo list
        (setq org-agenda-todo-ignore-with-date t) ;;!! tricky setting

        ;; 10.3.2 don't show scheduled entries in the global todo list
        (setq org-agenda-todo-ignore-scheduled 'future) ;;!! tricky setting

        ;; 10.3.2 don't show entries scheduled in the future in the global todo list (until
        ;; they are within the warning period)
        (setq org-agenda-todo-ignore-deadlines 'near) ;;!! tricky setting

        ;; 10.3.2 check also the sublevels of a TODO entry for TODO entries,
        ;; resulting in potentially much longer TODO lists.
        (setq org-agenda-todo-list-sublevels t)

        ;; 10.3.3 honor todo-list ...ignore options also in tags-todo search
        (setq org-agenda-tags-todo-honor-ignore-options t)

        ;; 10.3.5 list of extra files to be searched by text search commands
        ;; (C-c a s)
        (setq org-agenda-text-search-extra-files nil)
        (setq my/org-search-extra-files
              (append (if (file-exists-p "~/Public/")
                          (directory-files "~/Public/" t "^[^\\.#].*\\.\\(txt\\|org\\)$")
                        ;; no hidden nor autosave file!
                        ;; XXX Must dot inside the [] group be escaped or not?
                        nil)
                      (if (file-exists-p "~/Public/www.mygooglest.com/source/fni/")
                          (directory-files "~/Public/www.mygooglest.com/source/fni/" t "^[^\\.].*\\.txt$")
                        nil)
                      (if (file-exists-p "~/Examples/Org-scraps/")
                          (directory-files "~/Examples/Org-scraps/" t "^[^\\.].*\\.txt$")
                        nil)

                      ;; (if (file-exists-p "~/src/org-mode/contrib/babel/")
                      ;;     (directory-files "~/src/org-mode/contrib/babel/" t "^[^\\.].*\\.org$")
                      ;;   nil)

                      ;; (expand-file-name
                      ;;   (concat (file-name-directory (locate-library "org.el"))
                      ;;           "../contrib/babel/"))

                      (if (file-exists-p "~/src/org-config/")
                          (directory-files "~/src/org-config/" t "^[^\\.].*\\.org$")
                        nil)
                      (if (file-exists-p "~/src/Worg/")
                          (directory-files "~/src/Worg/" t "^[^\\.].*\\.org$")
                        nil)))

        ;; turn on individual word search (for Google addicts)
        (setq org-agenda-search-view-always-boolean t
              org-agenda-search-view-search-words-only t)

        ;; match part of a word
        (setq org-agenda-search-view-force-full-words nil)

        ;; 10.3.5 keyword search
        (defun my/org-grep (search &optional context)
          "Search for word in org files.
         Prefix argument determines number of lines."
          (interactive "sSearch for: \nP")
          (let ((grep-find-ignored-files '("#*" ".#*"))
                (grep-template (concat "grep <X> -i -nH "
                                       (when context
                                         (concat "-C" (number-to-string context)))
                                       " -e <R> <F>")))
            (lgrep search "*org*" org-directory)))
        ;; (global-set-key (kbd "<f8>") 'my/org-grep)

        ;; 10.3.6 how to identify stuck projects
        (setq org-stuck-projects '("+LEVEL=2/-DONE" ;; identify a project
                                   ("TODO" "STRT") ;; TODO keywords
                                   nil ;; tags
                                   "")) ;; regexp

;;** 10.4 (info "(org)Presentation and sorting")

        ;; 10.4 column to shift tags to (in agenda items)
        (setq org-agenda-tags-column -132)


        ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
        ;; With this typing "L" in agenda and todo buffers allows toggling
        ;; whether category/file names appear or not at the left or entries in
        ;; agenda/todo listings.
        ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

        (defvar my/org-agenda-list-category t)
        (defun my/org-agenda-toggle-list-category ()
          "Toggles whether category/file name appears or not at the left
          of entries in agenda listings. Useful to unclutter listings."
          (interactive)
          (if my/org-agenda-list-category
              (progn
                (setq my/org-agenda-list-category nil)
                ;; 10.4 format specifications for the prefix of items in the agenda views
                (setq org-agenda-prefix-format
                      '((agenda . " %i %-12:c%?-12t% s %-7e") ;; `%e' requires Org version 7.8
                        (timeline . "  % s")
                        (todo . " %i %-12:c")
                        (search . " %i %-12:c")
                        (tags . " %i %-12:c"))))
            (setq my/org-agenda-list-category t)
            (setq org-agenda-prefix-format
                  '((agenda  . "  %?-12t% s")
                    (timeline  . "  % s")
                    (todo  . "  ")
                    (search . "  ")
                    (tags  . "  "))))
          (org-agenda-redo))

        (add-hook 'org-mode-hook
                  (lambda ()
                    (define-key org-agenda-keymap
                      "L" 'my/org-agenda-toggle-list-category)
                    (define-key org-agenda-mode-map
                      "L" 'my/org-agenda-toggle-list-category)))



        ;; 10.4.2 settings for time grid for agenda display
        (setq org-agenda-time-grid '((daily today remove-match)
                                     ""
                                     (0800 1000 1200 1400 1600 1800 2000)))

        ;; string for the current time marker in the agenda
        (setq org-agenda-current-time-string "now")

        ;; 10.4.3 sorting structure for the agenda items of a single day
        ;; (setq org-agenda-sorting-strategy   ; original value
        ;;       '((agenda habit-down time-up priority-down category-keep)
        ;;         (todo priority-down category-keep)
        ;;         (tags priority-down category-keep)
        ;;         (search category-keep)))

        ;; FIXME refile.org should come first
        ;; Current workaround: added `#+CATEGORY: @refile' at the end of that
        ;; file (the `@' symbol is alphabetically before the letters)
        (setq org-agenda-sorting-strategy   ; custom value
              '((agenda time-up category-up priority-down)
                (todo priority-down category-keep)
                (tags priority-down category-keep)
                (search category-keep)))

        ;; from Bernt
        (setq org-agenda-sorting-strategy
              '((agenda habit-down time-up user-defined-up priority-down effort-up category-keep)
                (todo category-up priority-down effort-up)
                (tags category-up priority-down effort-up)
                (search category-up)))

        ;; Johnny Jacob
        (setq org-agenda-sorting-strategy
              '((agenda time-up priority-down tag-up)
                (todo tag-up)))

        ;; Bastien
        (setq org-agenda-sorting-strategy
              '((agenda time-up priority-down category-keep)
                (todo priority-down category-keep)
                (tags priority-down category-keep)
                (search category-keep)))


        ;;    (setq org-sort-agenda-notime-is-late nil)

        (setq org-agenda-window-frame-fractions '(1.0 . 1.0))

;;** 10.5 (info "(org)Agenda commands")

        ;; 10.5 number of days to include in overview display
        (setq org-agenda-span 'day)

        ;; 10.5 only show clocked entries in agenda log mode (no closed
        ;; entries, no state changes)
        (setq org-agenda-log-mode-items '(clock))

        ;; 10.5 parameters for the clocktable in clockreport mode
        (setq org-agenda-clockreport-parameter-plist
              '(:link t :maxlevel 2 :fileskip0 t))
        (setq org-agenda-clockreport-parameter-plist
              '(:link nil :maxlevel 2 :fileskip0 t))

        ;; 10.5 definition of what constitutes a clocking problem (overlapping
        ;; clock entries, clocking gaps)
        (setq org-agenda-clock-consistency-checks
              '(:max-duration "10:00" :min-duration 0
                :max-gap "0:00" :gap-ok-around ("4:00")
                :default-face
                ((:weight bold
                  :box (:line-width 1 :color "#AAEE77")
                  :foreground "black" :background "#BFFA9E"))
                :gap-face
                ((:weight bold
                  :box (:line-width 1 :color "#BBDDFF")
                  :foreground "black" :background "#D0EDFF"))))

        ;; 10.5? keep filters from one agenda view to the next
        (setq org-agenda-persistent-filter t)

        ;; faces for specific Priorities (#A, #B and #C)
        ;; XXX This generates an error when C-x C-w'ing the agenda view
        (setq org-priority-faces-XXX
              '((?A . (:weight bold :slant italic :underline t
                       :foreground "#6E0000" :background "#F67777"))
                (?B . (:slant italic
                       :foreground "#005606" :background "#B6E864"))
                (?C . (:slant italic
                       :foreground "#00337B" :background "#C3DCFF"))))

        ;; 10.5 Commands in the agenda buffer
        (defun my/weekday-p ()
          "Return t if current day is between Monday and Friday."
          (let ((dow (nth 6 (decode-time))))
            (and (> dow 0)
                 (< dow 6))))

        (defun my/working-p ()
          "Return t if current time is inside normal working hours.
        Currently: 08:30-12:30 and 13:30-17:30."
          (let* ((time (decode-time))
                 (hour (nth 2 time))
                 (mins (nth 1 time)))
            (and (my/weekday-p)
                 (or (or (and (= hour 8) (>= mins 30))
                         (and (< 8 hour) (< hour 12))
                         (and (= hour 12) (<= mins 30)))
                     (or (and (= hour 13) (>= mins 30))
                         (and (< 13 hour) (< hour 17))
                         (and (= hour 17) (<= mins 30)))))))

        (defun my/calling-hours-p ()
          "Return t if current time is inside normal calling hours.
        Currently: 08:00-21:59."
          (let* ((hour (nth 2 (decode-time))))
            (and (<= 8 hour) (<= hour 21))))

        (defun my/org-auto-exclude-function (tag)
          (and (cond
                ((string= tag "home")
                 (with-temp-buffer
                   (call-process "/sbin/ifconfig" nil t nil "en0" "inet")
                   (goto-char (point-min))
                   (not (re-search-forward "inet 192\\.168\\.9\\." nil t))))
                ((or (string= tag "errands")
                     (string= tag "phone"))
                 (let ((hour (nth 2 (decode-time))))
                   (or (< hour 8) (> hour 21)))))
               (concat "-" tag)))

        ;;! ensure that `:refile:' tags never will be excluded!
        (defun my/org-auto-exclude-function (tag)
          (and (cond
                ((string= tag "home")
                 (my/working-p))
                ((string= tag "work")
                 (not (my/working-p)))
                ((or (string= tag "errands")
                     (string= tag "phone"))
                 (not (my/calling-hours-p))))
               (concat "-" tag)))

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

;;** 10.6 (info "(org)Custom agenda views")

        ;; 10.6.3 custom commands for the agenda
        ;; Or use your agenda and use `/' to limit the view to what you want
        ;; (`C-c a a / TAG').

        ;; (setq org-agenda-custom-commands
        ;;       '(("f" "Agenda without Items tagged xyz"
        ;;          ((agenda ""))
        ;;          ((org-agenda-show-log nil)
        ;;           (org-agenda-span 'day)
        ;;           (org-agenda-log-mode-items '(state))
        ;;           (org-agenda-skip-function '(org-agenda-skip-entry-if 'regexp ":XYZ:"))))
        ;;         ;; other commands here
        ;;         ("d" "Agenda only Items tagged xyz"
        ;;          ((agenda ""))
        ;;          ((org-agenda-show-log nil)
        ;;           (org-agenda-span 'day)
        ;;           (org-agenda-log-mode-items '(state))
        ;;           (org-agenda-skip-function '(org-agenda-skip-entry-if 'notregexp ":XYZ:"))))
        ;;         ;; other commands here
        ;;         ("w" todo "WAIT")
        ;;         ("g" todo "STRT")
        ;;         ))

        (setq org-agenda-custom-commands
              '(

                ;;             ("D" "Daily Action List"
                ;;              ((agenda ""
                ;;                       ((org-agenda-span 'day)
                ;;                        (org-agenda-sorting-strategy
                ;;                         '((agenda time-up priority-down tag-up)))
                ;;                        (org-deadline-warning-days 0)))))
                ("d" "Daily Agenda"
                 ((agenda ""
                          ((org-agenda-todo-keyword-format "")
                           (org-agenda-remove-tags t)))
                  (tags "LEVEL=2+goals"
                        ((org-agenda-remove-tags t)
                         (org-agenda-prefix-format "  ")
                         (org-agenda-todo-keyword-format "")))
                  (todo "NEXT"
                        ((org-agenda-sorting-strategy '(tag-up))
                         (org-agenda-show-inherited-tags nil)
                         (org-agenda-todo-keyword-format "")))
                  (todo "PENDING"
                        ((org-agenda-todo-keyword-format "")))
                  (stuck ""
                         ((org-agenda-remove-tags t)))))

                ))

        (setq org-agenda-custom-commands
              '(

                ("p" "Printed agenda"
                 ((agenda ""
                          ((org-agenda-span 'week)
                           (org-agenda-start-on-weekday nil)
                           (org-agenda-time-grid nil)
                           (org-agenda-repeating-timestamp-show-all t)
                           (org-agenda-prefix-format "  -->  %t %s")
                           (org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'deadline 'scheduled))))
                  (agenda ""
                          ((org-agenda-span 'day)
                           (org-agenda-sorting-strategy '(time-up tag-up))
                           (org-agenda-todo-keyword-format "[ ]")
                           (org-agenda-scheduled-leaders '("" ""))
                           (org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'deadline))
                           (org-agenda-prefix-format "%t %T %s")
                           ))
                  (agenda ""
                          ((org-agenda-span 'day)
                           (org-deadline-warning-days 7)
                           (org-agenda-time-grid nil)
                           (org-agenda-include-diary nil)
                           (org-agenda-todo-keyword-format "[ ]")
                           (org-agenda-scheduled-leaders '("" ""))
                           (org-agenda-overriding-header "Deadlines:")
                           (org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'notdeadline))
                           (org-agenda-prefix-format "%t %s")))
                  (todo "TODO|STRT"
                        ((org-agenda-sorting-strategy '(tag-up priority-down))
                         (org-agenda-todo-ignore-with-date t)))
                  (todo "WAIT"))
                 ((org-agenda-with-colors nil)
                  (org-agenda-prefix-format "%T [ ]")
                  (org-agenda-todo-keyword-format "")
                  (org-agenda-include-all-todo nil)
                  (org-agenda-block-separator "---------------\n")
                  (org-agenda-remove-tags t)
                  (ps-number-of-columns 2)
                  ;; (ps-print-header nil)
                  (ps-landscape-mode t))
                 ("~/storage/agenda/agenda.pdf"))

                ("y" "Projects"
                 ((agenda ""
                          ((org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'notregexp "* PROJ")))
                          ((org-agenda-include-diary nil)
                           (org-agenda-include-all-todo nil)
                           (org-agenda-time-grid nil)))
                  (todo "PROJ" ((org-agenda-todo-ignore-deadlines-t)
                                   (org-agenda-sorting-strategy
                                    '(priority-down))))))
                ))

        ;; (key desc type match settings files)
        (setq org-agenda-custom-commands
              '(

                ("E" "Week's errands"
                 tags "errands&SCHEDULED<=\"<+1w>\"&TODO<>\"DONE\"&TODO<>\"CANX\""
                 nil)

                ("F" "Agenda of upcoming deadlines (6 months)"
                 ;; FIXME We don't see DEADLINE with `-1m' (or so)
                 ;; specifications (if they are more than 1m ahead of now)!
                 agenda ""
                 ((org-agenda-span 'day)
                  (org-deadline-warning-days 183)
                  (org-agenda-include-all-todo nil)
                  (org-agenda-time-grid nil)
                  (org-agenda-skip-function
                   '(org-agenda-skip-entry-if 'notdeadline))))
                ;; Some SCHEDULED are shown (when paired with a deadline and
                ;; scheduled in the past or for today)

                ;; hide Scheduled Items
                ("&" "Timeline" ((agenda "" ))
                 ((org-agenda-span 'day)
                  (org-agenda-show-log t)
                  (org-agenda-clockreport-mode t)
                  (org-agenda-log-mode-items '(clock))
                  (org-agenda-entry-types '(:timestamp :sexp :deadline))))
                  ;; (org-agenda-entry-types '()) ;; <-----pass blank list.

;;*** Stuck

                ("u" "Unscheduled TODO entries"
                 alltodo ""
                 ((org-agenda-entry-types '(:scheduled :deadline :timestamp))
                  (org-agenda-overriding-header "Unscheduled TODO entries: ")))

                ;; show unscheduled TODO items as a TODO list
                ("U"
                 todo "TODO"
                 ((org-agenda-todo-ignore-with-date t)
                  (org-agenda-tags-todo-honor-ignore-options t)))

                              ("Yu" "Unscheduled tasks (all, no DFRD/MAYB, prior down)"
                               tags "TODO<>\"\"&TODO<>{DONE\\|CANX\\|NOTE\\|PROJ}"
                               ((org-agenda-overriding-header "Unscheduled tasks: ")
                                (org-agenda-skip-function
                                 '(org-agenda-skip-entry-if 'scheduled 'deadline 'timestamp 'regexp "\\* \\(DFRD\\|MAYB\\)"))
                                (org-agenda-sorting-strategy '(priority-down))))

                              ("Yv" "Unscheduled tasks (work, no DFRD/MAYB, categ up)"
                               tags "work&TODO<>\"\"&TODO<>{DONE\\|CANX\\|NOTE\\|PROJ}"
                               ((org-agenda-overriding-header "Unscheduled work-related tasks")
                                (org-agenda-sorting-strategy '(category-up))
                                (org-agenda-skip-function
                                 '(org-agenda-skip-entry-if 'scheduled 'deadline 'timestamp 'regexp "\\* \\(DFRD\\|MAYB\\)"))))

                              ("Yw" "Work-related tasks"
                               tags "work&TODO<>\"\"&TODO<>{DONE\\|CANX\\|NOTE\\|PROJ}"
                               ((org-agenda-overriding-header "Work-related tasks")
                                (org-agenda-sorting-strategy
                                 '(category-up priority-down todo-state-up alpha-up))
                                (org-agenda-skip-function
                                 '(org-agenda-skip-entry-if 'regexp "\\* \\(DFRD\\|MAYB\\)"))))

                              ("Yx" "Deferred tasks"
                               tags "TODO=\"DFRD\""
                               ((org-agenda-overriding-header "Deferred tasks:")))

                              ("Yy" "Someday tasks"
                               tags "TODO=\"MAYB\""
                               ((org-agenda-overriding-header "Someday tasks:")))


                ("1"
                 tags-todo "+work"
                 ((org-agenda-view-columns-initially t)))
                ("2" tags-todo "+blog" ((org-agenda-view-columns-initially t)))
                ("3" tags-todo "+home" ((org-agenda-view-columns-initially t)))
                ("4" tags-todo "+phone" ((org-agenda-view-columns-initially t)))


                ;; Carsten
                ;; Is it listing only tasks *without* DEADLINE?
                ("x" "With deadline columns"
                 alltodo ""
                 ((org-agenda-overriding-columns-format "%65ITEM %DEADLINE")
                  (org-agenda-view-columns-initially t)))

            ("p" . "2. Process...")

                ("pr" "Tasks to refile (column view)"
                 org-tags-view ""
                 ((org-agenda-files (file-expand-wildcards "~/Personal/refile.org"))
                  (org-agenda-overriding-columns-format
                   "%65ITEM(Task) %4TODO %PRIORITY %20TAGS %14SCHEDULED %14DEADLINE %6Effort(Estim.)")
                  (org-agenda-view-columns-initially t)))

                ("pc" "Captured notes"
                 org-tags-view ""
                 ((org-agenda-files (file-expand-wildcards "~/Personal/capture.org"))
                  (org-agenda-overriding-columns-format
                   "%65ITEM(Task) %4TODO %PRIORITY %20TAGS %14SCHEDULED %14DEADLINE %6Effort(Estim.)")
                  (org-agenda-view-columns-initially t)))

            ("r" . "4. Review...")

;;*** TODO keyword

                ("r^" "Month Calendar"
                 (lambda (&rest ignore)
                   (cfw:open-org-calendar)))

                ;; list entries which are at some kind of completion state
                ;; (DONE or CANCELED), in all agenda files
                ("rc" "Completed Actions"
                 todo "DONE|CANX"
                 nil)

                ("r$" "Old Tasks to Archive"
                 todo "DONE|CANX|DFRD"
                 ((org-agenda-todo-ignore-scheduled nil)
                  (org-agenda-todo-ignore-deadlines nil)
                  (org-agenda-todo-ignore-with-date nil)))

                ("rx" "View Stuck Tasks"
                 ((stuck "" nil))
                 nil nil)

                ("rT" "TODO without SCHEDULED or DEADLINE"
                 tags-todo "TODO=\"TODO\"+SCHEDULED=\"\"+DEADLINE=\"\""
                 nil)

                ("rp" "Project List"
                 todo "PROJ"
                 ((org-agenda-todo-ignore-scheduled nil)
                  (org-agenda-todo-ignore-deadlines nil)
                  (org-agenda-todo-ignore-with-date nil)))

                ("rP" "Projects" tags-todo "project-DONE-CANX"
                 ((org-agenda-overriding-header "Projects (High Level)")
                  (org-agenda-sorting-strategy nil)))


                ("rR" "Review"
                 ((stuck "")
                  (agenda ""
                          ((org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'notdeadline))))
                  (agenda ""
                          ((org-agenda-span 'day)
                           (org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'deadline))))
                  (todo "PROJ"
                        ((org-agenda-sorting-strategy
                          '(todo-state-down priority-down))))
                  (todo "NEW|TODO|STRT"
                        ((org-agenda-sorting-strategy
                          '(todo-state-down priority-down))))
                  (todo "WAIT|DLGT")
                  (todo "MAYB"))
                 ((org-agenda-todo-ignore-with-date t)
                  (org-agenda-todo-ignore-deadlines t)
                  (org-agenda-time-grid nil)
                  (org-agenda-include-all-todo nil)
                  (org-deadline-warning-days 360)))

                ("rw" "Weekly review"   ;; Block weekly review
                 ((agenda "" ((org-agenda-span 'week)))
                  (stuck "")  ;; stuck projects
                  (todo "PROJ")  ;; review projects
                  (todo "WAIT|DFRD")))  ;; review waiting and deferred tasks

                ("rW" "Weekly Review"
                 ((agenda "" ((org-agenda-span 'week)))
                  (stuck "") ;; review stuck projects
                  (todo "PROJ") ;; review all projects
                  (todo "MAYB") ;; review someday/maybe items
                  (todo "WAIT"))) ;; review waiting items

                ("rA" "My custom agenda (= daily review?)"
                 ((agenda "" ((org-agenda-span 'day)))
                  (tags "PROJ-WAIT")
                  (tags-todo "WAIT")
                  (tags-todo "-MAYB")))

                ("rr" "Tasks to Refile"
                 tags "refile|capture"
                 ((org-agenda-overriding-header "Tasks to Refile")))

                ("c" "Clock Review"
                 ((agenda ""
                          ((org-agenda-overriding-header "Clocking Review")
                           (org-agenda-archives-mode t)
                           (org-agenda-span 'day)
                           (org-agenda-show-log 'clockcheck)
                           (org-agenda-clockreport-mode t)))))

            ("d" . "5. Do work...")

;;*** Calendar style views

                ;; from Matt Lundin
                ("dc" "Daily appointments" ;; skipping deadline and scheduled
                 agenda ""
                 ((org-agenda-span 'day)
                  (org-agenda-use-time-grid t)
                  (org-agenda-prefix-format " %i %-12:t ")
                  (org-agenda-include-all-todo nil)
                  (org-agenda-repeating-timestamp-show-all t)
                  (org-agenda-entry-types '(:timestamp :sexp))))

                ("dC" "Weekly appointments" ;; skipping deadline and scheduled
                 agenda ""
                 ((org-agenda-span 'week)
                  ;; (org-agenda-start-on-weekday 1)
                  (org-agenda-time-grid nil)
                  (org-agenda-prefix-format " %i %12:t ")
                  (org-agenda-include-all-todo nil)
                  (org-agenda-repeating-timestamp-show-all t)
                  (org-agenda-entry-types '(:timestamp :sexp))))

;;*** Other views

                ;; Today - daily tasks view
                ("dd" "Today"
                 ((agenda ""
                          ((org-agenda-span 'day)
                           (org-agenda-include-all-todo nil)))
                  (alltodo "" ((org-agenda-sorting-strategy '(todo-state-up))
                               (org-agenda-todo-ignore-with-date t)))))

                ("dn" "Now"
                 ((todo "STRT")
                  ((org-agenda-todo-ignore-with-date nil))))

                ;; Carsten
                ;; FIXME We don't see "timed" DEADLINE
                ("dD" "Due today"
                 agenda ""
                 ((org-agenda-span 'day)
                  (org-deadline-warning-days 0)
                  (org-agenda-skip-scheduled-if-deadline-is-shown t)
                  (org-agenda-skip-function
                   (lambda ()
                     (let* ((dl (org-entry-get nil "DEADLINE")))
                       (if (or (not dl)
                               (equal dl "")
                               (org-time> dl (org-time-today)))
                           (progn (outline-next-heading) (point))))))))

                ("ds" "Startup View"
                 ((agenda ""
                          ((org-agenda-span 3)
                           (org-deadline-warning-days 1)))
                  (agenda ""
                          ((org-agenda-time-grid nil)
                           (org-deadline-warning-days 365)
                           (org-agenda-entry-types '(:deadline))
                           (org-agenda-skip-entry-if 'scheduled)
                           (org-agenda-span 'day)
                           (org-agenda-overriding-header "Unscheduled upcoming deadlines:")))
                  (todo ""
                        '(org-agenda-overriding-header "Unscheduled No Deadline TODO: "))))

                ("dg" "GTD Task Dashboard"
                 ((agenda "" ((org-agenda-span 'day)
                              (org-agenda-start-on-weekday nil)
                              (org-agenda-entry-types '(:timestamp :sexp))
                              (org-agenda-overriding-header "Calendar")))
                  (agenda "" ((org-agenda-span 'day)
                              (org-agenda-time-grid nil)
                              (org-agenda-start-on-weekday nil)
                              (org-agenda-entry-types '(:deadline))
                              (org-agenda-overriding-header "Deadlines")
                              (org-agenda-sorting-strategy '(priority-down time-down))
                              (org-agenda-skip-function '(org-agenda-skip-entry-if 'todo 'done))))
                  (agenda "" ((org-agenda-span 'day)
                              (org-agenda-time-grid nil)
                              (org-agenda-start-on-weekday nil)
                              (org-agenda-entry-types '(:scheduled))
                              (org-agenda-overriding-header "Scheduled")
                              (org-agenda-sorting-strategy '(priority-down time-down))
                             (org-agenda-skip-function
                              '(org-agenda-skip-entry-if 'todo 'done))))
                  (todo "WAIT|DLGT"
                        ((org-agenda-sorting-strategy '(priority-down))
                         (org-agenda-overriding-header "Waiting")))
                  ;; FIXME: was "NEXT"
                  (todo "STRT" ((org-agenda-sorting-strategy '(priority-down effort-down))
                                (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline))
                                (org-agenda-overriding-header "Pending")))
                                ;;  ... Started Actions not being scheduled nor having a deadline
                  (todo "TODO" ((org-agenda-sorting-strategy '(priority-down effort-down))
                                (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline))
                                (org-agenda-overriding-header "Not started")))
                                ;;  ... Next Actions not being scheduled nor having a deadline
                  (todo "NEW" ((org-agenda-sorting-strategy '(priority-down effort-down))
                               (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline))
                               (org-agenda-overriding-header "New")))
                  (todo "PROJ" ((org-agenda-overriding-header "Active Projects"))))
                 ((org-agenda-format-date "%Y-%m-%d %a")
                  (org-agenda-start-with-clockreport-mode nil)))


                ("de" "Print reports (TODO)"
                 ;; See ThinkingRock examples
                 ((agenda ""
                          ((org-agenda-overriding-header "Scheduled TODO's")
                           (org-agenda-span 'week)
                           (org-agenda-skip-function
                            '(org-agenda-skip-entry-if 'regexp "habit"))
                           (org-agenda-sorting-strategy '(todo-state-up))
                           (org-agenda-prefix-format "%-7e")
                           (org-agenda-todo-keyword-format "%-10s")))
                  (tags-todo "thisweek"
                             ((org-agenda-overriding-iding-header "Unscheduled TODO's; also tasks (from which todo's were generated)")
                              (org-agenda-skip-function
                               '(org-agenda-skip-entry-if 'scheduled))
                              (org-agenda-prefix-format "%-7e")
                              (org-agenda-todo-keyword-format "%-10s")
                              (org-agenda-sorting-strategy '(todo-state-up)))))
                 ((org-agenda-remove-tags t))
                 ("C:\\home\\sva\\agenda.html"))


                ;; Past due
                ("dH" "Due in the next 3 days"
                 agenda ""
                 ((org-agenda-entry-types '(:deadline))
                  (org-deadline-warning-days 3)))

                ;; Toodledo
                ;; Hotlist: The hotlist contains tasks that are due soon as
                ;; well as tasks that have a high priority. This is a
                ;; convenient way to see your most important tasks at a
                ;; glance.
                ("dh" "TEST My Hot List!"
                 tags "DEADLINE<=\"<+2w>\"|PRIORITY=\"A\""
                 nil)
                ;; Hotlist Settings: At least a priority of '3 Top' or a due
                ;; date in the next 14 days.


                ;; checking tasks that are assigned to me in `worg-todo.org'
                ("dW"
                 tags "Owner=\"fni\"")


                ;; create a sparse tree (current buffer only) with all entries
                ;; containing the word `FIXME'
                ("df" "Sparse Tree with FIXME (Current Buffer)"
                 occur-tree "\\<FIXME\\>")

;;*** Printed agenda

                ;; exporting agenda views
                ("X"
                 agenda ""
                 ;; ((org-tag-faces nil))
                 (("~/agenda.html" "~/agenda.pdf")))

                ;; `c-x c-w' = write the agenda view to a file
                ("dp" "Call list"
                 tags-todo "phone"
                 ((ps-number-of-columns 1)
                  (ps-landscape-mode t)
                  (org-agenda-prefix-format " %-20:c [ ] " )
                  (org-agenda-with-colors nil)
                  (org-agenda-remove-tags t)

                  (org-agenda-write-buffer-name "Your Agenda View Name"))

                 ("~/calls.pdf"))

            ("v" . "6. More views...")

;;*** Priorities

                ;; priority levels
            ("v^" . "Priorities...")
                ("v^^" "Actions Grouped by Priority"
                 (;; Important things to do
                  (tags-todo "+PRIORITY=\"A\"")

                  ;; Medium important things to do
                  (tags-todo "+PRIORITY=\"B\"")

                  ;; Other things to do
                  (tags-todo "+PRIORITY=\"C\"")))

                ;; list only priority A tasks for the current day
                ("v^A" "Priority #A tasks for today"
                 agenda ""
                 ((org-agenda-skip-function
                   '(org-agenda-skip-entry-if 'notregexp "\\=.*\\[#A\\]"))
                  (org-agenda-span 'day)
                  (org-agenda-overriding-header
                   "Today's priority #A tasks: ")))

                ;; list priority A and B tasks for the current day
                ("v^B" "Priority #A and #B tasks for today"
                 agenda ""
                 ((org-agenda-span 'day)
                  (org-agenda-overriding-header
                   "Today's priority #A and #B tasks: ")
                  (org-agenda-skip-function
                   '(org-agenda-skip-entry-if 'regexp "\\=.*\\[#C\\]"))))

;;*** Tags

            ("v:" . "Contexts...")
                ("v:h" "Home realm" tags-todo "home")
                ("v:w" "Work realm" tags-todo "work")
                ("v:e" "Errands context" tags-todo "errands")
                ("v:c" "Computer context" tags-todo "computer")
                ("v:p" "Phone context" tags-todo "phone")
                ("v:m" "Mail context" tags-todo "mail")
                ("v:r" "Reading context" tags-todo "reading")
                ("v::" "Next/Started and Delegated/Waiting For Actions Grouped by Context"
                 (;; Next/Started Actions
                  (tags-todo "phone&TODO={TODO\\|STRT}")
                  (tags-todo "computer&TODO={TODO\\|STRT}")
                  (tags-todo "mail&TODO={TODO\\|STRT}")
                  (tags-todo "reading&TODO={TODO\\|STRT}")
                  (tags-todo "errands&TODO={TODO\\|STRT}")

                  ;; Delegated/Waiting For Actions
                  (tags-todo "phone&TODO={WAIT\\|DLGT}")
                  (tags-todo "computer&TODO={WAIT\\|DLGT}")
                  (tags-todo "mail&TODO={WAIT\\|DLGT}")
                  (tags-todo "reading&TODO={WAIT\\|DLGT}")
                  (tags-todo "errands&TODO={WAIT\\|DLGT}")))

;;*** Custom queries

            ("Q" . "Custom queries...") ;; give label to `Q'

              ("QS" . "SNCB...")

                ("QSb" tags "+sncb+Be")
                ("QSo" tags "+sncb+Oz")
                ("QSf" tags "+sncb+FNI")

                ("QSx" "Artemis with deadline columns"
                 alltodo ""
                 ((org-agenda-files
                   (file-expand-wildcards
                    "~/Projects/Transport/SNCB/admin/Timesheets/*.txt"))
                  (org-agenda-overriding-columns-format "%40ITEM %DEADLINE")
                  (org-agenda-view-columns-initially t)))

                ("QSA" "Artemis tags search"
                 org-tags-view ""
                 ((org-agenda-files
                   (file-expand-wildcards
                    "~/Projects/Transport/SNCB/admin/Timesheets/*.txt"))))

                ("Qs" "Scorpios tasks"
                 alltodo ""
                 ((org-agenda-files
                   '("~/Personal/Scorpios.org"))))

            ("S" . "7. Search...")

                ("Ss" "Search for keywords (extra files)"
                 search ""
                 ((org-agenda-text-search-extra-files my/org-search-extra-files)))
                 ;; FIXME Add (agenda-archives)

                ("Sw" "Website search"
                 search ""
                 ((org-agenda-files
                   (file-expand-wildcards "~/Public/www.mygooglest.com/source/fni/*.txt"))))

                ))

(defun my-gtd-frame ()
  (interactive)
  (save-excursion)
  (make-frame '(
     (name                      . "gtd")
     (active-alpha              . 0.75)
     (inactive-alpha            . 0.8)
     (top                       . 20)
     (left                      . 20)
     (width                     . 80)
     (height                    . 40)
     ;; (font . "-Adobe-Courier-Medium-R-Normal--18-180-75-75-M-110-ISO8859-1")
     ))
  (select-frame-by-name "gtd")
  ;; (toggle-fullscreen)
  ;; (catch 'exit
  ;;   (org-agenda-goto-today))
  (delete-other-windows)
  (split-window-horizontally)
  (other-window 1)
  (catch 'exit
    (org-batch-agenda "work"))
)

;;** 10.7 (info "(org)Exporting Agenda Views")

        ;; 10.7 alist of variable/value pairs that should be active during
        ;; agenda export
        (setq org-agenda-exporter-settings
              '((ps-number-of-columns 1)
                (ps-landscape-mode t)
                (htmlize-output-type 'css)))

;;** 10.8 (info "(org)Agenda column view")

        ;; 10.8 default column format, if no other format has been defined
        (setq org-columns-default-format
              "%1BLOCKED %4TODO %CATEGORY %5Effort{:} %50ITEM %20TAGS %21ALLTAGS")
              ;; "%65ITEM(Task) %DEADLINE %PRIORITY %6CLOCKSUM(Spent) %6Effort(Estim.){:}")

(setq org-columns-default-format "%60ITEM(Details) %5PRIORITY(PRIO) %12SCHEDULED(Scheduled) %15TAGS(Context) %7TODO(To Do) %6CLOCKSUM %5Effort(Effort){:} ")

        ;; DUPLICATE Obey `eval' variables -- RISKY!
        (setq enable-local-eval t)

        ;; highlight current line (may bring some slowness)
        (add-hook 'org-agenda-mode-hook 'hl-line-mode)

;;** Unsorted

        ;; don't search headline for a time-of-day
        (setq org-agenda-search-headline-for-time nil)

        ;; clockreport-mode in a newly created agenda window
        (setq org-agenda-start-with-clockreport-mode t)

        ;; personal settings...
        ;; (defvar icon-dir "~/emacs/site-lisp/Pictures/")
        ;; (setq org-agenda-category-icon-alist ...)

;;* 11 (info "(org)Markup")

        ;; add a face to #+begin_quote and #+begin_verse blocks
        (setq org-fontify-quote-and-verse-blocks t)

        ;; 11.1 hide the emphasis marker characters
        (setq org-hide-emphasis-markers t) ;; impact on table alignment!

        ;; 11.7 don't interpret "_" and "^" for export
        (setq org-export-with-sub-superscripts nil)

        ;; 11.7 convert LaTeX fragments to images when exporting to HTML
        (setq org-export-with-LaTeX-fragments t)

;; LaTeX back-end for Org generic export engine
(require 'org-e-latex)

;; To test it, run
;;   M-: (org-export-to-buffer 'e-latex "*Test e-LaTeX*") RET

;;* 12 (info "(org)Exporting")

        ;; execute buffer when exporting it (see some thread with Eric Schulte,
        ;; end of December 2010)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;        (add-hook 'org-export-first-hook 'org-babel-execute-buffer)


        ;; ;; 12.1 add the unbreakable space as allowed character after an
        ;; ;; emphasis string, and modify the maximum number of newlines
        ;; ;; allowed in an emphasis
        ;; (setq org-emphasis-regexp-components [...])

;;** 12.2 (info "(org)Export options")

        (section "12.2 (org)Export options")

        ;; include priority cookies in export
        (setq org-export-with-priority t)

        (defun my/org-switch-language ()
          "Switch language for Org file, if a `#+LANGUAGE:' meta-tag is
        on top 8 lines."
          (save-excursion
            (goto-line (1+ 8))
            (if (re-search-backward "#\\+LANGUAGE: +\\([A-Za-z_]*\\)" 1 t)
                (ispell-change-dictionary (match-string 1)))))

        ;; ;; guess language
        ;; (add-hook 'org-mode-hook 'my/org-switch-language)

        ;; don't skip all text before the first headline when exporting
        (setq org-export-skip-text-before-1st-heading nil)

;;** 12.5 (info "(org)HTML export")

        ;; 12.5.9 turn inclusion of the default CSS style off
        (setq org-export-html-style-include-default nil)

        ;; format for the HTML postamble
        (setq org-export-html-postamble
              "  <div id=\"copyright\">\n    &copy; %d %a\n  </div>")

        ;; ;; TEMP For testing purpose
        ;; (setq org-export-html-style
        ;;       "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///c:/home/sva/src/pirilampo/org/css/worg-leuven.css\">")
        ;; (setq org-export-html-validation-link "")

;;** 12.6 (info "(org)LaTeX and PDF export")

        (section "12.6 (org)LaTeX and PDF export")

        ;; LaTeX exporter for Org mode
        (eval-after-load "org-latex"
          '(progn

        ;; expressions to be used to convert emphasis fontifiers for LaTeX
        ;; export
        (setq org-export-latex-emphasis-alist ;; remove the strike-through emphasis
              '(("*" "\\textbf{%s}" nil)
                ("/" "\\emph{%s}" nil)
                ("_" "\\underline{%s}" nil)
                ("=" "\\protectedtexttt" t)
                ("~" "\\verb" t)))

        (add-to-list 'org-export-latex-emphasis-alist
                     '("@" "\\alert{%s}" nil))

        (defun my/change-pdflatex-program ()
          "When exporting an Org document to LaTeX, automatically run XeLaTeX,
        if asked."

          ;; default
          (setq org-latex-to-pdf-process
                ;; use latexmk (if installed with LaTeX)
                (if (executable-find "latexmk")
                    '("latexmk -pdf %f")
                  '("pdflatex -interaction=nonstopmode -output-directory=%o %f"
                    "pdflatex -interaction=nonstopmode -output-directory=%o %f"
                    "pdflatex -interaction=nonstopmode -output-directory=%o %f")))

          (when (string-match "^#\\+LATEX_CMD: xelatex" (buffer-string))
            (setq org-latex-to-pdf-process
                  (if (executable-find "latexmk")
                      '("latexmk -pdf -pdflatex=xelatex %f")
                    '("xelatex -interaction=nonstopmode -output-directory=%o %f"
                      "xelatex -interaction=nonstopmode -output-directory=%o %f"
                      "xelatex -interaction=nonstopmode -output-directory=%o %f")))))

        (add-hook 'org-export-latex-after-initial-vars-hook
                  'my/change-pdflatex-program)

        ;; tell org to use `listings' (instead of `verbatim') for source code
        (setq org-export-latex-listings t)

        ;; 12.6.2
        (when (boundp 'org-export-latex-default-packages-alist)

          ;; include the `listings' package for fontified source code
          (add-to-list 'org-export-latex-default-packages-alist '("" "listings") t)

          ;; include the `xcolor' package for colored source code
          (add-to-list 'org-export-latex-default-packages-alist '("" "xcolor") t))

        (defun my/change-pdflatex-packages ()
          "When exporting an Org document to LaTeX, automatically select the
        LaTeX packages to include (depending on PDFLaTeX vs XeLaTeX)."

          ;; unconditionally remove `inputenc' from all the default packages
          (setq org-export-latex-default-packages-alist
                (delete '("AUTO" "inputenc" t)
                        org-export-latex-default-packages-alist))

          ;; unconditionally remove `fontenc' from all the default packages
          (setq org-export-latex-default-packages-alist
                (delete '("T1" "fontenc" t)
                        org-export-latex-default-packages-alist))

          ;; unconditionally remove `textcomp' from all the default packages
          (setq org-export-latex-default-packages-alist
                (delete '("" "textcomp" t)
                        org-export-latex-default-packages-alist))

          (if (string-match "^#\\+LATEX_CMD: xelatex" (buffer-string))
              ;; packages to include when XeLaTeX is used
              (setq org-export-latex-packages-alist
                    '(("" "fontspec" t)
                      ("" "xunicode" t)))

            ;; packages to include when PDFLaTeX is used
            (setq org-export-latex-packages-alist
                  '(("AUTO" "inputenc" t)
                    ("T1" "fontenc" t)
                    ("" "textcomp" t)))))

        (add-hook 'org-export-latex-after-initial-vars-hook
                  'my/change-pdflatex-packages)

        (setq org-export-latex-inputenc-alist '(("utf8" . "utf8x")))

        ;; 12.6.5 default option for images
        (setq org-export-latex-image-default-option "width=.8\\linewidth")

        ;; 12.6.5 default position for LaTeX figures
        (setq org-latex-default-figure-position "!htbp")

        ;; 12.6.6 Beamer class export
        (add-to-list 'org-export-latex-classes
                     '("beamer"
                       "%\\usepackage{atbegshi}% incompatibility between hyperref and beamer
\\documentclass{beamer}
\\usepackage{etex}% too many packages (for PDFTeX)\n"
                       org-beamer-sectioning))

        (setq org-beamer-frame-default-options "")

        ;; default title of a frame containing an outline
        (setq org-beamer-outline-frame-title "Agenda")
))

;;** Not sorted

        (section "Not sorted")

        ;; markup for tags, as a printf format
        (setq org-export-latex-tag-markup "\\hfill{}\\fbox{%s}")
        ;; XXX source of "undefined control sequence"?

        ;; format string for links with unknown path type
        (setq org-export-latex-link-with-unknown-path-format "\\colorbox{red}{%s}")


        ;; turn Org blocks into LaTeX environments and HTML divs
        ;; (markup in environments in LaTeX export, or giving LaTeX attributes
        ;; to sections in export)
        (try-require 'org-special-blocks)
        ;; FIXME This was responsible of problems when used with Org-babel
        ;; (`\LaTeX{}' environments are created around verbatim environments)



        (setq org-export-copy-to-kill-ring nil)

        ;;
        (setq org-export-kill-product-buffer-when-displayed t)



;;      (require 'org-odt)
        ;; (eval-after-load "org-odt"
        ;;   '(setq org-export-odt-preferred-output-format "odt"))

;;* 13 (info "(org)Publishing")

        ;; ;; publish related Org mode files as a website
        ;; (try-require 'org-publish)

(setq org-publish-list-skipped-files nil)

        ;; ;; fontify what is treated specially by the exporters
        ;; (setq org-highlight-latex-fragments-and-specials t)

        ;; 13.1.5 don't include the JavaScript snippets in exported HTML files
        (setq org-export-html-style-include-scripts nil)

        ;; XML encoding
        (setq org-export-html-xml-declaration
              '(("html" . "<!-- <xml version=\"1.0\" encoding=\"%s\"> -->")
                ("was-html" . "<?xml version=\"1.0\" encoding=\"%s\"?>")
                ("php" . "<?php echo \"<?xml version=\\\"1.0\\\" encoding=\\\"%s\\\" ?>\"; ?>")))

        ;; output type to be used by htmlize when formatting code snippets
        (setq org-export-htmlize-output-type 'css)
        ;; To get a start for your css file, use the command
        ;; `M-x org-export-htmlize-generate-css' to extract class definitions.

        ;; (setq org-export-htmlized-org-css-url "style.css")

        ;; ;; 13.1.5 export all drawers (including properties)
        ;; (setq org-export-with-drawers t)


        ;; coding system for HTML export, defaults to
        ;; `buffer-file-coding-system'
        (setq org-export-html-coding-system 'utf-8)


        (setq org-export-creator-info nil)

        ;; ;; 13.2 always publish all files (do not use timestamp checking for
        ;; ;; skipping unmodified files)
        ;; (setq org-publish-use-timestamps-flag nil)

        ;; How to create web page by Emacs and Muse?
        ;; http://www.xshi.org/notes/WebPage.html

        ;; (define-key muse-mode-map
        ;;   (kbd "C-c C-c") 'ywb-muse-preview-source)
        ;; (define-key muse-mode-map
        ;;   (kbd "C-c C-j") 'ywb-muse-preview-html)
        ;; (define-key muse-mode-map
        ;;   (kbd "C-c C-m") 'ywb-muse-preview-with-w3m)

        ;; (defun tidy-do ()
        ;;   "Run the HTML Tidy program on the current buffer."
        ;;   (interactive)
        ;;   (shell-command-on-region (point-min) (point-max)
        ;;                            (concat "tidy"
        ;;                                    " -config ~/.tidyrc"
        ;;                                    " --error-file ./temp-tidy-errors") t)
        ;;   (delete-file "./temp-tidy-errors")
        ;;   (message "Buffer tidy'ed"))

        ;; ;; TODO Check that tidy is in PATH
        ;; ;; run in the buffer to be published
        ;; (eval-after-load "tidy"
        ;;   '(progn (add-hook 'muse-after-publish-hook 'tidy-do)))

        ;; How to preview in a browser?
        ;;
        ;; Press `C-c C-v' (`browse-url-of-buffer'). You can also get a
        ;; textual preview by pressing `C-c tab' (`sgml-tags-invisible'),
        ;; which will hide all the tags. Press `C-c tab' again to show tags.

        ;; You can create and publish a blog with Org mode
        ;; http://dto.freeshell.org/e/org-blog.el

        ;; 13.4 force publishing all files
        (defun org-publish-all-force ()
          (interactive)
          (org-publish-all t))

;;* 14 (info "(org)Working With Source Code")

        ;; literate programming and reproducible research

        ;; make the images in the Emacs buffer automatically refresh after
        ;; execution
        (add-hook 'org-babel-after-execute-hook 'org-display-inline-images)


        ;; command used to invoke a shell
        (setq org-babel-sh-command "bash")

        ;; use plain old syntax (instead of `$(...)') for Cygwin
        (setq org-babel-sh-var-quote-fmt
              "`cat <<'BABEL_TABLE'\n%s\nBABEL_TABLE\n`")

;;** 14.2 (info "(org)Editing source code")

        (section "14.2 (org)Editing source code")

        ;; mapping between languages (listings in LaTeX) and their major mode
        ;; (in Emacs): see `org-src-lang-modes'

        ;; display the source code edit buffer in the current window, keeping
        ;; all other windows
        (setq org-src-window-setup 'reorganize-frame)
        (setq org-src-window-setup 'current-window)

        ;; FIXME Bind this to the correct keys
        (defun my/org-babel-expand-src-block ()
          (interactive)
          (let ((org-src-window-setup 'reorganize-frame))
            (org-babel-expand-src-block)))

        ;; indent the content of a source code block
        (setq org-edit-src-content-indentation 2)

        ;; fontify code in code blocks
        (setq org-src-fontify-natively t)

        ;; preserve spaces and `tab' characters in source code blocks
        (setq org-src-preserve-indentation t)

        ;; same effect for `tab' as in the language major mode buffer
        (setq org-src-tab-acts-natively t)

        ;; allow comment region in the code edit buffer (according to language)
        (defun my/org-comment-dwim (&optional arg)
          (interactive "P")
          (or (org-babel-do-key-sequence-in-edit-buffer (kbd "M-;"))
              (comment-dwim arg)))

        ;; make `C-c C-v C-x M-;' more convenient
        (define-key org-mode-map
          (kbd "M-;") 'my/org-comment-dwim)

        ;; allow indent region in the code edit buffer (according to language)
        (defun my/org-indent-region (&optional arg)
          (interactive "P")
          (or (org-babel-do-key-sequence-in-edit-buffer (kbd "C-M-\\"))
              (indent-region arg)))

        ;; make `C-c C-v C-x C-M-\' more convenient
        (define-key org-mode-map
          (kbd "C-M-\\") 'my/org-indent-region)

        ;; prevent auto-filling in src blocks
        (setq org-src-prevent-auto-filling t)

        (global-set-key (kbd "C-c C-v C-d") 'org-babel-demarcate-block)


        ;; view just the source-code blocks within the current Babel file
        ;; (something logically equivalent to "tangle", but without creating a
        ;; separate file)

        (defvar only-code-overlays nil "Overlays hiding non-code blocks.")
        (make-variable-buffer-local 'only-code-overlays)

        (defun hide-non-code ()
          "Hide non-code-block content of the current Org-mode buffer."
          (interactive)
          (add-to-invisibility-spec '(non-code))
          (let (begs ends)
            (save-excursion
              (goto-char (point-min))
              (while (re-search-forward org-babel-src-block-regexp nil t)
                (push (match-beginning 5) begs)
                (push (match-end 5)       ends))
              (map 'list (lambda (beg end)
                           (let ((ov (make-overlay beg end)))
                             (push ov only-code-overlays)
                             (overlay-put ov 'invisible 'non-code)))
                   (cons (point-min) (reverse ends))
                   (append (reverse begs) (list (point-max)))))))

        (defun show-non-code ()
          "Show non-code-block content of the current Org-mode buffer."
          (interactive)
          (mapc 'delete-overlay only-code-overlays))

;;** 14.5 (info "(org)Evaluating code blocks")

        (section "14.5 (org)Evaluating code blocks")

        ;; I don't want to execute code blocks with `C-c C-c' (evaluate code
        ;; block only with `C-c C-v e')
        (setq org-babel-no-eval-on-ctrl-c-ctrl-c t)

        ;; languages for which Babel will raise literate programming errors
        ;; when noweb references can not be resolved.
        (add-to-list 'org-babel-noweb-error-langs "emacs-lisp")

;;** 14.6 (info "(org)Library of Babel")

        (section "14.6 (org)Library of Babel")

        ;; load the *named* code blocks defined in Org-mode files into the
        ;; library of babel (global `org-babel-library-of-babel' variable)
        (org-babel-lob-ingest
         (concat (file-name-directory (locate-library "org.el"))
                 "../contrib/babel/library-of-babel.org"))

        (org-babel-lob-ingest "~/src/org-config/mc-lob.org")
        (org-babel-lob-ingest "~/src/org-config/pfi-lob.org")
        (org-babel-lob-ingest "~/src/org-config/fni-lob.org")

(setq org-babel-exp-code-template
 "``` %lang %name
%body
```")

(setq org-babel-exp-code-template "#+BEGIN_SRC %lang%flags\n%body\n#+END_SRC")


;; keep lower-case
(setq org-babel-results-keyword "results")

;; keep lower-case (easy templates)
(setq org-structure-template-alist
      '(("s" "#+begin_src ?\n\n#+end_src" "<src lang=\"?\">\n\n</src>")
        ("e" "#+begin_example\n?\n#+end_example" "<example>\n?\n</example>")
        ("q" "#+begin_quote\n?\n#+end_quote" "<quote>\n?\n</quote>")
        ("v" "#+begin_verse\n?\n#+end_verse" "<verse>\n?\n</verse>")
        ("c" "#+begin_center\n?\n#+end_center" "<center>\n?\n</center>")
        ("l" "#+begin_latex\n?\n#+end_latex" "<literal style=\"latex\">\n?\n</literal>")
        ("L" "#+latex: " "<literal style=\"latex\">?</literal>")
        ("h" "#+begin_html\n?\n#+end_html" "<literal style=\"html\">\n?\n</literal>")
        ("H" "#+html: " "<literal style=\"html\">?</literal>")
        ("a" "#+begin_ascii\n?\n#+end_ascii")
        ("A" "#+ascii: ")
        ("i" "#+index: ?" "#+index: ?")
        ("I" "#+include: %file ?" "<include file=%file markup=\"?\">")))

;;** 14.7 (info "(org)Languages")

        (section "14.7 (org)Languages")

        ;; customize the `org-babel-load-languages' variable to enable support
        ;; for languages which can be evaluated in Org mode buffers

        ;; FIXME Test executable-find (of Rterm, gnuplot, ruby, etc.) before
        ;; setting language to yes...
        (when (fboundp 'org-babel-do-load-languages)
          (org-babel-do-load-languages
           'org-babel-load-languages
           '(
             (C . nil)
             (R . t) ;; requires R and ess-mode
             (awk . t)
             (calc . t)
             (ditaa . t) ;; sudo aptitude install openjdk-6-jre
             (dot . t)
             (emacs-lisp . t)
             (gnuplot . t) ;; requires gnuplot-mode
             (haskell . nil)
             (latex . t)
             (ledger . t) ;; requires ledger
             (ocaml . nil)
             (octave . nil)
             (org . t)
             (perl . nil)
             (python . t)
             (ruby . nil)
             (screen . nil)
             (sh . t)
             (sql . t)
             (sqlite . nil))))
        ;; `screen' offers support for interactive terminals. Mostly shell
        ;; scripts. Heavily inspired by `eev'
        ;;
        ;; Eric Schulte believes screen has more of a focus on sustained
        ;; interaction with an interactive terminal

        ;; ESS: Emacs Speaks Statistics
        (when (try-require 'ess-site-XXX)

          ;; don't request the process directory each time R is run
          (setq ess-ask-for-ess-directory nil)

          ;; name of the ESS process associated with the current buffer
          (setq ess-local-process-name "R")

          ;; Use `S-RET' (shift-return) to split window & launch R (if not
          ;; running), execute highlighted region (if R running & area
          ;; highlighted), or execute current line (and move to next line,
          ;; skipping comments). Nice.
          ;;
          ;; See http://www.emacswiki.org/emacs/EmacsSpeaksStatistics,
          ;; FelipeCsaszar. Adapted to spilit vertically instead of
          ;; horizontally.

          ;; XXX This should be useless, at least if R code is well written
          ;; inside Org documents!
          (defun my-ess-start-R ()
            (interactive)
            (if (not (member "*R*"
                             (mapcar (function buffer-name) (buffer-list))))
                (progn
                  (delete-other-windows)
                  (setq w1 (selected-window))
                  (setq w1name (buffer-name))
                  (setq w2 (split-window w1 nil t))
                  (R)
                  (set-window-buffer w2 "*R*")
                  (set-window-buffer w1 w1name))))

          (defun my-ess-eval ()
            (interactive)
            (my-ess-start-R)
            (if (and transient-mark-mode mark-active)
                (call-interactively 'ess-eval-region)
              (call-interactively 'ess-eval-line-and-step)))

          (add-hook 'ess-mode-hook
                    '(lambda()
                       (local-set-key (kbd "<S-return>") 'my-ess-eval)))

          (add-hook 'inferior-ess-mode-hook
                    '(lambda()
                       (local-set-key (kbd "<C-up>") 'comint-previous-input)
                       (local-set-key (kbd "<C-down>") 'comint-next-input)))

          ;; tooltip with some information about the R object at point
          ;; (invoked by `C-c C-g'). See
          ;; http://www.kieranhealy.org/blog/archives/2010/02/16/easily-display-information-about-r-objects-in-emacsess/
          (try-require 'ess-R-object-tooltip))

        ;; ;; add default arguments to use when evaluating a source block
        ;; (add-to-list 'org-babel-default-header-args '(:results . "wrap"))

;;** (info "(emacs-goodies-el)htmlize")

        (section "(emacs-goodies-el)htmlize")

        ;; HTML-ize font-lock buffers
        (autoload 'htmlize-buffer "htmlize"
          "Convert BUFFER to HTML, preserving colors and decorations." t)
        (autoload 'htmlize-region "htmlize"
          "Convert the region to HTML, preserving colors and decorations." t)
        (autoload 'htmlize-file "htmlize"
          "Load FILE, fontify it, convert it to HTML, and save the result." t)

        (eval-after-load "htmlize"
          '(progn
             ;; Emacs 23 users: in order to avoid "Invalid face" errors, you
             ;; need to use the version made available by Carsten Dominik in
             ;; `org-mode/contrib/lisp' directory

             ;; output type of generated HTML
             (setq htmlize-output-type 'css)

             ;; override output type `inline-css' used for htmlizing a region
             (defun htmlize-region-for-paste (beg end)
               "Htmlize the region and return just the HTML as a string.
           This forces the `css' style and only returns the HTML body, but
           without the BODY tag. This should make it useful for inserting
           the text to another HTML buffer."
               (let* ((htmlize-output-type 'css)  ; was `inline-css'
                      (htmlbuf (htmlize-region beg end)))
                 (unwind-protect
                     (with-current-buffer htmlbuf
                       (buffer-substring
                        (plist-get htmlize-buffer-places 'content-start)
                        (plist-get htmlize-buffer-places 'content-end)))
                   (kill-buffer htmlbuf))))

             ;; charset declared by the resulting HTML documents
             (setq htmlize-html-charset "utf-8")

             ;; non-ASCII characters (codes in the 128-255 range) are copied to
             ;; HTML without modification -- if your HTML is in Unicode
             (setq htmlize-convert-nonascii-to-entities nil)

             ;; key binding
             (global-set-key (kbd "M-P") 'htmlize-buffer)))

        ;; quick print preview (to Web browser) with `htmlize-view-buffer'
        (GNUEmacs
         (autoload 'htmlize-view-buffer "htmlize-view" nil t)

         (global-set-key (kbd "C-c C-e b") 'htmlize-view-buffer)

         ;; view current buffer as html in web browser
         (eval-after-load "htmlize-view"

           ;; add "Quick Print" entry to file menu
           '(htmlize-view-add-to-files-menu)))

        ;; Now, you can print from the browser in (complete) Unicode,
        ;; using your system's capabilities

;;* 15 (info "(org)Miscellaneous")

        ;; from Dan Davison
        (defun my/switch-to-org-scratch ()
          "Switch to a temp Org buffer. If the region is active, insert it."
          (interactive)
          (let ((contents
                 (and (region-active-p)
                      (buffer-substring (region-beginning)
                                        (region-end)))))
            (find-file "/tmp/org-scratch.org")
            (if contents (insert contents))))


        (setq org-x-backends '(ox-org ox-redmine))

;;** 15.3 (info "(org)Speed keys")

        (section "15.3 (org)Speed keys")

        (setq org-use-speed-commands t)

;;** 15.4 (info "(org)Code evaluation security") issues

        (section "15.4 (org)Code evaluation security issues")

        ;; don't be prompted on every code block evaluation
        (setq org-confirm-babel-evaluate nil)

;;** 15.6 Summary of (info "(org)In-buffer settings")

        (section "15.6 Summary of (org)In-buffer settings")

        ;; ;; 15.6 hide the first N-1 stars in a headline
        ;; (setq org-hide-leading-stars t)

        ;; 15.6 don't skip even levels for the outline
        (setq org-odd-levels-only nil)

;;** 15.8 A (info "(org)Clean view")

        ;; ;;??? change the face of a headline (as an additional information) if
        ;; ;; it is marked DONE (to face `org-headline-done')
        ;; (setq org-fontify-done-headline t)

;;** 15.10 (info "(org)Interaction")

        (section "15.10 (org)Interaction")

        ;; extension of Imenu
        (when (and
               ;; `org-babel' has been loaded
               (fboundp 'org-babel-execute-src-block)

               ;; `imenu' has been loaded
               (fboundp 'try-to-add-imenu))

          (try-require 'imenu+)

          (setq org-src-blocks-imenu-generic-expression
                `(("Snippets" ,org-babel-src-name-w-name-regexp 2)))

          (add-hook 'org-mode-hook
                    (lambda ()
                      (setq imenu-generic-expression
                            org-src-blocks-imenu-generic-expression))))



        ;; alternative to imenu
        (defun dan/find-in-buffer ()
          (interactive)
          (let ((targets
                 `(("<named src blocks>" . ,org-babel-src-name-regexp)
                   ("<src block results>" . ,org-babel-result-regexp))))
            (occur
             (cdr
              (assoc
               (completing-read "Find: " (mapcar #'car targets)) targets)))
            (other-window 1)))






        ;; allow YASnippet to do its thing in Org files
        ;; (from http://orgmode.org/worg/org-faq.php)
        (when (fboundp 'yas/expand)
          ;;! make sure you initialise YASnippet *before* Org mode

          (defun yas/org-very-safe-expand ()
            (let ((yas/fallback-behavior 'return-nil))
              (yas/expand)))

          (add-hook 'org-mode-hook
                    (lambda ()
                      ;; YASnippet (using the new org-cycle hooks)
                      (set (make-local-variable 'yas/trigger-key) (kbd "tab"))
                      (add-to-list 'org-tab-first-hook
                                   'yas/org-very-safe-expand)
                      (define-key yas/keymap (kbd "tab") 'yas/next-field))))

;;** Unsorted

        (section "Unsorted")

        ;; some commands act upon headlines in the active region
        (setq org-loop-over-headlines-in-active-region 'start-level)

        ;; Org refcard browser
        (when (try-require 'anything-orgcard)
          (define-key org-mode-map (kbd "M-4") 'aoc:anything-orgcard))

        ;; define special characters
        ;; (name latex math-p html ascii latin1 utf8)
        (add-to-list 'org-entities-user ;; \definecolor{checkmark}{HTML}{1FAC21}
                     '("ok" "{\\color{checkmark}\\ding{51}}" nil "<font color='green'>&#x2714;</font>" "OK" "OK" "✔"))
        (add-to-list 'org-entities-user ;; \usepackage{pifont}
                     '("nok" "{\\color{red}\\ding{55}}" nil "<font color='red'>&#x2718;</font>" "NOK" "NOK" "✘"))
        (add-to-list 'org-entities-user
                     '("omacr" "\\={o}" nil "&#333;" "o" "o" "ō"))

        ;; warn about deprecated features since version 7.8
        (add-hook 'org-mode-hook
                  (lambda ()
                    (save-excursion
                      (goto-char (point-min))
                      (when (re-search-forward (org-make-options-regexp
                                                '("BABEL")) nil t)
                        (display-warning 'org-babel
                                         (format "This file (%s) contains a \"#+BABEL:\" line."
                                                 (buffer-name (current-buffer)))
                                         :warning)))))

        (add-hook 'org-mode-hook
                  (lambda ()
                    (save-excursion
                      (goto-char (point-min))
                      (let ((n (count-matches "#\\+\\(srcname\\|source\\):")))
                      (when (> n 0)
                        (display-warning 'org-babel
                                         (format (concat "This file (%s) contains %s \"#+src"
                                                         "name:\" or \"#+"
                                                         "source:\" lines.")
                                                 ;; trick to avoid srcname to
                                                 ;; be found in the Org file
                                                 ;; itself which tangles
                                                 ;; `.emacs' file
                                                 (buffer-name (current-buffer))
                                                 n)
                                         :warning))))))

        (add-hook 'org-mode-hook
                  (lambda ()
                    (save-excursion
                      (goto-char (point-min))
                      (let ((n (count-matches "#\\+\\(\\(src\\)?name\\|source\\):.*=")))
                        (when (> n 0)
                          (display-warning 'org-babel
                                           (format "This file (%s) contains %s deprecated variable assignments."
                                                   (buffer-name (current-buffer))
                                                   n)
                                           :warning))))))

        (defun my/org-propertyze-babel-line ()
          "Play me as many times as needed..."
          (interactive)
          ;; (goto-char (point-min))
          ;; (search-forward "#+BABEL:")
          (search-forward-regexp ":")
          (delete-backward-char 2)
          (insert "\n#+PROPERTY:  "))

        ;; function to update Org-mode buffers to use the new code block
        ;; syntax (switch between versions 7.7 and 7.8)
        (defun update-org-buffer ()
          "Update an Org-mode buffer to the new data, code block and call line syntax."
          (interactive)
          (save-excursion
            (flet ((to-re (lst) (concat "^[ \t]*#\\+" (regexp-opt lst t)
                                        "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"))
                   (update (re new)
                           (goto-char (point-min))
                           (while (re-search-forward re nil t)
                             (replace-match new nil nil nil 1))))
              (let ((old-re (to-re '("RESULTS" "DATA" "SRCNAME" "SOURCE")))
                    (lob-re (to-re '("LOB")))
                    (case-fold-search t))
                (update old-re "name")
                (update lob-re "call")))))

        (defun my/org-check-property-line ()
          "Check the syntax of #+PROPERTY lines."
          (interactive)
          (goto-char (point-min))
          (search-forward "#+PROPERTY:" nil t)
          (if (looking-at " *:")
              (display-warning 'org-babel
                               (format "This file (%s) contains a syntax error on #+PROPERTY line: abusive colon."
                                       (buffer-name (current-buffer)))
                               :warning)))

        (add-hook 'org-mode-hook 'my/org-check-property-line)

        (add-hook 'org-mode-hook
                  (lambda ()
                    (save-excursion
                      (goto-char (point-min))
                      (if (search-forward "#+AUTHOR:" nil t)
                          (unless (search-forward "#+Time-stamp:" nil t)
                            (display-warning 'org-babel
                                             (format "This file (%s) does not contain a \"#+Time-stamp:\" line -- while #+AUTHOR found."
                                                     (buffer-name (current-buffer)))
                                             :warning))))))

        ;; use `C-c C-x f' to add a footnote, to go back to the message
        ;; *and* to go to a footnote
        (global-set-key (kbd "C-c C-x f") 'org-footnote-action)

        ;; prefer the future for incomplete dates
        (setq org-read-date-prefer-future 'time)

        ;; ;; advise `org-read-date' to bury the calendar buffer after selecting
        ;; ;; a date, so it is out of the way
        ;; (defadvice org-read-date
        ;;   (after abl/bury-calendar-after-org-read-date
        ;;          (&optional with-time to-time from-string prompt
        ;;          default-time default-input) protect)
        ;;   "Bury the *Calendar* buffer after reading a date."
        ;;   (bury-buffer "*Calendar*"))
        ;; (ad-activate 'org-read-date)


        ;; don't pad tangled code with newlines
        (setq org-babel-tangle-pad-newline nil)

        ;; how to combine blocks of the same name during tangling
        (setq org-babel-tangle-named-block-combination 'append)


        ;; minimum number of lines for output *block* (placed in a
        ;; #+begin_example...#+end_example) vs output marked as literal by
        ;; inserting a *colon* at the beginning of the lines
        (setq org-babel-min-lines-for-block-output 2)

        ;; insert an inline task (independent of outline hierarchy)
        (when (try-require 'org-inlinetask) ;; needed

          ;; ;; export inline tasks
          ;; (setq org-inlinetask-export t) ;; default

          ;; initial state (TODO keyword) of inline tasks
          (setq org-inlinetask-default-state "TODO")

          ;; templates for inline tasks in various exporters
          (setq org-inlinetask-export-templates
                '((html "<div class=\"%s %s\"><p><b>%s%s</b><br/></p>%s</div>"
                        '("inlinetask"
                          (replace-regexp-in-string ":" " " tags)
                          (unless (eq todo "")
                            (format "<span class=\"%s %s\">%s%s</span> "
                                    class todo todo priority))
                          heading content))

                  ;; this requires the `todonotes' package
                  (latex "\\todo[inline,caption={}]{\\textbf{\\textsf{%s %s}}\\\\ %s}"
                         '((unless (eq todo "")
                             (format "\\textsc{%s%s}" todo priority))
                           heading content))

                  (ascii "     -- %s%s%s"
                         '((unless (eq todo "")
                             (format "%s%s " todo priority))
                           heading
                           (unless (eq content "")
                             (format "\n         ¦ %s"
                                     (mapconcat 'identity
                                                (org-split-string content "\n")
                                                "\n         ¦ "))))))))

;; FIXME: export templates for inline tasks
;; (defun org-latex-format-inlinetask (heading content
;; &optional todo priority tags)
;; "Generate format string for inlinetask export templates for latex."
;; (let ((color (cond ((string-match "QnA" tags) "color=blue!40")
;; ((string-match "Qn" tags) "color=yellow!40")
;; (t ""))))
;; (concat (format "\\todo[inline,%s]{" color)
;; (unless (eq todo "")
;; (format "\\textsc{%s%s}" todo priority))
;; (format "\\textbf{%s}\n" heading)
;; content "}")))
;;
;; (defun org-latex-format-inlinetask (heading content
;;                                             &optional todo priority tags)
;;   "Generate format string for inlinetask export templates for latex."
;;   (concat "\\todo[inline,]{"
;;           (unless (eq todo "") (format "\\textsc{%s%s}" todo priority))
;;           (format "\\textbf{%s}\n" heading) content "}"))
;;
;; (setcdr (assoc 'latex org-inlinetask-export-templates)
;;         '("%s" '((org-latex-format-inlinetask
;;                   heading content todo priority tags))))

        ;; ;; FIXME Make this the default behavior
        ;; ;; grab the last line too, when selecting a subtree
        ;; (org-end-of-subtree nil t)

;; backend aware export preprocess hook
(defun sa-org-export-preprocess-hook ()
  "My backend aware export preprocess hook."
  (save-excursion
    (when (eq org-export-current-backend 'latex)
      ;; ignoreheading tag for bibliographies and appendices
      (let* ((tag "ignoreheading"))
        ;; (goto-char (point-min))
        ;; (while (re-search-forward (concat ":" tag ":") nil t)
        ;; (delete-region (point-at-bol) (point-at-eol)))
        (org-map-entries (lambda ()
                           (delete-region (point-at-bol) (point-at-eol)))
                         (concat ":" tag ":"))))
    (when (eq org-export-current-backend 'html)
      ;; set custom css style class based on matched tag
      (let* ((match "Qn"))
        (org-map-entries
         (lambda () (org-set-property "HTML_CONTAINER_CLASS" "inlinetask"))
         match)))))

(add-hook 'org-export-preprocess-hook 'sa-org-export-preprocess-hook)

        (defun insert-one-equal-or-two ()
          (interactive)
          (cond
           ((or (bolp) (not (looking-back "=")))
            ;; insert just one =
            (self-insert-command 1))
           ((save-excursion
              (backward-char)
              ;; Skip symbol backwards.
              (and (not (zerop (skip-syntax-backward "w_")))
                   (not (looking-back "="))
                   (or (insert-and-inherit "=") t))))
           (t
            ;; insert == around following symbol
            (delete-backward-char 1)
            (unless (looking-back "=") (insert-and-inherit "="))
            (save-excursion
              (skip-syntax-forward "w_")
              (unless (looking-at "=") (insert-and-inherit "="))))))

        (define-key org-mode-map
          (kbd "=") 'insert-one-equal-or-two)

        ;; using Org mode to send buffer/subtree per mail
        (when (try-require 'org-mime)

          (add-hook 'org-mode-hook
                    (lambda ()
                      (local-set-key "\C-c\M-o" 'org-mime-subtree)))

          ;; add a `mail_composed' property with the current time when
          ;; `org-mime-subtree' is called
          (add-hook 'org-mime-send-subtree-hook
                    (lambda ()
                      (org-entry-put (point) "mail_composed"
                                     (current-time-string)))))

        ;; keep my encrypted data (like account passwords) in my Org mode
        ;; files with a special tag instead
        (when (try-require 'org-crypt)

          ;; encrypt all entries before saving
          (org-crypt-use-before-save-magic)

          ;; To later decrypt an entry that's encrypted, use `M-x
          ;; org-decrypt-entry' or `C-c C-r' (fits nicely with the meaning of
          ;; "reveal").

          ;; which tag is used to mark headings to be encrypted
          (setq org-tags-exclude-from-inheritance '("crypt"))

          ;; GPG key to use for encryption
          (setq org-crypt-key "7F376D89"))

        ;; ;; to insert a reference, I use RefTeX and customized the citation
        ;; ;; format
        ;; (defun org-mode-reftex-setup ()
        ;;   (load-library "reftex")
        ;;   ;; I don't really want to activate the RefTeX minor mode within
        ;;   ;; Org mode (doing so, would overwrite various key bindings)
        ;;   (and (buffer-file-name)
        ;;        (file-exists-p (buffer-file-name))
        ;;        (reftex-parse-all))
        ;;   (reftex-set-cite-format
        ;;    '((?b . "[[bib::%l]]")
        ;;      (?n . "[[note::%l]]")))
        ;;   ;; (define-key org-mode-map (kbd "C-c )") 'reftex-citation)
        ;;   ;; ;; `C-c ]' already bound
        ;;   (define-key org-mode-map
        ;;     "\C-c\C-g" 'reftex-citation))

        ;; (add-hook 'org-mode-hook 'org-mode-reftex-setup)

        ;; ;; FIXME CONFLICT C-c / runs the command
        ;; ;; reftex-index-selection-or-word, which is an interactive
        ;; (add-hook 'org-mode-hook 'turn-on-reftex)

(setq TeX-auto-save t)
(setq TeX-parse-self t)
(setq-default TeX-master nil)
(make-variable-buffer-local 'TeX-master) ;; I think this is need because the variable is not buffer local until AUCTeX is active

(defun org-mode-reftex-setup ()
  (setq TeX-master t)
  (load-library "reftex")
  (and (buffer-file-name)
       (file-exists-p (buffer-file-name))
       (progn
     (reftex-parse-all)
     (reftex-set-cite-format "[[cite:%l][%l]]")))
  (define-key org-mode-map (kbd "C-c )") 'reftex-citation)
  (define-key org-mode-map (kbd "C-c (") 'org-mode-reftex-search))
;; (add-hook 'org-mode-hook 'org-mode-reftex-setup)

(defun org-mode-reftex-search ()
  ;; jump to the notes for the paper pointed to at from RefTeX search
  (interactive)
  (org-open-link-from-string (format "[[notes:%s]]" (reftex-citation t))))

        ;; Use Org mode together with org-annotate-file.el, this is mentioned
        ;; at http://orgmode.org/worg/org-contrib/index.php.

;;** A.3 (info "(org)Adding hyperlink types")

;; ;; define a new link type (`latex') whose path argument can hold the name of
;; ;; any LaTeX command
;; (org-add-link-type
;;  "latex" nil
;;  (lambda (path desc format)
;;    (cond
;;     ((eq format 'html)
;;      (format "<span class=\"%s\">%s</span>" path desc))
;;     ((eq format 'latex)
;;      (format "\\%s{%s}" path desc)))))

;; add background color by using custom links like [[bgcolor:red][Warning!]]
(org-add-link-type
  "bgcolor" nil
  (lambda (path desc format)
   (cond
    ((eq format 'html)
     (format"<span style=\"background-color:%s;\">%s</span>" path desc))
    ((eq format 'latex)
     (format"\\colorbox{%s}{%s}" path desc))
    (t
     (format"BGCOLOR LINK (%s): {%s}{%s}" format path desc)))))

;;** A.6 (info "(org)Dynamic blocks")

        ;; make sure that all dynamic blocks and all tables are always
        ;; up-to-date
        (add-hook 'before-save-hook
                  '(lambda ()
                     (when (eq major-mode 'org-mode)
                       (org-align-all-tags)
                       (org-update-all-dblocks)
                       (org-table-iterate-buffer-tables)
                       (when (file-exists-p (buffer-file-name (current-buffer)))
                         (my/org-remove-redundant-tags))
                       )))

)))

      (GNUEmacs
       ;; add weather forecast in your Org agenda
       (autoload 'org-google-weather "org-google-weather" nil t)

       (eval-after-load "org-google-weather"
         ;; '(try-require 'url)

         ;; add the city
         '(setq org-google-weather-format "%C %i %c, %l°-%h°")))

;;* Calendar framework for Emacs

;; https://github.com/kiwanami/emacs-calfw
;; display Org schedules
(when (locate-library "calfw-org")

  (autoload 'cfw:open-org-calendar "calfw-org"
    "Open an Org schedule calendar." t)

  ;; (define-key global-map (kbd "C-c c") 'cfw:open-org-calendar)

  (eval-after-load "calfw-org"
    '(progn

    ;; default setting
    (setq cfw:fchar-junction ?+
          cfw:fchar-vertical-line ?|
          cfw:fchar-horizontal-line ?-
          cfw:fchar-left-junction ?+
          cfw:fchar-right-junction ?+
          cfw:fchar-top-junction ?+
          cfw:fchar-top-left-corner ?+
          cfw:fchar-top-right-corner ?+ )

    ;; Unicode characters
    (setq cfw:fchar-junction ?╋
          cfw:fchar-vertical-line ?┃
          cfw:fchar-horizontal-line ?━
          cfw:fchar-left-junction ?┣
          cfw:fchar-right-junction ?┫
          cfw:fchar-top-junction ?┯
          cfw:fchar-top-left-corner ?┏
          cfw:fchar-top-right-corner ?┓)

  )))

;;* 39 (info "(emacs)Document View")

(chapter chapter-39-document-view "39 Document Viewing"

      ;; view PDF/PostScript/DVI files in Emacs

;;** 39.1 (info "(emacs)Navigation")

        (section "39.1 (emacs)Navigation")

        ;; `doc-view' integrates with the usual bookmark facility. So simply
        ;; use `C-x r m' (`bookmark-set') to jump back to the last page you've
        ;; read in a PDF document.

;;** 39.4 (info "(emacs)Conversion")

        (section "39.4 (emacs)Conversion")

        ;; DPI resolution used to render the documents
        ;; `doc-view-enlarge' (`+') and `doc-view-shrink' (`-') work fine to
        ;; zoom in or out
        (setq doc-view-resolution 96)

        ;; DPI your screen supports
        (setq doc-view-display-size 96)

        ;; You can open the *text* of the current doc in a new buffer, by
        ;; pressing `C-c C-t' in doc-view-mode

      ;; Another option, without `doc-view', is `! pdtotext ? - RET'


      ;; antiword will be run on every `.doc' file you open
      ;; TODO sudo aptitude install antiword (or via Cygwin setup)
      (autoload 'no-word "no-word"
        "word to txt")
      (add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))

      ;; un-xls files
      ;; TODO sudo aptitude install xlhtml
      (add-to-list 'auto-mode-alist '("\\.xls\\'" . no-xls))
      (defun no-xls (&optional filename)
        "Run xlhtml and w3m -dump on the entire buffer.
      Optional FILENAME says what filename to use.
      This is only necessary for buffers without
      proper `buffer-file-name'.  FILENAME should
      be a real filename, not a path."
        (interactive "fExcel File: ")
        (when (and filename
                   (not (buffer-file-name)))
          (write-file (make-temp-file filename)))
        (erase-buffer)
        (shell-command
         (format "xlhtml -nc -te %s | w3m -dump -T text/html"
                 (buffer-file-name))
         (current-buffer))
        (setq buffer-file-name nil)
        (set-buffer-modified-p nil))

      ;; no-ppt
      ;; TODO sudo aptitude install ppthtml
      ;; FIXME Not that good! (some text repeated multiple times)
      (defun no-ppt (&optional filename)
        "Run ppthtml and w3m -dump on the entire buffer.
      Optional FILENAME says what filename to use.
      This is only necessary for buffers without
      proper `buffer-file-name'.  FILENAME should
      be a real filename, not a path."
        (interactive "fPowerPoint File: ")
        (when (and filename
                   (not (buffer-file-name)))
          (write-file (make-temp-file filename)))
        (erase-buffer)
        (shell-command
         (format "ppthtml %s | w3m -dump -T text/html" (buffer-file-name))
         (current-buffer))
        (setq buffer-file-name nil)
        (set-buffer-modified-p nil))
      (add-to-list 'auto-mode-alist '("\\.ppt\\'" . no-ppt))

)

;;* 40 (info "(emacs)Gnus")

(chapter chapter-40-gnus "40 Gnus"

      ;; from NoGnus
      (try-require 'gnus-load)

      ;; full name of this user
      (setq user-full-name "John Doe")

      ;; full mailing address of this user
      ;; (used in MAIL envelope FROM, and to select the default personality
      ;; ID)
      (setq user-mail-address "john@doe.com")

      (global-set-key
       (kbd "C-c n") (lambda ()
                       (interactive)
                       (switch-or-start 'gnus "*Group*")))

      (defun switch-or-start (function buffer)
        "If the buffer is current, bury it. If there is a buffer with that
        name, switch to it; otherwise invoke the function."
        (if (equal (buffer-name (current-buffer)) buffer)
            (bury-buffer)
          (if (get-buffer buffer)
              (switch-to-buffer buffer)
            (funcall function))))

      ;; a newsreader for GNU Emacs
      (eval-after-load "gnus"
        '(progn

           ;; Gnus startup file name
           (setq gnus-init-file "~/.gnus")

           ;; open my Gnus configuration file
           (defun my/open-dot-gnus ()
             "Opening Gnus startup file."
             (interactive)
             (find-file gnus-init-file))
           (global-set-key (kbd "<C-f3>") 'my/open-dot-gnus)

           ;; package to compose an outgoing mail (Message, with Gnus
           ;; paraphernalia)
           (setq mail-user-agent 'gnus-user-agent)
           (XEmacs
            (setq toolbar-mail-reader 'gnus))

           ;; reading mail with Gnus
           (setq read-mail-command 'gnus)

           ;; ;; re-apply my color theme (as it seems Gnus is overriding part of
           ;; ;; it)
           ;; (when (locate-library "color-theme-leuven")
           ;;   (color-theme-leuven))
           ))

      ;; some info related functions
      ;; (to insert links such as `(info "(message)Insertion Variables")')
      (when (locate-library "rs-info")
        (autoload 'rs-info-insert-current-node "rs-info"
          "Insert reference to current Info node using STYPE in buffer." t)
        (autoload 'rs-info-boxquote "rs-info"
          "Yank text (from an info node), box it and use current info node as title." t)
        (autoload 'rs-info-reload "rs-info"
          "Reload current info node." t)
        (autoload 'rs-info-insert-node-for-variable "rs-info"
          "Insert a custom style info node for the top level form at point." t)
        (defalias 'boxquote-info 'rs-info-boxquote))

;;** Insidious bbdb

      (section "Insidious bbdb")


;;* (info "(bbdb)Installation")

      (unless (try-require 'bbdb-autoloads) ;; "hand-made"
        (autoload 'bbdb         "bbdb-com"
          "Insidious Big Brother Database" t)
        (autoload 'bbdb-name    "bbdb-com"
          "Insidious Big Brother Database" t)
        (autoload 'bbdb-company "bbdb-com"
          "Insidious Big Brother Database" t)
        (autoload 'bbdb-net     "bbdb-com"
          "Insidious Big Brother Database" t)
        (autoload 'bbdb-notes   "bbdb-com"
          "Insidious Big Brother Database" t)

        (autoload 'bbdb-insinuate-gnus "bbdb-gnus"
          "Hook BBDB into Gnus.")
        ;; (autoload 'bbdb-insinuate-message "bbdb"
        ;;   "Hook BBDB into `message-mode'.") ;; BBDB 2.35
        (autoload 'bbdb-insinuate-message "bbdb-message"
          "Hook BBDB into `message-mode'."))

      ;; search the BBDB
      (global-set-key (kbd "<C-f11>") 'bbdb)

      (eval-after-load "bbdb"
        '(progn

        ;; coding system used for reading and writing `bbdb-file'
        (setq bbdb-file-coding-system 'utf-8)

        ;; ensure `~/.bbdb' never becomes non utf-8 again (it is defined with
        ;; `defconst', so it is reset whenever `bbdb.el' is loaded)
        (add-hook 'bbdb-load-hook
                  (lambda () (setq bbdb-file-coding-system 'utf-8)))

        ;; enable the various package-specific BBDB functions
        (bbdb-initialize 'gnus 'message)

        ;; - add bindings for the default keys to Gnus and configure Gnus to
        ;;   notify the BBDB when new messages are loaded (required if the
        ;;   BBDB is to be able to display BBDB entries for messages displayed
        ;;   in Gnus)
        (add-hook 'gnus-startup-hook 'bbdb-insinuate-gnus)

        ;; - add a binding for `M-TAB' to Message mode. This will enable
        ;;   completion of addresses based on BBDB records
        (add-hook 'gnus-startup-hook 'bbdb-insinuate-message)


        ;; (bbdb-mua-auto-update-init 'gnus 'message)


        ;; (define-key gnus-summary-mode-map
        ;;      ":" 'bbdb-mua-display-sender)


        ;; ;; customizable completion in message headers
        ;; ;; (to avoid conflict between `flyspell' and `BBDB')
        ;; (try-require 'message-x)

        ;; FIXME Does not work (still ask to add address)
          ;; don't ask about fake addresses
          ;; NOTE: there can be only one entry per header (such as To, From)
          ;; http://flex.ee.uec.ac.jp/texi/bbdb/bbdb_11.html
          (setq bbdb-ignore-some-messages-alist
                '(("From" . "no.?reply\\|public.gmane.org")))

;;* (info "(bbdb)Interfaces")

        ;; mail aliases (local mailing lists)
        ;; (add-hook 'message-setup-hook 'bbdb-define-all-aliases) ;; BBDB 2.35
        (add-hook 'message-setup-hook 'bbdb-get-mail-aliases) ;; BBDB 3

        ;; always use full name when sending mail
        ;; (even if User Name has an address of the form <user.name@domain>)
        (setq bbdb-dwim-net-address-allow-redundancy t) ;; BBDB 2.35
        (setq bbdb-mail-avoid-redundancy nil) ;; BBDB 3

        ;; no popup on auto-complete
        (setq bbdb-completion-display-record nil)

        ;; completion is done across the set of all full-names and user-ids
        (setq bbdb-completion-type nil)

;;* (info "(bbdb)Reader-specific Features")

        ;; marking posters with records in the BBDB
        (setq bbdb/gnus-summary-mark-known-posters t)

        ;; mark authors in the Summary Buffer who have records in the BBDB
        (setq bbdb/gnus-summary-known-poster-mark "B")

        ;; display the poster's name from the BBDB if we have one
        (setq bbdb/gnus-summary-prefer-real-names t)

        ;; replace the information provided in the From header with data from
        ;; the BBDB if we have one
        (setq bbdb/gnus-summary-prefer-bbdb-data t)

        (setq bbdb/gnus-summary-show-bbdb-names t)

;;* (info "(bbdb)Options")

        ;; You can add the author of a mail or posting to the BBDB
        ;; by hitting `:'

        ;; name of the file which contains your personal database
        (setq bbdb-file "~/.bbdb")

        ;; no default area code to use when prompting for a new phone number
        (setq bbdb-default-area-code nil)

        ;; default country to use if none is specified
        (setq bbdb-default-country "")

        ;; disable syntax-checking of telephone numbers
        (setq bbdb-north-american-phone-numbers-p nil) ;; BBDB 2.35
        (setq bbdb-phone-style nil) ;; BBDB 3

        ;; restoration of the window configuration
        (setq bbdb-electric-p t) ;; BBDB 2.35
        (setq bbdb-electric t) ;; BBDB 3

        ;; don't display a continuously-updating BBDB window while in GNUS
        ;; (setq bbdb-use-pop-up nil) ;; BBDB 2.35
        ;; (setq bbdb-pop-up-layout nil) ;; BBDB 3

        ;; desired number of lines in a GNUS pop-up BBDB window
        (setq bbdb-pop-up-target-lines 1) ;; BBDB 2.35
        (setq bbdb-pop-up-window-size 1) ;; BBDB 3

        ;; default display layout
        (setq bbdb-display-layout 'multi-line)

        ;; default display layout pop-up BBDB buffers
        (setq bbdb-pop-up-display-layout 'one-line)

        ;; omit creation-date and timestamp from BBDB display
        (setq bbdb-display-layout-alist
              '((one-line          (order     . (phones notes))
                                   (name-end  . 24)
                                   (toggle    . t)
                                   (omit      . (net AKA mail-alias gnus-private
                                                     creation-date timestamp)))
                (multi-line        (indention . 14)
                                   (toggle    . t)
                                   (omit      . (AKA creation-date timestamp)))
                (pop-up-multi-line (indention . 14))))

        ;; allow cycling of email addresses while completing them
        (setq bbdb-complete-name-allow-cycling t) ;; BBDB 2.35
        (setq bbdb-complete-mail-allow-cycling t) ;; BBDB 3

        ;; save the database without asking (any time it would ask)
        (setq bbdb-offer-save 'auto)

        ;; automatically add some text to the notes field of the BBDB record
        (add-hook 'bbdb-notice-hook 'bbdb-auto-notes-hook)

        ;; capture auto-notes
        (setq bbdb-auto-notes-alist
              ;; organization
              `(("Organization" (".*" Organization 0))

                ;; mailer
                ("User-Agent" (".*" mailer 0 t))  ;; t = overwrite
                ("X-Mailer" (".*" mailer 0 t))
                ("X-Newsreader" (".*" mailer 0 t))

                ;; X-Face bitmaps of the people
                ("x-face" ,(list (concat "[ \t\n]*\\([^ \t\n]*\\)"
                                         "\\([ \t\n]+\\([^ \t\n]+\\)\\)?"
                                         "\\([ \t\n]+\\([^ \t\n]+\\)\\)?"
                                         "\\([ \t\n]+\\([^ \t\n]+\\)\\)?")
                                 'face
                                 "\\1\\3\\5\\7"))))

;;* (info "(bbdb)Utilities")

        ;; use BBDB to store PGP preferences
        (when (try-require 'bbdb-pgp)
          ;; what to do if the recipient is not in the BBDB
          (setq bbdb/pgp-default-action nil))))

)

;;* 41 Running (info "(emacs)Shell") Commands from Emacs

(chapter chapter-41-shell "41 Running Shell Commands from Emacs"

      ;; transform shell names to what they really are
      (eval-after-load "sh-script"
        '(add-to-list 'sh-alias-alist '(sh . bash)))


      (defun set-shell-cmdproxy()
        (interactive)
        (setq shell-file-name "cmdproxy")
        (setq explicit-shell-file-name "cmdproxy")
        (setenv "SHELL" explicit-shell-file-name)
        (setq w32-quote-process-args t)
        (setq shell-command-switch "/c"))

      ;; (set-shell-cmdproxy)


      ;; XXX Test the following (added on 2011-08-03)
      ;; (when (eq system-type 'windows-nt)
      ;;   ;; Workaround for Cygwin shell, when set 'CYGWIN=noglob'. By default
      ;;   ;; shell-quote-argument' quoted by double '\' chars, this cause failure.
      ;;   (defun shell-quote-argument (argument)
      ;;     (concat "'" argument "'"))
      ;;   ;; Workaround for Cygwin when 'shell-file-name' is 'bash'.
      ;;   (setq null-device "/dev/null"))
      ;;
      ;; ;; Use shell from Cygwin/MinGW.
      ;; (setq shell-file-name "bash")
      ;; (setenv "SHELL" "/bin/bash")
      ;; (setq explicit-bash-args '("-i"))
      ;; (setq explicit-sh-args '("-i"))


;;** 41.1 Single Shell

      (section "41.1 Single Shell")

      ;; force interactive behavior (to get my handy shell aliases)
      ;; FIXME Fix for Zsh (zsh:1: command not found: shopt)
      ;; (defadvice shell-command (before my/shell-command activate)
      ;;   (ad-set-arg 0
      ;;               (concat "source ~/.bashrc; shopt -s -q expand_aliases;\n "
      ;;                       (ad-get-arg 0))))

      ;; for single shell commands
      (setq shell-file-name
            ;; must be in the `PATH' (Windows users)
            (cond
                  ;; ((executable-find "zsh") "zsh") ;; problems to compile with AUCTeX
                  ((executable-find "bash") "bash")
                  ((executable-find "cmdproxy.exe") "cmdproxy.exe")
                  (t "cmd.exe"))) ;; = system shell

      ;; use `shell-file-name' as the default shell
      ;; (when (try-require 'env)
        (setenv "SHELL" shell-file-name)
;; )

      ;; switch used to have the shell execute its command line argument
      ;; (`/c' does not work with XEmacs)
      (setq shell-command-switch
            (cond ((eq shell-file-name "cmd.exe") "/c") ;; using a system shell
                  (t "-c")))

      ;; quote process arguments to ensure correct parsing on Windows
      (setq w32-quote-process-args
            (cond ((eq shell-file-name "cmd.exe") nil) ;; using a system shell
                  (t t)))

      ;; name of shell used to parse TeX commands
      (setq TeX-shell shell-file-name)

      ;; shell argument indicating that next argument is the command
      (setq TeX-shell-command-option shell-command-switch)

;;** 41.2 Interactive Shell

      (section "41.2 Interactive Shell")

      ;; for the interactive (sub)shell (and AUCTeX compilation?)
      (setq explicit-shell-file-name shell-file-name)

      ;; ;; args passed to inferior shell by `M-x shell', if the shell is bash
      ;; (setq explicit-bash-args '("--noediting" "--login"))
      ;; ;; FIXME This ensures that /etc/profile gets read (at least for Cygwin).
      ;; ;; Is this good?

      ;; regexp to match prompts in the inferior shell
      (setq shell-prompt-pattern "^[^#$%>\n]*[#$%>] *")

;;** 41.3 Shell Mode

      (section "41.3 Shell Mode")

      ;; general command-interpreter-in-a-buffer stuff (lisp, shell, R, ...)
      ;; (when (try-require 'comint)

        ;; `M-s'    `comint-next-matching-input'
        ;; `M-r'    `comint-previous-matching-input'
        ;; `M-n'    `comint-next-input'
        ;; `M-p'    `comint-previous-input'
        ;; `C-up'   `last command'

        ;; regexp to recognize prompts in the inferior process
        ;; (set it for Org-babel sh session to work!)
        ;; (defun set-shell-prompt-regexp ()
          (setq comint-prompt-regexp shell-prompt-pattern)
        ;;   )
        ;; (add-hook 'shell-mode-hook 'set-shell-prompt-regexp)

        ;; no duplicates in command history
        (setq-default comint-input-ignoredups t)

        ;; input to interpreter causes windows showing the buffer to scroll
        ;; (inserting at the bottom)
        (setq-default comint-scroll-to-bottom-on-input t)
        (setq comint-scroll-to-bottom-on-input t)

        ;; output to interpreter causes windows showing the buffer to scroll
        (setq-default comint-move-point-for-output t)
        (setq comint-move-point-for-output t)

        ;; remove the `^M' characters
        (add-hook 'comint-output-filter-functions 'comint-strip-ctrl-m nil t)
        ;; XXX [2011-11-23 Wed] Added `nil t'!???

        ;; show completion list when ambiguous
        (setq comint-completion-autolist t)

        ;; use the `up' and `down' arrow keys to traverse through the previous
        ;; commands
        (defun my/shell-mode-hook ()
          "Customize my shell-mode."
          (local-set-key (kbd "<up>") 'comint-previous-input)
          (local-set-key (kbd "<down>") 'comint-next-input))
        (add-hook 'shell-mode-hook 'my/shell-mode-hook)
;; )

      ;; translate ANSI escape sequences into faces (within shell mode)
      (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)

      ;; I prefer bash-style to zsh-style
      (setq pcomplete-cycle-completions nil)

      (setenv "PAGER" "/usr/bin/cat")

;;** 41.4 Shell Prompts

      (section "41.4 Shell Prompts")

;;** 41.5 History

      (section "41.5 History")

;;** 41.6 Directory Tracking

      (section "41.6 Directory Tracking")

;;** 41.7 Options

      (section "41.7 Options")

;;** 41.8 Terminal emulator

      (section "41.8 Terminal emulator")

;;** 41.9 Term Mode

      ;; I could use Term mode, which provides a full terminal, but that
      ;; defeats the purpose of running inside Emacs.
      ;;
      ;; I had similar gripes initially, but Term mode seems to do the job.
      ;; Switching between line-mode (`C-c C-j') and char-mode (`C-c C-k'),
      ;; you have a terminal emulator which you can treat as a Shell mode
      ;; buffer when you need to.

      ;; You can switch between term modes. Using `C-c c-j' will put you
      ;; in line mode where term is behaves like a buffer , then u can use
      ;; `C-c c-k' to switch back to char mode.

      (section "41.9 Term Mode")

      ;; Emacs shell is a "dump" terminal which doesn't support (all) terminal
      ;; control codes. You need to use `M-x term' if you want a proper
      ;; terminal (but even that is not as good as the good old XTerm).
      ;;
      ;; (term "bash")
      ;; If you do `M-x term', `bash' is offered as the default as well.
      ;;
      ;; Need a good terminal emulation for applications that are interactive
      ;; with your terminal, in the same way `top' is working or `man' ... or
      ;; `less' ... or `unison'

      ;; "less" needs a _terminal_. Emacs's shell-mode is not a terminal so
      ;; "less" doesn't work. If the programs you use needs terminal features
      ;; then you must use a terminal, such as "M-x term".

      ;; This "page-at-a-time" feature comes with terminal emulation. There's
      ;; no need to make "M-x shell" a real terminal because there already is
      ;; one: "M-x term".

      ;; Try also to use `M-x ansi-term' that is much better than `term': with
      ;; M-x term, you can run only one shell; with `ansi-term' you can start
      ;; more than one (*ansi-term*<2>, *ansi-term*<3>).

      ;; One weird thing, is that 'M-x term' is a term emulation where less(1)
      ;; works and it has the 'C-c C-q' one-page-at-a-time thing as well...
      ;;
      ;; M-x shell, has neither.

      ;; >> Or are there some things `M-x term' can't do while `M-x shell'
      ;; >> can?

      ;; > With M-x shell you're using emacs to construct the command to pass
      ;; > to the shell. This is an advantage if you shell doesn't keep a
      ;; > history or offers no completion mechanism. Also, you can use
      ;; > isearch to search through the command output, copy stuff into the
      ;; > kill ring or use the rectangle functions. Or you might just prefer
      ;; > the emacs key bindings over the one's your shell offers. 8-)

      ;; I'd like to point out that term-mode has also the so called "line
      ;; mode" (`C-c C-j') in which user can wander around the buffer pretty
      ;; much like anywhere else in Emacs. Kill-ring commands, isearch etc.
      ;; work. Then there is "char mode" (`C-c C-k'), the default, which is
      ;; like your normal terminal emulator except the escape key.

      ;; Actually you can read this in the emacs info pages: "In line mode,
      ;; Term basically acts like Shell mode".

      ;; The problem here is the word 'basically' which probably means
      ;; 'almost'. So they differ in the details.

      ;; In my case, I started to use `M-x shell', and like it since I almost
      ;; never have to use applications that need a real term emulation. But
      ;; if you look at them (M-x term and M-x shell) carefully, then `M-x
      ;; term' has some weird behaviours when using the shell mode key
      ;; bindings; try for instance: `C-c C-e', `C-c C-a', `C-c C-o'... but as
      ;; I said they're details.


      ;; managing multiple terminal buffers in Emacs
      ;; (and fixing some troubles of `term-mode': key bindings, etc.)
;;      (try-require 'multi-term)

(autoload 'multi-term "multi-term" nil t)
(autoload 'multi-term-next "multi-term" nil t)

(setq multi-term-program shell-file-name)

;; (global-set-key (kbd "C-c t") 'multi-term-next)
(global-set-key (kbd "C-c T") 'multi-term) ;; create a new one


      ;; "multi-term on POSIX hosts has let me switch from using screen, with
      ;; one emacs screen and lots of shell screens; to just using emacs, with
      ;; lots of terminals inside it."

      ;; run an inferior shell, with I/O through buffer `*shell*'
      (global-set-key
       (kbd "C-c !") (cond (running-ms-windows 'shell)
                           (t 'term)))

;;** 41.10 Paging in Term

      (section "41.10 Paging in Term")

;;** 41.11 Remote Host

      (section "41.11 Remote Host")

      ;; load ssh.el file
      (add-to-list 'same-window-regexps "^\\*ssh-.*\\*\\(\\|<[0-9]+>\\)")
      (autoload 'ssh "ssh"
        "Open a network login connection via `ssh'" t)
        ;; this is to run ESS remotely on another computer in my own emacs, or
        ;; just plain old reading remote files

      ;; See http://old.nabble.com/SSH-inside-Emacs--td29223353.html
      ;; - plink (with `dumb' terminal option?) as interactive shell
      ;; - ssh -t -t user@host
      ;; - Cygwin'ized Emacs
      ;; - MSYS (MinGW)

        ;; ;; let Emacs recognize Cygwin paths (e.g. /usr/local/lib)
        ;; (when (and running-ms-windows
        ;;            (executable-find "mount")) ;; Cygwin bin directory found
        ;;   (when (try-require 'cygwin-mount)
        ;;     (cygwin-mount-activate)))

)

;;* 42 (info "(emacs)Emacs Server")

(chapter chapter-42-emacs-server "42 Using Emacs as a Server"

      (defconst --batch-mode (member "--batch-mode" command-line-args)
        "True when running in batch-mode (`--batch-mode' command-line switch set).")


      ;; don't start server in batch mode
      (unless --batch-mode

        ;; use Emacs as a server (with the `emacsclient' program)
        (when (try-require 'server)

          ;; test whether server is running, avoiding the message of
          ;; "server-start" while opening another Emacs session
          (or (server-running-p)

              ;; start the Emacs server
              (server-start)))


        ;; ; This somehow produced a failure on excelior
        ;; (add-hook 'after-init-hook 'server-start)
        ;; (add-hook 'server-done-hook
        ;; 	  (lambda ()
        ;; 	    (shell-command "screen -r -X select `cat ~/tmp/emacsclient-caller`")))

        )

)

;;* 43 (info "(emacs)Printing")

(chapter chapter-43-printing "43 Printing Hard Copies"

      ;; print Emacs buffer on line printer
      ;; for {lpr,print}-{buffer,region}
      (when (try-require 'lpr)

        ;; name of program for printing a file
        (setq lpr-command (executable-find "enscript"))
                                        ; TODO Install `enscript'

        ;; list of strings to pass as extra options for the printer program
        (setq lpr-switches (list "--font=Courier8"
                                 "--header-font=Courier10"
                                 (format "--header=%s" (buffer-name))))

        ;; name of a printer to which data is sent for printing
        (setq printer-name
              (cond (running-ms-windows "//PRINT-SERVER/Brother HL-4150CDN")
                    (t t))))

      ;; print text from the buffer as PostScript
      (when (try-require 'ps-print)

        (defvar gsprint-program
          (concat windows-program-files-dir "Ghostgum/gsview/gsprint.exe")
          "Defines the Windows path to the gsview executable.")

        (my/file-exists-and-executable-p gsprint-program)

        (if (and gsprint-program
                 (executable-find gsprint-program))
            (progn
              ;; name of a local printer for printing PostScript files
              ;; adjusted to run Ghostscript
              (setq ps-printer-name t)

              ;; name of program for printing a PostScript file
              ;; tell Emacs where ghostscript print utility is located
              (setq ps-lpr-command gsprint-program)

              ;; list of extra switches to pass to `ps-lpr-command'
              ;; tell Ghostscript to query which printer to use
              (setq ps-lpr-switches '("-query")))

          (progn
            (setq ps-printer-name "//PRINT-SERVER/Brother HL-4150CDN")
            (setq ps-lpr-command "")
            (setq ps-lpr-switches '("raw"))))

;; ;; Printing
;; (setq ps-printer-name t)
;; (setq ps-lpr-command "g:/dev/bin/ghostscript/gs9.04/bin/gswin64c.exe")
;; (setq ps-lpr-switches '("-q" "-dNOPAUSE" "-dBATCH" "-sDEVICE=mswinpr2"))

(setq ps-font-family 'Courier) ;; see `ps-font-info-database'
(setq ps-font-size 9.1)

        ;; size of paper to format for
        (setq ps-paper-type 'a4)

        ;; print in portrait mode
        (setq ps-landscape-mode nil)

        ;; number of columns
        (setq ps-number-of-columns 1)


(defun ps-time-stamp-yyyy-mm-dd-aaa ()
  "Return date as \"2001-06-18 Mon\" (ISO date + day of week)."
  (format-time-string "%Y-%m-%d %a"))


;; Page layout: Header [file-name     2001-06-18 Mon]
;;              Footer [                         n/m]

;; Header
(setq ps-header-lines 1)
;; (setq ps-header-font-size 11)
(setq ps-header-title-font-size 11)
(setq ps-header-font-family 'Helvetica)
(setq ps-right-header '(ps-time-stamp-yyyy-mm-dd-aaa))
(setq ps-print-header-frame nil)	; no box top

;; see http://www.emacswiki.org/emacs/PsPrintPackage-23
(setq ps-header-frame-alist
  '((fore-color   . "#CCCCCC")))
(setq ps-footer-frame-alist
  '((fore-color   . "#CCCCCC")))

;; Footer
(setq ps-footer-lines 1)
(setq ps-footer-font-size 8)
(setq ps-footer-font-family 'Helvetica)
(setq ps-print-footer t)
(setq ps-left-footer nil)
(setq ps-right-footer (list "/pagenumberstring load")) ;; Page n of m
(setq ps-footer-offset .50)
(setq ps-footer-line-pad .50)
(setq ps-print-footer-frame nil)	; no box bottom

        ;; (setq ps-bottom-margin 36)
        ;; (setq ps-error-handler-message 'system)
        ;; (setq ps-inter-column 25)
        ;; (setq ps-left-margin 36)
        ;; (setq ps-line-number-color "green")
        ;; (setq ps-line-number-font "Courier-Bold")
        ;; (setq ps-print-control-characters nil)
        ;; (setq ps-right-margin 27)
        ;; (setq ps-top-margin 28)
        ;; (setq ps-warn-paper-type nil)
        )

      ;; generate and print a PostScript image of the buffer
      (GNUEmacs
       (when running-ms-windows
         (w32-register-hot-key (kbd "<snapshot>"))
         ;; override `Print Screen' globally used as a hotkey by Windows
         (global-set-key (kbd "<snapshot>") 'ps-print-buffer-with-faces)))
      (XEmacs
       (setq toolbar-print-function 'ps-print-buffer-with-faces))

      (global-set-key (kbd "M-p") 'ps-print-buffer-with-faces)

)

;;* 47 (info "(emacs)Sorting") Text

(chapter chapter-47-sorting "47 Sorting Text"

      ;; key binding
      (global-set-key (kbd "C-c ^") 'sort-lines)

)

;;* 48 (info "(emacs)Narrowing")

(chapter chapter-48-narrowing "48 Narrowing"

      ;; enable the use of the command `narrow-to-region' without confirmation
      (put 'narrow-to-region 'disabled nil)

)

;;* 51 (info "(emacs)Saving Emacs Sessions")

(chapter chapter-51-saving-emacs-sessions "51 Saving Emacs Sessions"

      (try-require 'saveplace)
      (eval-after-load "saveplace"
        '(progn

           ;; automatically save place in each file
           (setq-default save-place t)  ;; default value for all buffers

           ;; name of the file that records `save-place-alist' value
           (setq save-place-file
                 (convert-standard-filename "~/.emacs.d/places.txt"))

           ;; do not make backups of master save-place file
           (setq save-place-version-control "never")))
)

;;* 54 (info "(emacs)Hyperlinking")

(chapter chapter-54-hyperlinking "54 Hyperlinking and Navigation Features"

;;** HTML Tidy

      (section "HTML Tidy")

      (when (executable-find "tidy")
        ;; interface to the HTML Tidy program
        (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/nxml-mode-hook ()
          "Customize my nxml-mode."
          (tidy-build-menu nxml-mode-map)
          (local-set-key (kbd "C-c C-c") 'tidy-buffer)
          (setq sgml-validate-command "tidy"))

        (add-hook 'nxml-mode-hook 'my/nxml-mode-hook))

;;** pass a URL to a WWW browser

      (section "pass a URL to a WWW browser")

      ;; default browser started when you click on some URL in the buffer
      (setq browse-url-browser-function
            (if (not window-system)
                'w3m-browse-url
              (if running-ms-windows
                  'browse-url-default-windows-browser
                'browse-url-generic)))
      ;; (setq browse-url-browser-function
      ;;       '(("file:///usr/share/doc/hyperspec/" . w3m-browse-url)
      ;;         ("emacswiki.org" . w3m-browse-url)
      ;;         ("lispdoc.com" . w3m-browse-url)
      ;;         ( "." . browse-url-firefox)))
      ;; that let me use `w3m' for EmacsWiki/Common Lisp documentation and
      ;; Firefox otherwise.

      ;; ;; name of the browser program used by `browse-url-generic'
      ;; (setq browse-url-generic-program
      ;;       (when (and window-system
      ;;                  (not running-ms-windows))
      ;;         (executable-find "firefox"))) ;; could be `google-chrome'

      ;; ;; shortcut to view the current file in browser
      ;; (eval-after-load "nxml-mode"
      ;;   '(define-key nxml-mode-map
      ;;     (kbd "C-c v") 'browse-url-of-buffer)
      ;; )

      (defun my/browse (url)
        "If prefix is specified, use the system default browser else use the
      configured emacs one."
        (if current-prefix-arg
            ;; open in your desktop browser (firefox here)
            (when url (browse-url-default-browser url))
          ;; open using your Emacs browser (whatever that is configured to)
          (if url (browse-url url) (call-interactively 'browse-url))))

      (defun my/browse-url (&optional url)
        "Browse the url passed in."
        (interactive)
        (setq url (or url
                      (w3m-url-valid (w3m-anchor))
                      (browse-url-url-at-point)
                      (region-or-word-at-point)))
        (setq url (read-string (format "Url \"%s\" :" url) url nil url))
        (my/browse url))

;;** Web search

      (section "Web search")

      (when t ;; (try-require 'browse-url)

        (defvar my/google-maxlen 200
          "Maximum length of search string to send. This prevents you from
        accidentally sending a 5 MB query string.")

        (defun my/google-search ()
          "Prompt for a query in the minibuffer, launch the web browser and
        query Google."
          (interactive)
          (let ((query (read-from-minibuffer "Google Search: ")))
            (browse-url (concat "http://www.google.com/search?q="
                                (url-hexify-string query)))))

        ;; (defun google-it (search-string)
        ;;   "Search for SEARCH-STRING on Google."
        ;;   (interactive "sSearch for: ")
        ;;   (browse-url (concat "http://www.google.com/search?q="
        ;;                   (url-hexify-string
        ;;                     (encode-coding-string search-string 'utf-8)))))

        (defun my/google-search-word-at-point ()
          "Google the word at point."
          (interactive)
          (browse-url (concat "http://www.google.com/search?q="
                              (word-at-point))))
        (defun my/google-search-region (prefix start end)
          "Create a search URL and send it to the web browser."
          (interactive "P\nr")
          (if (> (- end start) my/google-maxlen)
              (message "Search string too long!")
            (let ((query (buffer-substring-no-properties start end)))
              (browse-url
               (concat "http://www.google.com/search?q="
                       (url-hexify-string query))))))

        ;; (defun google-search-selection ()
        ;;   "Create a Google search URL and send it to your web browser."
        ;;   (interactive)
        ;;   (let (start end term url)
        ;;     (if (or (not (fboundp 'region-exists-p)) (region-exists-p))
        ;;         (progn
        ;;           (setq start (region-beginning)
        ;;                 end   (region-end))
        ;;           (if (> (- start end) my/google-maxlen)
        ;;               (setq term (buffer-substring start (+ start my/google-maxlen)))
        ;;             (setq term (buffer-substring start end)))
        ;;           (google-it term))
        ;;       (beep)
        ;;       (message "Region not active"))))


             (defun google (what)
               "Use google to search for WHAT."
               (interactive "sSearch: ")
               (save-window-excursion
                 (delete-other-windows)
                 (let ((dir default-directory))
                   (w3m-browse-url (concat "http://www.google.com/search?q="
                                           (w3m-url-encode-string what)))
                   (cd dir)
                   (recursive-edit))))
             (global-set-key (kbd "C-c g s") 'google)

(defun pm/region-or-word (prompt)
  "Read a string from the minibuffer, prompting with PROMPT.
If `transient-mark-mode' is non-nil and the mark is active,
it defaults to the current region, else to the word at or before
point. This function returns a list (string) for use in `interactive'."
  (list (read-string prompt (or (and transient-mark-mode mark-active
                                     (buffer-substring-no-properties
                                      (region-beginning) (region-end)))
				(current-word)))))

(defun pm/google (string)
  "Ask a WWW browser to google string.
Prompts for a string, defaulting to the active region or the current word at
or before point."
  (interactive (pm/region-or-word "Google: "))
  (browse-url (concat "http://google.com/search?num=100&q=" string)))

        (defvar my/google-prefix-map (make-sparse-keymap)
          "Keymap for my Google commands.")

        ;;     (global-set-key (kbd "M-s") 'my/google-search-region)

        (global-set-key (kbd "C-c g") my/google-prefix-map)
        (define-key my/google-prefix-map "g" 'my/google-search)
        (define-key my/google-prefix-map "w" 'my/google-search-word-at-point)
        (define-key my/google-prefix-map "r" 'my/google-search-region)

      ;; excellent!
      (defun answers-define ()
        "Look up the word under cursor in a browser."
        (interactive)
        (browse-url
         (concat "http://www.answers.com/main/ntquery?s="
                 (thing-at-point 'word))))

        (defun lookup-word-definition-in-w3m ()
          "Look up the word's definition in a emacs-w3m.\n
        If a region is active (a phrase), lookup that phrase."
          (interactive)
          (let (myword
                myurl)
            (setq myword
                  (if (and transient-mark-mode mark-active)
                      (buffer-substring-no-properties (region-beginning)
                                                      (region-end))
                    (thing-at-point 'symbol)))
            (setq myword (replace-regexp-in-string " " "%20" myword))
            (setq myurl (concat "http://www.answers.com/main/ntquery?s=" myword))
            (w3m-browse-url myurl)))
        (define-key my/google-prefix-map "a" 'lookup-word-definition-in-w3m)

)

;;** Emacs-w3m

      (section "Emacs-w3m")

      ;; only use if `w3m' command is available on system
      (when (executable-find "w3m")

        ;; `w3m' slows down the startup process dramatically
        (unless (try-require 'w3m-load)
          (autoload 'w3m "w3m"
            "Visit the WWW page using w3m" t)
          (autoload 'w3m-find-file "w3m"
            "Find a local file using emacs-w3m." t)
          (autoload 'w3m-browse-url "w3m"
            "Ask emacs-w3m to show a URL." t))

        (eval-after-load "w3m"
          '(progn

;;*** 3.1 Browsing Web Pages

             ;; go ahead, just try it
             (defun my/w3m-goto-url ()
               "Type in directly the URL I would like to visit (avoiding to
             hit `C-k')."
               (interactive)
               (let ((w3m-current-url ""))
                 (call-interactively 'w3m-goto-url)))

             (define-key w3m-mode-map
               (kbd "U") 'my/w3m-goto-url)

             ;; fix inappropriate key bindings for moving from place to place
             ;; in a page
             (define-key w3m-mode-map
               (kbd "<up>") 'previous-line)
             (define-key w3m-mode-map
               (kbd "<down>") 'next-line)
             (define-key w3m-mode-map
               (kbd "<left>") 'backward-char)
             (define-key w3m-mode-map
               (kbd "<right>") 'forward-char)

             (define-key w3m-mode-map
               (kbd "<tab>") 'w3m-next-anchor)

             ;; moving from page to page
             (define-key w3m-mode-map
               (kbd "F") 'w3m-view-next-page)


;;*** 3.5 Using Tabs

             (define-key w3m-mode-map
               (kbd "<C-tab>") 'w3m-next-buffer)
             (define-key w3m-mode-map
               [(control shift iso-lefttab)] 'w3m-previous-buffer)

             (defun w3m-new-tab ()
               (interactive)
               (w3m-copy-buffer nil nil nil t))

             (define-key w3m-mode-map
               (kbd "C-t") 'w3m-new-tab)

             (define-key w3m-mode-map
               (kbd "C-w") 'w3m-delete-buffer)

;;*** 5.1 General Variables

             ;; send referers only when both the current page and the target
             ;; page are provided by the same server
             (setq w3m-add-referer 'lambda)

             ;; home page
             (setq w3m-home-page "http://www.emacswiki.org/")

             ;; number of steps in columns used when scrolling a window
             ;; horizontally
             (setq w3m-horizontal-shift-columns 1)  ; 2

             ;; proxy settings
             (when (string= (upcase (system-name)) "PC3701")
               (setq w3m-command-arguments
                        (nconc w3m-command-arguments
                               '("-o" "http_proxy=proxy:8080"))))
                                        ; FIXME https_proxy for HTTPS support

             (setq w3m-no-proxy-domains '("localhost" "127.0.0.1"))


;;*** 5.2 Image Variables

             ;; always display images
             (setq w3m-default-display-inline-images t)

             ;; show favicon images if they are available
             (setq w3m-use-favicon t)


;;*** 5.4 Cookie Variables

             ;; functions for cookie processing
             (eval-after-load "w3m-cookie"
             '(progn
               ;; ask user whether accept bad cookies or not
               (setq w3m-cookie-accept-bad-cookies 'ask)

               ;; list of trusted domains
               (setq w3m-cookie-accept-domains
                     '("google.com" "google.be"
                       "yahoo.com" ".yahoo.com" "groups.yahoo.com"
                       "www.dyndns.org"))))

             ;; enable cookies (to use sites such as Gmail)
             (setq w3m-use-cookies t)


;;*** 5.14 Other Variables

             ;; list of content types, regexps (matching a url or a file
             ;; name), commands to view contents, and filters to override the
             ;; content type specified at first
             (setq w3m-content-type-alist
                   (append '(("text/html" "\\.xhtml\\'" nil nil))
                           w3m-content-type-alist))

             ;; toggle a minor mode showing link numbers
             (when (try-require 'w3m-lnum)

               (defun my/w3m-go-to-link-number ()
                 "Turn on link numbers and ask for one to go to."
                 (interactive)
                 (let ((active w3m-lnum-mode))
                   (when (not active) (w3m-lnum-mode))
                   (unwind-protect
                       (w3m-move-numbered-anchor (read-number
                                                  "Anchor number: "))
                     (when (not active) (w3m-lnum-mode))
                     (w3m-view-this-url))))

               (define-key w3m-mode-map
                 (kbd "f") 'my/w3m-go-to-link-number)

               ;; enable link numbering mode by default
               (add-hook 'w3m-mode-hook 'w3m-lnum-mode))

             )))

;;*** 9.1 Turning Gnus into a web browser!

      ;; `nnshimbun' is a Gnus back end, but it is distributed with emacs-w3m,
      ;; not Gnus, exceptionally. `Nnshimbun' allows you to turn Gnus into an
      ;; exceptionally useful web browser. You can skim through the articles
      ;; on a newspaper's web server without having to see all the
      ;; advertisement. You can read articles in mailing list archives as if
      ;; you were subscribed to the list. You can also read submissions in
      ;; bulletin boards, etc...

      (GNUEmacs
      ;; Google maps
      (try-require 'google-maps-XXX))

;;** Babel

      (section "Babel")

      (autoload 'babel "babel"
        "Use a web translation service to translate the message MSG." t)
      (autoload 'babel-region "babel"
        "Use a web translation service to translate the current region." t)
      (autoload 'babel-as-string "babel"
        "Use a web translation service to translate MSG, returning a string." t)
      (autoload 'babel-buffer "babel"
        "Use a web translation service to translate the current buffer." t)

      (defun my/translate ()
        "Translate using many online translators."
        (interactive)
        (let (source)
          (autoload 'babel-work "babel" nil t)
          (switch-to-buffer "*my/translate*")
          (erase-buffer)
          (yank)
          (setq source (buffer-substring-no-properties (point-min) (point-max)))
          (erase-buffer)
          (insert "--- Source ---\n\n")
          (insert source)
          (insert "\n\n\n--- Translation done by Free ---\n\n")
          (insert (babel-work source "fr" "en" 'babel-free-fetch 'babel-free-wash))
          (insert "\n\n\n--- Translation done by BabelFish ---\n\n")
          (insert (babel-work source "fr" "en" 'babel-fish-fetch 'babel-fish-wash))))

      (global-set-key (kbd "<f7>") 'my/translate)
)

;;* 56 Other (info "(emacs)Amusements")

(chapter chapter-56-amusements "56 Other Amusements"

      (GNUEmacs
       ;; get rid of the Games in the Tools menu
       (define-key menu-bar-tools-menu [games] nil))

)

;;* 57 (info "(emacs)Customization")"

(chapter chapter-57-customization "57 Customization"

      ;; inhibit the initial startup message in the `*scratch*' buffer
      (setq inhibit-startup-message t)
      (setq initial-scratch-message nil)

      ;; limit serving to catch infinite recursions for you before they
      ;; cause actual stack overflow in C, which would be fatal for Emacs
      (setq max-lisp-eval-depth 500) ;; GNU Emacs 24
      (setq max-lisp-eval-depth 600) ;; GNU Emacs 23
      (setq max-lisp-eval-depth 600) ;; XEmacs 21.5.29

      ;; limit on number of Lisp variable bindings & unwind-protects
      (setq max-specpdl-size 1000) ;; GNU Emacs 23 and 24
      (setq max-specpdl-size 3000) ;; XEmacs 21.5.29

      ;; speed up things by preventing garbage collections
      (setq gc-cons-threshold 400000) ;; GNU Emacs 23 and 24
      (setq gc-cons-threshold 3500000) ;; make Gnus fast
      ;; from (info "(gnus)FAQ 9-2")

      ;; don't display messages at start and end of garbage collection (as it
      ;; hides too many interesting messages)
      (setq garbage-collection-messages nil)

;;** 57.3 (info "(emacs)Variables")

      (section "57.3 (emacs)Variables")

      ;; file local variables specifications are obeyed, without query --
      ;; RISKY!
      (setq enable-local-variables t)

      ;; obey `eval' variables -- RISKY!
      (setq enable-local-eval t)

      ;; record safe values for some local variables
      (setq safe-local-variable-values
            '((TeX-master . t)
              (ac-sources . (ac-source-words-in-buffer ac-source-dictionary))
              (ac-user-dictionary-files . ("../dictionary.txt"))
              (balloon-help-mode . -1)
              (before-save-hook . nil)
              (flyspell-mode . -1)
              (flyspell-mode . t)
              (ispell-local-dictionary . "en_US")
              (ispell-local-dictionary . "fr_FR")
              (ispell-mode . t)
              (org-tags-column . -80)))

;;** 57.4 Customizing (info "(emacs)Key Bindings")

      (section "57.4 Customizing (emacs)Key Bindings")

      ;; See as well Print keybindings (pkb)


      ;; print the key bindings in a tabular form
      ;; [from http://www-xray.ast.cam.ac.uk/~gmorris/dotemacs.html]
      (GNUEmacs
       (defun my/keytable (arg)
         "Print the key bindings in a tabular form."
         (interactive "sEnter a modifier string:")
         (with-output-to-temp-buffer "*Key table*"
           (let* ((i 0)
                  (keys (list "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l"
                              "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x"
                              "y" "z" "<return>" "<down>" "<up>" "<right>"
                              "<left>" "<home>" "<end>" "<f1>" "<f2>" "<f3>"
                              "<f4>" "<f5>" "<f6>" "<f7>" "<f8>" "<f9>"
                              "<f10>" "<f11>" "<f12>" "1" "2" "3" "4" "5" "6"
                              "7" "8" "9" "0" "`" "~" "!" "@" "#" "$" "%" "^"
                              "&" "*" "(" ")" "-" "_" "=" "+" "\\" "|" "{" "["
                              "]" "}" ";" "'" ":" "\"" "<" ">" "," "." "/" "?"
                              ))
                  (n (length keys))
                  (modifiers (list "" "S-" "C-" "M-" "M-C-"))
                  (k))
             (or (string= arg "") (setq modifiers (list arg)))
             (setq k (length modifiers))
             (princ (format " %-10.10s |" "Key"))
             (let ((j 0))
               (while (< j k)
                 (princ (format " %-28.28s |" (nth j modifiers)))
                 (setq j (1+ j))))
             (princ "\n")
             (princ (format "_%-10.10s_|" "__________"))
             (let ((j 0))
               (while (< j k)
                 (princ (format "_%-28.28s_|"
                                "_______________________________"))
                 (setq j (1+ j))))
             (princ "\n")
             (while (< i n)
               (princ (format " %-10.10s |" (nth i keys)))
               (let ((j 0))
                 (while (< j k)
                   (let* ((binding
                           (key-binding (read-kbd-macro
                                         (concat (nth j modifiers)
                                                 (nth i keys)))))
                          (binding-string "_"))
                     (when binding
                       (if (eq binding 'self-insert-command)
                           (setq binding-string (concat "'" (nth i keys) "'"))
                         (setq binding-string (format "%s" binding))))
                     (setq binding-string
                           (substring binding-string 0
                                      (min (length binding-string) 28)))
                     (princ (format " %-28.28s |" binding-string))
                     (setq j (1+ j)))))
               (princ "\n")
               (setq i (1+ i)))
             (princ (format "_%-10.10s_|" "__________"))
             (let ((j 0))
               (while (< j k)
                 (princ (format "_%-28.28s_|"
                                "_______________________________"))
                 (setq j (1+ j))))))
         (delete-window)
         (hscroll-mode)
         (setq truncate-lines t)))


      ;; You can get a list of all the disabled functions by typing
      ;; `M-: (let(lst)(mapatoms(lambda(x)(if(get x 'disabled)(push x lst))))lst) RET'


      (defmacro rloop (clauses &rest body)
        (if (null clauses)
            `(progn ,@body)
          `(loop ,@(car clauses) do (rloop ,(cdr clauses) ,@body))))

      (defun all-bindings ()
        (interactive)
        (message "all-bindings: wait a few seconds please...")
        (let ((data
               (with-output-to-string
                 (let ((bindings '()))
                   (rloop ((for C in '("" "C-"))       ; Control
                           (for M in '("" "M-"))       ; Meta
                           (for A in '("" "A-"))       ; Alt
                           (for S in '("" "S-"))       ; Shift
                           (for H in '("" "H-"))       ; Hyper
                           (for s in '("" "s-"))       ; super
                           (for x from 32 to 127))
                          (let* ((k (format "%s%s%s%s%s%s%c" C M A S H s x))
                                 (key (ignore-errors (read-kbd-macro k))))
                            (when key
                              (push
                               (list k
                                     (format "%-12s  %-12s  %S\n" k key
                                             (or
                                              ;; (string-key-binding key)
                                              ;; What is this string-key-binding?
                                              (key-binding key))))
                               bindings))))
                   (dolist (item
                            (sort bindings
                                  (lambda (a b)
                                    (or (< (length (first a))
                                           (length (first b)))
                                        (and (= (length (first a))
                                                (length (first b)))
                                             (string< (first a)
                                                      (first b)))))))
                     (princ (second item)))))))
          (switch-to-buffer (format "Key bindings in %s" (buffer-name)))
          (erase-buffer)
          (insert data)
          (goto-char (point-min))
          (values)))

;;** 57.5 The (info "(emacs)Syntax") Table

      (section "57.5 The (emacs)Syntax Table")

      ;; ;; fix completion syntax for `text-mode-syntax-table' (syntax table used
      ;; ;; for editing text files)
      ;; (defun my/change-word-constituent ()
      ;;   (map nil
      ;;        (function
      ;;         (lambda (char)
      ;;           (modify-syntax-entry char "w" text-mode-syntax-table)))
      ;;        ;; include accented characters in completion syntax
      ;;        "áéíóúàèìòùâêîôûäëïöüñåç"))
      ;;
      ;; (my/change-word-constituent)

      ;; now '-' is not considered a word-delimiter
      ;; (add-hook 'emacs-lisp-mode-hook
      ;;           (lambda ()
      ;;             (modify-syntax-entry ?- "w")))

)

;;* App G Emacs and (info "(emacs)MS-DOS")

(chapter chapter-AppG-ms-dos "Appendix G Emacs and MS-DOS"

      ;; numeric keypad (needed in XEmacs for Windows)
      (XEmacs
       ;; keys to the right of the regular keyboard
       (define-key key-translation-map [kp-divide]     [?/])
       (define-key key-translation-map [kp-multiply]   [?*])
       (define-key key-translation-map [kp-subtract]   [?-])
       (define-key key-translation-map [kp-add]        [?+])
       (define-key key-translation-map [kp-enter]     [?\r])
       (define-key key-translation-map [kp-decimal]    [?.])

       ;; keys with digits
       (define-key key-translation-map [kp-0]          [?0])
       (define-key key-translation-map [kp-1]          [?1])
       (define-key key-translation-map [kp-2]          [?2])
       (define-key key-translation-map [kp-3]          [?3])
       (define-key key-translation-map [kp-4]          [?4])
       (define-key key-translation-map [kp-5]          [?5])
       (define-key key-translation-map [kp-6]          [?6])
       (define-key key-translation-map [kp-7]          [?7])
       (define-key key-translation-map [kp-8]          [?8])
       (define-key key-translation-map [kp-9]          [?9])

       ;; additional keypad duplicates of keys ordinarily found elsewhere
       (define-key key-translation-map [kp-left]     [left])
       (define-key key-translation-map [kp-right]   [right])
       (define-key key-translation-map [kp-up]         [up])
       (define-key key-translation-map [kp-down]     [down])
       (define-key key-translation-map [kp-begin]   [begin])
       (define-key key-translation-map [kp-home]     [home])
       (define-key key-translation-map [kp-end]       [end])
       (define-key key-translation-map [kp-next]     [next])
       (define-key key-translation-map [kp-prior]   [prior])
       (define-key key-translation-map [kp-insert] [insert])
       (define-key key-translation-map [kp-delete] [delete]))

      ;; divide key (needed in GNU Emacs for Windows)
      (GNUEmacs
       (global-set-key (kbd "<kp-divide>") (kbd "/")))
)

;;* Emacs Display

(chapter chapter-XX-emacs-display "XX Emacs Display"

;;** (info "(elisp)Faces")

      (section "Faces")

;; enable more bold and italic fonts to be displayed
(setq w32-enable-synthesized-fonts t)

      (defun merge-x-resources ()
        (let ((file (file-name-nondirectory (buffer-file-name))))
          (when (or (string= file ".Xdefaults")
                    (string= file ".Xresources"))
            (start-process "xrdb" nil "xrdb" "-merge" (buffer-file-name))
            (message (format "Merged %s into X resource database" file)))))

      (add-hook 'after-save-hook 'merge-x-resources)

      ;; allow any scalable font
      (when running-ms-windows
        (setq scalable-fonts-allowed t))

      ;; color sort order for `list-colors-display'
      (setq list-colors-sort '(rgb-dist . "#FFFFFF"))

;;** color-theme (emacs-goodies-el)

      ;; code was HERE. It has been temporarily moved to the beginning of the
      ;; `.emacs' (for testing purpose)

)

;;** 38.16 (info "(elisp)Images")

;;* Emacs IRC client

;; Other IRC for Emacs: rcirc, circe, bitlbee, liece, riece, zenirc, erc
;; Circe is advised by Tassilo (contributor)

(autoload 'circe "circe"
  "Connect to an IRC server" t)

;; connect to the Freenode network
(defun my/irc-connect ()
  "Connect to Freenode."
  (interactive)
  (circe "irc.freenode.net" "6667" "freenode"))

;; ... upon hitting `C-c i'
(global-set-key
 (kbd "C-c i") (lambda ()
                 (interactive)
                 (switch-or-start 'my/irc-connect
                                  "irc.freenode.net:6667")))

(eval-after-load "circe"
  '(progn

;;** 1 Basics

        ;; See http://en.wikipedia.org/wiki/List_of_IRC_commands
        ;; /whois
        ;; /leave

        ;; default channels to join whenever connecting to Freenode
        (setq circe-server-auto-join-channels
              '(("^freenode$"
                 ;; "#emacs"
                 ;; "#gnus"
                 ;; "#latex"
                 ;; "#ledger"
                 "#org-mode"
                 ;; "#stumpwm"
                 ;; "#zsh"
                 "#xemacs"
                 )))

;;** 2 Reference

;;*** 2.3 Configuration

        ;; default nick
        (setq circe-default-nick "john_doe")

        ;; your "real name" on IRC
        (setq circe-default-realname "John Doe")

        ;; authentication info
        (setq freenode-passwd "")
        (setq circe-nickserv-passwords
              `(("freenode" ,freenode-passwd)))

;;** 3 Fighting Information Overload

;;*** 3.1 Channels

      ;; When other people say things in buffers that are currently buried (no
      ;; window is showing them), the mode line will now show you the
      ;; abbreviated channel or nick name. Use `C-c C-SPC' to switch to these
      ;; buffers.

;;*** 3.3 Keywords

        ;; list of keywords to highlight
        (setq lui-highlight-keywords
              '(
                ;; "[^<]vauban"
                "org" "beamer" "ledger" "tikz"))

        (eval-after-load "circe"
          '(progn

             ;; add IRC color support to LUI
             (require 'lui-irc-colors)

             (add-to-list 'lui-pre-output-hook 'lui-irc-colors)))

;;** 4 Hacking and Tweaking

;;*** 4.2 Using fly spell mode

        ;; check if `ispell-program-name' seems correct
        (when (executable-find ispell-program-name)
          (setq lui-flyspell-p t)
          (setq lui-flyspell-alist '(("." "en_US"))))

;;** Others

        (setq circe-highlight-nick-type 'occurrence)

        (when (try-require 'circe-highlight-all-nicks)
          (enable-circe-highlight-all-nicks))

        ;; format for messages to queries or channels
        (setq circe-format-self-say "<{nick}> {body}")

        ;; truncate the buffer (at the top) if it grows too much
        (setq lui-max-buffer-size 30000)

        ;; column at which Lui should break output
        (setq lui-fill-column 78)

        ))

        ;; Gtalk
        (setq jabber-account-list
              '(("john@doe.com"
                 (:network-server . "talk.google.com")
                 (:connection-type . ssl))))

(when (try-require 'emms-auto)
  ;; first good use for the pause key in a very long time!
  (global-set-key (kbd "<pause>") 'emms-pause))

;; multi-buffer occur (grep) mode
(mapc (function (lambda (x) (autoload x "color-moccur" nil t)))
      '(moccur
	dmoccur
	dired-do-moccur
	Buffer-menu-moccur
	grep-buffers
	search-buffers
	occur-by-moccur
	isearch-moccur
	moccur-grep
	moccur-grep-find))

(setq moccur-split-word t)

;; Recovery from Problems

;;* Debugging

(chapter chapter-99-debugging "99 Debugging"

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


      (ad-disable-advice 'message 'before 'when-was-that)
      (ad-update 'message)


      ;; get the backtrace when uncaught errors occur
      (setq debug-on-error nil)) ;; was set to `t' at beginning of buffer

;; Load user specific config if we find it
(let* ((file "~/.emacs-post-init-file")
       (gpg (concat file ".gpg")) ;; to keep secrets secret
       (el (concat file ".el")))
  (cond ((file-readable-p gpg) (load-file gpg))
        ((file-readable-p el) (load-file el))))


(message "... Emacs Config Fni loading time: %.2f seconds ..."
         (- (float-time) my/emacs-load-time-start))
(sit-for 1)

(message "* End of Emacs Config Fni...")

(message "| Chapter | Time |")
(message "|-------------------------------------------------+---------|")
(mapcar (lambda (el) (message el))
        (nreverse my/load-times-list))
(message "|-------------------------------------------------+---------|")
(message "|                                                 | =vsum(@-I..@-II) |")


(provide 'emacs-config-fni)


;; This is for the sake of Emacs.
(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.
 '(column-number-mode t)
 '(ecb-options-version "2.40")
 '(font-use-system-font t)
 '(show-paren-mode t)
 '(tool-bar-mode nil))
(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.
 '(default ((t (:inherit nil :stipple nil :background "#ffffff" :foreground "#221f1e" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 113 :width normal :foundry "unknown" :family "DejaVu Sans Mono")))))
;; Local Variables:
;; coding: utf-8
;; eval: (when (locate-library "rainbow-mode") (rainbow-mode))
;; ispell-local-dictionary: "en_US"
;; End:

;;; emacs-config-fni.el ends here

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2012-07-05  6:37 UTC | newest]

Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2012-07-05  6:37 ECB configuration Sajid Hussain

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).