Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 10212 lines (7755 sloc) 356.313 kb
;;; .emacs --- my Emacs Init File
;; Copyright (C) 1999-2010 Fabrice Niessen
;; Time-stamp: <2010-07-09 Fri 11:40 sva on mundaneum>
;; Author: Fabrice Niessen <(concat "fni" at-symbol "")>
;; Keywords: emacs, dotfile, config
;; $Revision: 4145 $
;; $Date: 2010-07-08 15:13:00 +0200 (Thu, 08 Jul 2010) $
;; ___ _ __ ___ __ _ ___ ___
;; / _ \ '_ ` _ \ / _` |/ __/ __|
;; | __/ | | | | | (_| | (__\__ \
;; (_)___|_| |_| |_|\__,_|\___|___/
;; 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 2 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
;; 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, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.
;;; Commentary:
;; 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]
;; 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).
;; 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.
;; - `C-x SPC' = gud-break, unknown function
;; - menu-bar-mode disappears sometimes
;;; Emacs Tour
;; XXX Go and see
;;; Code:
;; This file is only provided as an example. Customize it to your own taste!
;;* Prerequisites
(message "* --[ Loading my Emacs init file ]--")
;; uptimes
(setq emacs-load-start-time (current-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'.
;; turn on Common Lisp support
(require 'cl) ; provides useful things like `loop' and `setf'
;; ;; keep my secrets secret (and not in my `.emacs' file)
;; (let ((personal-settings "~/.hide/.emacs-secrets.gpg"))
;; (when (file-exists-p personal-settings)
;; (load personal-settings)))
;; allow quick include/exclude of setup parts
(defvar section-environment t) ; required
(defvar section-loading-libraries t) ; required
(defvar section-debugging t)
(defvar section-screen t)
(defvar section-basic t)
(defvar section-minibuffer t)
(defvar section-help t)
(defvar section-mark t)
(defvar section-killing t)
(defvar section-yanking t)
(defvar section-rectangles t)
(defvar section-cua-bindings t)
(defvar section-registers t)
(defvar section-display t)
(defvar section-search t)
(defvar section-fixit t)
(defvar section-keyboard-macros t)
(defvar section-files t)
(defvar section-buffers t)
(defvar section-windows t)
(defvar section-frames t)
(defvar section-international t)
(defvar section-major-modes t)
(defvar section-indentation t)
(defvar section-text t)
(defvar section-programs t)
(defvar section-building t)
(defvar section-maintaining t)
(defvar section-abbrevs t)
(defvar section-dired t)
(defvar section-calendar-diary t)
(defvar section-document-view t)
(defvar section-gnus t)
(defvar section-shell t)
(defvar section-emacs-server t)
(defvar section-printing t)
(defvar section-sorting t)
(defvar section-narrowing t)
(defvar section-saving-emacs-sessions t)
(defvar section-hyperlinking t)
(defvar section-amusements t)
(defvar section-pgg t)
(defvar section-customization t)
(defvar section-ms-dos t)
(defvar section-emacs-display t)
;;** Environment
(when section-environment (message "0 Environment...")
;; OS type --- are we running Microsoft Windows?
(defvar running-ms-windows
(eq system-type 'windows-nt))
(defvar running-ms-windows
(string-match "windows" (prin1-to-string system-type)))
(defvar running-gnu-linux
(string-match "linux" (prin1-to-string system-type)))
;; Emacs type --- are we running XEmacs (or GNU Emacs)?
(defvar running-xemacs
(string-match "XEmacs" emacs-version))
;; OS type --- are we running GNU Linux?
(defmacro GNULinux (&rest body)
(list 'if (string-match "linux" (prin1-to-string system-type))
(cons 'progn body)))
(defmacro Windows (&rest body)
(list 'if (string-match "windows" (prin1-to-string system-type))
(cons 'progn body)))
(defmacro XLaunch (&rest body)
(list 'if (eq window-system 'x)(cons 'progn body)))
;; Emacs type --- are we running GNU Emacs?
(defmacro GNUEmacs (&rest body)
"Execute any number of forms if running under GNU Emacs."
(list 'if (string-match "GNU Emacs" (version))
(cons 'progn body)))
(defmacro GNUEmacs23 (&rest body)
(list 'if (string-match "GNU Emacs 23" (version))
(cons 'progn body)))
(defmacro GNUEmacs22 (&rest body)
(list 'if (string-match "GNU Emacs 22" (version))
(cons 'progn body)))
(defmacro XEmacs (&rest body)
"Execute any number of forms if running under XEmacs."
(list 'if (string-match "XEmacs" (version))
(cons 'progn body)))
;; Emacs version
(list emacs-version emacs-major-version emacs-minor-version
system-type system-name system-configuration
(when (boundp 'aquamacs-version) aquamacs-version)))
;; don't offer migration of the init file
(setq load-home-init-file t))
(when running-gnu-linux
'((height . 32))))
(message "0 Environment... Done"))
;;** Loading Libraries of Lisp Code for Emacs
(when section-loading-libraries (message "0 Loading Libraries...")
;; make loaded files give a message
(defadvice load (before debug-log activate)
(message "Loading %s..." (locate-library (ad-get-arg 0)))))
;; load-path enhancement
(defun fni/add-to-load-path (this-directory &optional with-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 WITH-SUBDIRS is not nil.
Do it recursively if the third argument is not nil."
(when (and this-directory
(file-directory-p this-directory))
(let* ((this-directory (expand-file-name this-directory))
(files (directory-files this-directory t "^[^\\.]")))
;; completely canonicalize the directory name (*may not* begin with `~')
(while (not (string= this-directory (expand-file-name this-directory)))
(setq this-directory (expand-file-name this-directory)))
(message "Adding `%s' to load-path..." this-directory)
(add-to-list 'load-path this-directory)
(when with-subdirs
(while files
(setq dir-or-file (car files))
(when (file-directory-p dir-or-file)
(if recursive
(fni/add-to-load-path dir-or-file 'with-subdirs 'recursive)
(fni/add-to-load-path dir-or-file)))
(setq files (cdr files)))))))
;; Use `M-x list-load-path-shadows RET' to display a list of external Emacs
;; Lisp files that shadow Emacs builtins (listing potential load path
;; problems).
;;*** Features
;; ;; 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 file)
;; "Leave a trace of packages being loaded."
;; (cond ((member feature features)
;; (message "%sRequiring `%s' (already loaded)"
;; (concat (make-string (* 2 my-require-depth) ?-) "> ")
;; feature)
;; (sit-for 0))
;; (t
;; (message "%sRequiring `%s'"
;; (concat (make-string (* 2 my-require-depth) ?-) "> ")
;; feature)
;; (sit-for 0)
;; (let ((my-require-depth (+ 1 my-require-depth)))
;; (cond (file
;; (orig-require feature file))
;; (t
;; (orig-require feature))))
;; (message "%sRequiring `%s'...done"
;; (concat (make-string (* 2 my-require-depth) ?-) "> ")
;; feature)
;; (sit-for 0))))
(defvar missing-packages-list nil
"List of packages that `try-require' can't find.")
;; attempt to load a feature/library, failing 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."
(condition-case err
;; protected form
(message "Checking for library `%s'..." feature)
(if (stringp feature)
(load-library feature)
(require feature))
(message "Checking for library `%s'... Found" feature))
;; error handler
(file-error ; condition
(message "Checking for library `%s'... Missing" feature)
(add-to-list 'missing-packages-list feature 'append))
;;*** Library Search
;; `load-path' is a list of directories where Emacs Lisp libraries (`.el' and
;; `.elc' files) are installed.
;; `exec-path' is different: it is a list of directories where executable
;; programs are installed.
;; Shouldn't be `exec-path' and `PATH' achieve the same goal under Emacs?
;; No. `exec-path' is used by Emacs to search for programs it runs directly.
;; But `M-x grep' does not run `grep.exe' directly; it runs the shell passing
;; it a command that invokes `grep'. So it's the shell that needs to find
;; `grep.exe', and it uses PATH, of course, not `exec-path'.
;; So the right thing to do when you install a new program, in order for Emacs
;; to find it, is *both* to update `exec-path' *and* update `PATH'. This is
;; because some Emacs features invoke programs directly, while others do that
;; through the shell or some other intermediary programs.
;; The most important directories are the last!
;; TODO Specify variables using `defcustom'
;; 1.
(defvar distro-site-lisp-directory
(concat (or (getenv "SHARE")
"/usr/share") "/emacs/site-lisp/")
"Name of directory where additional Emacs goodies Lisp files (from the
distro optional packages) reside.")
(fni/add-to-load-path distro-site-lisp-directory
;; If you put stuff you have installed from tar balls, etc. within the same
;; directory hierarchy as the distro packaged Emacs, you can get problems when
;; upgrading the distro version as many package systems will assume once all
;; the packaged stuff is removed, directories are empty. If they are not, the
;; package management scripts can fail or possibly get into a "confused"
;; state.
;; 2.
(defvar local-site-lisp-directory
(concat (or (getenv "LOCAL_SHARE")
"~/Downloads") "/emacs/site-lisp/")
"Name of directory where additional Emacs goodies Lisp files (from the
Internet) reside.")
(fni/add-to-load-path local-site-lisp-directory
'with-subdirs 'recursive)
;; `local-site-lisp-directory' is there so that you have an easy way of
;; installing your own (possibly not distro packaged) Emacs add-ons which are
;; specific to the version of Emacs your running. This keeps your local
;; add-ons apart from distro supplied ones. If your have a `/usr/local'
;; partition, it also means you can do a complete re-install of Emacs (or even
;; your Linux distro) without impacting on stuff you have added by hand.
;; 3.
(defvar my-site-lisp-directory "~/emacs/site-lisp/"
"Name of directory where my personal additional Emacs Lisp files reside.")
(fni/add-to-load-path my-site-lisp-directory
;; 4.
;; automatically compile `.el' files as they're loaded
(setq load-source-file-function 'load-with-code-conversion) ; for XEmacs
(when (try-require 'byte-code-cache-XXX)
(require 'bytecomp)
;; directory in which we store cached byte-compiled files
(setq bcc-cache-directory
;; FIXME Concat env var (so that it can be stored locally on C:)
(running-gnu-linux "~/.emacs.d/byte-cache-linux")
(running-ms-windows "~/.emacs.d/byte-cache-ms-windows")))
(fni/add-to-load-path bcc-cache-directory))
;; load elisp libraries while Emacs is idle
(if (try-require 'idle-require-XXX)
;; idle time (in seconds) after which autoload functions will be loaded
(setq idle-require-idle-delay 5)
;; time in seconds between automatically loaded functions
(setq idle-require-load-break 3)
;; load unloaded autoload functions when Emacs becomes idle
(idle-require-mode 1)
(defun try-idle-require (feature)
(when (locate-library (symbol-name feature))
(idle-require feature))))
(defun try-idle-require (feature)
(when (locate-library (symbol-name feature))
(require feature))))
(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)
(concat "Cannot continue without directory `" dir "'"))))
(error "my-make-directory-yes-or-no: missing operand")))
(defun my-file-executable-p (file)
"Make sure the file FILE exists and is executable."
(if file
(if (file-executable-p 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-executable-p: missing operand")))
(message "0 Loading Libraries... Done"))
;;** Debugging
(when section-debugging (message "0 Debugging...")
;; ;; 2008-05-23 set it to nil to temporarily avoid the broken vc functions
;; ;; get the backtrace when uncaught errors occur
;; (setq debug-on-error t) ; will be unset at the end
(setq stack-trace-on-error t))
;; ;; hit `C-g' while it's frozen to get an ELisp backtrace
;; (setq debug-on-quit t)
(message "0 Debugging... Done"))
;;* Important General Concepts
;;** 1 The Organization of the (info "(emacs)Screen")
(when section-screen (message "1 The Organization of the Screen...")
;;*** 1.2 The (info "(emacs)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'
(message "1 The Organization of the Screen... Done"))
;;* Fundamental Editing Commands
;;** 7 (info "(emacs)Basic") Editing Commands
(when section-basic (message "7 Basic Editing Commands...")
;;*** 7.1 (info "(emacs)Inserting Text")
;; use decimal for `C-q'
(setq read-quoted-char-radix 10)
;;*** 7.2 (info "(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
(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))
(setq start (point))
(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
;; undo some previous changes
(global-set-key (kbd "<f11>") 'undo)
;; redo the most recent undo
(when (try-require 'redo)
(global-set-key (kbd "<S-f11>") 'redo))
;;*** 7.8 (info "(emacs)Continuation Lines")
(defun my-wrap-mode-on ()
"Minor mode for making buffer not wrap long lines to next line."
(setq truncate-lines nil))
(defun my-wrap-mode-off ()
"Minor mode for making buffer wrap long lines to next line."
(setq truncate-lines t))
(defun my-toggle-wrap-mode ()
"Switch wrap mode from wrap to non-wrap, or vice-versa."
(if (eq truncate-lines nil)
;;*** 7.11 (info "(emacs)Repeating") a Command
;; repeat last command passed to `shell-command'
(defun repeat-shell-command ()
"Repeat most recently executed shell command."
(or shell-command-history (error "Nothing to repeat."))
(shell-command (car shell-command-history)))
(global-set-key (kbd "C-c j") 'repeat-shell-command)
(message "7 Basic Editing Commands... Done"))
;;** 8 The (info "(emacs)Minibuffer")
(when section-minibuffer (message "8 The Minibuffer...")
;;*** 8.1 (info "(emacs)Minibuffer File") Names
;; ignore case when reading a file name completion
(setq read-file-name-completion-ignore-case t)
;; dim the ignored part of the file name
(file-name-shadow-mode 1))
;;*** 8.2 (info "(emacs)Minibuffer Edit")ing
;; 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")
;; ;; allow to type space chars in minibuffer input
;; ;; (for `timeclock-in', for example)
;; (define-key minibuffer-local-completion-map " " nil)
;; (define-key minibuffer-local-must-match-map " " nil)
;; minibuffer completion incremental feedback
;; 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)
;;> I frequently find myself doing `C-M :' for some quick elisp calls, and
;;> find it tedious to type expressions. Is there some way to allow
;;> completion when writing a sexp in the minibuffer? I'd like this to work
;;> similar to the way `M-x' helps you complete some command.
;;;;;;(define-key read-expression-map (kbd "TAB") 'lisp-complete-symbol)
(message "8 The Minibuffer... Done"))
;;** 10 (info "(emacs)Help")
(when section-help (message "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.4 (info "(emacs)Apropos")
;; You can ask what pertains to a given topic by typing
;; `M-x apropos RET pattern RET'
;; 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')
(define-key help-map (kbd "A") 'apropos-variable))
;;*** 10.8 (info "(emacs)Misc Help") Commands
;; ls -l /usr/share/info/dir*
;; update-info-dir
;; Info documentation browse
(when (try-require 'info)
;; enter Info
(global-set-key (kbd "<f1>") 'info)
;; list of directories to search for Info documentation files
;; (in the order they are listed)
(setq Info-directory-list
(cond (running-ms-windows
(append Info-default-directory-list
`(,(concat (getenv "SHARE") "/info/")
;; I find this handy:
;; (setq Info-directory-list
;; `("~/.emacs.d/info" ,@Info-directory-list))
;;; ;; adding doc for Org mode
;;; (setq Info-default-directory-list
;;; (cons (expand-file-name
;;; (concat org-general-path "org/doc"))
;;; Info-default-directory-list))
;; adding TexLive?
(setq Info-directory-list
;;; dir files will be merged by emacs, so you can create
;;; one for your local additions. Probably by copying the
;;; systems one from /usr/share/info/dir or wherever, delete
;;; all entries after '* Menu:' and put in your own.
;;; (info "(texinfo)Other Info Directories")
;;; The dir file has to have a special header format. Just copy the
;;; systems one into a directory in INFOPATH, erase everything after
;;; '*Menu ' and put in your own stuff.
;;; Wouldn't the use of install-info be more appropriate? When the
;;; actual info file is well prepared, then this programme does a
;;; perfect job, sorting the info file into its proper section ...
;; The canonical way to do that is to set the environment variable `INFOPATH'
;; outside of Emacs, in the same shell from which you invoke Emacs.
;; `INFOPATH's value should be a list of Info directories in the same format
;; as the `PATH' variable on your system.
;; The environment variable INFOPATH tells GNU Emacs where to look for info
;; files.
;; If you want, you can edit the dir files and remove entries. The utility
;; install-info is used to maintain the dir file.
;; See, "Installing Gnus":
;; In order to get the Gnus info pages added to your documentation, also
;; augment the INFOPATH environment variable, like
;; INFOPATH=$INFOPATH:/usr/local/share/emacs/site-lisp/gnus-5.8.8/texi
;; export INFOPATH
;; The above should go in your shell startup file, such as ~/.profile.
;;; > Is there an automated procedure to transfer the additional info files
;;; > and info/dir entries into the new emacs?
;;; Copy the files, then run install-info on them to update the info/dir file.
;; Don't play with `Info-directory-list', it's not intended to be settable by
;; the user
;; 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))
(try-require 'info+))
;; with `info+.el', you can merge an Info node with its subnodes into
;; the same buffer, by calling `Info-merge-subnodes' (bound to `+')
;; `C-h K' goes to the node in the Emacs manual describing the command
;; bound to a key.
;; dictem (dict protocol and dictem for a documentation)
;; describe-function
;; avoid the description of all minor modes
(defun describe-major-mode ()
"Describe only `major-mode'."
(describe-function major-mode))
;; find convenient unbound keystrokes
(try-require 'unbound) ; `M-x describe-unbound-keys'
;; 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)))
;; same behavior as woman when manpage is ready
(setq Man-notify-method 'newframe)
;; (setq Man-frame-parameters '((foreground-color . "black")
;; (background-color . "grey90")
;; (cursor-color . "black")
;; (mouse-color . "gold")
;; (width . 80)
;; (tool-bar-lines . 0)))
;; browse Unix manual pages "W.o. (without) Man"
(when (try-require 'woman)
;; list of directory trees to search for Unix manual files
(setq woman-manpath
(cond (running-ms-windows
`(,(concat (getenv "SHARE") "/man/")
;;*** Documentation Basics
;; jump to section in XEmacs Lisp Reference manual
(autoload 'lispref-search "lispref")
(define-key help-map (kbd "L") 'lispref-search)
(message "10 Help... Done"))
;;* Important Text-Changing Commands
;;** 11 The (info "(emacs)Mark") and the Region
(when section-mark (message "11 The Mark and the Region...")
;;*** 11.7 (info "(emacs)Persistent Mark")s
;; when the mark is active, the *region is highlighted*
;; (enabled by default in Emacs 23)
(when window-system
(transient-mark-mode 1)))
(message "11 The Mark and the Region... Done"))
;;** 12 (info "(emacs)Killing") and Moving Text
(when section-killing (message "12 Killing and Moving Text...")
;;*** 12.3 (info "(emacs)Other Kill Commands")
;; Change cutting behavior:
;; "Many times you'll do a kill-line command with the only intention of
;; getting the contents of the line into the killring. Here's an idea stolen
;; from Slickedit, if you press copy or cut when no region is active, you'll
;; copy or cut the current line."
;; <>
(defadvice kill-ring-save (before slickcopy activate compile)
"When called interactively with no active region, copy the
current line instead."
(if mark-active (list (region-beginning) (region-end))
(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."
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
(message "12 Killing and Moving Text... Done"))
;;** 13 (info "(emacs)Yanking")
(when section-yanking (message "13 Yanking...")
;;*** 13.1 The (info "(emacs)Kill Ring")
;; auto-indent pasted code
(defadvice yank (after indent-region activate)
(if (member major-mode
'(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode
objc-mode latex-mode plain-tex-mode python-mode))
(indent-region (region-beginning) (region-end) nil)))
(defadvice yank-pop (after indent-region activate)
(if (member major-mode
'(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode
objc-mode latex-mode plain-tex-mode python-mode))
(indent-region (region-beginning) (region-end) nil)))
;;*** 13.3 Yanking (info "(emacs)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
;; 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 "Blueviolet" :weight bold))) nil)
; slate gray
(setq browse-kill-ring-separator-face 'separator-face)
;; use `M-y' to invoke `browse-kill-ring'
(message "13 Yanking... Done"))
;;** 15 (info "(emacs)Rectangles")
(when section-rectangles (message "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.
(message "15 Rectangles... Done"))
;;** 16 (info "(emacs)CUA Bindings")
(when section-cua-bindings (message "16 CUA Bindings...")
;; CUA mode sets up key bindings used in many other applications (`C-x',
;; `C-c', `C-v' and `C-z').
;; The `C-x' and `C-c' keys only do cut and copy when the region is active, so
;; in most cases, they do not conflict with the normal function of these
;; prefix keys.
;; If you really need to perform a command which starts with one of the prefix
;; keys even when the region is active, you have three options:
;; - press the prefix key twice very quickly (within 0.2 seconds),
;; - press the prefix key and the following key within 0.2 seconds, or
;; - use the SHIFT key with the prefix key, i.e. `C-S-x' or `C-S-c'.
;; You can customize `cua-enable-cua-keys' to completely disable the CUA
;; bindings, or `cua-prefix-override-inhibit-delay' to change the prefix
;; fallback behavior.
;; CUA mode also provides enhanced rectangle support with visible rectangle
;; highlighting. Check out "Emacs Column Editing" at
;; `C-RET' runs the command `cua-set-rectangle-mark'
;; `M-n' runs the command `cua-sequence-rectangle'
;; ;; activate CUA mode
;; (cua-mode t)
;; standard Windows behavior
(setq cua-keep-region-after-copy t)
;; fix funny things of cursor moving commands
(add-hook 'cua-mode-hook
(lambda ()
(dolist (cmd '(forward-char
(put cmd 'CUA nil))))
(message "16 CUA Bindings... Done"))
;;** 17 (info "(emacs)Registers")
(when section-registers (message "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")
;; 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
;; 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-remember-last-stored
;; `----
;; visible bookmarks in buffer
;; repository should be restored when loading `bm'
(setq bm-restore-repository-on-load t)
(when (try-require 'bm)
;; key binding
(global-set-key (kbd "<M-f2>") 'bm-toggle)
;; buffer should be recentered around the bookmark
(setq bm-recenter t)
;; make bookmarks persistent as default
(setq-default bm-buffer-persistence t)
;; loading the repository from file when on start up
(add-hook' after-init-hook 'bm-repository-load)
;; 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
;; update bookmark repository when saving the file
(add-hook 'after-save-hook 'bm-buffer-save))
;; lists all bookmarks in all buffers
(try-require 'bm-ext))
(message "17 Registers... Done"))
;;** 18 Controlling the (info "(emacs)Display")
(when section-display (message "18 Controlling the Display...")
;;*** 18.1 (info "(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")
;; make buffer size irrelevant for fontification
(setq font-lock-maximum-size nil)
;; stop showing that annoying progress bar when fontifying
(setq progress-feedback-use-echo-area nil)
;; enable Font Lock mode
;; highlight non-breaking spaces
(require 'disp-table)
(aset standard-display-table
(make-char 'latin-iso8859-1 (- ?\240 128))
(vector (+ ?\267 (* 524288 (face-id 'nobreak-space))))))
;; special words
;; XXX add `fatal', and `Undefined'
(setq keywords-critical-pattern
(make-face 'keywords-critical)
(GNUEmacs (set-face-attribute 'keywords-critical nil
:foreground "red" :background "yellow"
:weight 'bold))
(setq keywords-org-critical-pattern
"\\(BUGS\\|FIXME\\|XXX\\|[^*] TODO\\|[Ee][Rr][Rr][Oo][Rr]\\|[Mm][Ii][Ss][Ss][Ii][Nn][Gg]\\|[Ii][Nn][Vv][Aa][Ll][Ii][Dd]\\|[Ff][Aa][Ii][Ll][Ee][Dd]\\|[Cc][Oo][Rr][Rr][Uu][Pp][Tt][Ee][Dd]\\)")
; 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...
(make-face 'keywords-org-critical)
(GNUEmacs (set-face-attribute 'keywords-org-critical nil
:foreground "red" :background "yellow"
:weight 'bold))
(setq keywords-normal-pattern "\\([Ww][Aa][Rr][Nn][Ii][Nn][Gg]\\)")
(make-face 'keywords-normal)
(GNUEmacs (set-face-attribute 'keywords-normal nil
:foreground "magenta2" :background "yellow"))
;; set up highlighting of special words for proper selected major modes only
(dolist (mode '(fundamental-mode
text-mode)) ; no interference with Org mode (which derives
; from text-mode)
(font-lock-add-keywords mode
`((,keywords-critical-pattern 1 'keywords-critical prepend)
(,keywords-normal-pattern 1 'keywords-normal prepend))))
;; set up highlighting of special words for Org mode only
(dolist (mode '(org-mode))
(font-lock-add-keywords mode
`((,keywords-org-critical-pattern 1 'keywords-org-critical prepend)
(,keywords-normal-pattern 1 'keywords-normal prepend))))
;; add fontification patterns (even in comments) to a selected major mode
;; *and* all major modes derived from it
(defun fontify-keywords ()
;;; (font-lock-mode -1)
;;; (font-lock-mode 1)
(font-lock-add-keywords nil
`((,keywords-critical-pattern 1 'keywords-critical prepend)
(,keywords-normal-pattern 1 'keywords-normal 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
(add-hook hook 'fontify-keywords))
;;*** 18.9 (info "(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 for
;; searching regexp in buffer
;; "identical token highlighting" commands
(when (try-require 'highlight)
(defface hlt-1 '((t (:background "#FFFFA0"))) nil)
(defface hlt-2 '((t (:background "#A0FFA0"))) nil)
(defface hlt-3 '((t (:background "#A0FFFF"))) nil)
(defface hlt-4 '((t (:background "#FFA0FF"))) nil)
(defface hlt-5 '((t (:background "#FFA0A0"))) nil)
(defface hlt-6 '((t (:background "#FFFFA0"))) nil)
(defface hlt-7 '((t (:background "#A0FFA0"))) nil)
(defface hlt-8 '((t (:background "#A0FFFF"))) nil)
(defface hlt-9 '((t (:background "#FFA0FF"))) nil)
(defface hlt-10 '((t (:background "#FFA0A0"))) nil)
(global-set-key (kbd "C-S-p") 'hlt-previous-highlight)
(global-set-key (kbd "C-S-n") 'hlt-next-highlight)
(defun hlt-highlight-current-word ()
(let ((var_name (current-word t)))
(when var_name
(regexp-quote var_name))))))
;; emulation of Vim's `*' search
(global-set-key (kbd "C-*") 'hlt-highlight-current-word)
;; ;; 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)
;; ;; 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
;; (when (try-require 'light-symbol)
;; (light-symbol-mode))
;; highlight current symbol
(setq highlight-symbol-idle-delay 0.5)
(when (try-require 'highlight-symbol)
;;*** 18.11 (info "(emacs)Displaying Boundaries")
;; visually indicate buffer boundaries and scrolling
(setq indicate-buffer-boundaries t)
;;*** 18.12 (info "(emacs)Useless Whitespace")
;; highlight trailing whitespaces in all modes
(setq-default show-trailing-whitespace t)
;; ;; FIXME When turned on, Gnus becomes black and white only...
;; (when (try-require 'show-wspace)
;; ;; Highlight tabs
;; (add-hook 'font-lock-mode-hook 'show-ws-highlight-tabs)
;; ;; Highlight trailing whitespace
;; (add-hook 'font-lock-mode-hook 'show-ws-highlight-trailing-whitespace)
;; ;; Highlight non-breaking spaces
;; (add-hook 'font-lock-mode-hook 'show-ws-highlight-hard-spaces))
;; FIXME Same problem as above
;; ;; highlight tabs in all modes
;; (add-hook 'font-lock-mode-hook
;; '(lambda ()
;; (font-lock-add-keywords
;; nil
;; '(("\t" 0 'trailing-whitespace prepend)))))
;; 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 "*")
(untabify (point-min) (point-max)))
;; visually indicate empty lines after the buffer end
(setq-default indicate-empty-lines t)
;;*** 18.14 (info "(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)
;; 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
;; convert a buffer from DOS `^M' end of lines to Unix end of lines
(defun dos-to-unix ()
"Cut all visible ^M from the current buffer."
(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 unix-to-dos ()
(goto-char (point-min))
(while (search-forward "\n" nil t)
(replace-match "\r\n"))))
;; Bad interaction with CVSNT/diff/... (not yet understood)
;; ;; 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)))
;; (search-forward-regexp "\015$" nil t))
;; ;: a ^M is found
;; (if (or (= (preceding-char) ?\^J)
;; (= (following-char) ?\^J) )
;; (if (y-or-n-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")
;; 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
(when (try-require 'column-marker)
(dolist (hook '(emacs-lisp-mode-hook
(add-hook hook (lambda ()
(column-marker-1 78)
(column-marker-2 79)
(column-marker-3 80))))
;; use `C-c m' interactively to highlight with `column-marker-1-face'
(global-set-key (kbd "C-c m") 'column-marker-1))
;;*** 18.17 (info "(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
;; see what I'm typing *immediately*
(setq echo-keystrokes 0.01)
;;*** Temporary Displays
;; make the help, apropos and completion windows the right height for their
;; contents
(temp-buffer-resize-mode t)) ; auto-fit the *Help* buffer to its contents
;; enhanced display of temporary windows (such as help buffers)
;; (try-require 'show-temp-buffer) [bug with XEmacs 21.5]
(message "18 Controlling the Display... Done"))
;;** 19 (info "(emacs)Search")ing and Replacement
(when section-search (message "19 Searching and Replacement...")
;;*** 19.1 (info "(emacs)Incremental Search")
;; Have a look at the "Standard Isearch Keys" on
;; 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)))
;;*** 19.4 (info "(emacs)Regexp Search")
;; You can build regexps with visual feedback by using:
;; - `M-x re-builder' or
;; - `M-x regex-tool' (by John Wiegley, get it from
;; 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 ()
(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))
;;*** 19.8 (info "(emacs)Search Case")
;; searches and matches should ignore case
(setq-default case-fold-search t)
(setq default-case-fold-search t) ; FIXME obsolete since Emacs 23.2, but
; still needed!?
;;*** 19.9 (info "(emacs)Replace")ment Commands
;; You can force a matched regex text pattern to upper case by entering
;; `C-M-% your_regexp RET \,(upcase \num_of_match)'
;;*** 19.10 (info "(emacs)Other Repeating Search") Commands
(defun isearch-occur ()
"Invoke `occur' from within isearch."
(let ((case-fold-search isearch-case-fold-search))
(occur (if isearch-regexp isearch-string (regexp-quote isearch-string)))))
(define-key isearch-mode-map (kbd "C-o") 'isearch-occur)
;; `M-x flush-lines' deletes each line that contains a match for REGEXP
(message "19 Searching and Replacement... Done"))
;;** 20 Commands for (info "(emacs)Fixit") Typos
(when section-fixit (message "20 Commands for Fixing Typos...")
;;*** 20.1 (info "(emacs)Undo")
;; (GNUEmacs
;; ;; keep no more undo information once it exceeds this size
;; (setq undo-limit (* 4 undo-limit)) ; 4 * 20 MB (default)
;; ;; don't keep more than this much size of undo information
;; (setq undo-strong-limit (* 4 undo-strong-limit))) ; 4 * 30 MB (default)
;;*** 20.4 Checking and Correcting (info "(emacs)Spelling")
;; aspell -H list Article.html
;; aspell -H check Article.html
;; Then hold your finger down on the `a' (add) or `l' (add lower case) key.
;; use Hunspell or GNU Aspell instead of `ispell'
(setq-default ispell-program-name
(cond (running-ms-windows
"C:/Program Files/Aspell/bin/aspell.exe")
(if (file-executable-p "/usr/bin/hunspell")
(my-file-executable-p ispell-program-name)
(when (and ispell-program-name
(file-executable-p ispell-program-name))
(require 'ispell)
(eval-after-load "ispell"
;; so that following modifications won't be lost when ispell is loaded
;; default dictionary to use (if `ispell-local-dictionary' is nil)
(setq ispell-dictionary "fr_FR")
;; save the personal dictionary without confirmation
(setq ispell-silently-savep t)
;; extra switches to pass to the `ispell' program
;; TODO Check they are right!
(setq ispell-extra-args
(cond ((equal ispell-program-name "/usr/bin/hunspell")
;; '("-a" "-i" "utf-8"))
; aspell doesn't understand `-i
; utf-8', hunspell needs it
; 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.
;; 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!!!
(setq ispell-dictionary-alist
;; those not here will be "undefined dictionary"
;; default
"[A-Za-z]" "[^A-Za-z]"
"[']" nil ("-B") nil iso-8859-1)
;; Yankee English
"[A-Za-z]" "[^A-Za-z]"
"[']" nil ("-B") nil utf-8)
;; Spanish mode
"[a-zñáàéèíìóòúùüA-ZÑÁÀÉÈÍÌÓÒÚÙÜ]" "[^a-zñáàéèíìóòúùüA-ZÑÁÀÉÈÍÌÓÒÚÙÜ]"
"[-]" nil ("-B") "~tex" iso-8859-1)
;; standard French
"[a-zàâäéèêëîïôöùûüçA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ]" "[^a-zàâäéèêëîïôöùûüçA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ]"
"[-']" t nil "~list" utf-8)
;; Nederlands.aff
"[a-zàâçëîïôùûüA-ZÀÂÇËÎÏÔÙÛÜ]" "[^a-zàâçëîïôùûüA-ZÀÂÇËÎÏÔÙÛÜ]"
"[']" t ("-C") nil iso-8859-1)
;; `aspell' extensions should *not* be used
(setq ispell-really-aspell nil)
;; `hunspell' extensions should be used
(setq ispell-really-hunspell t)
;; ;; 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))))
;; from Alex Schroeder
(defun my-change-dictionary ()
"Change the dictionary."
(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
;; key bindings
(global-set-key (kbd "<f7>") 'ispell-word)
(global-set-key (kbd "<S-f7>") 'my-change-dictionary)
(global-set-key (kbd "<C-f7>") 'ispell-change-dictionary)
;; on-the-fly spelling checking
(autoload 'flyspell-mode "flyspell" "On-the-fly spelling checking" t)
;; 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)
;; don't use `M-TAB' to correct word (only use `C-.')
(setq flyspell-use-meta-tab nil)
;; `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.
;; dash character (`-') is considered as a word delimiter
(setq flyspell-consider-dash-as-word-delimiter-flag t)
(defun my-turn-on-flyspell-french ()
"Unconditionally turn on flyspell-mode (in French) and call
(flyspell-mode 1) ;; instead of just toggling the mode
(ispell-change-dictionary "fr_FR")
(defun my-turn-on-flyspell-english ()
"Unconditionally turn on flyspell-mode (in American English)
and call `flyspell-buffer'."
(flyspell-mode 1)
(ispell-change-dictionary "en_US")
;; turn on `flyspell' when changing a buffer which is unmodified
(or (file-readable-p "/usr/share/myspell/dicts/fr_FR.aff") ; hunspell
(file-readable-p "/usr/lib/aspell/francais.alias")
(when running-ms-windows
"C:/Program Files/Aspell/dict/francais.alias")))
; check that the French dictionary
; can be opened for reading
(defvar my-flyspell-major-mode-list
;;; nuweb-mode (emmerdant: je sauve, compile, et recheck spell!)
;; org-mode ; FIXME Problem with flyspell (.emacs is *completely* screened...)
(add-hook 'first-change-hook
#'(lambda ()
(when (and (memq major-mode my-flyspell-major-mode-list)
(not flyspell-mode))
;; 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)))
;;; ;; don't print messages for every word (when checking the entire buffer)
;;; ;; as it causes an enormous slowdown
;;; (setq flyspell-issue-message-flag nil)
;; flyspell comments and strings in programming modes
;; (preventing it from finding mistakes in the code)
(add-hook 'autoconf-mode-hook 'flyspell-prog-mode)
(add-hook 'autotest-mode-hook 'flyspell-prog-mode)
(add-hook 'c++-mode-hook 'flyspell-prog-mode)
(add-hook 'c-mode-hook 'flyspell-prog-mode)
(add-hook 'cperl-mode-hook 'flyspell-prog-mode)
(add-hook 'emacs-lisp-mode-hook 'flyspell-prog-mode)
(add-hook 'makefile-mode-hook 'flyspell-prog-mode)
(add-hook 'nxml-mode-hook 'flyspell-prog-mode)
(add-hook 'python-mode-hook 'flyspell-prog-mode)
(add-hook 'sh-mode-hook 'flyspell-prog-mode)
;; (add-hook 'c-mode-common-hook 'flyspell-prog-mode t)
;; (add-hook 'java-mode-common-hook 'flyspell-prog-mode t)
;; spell-check your XHTML
(eval-after-load "flyspell"
(add-to-list 'flyspell-prog-text-faces 'nxml-text-face))))
;; TODO Have a look at `diction' (style and grammar for English)
;; pull definitions from Google and display them in a buffer
(when (try-require 'google-define)
(global-set-key (kbd "C-c D") 'google-define))
(defun google-define-word-or-phrase (query)
(interactive "sInsert word or phrase to search: ")
(let* ((url (concat ""
(replace-regexp-in-string " " "+" query)))
(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'
;; excellent!
(defun answers-define ()
"Look up the word under cursor in a browser."
(concat ""
(thing-at-point 'word))))
(when (try-require 'dictionary-FIXME)
(load "dictionary-init")
;; 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")
;; port of the proxy server
(setq dictionary-proxy-port 8080)
;; 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))
(when (try-require 'dictem-FIXME)
(setq dictem-server "localhost")
(define-key mode-specific-map [?s] 'dictem-run-search)
(define-key dictem-mode-map [tab] 'dictem-next-link)
(define-key dictem-mode-map [(backtab)] 'dictem-previous-link)
;; For creating hyperlinks on database names and found matches.
;; Click on them with `mouse-2'
(add-hook 'dictem-postprocess-match-hook
;; For highlighting the separator between the definitions found.
;; This also creates hyperlink on database names.
(add-hook 'dictem-postprocess-definition-hook
;; For creating hyperlinks in dictem buffer that contains definitions.
(add-hook 'dictem-postprocess-definition-hook
;; For creating hyperlinks in dictem buffer that contains information
;; about a database.
(add-hook 'dictem-postprocess-show-info-hook
(message "20 Commands for Fixing Typos... Done"))
;;** 21 (info "(emacs)Keyboard Macros")
(when section-keyboard-macros (message "21 Keyboard Macros...")
;;*** 21.1 (info "(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."
(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."
(global-set-key (kbd "<S-f8>") 'my-toggle-kbd-macro-recording-on)
;; 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
;; assign a name to the last keyboard macro defined
(global-set-key (kbd "<C-f8>") 'name-last-kbd-macro)
(message "21 Keyboard Macros... Done"))
;;* Major Structures of Emacs
;;** 22 (info "(emacs)Files") Handling
(when section-files (message "22 Files Handling...")
;;*** 22.2 (info "(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'."
(find-file "~/.emacs"))
(global-set-key (kbd "<S-f3>") 'my-open-dot-emacs)
;; open my Gnus configuration file
(defun my-open-dot-gnus ()
"Opening `~/.gnus'."
(find-file "~/.gnus"))
(global-set-key (kbd "<C-f3>") 'my-open-dot-gnus)
;; open my Timeclock file
(defun my-open-timeclock ()
"Opening `~/Projects/'."
(find-file "~/Projects/"))
(global-set-key (kbd "<C-f4>") 'my-open-timeclock)
;;*** 22.3 (info "(emacs)Saving") Files
;; make your changes permanent
(global-set-key (kbd "<f2>") 'save-buffer)
;; (add-hook 'after-save-hook
;; 'executable-make-buffer-file-executable-if-script-p)
;; offer save of `*scratch*' buffer on exit
(set-buffer "*scratch*")
(setq buffer-file-name "~/*scratch*"))
;; `(setq buffer-offer-save t)' does not have its intended effect in my
;; `.emacs' file (i.e., `buffer-offer-save' still has its global default
;; value of nil in the `*scratch*' buffer). But if I immediately evaluate it
;; in the `*scratch*' buffer, it works.
;; That is because at startup, Emacs sets the major mode of `*scratch*'
;; according to `initial-major-mode', _after_ my `.emacs' is read. Changing
;; major modes kills all local variables that are not permanently local,
;; including `buffer-offer-save'.
;; ;; major mode command symbol to use for the initial `*scratch*' buffer
;; (setq initial-major-mode 'text-mode) ; to avoid autoloads for Lisp mode (cedet)
;; ensure a file ends in a newline when it is saved
(setq require-final-newline t)
;; TODO I should do this only for text and Fundamental modes, because I could
;; edit binary files (see `mode-require-final-newline')
;; directory used for temporary files
(setq temporary-file-directory (or (getenv "TEMP") "/tmp/")))
;; maintain last change time stamps (`Time-stamp: <>' occurring within the
;; first 8 lines) in files edited by Emacs
(when (try-require 'time-stamp)
;; 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
;; update time stamps every time you save a buffer
(add-hook 'write-file-hooks 'time-stamp))
;; insert a time stamp string
(defun my-insert-time-stamp ()
"Insert a time stamp."
(interactive "*")
(insert (format "%s %s %s %s"
(format-time-string "%Y-%m-%d")
(defun insert-date (prefix)
"Insert the current date in ISO format. With prefix-argument,
add day of week. With two prefix arguments, add day of week and
(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)
;; update the copyright notice in current buffer
(when (try-require 'copyright)
; XXX Check no other copyright.el gets in the way
(add-hook 'write-file-hooks 'copyright-update)))
;;*** 22.4 (info "(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."
(flet ((yes-or-no-p (msg) t))
;; key binding
(global-set-key (kbd "<C-f12>") 'my-revert-buffer)
;;*** 22.6 (info "(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 15 seconds idle time
(setq auto-save-timeout 15)
;; 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
;; regexp => directory mappings
;; filenames matching a regexp are backed up in the corresponding directory
(setq backup-directory-alist
'((".*" . "~/.emacs.d/backups/")))) ;; '(("." . "~/.saves"))
;; or "/tmp/"?
;; Emacs will `make-directory' it if necessary
(when (try-require 'backup-dir)
(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)
;; 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 recover-this-file
'((t :background "orange"))
"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
(file-newer-than-file-p (or buffer-auto-save-file-name
(set (make-local-variable 'recover-this-file)
(make-overlay (point-min) (point-max)))
(overlay-put recover-this-file 'face 'recover-this-file))))
(add-hook 'find-file-hook 'recover-this-file-find-file-hook)
;;*** 22.9 (info "(emacs)Comparing Files")
;; default to unified diffs
(setq diff-switches "-u")
;; compare text in current window with text in next window
(global-set-key (kbd "C-c =") 'compare-windows)
;;;;;;;;;;;;;;;; FIXME Conflict with reftex
;;*** 22.10 (info "(emacs)Diff Mode")
;; run `diff' in compilation-mode
(autoload 'diff-mode "diff-mode" "Diff major mode" t)
;; extensions to `diff-mode.el'
(try-require 'diff-mode-)
;; ediff, a comprehensive visual interface to diff & patch
;; setup for Ediff's menus and autoloads
(try-require 'ediff-hook)
;; auto-refine only the regions of this size (in bytes) or less
(setq ediff-auto-refine-limit (* 2 14000))
;; 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")
;; Using the Emacs Dired utility, you can compress or uncompress a file by
;; pressing `Z'
;; easy editing of arc/zip/zoo/lhz archives
(require 'arc-mode)
;; TODO See `archive-zip-extract'
(when 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
;; 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)
(if handler (apply handler 'dired-call-process
program discard arguments)
(if (string-equal program "gunzip")
(setq program "gzip")
(add-to-list 'arguments "-d")))
(apply 'call-process
program nil (not discard) nil arguments)))))))
;;*** 22.13 (info "(emacs)File Archives")
;; simple editing of tar files as a Dired-like listing of its contents
(try-require 'tar-mode)
;; reading/writing/loading compressed files
(try-idle-require 'jka-compr)
;; ;; code for handling all sorts of compressed and encrypted files
;; (try-idle-require 'crypt++) ; EasyPG takes care of the encryption
;; ;; allows you to encrypt/decrypt files within Emacs. I use it regularly and
;; ;; it works very reliably. When I use `C-x C-f' to access an encrypted
;; ;; file, Emacs asks me for the passphrase and then decrypts the file before
;; ;; displaying it. When I save the file, Emacs automatically encrypts it
;; ;; again.
;; Once you've encrypted a file once, either externally or using a
;; crypt++-provided command, you don't need any new functions or
;; key-bindings -- you just visit it, and you get prompted for the
;; key, and when you save it it gets re-crypted with that same key.
;; This is achieved by sniffing every file as it is visited, and
;; prompting for a key if it "looks binary". If you blow off the prompt,
;; you get the raw file.
;; I use `epa' now, but don't like the fact that it remembers the password
;; forever...
;; Hmmm, interesting -- crypt++ remembers for output, but _always_ prompts on
;; input. Which did you mean wrt epa? And by 'forever' do you mean across
;; sessions?
;; Crypt++ would forget the password after a certain time. Epa seems to
;; remember the password for each XEmacs session, which for me means between
;; reboots.
;; For gpg-encrypted files you can use EasyPG (aka epg, the successor of pgg)
;; <> (which is also used by Gnus, when available, and
;; ships with current Emacs versions).
;; See
;; I think the only setup necessary is:
;; (require 'epa-setup)
;; See further section "(info "(pgg)Top") (Emacs interface to GnuPG)"
;; enable EPA to get `.gpg' files to be automatically encrypted
(require 'epa)
;; (require 'epa-file)
;; stop EasyPG from asking for the recipient
(setq epa-file-encrypt-to "")
;; If no one is selected, symmetric encryption will be performed
;; (setq epa-file-encrypt-to "")
;; 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. For more information see here:
;; (info "(pgg) Prerequisites")
;; Works fine with epa as well.
;; prompt for the password in the Emacs minibuffer (instead of using a
;; graphical password prompt for gpg)
(setenv "GPG_AGENT_INFO" nil)
;; 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.
;; > `mml2015-use'
;; > Symbol indicating elisp interface to OpenPGP implementation for
;; > PGP/MIME messages. The default is `pgg', but `mailcrypt' and
;; > `gpg' are also supported although deprecated.
;;*** 22.14 (info "(emacs)Remote Files")
;;**** Ange-FTP
;; transparent FTP support
(when (try-require '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
;;**** (info "(tramp)Top") TRAMP - Transparent Remote Access, Multiple Protocols
;; (other protocols than just FTP)
;; Examples: C-x C-f /ssh:fni@server:/home/fni/.bashrc
;; C-x C-f /plink:fni@server:/home/fni/.bashrc (from Windows)
;; C-x C-f /sudo:root@localhost:/etc/group
;; Note -- `sshfs' can give me the same functionality as TRAMP: it is like a
;; personal NFS (another mounted file system) over SSH. If you can SSH to a
;; server, you can probably do `sshfs'.
;; > I'm in shell mode, logged in on another machine over ssh, and I want to
;; > do some 'crontab -e' editing on that machine. But that will bring up a
;; > new editor, which is whatever you set in your EDITOR env variable, and
;; > both vi and emacs cannot be used in this dumb shell. How can I edit the
;; > crontab in my emacs session?
;; Create the crontab on the remote machine, open it using TRAMP from your
;; machine, edit and save and then reinstall it.
;; That or simply enable x forwarding so running emacs on the remote
;; bring up emacs gtk/x on your main machine editing your cron file
;; on the remote.
;; TRAMP is very slow to load! You definitely want to autoload!
(try-idle-require 'tramp-XXX)
(eval-after-load "tramp"
;;** 4 (info "(tramp)Configuration") of TRAMP for use
;;*** 4.6 Selecting a (info "(tramp)Default Method")
;; /method:user@host:/path/file
;; 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
;; 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.
;;*** 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
'("" "\\`root\\'" "/ssh:%h:")))
;; Opening `/sudo:' would connect first `' 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
;;*** 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")
;; help debugging
(setq tramp-verbose 9) ; default is 0
;; 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."
(defadvice tramp-handle-do-copy-or-rename-file
(after tramp-copy-beep-advice activate)
" make tramp beep after copying a file."
(defadvice tramp-handle-insert-file-contents
(after tramp-copy-beep-advice activate)
" make tramp beep after copying a file."
;; 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.
;; Open a file as root, easily [from Alex Schroeder]
(defvar find-file-root-prefix "/sudo:root@localhost:"
"*The filename prefix used to open a file with `find-file-root'.
This should look something like \"/sudo:root@localhost:\" (new style
TRAMP) or \"/[sudo:root@localhost]/\" (XEmacs or old style TRAMP).")
(defvar find-file-root-history nil
"History list for files found using `find-file-root'.")
(defvar find-file-root-hook nil
"Normal hook for functions to run after finding a \"root\" file.")
(defun find-file-root ()
"*Open a file as the root user.
Prepends `find-file-root-prefix' to the selected file name so that it
maybe accessed via the corresponding TRAMP method."
(require 'tramp)
(let* (;; We bind the variable `file-name-history' locally so we can
;; use a separate history list for "root" files.
(file-name-history find-file-root-history)
(name (or buffer-file-name default-directory))
(tramp (and (tramp-tramp-file-p name)
(tramp-dissect-file-name name)))
path dir file)
;; If called from a "root" file, we need to fix up the path.
(when tramp
(setq path (tramp-file-name-path tramp)
dir (file-name-directory path)))
(when (setq file (read-file-name "Find file (UID = 0): " dir path))
(find-file (concat find-file-root-prefix file))
;; If this all succeeded save our new history list.
(setq find-file-root-history file-name-history)
;; allow some user customization
(run-hooks 'find-file-root-hook))))
(defface find-file-root-header-face
'((t (:foreground "white" :background "red3")))
"*Face use to display header-lines for files opened as root.")
(defun find-file-root-header-warning ()
"*Display a warning in header line of the current buffer.
This function is suitable to add to `find-file-root-hook'."
(space (+ 6 (- (frame-width) (length warning))))
(bracket (make-string (/ space 2) ?-))
(warning (concat bracket warning bracket)))
(setq header-line-format
(propertize warning 'face 'find-file-root-header-face))))
(add-hook 'find-file-root-hook 'find-file-root-header-warning)
(global-set-key (kbd "C-x C-S-r") 'find-file-root)
;;*** 22.17 (info "(emacs)File Conveniences")
;; setup a menu of recently opened files
(try-idle-require 'recentf)
(eval-after-load "recentf"
;; file to save the recent list into
(setq recentf-save-file "~/.emacs.d/.recentf")
;; maximum number of items in the recentf menu
(setq recentf-max-menu-items 30)
;; 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)))
;; find file (or URL) at point
(try-idle-require 'ffap)
(eval-after-load "ffap"
;; 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'
;; visit a file
(global-set-key (kbd "<f3>") 'find-file-at-point)))
;; Possible error: Install w3m command in `exec-path' or set `w3m-command'
;; variable correctly
;; open anything
(when (try-require 'anything-config) ; loads `anything.el' too
(defun anything-c-define-dummy-source (name func &rest other-attrib)
`((name . ,name)
(candidates "dummy")
. (lambda (candidates source)
(funcall ',func)))
(requires-pattern . 1)
(category create)))
(defun anything-c-dummy-candidate ()
;; `source' is defined in filtered-candidate-transformer
(list (cons (concat (assoc-default 'name source)
" '" anything-input "'")
;;*dummy websearch
(defun make-anything-c-source-websearch (name url &rest extra)
(concat "Websearch for " name)
`(action . ,(eval `(lambda (args)
(apply 'concat
,url anything-pattern (quote ,extra))))))))
;; See
;; source of candidates for anything
(setq anything-sources
anything-c-source-buffers ; needs w3m-command to be set!
anything-c-source-org-headline ; show Org headlines (when Org mode)
anything-c-source-locate ; find files everywhere
;; ;; FIXME 2010-02-26 sva
;; ;; When google suggest is on, selecting a buffer does not work
;; ;; anymore: it presents the file as being empty...
;; anything-c-source-google-suggest ; do a quick google search
;; triggered only when no exact match is found
(make-anything-c-source-websearch "Google"
(make-anything-c-source-websearch "Emacs Wiki"
(make-anything-c-source-websearch "Wikipedia"
;; ;; ;; anything-c-source-bookmarks-local
;; ;; ;; anything-c-source-bookmarks-su
;; ;; ;; anything-c-source-bookmarks-ssh
;; ;; ;; anything-c-source-emms-dired
;;; Here the extensions i use: (you can find all of them on emacswiki)
;;; anything-complete.el
;;; anything-dabbrev-expand.el
;;; anything-match-plugin.el
;;; anything-traverse.el (if you don't use traverselisp.el have a look at
;;; anything-grep.el)
;; do not show more candidates than this limit from individual sources
(setq anything-candidate-number-limit 999)
;; 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 anything-idle-delay 0.9) ; 1.3 works nicely
;; ;; make anything minibuffer better input latency
;; (defadvice anything-check-minibuffer-input (around sit-for activate)
;; (if (sit-for anything-idle-delay t)
;; ad-do-it))
;; the user has to be idle for this many seconds, before ALL candidates are
;; collected (also effective for *non-delayed* sources)
(setq anything-input-idle-delay 0.4) ; 0.6 works nicely
;; uses the current window to show the candidates
(setq anything-samewindow t)
;; candidates separator of `multiline' source
(setq anything-candidate-separator
(propertize (make-string 42 ?-) 'face 'traverse-match-face))
;; suppress displaying sources which are out of screen at first
(setq anything-quick-update t)
;; don't save history information to file
(remove-hook 'kill-emacs-hook 'anything-c-adaptive-save-history)
;; select anything
(global-set-key (kbd "<f3>") 'anything)))
;; 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)
(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:\\(~?"
"\\)\\]") 1))
(defun org-toggle-iimage-in-org ()
(let ((turning-on (not iimage-mode)))
(set-face-underline-p 'org-link (not turning-on))
(iimage-mode (or turning-on 0)))))
(message "22 Files Handling... Done"))
;;** 23 Using Multiple (info "(emacs)Buffers")
(when section-buffers (message "23 Using Multiple Buffers...")
;;*** 23.2 (info "(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
(when (try-require 'ibuffer)
;; completely replaces `list-buffer'
(defalias 'ibuffer-list-buffers 'list-buffer)
(global-set-key (kbd "C-x C-b") 'ibuffer)
(setq ibuffer-show-empty-filter-groups nil)
(setq ibuffer-saved-filter-groups
("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 . "^\\*Help\\*$")
(name . "^\\*info\\*$")
(name . "^\\*Occur\\*$")
(name . "^\\*grep\\*$")
(name . "^\\*Compile-Log\\*$")
(name . "^\\*Backtrace\\*$")
(name . "^\\*Process List\\*$")
(name . "^\\*gud\\*$")
(name . "^\\*Man")
(name . "^\\*WoMan")
(name . "^\\*Kill Ring\\*$")
(name . "^\\*Completions\\*$")
(name . "^\\*tramp")
(name . "^\\*shell\\*$")
(name . "^\\*compilation\\*$")))
("emacs source" (or (mode . emacs-lisp-mode)
(filename . "/Applications/")
(filename . "/bin/emacs")))
("agenda" (or (name . "^\\*Calendar\\*$")
(name . "^diary$")
(name . "^\\*Agenda")
(name . "^\\*org-")
(name . "^\\*Org")
(mode . org-mode)
(mode . muse-mode)))
("latex" (or (mode . latex-mode)
(mode . LaTeX-mode)
(mode . bibtex-mode)
(mode . reftex-mode)))
("dired" (or (mode . dired-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 ()
(setq ad-return-value (nreverse ad-return-value)))
;; customizable buffer-selection with multiple menus
(when window-system
(require 'msb)))
;; buffer selection
(try-require 'ibs))
;; make a menu of buffers so you can manipulate buffers or the buffer list
(global-set-key (kbd "C-x C-b") 'bs-show)
;; `cyclebuffer.el'
;; 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")
;; kill buffer without confirmation (if not modified)
(defun my-kill-this-buffer ()
"Kill the current buffer without confirmation (if not modified)."
;;; (let ((bufname (buffer-name)))
;;; (if (or
;;; (string-equal "*Group*" bufname))
;;; (bury-buffer bufname)
(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
;; unique buffer names dependent on file name
(try-idle-require 'uniquify)
(eval-after-load "uniquify"
;; style used for uniquifying buffer names with parts of directory name
(setq uniquify-buffer-name-style 'forward)))
(message "23 Using Multiple Buffers... Done"))
;;** 24 Multiple (info "(emacs)Windows")
(when section-windows (message "24 Multiple Windows...")
;; TODO Have a look at `ido'
;;*** 24.1 Concepts of Emacs (info "(emacs)Basic Window")s
;; turn off this horrible tab thingy in XEmacs
(when (boundp 'default-gutter-visible-p)
(set-specifier default-gutter-visible-p nil)))
;;*** 24.3 Using (info "(emacs)Other Window")
;; cycle through all windows on current frame
(global-set-key (kbd "<f6>") 'other-window)
;;*** 24.6 Deleting and (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."
(cond ((not (= (count-windows) 2))
(message "You need exactly 2 windows to do this."))
(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."
(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)))))
(if (= (car this-win-edges)
(car (window-edges (next-window))))
(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)
;; 25.7 (info "(emacs)Window Convenience") Features and Customization
;; Use `M-x scroll-all-mode' to scroll all visible windows together in
;; parallel.
;; numbered window shortcuts
;; (It numbers windows and you can switch them easily with `M-<number>').
(when (try-require 'window-numbering)
(window-numbering-mode 1))
;; >> Is there any way of making a particular window persistent? I have an erc
;; >> window which obviously disappears when I do other things and I'd like to
;; >> keep a small window at the bottom of the screen so I can keep an eye on
;; >> it. Is there a function or hack to do this?
;; >
;; > You can store the window configuration in a register, and jump back to it.
;; >
;; > But if you want to keep an eye on it, the best is to open another
;; > frame, if you're using a window manager.
;; >
;; > C-x 5 2 to create a new frame
;; > C-x 5 o to switch from one frame to the other.
;; Also, frob special-display-buffer-names: You can make a window dedicated,
;; which does just what you want. You can do it for all windows or windows for
;; buffers whose names match some pattern, and so on.
;; Check the Elisp manual (that's Emacs Lisp), and look for `dedicated'
;; windows. See, in particular, user options `special-display-buffer-names'
;; and `special-display-regexps'.
;; winring
(message "24 Multiple Windows... Done"))
;;** 25 (info "(emacs)Frames") and Graphical Displays ]
(when section-frames (message "25 Frames and Graphical Displays...")
;;*** 25.1 (info "(emacs)Cut and Paste") on Graphical Displays
;; copy/paste with Gnome desktop
;; cutting and pasting uses the clipboard
(setq x-select-enable-clipboard t)
;; make cut, copy and paste (keys and menu bar items) use the clipboard
;; ;; UNDER-TEST mouse drag copies region to kill-ring
;; (setq mouse-drag-copy-region nil)
;; ;; UNDER-TEST cutting and pasting does not use the primary selection
;; (setq x-select-enable-primary nil)
;; ;; UNDER-TEST an active region automatically becomes the window selection
;; (setq select-active-regions t)
;;*** 25.5 (info "(emacs)Creating Frames")
;; - resize the frame to the size you want
;; - enter `(frame-parameters)' in the `*scratch*' buffer
;; - evaluate the form: place the cursor after the closing paren, and type
;; `C-j', so that the output goes right into the `*scratch*' buffer
;; 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 frame parameters for creating the initial frame
(setq initial-frame-alist '((top . 0) (left . 0)))
(setq initial-frame-alist
(append (list
'(internal-border-width . 2)
'(line-spacing . 1))
;; list of default values for frame creation
(setq default-frame-alist
(cond ((= (x-display-pixel-height) 1200)
'((left . 0) (height . 74)))
((= (x-display-pixel-height) 1024)
'((left . 0) (height . 63)))
((= (x-display-pixel-height) 800)
(cond (running-ms-windows
'((left . 0) (height . 55)))
'((left . 0) (height . 47)
(vertical-scroll-bars . right)))))
((= (x-display-pixel-height) 768)
'((left . 0) (height . 46)))))
(setq default-vertical-scroll-bar 'right))
(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")
;;; From sample .emacs
;;; local Emacs background: default
;;; remote Emacs background: palegreen1
;;; root Emacs background: coral2
;; ((and (string-match "XEmacs" emacs-version)
;; (eq window-system 'x)
;; (boundp 'emacs-major-version)
;; (= emacs-major-version 19)
;; (>= emacs-minor-version 12))
;; (let* ((root-p (eq 0 (user-uid)))
;; (dpy (or (getenv "DISPLAY") ""))
;; (remote-p (not
;; (or (string-match "^\\(\\|unix\\|localhost\\):" dpy)
;; (let ((s (system-name)))
;; (if (string-match "\\.\\(netscape\\|mcom\\)\\.com" s)
;; (setq s (substring s 0 (match-beginning 0))))
;; (string-match (concat "^" (regexp-quote s)) dpy)))))
;; (bg (cond (root-p "coral2")
;; (remote-p "palegreen1")
;; (t nil))))
;; (cond (bg
;; (let ((def (color-name (face-background 'default)))
;; (faces (face-list)))
;; (while faces
;; (let ((obg (face-background (car faces))))
;; (if (and obg (equal def (color-name obg)))
;; (set-face-background (car faces) bg)))
;; (setq faces (cdr faces)))))))))
;;*** 25.6 (info "(emacs)Frame Commands")
(defun toggle-full-screen ()
"Toggle between full screen and partial screen display on X11;
courtesy of"
(x-send-client-message nil 0 nil "_NET_WM_STATE" 32
(global-set-key (kbd "C-c z") 'toggle-full-screen))
(when running-ms-windows
(defun w32-maximize-frame ()
"Maximize the current frame."
(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."
(w32-send-sys-command 61728)
(global-set-key (kbd "C-c z") 'w32-maximize-frame))))
;;*** 25.7 (info "(emacs)Speedbar") Frames
;; everything browser (into individual source files), or Dired on steroids
(when (try-require 'speedbar-XXX)
;; number of spaces used for indentation
(setq speedbar-indentation-width 2)
;; expand/collapse LaTeX sections
(speedbar-add-supported-extension '(".tex" ".bib" ".w" ".nw"))
;; jump to speedbar frame
(global-set-key (kbd "<f4>") 'speedbar-get-focus)
;; bind the arrow keys in the speedbar tree
;; []
(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 frame (vs window)
(when (try-require 'sr-speedbar)
(global-set-key (kbd "<f4>") 'sr-speedbar-toggle))
;;*** 25.12 Scrolling with (info "(emacs)Wheeled Mice")
;; mouse wheel support
;;*** 25.14 (info "(emacs)Menu Bars")
;; turn menus off
(unless window-system
(menu-bar-mode 0))
;;*** 25.16 Using (info "(emacs)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)Mouse Avoidance")
(when window-system
;; make mouse pointer stay out of the way of editing
(when (try-require 'avoid)
(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))
(message "25 Frames and Graphical Displays... Done"))
;;** 26 (info "(emacs)International") Character Set Support ]
(when section-international (message "26 International Character Set Support...")
;; To open (or save) a file in UTF-8, you can press `C-x RET c utf-8 RET'
;; (`universal-coding-system-argument') before the `C-x C-f' (or `C-x C-s')
;; To help you find all the chars you need to replace by escape sequences, you
;; can use `C-u C-s [^[:ascii:]]'
;; To check your locale settings, you can have a look to what Emacs produce
;; (in a mail buffer) under "Important settings" when you type
;; `M-x report-emacs-bug RET foo RET':
;; Important settings:
;; value of $LC_ALL: nil
;; value of $LC_COLLATE: nil
;; value of $LC_CTYPE: nil
;; value of $LC_MESSAGES: nil
;; value of $LC_MONETARY: nil
;; value of $LC_NUMERIC: nil
;; value of $LC_TIME: nil
;; value of $LANG: en_US.UTF-8
;; value of $XMODIFIERS: nil
;; locale-coding-system: utf-8-unix
;; default-enable-multibyte-characters: t
;;*** 26.3 (info "(emacs)Language Environments")
;; system locale to use for formatting time values (e.g., timestamps in
;; Org mode files)
(setq system-time-locale "en_US.utf8") ; "C"?
;;*** 26.5 (info "(emacs)Select Input Method")
;; `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")
;; 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
(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
(cond (running-ms-windows
(prefer-coding-system 'iso-latin-1)) ; FIXME Temp for PFlow
(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
;; 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))
(set-selection-coding-system 'utf-8))))
;;*** 26.17 (info "(emacs)Undisplayable Characters")
;; display page delimiter character `^L' as an horizontal line
(when (try-require 'pp-c-l)
;; function to produce string displayed in place of each Control-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'
(pretty-control-l-mode 1)
;; normal hook run to initialize window system display
(add-hook 'window-setup-hook
;; functions to call when window configuration changes
(add-hook 'window-configuration-change-hook
(message "26 International Character Set Support... Done"))
;;* Advanced Features
;;** 27 (info "(emacs)Major Modes")
(when section-major-modes (message "27 Major Modes...")
;; Have a look at
;;*** 27.1 How (info "(emacs)Choosing Modes")
;; ;; default major mode for new buffers and any files with unspecified mode
;; (when (locate-library "org.el")
;; (setq-default major-mode 'org-mode))
;; Since `foo-mode' toggles Foo (minor) mode, it's better to use a function on
;; those hooks that unconditionally turns it on. Many minor modes have
;; `turn-on-foo-mode' and `turn-off-foo-mode' convenience functions for that
;; purpose, but you can fake it with an anonymous function:
;; (add-hook 'text-mode-hook (lambda () (foo-mode 1)))
;; or define your own convenience function and use that instead:
;; (defun turn-on-foo-mode ()
;; "Turn on Foo mode."
;; (foo-mode 1))
;; (add-hook 'text-mode-hook 'turn-on-foo-mode)
(autoload 'dtd-mode "tdtd" "Major mode for SGML and XML DTDs." t)
(autoload 'sql-mode "sql" nil)
(autoload 'css-mode "css-mode")
(autoload 'nxml-mode "nxml-mode" "XML mode" t)
(autoload 'ssh-config-mode "ssh-config-mode" t)
;; ledger
(try-require 'ledger)
;; 1. list of filename patterns
;; vs. corresponding major mode functions
(setq auto-mode-alist
(append '(
("\\.css\\'" . css-mode)
("\\.\\(htm\\|html\\|xhtml\\)$" . nxhtml-mode)
("\\.sql$" . sql-mode)
;; ("\\.js$" . java-mode)
("\\.dcl$" . dtd-mode)
("\\.dec$" . dtd-mode)
("\\.dtd$" . dtd-mode)
("\\.ele$" . dtd-mode)
("\\.ent$" . dtd-mode)
("\\.mod$" . dtd-mode)
;; sorted by chapter
("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
("\\.txt$" . org-mode)
("\\.dat$" . ledger-mode)
("\\.log$" . text-mode)
("\\.tex$" . LaTeX-mode)
("\\.tpl$" . LaTeX-mode)
("\\.cgi$" . perl-mode)
("[mM]akefile" . makefile-mode)
("\\.bash$" . shell-script-mode)
("\\.expect$" . tcl-mode)
(".ssh/config\\'" . ssh-config-mode)
("sshd?_config\\'" . ssh-config-mode)
) auto-mode-alist))
;; major mode for editing comma-separated value files
(when (try-require 'csv-mode)
;; field separators: a list of *single-character* strings
(setq csv-separators '("," ";")))
;; See (info "(elisp) Syntax of Regexps")
;; \' matches end of string
;; $ matches end of line
;; Some Emacs modes are over 10K lines of code. (e.g. js2-mode, nxml-mode,
;; CEDET). Many packages make use of the `autoload' feature, so that you only
;; need to load a single file that define autoloaded functions.
;; 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))
(add-to-list 'auto-mode-alist
(cons "\\.\\(xml\\|xsd\\|sch\\|rng\\|xslt\\|svg\\|rss\\|owl\\|xbl\\)\\'"
(fset 'xml-mode 'nxml-mode)
;; 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. list of buffer beginnings
;; vs. corresponding major mode functions (Emacs 22+)
;; see `magic-mode-alist'
;; 3. list of interpreters specified in the first line (starts with `#!')
;; vs. corresponding major mode functions
(push '("expect" . tcl-mode) interpreter-mode-alist)
;; multiple major modes
;; - nXhtml includes `mumamo.el' (= one of the most compatible with Org-babel)
;; - MMM mode
;; load generic modes which support e.g. batch files
(try-require 'generic-x)
(message "27 Major Modes... Done"))
;;** 28 (info "(emacs)Indentation")
;; Just hit C-j -- as in other modes, it runs the command
;; `newline-and-indent'.
;; Usually one binds `RET' to `newline-and-indent'.
(when section-indentation (message "28 Indentation...")
;;*** 28.1 (info "(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 ()
;;*** 28.3 Tabs vs. (info "(emacs)Just Spaces")
;; indentation can't insert tabs
(setq-default indent-tabs-mode nil)
(message "28 Indentation... Done"))
;;** 29 Commands for (info "(emacs)Text") Human Languages ]
(when section-text (message "29 Commands for Human Languages...")
;;*** 29.1 (info "(emacs)Words")
;; GNU Emacs default for killing back to the beginning of a word
(global-set-key [(control backspace)] 'backward-kill-word))
;; delete previous character, changing tabs into spaces
(global-set-key [(shift backspace)] 'backward-delete-char-untabify)
;;*** 29.2 (info "(emacs)Sentences")
;; FIXME When changing the ispell language, this should be changed
;; simultaneously.
;; a single space does end a sentence
(setq-default sentence-end-double-space nil)
;; See `sentence-end' and `(sentence-end)'
;;*** 29.5 (info "(emacs)Filling") Text
(defun my-text-mode-hook ()
"Turn on filling modes in text mode."
;; adaptative filling
(when (try-require 'filladapt)
(setq-default filladapt-mode nil)
;; turn on filladapt mode everywhere but in ChangeLog files
(cond ((equal mode-name "Change Log")
;; 2010-05-21 John Wiegley:
;; The Emacs ChangeLog is a file which predates the existence of freely
;; available, project-wide version control. It was a way to see, in one place,
;; the stream of changes occurring in a project -- something which RCS could
;; not do for you.
;; However, in this modern era of project-wide, atomic commits, the ChangeLog
;; is not only an archaism, but is a continuous source of merge conflicts. For
;; example, when I reverted Russell's latest change -- a one-liner that was
;; minor in the extreme -- I had to do with a merge conflict in
;; lisp/ChangeLog.
;; With a system like Git, and properly written commits, you can produce a
;; ChangeLog at any time with "git log". You even see a ChangeLog for just one
;; file, or a directory with "git log --follow PATH". This completes
;; supersedes any need for a ChangeLog file, and has led me to abandon the use
;; of ChangeLogs in all the projects I maintain.
;; 2010-05-21 Ben Finney:
;; It seems worth pointing out explicitly, though: Eliminating a
;; manually-maintained ChangeLog doesn't obviate the need for a ChangeLog (or
;; the equivalent) in the distributed source.
;; This is because the copyright holders license their works under the GPLv2,
;; and §2.a of those terms requires the work to include dated notice of all
;; modifications made to the work. This is conventionally understood to be
;; most directly satisfied by a ChangeLog in the distributed source for the
;; work.
;; Generating that file automatically from the VCS commit messages, at the
;; time a source release is packaged, is a good use of the VCS.
;; turn on my text setup
(add-hook 'text-mode-hook 'my-text-mode-hook)
;; fabrication automatique de la typo française avec la ponctuation
;; ajout automatique de l'espace insécable là où cela va bien
(defun my-insert-interrogation-mark ()
(if (eq (char-before) ?\ ) ; normal space
(backward-delete-char 1)
(if (equal mode-name "PDFLaTeX")
(insert "~?")
(insert " ?"))) ; non-breaking space
(insert "?")))
(defun my-insert-exclamation-mark ()
(if (eq (char-before) ?\ ) ; normal space
(backward-delete-char 1)
(if (equal mode-name "PDFLaTeX")
(insert "~!")
(insert " !"))) ; non-breaking space
(insert "!")))
;; FIXME Remove NBSP if two colons are put one after the other (for terms and
;; definitions in Org)
(defun my-insert-colon ()
(if (eq (char-before) ?\ ) ; normal space
(backward-delete-char 1)
(if (equal mode-name "PDFLaTeX")
(insert "~:")
(insert " :"))) ; non-breaking space
(insert ":")))
(defun my-insert-semi-colon ()
(if (eq (char-before) ?\ ) ; normal space
(backward-delete-char 1)
(if (equal mode-name "PDFLaTeX")
(insert "~;")
(insert " ;"))) ; non-breaking space
(insert ";")))
(defun my-double-keys ()
"Touches spécifiques"
(local-set-key "?" 'my-insert-interrogation-mark)
(local-set-key "!" 'my-insert-exclamation-mark)
(local-set-key ":" 'my-insert-colon)
(local-set-key ";" 'my-insert-semi-colon))
;; typo auto pour les modes suivants
(add-hook 'text-mode-hook 'my-double-keys)
(add-hook 'message-mode-hook 'my-double-keys)
;; (add-hook 'text-mode-hook 'turn-on-auto-fill)
;; (add-hook 'fill-nobreak-predicate 'fill-french-nobreak-p)
;; (add-hook 'fill-nobreak-predicate 'fill-single-word-nobreak-p)
(defun insert-one-quote-or-two ()
((or (bolp) (not (looking-back "'")))
;; insert just one '
(self-insert-command 1))
;; Skip symbol backwards.
(and (not (zerop (skip-syntax-backward "w_")))
(not (looking-back "`"))
(or (insert-and-inherit "`") t))))
;; insert `' around following symbol
(delete-backward-char 1)
(unless (looking-back "`") (insert-and-inherit "`"))
(skip-syntax-forward "w_")
(unless (looking-at "'") (insert-and-inherit "'"))))))
(global-set-key [39] 'insert-one-quote-or-two)
;; automatic line-wrapping beyond that column
(setq-default fill-column 78)
;;*** 29.6 (info "(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")
;; Outline is line-oriented and does not distinguish end-of-block.
;; `outline-minor-mode.el' is also used to collapse Lisp code (i.e., to see in
;; the buffer just the definition of a function instead of the whole body)
;; See also the library `foldout' and `hs-minor-mode', for instance, in the
;; Emacs manual.
;; outline mode commands for Emacs
(when (try-require 'outline)
;; bind the function `open-line' to `M-o' instead of `C-o' (by default)
(global-set-key (kbd "M-o") 'open-line)
;; 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 "C-o"))
;; make other `outline-minor-mode' files (LaTeX, etc.) feel like Org files
(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)
(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 "[*]+ ")))
(defun my-outline-minor-mode-hook ()
(setq outline-regexp (my-outline-regexp))
;; highlight the headings
;; see
;; 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?")
(concat (substring outline-regexp 0 -1)
"\\{1\\} \\(.*" org-fontify-whole-heading-line "\\)"))
(concat (substring outline-regexp 0 -1)
"\\{2\\} \\(.*" org-fontify-whole-heading-line "\\)"))
(concat (substring outline-regexp 0 -1)
"\\{3\\} \\(.*" org-fontify-whole-heading-line "\\)"))
(concat (substring outline-regexp 0 -1)
"\\{4,\\} \\(.*" org-fontify-whole-heading-line "\\)")))
`((,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
;; Add the following as the top line of your `.emacs':
;; ; -*- mode: emacs-lisp; mode: outline-minor; -*-
;; 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)
(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 [backtab] '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
;; 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)
(defun org-cycle-global ()
(org-cycle t))
(defun org-cycle-local ()
(move-beginning-of-line nil)
(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
;; unified user interface for Emacs folding modes
(when (try-require 'fold-dwim)
(global-set-key (kbd "C-c f t") 'fold-dwim-toggle)
(global-set-key (kbd "C-c f h") 'fold-dwim-hide-all)
(global-set-key (kbd "C-c f s") 'fold-dwim-show-all)))
(global-set-key (kbd "<S-f6>") 'visible-mode)
;;*** 29.9 (info "(emacs)TeX Mode")
;; - text-mode-hook = all text modes
;; - (la)tex-mode-hook = default Emacs built-in (La)TeX mode
;; - (La)TeX-mode-hook = AUCTeX
;; Note -- AUCTeX aliases tex-mode to TeX-mode
;; Note -- Invoking `(la)tex-mode' also runs `text-mode-hook'
;;**** 2 (info "(auctex)Installation") of AUCTeX
;; support for LaTeX documents
(message "29.9 TeX mode....AAA.AAA.AAA..............")
(try-idle-require 'latex-XXX)
(message "29.9 TeX mode....BBB.BBB.BBB..............")
(eval-after-load 'latex
;; (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)))
;;**** 3 (info "(auctex)Quick Start")
;; Press `C-c C-c File RET RET' to run `dvips'
;; (note that the command is `File' and not `Dvips' as one might expect)
;; Press `C-c C-c Print RET RET' to run `GSview'
;; (also somewhat misleading name)
;; If you want to print the document, do it from GSview.
;;**** 5 (info "(auctex)Advanced Features")
;;***** 5.2 (info "(auctex)Completion")
;; if this is non-nil when AUC TeX is loaded, the TeX escape character `\'
;; will be bound to `TeX-electric-macro'
(setq TeX-electric-escape t)
;;***** 5.4 (info "(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)
;; number of spaces to add to the indentation for `\item''s in list
;; environments
(setq LaTeX-item-indent 0) ; -4
;; number of spaces to add to the indentation for each `{' not matched
;; by a `}'
(setq TeX-brace-indent-level 0) ; 4
;; 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)
;;**** 6 Controlling Screen (info "(auctex)Display")
;;***** 6.1 (info "(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
;;**** 7 (info "(auctex)Running TeX and friends") Processors, Viewers and Other Programs
;;***** 7.1 Executing (info "(auctex)Commands")
;; use PDF mode by default (instead of DVI)
(setq-default TeX-PDF-mode t)
;;***** 7.2 (info "(auctex)Viewing") the formatted output
;; use a saner PDF viewer (evince, SumatraPDF)
(setcdr (assoc "^pdf$" TeX-output-view-style)
(cond (running-ms-windows
'("." "\"C:/Program Files/SumatraPDF/SumatraPDF.exe\" %o"))
; under Windows, we could open the PDF file with:
; start "" xxx.pdf
'("." "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.
;;***** 7.3 (info "(auctex)Debugging") Catching the errors
;; don't show output of TeX compilation in other window
(setq TeX-show-compilation nil)
;;**** 8 (info "(auctex)Multifile") Documents
;; AUC TeX will will assume the file is a master file itself
(setq-default TeX-master t)
;;**** 9 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)
;;**** 11 (info "(auctex)Automatic") Customization
;;***** 11.1 (info "(auctex)Automatic Global") Customization for the Site
;; directory containing automatically generated TeX information. Must end
;; with a slash
(setq TeX-auto-global
;;***** 11.3 (info "(auctex)Automatic Local") Customization for a Directory
;; directory containing automatically generated TeX information. Must end
;; with a slash
(setq TeX-auto-local
;; (try-require 'beamer)
(try-require 'babel)
;; minor mode with distinct support for `\label', `\ref', `\cite' and
;; `\index' in LaTeX
(when (try-require 'reftex)
;; A Table of Contents of the entire (multifile) document with
;; browsing capabilities is available with `C-c ='.
;; Hitting `l' there will show all the labels and cites.
;; Labels can be created with `C-c (' and referenced with `C-c )'.
;; When referencing, you get a menu with all labels of a given type
;; and context of the label definition. The selected label is
;; inserted as a `\ref' macro.
;; Citations can be made with `C-c [' which will use a regular
;; expression to pull out a *formatted* list of articles from your
;; BibTeX database. The selected citation is inserted as a `\cite'
;; macro.
;; Index entries can be made with `C-c /' which indexes the word at
;; point or the current selection. More general index entries are
;; created with `C-c <'. `C-c >' displays the compiled index.
(add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
;; 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))
;; Remap default face in current buffer (Emacs 23)
;;; (add-hook 'LaTeX-mode-hook
;;; '(lambda ()
;;; (face-remap-set-base
;;; 'default
;;; '(:family "LMRoman10" :height 100 :background "white"))))
;;*** (info "(preview-latex)Top")
(add-hook 'LaTeX-mode-hook 'LaTeX-preview-setup)
(autoload 'LaTeX-preview-setup "preview")
;; how to call gs for conversion from EPS
(setq preview-gs-command
(cond (running-ms-windows
"C:/Program Files/gs/gs8.64/bin/gswin32c.exe")
(my-file-executable-p preview-gs-command)
;; scale factor for included previews
(setq preview-scale-function 1.2)
;; major mode to edit nuweb files with AUCTex
(when (try-require 'nuweb) ;; depends on `TeX-lisp-directory'
;; define what's needed to properly call nuweb
(make-variable-buffer-local 'outline-prefix-char)
(make-variable-buffer-local 'outline-regexp)
(make-variable-buffer-local 'outline-level-function)
;; our version of nuweb knows about `@%' comments
(setq nuweb-comment-leader "@%")
;; major mode
(add-to-list 'auto-mode-alist '("\\.w$" . nuweb-mode))
;; to get a menu with scraps/files/index entries
(add-hook 'nuweb-mode-hook
(imenu-add-to-menubar "Nuweb")))
;; recompute all the defs and uses point in the current file
(add-hook 'nuweb-mode-hook 'nuweb-compute-d-u)
;; replace the existing `Web' command in order to use PDF mode by
;; default (instead of DVI) -- without writing explicitly the entire
;; `TeX-command-list' in the `.emacs' file (as `customize-variable'
;; would do):
(setcdr (assoc "Web" TeX-command-list)
'("nuweb %s && pdflatex \"\\nonstopmode\\input{%s}\""
TeX-run-LaTeX nil t
:help "Extract files, create LaTeX document, and run `pdflatex' on it"))))
;; Tangle = Extract
;; FIXME Noweb -- Problem with multi-mode?
(try-require 'noweb)
;;*** (info "(emacs-goodies-el)boxquote")
;; quote text with a semi-box
(when (try-require 'boxquote)
;; put spaces before my boxquotes
(setq boxquote-top-corner " ,")
(setq boxquote-side " | ")
(setq boxquote-bottom-corner " `")
(global-set-key (kbd "C-c b r") 'boxquote-region)
(global-set-key (kbd "C-c b t") 'boxquote-title))
;; --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---
;; interface to the festival speech synthesizer system
(when (locate-library "festival-XXX")
(autoload 'say-minor-mode "festival" "Menu for using Festival." t)
(say-minor-mode t)
(setq auto-mode-alist
(append '(("\\.festivalrc$" . scheme-mode)) auto-mode-alist))
(setq festival-program-name "/usr/bin/festival"))
;; phonetic spelling
(try-idle-require 'phonetic)
(message "29 Commands for Human Languages... Done"))
;;** 30 Editing (info "(emacs)Programs")
(when section-programs (message "30 Editing Programs...")
;;*** 30.1 Major Modes for (info "(emacs)Program Modes")
(autoload 'awk-mode "cc-mode" "Awk editing mode." t)
;; TODO Or use a new AWK Mode for AWK files, rather than the older mode
;; contained in the file `awk-mode.el'
;; [from]
;; (try-require 'graphviz-dot-mode)
;; Have a look at:
;; - for C/C++ development,
;; - for Common Lisp development,
;; - for Java programs.
;; Emacs tool for ELISP code analysis (to keep overview of the
;; function calls and dependecies between functions/variables):
;; byte-compile-generate-call-tree
;; Also
;;*** 30.3 (info "(emacs)Program Indent")ation
;; From (info "(ccmode)Indentation Commands"):
;; Changing the "hanginess" of a brace and then reindenting, will not
;; move the brace to a different line. For this, you're better off
;; getting an external program like GNU `indent', which will rearrange
;; brace location, amongst other things.
;; 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)
;; use one of several different indentation styles for C-like modes
(setq c-default-style
'((awk-mode . "stroustrup")
(other . "stroustrup")))
; Try the different pre-defined styles
; of indentation via a call to
; `c-set-style'
(defun my-c-mode-hook ()
"Customize my c/c++-mode and awk-mode."
;; auto-indentation
(local-set-key (kbd "<return>") 'newline-and-indent) ; (control m)
(local-set-key (kbd "<linefeed>") 'newline)) ; (control j)
(add-hook 'c-mode-hook 'my-c-mode-hook)
(add-hook 'c++-mode-hook 'my-c-mode-hook)
(add-hook 'awk-mode-hook 'my-c-mode-hook)
(defun back-to-indentation-or-beginning ()
(if (/= (point) (line-beginning-position))
(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")
;; find matching parenthesis (% command in vim)
(defun match-paren (arg)
"Go to the matching parenthesis, if on 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)))))
(global-set-key (kbd "%") 'match-paren)
;; highlight matching parenthesis
(when (try-require 'paren)
(show-paren-mode t)
(setq show-paren-ring-bell-on-mismatch t))
(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
;; from
;; goto-matching-paren
;;*** 30.6 (info "(emacs)Documentation") Lookup
;; show the function arglist or the variable docstring in the echo area
(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
;; You can have block-oriented folding in programming modes: Hideshow
;; distinguishes end-of-block.
;; `hs-minor-mode.el' collapses code for a lot of languages, not only Lisp.
;; See `outline-minor-mode' as well.
;; enable `hs-minor-mode' at startup
(add-hook 'emacs-lisp-mode-hook
(lambda () (hs-minor-mode 1)))
;; Especially after changing a couple of those really awkward keybindings
;; 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")
;; It's more or less a convention that each language mode binds its symbol
;; completion command to `M-TAB' which is a reserved hot key under Windows.
;; Way to solve this: when you hit `C-TAB', the command normally bound to
;; `M-TAB' will be called.
(global-set-key (kbd "<C-tab>")
'(lambda ()
(call-interactively (key-binding (kbd "M-TAB")))))
;; `M-/' runs the command `dabbrev-expand' by default
;; Expand previous word "dynamically". Expands to the most recent, preceding
;; word for which this is a prefix.
(global-set-key (kbd "C-`") 'dabbrev-expand)
;; `C-M-/' runs the command `dabbrev-completion'
;; Completion on current word. Like `M-/' but finds all expansions in the
;; current buffer and presents suggestions for completion.
;; expand text trying various ways to find its expansion
(when (try-require 'hippie-exp)
;; list of expansion functions tried (in order) by `hippie-expand'
(setq hippie-expand-try-functions-list
'(try-expand-dabbrev ; from current buffer
try-expand-dabbrev-visible ; from visible parts of all windows
try-expand-dabbrev-all-buffers ; from all other buffers
;; 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)))
(global-set-key [(control tab)] 'my-hippie-expand))
;; (global-set-key (kbd "M-/") 'hippie-expand)
;; I recommend you split the key binding of those two command.
;; I binding TAB yas/expand, and binding M-/ hippie-expand.
;; So yas/expand don't conflict with hippie/expand.
;; predictive abbreviation expansion ("à la IntelliSense")
(when (try-require 'pabbrev)
;; don't print messages while scavenging on idle timer
(setq pabbrev-idle-timer-verbose nil)
;; tab completion with continual, as-you-type feedback
;; > I'm trying to have code completion in Emacs, but i don't know what to
;; > do. In eclipse, when we writing a java code line, for example:
;; > System.out., we do C^SPACE to show a window with several methods
;; > associated (printl, print,etc).
;; > I would like to have something similar in Emacs. Can anybody help me?
;; Try M-TAB with cursor on the symbol; is that what you are looking for?
;; extensible inline text completion mechanism -- really brilliant!
(when (try-require 'company)
(define-key company-mode-map (kbd "M-SPC") 'company-complete)
(defun my-turn-on-company-mode ()
(company-mode 1))
(dolist (hook (list
(add-hook hook 'my-turn-on-company-mode))
(setq company-idle-delay nil)
(setq company-eclim-auto-save t)
(setq company-eclim-executable
(defun my-java-mode-init ()
(setq company-backend 'company-eclim))
(add-hook 'java-mode-hook 'my-java-mode-init))
;;*** 30.9 (info "(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 "")
;;*** Add-Ons
;; XXX semanticdb-project-database-file ??
;; Collection of Emacs Development Environment Tools
;; ;; list of directories, where each directory is the root of some project
;; (setq semanticdb-project-roots '("~/emacs/site-lisp"))
;; turn on all "useful" features
(setq semantic-load-turn-useful-things-on t)
;; setup complete development environment
(try-idle-require 'cedet)
(eval-after-load 'cedet
;; Enabling various SEMANTIC minor modes. See semantic/INSTALL for more
;; ideas.
;; Select one of the following:
;; - This is the default. Enables the database and idle reparse engines
;; - This enables some tools useful for coding, such as summary mode imenu
;; support, and the semantic navigator <<<
;; - This enables even more coding tools such as the nascent IntelliSense
;; mode decoration mode, and stickyfunc mode (plus regular code helpers)
;; - This turns on which-func support (plus all other code helpers)
;; ;; This turns on modes that aid in writing grammar and developing
;; ;; semantic tool. It does not enable any other features such as code
;; ;; helpers above.
;; (semantic-load-enable-semantic-debugging-helpers)
;; getting rid of semantic.caches
(setq semanticdb-default-save-directory "~/.emacs.d/semantic-cache")
(my-make-directory-yes-or-no semanticdb-default-save-directory)
;; fix the max CPU problem on latest Emacs snapshots
(setq semantic-idle-scheduler-idle-time 432000)
;; Emacs Code Browser (provides views of directories and files)
;; see
(when (try-require 'ecb-autoloads) ; load all available autoloads of ECB
;; ECB version
(setq ecb-options-version "2.32")
;; don't show tip of the day at start time of ECB
(setq ecb-tip-of-the-day nil)
;; toggle activation of ecb
(global-set-key (kbd "C-c e") 'ecb-minor-mode)))))
;; If you've installed CEDET and ECB, EAssist is worth trying out:
;; It uses CEDET to provide a handy symbols browser for the current file, that
;; narrows down the list as you type substrings. Tastes differ, but I for one
;; really like this.
(message "30 Editing Programs... Done"))
;;** 31 (info "(emacs)Building") Compiling and Testing Programs ]
(when section-building (message "31 Compiling and Testing Programs...")
;; >> It's possible to see, while we are programming, if we did a mistake. In
;; >> eclipse, when we do an error, for example, forget a ; , an underline
;; >> appears in the line indicating that something is wrong. It's possible to
;; >> have something like this in Emacs?
;; >
;; > 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
(when (try-require 'flymake)
;; 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
;; 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!"))))
(defun cc-goto-first-error( buffer exit-condition )
(with-current-buffer buffer
(goto-char (point-min))
(compilation-next-error 1)))
(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")
;; 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)
;; Some code that will make it so the background color of the lines that gcc
;; found errors on, should be in another color.
(defvar all-overlays ())
(defun delete-this-overlay (overlay is-after begin end &optional len)
(delete-overlay overlay))
(defun highlight-current-line ()
(setq current-point (point))
(setq beg (point))
(forward-line 1)
(setq end (point))
;; Create and place the overlay
(setq error-line-overlay (make-overlay 1 1))
;; Append to list of all overlays
(setq all-overlays (cons error-line-overlay all-overlays))
(overlay-put error-line-overlay
'face '(background-color . "pink"))
(overlay-put error-line-overlay
'modification-hooks (list 'delete-this-overlay))
(move-overlay error-line-overlay beg end)
(goto-char current-point))
(defun delete-all-overlays ()
(while all-overlays
(delete-overlay (car all-overlays))
(setq all-overlays (cdr all-overlays))))
(defun highlight-error-lines (compilation-buffer, process-result)
(condition-case nil
(while t
(error nil)))
(setq compilation-finish-function 'highlight-error-lines)
;;*** 31.4 (info "(emacs)Grep Searching") under Emacs
;; ignore case distinctions in the default grep command
;;(if (my-file-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:
;; (defun my-grep ()
;; "look for word at point in files ending by .cpp and .h
;; recursively starting from the work directory"
;; (interactive)
;; (rgrep (thing-at-point 'word) "*.cpp *.h" "~/work"))
;; (global-set-key [(control shift f)] 'my-grep)
;;*** 31.6 Running (info "(emacs)Debuggers") Under Emacs
;; > Enable debug-on-error via 'M-x toggle-debug-on-error', then start
;; > flyspell-mode again and examine the error. If that does not work, try
;; > edebug. Open the file where flyspell-mode is defined. Reeval the
;; > function with 'C-u C-M-x' and again, start flyspell-mode. Now you are
;; > in edebug-mode. Hit Space till you get the error. Press 'i' to enable
;; > debugging of the called function after point.
;; The cursor has to be inside the flyspell-mode function for this to work.
;; (C-M-x evals the current function , with prefix it also installs the
;; debug routines.)
;; Alternatively this should enable edebug on all forms in the current buffer:
;; M-x edebug-all-defs
;; M-x eval-buffer
;;**** Debugging Mercury programs
;; 1. Put these lines in your .emacs file:
;; (setq mercury-dir (getenv "MERCURY_DIR"))
;; (load-file (concat mercury-dir "/lib/mercury/elisp/gud.el"))
;; (setq mdb-command-name "bash.exe mdb ./mas_server.exe
;; -c ../online/mas_server/mas_config_local.xml -d ../data"))
;; 2. To start the debugger, open a file in your build directory,
;; e.g. build/Makefile
;; 3. Run M-x and then type mdb
;; 4. At the prompt you should see the command from the .emacs file:
;; "bash.exe mdb ./mas_server.exe
;; -c ../online/mas_server/mas_config_local.xml -d ../data"
;; Change if necessary and hit the `RET' key
;; 5. Find your bugs.
;; Known problems:
;; - tab completion doesn't work
;;**** Debugging Lisp programs
;; Emacs has the basic debugger/stack trace, but it also has the edebug
;; facility, which is very powerful, for the more complex situation.
;; , (info "(elisp)Edebug") ]
;; | Edebug is a source-level debugger for Emacs Lisp programs with which
;; | you can:
;; |
;; | * Step through evaluation, stopping before and after each expression.
;; |
;; | * Set conditional or unconditional breakpoints.
;; | [...]
;; `----
;; You can cause the debugger to be called at a certain point in your program
;; by writing the expression `(debug)' at that point. To do this, visit the
;; source file, insert the text `(debug)' at the proper place, and type
;; `C-M-x'.