My .emacs

bitches-dont-know-emacs.jpg

With great power comes great responsibilities

1 INTRODUCTION

1.1 A Few Words

My emacs configuration file, consisting of various hacks, some copy pasted, others modified/written by me. Much taken from emacs-fu, emacs rocks, and emacswiki. Note that most of the descriptions/explanations to the code are in the code blocks as comments. For learning lisp, structural interpretation of programs is considered the "bible", although Scheme dialect differs from elisp, it's similar.

I'm using varius other modes (file.el-files) that I have in my load-path. I'll link to the source where possible. (Almost?) all are available through emacs wiki or the emacs package mannager, (the built, elpa, or el-get)

Table of Contents

1.2 Emacs keybindings   KEY BINDINGS KEYBINGDINGS SHORTCUTS

C-c prefix is reserved for the user, although most third party packages steal this. Also F5 and up are for the user, if not all F-keys.

You can allways see which function (and its documentation) a sequence is bound to by prefixing it with C-h k ("help key"), in the same way you get help for functions or variables with C-h f, or C-h v, respectivley. C-h b runs describe-binding which is also pretty awseome, as it lists all keys currently bound in the buffer/mode you're in.

When using the kbd macro, all function keys and directinal keys must be enclosed in "<>", like so: <f5>, <home>, <next>, <left>. This is not needed for normal keys like C-c e is: (kbd "C-c e")

see: mastering emacs

1.2.1 help keys

Emacs is self documenting, and all documentation/help starts with the key C-h. C-h r brings up the Emacs manual, and C-h i brings up the info index. M-x info-display-manual is an easy way to get to the right section (with tab compleation) in the info manual.

C-h k <key sequence> is excellent when ever I want to know what function a <key sequence> is bound to.

Table 1: Help keys
Key Action
C-h i info manual
C-h r Emacs section of the info manual
C-h k describe-key
C-h f describe-function
C-h c describe-command
C-h v describe-variable
C-h a describe-apropos (search)
C-h m list all keys assoiciated wth current modes.
C-h n list all news in this version of emacs.
C-h e show Message buffer (echo area)
prefix C-h list all keys belonging to the prefix,
C-x r C-h example of above code. List all keys with that prefix

Furthermore, to find relevant elisp source code there are several very useful functions:

  • M-x find-library
  • M-x find-function
  • M-x find-variable
;; bind useful function to C-h C-l, and C-h C-i
(define-key 'help-command (kbd "C-l") 'find-library)
(define-key 'help-command (kbd "C-i") 'info-display-manual)

1.2.2 basic usage

For hard-core navigation using just the emacs way, remove arrow keys by evaluating: (mapc 'global-unset-key [[up] [down] [left] [right]])

Table 2: Basic emacs keys
Key Action
C-g Most important key: abort/escape. When ever in doubt: C-g
C-x h mark whole buffer
   
C-x u undo
C-_ undo
   
M-u convert whole word in front of point to upper case
M-l convert whole word in front of point to lower case
M-c convert character infront of point to upper case
   
C-t transpose characters i.e. ab -> ba
M-t transpose word i.e. abc def -> def abc
C-x C-t transpose lines
   
C-M-[N] N = number, sending a number as arg. to command.
C-[N] Same as above.
M-[N] Same as above.
   
M-- invert following command. e.g. M– M-l "lower case backward"

1.2.3 basic movement and editing

Table 3: Movement and editing
Key Action
C-a Move to beginning of line
C-e Move to end of line
   
M-a Move to sentence beginning
M-e Move to sentence end
   
C-k Kill Line from point
C-S-BKSPC Kill whole Line
   
M-q fill paragraph (i.e. break paragraph in hard line breaks)
C-x f set fill column (how many columns a line is before line break)
   
C-up move up paragraph/code block
C-down move down paragraph/code block
C-left same as M-b (backward word)
C-right same as M-f (forward word)

1.2.4 registers and rectangular marking / editing

Set mark at upper left corner, and then lower right then do any of the following, (except for C-x r y no marking is needed):

GNU-manual

Table 4: Register / rectangular regions
Key Action
C-x r k kill text (save to "last killed rectangle")
C-x r d Delete the text of the region-rectangle
C-x r y Yank the last killed rectangle with its upper left corner at point
C-x r t str Replace rectangle contents with string on each line
C-x r N Insert line numbers along the left edge of the region-rectangle.
   
C-x r o Insert blank space to fill the space of the region-rectangle
C-x r c Clear the region-rectangle by replacing all of its contents with spaces
Table 5: save rectangular region
object store retrieve notes
normal region C-x r s R C-x r i R save region (selection) into register R /insert R
rectangle region C-x r r R C-x r i R save rectangle into register R (see working with rectangular selections, and insert it);
buffer/position C-x r <SPC> R C-x r j R save buffer/position in register R, and jump back to it
window C-x r w R C-x r j R save window configuration in register R, and jump back to it. Note that what emacs calls a window is called a window pane elsewhere, see emacs terminology)
frame C-x r f R C-x r j R save frame configuration in register R, and jump back to it. Note that what emacs calls a frame is called a window elsewhere, see emacs terminology

Alternatively there's the cua-mode rectangles, with useful functions: cua-sequence-rectangle (M-n, when the region is active) which asks for start value and increment, and format.

1.2.5 registers:

By setting registers one bookmarks a line in a file (C-x r SPC 42), so that one can easily return/jump to it at a later point (C-x r j 42).

With registers you can also copy text into multiple "slots", and retrieve them.

Key Action
C-x r SPC set register mark (with a number)
C-x r j jump to register mark (with a number)
   
C-x r s save selection to register
C-x r i load selection from register
   
C-x r m add bookMark
C-x r b visit bookmark
C-x r l list bookmarks

1.2.6 font-size

C-x C-+ Increase font size C-x C– Decrease font size

1.2.7 search and replace   SEARCH REPLACE

Powerful: M-x multi-occur M-x multi-occur-in-matching-buffers M-x list-matching-lines

Table 7: Search and replace
Key Action
C-s searach forward
C-r search backward
   
C-M-s regexp searach forward
C-M-r regexp search backward
   
M-s . search symbol under cursor. Note: if "foo", will not match 1foo2
M-s w search word, ignore underscore, hyphen or space
   
M-% query replace (i.e. search and replace)
  y or SPC replace this
  n or DEL don't replace
  q or RET quit replace
  ! replace all occurrences
  . replace this and exit
   
M-C-% query replace regexp
   
M-s o occur: similar to grep. Show hits in separate buffer, with
  syntax highlighting preserved. (r in occur-buffer renames it)
  Lines can be edited in place(!) in the occur buffer
  M-g M-n move next hit from source buffer
  M-g M-p move prev hit from source buffer
  C-c C-f toggle follow mode on/off
   
  g rerun/re-read in dired, compile, occur, grep buffers.
  Can be started from within isearch with M-s o!
Table 8: While searching (in minibuffer):
Key Action
C-w add word at point to search
C-y yank/paste into minibuffer
M-e edit search entry in mini-buffer
M-c toggle case sensitivity
M-r regexp
M-SPC Match spaces
C-s repeat most recent search
M-n next search in history
M-p previous search in history

1.2.8 Emacs window frames

Table 9: Splitting / moving between Emacs panalized
Key Action
C-x 0 undo previous window split
C-x 1 one window
C-x 2 split window horizontally
C-x 3 split window vertically
C-x + Balance window (same size)
C-x o jump to other window

1.2.9 Keyboard macros!

The Power! To record and play back keyboard sequences. Awesome when doing the same thing on data/text with a pattern.

Table 10: Keyboard macros are the shit!
Key Description
C-x ( start (same as F3)
C-x ) stop (same as F4)
C-x e run macro (same as F4)
C-u N C-x e repeat N number of times
C-u 0 C-x e repeat until end of buffer is reached (macro must reach the end, else C-g).
C-x C-k r apply macro to each line in region. (macro does not have to move to next line)
C-x C-k n name and save macro (for this emacs session) use again with M-x name-of-macro
C-x C-k b bind to key, reserved by default: C-x C-k [0-9,A-Z]
C-x C-k e edit-kbd-macro: M-x name-of-macro pull upp a buffer where we can edit the macro
   
C-x C-k C-n next in keyboard macro ring
C-x C-k C-p previous in keyboard macro ring
C-x C-k C-k execute / select macro
   
C-x C-k C-c set counter, (set initial state, do before running the macro, default: 0)
C-x C-k C-a N add N to the counter
C-x C-k C-i add counter (adds one to each execution)
C-x C-k C-f set format of counter, default: %d
   
C-x q ask user for input

M-x insert-kbd-macro take a named macro and return elisp code.

1.2.10 scrolling in buffer

Key Action
C-l toggle between marker in center, top or bottom of screen.
   
C-v page down
PgD page down
   
M-v page up
PgUp page up
   
M-PgD page down in other window (if buffer split in two)
M-PgUp page up in other window (if buffer split in two)
   
C-M-S-v scroll other buffer up
C-M-v scroll other buffer down

1.2.11 Code navigation:

Table 11: Navigate in code
Key Action
C-M-a Move to start of function
C-M-e Move to end of function
   
C-M-f Move one syntax forward. i.e. jump to matching closing parenthesis/bracket/quote
C-M-b Move one syntax backward. i.e. jump to matching opening parenthesis/bracket/quote
   
M-m back to indentation (like doing C-a M-f)
   
C-M-u move up in hirarcy/list
C-M-d move down in hirarcy/list
   
C-up move up paragraph/code block
C-down move down paragraph/code block
C-left same as M-b (backward word)
C-right same as M-f (forward word)
   
M-; comment/uncoment region, or insert comment to the right if no active region

Note: to treat camelCased words as two, set M-x subword-mode

1.2.12 Goto line:

Table 12: line navigation
Key Action
M-g g goto line
M-g M-g goto line
M-g c goto char
M-g TAB goto column
   
M-g n goto next compilation error (next-error)
M-g p goto previous compilation error (previous-error)
   
M-g M-n goto next compilation error
M-g M-p goto previous compilation error

1.2.13 Tags:

Easy navigation in code. This requires that the the command etags *.{h,cpp} has been run, to generate a TAGS file. After this is done you can easily jump from where a function is used to where it's defined.

M-. goto where it's definied
M-, goto where it's used
M-* return to previous position

1.2.14 Other keys

Table 13: Misc
Key Action
C-o insert line above mark
M-q adjust paragraph
M-r move cursor to center of screen
C-l move buffer & mark to center/top/bottom of screen
M-/ dynamic expand (dabbrev-expand).
M-= count words

1.3 Useful functions   SEARCH REPLACE

Some stuff I keep handy for myself.

Table 14: Useful functions for Searching
key action
M-x list-matching-lines useful for searching one buffer
M-x grep -nH -e useful for searching dired of files
M-x grep-find for recursive searching through folders
M-x occur Can edit with e in emacs 24.1
M-x multi-occur  
Table 15: Misc
key action
M-x locate-library Where is that damn elisp-file?
M-x check-paren For finding unmatched parenthesis:
M-x phase-of-moon For gigs and laughs
M-x butterflies For gigs and laughs
M-x re-builder regexp-builder
C-u 0 M-x byte-recompile-directory recursive bytecomp. all files and subfolders

1.4 Compile Emacs from source   COMPILING

Extract source to build directory somewhere, then:

./configure  --prefix=/home/usr \
--without-tiff --without-toolkit-scroll-bars --without-gconf \
--without-gsettings --with-gif=no  --with-xft

(I also used to have

--with-x=no --with-x-toolkit=no

when I had GTK2, or otherwise it would kill my emacs server when GTK2 crashed. Not need now.

(run make distclean if I need to reconfigure.) Then compile, test run and install:

make
src/emacs -Q
make install

Problem with w3m? Install from el-get.

1.5 emacs regexp   REGEXP

The following copied from effective-emacs

  • You need to double-escape ("\\") regexp metacharacters in strings in elisp code, but you single-escape them when entering regexps at the minibuffer.
  • Emacs code does so much matching of parens that Emacs regexps reverse the paren character and metacharacter. In an Emacs regexp, "(" and ")" match actual parens, while "\(" and "\)" create matching groups.
  • In the replacement string, use \1, \2, etc. for inserting match-groups from the regexp.
  • If you enter in a regexp and it doesn't work, undo the result if the command actually changed anything. Then type the command again, and when it prompts you, use the arrow keys to scroll up and down to find your regexp and replacement string, and modify them in place. This can save you a lot of typing and frustration.
  • You can yank text into the middle of a regexp you're typing out with most regexp commands, but NOT in the isearch-*-regexp commands. Yank does weird things in those. I'd love to know how to fix this.

2 INITIALIZATION

Must set up paths (load-path) for lisp-files first. This is the most important line, and should be at the top of any configuration file.

"custom-file" hack was taken from here.

Note: M-: evaluates code. Write in variables here to check what their value is. (or use scrach buffer for same thing, and C-x C-e at end of name)

;; -*- emacs-lisp -*-
;; Time-stamp: <Last changed 2012-11-30 19:31:12 by Art Vandelay, vandelay>
(message "Reading configuration file...")

;;Initialize files----------------------------
;; Where to find external lisp-files, for modes, etc. I put my *el
;; files in "~/.emacs.d/elisp/" where ~/.emacs.d/ is the
;; user-emacs-directory
(add-to-list 'load-path (expand-file-name "elisp" user-emacs-directory))
;;--------------------------------------------

;; For the built in customization UI in emacs that no one uses. If
;; some package tries to use it, at least have the decency to keep
;; this config file clean.
(setq custom-file "~/.emacs.d/custom.el")
(load custom-file 'noerror)

2.1 Message buffer

Have this in the beginning of .emacs, to see which libraries are loaded on start up. Change as much as possible to auto-load.

;;keep message buffer complete.
(setq message-log-max t)

3 PACKAGE MANAGEMENT

3.1 package management

From masteringemacs.org "By default, all installed packages are loaded and activated automatically when Emacs starts up. To disable this, set `package-enable-at-startup’ to nil. To change which packages are loaded, customize `package-load-list’."

Update list: M-x package-refresh-contents Open list: M-x package-list-packages

Table 16: Keys in package-list.
key descirption
U Update all installed
? info on package
h help: show keys in minibuffer

You can pinn (short version) packages allowing emacs which repository to use for a certain package.

Regarding which repositories to use ELPA is the original one, but no longer maintained; GNU is the official maintained one and should always work, but isn't updated that often. Marmalade is a repo where you can upload packages, and what the community is most hopeful about. It was unmaintained a recent while, but is back on track. Melpa builds packages automatically from URL's from github or emacswiki, so it's never more than 1 day behind the repositories it tracks, and is surprisingly stable. Melpa stable tracks fewer packages, and has a time lag, to allow for bugfixes in the upstream repositories.

;; Note: Don't (require ...) packages prior to loading them with the
;; emacs package system ("elpa"), as it is not meaningful, doesn't
;; serve any purpose, nor semantically correct. Packages loaded in the
;; package system are autoloaded when visiting files where they're
;; needed (if well written).

(require 'package)

;; Since emacs 24 there's a very neat package system.
(when (>= emacs-major-version 24)
  (setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
                           ("melpa" . "http://melpa.org/packages/")
                           ("melpa-stable" . "http://stable.melpa.org/packages/")
                           ;;; Old, and no longer maintained:
                           ;;("ELPA" . "http://tromey.com/elpa/")
                           ;;("marmalade" . "http://marmalade-repo.org/packages/")
                           )))
(package-initialize)

3.2 pinn package source

If a package is available in multiple archives, we can set which ones to use for which package. I'm not using this, but might be useful.

;; Check if we're on Emacs 24.4 or newer, if so, use the pinned package feature
(when (boundp 'package-pinned-packages)
  (setq package-pinned-packages
        '((smex               . "melpa-stable")
          (zenburn-theme      . "melpa-stable") ; a nice theme
          (anti-zenburn-theme . "melpa-stable") ; a nice theme (brighter)
          (zen-and-art-theme  . "marmalade")    ; a nice theme (darker)
          ;;(htmlize            . "marmalade")
          ;;(rainbow-delimiters . "melpa-stable")
          ;; "unstable" package
          ;;(icicles            . "melpa")
          )))

3.3 Package auto-install

If running emacs on a new computer for the first time, then auto-install my packages. Source: stackoverflow.

Note: there is a package that does use same, that's called use-package, which is very popular, but I want to see the nuts and bolts, so I prefer this way.

;;Auto-install missing packages ---------------

;; packages I use all the time, which _must_
;; be installed on all my emacs-machines:
(setq my-must-have-packages
      '(auctex                          ; a must for LaTeX
        avy                             ; awesome for jumping / navigating cursor on screen
        bbcode-mode                     ; for editing forum-posts
        beacon                          ; show whre the cursor is when jumping between buffers & frames
        browse-kill-ring                ; a must! C-y (and M-y) on steroids!
        color-theme-sanityinc-tomorrow  ; blue version is nice (doesn't need the old color-theme package)
        command-log-mode                ; log pressed keys to buffer (e.g. useful for presentations)
        company                         ; for auto-compleate variables/functions (with drop down menu)
        company-auctex                  ; auto-complete for latex
        dtrt-indent                     ; awesome: automagically guess indentation style of file
        ;;emms                          ; emacs multimedia system, (for playlists etc.)
        erc-hl-nicks                    ; colour names on IRC
        ;;flycheck                        ; check code sanity while I type
        geiser                          ; for writing Scheme lisp
        gnuplot                         ; gnuplot-mode
        goto-chg                        ; navigate in buffer by using undo-history
        graphviz-dot-mode               ; because syntax highlight in graphviz scripts is nice
        green-phosphor-theme            ; a color theme, as the name suggests
        htmlize                         ; render current buffer face and syntax highlight to html
        lua-mode                        ; at least gives syntax highlight for Lua-code
        magit                           ; powerful git-interface
        matlab-mode                     ; yuck! when you must, you must
        markdown-mode                   ; markdown-mode for github posts
        mediawiki                       ; mode for editing mediawiki-buffers
        org                             ; use a more recent than default emacs
        paredit                         ; excellet for lisp, but steep lerning, for parenthesis manegement
        pov-mode                        ; for editing pov-ray files, (raytracer)
        rainbow-mode                    ; Colour hex rgb values, e.q. "#00ff00" in it's colour
        slime                           ; Superios Lisp Interaction Mode for Emacs
        ;;smartparens                   ; better parenthesis management: insert/delete/replace pairs
        smex                            ; smarter "M-x"
        sml-modeline                    ; I use it to replaces scrollbar, show info in modeline instead
        stumpwm-mode                    ; I'm not actually using this, but for my WM
        volatile-highlights             ; slightly shade just pasted region
        wanderlust                      ; email-client
        which-key                       ; smarter when half finished key combo
        with-editor                     ; make emacs default $EDITOR
        yasnippet                       ; auto-complete templates (e.g. if, for, do ...)
        ))

;; install any packages in my-must-have-packages,
;; if they are not installed already
(let ((refreshed nil))
  (when (not package-archive-contents)
    (package-refresh-contents)
    (setq refreshed t))
  (dolist (pkg my-must-have-packages)
    (when (and (not (package-installed-p pkg))
               (assoc pkg package-archive-contents))
      (unless refreshed
        (package-refresh-contents)
        (setq refreshed t))
      (package-install pkg))))

(defun package-list-unaccounted-packages ()
  "Like `package-list-packages', but shows only the packages that
  are installed and are not in `my-must-have-packages'.  Useful for
  cleaning out unwanted packages."
  (interactive)
  (package-show-package-list
   (remove-if-not (lambda (x) (and (not (memq x my-must-have-packages))
                                   (not (package-built-in-p x))
                                   (package-installed-p x)))
                  (mapcar 'car package-archive-contents))))
;;---------------------------------------------

4 THEMES & (NO)TOOLBAR

Set theme so emacs doesn't hurt my eyes anymore.

Sample Gallery of popular emacs theme can be seen on github.io/emacs-theme-gallery and emacsthemes.com.

Useful tip for the hacker: If you see some text that has some unexpected color, and you wonder why that is, move the cursor there, and call M-x describe-face.

Prior to emacs 24, one used the color-theme package to theme emacs (all themes prefixed with color-theme-...). However, since Emacs 24 a native theme system is now included. For the old color-theme packages converted to the new system check out this link.

4.1 For Emacs 24: Choose theme

Wombat is nice. Or zenburn, (there's an older alternative version by emacs-fu).

M-x customize-themes lists custom themes which can be enabled. Unlike just doing repeated M-x load-theme this actually unloads the previous one, so good for resetting, thus no lingering colors from previous theme. Note that emacs looks in custom-theme-directory followed by a built-in theme directory named “themes/” in data-directory.

;; Where to find Emacs24 themes for M-x load-theme
(when (>= emacs-major-version 24)
  (add-to-list 'custom-theme-load-path "~/.emacs.d/themes")
  (load-theme 'zenburn t nil)
  ;;(load-theme 'sanityinc-tomorrow-blue t nil)
)

4.2 For pre-Emacs 24: Choose theme

This chooses the theme for the emacsclient daemon depending on if I attach to it using

(when (require 'color-theme nil 'noerror)
  (setq color-theme-is-cumulative nil)

  ;;if using daemon mode / emacsclient
  (defun mb/pick-color-theme (frame)
    (select-frame frame)
    (let ((color-theme-is-global nil))
      (if (window-system frame)
          (cond ((require 'zenburn nil 'noerror)
                 (message "Choosing color theme zenburn.")
                 (color-theme-zenburn))
                (t
                 (message "Cant find zenburn, inverting face.")
                 (invert-face 'default))))))
  (add-hook 'after-make-frame-functions 'mb/pick-color-theme)

  ;; For when started with emacs or emacs -nw rather than emacs --daemon
  (let ((color-theme-is-global nil))
    ;;(color-theme-initialize)              ;;what is this? Do I need it?
    (if window-system                       ;;if running in x...
        (if (require 'zenburn nil 'noerror) ;;..and if we find color theme
            (eval-after-load "color-theme"
              '(color-theme-zenburn))       ;;...load it. (why must it be "eval-after-load"?)
          (invert-face 'default)))))        ;; if in x, but no theme, invert colors.
;;---------------------------------------------

4.3 TODO Graphical environment, X11 vs CLI

Find out if we are in tty or graphical environment, and set pertinent variables. This worked well, until I started using emacsclient (as server) instead of emacs. Thus the commented region.

;;--------------------------------------------
(tool-bar-mode -1)                        ;;never have a retarded tool-bar at top
(menu-bar-mode -1)                        ;;never have a retarded menu-bar at top
(scroll-bar-mode -1)                      ;;never have a retarded scrill-bar at side
(setq-default indicate-empty-lines t)     ;;show (in left margin) marker for empty lines

;;NOTE: not good when in daemon mode...
;; (cond ((eq window-system 'x)
;;        ;;Put properties for emacs in Xorg here:
;;        (message "Running in X")
;;        (setq-default indicate-empty-lines t))
;;       (t
;;        ;; Put properties for emacs in CLI here
;;        (message "Running in terminal")
;;        ;;(menu-bar-mode 0)
;;        ))
;;--------------------------------------------

4.4 Mode-line

http://www.emacswiki.org/emacs/sml-modeline.el

;;Modline-------------------------------------
(line-number-mode t)                        ;; show line numbers
(column-number-mode t)                      ;; show column numbers
;;(size-indication-mode t)                    ;; show file size (emacs 22+)

;;(when (> (display-color-cells) 16)          ;if not in CLI
(if (require 'sml-modeline nil 'noerror)  ;; use sml-modeline if available
    (progn
      (sml-modeline-mode 1)               ;; show buffer pos in the mode line
      (scroll-bar-mode -1))               ;; turn off the scrollbar
  (scroll-bar-mode -1))                   ;; otherwise, still don't show a scrollbar...
;;--------------------------------------------

5 RSS/Atom-reader: NEWSTICKER

Newsticker is the built in RSS-reader and Atom aggregator that comes with Emacs. M-x newsticker-show-news. There are two display types, treeview (use multiple split buffers), and plainview (one buffer).

Newsticker provides several commands for reading headlines, navigating through them, marking them as read/unread, hiding old headlines etc. Headlines can be displayed as plain text or as rendered HTML.

Table 17: Newsticker keys
Key Action
N Next, unread
P Previous, unread
n next
p previous
O  
o  
v open in browser
b  
q quit

RSS feeds for youtube channels named say xxx can be gotten through: https://gdata.youtube.com/feeds/api/users/xxx/uploads https://www.youtube.com/feeds/videos.xml?user=xxx

(setq
 ;; newsticker-heading-format "%t"
 ;; newsticker-item-format "%t"
 ;; newsticker-desc-format "%d\n%c"
 ;; newsticker-hide-old-items-in-newsticker-buffer t
 newsticker-html-renderer 'shr-render-region
 ;; newsticker-frontend 'newsticker-plainview
 ;; newsticker-use-full-width nil
 newsticker-treeview-treewindow-width 40
 newsticker-treeview-listwindow-height 20
 newsticker-url-list-defaults nil  ;remove default list (i.e. emacswiki)
 newsticker-retrieval-interval 0   ;don't fetch when I'm not reading RSS
 newsticker-automatically-mark-items-as-old nil
 newsticker-url-list '(
                       ("emacs-fu" "http://emacs-fu.blogspot.com/feeds/posts/default" nil nil nil)
                       ("abandonia" "http://www.abandonia.com/en/rss.xml" nil nil nil)
                       ("arch linux" "https://www.archlinux.org/feeds/news/" nil nil nil)
                       ("Planet Emacsen" "http://planet.emacsen.org/atom.xml" nil nil nil)
                       ("slashdot" "http://rss.slashdot.org/Slashdot/slashdot" nil nil nil)
                       ("Kmandla" "http://kmandla.wordpress.com/feed/" nil nil nil)
                       ("mojäng" "http://www.mojang.com/feed" nil nil nil)
                       ("SMBC" "http://www.smbc-comics.com/rss.php" nil nil nil)
                       ("xkcd" "https://www.xkcd.com/rss.xml" nil nil nil)
                       ;;("imdb" "http://rss.imdb.com/daily/poll" nil nil nil)
                       ;;("rotten" "https://www.rottentomatoes.com/syndication/rss/top_news.xml" nil nil nil)
                       ;;("BBC World" "http://feeds.bbci.co.uk/news/world/rss.xml" nil nil nil)
                       ("BBC Sci" "http://feeds.bbci.co.uk/news/science_and_environment/rss.xml" nil nil nil)
                       ;;("Coursera" "http://blog.coursera.org/rss" nil nil nil)
                       ;;("stallman" "http://www.stallman.org/rss/rss.xml" nil nil nil)
                       ("emacs rocks" "http://emacsrocks.com/atom.xml" nil nil nil)
                       ("endlessparentheses" "http://endlessparentheses.com/atom.xml" nil nil nil)
                       ("affärsvärlden" "http://www.affarsvarlden.se/?service=rss" nil nil nil)
                       ("börspodden" "http://borspodden.se/feed/" nil nil nil)
                       ("dividend mantra" "http://feeds.feedburner.com/DividendMantra/" nil nil nil)
                       ("avpixlat" "http://avpixlat.info/feed/" nil nil nil)
                       ("recepten" "http://www.recepten.se/feed/blog_rss2.xhtml" nil nil nil)
                       ;;("Hacker News" "http://news.ycombinator.com/rss" nil nil nil)
                       ("screen junkies" "https://www.youtube.com/feeds/videos.xml?user=screenjunkies" nil nil nil)
                       ("Matte Northice" "https://www.youtube.com/feeds/videos.xml?user=gurskit8" nil nil nil)
                       ("Simon Smith" "https://www.youtube.com/feeds/videos.xml?user=simonthedragon" nil nil nil)
                       ("failarmy" "https://www.youtube.com/feeds/videos.xml?user=failarmy" nil nil nil)
                       ("thuleanperspective" "https://www.youtube.com/feeds/videos.xml?user=ThuleanPerspective" nil nil nil)
                       ("danwood" "https://www.youtube.com/feeds/videos.xml?user=techguruuk" nil nil nil)
                       ("LGR" "https://www.youtube.com/feeds/videos.xml?user=phreakindee" nil nil nil)
                       ))

6 BUFFERS

Controlling the buffer behavior.

6.1 Revert buffers

If many files changes on disk while emacs has them opened as buffers, we can either revert every buffer independently, or call the command defined below.

(defun revert-all-buffers ()
  "Refreshes all open buffers from their respective files."
  (interactive)
  (dolist (buf (buffer-list))
    (with-current-buffer buf
      (when (and (buffer-file-name) (not (buffer-modified-p)))
        (revert-buffer t t t) )))
  (message "Refreshed open files."))

6.2 Uniquify

When several buffers have the same name, make the name uniqe by including part of path in name.

;;Uniquify-buffers ----------------------------
(when (require 'uniquify nil 'noerror)  ;; make buffer names more unique
  (setq
   uniquify-buffer-name-style 'post-forward
   uniquify-separator ":"
   uniquify-after-kill-buffer-p t       ;; rename after killing uniquified
   uniquify-ignore-buffers-re "^\\*"))  ;; don't muck with special buffers
;;---------------------------------------------

6.3 Auto remove/kill Completion buffer when done

This is my own hack. For a more complete solution there's popwin-el, which allows C-g to close any pop-up buffer like \*Help\* or \*Completions\* etc.

;;Remove/kill completion buffer when done-----
;;could use ido-find-file instead, since it never uses *Completions*
;;Note that ido-mode affects both buffer switch, &  find file.
(add-hook 'minibuffer-exit-hook
          '(lambda ()
             (let ((buffer "*Completions*"))
               (and (get-buffer buffer)
                    (kill-buffer buffer)))
))
;; TODO: Kill: *dictem buffer*, *Apropos, *Help*
;; kill them when you leave the buffer, like: C-x o
;;--------------------------------------------

6.4 Winner-mode (for window/buffer layout)

Useful to switch between different/previous buffer-layouts, or buffer history, but I don't actually use this though (Winner-mode is in Emacs since v.20).

There's also ace-window for moving between many windows.

;;Winner-mode---------------------------------
;; cycle through window layouts/contents
;; winner conflicts with org, use C-c left/right instead
(when (require 'winner nil 'noerror)
  (setq winner-dont-bind-my-keys t)
  (global-set-key (kbd "<C-c left>")  'winner-undo)
  (global-set-key (kbd "<C-c right>") 'winner-redo)
  (global-set-key (kbd "<XF86Back>")    'winner-undo)
  (global-set-key (kbd "<XF86Forward>") 'winner-redo)
  (winner-mode t))
;;--------------------------------------------

6.5 Dired-face

By default dired colors files with one of two colors, depending on if it's a folder or not. We can do better: screenshot, EW-source, git-source

(eval-after-load 'dired '(progn (require 'dired-filetype-face)))

6.6 ibuffer

Replace the normal list buffers command, (C-x C-b) with ibuffer.

Table 18: ibuffer frequently used keys
Key  
m Mark
u Unmark
*u Mark unsaved
S Save marked buffer
D Close marked buffers
t Invert marked/unmarked buffers.
* * Unmark all marked buffers.
* M Mark buffers by major mode.
* s Mark special buffers
* / mark dired buffers
* e mark dissociated buffers
* h mark help buffers
* m mark modified buffers
* r mark read only buffers
* u mark unsaved buffers
* z mark compressed file buffers
s f Sort the buffers by the file name.
s v Sort the buffers by last viewing time.
s s Sort the buffers by size.
s m Sort the buffers by major mode.
/ m Add a filter by major mode.
/ n Add a filter by buffer name.
/ c Add a filter by buffer content.
/ e Add a filter by an arbitrary Lisp predicate.
/ / Remove all filtering currently in effect.
"=" View the differences between this buffer and its
% f mark by file name regexp
% m mark by mode regexp
% n mark by name regexp

M-s a C-s ibuffer-do-isearch "Do an incremental search in the marked buffers. This is so awesome that you have to try it right this instant. Select two or more buffers, hit the hotkey, search for something that occurs in all these buffers. These two features alone are enough to make me a lifelong fan of IBuffer."

Q ibuffer-do-query-replace

M-s a C-s - Do incremental search in the marked buffers. M-s a C-M-s - Isearch for regexp in the marked buffers. U - Replace by regexp in each of the marked buffers. Q - Query replace in each of the marked buffers. I - As above, with a regular expression.

6.6.1 filter

Group the open buffers in a list according to these rules:

  ;;---------------------------------------------
  ;; pressing S saves all unsaved buffers, try hitting SPC at [Org]-label.
  ;; See what happens
  ;; RET folds a filter (like folders and hierarchies)

  (require 'ibuffer)

  ;;replace default with ibuffer. Open i other window, and take me there.
  (global-set-key (kbd "C-x C-b") 'ibuffer-other-window)

  ;;sort on major-mode
  (setq ibuffer-default-sorting-mode 'major-mode)

  (setq ibuffer-saved-filter-groups
        (quote (("default"
                 ("Org" ;; all org-related buffers
                  (mode . org-mode))
                 ;; ("equfitter"
                 ;;  (filename . "equationfitter/"))
                 ("Programming C++" ;; prog stuff not already in MyProjectX
                  (or
                   (mode . c-mode)
                   (mode . c++-mode)
                   ))

                 ("Source Code" ;; non C++ related stuff.
                  (or
                   (mode . python-mode)
                   (mode . emacs-lisp-mode)
                   (mode . shell-script-mode)
                   (mode . f90-mode)
                   (mode . scheme-mode)
                   ;; etc
                   ))

                 ("LaTeX"
                  (or
                   (mode . tex-mode)
                   (mode . latex-mode)
                   (name . ".tex")
                   (name . ".bib")
                   ))

                 ("Text" (name . ".txt"))

                 ("Mail"
                  (or  ;; mail-related buffers
                   (mode . message-mode)
                   (mode . mail-mode)
                   (mode . mime-mode)
;;                   (mode . MIME-mode)

                   ;; etc.; all your mail related modes
                   ))

                 ("Web" (or (mode . html-mode)
                            (mode . css-mode)))

                 ("ERC"   (mode . erc-mode))

                 ;; ("Subversion" (name . "\*svn"))
                 ;; ("Magit" (name . "\*magit"))

                 ("Emacs-created"
                  (or
                   (name . "^\\*")))
                 ))))

  (add-hook 'ibuffer-mode-hook
            (lambda ()
              ;;(ibuffer-auto-mode 1)   ;auto update the buffer-list
              (ibuffer-switch-to-saved-filter-groups "default")))

  ;;Don't show (filter) groups that are empty.
  (setq ibuffer-show-empty-filter-groups nil)
  ;;(autoload 'ibuffer "ibuffer" "List buffers." t)

  ;; keep from warning, twice, about deleting buffers.
  ;; only warn about deleting modified buffers.
  (setq ibuffer-expert t)

  ;; ;; Switching to ibuffer puts the cursor on the most recent buffer
  ;; (defadvice ibuffer (around ibuffer-point-to-most-recent) ()
  ;;   "Open ibuffer with cursor pointed to most recent buffer name"
  ;;   (let ((recent-buffer-name (buffer-name)))
  ;;     ad-do-it
  ;;     (ibuffer-jump-to-buffer recent-buffer-name)))
  ;; (ad-activate 'ibuffer)
  ;;---------------------------------------------

6.6.2 Restore window layout/configuration after selecting a buffer

When invoking ibuffer-other-window (which I've bound to C-x C-b) ibuffer pops up in a split buffer, which goes away when pressing "q". But it should also go away if I open a buffer from the ibuffer list. This does that: (or just use C-u RET)

;;---------------------------------------------
(define-key ibuffer-mode-map [remap ibuffer-visit-buffer]
  '(lambda () (interactive)
     (ibuffer-visit-buffer t)))
;;---------------------------------------------

6.6.3 compare marked buffers

;;---------------------------------------------
(defun ibuffer-ediff-marked-buffers ()
  (interactive)
  (let* ((marked-buffers (ibuffer-get-marked-buffers))
         (len (length marked-buffers)))
    (unless (= 2 len)
      (error (format "%s buffer%s been marked (needs to be 2)"
                     len (if (= len 1) " has" "s have"))))
    (ediff-buffers (car marked-buffers) (cadr marked-buffers))))

(define-key ibuffer-mode-map "e" 'ibuffer-ediff-marked-buffers)
;;---------------------------------------------

6.7 icomplete / iswitchb

Auto completion in minibuffer, with list sorted by most recently visited buffer. Can auto complete any part of file name to get it unique. Another nice feature: the list can be scrolled through with C-s and C-r.

;;buffer switching ----------------------------
;;better C-x b  (ido does the same for C-x C-f)
(iswitchb-mode t) ;; obsolete by icomplete-mode!
;;---------------------------------------------

icomplete's advantage over ido is that it works with files, buffers, and variables, fuctions, etc.

ido only works with buffers and files, I think; at least not with variables and functions.

C-. and C-, cycles through the list, and C-j (or RET) selects the buffer, but I prefer the backwards/forwards search C-r/s keys.

(icomplete-mode 1)
(define-key icomplete-minibuffer-map [?\C-s]
            'icomplete-forward-completions)
(define-key icomplete-minibuffer-map [?\C-r]
            'icomplete-backward-completions)

Or, just do:

(ido-mode 'buffers)

6.8 Occur

occur write up

Occur is awesome. Do M-s o to search for a word in current buffer and show list of all occurrences in a separate buffer.

M-x   multi-occur-in-matching-buffers

is where the real power is, since this lets you search all open buffers matching the regexp you give it, and show hits in a new buffer, which behaves just like the compile buffer.

(eval-when-compile
  (require 'cl))

(defun get-buffers-matching-mode (mode)
  "Returns a list of buffers where their major-mode is equal to MODE"
  (let ((buffer-mode-matches '()))
    (dolist (buf (buffer-list))
      (with-current-buffer buf
        (if (eq mode major-mode)
            (add-to-list 'buffer-mode-matches buf))))
    buffer-mode-matches))

(defun multi-occur-in-this-mode ()
  "Show all lines matching REGEXP in buffers with this major mode."
  (interactive)
  (multi-occur
   (get-buffers-matching-mode major-mode)
   (car (occur-read-primary-args))))

;; global key for `multi-occur-in-this-mode' - you should change this.
;;(global-set-key (kbd "C-<f2>") 'multi-occur-in-this-mode)

7 MAIN EMACS HACKS

7.1 arch linux pkgbuild-mode:

(autoload 'pkgbuild-mode "pkgbuild-mode.el" "PKGBUILD mode." t)
(setq auto-mode-alist (append '(("/PKGBUILD$" . pkgbuild-mode)) auto-mode-alist))

7.2 abbrevs

Abbrev lets you replace an abreviation with a full string after you press SPC (or punctuation). See example below.

Abrevs can be saved with "C-x a i g" (abbrev inverse global) with point at end of expanded full word.

C-x a g Define new (mode) global abbrev C-x a l Define new (mode) local abbrev

To not expand what you just typed into the abbrev: C-q before hitting SPC (or punctuation).

(setq abbrev-file-name                ;; tell emacs where to read abbrev
      "~/.emacs.d/abbrev_defs.el")    ;; definitions from...
(setq save-abbrevs t)                 ;; (ask) save abbrevs when files are saved
(setq-default abbrev-mode t)          ;; turn it on for all modes

;; (when (file-exists-p abbrev-file-name)
;;   (quietly-read-abbrev-file))          ;;  don't tell
;; (add-hook 'kill-emacs-hook             ;; write when ...
;;           'write-abbrev-file)          ;; ... exiting emacs

7.2.1 example

My global abrevs are prefixed by 8 due to utf8 key sequence in emacs C-x 8 C-h.

The following is in my file "~/.emacs.d/abbrev_defs.el", and replaces the string in the list like so: when typing "8alpha" SPC it is replaced by the correct character.

(define-abbrev-table 'global-abbrev-table '(
    ("8alpha"   "α")
    ("8beta"    "β")
    ("8gamma"   "γ")
    ("8Delta"   "Δ")
    ("8delta"   "δ")
    ("8theta"   "θ")
    ("8lambda"  "λ")
    ("8mu"      "µ")
    ("8nu"      "ν")
    ("8pi"      "π")
    ("8Sigma"   "Σ")
    ("8sigma"   "σ")
    ("8tau"     "τ")
    ("8phi"     "φ")
    ("8psi"     "ψ")
    ("8Omega"   "Ω")
    ("8omega"   "ω")
    ("8in"      "∈")
    ("8nin"     "∉")
    ("8inf"     "∞")
    ))

7.3 Various one line commands/configurations

;;One-Line commands---------------------------
(defalias 'yes-or-no-p 'y-or-n-p)     ;;answer "y/n" rather than "yes/no"
;(delete-selection-mode t)            ;;delete region at key press, not needed due to cua-mode nil (in rectangle)
(setq visible-bell t)                 ;;blink instead of beep
(setq inhibit-startup-message t)      ;;Don't show start up message/buffer
(file-name-shadow-mode t)             ;;be smart about file names in mini buffer
(global-font-lock-mode t)             ;;syntax highlighting on...
(setq font-lock-maximum-decoration t) ;;...as much as possible
(setq frame-title-format '(buffer-file-name "%f" ("%b"))) ;;titlebar=buffer unless filename

(setq-default indent-tabs-mode nil)   ;;use spaces instead of evil tabs

(setq tetris-score-file "~/.emacs.d/tetris-scores") ;;keep home-folder clean

;; Instead of C-u C-SPC C-u C-SPC to pop mark twice, do: C-u C-SPC C-SPC
(setq set-mark-command-repeat-pop t)
;;--------------------------------------------

7.4 Miscellaneous

Inconsolata is nice open source font for programming.

;;miscellaneous--------------------------------
;;set the font to use:

;; Now using emacsclient, must use this format instead:
(add-to-list 'default-frame-alist '(font . "Inconsolata-11"))
;; or:
;;(setq default-frame-alist '((font . "Inconsolata-11")))

;; pre-using emacsclient:
;;(set-frame-font "Inconsolata-11")
;;(set-frame-font "DejaVu Sans Mono-9")
;;(set-default-font "7x13")


;; Make URLs in comments/strings clickable, (emacs > v22)
(add-hook 'find-file-hooks 'goto-address-prog-mode)

;; Make shell scrips executable on save. Good!
(add-hook 'after-save-hook 'executable-make-buffer-file-executable-if-script-p)

(setq initial-scratch-message ";; scratch buffer created -- happy hacking\n")

;;Emacs is a text editor, make sure your text files end in a newline
(setq require-final-newline 'query)

;; set default mode for unknown files
(setq-default major-mode 'org-mode)

;;no extra whitespace after lines
;; http://emacsredux.com/blog/2013/05/16/whitespace-cleanup/
;;'whitespace-cleanup is better than delete-trailing-whitespace
;;(add-hook 'before-save-hook 'delete-trailing-whitespace)
(add-hook 'before-save-hook 'whitespace-cleanup)

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

7.5 Allow use of some advanced commands

;;--------------------------------------------
;;Enable disabled command:
(put 'upcase-region 'disabled nil)    ;; same as M-u but on whole regions C-x C-u
(put 'downcase-region 'disabled nil)  ;; same as M-l but on whole regions C-x C-l
;;--------------------------------------------

7.6 Global Key-Bindings

;;Key-Bindings--------------------------------
(global-set-key (kbd "M-#")   'sort-lines)            ;;sort lines with Alt-#
(global-set-key (kbd "C-#")   'sort-paragraphs)       ;;sort paragraphs Ctrl-#

(global-set-key [(control tab)] 'hippie-expand)       ;;Ctrl-Tab, word-completion

;;(global-set-key (kbd "C-v")   'yank)                ;;closer on keyboard than "C-y"
;;(global-set-key (kbd "C-z")   'undo)                ;;better than "C-_"

(global-set-key (kbd "<f7>")  'toggle-truncate-lines)       ;;line wrapping on/off
(global-set-key (kbd "<f8>")  'comment-or-uncomment-region) ;; comment/un-comment region
(global-set-key (kbd "<f9>")  'compile)                     ;; compile

;;Learn to use default: M-next / M-prior (i.e. M-PgUp/M-PgDwn)
;;(global-set-key (kbd "<C-M-next>")  'scroll-other-window)
;;(global-set-key (kbd "<C-M-prior>") 'scroll-other-window-down)

;; a better C-h i is C-h C-i which has tab compleation on info sections
;; http://emacsredux.com/blog/2014/11/13/quickly-open-an-info-manual/
(define-key 'help-command (kbd "C-i") 'info-display-manual)

(global-set-key (kbd "C-x w") 'write-region)   ;;save marked region as a file

(global-set-key (kbd "M-SPC ") 'cycle-spacing)   ;;Since Emacs 24: a better way of M-SPC

(global-set-key "\C-ct" 'untabify)               ;;replace all evil TAB to SPC nice!
(global-set-key "\C-ci" 'indent-region)          ;;Indent row/marked region
;;(global-set-key "\C-ca" 'mark-whole-buffer)    ;;same as C-x h

;; C-pgup goes to the start, C-pgdw goes to the end:
(global-set-key(kbd "<C-prior>")(lambda()(interactive)(goto-char(point-min))))
(global-set-key(kbd "<C-next>") (lambda()(interactive)(goto-char(point-max))))

;;If you find yourself setting and unsetting selective-display as often as i do,
;; next thing will be defining a handy keyboard shortcut, right?
(defun jao-toggle-selective-display ()
  (interactive)
  (set-selective-display (if selective-display nil 1)))
(global-set-key [f12] 'jao-toggle-selective-display)

;;navigatoin-menu on right mouse button. Used by ref-TeX, and Org-mode.
(global-set-key [down-mouse-3] 'imenu)

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

7.7 ediff mode

Ediff is awesome, but has some stupid defaults, with separate useless control window. Be a buffer instead! Wisdom from here

ediff-current-file
useful for diffing unsaved changes in buffer.
ediff-buffers
useful if you have two frames open with different buffers.
ediff-buffers
same as ediff-buffers, but on files.
Table 19: Keys useful in ediff. (Possible some are for when using ediff in magit?)
Key Function
n next
p previous
q quit
a ediff-copy-A-to-B
b ediff-copy-B-to-A
;;Don't use strange separate control-window.
(customize-set-variable 'ediff-window-setup-function 'ediff-setup-windows-plain)

;;Side by side comparison is easier than vertical split
;;(tob-bottom-stacked) window
(customize-set-variable 'ediff-split-window-function 'split-window-horizontally)

;; ;; To ignore white space. Note: not good for Python
;; (csetq ediff-diff-options "-w")

;; reset the window configuration after ediff is done
;;(winner-mode)
;;(add-hook 'ediff-after-quit-hook-internal 'winner-undo)

7.8 htmlize

File for converting Emacs fontification (colours, italics, etc) into HTML. Handy to convert parts or whole buffers to html, with syntax highlighting. Like saving ERC logs, or code. It's included in emacs-goodies-el.deb on Debian.

Check out http://www.emacswiki.org/emacs/PrintWithWebBrowser.

;;htmlize--------------------------------------
;; convert buffer (with type face, and syntax highlighting) to *.html
;; htmlize; http://fly.cc.fer.hr/~hniksic/emacs/htmlize.el.html
(autoload 'htmlize-region "htmlize" "htmlize the region" t)
(autoload 'htmlize-buffer "htmlize" "htmlize the buffer" t)
;;---------------------------------------------

7.9 beacon-mode

A minor mode that indicates the position of your cursor in the buffer, by a short flash, whenever it moves, so that you don't loose it. Install it from melpa. Official soruce on github. Also mention by endlessparentheses.

;;htmlize--------------------------------------
;; When cursor jumps, flash it's new position, so we don't loos it
(if (functionp 'beacon)
  (beacon-mode 1)

  ;; only flash on window/buffer changes...
  (setq beacon-blink-when-window-changes t)
  ;; ... don't be excessive:
  (setq beacon-blink-when-window-scrolls nil)
  (setq beacon-blink-when-point-moves nil)
  (setq beacon-blink-duration .2)       ; default .3
  (setq beacon-blink-delay .2)          ; default .3
  (setq beacon-size 20))                ; default: 40
;;---------------------------------------------

7.10 TAB-completion

7.10.1 Hippie expand

I believe this tries to expand the word at point by going through a list of many different methods, dabbrevs is one of them:

"HippieExpand looks at the word before point and tries to expand it in various ways including expanding from a fixed list (like "expand-abbrev"), expanding from matching text found in a buffer (like "dabbrev-expand") or expanding in ways defined by your own functions. Which of these it tries and in what order is controlled by a configurable list of functions."

By default M-/ is bound to dabbrev-expand dynamic abbrev. M-/ cycles through different completions, based on what you have written before point, and after.

;; hippie-expand ------------------------------
(setq hippie-expand-try-functions-list
      '(try-expand-dabbrev-visible
        try-expand-dabbrev
        try-expand-dabbrev-all-buffers
        try-expand-dabbrev-from-kill
        try-complete-file-name-partially
        try-complete-file-name
        ;; yas has TAB, and abbrevs has SPC, so not needed here
        ;; try-expand-all-abbrevs
        ;; yas/hippie-try-expand
        ;;
        ;;         try-expand-list
        ;;         try-expand-line
        ;;        try-complete-lisp-symbol-partially
        ;;        try-complete-lisp-symbol
        ))

;;preserve case on expand with dabbrev
;;(setq dabbrev-case-replace nil)

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

7.10.2 Yasnippet

First emacs had it's abrevs. Then Textmate was jealous and came up with even more powerful TAB-completion/templates with query-fields. With Emacs being easily extendable, it was a no brainer to port that to emacs and make it even more powerful. It uses same/similar syntax as textmate, so import was simple. Plus you can write your own easily but save them elsewhere*. Can easily be installed through the emacs package system, but for reference: git-soruce (for the official yasnippet elisp code) git-source-snippets (for the templates/snippets used by yasnippet)

Now yasnippet only loads snippets on demand, so (yas/load-directory ...) is no longer needed, which gives faster starup.

  • When looking for snippets the variable that holds the snippets is read. This can be set e.g. (setq yas-snippet-dirs '("~/emacs.d/mysnippets" "~/Downloads/interesting-snippets")). By default it looks for the users personal snippets in "~/.emacs.d/snippets", and the bundled ones as a subdirectory relative to the location of yasnippet.el.
;;Yasnippet ----------------------------------
(with-eval-after-load 'yasnippet (yas/global-mode 1))
;;--------------------------------------------

7.11 Copy/Paste buffers across X11

;;Copy-Paste----------------------------------
;;(work with both terminal (S-INS) and X11 apps.):
(when (> (display-color-cells) 16)         ;if not in CLI
  (setq x-select-enable-clipboard t        ;copy-paste should work (default in emacs24)
        interprogram-paste-function        ; ...with ...
        'x-cut-buffer-or-selection-value)) ; ...other X-clients
;;--------------------------------------------

7.12 Encryption

Automatically decrypt/encrypt *.gpg-files. Works like a charm. For instance, a file my_passwords.org.gpg gets loaded in org-mode, by default.

However, I haven't been able to get the password promt to be in the minibuffer. I've tried everything at How to use a non-graphical password prompt for gpg.

You may also encrypt just part of a text in org-mode, using org-crypt. See org-section for further details.

;;Encryption-------------------------------
;;Setup for transparent, automatic encryption and decryption:
;;(does naught... ?)
(when (require 'epa-file nil 'noerror)
  (epa-file-enable)

  ;; t      to always ask for user
  ;; nil    to ask for users unless specified
  ;;'silent to use symmetric encryption:
  (setq epa-file-select-key 'silent)

  ;;Note: if you have an instance of seahorse running, then the environment
  ;;variable GPG_AGENT_INFO=/tmp/seahorse-nDQm50/S.gpg-agent:6321:1, which
  ;;causes emacs to start a GUI for password, instead of using mini-buffer.

  (setenv "GPG_AGENT_INFO" nil)
  ;; Note: another form is:
  ;;(setenv (concat "GPG_AGENT_INFO" nil))
  )
;;---------------------------------------------

Turn off any auto-saving function or backup for gpg-files, since they are saved as plain text. src

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

With no argument, this command toggles the mode. Non-null prefix
argument turns on the mode. Null prefix argument turns off the
mode."
  ;; The initial value.
  nil
  ;; The indicator for the mode line.
  " Sensitive"
  ;; The minor mode bindings.
  nil
  (if (symbol-value sensitive-mode)
      (progn
        ;; disable backups
        (set (make-local-variable 'backup-inhibited) t)
        ;; disable auto-save
        (if auto-save-default
            (auto-save-mode -1)))
    ;; resort to default value of backup-inhibited
    (kill-local-variable 'backup-inhibited)
    ;;resort to default auto save setting
    (if auto-save-default
        (auto-save-mode 1))))

(setq auto-mode-alist
      (append '(("\\.gpg$" . sensitive-mode))
              auto-mode-alist))
;;---------------------------------------------

7.13 Effective Emacs

:noexport: Once one have taken a shine to Emacs, it's well worth optimizing it: https://sites.google.com/site/steveyegge2/effective-emacs

(…although I acutally don't use anything that's in there)

;; Rebind M-x to C-x C-m, for ergonomics
(global-set-key "\C-x\C-m" 'execute-extended-command)
(global-set-key "\C-c\C-m" 'execute-extended-command)

;; nicer on the fingers, if using M-x, since using non-US-keyboard.
(defalias 'qrr 'query-replace-regexp)

7.14 Auto compile LISP files on save

Very handy! Auto compiles .emacs if changes (and saved), if there is a byte compiled version of it from before. I actually don't have any byte compiled version of my .emacs anymore since I'm running emacsclient.

;;Auto compile *.elc-files on save -----------
(defun auto-byte-recompile ()
  "If the current buffer is in emacs-lisp-mode and there already exists an `.elc'
file corresponding to the current buffer file, then recompile the file on save."
  (interactive)
  (when (and (eq major-mode 'emacs-lisp-mode)
             (file-exists-p (byte-compile-dest-file buffer-file-name)))
    (byte-compile-file buffer-file-name)))
(add-hook 'after-save-hook 'auto-byte-recompile)
;;--------------------------------------------

7.15 Bookmarks

TODO: I've never used bookmarks. I just use register marks instead. C-x r SPC/j.

;;Bookmarks-----------------------------------
;; C-x r m ('make') will create a new bookmark, defaulting to the current file.
;; Jump to an existing bookmark with C-x r b ('bookmark')
;; You can see the list of your bookmarks with C-x r l ('list').
(setq
  bookmark-default-file "~/.emacs.d/bookmarks" ;; keep ~/ clean from .files
  bookmark-save-flag 1)                        ;; auto save changes
;;--------------------------------------------

7.16 register

Registers are super useful in emacs. It's what prefixed by "C-x r". Allows storing of rectangular selections, copy, paste, multiple cut/paste, etc, and remember positions in a buffer (for that session).

Set register (bookmark) with C-x r SPC [number], and jump to it with C-x r j [number].

;;Recenter after jump-to-register--------------
;;When jumping, put mark on top of screen, not bottom, as is default
(defadvice jump-to-register
  (after jump-to-register-recenter-top)
  "Recenter point to top of window after jumping to a register."
  (recenter 0))
(ad-activate 'jump-to-register)
;;---------------------------------------------
;; Useful to display list of the registers
(when (require 'list-register nil 'noerror)
 (global-set-key (kbd "C-x r v") 'list-register))

7.17 avy-mode

avy (src) is best described as an improved ace-jump (video) that is more well maintained, and works for links (info-mode, help-mode, eww-mode), and windows as well. Also, it supports two char input! (blog)

(global-set-key (kbd "C-c SPC") 'avy-goto-char)
(global-set-key (kbd "M-g w") 'avy-goto-word-1)
(global-set-key (kbd "M-g M-w") 'avy-goto-word-1)
(define-key (current-global-map) [remap goto-line] 'avy-goto-line)

;; When org-mode starts it (org-mode-map) overrides this binding.
(add-hook 'org-mode-hook
          (lambda ()
            (local-set-key (kbd "C-c SPC") 'avy-goto-char)))

;; Use the home keys on a qwety keyboard
(setq avy-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))

;; Put overlay ontop (obscuring) the text, since this doesn't shift the line
;; 'at = single char at target; 'pre = before target; 'post = after target
(setq avy-style 'at-full)

;; Bind o to jump link in info-mode, help-mode, and eww-mode
;;(ace-link-setup-default)

7.18 goto-chg

Very useful. Go to the place where you last changed something. I actually find myself sometimes undoing something just to get to where I made a change and then undo the undo. With goto-chg, no more! It jumps the marker to the last place of a change.

Note for keybinding, "M-." will conflict with etags navigation in code, and "C-." will conflict with flyspell-mode, both of which I use a lot. Time to cash in on actually having extra letters in the alphabet.

(when (require 'goto-chg nil 'noerror)
  (global-set-key (kbd "C-ä") 'goto-last-change)
  (global-set-key (kbd "C-M-ä") 'goto-last-change-reverse))

7.19 undo tree

See pragmatic emacs for example, or ew, src.

Table 20: undo-tree keys
Key Alt. Key Description
C-_ C-/ undo (as before)
M-_ C-? for redo
C-x u   for undo-tree (then use cursors)
(when (not (require 'undo-tree nil 'noerror))
  (global-undo-tree-mode))

7.20 zap-to-char

To delete everything from marker up to (and including) character: M-z. But excluding the character, we can rebind M-z from here.

(autoload 'zap-up-to-char "misc"
  "Kill up to, but not including ARGth occurrence of CHAR.")
(global-set-key (kbd "M-z") 'zap-up-to-char)

7.21 find-file-at-point (ffap)

It's in emacs. When doing C-x C-f use information at point (your cursor) to open file or URL. I.e. if your cursor is on a file path, or URL, it defaults to that filled in the minibuffer.

;;find-file-at-point, smarter C-x C-f when point on path or URL
(ffap-bindings)

7.22 auto completion for M-x

This can be done in many ways. I used to use:

(icomplete-mode t)

It worked, but smex is more powerful.

The commands are displayed in an Ido (part of emacs since verison 22) completion buffer, ordered by relevance. The 7 most recently executed commands come first, the rest are sorted by frequency of use, command length and in alphabetical order.

;;smex - A smarter M-x compleation ------------
(with-eval-after-load "smex"
  (smex-initialize)
  (global-set-key (kbd "M-x") 'smex)
  (global-set-key (kbd "M-X") 'smex-major-mode-commands)
  (setq smex-save-file "~/.emacs.d/smex-items"))         ; don't save state to "~/.smex-items"
;;---------------------------------------------

7.23 which-key

After 1 second of an unfinished key-press, show the documentation of the sub-keys available in the key sequence. See source page for screenshots.

(when (require 'which-key nil 'noerror)
  (which-key-mode))

7.24 Moving lines or regions up/down

This (EW) allows you to easily drag lines or regions around in the buffer. Alternative code from emacs-rocks.

;;Move lines up/down---------------------------
;; If move-text not installed, then define some of it:
(when (not (require 'move-text nil 'noerror))
  (defun move-text-down ()
    (interactive)
    (let ((col (current-column)))
      (save-excursion
        (forward-line)
        (transpose-lines 1))
      (forward-line)
      (move-to-column col)))

  (defun move-text-up ()
    (interactive)
    (let ((col (current-column)))
      (save-excursion
        (forward-line)
        (transpose-lines -1))
      (move-to-column col))))

(global-set-key (kbd "<C-S-down>") 'move-text-down)
(global-set-key (kbd "<C-S-up>") 'move-text-up)
;;---------------------------------------------

7.25 save history

A must for sane behavior of emacs. Thank you emacs-fu.

;;Save History--------------------------------
;;Save mode-line history between sessions. Very good!
(setq savehist-additional-variables    ;; Also save ...
  '(search-ring regexp-search-ring)    ;; ... searches
  savehist-file "~/.emacs.d/savehist") ;; keep home clean
(savehist-mode t)                      ;; do this before evaluation
;;--------------------------------------------

7.26 save places (position/point)

Save the position I was in each file, i.e. no scrolling down to paragraph N or function foo when I reopen my files.

;; Save point position between sessions
(require 'saveplace)
(setq-default save-place t)
(setq save-place-file (expand-file-name "save-point-places" user-emacs-directory))

7.27 rectangular highlighting

Most excellent! Sure you could use the C-x r followed by k (kill) or y (yank) or M-w (copy, since Emacs 24.3) keys to do the same, which also works in tty/terminal, but this is easier, and you see the result "live".

;;Rectangular markings-----------------------
;;COOL! C-RET gives rectangular marking for copy/paste, extremely useful
;;for tables. NOTE, second line needed for rectangle, but also gives
;; (transient-mark-mode t) = visualize C-SPC-marking (i.e. highlight)
(setq cua-enable-cua-keys nil) ;;only for rectangle, don't use C-x/c/v for copy/paste
(cua-mode t)                   ;;gives rectangle + same as "(pc-selection-mode)" (=shift+arrow highlights)
;;--------------------------------------------

7.28 awesome copy/paste!

This is super-amazing hack by emacs-fu.

;;Awesome copy/paste!----------------------
;;My most used hack! If nothing is marked/highlighted, and you copy or cut
;;(C-w or M-w) then use column 1 to end. No need to "C-a C-k" or "C-a C-w" etc.
(defadvice kill-ring-save (before slick-copy activate compile) "When called
  interactively with no active region, copy a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (message "Copied line")
     (list (line-beginning-position)
           (line-beginning-position 2)))))

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

7.29 parenthesis matching

Another must have for sanity reasons.

;;Parantes-matchning--------------------------
;;Match parenthesis through highlighting rather than retarded jumps. Good!
(when (fboundp 'show-paren-mode)
  (show-paren-mode t)
  (setq show-paren-style 'parenthesis))
;;--------------------------------------------

7.30 volatile-highlight

Highlight the latest changes in the buffer (like text inserted from: yank, undo, etc.) until the next command is run. Nice, since it lets me see exactly what was changed. Get it here.

(when (require 'volatile-highlights nil 'noerror)
  (volatile-highlights-mode t))

7.31 browse-Kill-Ring

Requires "browse-kill-ring.el" which is a part of emacs-goodies-el.deb on Debian. It's one of those esential packages, that everyone should use.

;;Browse-Kill-Ring----------------------------
;;this makes M-y activate the kill-ring IF the previous command
;;was not a yank. (C-y (or C-v in my case))
(when (require 'browse-kill-ring nil 'noerror)
  (browse-kill-ring-default-keybindings)
  (setq browse-kill-ring-quit-action 'save-and-restore))
;;--------------------------------------------

7.32 narrow to region

Lets you reduce a buffer to show only what is currently needed for editing purpose. Combined with indirect buffers it lets you use several different modes (one for each panel) all operating on the same buffer. Useful for:

  • Writing an email, with some code in it. E.g. C++.
  • Editing HTML, with embedded CSS and/or javascript.

    Split frame in several panels. Select region, run narrow-to-region. This narrows in all panels, which is not what we want (mode-line will say "Narrow"). Thus we use "indirect buffers".

    "An indirect buffer shares the text of some other buffer, which is called the base buffer of the indirect buffer. In some ways it is a buffer analogue of a symbolic link between files."

    Given a file, split the buffer into as many panels as wanted. Run clone-indirect-buffer on each panel, then narrow-to-region again, and each panel can have its own major mode.

Table 21: Narrow to region keys
Key Command
C-x n n narrow to region
C-x n p narrow to page
C-x n s narrow to subtree (for org-mode)
C-x n w widen (i.e. un-narrow)
;;C-x n n disabled by default:
(put 'narrow-to-region 'disabled nil)
(put 'narrow-to-defun  'disabled nil)
(put 'narrow-to-page   'disabled nil)
;; open an indirect buffer, and narow to region
(defun narrow-to-region-indirect (start end)
  "Restrict editing in this buffer to the current region, indirectly."
  (interactive "r")
  (deactivate-mark)
  (let ((buf (clone-indirect-buffer nil nil)))
    (with-current-buffer buf
      (narrow-to-region start end))
      (switch-to-buffer buf)))

Alternative code: http://paste.lisp.org/display/135818

7.33 thin marker

;; NOTE! This causes PDF's to flicker, when viewing them in Emacs.
;;
;;Modifiera Markören--------------------------
;;Normal mode:              Cursor is a yellow vertical bar
;;Overwrite mode (ins-key): Cursor is a red block
;;Read-only mode:           Cursor is gray vertical bar
;; http://www.emacswiki.org/emacs/ChangingCursorDynamically
(defun djcb-set-cursor-according-to-mode ()
  "change cursor color and type according to some minor modes."
  (cond
    (buffer-read-only
      (set-cursor-color "gray")
      (setq cursor-type 'hbar))
    ;; valid values are t, nil, box, hollow, bar, (bar . WIDTH), hbar,
    ;; (hbar. HEIGHT); see the docs for set-cursor-type
    (overwrite-mode
      (set-cursor-color "red")
      (setq cursor-type 'box))
    (t
      (set-cursor-color "yellow")
      (setq cursor-type 'bar))))

;;TODO: only activate this setup if not in doc-view-mode:
(add-hook 'post-command-hook 'djcb-set-cursor-according-to-mode)

;; (add-hook 'post-command-hook
;;           (lambda () (interactive)
;;             (unless (member
;;                      major-mode '(pdf-docs doc-view-mode)
;;                      (djcb-set-cursor-according-to-mode)))))
;;--------------------------------------------

7.34 web browser

Every fan of Emacs should use Conkeror. No exceptions.

;;--------------------------------------------
;;Use the awesome conkeror to open url's
(setq browse-url-browser-function (quote browse-url-generic))
(setq browse-url-generic-program "conkeror")
;;--------------------------------------------

7.35 word lookup

Testing this at the moment.

(defun lookup-word-definition ()
  "Look up the current word's definition in a browser.
If a region is active (a phrase), lookup that phrase."
  (interactive)
  (let (myWord myUrl)
    (setq myWord
          (if (region-active-p)
              (buffer-substring-no-properties (region-beginning) (region-end))
            (thing-at-point 'symbol)))

    (setq myWord (replace-regexp-in-string " " "%20" myWord))
    (setq myUrl (concat "http://www.answers.com/main/ntquery?s=" myWord))

    (browse-url myUrl)
    ;; (w3m-browse-url myUrl) ;; if you want to browse using w3m
    ))

(global-set-key (kbd "<f6>") 'lookup-word-definition)

7.36 scroll softly

  ;;Scroll--------------------------------------
  ;;Soft scroll, no spastic jumps
  (setq scroll-margin 0                ;;start scrolling when marker at top/bottom
        scroll-conservatively 100000   ;;marker distance from center (don't jump to center)
;        scroll-up-aggressively 0     ; doesn't work in 24.4 todo xxx yyy C-h n scroll-up-line
;        scroll-down-aggressively 0
        scroll-preserve-screen-position 1) ;;try to keep screen position when PgDn/PgUp
  ;;--------------------------------------------

7.37 scroll up/down (S-up/down) keep cursor

Behave like the terminal, S+Up/Down, scrolls up but keeps the cursor (vertically) centered on the screen. (keybinding is overwritten in org-mode)

Note: this also disables highlighting/marking with shift. Use C-SPC instead, there are not enough keys for emacs to waste S-Arrow on.

;;---------------------------------------------
(defun scroll-down-keep-cursor ()
  ;; Scroll the text one line down while keeping the cursor
  ;; at the same position relative the window frame
  (interactive)
  (scroll-down 1)  ; move window
  (next-line 1))   ; move cursor back, to keep it on the same line

(defun scroll-up-keep-cursor ()
   ;; Scroll the text one line up while keeping the cursor
   (interactive)
   (scroll-up 1)
   (previous-line 1))

;;Bind the functions to the /-key and the *-key (on the numeric keypad) with:
;;(global-set-key [kp-divide] 'scroll-down-keep-cursor)
;;(global-set-key [kp-multiply] 'scroll-up-keep-cursor)

(global-set-key [S-up]   'scroll-down-keep-cursor)
(global-set-key [S-down] 'scroll-up-keep-cursor)
;;---------------------------------------------

7.38 shell-term

M-x shell, starts a buffer that is like a normal emacs buffer, but you can type shell commands in it. It does not play nice with top, etc.

For a "real" terminal buffer use ansi-term, or multi-term.

;;When compiling from shell, display error result as in compilation
;;buffer, with links to errors.
(add-hook 'shell-mode-hook 'compilation-shell-minor-mode)

7.39 auto-insert-mode

For automatically inserting useful stuff into new *.tex, *.cpp, *.gnu files. Put skeleton files in ~/.emacs.d/auto-insert/ directory.

;;Auto-insert-mode---------------------------
;;(auto-insert-mode t)
(require 'autoinsert)
(auto-insert-mode)                                     ;; Adds hook to find-files-hook
(setq auto-insert-directory "~/.emacs.d/auto-insert/") ;; Or use custom, *NOTE* Trailing slash important
;;(setq auto-insert-query nil)                         ;; If you don't want to be prompted before insertion
(define-auto-insert "\.tex" "latexmall.tex")
(define-auto-insert "\.cpp" "cppmall.cpp")
;;--------------------------------------------

7.40 backups

Backups are mostly just annoying, but will save your life one day. Thus I want all of them in the same folder.

There are two different mechanisms. First is auto-save to save unsaved changes to file "filename" every 300 characters, to "#filename#" in the same folder. It is removed when you actually save the file.

Second is to make backups files to specific backup directory, and keep several versions. I don't like the "file~" method as it clutters up, instead stick them all in a common folder.

;;Backups-------------------------------------
(defconst my-backup-dir
  (expand-file-name (concat user-emacs-directory "backups")))

(setq make-backup-files t ;; make backup first time a file is saved
      version-control t   ;; number and keep versions of backups
      backup-by-copying t ;; and copy (don't clobber symlinks) them to...
      backup-directory-alist `(("." . ,my-backup-dir)) ;; ...here
      kept-new-versions 2
      kept-old-versions 5
      delete-old-versions t ;; don't ask about deleting old versions
      ;;vc-make-backup-files t ;; even backup files under version control (git/svn/etc.)
      ;;make-backup-files nil      ;;No annoying "~file.txt"
      ;;auto-save-default nil      ;;no auto saves to #file#
      ;;auto-save-interval 300     ;; Auto save "file" to "#file#" every 300 (default)
      )

;; if no backup directory exists, then create it:
(if (not (file-exists-p my-backup-dir))
    (mkdir my-backup-dir t))
;;--------------------------------------------

7.41 Dictionary (dict)

Most useful if one has the dict server installed, together with some dictionaries, like Webster, WordNet, and the like.

;;Dictionary (dict)---------------------------
;;(when (require 'dictem nil 'noerror)
(when (locate-library "dictem")
  (autoload 'dictem-run-define "dictem" "define word at point" t)

  ;; ;; Code necessary to obtain database and strategy list from DICT
  ;; ;; server. As of version 0.90, dictem runs this function from
  ;; ;; dictem-select-database and dictem-select-strategy if an
  ;; ;; initialization was not completed or failed previously, that is
  ;; ;; running dictem-initialize is optional
  ;; (dictem-initialize)
  ;; ;; Assigning hot keys for accessing DICT server

  ;; ;; SEARCH = MATCH + DEFINE
  ;; ;; Ask for word, database and search strategy
  ;; ;; and show definitions found
  ;; (global-set-key "\C-cs" 'dictem-run-search)

  ;; ;; MATCH
  ;; ;; Ask for word, database and search strategy
  ;; ;; and show matches found
  ;; (global-set-key "\C-cm" 'dictem-run-match)

  ;; DEFINE
  ;; Ask for word and database name
  ;; and show definitions found
  (global-set-key "\C-cd" 'dictem-run-define)

  ;;Hyperlinks:
  ;;...........
  ;; For creating hyperlinks on database names
  ;; and found matches.
  ;; Click on them with mouse-2
  (add-hook 'dictem-postprocess-match-hook
            'dictem-postprocess-match)

  ;; For highlighting the separator between the definitions found.
  ;; This also creates hyperlink on database names.
  (add-hook 'dictem-postprocess-definition-hook
            'dictem-postprocess-definition-separator)

  ;; For creating hyperlinks in dictem buffer
  ;; that contains definitions.
  (add-hook 'dictem-postprocess-definition-hook
            'dictem-postprocess-definition-hyperlinks)

  ;; For creating hyperlinks in dictem buffer
  ;; that contains information about a database.
  (add-hook 'dictem-postprocess-show-info-hook
            'dictem-postprocess-definition-hyperlinks)
  )
;;--------------------------------------------

7.42 Time-stamp files with "Time-stamp: <>" in header

;;Time-stamp-----------------------------------
;; when there is a "Time-stamp: <>" in the first 10 lines of the file,
;; emacs will write time-stamp information there when saving the file.
(setq time-stamp-active t          ; do enable time-stamps
      time-stamp-line-limit 10     ; check first 10 buffer lines for Time-stamp: <>
      time-stamp-format "Last changed %04y-%02m-%02d %02H:%02M:%02S by %L, %u") ; date format
(add-hook 'write-file-hooks 'time-stamp) ; update when saving
;;--------------------------------------------

7.43 Printing to ps-files

Don't use M-x print-buffer. Rather, use M-x ps-print-buffer or M-x ps-print-region

;;Printing --------------------------------
;; 2 column landscape size 7 prints column 0-78, lines 1 to 70
(setq ps-paper-type 'a4
      ps-font-size 7.0
      ps-print-header nil
      ps-print-color-p t
      ps-landscape-mode nil    ; for two pages per page: t
      ps-number-of-columns 1)  ; for two pages per page: 2
;;-----------------------------------------

7.44 Tramp

Tramp is used to access files remotely on another computer, and edit them in your current local emacs session. Very handy.

Use C-x C-f to find files over ssh.

  • Normally: C-x C-f /path/to/file
  • Through ssh: C-x C-f /ssh:username@myhost.univ:/path/to/file
  • Using sudo: C-x C-f /su::/etc/hosts

/sudo:: is an alias for /sudo:localhost: which is an alias for /sudo:root@localhost:

Since I'm using zsh with some fancy propt stuff, it will hang tramp, so I reset the tramp-shell-prompt-pattern to deal with the [] and such. Works for the zsh promp I'm using now.

Alternativley one could do:

(eval-after-load 'tramp '(setenv "SHELL" "/bin/bash"))

but this changes the SHELL for the remainder of the emacs session.

What I actually use looks like:

;;Tramp---------------------------------------
;;Open files remotley through ssh; or open in su(do).
;;(eval-after-load "tramp"                     ;;run once we actually use tramp
(when (require 'tramp nil 'noerror)            ;;run if tramp exists && not loaded yet.
  (setq tramp-shell-prompt-pattern             ;;to work with zsh prompt
        "^[^$>\n]*[#$%>] *\\(\[[0-9;]*[a-zA-Z] *\\)*")
  (setq tramp-default-method "sshx"))          ;;faster, as is "scp"
;;--------------------------------------------

7.45 Ask to open as root if I lack permission to edit

Very useful. If I try to open a file I don't have write permissions to, ask if I want to open it as root (using tramp). source

Note: if you're experiencing problems using this (like tramp hanging), check that you can open them "manually" in the first place, C-x C-f /sudo::/path/to/file. Check the tramp troubleshooting section at emacs wiki.

;;Open as root---------------------------------
;;Ask if I want to open file as root (and use tramp-sudo to give
;;permission)
(defun th-rename-tramp-buffer ()
  (when (file-remote-p (buffer-file-name))
    (rename-buffer
     (format "%s:%s"
             (file-remote-p (buffer-file-name) 'method)
             (buffer-name)))))

(add-hook 'find-file-hook
          'th-rename-tramp-buffer)

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

(defun th-find-file-sudo (file)
  "Opens FILE with root privileges."
  (interactive "F")
  (set-buffer (find-file (concat "/sudo::" file))))
;;---------------------------------------------

8 MARKDOWN MODE (GIT)

Markdown mode from (git) for typsetting git comments for issues and pull requests. This cheat sheet is a good place to start with markdown, and github flavored markdown (gfm), which is what I use.

(autoload 'gfm-mode "markdown-mode"
  "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.text\\'" . gfm-mode))
(add-to-list 'auto-mode-alist '("\\.markdown\\'" . gfm-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . gfm-mode))

;; ;; I think with gfm-mode instead of markdown-mode, I don't need this
;; (add-hook 'markdown-mode-hook '(lambda ()
;;                                         ;(set-fill-column 999999)
;;                                  (auto-fill-mode -1)))

9 BBCODE MODE

For forums. Available on github.

Table 22: bbcode keys
Key Action
C-c C-t c code
C-c C-t b bold
C-c C-t i italic
C-c C-t u undelined
C-c C-t q quote
C-c C-t l url
;;BBCode mode----------------------------------
;; TODO: not sure what is the best way to load this mode
(require 'bbcode-mode)
;; (autoload 'bbcode-mode "bbcode-mode" "For BBcode on forums" t)
;; (add-to-list 'auto-mode-alist '("\\.bbcode$" . bbcode-mode))

(add-hook 'bbcode-mode-hook
          (lambda ()
            ;;(set-fill-column 120)
            (auto-fill-mode -1)))
;;---------------------------------------------

10 GNUPLOT MODE

Gnuplot-mode is now available in a much improved version , using the compilation buffer for compilation-error handling, easy keybinding, and better syntax highlighting. I keep a copy in my git.

Also, rainbow-mode is nice to give color to all color strings like "#rrggbb".

Key command
C-c C-c compile buffer
C-c C-r compile-run region
C-c C-b compile-run buffer
;;============================================
;;              GNUPLOT-MODE
;;============================================
(autoload 'gnuplot-mode "gnuplot-mode" "gnuplot major mode" t)

;; Automatically load gnuplot mode for all .gp & .gnu extension
(setq auto-mode-alist (append '(("\\.gp$" . gnuplot-mode)) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.gnu$" . gnuplot-mode)) auto-mode-alist))

;; color background in any color string: #RRGGBB with relevant color
(autoload 'rainbow-mode "rainbow-mode" "rainblow-mode." t)
(add-hook 'gnuplot-mode-hook 'rainbow-mode)
;;============================================

11 GEDCOM MODE

Standard system for geneaology. Used in C-programs (ncurses based) LifeLine, and can be imported/exported in python GTK-program Gramps.

#+begin_src emacs-lisp :tangle .emacs (autoload 'gedcom-mode "gedcom") (setq auto-mode-alist (cons '("\\.ged\(" . gedcom-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("lltmp[0-9a-zA-Z.]+\)" . gedcom-mode) auto-mode-alist)) #+end_src emacs-lisp :tangle .emacs

12 POV-RAY-MODE

Pov-ray is a ray tracer renderer written in C++ using only text files. Following is a quick review of useful keys.

Table 23: Povray mode keys
Key Description
C-c C-c c r render, default quality
C-c C-c c 1 render, test quality
C-c C-c c 5 render, highest quality
C-c C-c c v view, internal viewer
C-c C-c c e view, external viewer
C-c C-c C-h look up word under cursor
C-c C-c c i open include file under cursor

TODO: C-c C-c v + "y".

;;============================================
;;             POV-RAY-MODE
;;============================================
;; https://gitorious.org/pov-mode/pov-mode/trees/master

(autoload 'pov-mode "pov-mode" "PoVray scene file mode" t)
(add-to-list 'auto-mode-alist '("\\.pov\\'" . pov-mode))
(add-to-list 'auto-mode-alist '("\\.inc\\'" . pov-mode))

;; TODO
;;(set pov-documentation-directory "")
;;(set pov-include-dir "")

(defun set-my-pov-mode-hotkeys  ()
  "Sets some convenient keyboard shortcuts for pov-mode."
  (interactive)
  (define-key pov-mode-map (kbd "<f9>") 'pov-menu-render-test))

(add-hook 'pov-mode-hook 'set-my-pov-mode-hotkeys)

;;============================================

13 ORG MODE

Org mode (overview), possibly the easiest, most useful, most awesome thing in Emacs. Perfect for creating list or documents with hierarchy.

Emacs org-mode examples and cookbook

13.1 Keys

Org mode: greatest invention since the wheel!

Table 24: General keys
Key binding function
C-c C-t set TODO/DONE on line.
M-RET new section (same level)
M-Shift-RET new section (same level) + "TODO"
Shift-TAB toggle show-mode: overview, contents, showall
M-S-up/down move entire tree one level up/down
C-c C-o open-at-point (expandera)
C-c C-e export org-file
Table 25: Calender:
Key binding function
C-c . Show calender
S-up/dn/l/r Move one day up/dn/r/l in calender view
> / < Move one month
10 Sets the day to 10th of default month
Tue Sets the day to Tuesday fo default week
+1d +1w +1y Add a day, a week or a year to date.
Table 26: Tables: (replaces all spreadsheat programs)
Key binding function
RET Realign and move to one row down
TAB Realign and move to one column right
S-TAB Realign and move to one column left
C-c C-c Realign table (don't move cursor)
M-up/down Move row
M-right/left Move column
M-S-left Kill current column
M-S-right Insert column (to the left)
M-S-up Kill current row
M-S-down Insert row (above current)
C-| Convert region into table.
C-- insert hline below current position
C-RET insert hline below current position, and move to it
C-c ? Show coordinate/ref for current cell
C-c } Show position/coordinates in table (eg. "A12")
C-c C-c (Re)Apply formula. (if on a [Formula] or TBLFM field)
C-u C-c = Insert field formula in cell
C-c = Insert field formula in column
C-c + Sum numbers in column, show in echo area
C-c ` Edit current field (cell) in separate buffer

Some more functions of tables

  • C-c ^ org-table-sort-lines

    Sort the table lines in the region based on current column, and range of lines between the nearest horizontal separator lines, or the entire table. If point is before the first column, you will be prompted for the sorting column. If there is an active region, the mark specifies the first line and the sorting column, while point should be in the last line to be included into the sorting. The command prompts for the sorting type (alphabetically, numerically, or by time). When called with a prefix argument, alphabetic sorting will be case-sensitive.

  • M-x org-table-import

    Import table from (TAB or SPC) seperated file. Prefix arg specifies seperator.

  • M-x org-table-export

    Export table to TAB seperated file. Might want to specify TABLE_EXPORT_FILE and TABLE_EXPORT_FORMAT

13.2 General, keys, etc.

;;General------------------------------------
(require 'org-install)
;; The following lines are always needed.  Choose your own keys.
(add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
(define-key global-map "\C-cl" 'org-store-link)
(define-key global-map "\C-ca" 'org-agenda)
(define-key global-map "\C-cb" 'org-iswitchb)

(setq org-log-done t)

;; replace the "..." with "…" for collapsed org-mode content
(setq org-ellipsis "…")

;;RET follows hyperlinks in org-mode:
(setq org-return-follows-link t)

;;Use abbrev-minor-mode with org-mode: (I have global abbrev mode now)
;;(add-hook 'org-mode-hook (lambda () (abbrev-mode 1)))

;;Can be set per file basis with: #+STARTUP: noalign (or align). Same
;;as doing C-c C-c in a table.
(setq org-startup-align-all-tables t)
;;---------------------------------------------

13.3 Export to LaTeX

Here I have some tweaks for when exporting org-mode files to LaTeX:

  • When exporting org files with code-snippets in them to LaTeX, have the resulting LaTeX file use the LaTeX listings package for those code-blocks.
  • I also add my own export class for Org-mode to Latex, that doesn't add as many redundant packages. use by putting this on top of the org-mode file:
    #+LATEX_CLASS: myclass
    #+LaTeX_CLASS_OPTIONS: [a4paper]
    
;; Make markdown export is always available
(eval-after-load "org"
  '(require 'ox-md nil t))

;;Org-export to LaTeX--------------------------
(eval-after-load "ox-latex"
  '(progn
     (message "Now I'm loading org-latex export stuff")
     ;; requite org-latex so that the following variables are defined
     ;;(require 'org-latex) ;; Maybe this isn't needed anymore in 8.0? 2015-10-29

     ;; use with: #+LATEX_CLASS: myclass
     ;;#+LaTeX_CLASS_OPTIONS: [a4paper,twoside,twocolumn]
     (add-to-list 'org-latex-classes
                  '("myclass" "\\documentclass[11pt,a4paper]{article}
                     [NO-DEFAULT-PACKAGES]
                     [NO-PACKAGES]"
                    ("\\usepackage[utf8]{inputenc}")
                    ("\\usepackage[T1]{fontenc}")
                    ("\\usepackage{graphicx}")
                    ("\\usepackage{longtable}")
                    ("\\usepackage{amssymb}")
                    ("\\usepackage[colorlinks=true,urlcolor=SteelBlue4,linkcolor=Firebrick4]{hyperref}")
                    ("\\usepackage[hyperref,x11names]{xcolor}")
                    ("\\section{%s}" . "\\section*{%s}")
                    ("\\subsection{%s}" . "\\subsection*{%s}")
                    ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                    ("\\paragraph{%s}" . "\\paragraph*{%s}")
                    ("\\subparagraph{%s}" . "\\subparagraph*{%s}"
                     )))

     ;; tell org to use listings
     (setq org-export-latex-listings t)

     ;; you must include the listings package
     ;;(add-to-list 'org-export-latex-packages-alist '("" "listings")) ;; don't work in Org 8?

     ;; if you want colored source code then you need to include the color package
     ;;(add-to-list 'org-export-latex-packages-alist '("" "color"))
  ))
;;---------------------------------------------

13.4 Ispell in Org-mode

Fix orgmode in ispell mode. From: http://endlessparentheses.com/ispell-and-org-mode.html?source=rss

(defun endless/org-ispell ()
  "Configure `ispell-skip-region-alist' for `org-mode'."
  (make-local-variable 'ispell-skip-region-alist)
  (add-to-list 'ispell-skip-region-alist '(org-property-drawer-re))
  (add-to-list 'ispell-skip-region-alist '("~" "~"))
  (add-to-list 'ispell-skip-region-alist '("=" "="))
  (add-to-list 'ispell-skip-region-alist '("^#\\+BEGIN_SRC" . "^#\\+END_SRC")))
(add-hook 'org-mode-hook #'endless/org-ispell)

13.5 a useful template

From pragmaticemacs I found this little code snippet. Highlight text, then M-x org-begin-template, and select what you want.

(defun org-begin-template ()
  "Make a template at point."
  (interactive)
  (if (org-at-table-p)
      (call-interactively 'org-table-rotate-recalc-marks)
    (let* ((choices '(("s" . "SRC")
                      ("e" . "EXAMPLE")
                      ("q" . "QUOTE")
                      ("v" . "VERSE")
                      ("c" . "CENTER")
                      ("l" . "LaTeX")
                      ("h" . "HTML")
                      ("a" . "ASCII")))
           (key
            (key-description
             (vector
              (read-key
               (concat (propertize "Template type: " 'face 'minibuffer-prompt)
                       (mapconcat (lambda (choice)
                                    (concat (propertize (car choice) 'face 'font-lock-type-face)
                                            ": "
                                            (cdr choice)))
                                  choices
                                  ", ")))))))
      (let ((result (assoc key choices)))
        (when result
          (let ((choice (cdr result)))
            (cond
             ((region-active-p)
              (let ((start (region-beginning))
                    (end (region-end)))
                (goto-char end)
                (insert "#+END_" choice "\n")
                (goto-char start)
                (insert "#+BEGIN_" choice "\n")))
             (t
              (insert "#+BEGIN_" choice "\n")
              (save-excursion (insert "#+END_" choice))))))))))

13.6 orgtbl-mode

orgtbl-mode allows you to use the power of org-mode tables in non-org-mode documents, where you would have the org-table as a comment in that mode's language.

M-x orgtbl-insert-radio-table inserts all you need by querying use in mini-buffer.

;;For smart org-tables in LaTeX, emails, and other modes.
;;Use M-x orgtbl-insert-radio-table
(add-hook 'LaTeX-mode-hook 'turn-on-orgtbl)
(add-hook 'message-mode-hook 'turn-on-orgtbl)
(add-hook 'html-mode-hook 'turn-on-orgtbl)
\begin{tabular}{lrrr}
Month & \multicolumn{1}{c}{Days} & Nr.\ sold & per day\\
% BEGIN RECEIVE ORGTBL salesfigures
% END RECEIVE ORGTBL salesfigures
\end{tabular}
%
\begin{comment}
#+ORGTBL: SEND salesfigures orgtbl-to-latex :splice t :skip 2
| Month | Days | Nr sold | per day |
|-------+------+---------+---------|
| Jan   |   23 |      55 |     2.4 |
| Feb   |   21 |      16 |     0.8 |
| March |   22 |     278 |    12.6 |
#+TBLFM: $4=$3/$2;%.1f
% $ (optional) to make font lock happy if unbalanced in TBLFM.
\end{comment}
  • :splice nil/t

    When set to t, return only table body lines, don't wrap them into a tabular environment. Default is nil.

  • :fmt fmt

    A format to be used to wrap each field, it should contain %s for the original field value. For example, to wrap each field value in dollars, you could use :fmt "\(%s\)".

13.7 org-babel

Set up which languages should be executable through org-babel-mode. Ditaa is a nice way to convert ascii-art-styled figures into typeset png files, excellent for including in an org file for html or LaTeX export.

;;Org-Babel -----------------------------------
;;Requires org-mode 7.x or later:
(eval-after-load "org"
  '(org-babel-do-load-languages
    'org-babel-load-languages
    '((sh . t)
      (python . t)
      (emacs-lisp . t)
      (ditaa . t)
      )))
;; specify path to ditaa
(setq org-ditaa-jar-path "~/ditaa0_9/ditaa0_9.jar")

;; fontlock src blocks even when I'm outsied them
(setq org-src-fontify-natively t)

;; no extra indentation for contents in src code blocks
(setq org-edit-src-content-indentation 0)
;;---------------------------------------------

13.8 org agenda

http://orgmode.org/manual/Agenda-Views.html http://members.optusnet.com.au/~charles57/GTD/org_dates/ http://www.gnu.org/software/emacs/manual/html_node/org/Agenda-commands.html

key  
C-c a t list of TODO items (t marks as DONE), prefix with C-u [N-days]
C-c a a agenda of scheduled items (l log-mode on/off)
   
n / p next / previous line
f / b move agenda forward / backwards in time
j jump to date
. today
L recenter on item in other buffer
TAB also move to other buffer
F Follow mode on/off: Like "L" for every n & p
v d/w/m/y view day / week / month / year
C-x C-s save all org-buffers files
;; Setting org-agenda-start-on-weekday to nil means that the agenda
;; view start on current day

(custom-set-variables
 '(org-agenda-ndays 7)
 '(org-agenda-start-on-weekday nil))

;; Do C-c C-c on any item to add tags
(setq org-tag-alist '((:startgroup . nil)  ;; start mutualy exclusive list
                      ("@THEP" . ?t)
                      ("@HEMMA" . ?h)
                      (:endgroup . nil)    ;; end mutually exclusive
                      ("VIKTIGT" . ?v)
                      ("DATOR" . ?d)))
    ;;C-c a t compiles list of all open TODO items.
    (setq org-agenda-files (list "~/.emacs.d/org"
                                 ;;"~/.emacs.d/agenda"
  ))

;;Calendar starts with Monday
(setq calendar-week-start-day 1)

;; highlight the line I'm on
(add-hook 'org-agenda-finalize-hook (lambda () (hl-line-mode)))

13.9 org-contacts

For managing contacts (phone, email, birthdays, etc.) Note: you must run 64 bit emacs for dates prior to 1970, or else it will fail.

;;org-contacts --------------------------------
(eval-after-load "org"
  '(progn
     (require 'org-contacts)
     (setq org-contacts-files '("~/dokument/kontakter.org"))))
;;---------------------------------------------

13.10 org-capture

The following customization sets a default target1 file for notes, and defines a global key2 for capturing new stuff.

C-c c
Start a capture process. You will be placed into a narrowed indirect buffer to edit the item.
C-c C-c
Once you are done entering information into the capture buffer, C-c C-c will return you to the window configuration before the capture process, so that you can resume your work without further distraction.
C-c C-w
Finalize by moving the entry to a refile location (see Refiling notes).
C-c C-k
Abort the capture process and return to the previous state.

In the configuration below I specify which files to store what in when commiting a note (C-c C-c). See Manual: Template-expansion for syntax and here for an example.

Here is story of a person describing how his usage of capture has evolved over time. Ends with capture creating a separate file for each day.

(setq org-default-notes-file "~/.emacs.d/org/notes.org")
(define-key global-map (kbd "\C-c c") 'org-capture)

;; set up different templates
(setq org-capture-templates
      '(;(<key> <description> entry (file+headline <path> <headline> <template-string>))
        ("s" "schemalägg" entry (file+headline "~/.emacs.d/org/agenda.org" "Schema")
         "** %^{description} \n   SCHEDULED: %^t %?\n" :empty-lines 1)
        ("a" "agenda" entry (file+headline "~/.emacs.d/org/agenda.org" "Händelser")
         "** %^{description} %u %?\n" :empty-lines 1)
        ("t" "todo/Att göra" entry (file "~/.emacs.d/org/todo.org")
         "* TODO %^{Description} %^g %i\n %?" :empty-lines 1)
        ("K" "att köpa" entry (file+headline "~/.emacs.d/org/köp-sälj.org" "ATT KÖPA")
         "** TODO %^{description} \n Skapad: %u\n %?" :empty-lines 1)
        ("S" "att sälja" entry (file+headline "~/.emacs.d/org/köp-sälj.org" "ATT SÄLJA")
         "** TODO %^{description} \n Skapad: %u\n %?" :empty-lines 1)
        ("d" "diary" entry (file+datetree "~/.emacs.d/org/diary.org")
         "* %^{description}  %^g \n %? \n Skapad: %U" :empty-lines 1)
        ))

13.11 org-crypt

Any text under a section tagged with :crypt: will be encrypted when saved.

Preventing tag inheritance stops you having encrypted text inside encrypted text.

To decrypt text at point: M-x org-decrypt-entry

;;org-crypt -----------------------------------
(require 'org-crypt)
(org-crypt-use-before-save-magic)
(setq org-tags-exclude-from-inheritance (quote ("crypt")))
;; GPG key to use for encryption
;; Either the Key ID or set to nil to use symmetric encryption.
(setq org-crypt-key nil)
;;---------------------------------------------

14 TEXT MODE

14.1 Line breaks / long lines

Linebreaks in emacs can either be:

Soft
Use visual-lines-mode, to behave just like a word processor: Long lines are wrapped arond automatically at the edge of the current emacs window frame, and line is readjusted, but these "virtual" line breaks are not saved to file, nor do they mess up the line number counter.

(Starting from Emacs 23 line-move-visual is t by default, which makes movement of point (C-a, C-e, etc.) by visual lines displayed on screen rather than logical/real buffer lines, as it should be).

Hard
Use auto-fill-mode, to insert RET (a hard/real line break) after fill-column (C-x f) value is passed. Evaluated when SPC is pressed. One can always re-process the current paragraph with M-q.

To undo the hard line breaks: C-x f 99999 RET, M-q.

(defvar soft-line-breaks-p nil   ; nil or t
  "Use hard or soft line breaks for long lines")

;; M-q doesn't insert double space after period.
(setq sentence-end-double-space nil)

(if soft-line-breaks-p
    (add-hook 'text-mode-hook 'turn-on-visual-line-mode)
  (add-hook 'text-mode-hook
            '(lambda ()
               (set-fill-column 78)       ; lines are 78 chars long ...
               (auto-fill-mode t))))      ; ...and wrapped around automagically

14.2 Spell check

Several different programs for spellchecking can be used in emacs. Default is ispell, however, aspell is the GNU spell checker (better than ispell, gives more suggestions etc.), and myspell is by they same author who did apsell and pspell. Then there's hunspell which is a (backwards compatible) far better derivative of myspell, now in use by libre/open office, and Mozilla. Unfortunately I have not managed to get hunspell up and running. Yet.

Run M-x ispell-change-dictionary RET SPC to see which are available.

;;Spell check---------------------------
;;Swedish spell check in all i text files (including LaTeX-files).
;;These settings will not affect programming.

(add-hook 'text-mode-hook '(lambda () (flyspell-mode nil)))
;;(add-hook 'text-mode-hook '(lambda () (ispell-change-dictionary "svenska" nil)))

;;don't print words in mini-buffer when scanning, so sloooow
(setq flyspell-issue-message-flag' nil)

;;auto configure language (does not work? Says "??" in mod-line)
;;(require 'auto-dictionary)
;;(add-hook 'flyspell-mode-hook '(lambda () (auto-dictionary-mode 1)))

;;ispell=unix native spell checker, aspell=GNU's ispell, hunspell=OpenOffice & firefox
(setq ispell-program-name "aspell"
  ispell-extra-args '("--sug-mode=normal"))

;;change dictionary: "C-c e" = engelska, "C-c s"=svenska, "C-c w"=turn off flyspell
(add-hook 'text-mode-hook
          '(lambda ()
             (local-set-key (kbd "C-c s 1")
                             (lambda()(interactive)
                               (ispell-change-dictionary "svenska")
                               (flyspell-mode 1)
                               (flyspell-buffer)))
             (local-set-key (kbd "C-c s 2")
                             (lambda()(interactive)
                               (ispell-change-dictionary "american")
                               (flyspell-mode 1)
                               (flyspell-buffer)))
             (local-set-key (kbd "C-c s 3")
                             (lambda()(interactive)
                               (ispell-change-dictionary "british-ize")
                               (flyspell-mode 1)
                               (flyspell-buffer)))
             (local-set-key (kbd "C-c s 4")
                             (lambda()(interactive)
                               (ispell-change-dictionary "british-ise")
                               (flyspell-mode 1)
                               (flyspell-buffer)))
             (local-set-key (kbd "C-c s 0")
                             (lambda()(interactive)
                               (flyspell-mode -1)))
             ))
;;--------------------------------------------

15 LaTeX MODE

AuCTex is a must for Latex. It can be installed through the package manager in your OS (ubuntu/debian: auctex.deb), or through ELPA (internal package system of Emacs).

AuCTeX has tonnes of features, but preview and reftex are modes I find extremely useful. Reftex is amazing, it inserts labels, references, citations, right where you want them, and shows table of contents of sections, and labels.

15.1 Keys for LateX with AuCTeX installed

Table 27: Excluding ReTeX-keys, these are my most used AuCTeX keys (at least the first 5)
Key binding function
C-c C-c compile buffer if any changees, else view
C-c C-r compile region (into region.dvi) / view region
C-c C-s insert section
C-c C-e insert environment
C-u C-c C-e change enclosing environment
C-c ] close environment
C-c ? gives documentation for the symbol at point
   
C-c ~ math mode
C-c C-m macro insert (or C-c RET)
C-c C-w something with overfull boxes
   
C-c C-p C-s preview section
C-c C-q C-s automatic formatting of a section:
Table 28: Keys for RefTeX (note: RefTeX is not on by default in AuCTeX, check config)
Key binding function
C-c = table of contents
C-c ( create label
C-c ) reference label
C-c & try when marker at a ref, label, cite, index
C-c [ search citations, uses file used by \bibliography
   
C-c / insert index
C-c < alternative index, more advanced
C-c \ add word or selection to index phrase file
C-c > display/edit index
Table 29: Preview keys for typesetting equations right in the document (using magic and png?)
Key binding function
C-c C-k kill running preview process
   
C-c C-p C-s preview-section
C-c C-p C-r preview-region
C-c C-p C-b preview-buffer
C-c C-p C-d preview-document
   
C-c C-p C-c C-p preview-clearout-at-point
C-c C-p C-c C-s preview-clearout-section
C-c C-p C-c C-r preview-clearout
C-c C-p C-c C-b preview-clearout-buffer
C-c C-p C-c C-d preview-clearout-document

15.2 Miscellaneous

;; choose one, for what happens with long lines:
;;(add-hook 'LaTeX-mode-hook 'visual-line-mode)
;;(add-hook 'LaTeX-mode-hook 'auto-fill-mode)

(add-hook 'LaTeX-mode-hook
          '(lambda ()
             (ispell-change-dictionary "american" nil)

             ;;Make equations into images & show in emacs:
             (autoload 'latex-math-preview-expression "latex-math-preview" nil t)
             (autoload 'latex-math-preview-save-image-file "latex-math-preview" nil t)
             (autoload 'latex-math-preview-beamer-frame "latex-math-preview" nil t)))

(setq font-latex-fontify-script nil ;;Don't fontify sub/super: _ ^
      TeX-auto-save t               ;;enable parse on save
      TeX-parse-self t              ;;enable parse on load
      TeX-auto-untabify t           ;; remove Tabs at save
      ispell-check-comments nil)    ;;don't spell check comments

;;Auto choose Swedish if usepackage{babel}[swedish]
;;so that:  Shift+2-> '' rather than ", or similar...
(add-hook 'TeX-language-sv-hook
(lambda() (ispell-change-dictionary "svenska")))

15.3 Math $$-matching

;;Math-$$-matchning---------------------------
(setq LaTeX-mode-hook'
      (lambda () (defun TeX-insert-dollar ()
                   "custom redefined insert-dollar"
                   (interactive)
                   (insert "$$")           ;;in LaTeX mode, typing "$" automatically
                   (backward-char 1))))    ;;insert "$$" and move back one char.
;;--------------------------------------------

15.4 RefTeX awesomeness

;;RefTeX--------------------------------------
;;Navigate sections by right mouse button. Similar to as C-c =
(add-hook 'reftex-load-hook 'imenu-add-menubar-index)
(add-hook 'reftex-mode-hook 'imenu-add-menubar-index)

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

(autoload 'reftex-mode    "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" t)

;; To integrate RefTex even closer with AUCTeX.  E.g: when C-c C-s
;; or C-c C-e is called, AUCTex will call RefTeX, which will insert
;; a label automatically instead of having AUCTeX ask you for one;
;; When C-c C-s AUCTeX will update section list in RefTeX; RefTeX
;; will also tell AUCTeX about new label, citation, and index keys,
;; and add them to completions list.
(setq reftex-plug-into-AUCTeX t)

;;Make C-u prefixed commands not re-parse entire doc.
(setq reftex-enable-partial-scans t)

;; ;;Even with partial-scan enables, reftex must make one full scan,
;; ;;this saves the result to a file "*.rel"
;; (setq reftex-save-parse-info t)

;; ;; use separate buffer for selecting each label type
;; (setq reftex-use-multiple-selection-buffers t)
;;--------------------------------------------

16 GUD MODE (gdb debugging)

Awesome debugging power at my fingertips. Run with

M-x gdb

or

gdb --annotate=3 ./yourbinary

See emacswiki

16.1 Main stuff

;;Make up/down behave as in terminal
;;run it like this "M-x gdb",
;;  gdb --annotate=3 ./yourBinary
(add-hook 'gud-mode-hook
          '(lambda ()
             (local-set-key [home] ; move to beginning of line, after prompt
                            'comint-bol)
             (local-set-key [up] ; cycle backward through command history
                            '(lambda () (interactive)
                               (if (comint-after-pmark-p)
                                   (comint-previous-input 1)
                                 (previous-line 1))))
             (local-set-key [down] ; cycle forward through command history
                            '(lambda () (interactive)
                               (if (comint-after-pmark-p)
                                   (comint-next-input 1)
                                 (forward-line 1))))
             )
          (setq gdb-many-windows t))
;;============================================

17 PROGRAMMING-MODE

New major mode in Emacs 24 loaded for all programming modes. Thus stuff that is common for C++, lisp, python, etc. can be specified here.

What about LaTeX? Nope, not a prog-mode derivative.

Here is a guide on how to use emacs for code development, starting with basic introduction to emacs, keys, modes, and useful packages.

17.1 auto-check code syntax

Flycheck is an improved version of the built in flymake-mode. M-x flycheck-info. It relies on extrnal tools, like gcc or cang for C/C++ or pylint for python. (For having the error description in a pop-up window instead of echoed in the mini-buffer, install flycheck-pos-tip.)

After install: M-x flycheck-verify-setup

Table 30: Key-commands, also available through menu: Tools->Syntax-checking
Key  
C-c ! c flycheck-buffer
C-c ! n next error
C-c ! p previous error
C-c ! l list errors
C-c ! C clear errors
C-c ! s select syntax checker
C-c ! f enable on the fly checker
   
;; ;;Check syntax while typing code:
;; (add-hook 'prog-mode-hook #'flycheck-mode)

17.2 TODO auto-complete code

There are two major systems. auto-complete and company. The latter is more maintained, more actively developed, has a better API for developers to hook into it. The former has more supported languages (but that is changing fast), and shows doc-strings by default, but is more difficult to setup, and doesn't work so well.

To get company to use ispell list for auto completion in text mode see this

See third party packages for stuff for company mode to use.

I installed company-auxtex (for LaTeX), company-c-headers (for auto-completion of header #include<> statement)

M-x company-mode - start mode M-x company-complete - start completion manually

M-x customize-variable RET company-backends

After having typed a few letters a list will show up,

  • M-n / M-p move in completion list
  • TAB to complete common part
  • C-h (and F1?) show doc-string (in separate buffer)
  • C-r/s/o search completions
  • C-w shows source, if supported by the backend.
(add-hook 'after-init-hook 'global-company-mode)

(with-eval-after-load 'company
  (company-auctex-init)
  (add-hook 'python-mode 'run-python)
  ;;(add-to-list 'company-backends 'company-c-headers)
  (define-key company-active-map (kbd "M-n") nil)
  (define-key company-active-map (kbd "M-p") nil)
  (define-key company-active-map (kbd "C-n") #'company-select-next)
  (define-key company-active-map (kbd "C-p") #'company-select-previous))

17.3 Spell check comments and strings

;;Spell check---------------------------------
;;Spell check comments and strings
;;Change dictionary: "C-c e" = engelska, "C-c s"=svenska, "C-c w"=turn off flyspell
(add-hook 'prog-mode-hook
            '(lambda ()
               (local-set-key (kbd "C-c s 1")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "svenska")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 2")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "american")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 3")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "british-ize")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 4")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "british-ise")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 0")
                               (lambda()(interactive)
                                 (flyspell-mode -1)))
               ))
;;---------------------------------------------

17.4 code-review-region

Copies code region, inserts file name, and line number, ready to be pasted into an email. Use: M-x code-review-region. src

(defun code-review-region (beg end)
  (interactive "r")
  (let* ((text (chomp (buffer-substring-no-properties beg end)))
         (line-number (line-number-at-pos))
         (file (buffer-file-name))
         (path (replace-regexp-in-string "^.*branches/" ""
                                         (replace-regexp-in-string
                                          "^.*trunk/" "" file))))
     (with-temp-buffer
       (insert text)
       (goto-char (point-min))
       (while (re-search-forward "^" nil t)
         (replace-match "| " nil nil))
       (goto-char (point-min))
       (insert (format "+---[%s:%s]\n" path line-number))
       (goto-char (point-max))
       (insert "\n+---\n")
       (kill-region (point-min) (point-max)))))

17.5 Highlight (too) long lines, and key-words

;;Fontify -------------------------------------
;;Highlight columns longer than 79 lines
(when (> (display-color-cells) 16)         ;if not in CLI
  (add-hook 'prog-mode-hook
            (lambda ()
              (font-lock-add-keywords nil '(("^[^\n]\\{79\\}\\(.*\\)$" 1 font-lock-warning-face t)))
              (font-lock-add-keywords nil '(("\\<\\(FIXA\\|TEST\\|TODO\\|FIXME\\|BUG\\|NOTE\\)"
                                             1 font-lock-warning-face prepend)))
              (font-lock-add-keywords nil '(("\\<\\(__FUNCTION__\\|__PRETTY_FUNCTION__\\|__LINE__\\)"
                                             1 font-lock-preprocessor-face prepend)))
           )))
;;--------------------------------------------

17.6 Auto Kill compile buffer if no errors

This function is global, and not associated with prog-mode at all. Very handy. Kill the compilation buffer if it was successful.

TODO: Working on some kind of matching for a no-error, but warnings in compile. Then I want to keep the buffer, in the background.

;;Kill-compile-buffer-if-success-------------
;;If compilation was successful, kill it.
;;Also works for LaTeX. TODO: keep in background if there are warnings.

;; Note: the M-x grep command will print its result as a Compilation
;; buffer (named *grep*), but we do not want to kill that one.

(defvar current-frame) ;;to avoid Elisp-compiler warning. temp fix.

(defun notify-compilation-result(buffer msg)
  "Close *compilation* buffer if successful, set the focus back
to Emacs frame. Note: *grep* is a compilation buffer, but we want
to keep that if it's successful."
  (if (string= (buffer-name) "*compilation*") ;don't match *grep* buff
      (cond ((string-match "^finished" msg)   ;kill buffer
             ;;(tooltip-show "\n Compilation Successful :-) \n "))
             (kill-buffer-and-window))
            ((string-match "^warnings" msg) ;buffer to background
             ;;(tooltip-show "\n Compilation Warnings :-| \n")
             (delete-windows-on buffer)))
    ;;(tooltip-show "\n Compilation Failed :-( \n ")
    )

  (setq current-frame (car (car (cdr (current-frame-configuration)))))
  (select-frame-set-input-focus current-frame))

(add-to-list 'compilation-finish-functions
             'notify-compilation-result)
;;--------------------------------------------

17.7 compile

From http://endlessparentheses.com/better-compile-command.html

(defun my-compile-please ()
  "Compile without confirmation."
  (interactive)
  ;; Do the command without a prompt.
  (save-window-excursion
    (compile compile-command))
  ;; Create a compile window of the desired width.
  (pop-to-buffer (get-buffer "*compilation*"))
  (enlarge-window
   (- my-compile-window-size (window-width))
   'horizontal))

;; This gives a regular `compile-command' prompt.
(define-key prog-mode-map [C-f9] #'compile)
;; This just compiles immediately.
(define-key prog-mode-map [f9]
  #'my-compile-please)

;; Don't ask me to save _all_ buffers. If there's an error due to me
;; not having saved the file prior to compilation, I'll figure it out
;; on my own:
(setq compilation-ask-about-save nil)

;; Stop on the first error.
(setq compilation-scroll-output 'first-error)

;; Don't stop on info or warnings.
(setq compilation-skip-threshold 2)

18 LISP MODE

18.1 SLIME

18.1.1 Common Lisp SBCL

;;Different paths for sbcl at Home and at Work:
(cond ((file-exists-p "/etc/SuSE-release")
       (message "Slime setting up for Work computer")
       (setq inferior-lisp-program "/home/b2/firstname/usr/bin/sbcl")
       (add-to-list 'load-path "/home/b2/firstname/usr/share/emacs/site-lisp/slime/")
       (setenv "SBCL_HOME" "/home/b2/firstname/usr/lib/sbcl"))
      (t
       (message "Slime setting up for Home computer")
       (setq inferior-lisp-program "/usr/bin/sbcl"
             ;; lisp-indent-function 'common-lisp-indent-function
             common-lisp-hyperspec-root "file:///home/vandelay/usr/share/doc/common-lisp/HyperSpec/")
       (add-to-list 'load-path "/usr/share/emacs/site-lisp/slime/")))

18.1.2 Scheme

Slime can be used with Scheme, both MIT scheme and chicken scheme are supported, however I could only get the latter to work, by following the instructions here.

Currently, I'm not using this, as I've started playing around with common lisp, so I use the "normal" slime.

http://www.wingolog.org/archives/2006/01/02/slime https://github.com/redline6561/dotemacs/commit/78581e7027284605d2aa77ccaf0df1265ccd8db8#L0L65

;;Slime + Chicken:
(cond ((file-exists-p "/etc/SuSE-release")
       (message "loading chicken-slime for work computer")
       (setenv "CHICKEN_DOC_REPOSITORY" "~/usr/local/share/chicken/doc/manual")
       (setq slime-csi-path "~/usr/local/bin/csi")
       (setq inferior-lisp-program "~/usr/local/bin/csi")
       (add-to-list 'load-path "~/usr/local/lib/chicken/6/"))
      (t
       (message "loading chicken-slime for home computer")
       (setenv "CHICKEN_DOC_REPOSITORY" "~/usr/share/chicken/doc/manual")
       (setq inferior-lisp-program "/usr/bin/csi")
       (add-to-list 'load-path "/usr/lib/chicken/6/") ;where eggs are installed
       ))
(autoload 'chicken-slime "chicken-slime" "SWANK hacked for Chicken" t)
(add-hook 'scheme-mode-hook
          (lambda () slime-mode t))

18.2 ParEdit

paredit (ew) is a must if programming any Lisp dialect. It has a threshold, no matter if you're pro or beginner, but it is worth the effort.

This animated example page is nice, although the animations are way too fast.

(autoload 'paredit-mode "paredit"
  "Minor mode for pseudo-structurally editing Lisp code." t)
(add-hook 'emacs-lisp-mode-hook       (lambda () (paredit-mode +1)))
(add-hook 'lisp-mode-hook             (lambda () (paredit-mode +1)))
(add-hook 'lisp-interaction-mode-hook (lambda () (paredit-mode +1)))
(add-hook 'scheme-mode-hook           (lambda () (paredit-mode +1)))
(add-hook 'slime-repl-mode-hook       (lambda () (paredit-mode +1)))
(add-hook 'ielm-mode-hook             (lambda () (paredit-mode +1)))
;; ;;Make eldoc aware of paredit's most used commands
;; (add-hook 'paredit-mode-hook
;;           (lambda) ()
;;           (require 'eldoc)
;;           (eldoc-add-command
;;            'paredit-backward-delete
;;            'paredit-close-round))
(add-hook 'emacs-lisp-mode-hook
          (lambda ()
            (paredit-mode t)

            (turn-on-eldoc-mode)
            (eldoc-add-command
             'paredit-backward-delete
             'paredit-close-round)

            (local-set-key (kbd "RET") 'electrify-return-if-match)
            (eldoc-add-command 'electrify-return-if-match)))

18.3 Eldoc

As you type a function (in emacs-lisp) in current buffer eldoc shows in the minibuffer the documentation for that function, arguments etc.

http://emacswiki.org/emacs/ElDoc

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

;;Also have documentation when writing Scheme-code:
(when (locate-library "scheme-complete")
  (autoload 'scheme-get-current-symbol-info "scheme-complete" nil t)
  (add-hook 'scheme-mode-hook
            (lambda ()
              (make-local-variable 'eldoc-documentation-function)
              (setq eldoc-documentation-function 'scheme-get-current-symbol-info)
              (eldoc-mode))))

18.4 Minibuffer

Have nicer emacs-list support in the "M-x" prompt

;; When evaluating code in Emacs, put eldoc ducumentation in modeline instead!
;; http://endlessparentheses.com/sweet-new-features-in-24-4.html
(add-hook 'eval-expression-minibuffer-setup-hook #'eldoc-mode)
(add-hook 'eval-expression-minibuffer-setup-hook #'paredit-mode)

19 C++ MODE

Most of this is for both C and C++.

This link: https://tuhdo.github.io/c-ide.html#sec-6 collects more than I have time to go through at the moment.

To set up emacs for powerful C/C++ editing, I recommend these two short videos part 1 and part 2.

Also, CppCon 2015: Atila Neves "Emacs as a C++ IDE" presentation introduces some nifty things (which he provides in cmake-ide through MELPA), using the compiler itself to set all local variables, suitable for large projects.

For jumping between definitions there's ETags eller Ctags but I've heard Cscope is best. They all have problems finding the correct place in big projects, with complicated hierarchies.

19.1 One liners

;;Generic -------------------------------------
;; C++-specific. Which extensions should be associated with C++ (rather than C)
(add-to-list 'auto-mode-alist '("\\.h$"  . c++-mode)) ;h-files
(add-to-list 'auto-mode-alist '("\\.icc" . c++-mode)) ;implementation files
(add-to-list 'auto-mode-alist '("\\.tcc" . c++-mode)) ;files with templates

;;Indentation style:
;;(add-hook 'c-mode-common-hook '(lambda () (c-set-style "stroustrup")))
;;(add-hook 'c-mode-common-hook '(lambda () (c-set-style "linux")))
;;---------------------------------------------

19.2 Improve compile

;; Better compile buffer ----------------------
(require 'compile)
(add-hook 'c-mode-common-hook
          (lambda ()
            (setq
             compilation-scroll-output 'first-error  ; scroll until first error
             ;; compilation-read-command nil          ; don't need enter
             compilation-window-height 11)

            (local-set-key (kbd "<M-up>")   'previous-error)
            (local-set-key (kbd "<M-down>") 'next-error)

            (unless (file-exists-p "Makefile")
              (set (make-local-variable 'compile-command)
                   ;; emulate make's .c.o implicit pattern rule, but with
                   ;; different defaults for the CC, CPPFLAGS, and CFLAGS
                   ;; variables:
                   ;; $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $<
                   (let ((file (file-name-nondirectory buffer-file-name)))
                     (format "%s -o %s %s %s"
                             (or (getenv "CC") "g++")
                             (file-name-sans-extension file)
                             ;;(or (getenv "CPPFLAGS") "-DDEBUG=9")
                             (or (getenv "CFLAGS") " -g -O2")
                             file)))))
          ;;(number of things in " " in format must match number of arg. in getenv.)

          ;;This will run Make if there is a Makefile in the same directory as the
          ;;source-file, or it will create a command for compiling a single
          ;;file and name the executable the same name as the file with the extension
          ;;stripped.
          )
;;---------------------------------------------

19.3 Show function name in mod-line

;;Show function name in mod-line--------------
(add-hook 'c-mode-common-hook
  (lambda ()
    (which-function-mode t)))
;;--------------------------------------------

19.4 Smart navigation between h and cpp/cc files

Simple keybinding to switch between header and corresponding implementatio file. If marker is on an "#include" it goes to that file instead.

;;Navigate .h och .cpp ------------------------
;;Now, we can quickly switch between myfile.cc and myfile.h with C-c o.
;;Note the use of the c-mode-common-hook, so it will work for both C and C++.
(add-hook 'c-mode-common-hook
  (lambda()
    (local-set-key  (kbd "C-c o") 'ff-find-other-file)))
;;--------------------------------------------

19.5 Fold code-block

Keybinding collides with next-error, i.e. sub-optimal.

;;Fold code-block-----------------------------
(add-hook 'c-mode-common-hook
          (lambda()
            ;; ;; Collides with winner mode:
            ;; (local-set-key (kbd "C-c <right>") 'hs-show-block)
            ;; (local-set-key (kbd "C-c <left>")  'hs-hide-block)
            ;; (local-set-key (kbd "C-c <up>")    'hs-hide-all)
            ;; (local-set-key (kbd "C-c <down>")  'hs-show-all)

            ;; Now same/similar to org-mode hirarcy, but collides with
            ;; my (previous) setting for next-error/previous-error
            (local-set-key (kbd "M-<right>") 'hs-show-block)
            (local-set-key (kbd "M-<left>")  'hs-hide-block)
            (local-set-key (kbd "M-<up>")    'hs-hide-all)
            (local-set-key (kbd "M-<down>")  'hs-show-all)

            ;;hide/show code-block
            (hs-minor-mode t)))
;;--------------------------------------------

19.6 Indentation

I don't want tabs at all in my source code, unless my collaborator is using tabs. This section deals with how to rectify the problem.

19.6.1 My Style:

This style uses spaces for indentation, unless the code is written using tabs, in which case dtrt-indent autodetects. Then it uses tabs, and they are 3 columns wide.

Does not work (yet): cant re-indent comment-lines at column 0, and class indention is fucked.

;;My-C++-style---------------------------------
;; Define my own style for c++-mode:
(c-add-style "my-style"
             '("linux"                    ;; dont indent { } like "gnu" style does (use same level as "for" "if" etc.)
               (indent-tabs-mode . nil)   ;; don't use tabs use spaces for indentation
               (c-basic-offset . 2)       ;; indent 2 columns (default in linux style I think)
               (tab-width . 3)            ;; if there is a tab it is displayed as 3 columns (Carl's wishes)
               (c-tab-always-indent . t)  ;; TAB-key only indents.
               ;; (backward-delete-function . nil) ;; DO NOT expand tabs to spaces when deleting, (Not working?)
               ;;(c-syntactic-indentation . t)     ;; Is default: indent according to syntax, not prev. line
               ;;(c-set-offset 'substatement-open . 0)     ;; brackets at same indentation level as statements they open
               (c-offsets-alist . ((inline-open . 0)       ;; custom indentation rules
                                   (brace-list-open . 0)            ;; what does this do?
                                   (statement-case-open . +)))      ;; what does this do?


               ))

(defun my-c++-mode-hook ()
  (c-set-style "my-style")               ;; use my-style defined above
  ;; (auto-fill-mode)                     ;; Auto-insert hard line breaks after current-fill-column
  ;; (c-toggle-auto-hungry-state 1)       ;; Both auto-newline (after } etc.) and hungry delete
  )

  (add-hook 'c++-mode-hook 'my-c++-mode-hook)
;;---------------------------------------------

19.6.2 dtrt-indent

Gets loaded first time we enter C or C++ mode. source. Note that with the (current, 2014-03-01) default of dtrt-indent-min-indent-superiority 100, dtrt will not adjust if number of single indentation lines are too small compared to double indentated for instance. See documentation for better explenation.

;; Guess indentation style --------------------
;;Automagically find the indentation style in the source file.
;;(Good for me, since my collaborator is using tabs -- the horror!)

;;Use autoload for faster start-up (rather than "require"):
;;(autoload 'dtrt-indent-mode "dtrt-indent" "Adapt to foreign indentation offsets" t)
;;(add-hook 'c-mode-common-hook 'dtrt-indent-mode)

(add-hook 'c-mode-common-hook
          (lambda()
            (when (require 'dtrt-indent nil 'noerror)
              (dtrt-indent-mode t)
              ;; don't be so strict about getting the guess right
              (setq dtrt-indent-min-indent-superiority 50))))
;;---------------------------------------------

20 PYTHON MODE

Good soruce

TODO: check out: http://ctags.sourceforge.net/

ctags-exuberant -e -R --languages=python --exclude="__init__.py"

20.1 pylint

Check the code with pylint (requires pylint to be installed). Use M-x pylint in buffer. source

(autoload 'python-pylint "python-pylint" nil t)
(autoload 'pylint "python-pylint" nil t)

20.2 Misc

Make RET indent to same level as previous line.

(add-hook 'python-mode-hook
          '(lambda ()
             (define-key python-mode-map "\C-m" 'newline-and-indent)))

20.3 python lookup

pylookup.el

;; load pylookup when compile time
;;(eval-when-compile (require 'pylookup))

;; set search option if you want
;; (setq pylookup-search-options '("--insensitive" "0" "--desc" "0"))

;; to speedup, just load it on demand
(autoload 'pylookup-lookup "pylookup"
  "Lookup SEARCH-TERM in the Python HTML indexes." t)
(autoload 'pylookup-update "pylookup"
  "Run pylookup-update and create the database at `pylookup-db-file'." t)

;; set executable file and db file
(setq pylookup-program "~/.emacs.d/pylookup.py")
(setq pylookup-db-file "~/.emacs.d/pylookup.db")

(add-hook
 'python-mode-hook
 '(lambda ()
    (local-set-key (kbd "C-c h") 'pylookup-lookup)))

20.4 lambda font

Replace the word "lambda" in python code with the greek letter in the font-lock. I.e. the text isn't changed just the display of it.

(require 'lambda-mode)
(add-hook 'python-mode-hook #'lambda-mode 1)
;;change default symbol for lambda:
(setq lambda-symbol (string (make-char 'greek-iso8859-7 107)))

21 FORTRAN MODE

Fortran is terrible. But this is how I make it less so.

Manual: Emacs normally uses Fortran mode for files with extension ‘.f’, ‘.F’ or ‘.for’, and F90 mode for the extensions ‘.f90’, ‘.f95’, ‘.f03’ and ‘.f08’.

Default "fortran-mode" is fixed fortran 77 form. We want to use free fortran 90 form i.e. "f90-mode":

(add-to-list 'auto-mode-alist '("\\.f\\'" . f90-mode))

22 LUA-MODE

Lua is a powerful scripting/configuration language.

;;lua-mode------------------------------------
(autoload 'lua-mode "lua-mode" "Lua editing mode." t)
(add-to-list 'auto-mode-alist '("\\.lua$" . lua-mode))
(add-to-list 'interpreter-mode-alist '("lua" . lua-mode))

(add-hook 'lua-mode-hook 'hs-minor-mode)

(add-hook 'lua-mode-hook
      (lambda ()
        (setq indent-tabs-mode t)
        (setq tab-width 4)
        (setq lua-indent-level 4)))
;;--------------------------------------------

23 MATLAB MODE

Seems like the matlab.el file is not very well maintained.

Requires "matlab.el" which is a part of emacs-goodies-el.deb on Debian.

;;============================================
;;              MATLAB-MODE
;;============================================
(autoload 'matlab-mode "matlab" "Enter Matlab mode." t)
(setq auto-mode-alist (cons '("\\.m\\'" . matlab-mode) auto-mode-alist))
(autoload 'matlab-shell "matlab" "Interactive Matlab mode." t)

;; User Level customizations (You need not use them all):
(setq matlab-shell-command-switches '("-nosplash -nojvm"))
(setq matlab-indent-function t)       ;if you want function bodies indented
(setq matlab-verify-on-save-flag nil) ;turn off auto-verify on save
(defun my-matlab-mode-hook ()
  (setq fill-column 76))              ;where auto-fill should wrap
(add-hook 'matlab-mode-hook 'my-matlab-mode-hook)
(defun my-matlab-shell-mode-hook ()
  '())
(add-hook 'matlab-shell-mode-hook 'my-matlab-shell-mode-hook)

;; use F10 to submit selected txt
;;(define-key matlab-mode-map (quote [f10]) `matlab-shell-run-region)

;; This package requires easymenu, tempo, and derived.
;; This package will optionally use custom, shell, and gud.
;;============================================

24 MAKEFILE MODE

Note, since version 4.0 of make, it is now fully extendable with the GNU Scheme Lisp interpreter Guile.

24.1 no trailing whitespace

Makefiles are picky about whitespaces at the end of lines.

(add-hook 'makefile-mode-hook
          (lambda()
            (setq show-trailing-whitespace t)))

;;This sets the buffer-local variable show-trailing-whitespace,
;;only for Makefiles (including Makefile.am and Makefile.in)
;;============================================

25 TIME

25.1 Time zones

List which places are of interest when calling this function: M-x display-time-world

(setq display-time-world-list
      '(("Australia/Sydney" "Sydney")
        ("Asia/Tokyo" "Tokyo")
        ("Asia/Singapore" "Singapore")
        ("Europe/Copenhagen" "Copenhagen")
        ("Europe/London" "London")
        ("America/New_York" "New York")
        ("America/Los_Angeles" "Los Angeles")))

26 ERC-MODE

ERC is the Emacs IRC-client. It works great, and has several useful modules enabled by default, like auto-complete all nicknames in current channel, and clickable url's (or do RET), and channel tracking in the mode-line.

Table 31: Standard IRC commands
IRC command Key Description
  M-p erc-previous-command
  M-n erc-next-command
/join #foo C-c C-j join channel #foo.
/part msg C-c C-p leave current channel.
/quit msg C-c C-q disconnect & leave message msg for all to see
/gquit msg   quit all servers, with message msg
/nick newnick   changes nickname
/names (in channel) C-c C-n runs /names #channel in current channel
/query nick   open private buffer shared with "nick".
    (both must be registered)
/dcc    
/reconnect    
/amsg   send message to all channels on server
/away reason   mark user as away, for "reason"
/clear   clear/wipe out window contents
/idle nick   show idle time for user nick

See irc help.

Switching between buffers can be done as usual (C-xb,C-x left), or by C-c C-b when already in one erc-buffer. C-c C-SPC cycles through buffers with changes, and finaly goes to most recent non-erc buffer.

To display channel nicknames in a side buffer, just add the following to your .emacs or ERC configuration file:

(require 'erc-nicklist)

Then activate the nicklist buffer, using M-x erc-nicklist RET in the channel buffer (you need to do this for each channel buffer if you want a nicklist for each channel).

M-x erc-nicklist-quit closes the nicklist buffer.

26.1 Auto connect

Automatically connect to the irc-networks, and their channels. I made it into a function, that I must call manually, so it doesn't start unless I explicitly tells it to.

;; Auto joining--------------------------------
;; Make sure to use wildcards for e.g. freenode as the actual server
;; name can be be a bit different, which would screw up auto connect.

(defun erc-hook-me-up ()
  "Call function manually to start all my ERC-buffers.

If the code is put directly into ~/.emacs (without this function
around it), it will restart ERC each time I reload the config, or
start a new emacs session, which is silly."
  (interactive)
  (require 'erc-join)
  (erc-autojoin-mode t)

  (erc :server "irc.freenode.net" :port 6667 :nick "mynick" :password "mypassword")

  (setq erc-autojoin-channels-alist
        '((".*\\.freenode.net" "#wanderlust"
           ;;"#ubuntu-se"  "#emacs"  "#conkeror" "#archlinux" "#debian" "##c++" "#gnuplot" "#zsh"
           ;;"#stumpwm" "#minecraft" "#lisp" "#scheme" "#lispgames" "##ibmthinkpad" "#pioneer"
           )
          ;;          ("irc.irchighway.net" "#comics-anonomous")
          ;;          ("localhost" "&bitlbee")  ;; don't know if this it right.
          ;;          ("oftc.net" "#suckless" "#bitlbee")
          )))
;;---------------------------------------------

26.2 General commands

General one-line commands go here

;;General-settings----------------------------------

;;If I post while status is "away", set me as back. (i.e. unset /away)
(setq erc-auto-discard-away t)

;;set defaults (not used when auto-joining I think).
(setq erc-server "irc.freenode.net"  ;default, works well
      erc-port 6667                  ;default, works well
      erc-nick "mynick"
      ;;      erc-user-full-name user-full-name
      ;;      erc-email-userid "userid"    ; for when ident is not activated
      erc-prompt-for-password t) ;whether to query for passwords or not required for OPN.

;;Kill buffers for channels after /part
(setq erc-kill-buffer-on-part t)
;;Kill buffers for private queries after quitting the server
(setq erc-kill-queries-on-quit t)
;;Kill buffers for server messages after quitting the server
(setq erc-kill-server-buffer-on-quit t)

;; utf-8 always and forever
(setq erc-server-coding-system '(utf-8 . utf-8))

;;TEST: Interpret mIRC-style color commands in IRC chats
(setq erc-interpret-mirc-color t)

;;Disable text "buttonization", since slow & is useless in text mode
;;(erc-button-mode nil)

;;If someone sends a /notice don't just show it in the server buffer,
;;but also in the mini-buffer.
(setq erc-echo-notices-in-minibuffer-flag t)

;;enable fly-spell for my input (only). Can have channel specific
;;dictionaries.
(erc-spelling-mode 1)

(setq erc-spelling-dictionaries '(("irc.freenode.net:6667"   "american")
                                  ("#pioneer"                "british-ize")
                                  ("#clocksim"               "svenska")
                                  ("&bitlbee"                "svenska")
                                  ("#ubuntu-se"              "svenska")
                                  ("irc.oftc.net:6667"       "american")
                                  ("irc.irchighway.net:6667" "american")
                                  ("localhost:6667"          "svenska")))
;;---------------------------------------------

26.3 Don't track every little thing

In the Mode-line you get a notice when the status of one of the channels/buffers changes (in a: [#e,#i…]), but we don't need to be notified upon every change in the channels status.

;;Don't track every little thing: -------------
;;shown in channel-status in modline...
(erc-track-mode t)
;;But exclude these: (numbers are for the irc-server)
(setq erc-track-exclude-types '("JOIN" "NICK" "PART" "QUIT" "MODE"
                                 "324" "329" "332" "333" "353" "477"))

;; don't show any of this (separate from command above...)
;;(setq erc-hide-list '("JOIN" "PART" "QUIT" "NICK"))

;;For the bitlbee channel:
(defun erc-ignore-unimportant (msg)
  (if (or (string-match "*** localhost has changed mode for &bitlbee to" msg)
          ;;(string-match "Unknown error while loading configuration" msg)
          (string-match "Account already online" msg))
      (setq erc-insert-this nil)))
(add-hook 'erc-insert-pre-hook 'erc-ignore-unimportant)

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

26.4 Make header red when IRC connection is closed

Makes the header-line red when the IRC-server is disconnected, as the "ERC: CLOSED" message in the mod-line easily goes by without a notice. Very useful.

;; change header face if disconnected----------
(defface erc-header-line-disconnected
  '((t (:foreground "black" :background "indianred")))
  "Face to use when ERC has been disconnected.")

(defun erc-update-header-line-show-disconnected ()
  "Use a different face in the header-line when disconnected."
  (erc-with-server-buffer
   (cond ((erc-server-process-alive) 'erc-header-line)
         (t 'erc-header-line-disconnected))))

(setq erc-header-line-face-method 'erc-update-header-line-show-disconnected)
;;---------------------------------------------

26.5 Colorize NickNames

Gives all nicknames colors, by using md5sum on the first characters, to get a rrggbb value. emacsWiki:ErcHighlightNicknames

Note: I'm having problems with this in emacs 24.3.91.1, so I use erc-hl-nicks.el instead.

;;Make NickName colors unique------------------
(with-eval-after-load "erc"
  (add-to-list 'erc-modules 'highlight-nicknames)
  (erc-update-modules))
;;---------------------------------------------

26.6 Match/highlight words

;;Match/highlight words------------------------
;;cause all instances of these words to be highlighted in the channel buffers.
;;Also: if you are using track-modified-channels-mode, channels that mention
;;the keywords in them will appear in a difference face in your modeline.

;;highlight differently when running the bitlbee command: blist
(setq erc-keywords '((".*Online.*" (:foreground "green"))
                     (".*Busy"     (:foreground "red"))
                     (".*Away"     (:foreground "orange"))
                     (".*Do not"   (:foreground "red"))
                     (".*Idle"     (:foreground "orange"))
                     ;; Above for bitlbee blist command.
                     ))
;;---------------------------------------------

26.7 Logging

Logging is not enabled by default. To save a log wile in ERC-mode: C-c C-l (calls erc-save-buffer-in-logs).

buffer hasn't been saved before, as the number 1 (point-min)).

The region between `erc-last-saved-position' and `erc-insert-marker' is saved to the current buffer's logfile, and `erc-last-saved-position' is updated to reflect this.

;;Logs ----------------------------------------
(require 'erc-log)
(add-to-list 'erc-modules 'log)

(setq erc-log-insert-log-on-open nil             ;;is on by default
      erc-log-channels-directory "~/.emacs.d/erc-logs/"   ;;default is C-c C-l saves to ~/logs/
      erc-save-buffer-on-part t                  ;;autosave log when /part or /quit
      )

(if (not (file-exists-p erc-log-channels-directory))
    (mkdir erc-log-channels-directory t))
;;---------------------------------------------

26.8 Timestamp on left

This is useful when searching logs. I'm not using it though.

;;Timestamp on left----------------------------
;; Set up timestamp on each line on the left
(setq erc-timestamp-only-if-changed-flag nil
      erc-timestamp-format "[%R-%m/%d] "
      erc-insert-timestamp-function 'erc-insert-timestamp-left)
;;---------------------------------------------

26.9 Functions

Useful functions for ERC mode:

;;---------------------------------------------
;; Clears out annoying erc-track-mode stuff for when we don't care.
;; Useful for when ChanServ restarts :P
(defun erc-reset-track-mode ()
  (interactive)
  (setq erc-modified-channels-alist nil)
  (erc-modified-channels-update))
;;(global-set-key (kbd "C-c r") 'erc-reset-track-mode)
;;---------------------------------------------

26.10 Function to show number of users logged in

Call through M-x, or through /howmany.

;;---------------------------------------------
(defun erc-cmd-HOWMANY (&rest ignore)
  "Display how many users (and ops) the current channel has."
  (interactive)
  (erc-display-message nil 'notice (current-buffer)
                       (let ((hash-table (with-current-buffer
                                             (erc-server-buffer)
                                           erc-server-users))
                             (users 0)
                             (ops 0))
                         (maphash (lambda (k v)
                                    (when (member (current-buffer)
                                                  (erc-server-user-buffers v))
                                      (incf users))
                                    (when (erc-channel-user-op-p k)
                                      (incf ops)))
                                  hash-table)
                         (format
                          "There are %s users (%s ops) on the current channel"
                          users ops))))
;;---------------------------------------------

26.11 Bitlbee

Bitlbee is an awesome instant messenger that pipes all messages from GMail, MSN, etc, to a local IRC server, which you can connect to through any IRC-client, such as ERC or IRSSI.

source: link, bitlbee.el and http://wiki.bitlbee.org/

26.11.1 getting started

Installing:

sudp apt-get install betlbee

Starting the server:

sudo /etc/init.d/bitlbee start

Connect to:

localhost:6667

Now you need to register an account on the channel:

register mypassword

Now start adding accounts you do,

For Jabber:

account add jabber username@jabber.org yourpassword

For MSN:

account add msn username@hotmail.com yourpassword

For ICQ:

account add oscar 648244897 yourpassword login.icq.com

For TWITTER:

account add twitter username password

For AIM:

account add oscar 321454897 yourpassword login.oscar.aol.com

For YIM:

account add yahoo username yourpassword

For GMAIL:

account add jabber username@gmail.com youpassword talk.google.com:5223:ssl

If there's a problem try port 5223 or 5222.

To see which number to use, run:

account list

To turn on an account do:

account 0 on

Now save your configuration with:

save

Turn off all accounts

account off

Remove account

account 0 del

Remove everything, including my login

drop mypassword

Things to set:


set strip_html true set auto_connect true set auto_reconnect true set save_on_quit true

Table 32: Bitlbee Commands
Commands: description
blist will list your buddies and their status.
blist all show all buddies
account list list all accounts available in the bitlbee server
account del [#] delete account number #. Same number as in the list
rename [user] [alias] change name of a person
add [#] [user]  
help  
set view account settings
save ?
set charset ISO8859-1 gives Norwegian/danish åäö -> åæø
  (run in terminal "iconv -l" to see available charset)
drop remove my entire account

26.11.2 code for .emacs

;;Bitlbee--------------------------------------
;;connect to bitlbee
(when (require 'bitlbee nil 'noerror)
  (defvar bitlbee-password "mypassword")

  (defun bitlbee-identify ()
    "If we're on the bitlbee server, send the identify command to the
    &bitlbee channel."
    (when (and (string= "localhost" erc-session-server)
               (string= "&bitlbee" (buffer-name)))
      (erc-message "PRIVMSG" (format "%s identify %s"
                                     (erc-default-target)
                                     bitlbee-password))))
  (add-hook 'erc-join-hook 'bitlbee-identify)

  (defun bitlbee-connect ()
    (interactive)
    (save-window-excursion
      (when (get-buffer "&bitlbee")
        (switch-to-buffer "&bitlbee")
        (erc-message "PRIVMSG" (concat (erc-default-target) " identify " bitlbee-password))
        (erc-message "PRIVMSG" (concat (erc-default-target) " account on 0")
                     (erc-message "PRIVMSG" (concat (erc-default-target) " account on 1"))))))
  (setq bitlbee-reconnect-timer (run-with-timer 0 60 'bitlbee-connect))
  )

;;start bitlbee server on startup:
(erc :server "localhost" :port "6667" :nick "jag" :password bitlbee-password)
;;---------------------------------------------

26.12 Erc-tex

If you have LaTeX installed, you most likely also have dvipng, and then you can use this nice mode. It automatically renders any math between $$. Since I'm not using math that often in my erc, I autoload it and call it manually M-x erc-tex-mode if I feel the need for it.

(autoload 'erc-tex-mode "erc-tex" "insert math in \"$$\" in ERC buffer" t)

27 UNISON MODE

Something I hacked up myself. I keep it here https://github.com/impaktor/unison-mode, but I think someone put it into MELPA/Marmelade? I don't maintain it much.

I made it mostly to learn how to do an emacs mode. Note to self: If in future endeavors I want to add a compilation buffer to my mode, check out this post.

(autoload 'unison-mode "unison-mode" "my unison mode" t)
(setq auto-mode-alist (append '(("\\.prf$" . unison-mode)) auto-mode-alist))

28 FUNCTIONS

Functions that are handy to have. Invoke by M-x.

28.1 Remove ^M from files

;;Remove ^M------------------------------------
;; Call with M-x strip[TAB]
(defun strip-^m ()
  (interactive)
  (goto-char (point-min))
  (while (search-forward "\r" nil nil)
    (replace-match "")))
;;(define-key esc-map "o" 'strip-^m)
;;--------------------------------------------

28.2 Search across buffers

Search for word across all open buffers. Note: ibuffer can do this as well.

;;Search all open buffers---------------------
(defun search (regexp)
  "Search all buffers for a regexp."
  (interactive "sRegexp to search for: ")
  (multi-occur-in-matching-buffers ".*" regexp))
;;--------------------------------------------

28.3 Nuke all buffers

;;nuke-all-buffers-----------------------------
(defun nuke-all-buffers ()
"Kill all buffers, leaving *scratch* only."
(interactive)
(mapc (lambda (x) (kill-buffer x)) (buffer-list)) (delete-other-windows))
;;---------------------------------------------

28.4 Kill all other buffers

;;Kill all other buffers----------------------
;;kills all buffers, except the current one.
    (defun kill-all-other-buffers ()
      "Kill all other buffers."
      (interactive)
      (mapc 'kill-buffer (delq (current-buffer) (buffer-list))))
;;--------------------------------------------

28.5 Artistic mode

For ASCII-art

;;Artistic mode ASCII-art---------------------
;; toggle artiste-mode
(defun artist-mode-toggle ()
  "Toggle artist-mode"
  (interactive)
  (if (eq major-mode 'artist-mode)
      (artist-mode-off)
    (artist-mode)))
;;(global-set-key (kbd "C-c d") 'artist-mode-toggle)
;;--------------------------------------------

29 OBSOLETE / UNUSED

Here I put fun/interesting/useful things that are no longer needed by me, but could be of interest to others or my future self.

29.1 recent buffers

Recent file is in Emacs since v.21. The code below binds it to C-x C-r which is otherwise bound to find-file-read-only which I've never found useful anyways. There are tons of ways to use icicles, ido, or iswitch with recentf, or filter files based on directory, or time etc.

I find TAB or corresponding numbers easiest to use in the recentf-open-files buffer.

;;Recent files --------------------------------
;; List of recent opened files
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
;;---------------------------------------------

29.2 turn on line numbers when goto-line is called

This could be fun. I never use linum-mode (shows line numbers in the margin, available since (> emacs-major-version 22)) but this code turns it on only temporarily while you goto-line: M-g g or M-g M-g.

(code from emacs-rocks)

;;Goto line with linum-mode--------------------
;; only active when M-g M-g or M-g g
(defun goto-line-with-feedback ()
  "Show line numbers temporarily, while prompting for the line number input"
  (interactive)
  (if (and (boundp 'linum-mode)
           linum-mode)
      (call-interactively 'goto-line)
    (unwind-protect
        (progn
          (linum-mode 1)
          (call-interactively 'goto-line))
      (linum-mode -1))))

(global-set-key [remap goto-line] 'goto-line-with-feedback)
;;---------------------------------------------

29.3 iy-go-to-char

Same as 'f' in vim. For faster navigation/jump through text. I haven't gotten into the habit of using this yet. Good to combine with key-chord

;;iy-go-to-char--------------------------------
;;move marker to character. Like 'f' in vim.
(when (require 'iy-go-to-char nil 'noerror)
;;(when (locate-library "iy-go-to-char")
  (global-set-key (kbd "C-c f") 'iy-go-to-char)
  (global-set-key (kbd "C-c F") 'iy-go-to-char-backward)
  (global-set-key (kbd "C-c ,") 'iy-go-to-char-continue)
  (global-set-key (kbd "C-c .") 'iy-go-to-char-continue-backward)
)
;;---------------------------------------------

29.4 cursor

Similar to emacs-fu's code, but not as good for read only.

;; cursor -------------------------------------
(blink-cursor-mode 1)           ; blink cursor
;; http://www.emacswiki.org/cgi-bin/wiki/download/cursor-chg.el
;; change cursor for verwrite/read-only/input
(when (require 'cursor-chg nil 'noerror)  ; Load this library
  (change-cursor-mode 1) ; On for overwrite/read-only/input mode
  (toggle-cursor-type-when-idle 1)
  (setq curchg-default-cursor-color "Yellow"))
;;---------------------------------------------

29.5 popup-shell

Some code from here. Could be handy but I never use it. A shell pops up when pressing F11.

(defvar th-shell-popup-buffer nil)

(defun th-shell-popup ()
  "Toggle a shell popup buffer with the current file's directory as cwd."
  (interactive)
  (unless (buffer-live-p th-shell-popup-buffer)
    (save-window-excursion (shell "*Popup Shell*"))
    (setq th-shell-popup-buffer (get-buffer "*Popup Shell*")))
  (let ((win (get-buffer-window th-shell-popup-buffer))
        (dir (file-name-directory (or (buffer-file-name)
                                      ;; dired
                                      dired-directory
                                      ;; use HOME
                                      "~/"))))
    (if win
        (quit-window nil win)
      (pop-to-buffer th-shell-popup-buffer nil t)
      (comint-send-string nil (concat "cd " dir "\n")))))

(global-set-key (kbd "<f11>") 'th-shell-popup)

29.6 auto-dictionary (fails):

Should autodetect language, but is just slow.

;;--------------------------------------------
(when (require 'auto-dictionary nil 'noerror)
  ;;So slow, does not work as well as wished.
  (add-hook 'flyspell-mode-hook (lambda () (auto-dictionary-mode 1)))
)
;;--------------------------------------------

29.7 highlight current line

;;highlight line------------------------------
;; hl-line: highlight the current line
(when (fboundp 'global-hl-line-mode)
  (global-hl-line-mode t)) ;; turn it on for all modes by default
;;--------------------------------------------

29.8 cyberpunk cursor

Changes color while blinking. Keep in mind: blinking cursor equals screen updates equals higher power usage which might not be what you want on a laptop, or in a world with no infinite energy-source.

;;Cyberpunk cursor-----------------------------
;; Changes color while blinking
(defvar blink-cursor-colors (list  "#92c48f" "#6785c5" "#be369c" "#d9ca65")
  "On each blink the cursor will cycle to the next color in this list.")

(setq blink-cursor-count 0)
(defun blink-cursor-timer-function ()
  "Cyberpunk variant of timer `blink-cursor-timer'. OVERWRITES original version in `frame.el'.
This one changes the cursor color on each blink. Define colors in `blink-cursor-colors'."
  (when (not (internal-show-cursor-p))
    (when (>= blink-cursor-count (length blink-cursor-colors))
      (setq blink-cursor-count 0))
    (set-cursor-color (nth blink-cursor-count blink-cursor-colors))
    (setq blink-cursor-count (+ 1 blink-cursor-count))
    )
  (internal-show-cursor nil (not (internal-show-cursor-p)))
  )
;;--------------------------------------------

29.9 geeky startup message

Definitley not needed by anyone, but nerdy fun.

;;--------------------------------------------
;;A geeky startup message, somewhat reminiscent of “The Matrix: Reloaded”
(defconst animate-n-steps 3)
(defun emacs-reloaded ()
  (animate-string (concat ";; Initialization successful, welcome to "
                          (substring (emacs-version) 0 16) ".")
                  0 0)
  (newline-and-indent)  (newline-and-indent))
(add-hook 'after-init-hook 'emacs-reloaded)
;;--------------------------------------------

30 EMACS 24 news

30.1 TODO Check out

electric-pair-mode, electric-indent-mode, electric-layout-mode

30.2 Count words (obsolete since Emacs 24)

From emacs 24(.3?) M-= counts words (as defined by the current mode), lines, and characters in region; C-u M-= in entire buffer, so this code is no longer needed. Uses count-words-region and count-words.

;;count words-----------------------------------
;;Prior to emacs 24 there was no count-words function
;;Taken from emacs-fu.
(if (< emacs-major-version 24)
    (defun count-words (&optional begin end)
      "count words between BEGIN and END (region); if no region defined, count words in buffer"
      (interactive "r")
      (let ((b (if mark-active begin (point-min)))
            (e (if mark-active end (point-max))))
        (message "Word count: %s" (how-many "\\w+" b e)))))
;;--------------------------------------------

30.3 minibuffer TAB completion

Nice. More like zsh.

;;TAB cycles if fewer than 5 completions. Else show *Completions*
;;buffer.
  (if (>= emacs-major-version 24)
      (setq completion-cycle-threshold 5))

31 TESTING GROUND

Here I put stuff I'm currently playing around with, or just forgotten about.

31.1 test .emacs sanity

Code snippet that will test the emacs config file and echo "all is well" if no errors, or pop up a buffer describing the error. From here

(defun my-test-emacs ()
  (interactive)
  (require 'async)
  (async-start
   (lambda () (shell-command-to-string
          "emacs --batch --eval \"
(condition-case e
    (progn
      (load \\\"~/.emacs\\\")
      (message \\\"-OK-\\\"))
  (error
   (message \\\"ERROR!\\\")
   (signal (car e) (cdr e))))\""))
   `(lambda (output)
      (if (string-match "-OK-" output)
          (when ,(called-interactively-p 'any)
            (message "All is well"))
        (switch-to-buffer-other-window "*startup error*")
        (delete-region (point-min) (point-max))
        (insert output)
        (search-backward "ERROR!")))))

31.2 Screenwriting mode

http://ericjmritz.name/2014/04/26/screenwrite-mode-for-gnu-emacs/

screenwriter mode (fork)

Fix stuipid rebinding of default emacs keys:

(define-key screenwriter-mode-map (kbd "C-c C-s") 'screenwriter-slugline)
(define-key screenwriter-mode-map (kbd "C-c C-a") 'screenwriter-action-block)
(define-key screenwriter-mode-map (kbd "C-c C-d") 'screenwriter-dialog-block)
(define-key screenwriter-mode-map (kbd "C-c C-t") 'screenwriter-transition)

31.3 open-with

Good for opening an html-file in your web browser, for instance.

On OSX it would use the "open" program to decide which program to open the file with, otherwise you’d be prompted to enter the name of the program in the minibuffer. src

Note: This causes Emacs to lock until the opened program exits.

;;Open-file-with-------------------------------
(defun open-with ()
  "Simple function that allows us to open the underlying
file of a buffer in an external program."
  (interactive)
  (when buffer-file-name
    (shell-command (concat
                    (if (eq system-type 'darwin)
                        "open"
                      (read-shell-command "Open current file with: "))
                    " "
                    buffer-file-name))))

;;(global-set-key (kbd "C-c o") 'open-with)
;;---------------------------------------------

31.4 lusty exploorer

Alternative way to open files. Opens a split minibuffer with all files matching current typed string, and narrows search as you type. Better than default emacs behavior, there are other ways I prefer.

;Testar lusty exploorer----------------------
(when (require 'lusty-explorer nil 'noerror) ;;Only read if package available
  ;; override the normal file-opening, buffer switching
  (global-set-key (kbd "C-x C-f") 'lusty-file-explorer)
  (global-set-key (kbd "C-x b")   'lusty-buffer-explorer))
;;--------------------------------------------

31.5 Disable cua and transient mark modes in term-char-mode

;;--------------------------------------------
;; disable cua and transient mark modes in term-char-mode
;; http://www.emacswiki.org/emacs/AnsiTermHints
;; remember: Term-mode remaps C-x to C-c
(defadvice term-char-mode (after term-char-mode-fixes ())
  (set (make-local-variable 'cua-mode) nil)
  (set (make-local-variable 'transient-mark-mode) nil)
  (set (make-local-variable 'global-hl-line-mode) nil)
  (ad-activate 'term-char-mode)
  (term-set-escape-char ?\C-x))

(add-hook 'term-mode-hook
          (lambda()
            (local-unset-key (kbd "<tab>"))))
;;--------------------------------------------

31.6 Only show auto-completions buffer on second Tab-press

;;--------------------------------------------
;;only show auto-completions buffer on second Tab-press
;;if no match is found
(setq completion-auto-help 1)
;;--------------------------------------------

31.7 Auto completion for: () {} [] "" ''

Pairs any kind of bracket. Simple but effective. Note, don't use this with paredit (which is a powerful Lisp-mode parenthesis matcher).

;;--------------------------------------------
;; auto-completion on brackets.
(setq skeleton-pair t)
(global-set-key (kbd "(") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "{") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "[") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "\"") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "'") 'skeleton-pair-insert-maybe)   ;; TODO: don't use in lisp-mode'
;;--------------------------------------------

31.8 autopair ({[]})

Smart matching of parenthesis. EW. source.

;;(autoload 'autopair-global-mode "autopair" nil t)
(when (require 'autopair nil 'noerror)
  ;; Use paredit intead in any lsip-environment:
  (add-hook 'lisp-mode-hook             #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'emacs-lisp-mode-hook       #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'lisp-mode-hook             #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'lisp-interaction-mode-hook #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'scheme-mode-hook           #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'slime-mode-hook            #'(lambda () (setq autopair-dont-activate t))) ;does not fix
  (add-hook 'slime-repl-mode-hook       #'(lambda () (setq autopair-dont-activate t))) ;does not fix
  (autopair-global-mode) ;; to enable in all buffers
  (setq autopair-blink 'nil))

32 END

32.1 custom stuff

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(safe-local-variable-values (quote ((flyspell-mode)))))
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )

32.2 Send message to message-buffer

(message "Configuration file read to end")

Created: 2016-07-07 Thu 11:48

Emacs 24.5.1 (Org mode 8.2.10)

Validate