Emacs - <troll>is WAY better than Vi</troll>

Emacs glossary

buffer
the area where you can read / edit text.
Most of the time : 1 buffer = 1 file, but this is not always true because of specialized buffers : *Completions*, *Messages*, *scratch*, ...
M-any
  • M stands for the "meta" key, which is Alt on PC keyboards
  • key1-key2 (with a dash) means : "press key2 while maintaining key1 down"

How to open files in an already running Emacs instance from the shell ?

  1. in Emacs : Alt-x server-start
  2. in the shell : emacsclient fileToOpenInEmacs &
  3. (do some work)
  4. when you're done, close the buffer : Ctrl-x #

WARNING **: Couldn't register with accessibility bus: ... when starting Emacs

Situation :

When starting Emacs from the command line (but within a graphical environment), I get the error message :
** (emacs:3920): WARNING **: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.

Solution :

Append to ~/.bashrc :
export NO_AT_BRIDGE=1

If, for any reason ((non-)?(login|interactive) shell), you prefer not to alter ~/.bashrc, you can apply changes to /etc/bash.bashrc

RegExp in Emacs

To replace ... with ... query-replace-regexp ... with ...
"dd/mm/yyyy" "yyyy/mm/dd" "\([0-9]\{2\}\)/\([0-9]\{2\}\)/\([0-9]\{4\}\)" "\3/\2/\1"
newlines in a paragraph of text auto-wrapped lines of text \([a-zA-Z0-9\.,]\)CTRL-q-j \1SPACE
consecutive space characters a single space character  + (a space character followed by a + sign)   (a single space character)
<span class="code">...</span> <code>...</code> <span class="code">\([^<]*\)</span> <code>\1</code>
Some tips / snippets :

How to setup Jabber / XMPP to use Emacs as a GTalk client ?

Setup :

  1. Get the Jabber extension :
    • For Debian, it's packaged as emacs-jabber (get a hint for the load-path with : dpkg -L emacs-jabber)
    • for Windows (download and extract into the extensions directory, declared as load-path in Emacs configuration file). Important notes below.
  2. In the configuration file, let Emacs know where it may find the extension, then "require" it :
    (add-to-list 'load-path "/path/to/the/jabber/extension")
    (require 'jabber)
    My advice :
    • There may be several load-path directives in the configuration file (but possibly a better way to configure this ?)
    • The path must lead to the directory containing the extension files. It won't work if it's the path to a generic directory containing all extensions as sub-directories
    • If running on Windows, don't forget to change the \ into / in the path
  3. start Emacs
  4. ALT-x jabber-customize
  5. Edit the Jabber Account List section (put the cursor on Show Value, then ) :
    • JID (Jabber ID) : john.smith@gmail.com
    • Password : 12345
    • Network server : talk.google.com
    • Connection type : Legacy SSL/TLS
    Don't forget to save with Save for future sessions.
  6. add into the configuration file :
    ; JABBER / XMPP (GTalk)
    (require 'jabber)
    (setq-default jabber-account-list (quote (
    	("john.smith@gmail.com"
    		(:password . "12345")
    		(:network-server . "talk.google.com")
    		(:connection-type . ssl)
    	)))
    )
  7. You're ready to connect !
On Windows + behind a corporate firewall/proxy :

Well, things get tough (details) ! Here is what ALMOST worked :

  1. Apply this configuration :
    ; JABBER / XMPP (GTalk)
    (require 'jabber)
    (setq-default jabber-account-list (quote (
    	("john.smith@gmail.com"
    		(:password . "12345")
    		(:network-server . "127.0.0.1")
    		(:port . 12345)
    		(:connection-type . ssl)
    	)))
    )
  2. Setup a tunnel with PuTTY from 127.0.0.1:12345 to talk.google.com:443
  3. This fails saying :
    Opening TLS connection to `127.0.0.1'...
    Opening TLS connection with `gnutls-cli -p 12345 127.0.0.1'...failed
    Opening TLS connection with `gnutls-cli -p 12345 127.0.0.1 --protocols ssl3'...failed
    Opening TLS connection with `openssl s_client -connect 127.0.0.1:12345 -no_ssl2 -ign_eof'...failed
    Opening TLS connection to `127.0.0.1'...failed
    Jabber connection failed
    john.smith@gmail.com/nil: connection lost: `nil'
Other failure :

Connecting may also fail saying :

Opening TLS connection to `talk.google.com'...
Opening TLS connection with `gnutls-cli -p 5223 talk.google.com'...done
Opening TLS connection to `talk.google.com'...done
john.smith@gmail.com/nil: connection lost: `exited abnormally with code 1
'
Workaround : append to the configuration file (source) :
(setq starttls-use-gnutls t
	starttls-gnutls-program "gnutls-cli"
	starttls-extra-arguments '("--starttls" "--insecure")
)
But the connection is now insecure !

Usage :

  1. Connect : ALT-x jabber-connect
  2. You'll be prompted for your Jabber ID (JID) : john.smith@gmail.com
  3. Once connected, the buddy list is available in the *-jabber-roster-* Emacs buffer.
  4. To start a conversation, just place the cursor on the line of a contact name and . This will open a new Emacs buffer.
  5. Enjoy !
  6. Disconnect : ALT-x jabber-disconnect

Emacs shortcut keys

Notes :
CTRL ALT CTRL-x ESC other
a goto beginning of line goto beginning of paragraph
b Backward 1 word
  • switch between Buffers
  • + bufferName : open new Buffer (bufferName can be anything as file name will be prompted upon save)
c + c : send mail
+ / : close current HTML tag
change to uppercase the letter under the point and go forward one word exit Emacs
d Delete current character (= DEL) Delete word forward from point (kill-word)
e goto End of line goto End of paragraph
f Forward 1 word open File
g quit almost anything + g n : Goto line number n
h + b : list existing key bindings
+ c : describe key briefly
+ e : display startup error messages
select whole buffer (mark-whole-buffer) CTRL-h F : show the FAQ
i indent point up to the next tab stop (source)
j make new line with same indentation (newline-and-indent)
k Kill text from point to end of line Kill current buffer F1-k-key : describe key
l centers the point vertically starting from the point, change to lowercase the letters of the current word, then go forward 1 word Display the total number of Lines of the current buffer, lines before cursor and lines after.
m Move (forward or back) to the first nonblank character on the current line (back-to-indentation) create a new Mail
o change the selected window query-replace-regexp occur : return lines matching RegExp
See also keep-lines and flush-lines
q CTRL-q TAB : indent point up to the next tab stop (ALT-i is easier)
r Reverse incremental search (i-search) CTRL-ALT-r : Reverse incremental regular expression search (isearch-backward-regexp) Regexp help
s forward incremental Search (i-search) Save current buffer
  • CTRL-s-s : search the previous search
  • CTRL-s-w : search the word found under the cursor (starting at point until end of word. CTRL-w to expand selection to next word)
  • CTRL-ALT-s : forward incremental regular expression Search (isearch-forward-regexp) Regexp help
u starting from the point, change to uppercase the letters of the current word, then go forward 1 word +u : undo
v page up page down +v : reload buffer from disk (revert-buffer)
w cut selection copy selection Save current buffer as ...
x + show-paren-mode highlight matching parenthesis
+ shell: open a shell session in an Emacs buffer

+ blackbox
+ doctor: talk to the psycho
+ dunnet : RPG (solution)
+ gomoku : Puissance 5
+ hanoi
+ life : the Game of Life
+ mpuz : multiplication puzzle
+ tetris
exchanges the point and the mark + ispell-buffer : checks spelling (details) Convert line endings from Dos to Unix :
CTRL-x f undecided-unix
Or : ALT-x set-buffer-file-coding-system undecided-unix
Convert line endings from Unix to Dos :
CTRL-x f undecided-dos
Or : ALT-x set-buffer-file-coding-system undecided-dos
y paste
z repeat the previous command
SPACE set mark (use arrows to make selection)
BACKSPACE Delete word backward from point (backward-kill-word)
_ undo (Win), baskspace (Linux) (???)
{ decrease width of the current window
} increase width of the current window
% Search and query replace.
! replace all remaining matches
^ Make current window higher. (enlarge-window). CTRL-x ^ SPC to avoid inserting a ^, CTRL-x z to repeat.
< Go to 1st character of buffer
> Go to last character of buffer
+ Make all windows the same height (balance-windows)
/ word completion (made as "best-effort", based on words found in the current buffer)
\ delete all spaces surrounding the point CTRL-ALT-\ (defunct ?) : indent all lines beginning in the region (indent-region)
1 completely unsplit display
2 split current buffer display horizontally (1 on top / 1 on bottom)
3 split current buffer display vertically (1 left / 1 right)
CTRL ALT CTRL-x ESC other

Remove duplicate lines

In the configuration file, add :

; Remove duplicate lines
; source : http://www.emacswiki.org/emacs/DuplicateLines#toc2

; Execute this with :
;	M-x uniquify-all-lines-buffer

(defun uniquify-all-lines-region (start end)
"Find duplicate lines in region START to END keeping first occurrence."
(interactive "*r")
(save-excursion
	(let ((end (copy-marker end)))
		(while
			(progn
				(goto-char start)
				(re-search-forward "^\\(.*\\)\n\\(\\(.*\n\\)*\\)\\1\n" end t))
			(replace-match "\\1\n\\2")))))

(defun uniquify-all-lines-buffer ()
"Delete duplicate lines in buffer and keep first occurrence."
(interactive "*")
(uniquify-all-lines-region (point-min) (point-max)))

And use it with : ALT-x uniquify-all-lines-buffer

Emacs commands

Commands below can be executed with :
Alt-x command
Emacs documentations generally refer to the Meta key (M), which is the Alt key of PC keyboards .
Command Usage Details
column-number-mode Show the column number
compare-windows Compare the text in the current window with that in the next window
delete-matching-lines Delete lines matching RegExp
delete-non-matching-lines Delete lines not matching RegExp
delete-trailing-whitespace Delete trailing whitespaces (space or TAB) in the whole buffer
erc Start the Emacs IRC Client
flush-lines Delete lines matching RegExp alias : delete-matching-lines
hexl-find-file View and edit a file in hexadecimal
highlight-lines-matching-regexp Highlight lines matching RegExp alias : hi-lock-line-face-buffer
how-many Count lines matching RegExp alias : count-matches
keep-lines Delete lines not matching RegExp alias : delete-non-matching-lines
list-colors-display Display Emacs colors names
list-matching-lines List lines matching RegExp
menu-bar-mode Toggle display of the menu bar : File | Edit | Options | ...
occur Count lines matching RegExp alias : list-matching-lines
sort-lines Sort lines alphabetically
  • in ascending order
  • to reverse the sort (source) :
    Ctrl-u Alt-x sortCommand
sort-numeric-fields Sort lines numerically
toggle-word-wrap Long lines are wrapped at white space, instead of cutting words in the middle at the edge of window
tool-bar-mode Toggle display of the tool bar (icons)
whitespace-mode Toggle display of spaces and tabs

How to insert special characters in the minibuffer ?

character to insert command
TAB CTRL-q TAB
CTRL-q-j

Emacs collapse/expand regions

This is achieved with the built-in HideShow module, which is activated by the ALT-x hs-minor-mode command (When activated, (hs) should appear in the status bar).
All keyboard shortcuts start with C-c @. Those ending in s are used to show stuff. Those in h are there to hide stuff.

object hide show
block
  1. place the point within the (, {, or [ to collapse
  2. C-c @ C-h
  1. place the point within the (, {, or [ to expand
  2. C-c @ C-s
level
  1. place the point 1 level higher than the level to hide
  2. C-c @ C-l
  1. place the point within the (, {, or [ to expand
  2. C-c @ C-s
all blocks C-c @ ESC C-h C-c @ ESC C-s

Customizing Emacs

Custom configuration file

OS version custom options file
Debianoids GNU Emacs 22.2.1 ~/.emacs
GNU/Linux Emacs 21.3.1 ~/.gnu-emacs-custom
Windows 7 GNU Emacs 24.3.1 ~/AppData/Roaming/.emacs
Windows GNU Emacs 23.3.1 ~/Application Data/.emacs
Windows XEmacs 21.5 ~/.xemacs/custom.el

Change the font face

in the current buffer (source) :
  • SHIFT-click | Change Buffer Font... then pick the installed font you like (such as Dotsies ?).
    To restore the initial settings, consider the Reset to Default option.
  • OR :
    1. ALT-x | set-frame-font
    2. enter fontName or fontName-fontSize (examples : consolas, consolas-11), then
in all buffers (i.e. set this as a startup value) (sources : 1, 2) :
add to the configuration file a line such as :

Set the font size

Edit the custom configuration file, and add :
(set-face-attribute 'default nil :height 100)
The height is given in 1/10 of point, so 100 means 10 points.

Change colors

For the Syntax Highlighting :
  1. Options | Edit Faces...
  2. a "semi-graphical" interface will appear in a new buffer. There is just to find which "style" to modify, then click the small triangle to open it for changes.
  3. The available colors names can be listed with ALT-x list-colors-display
  4. Once you're satisfied with the changes you made, click on the Set | Save buttons at the top of the buffer
  5. the changes are saved into the custom configuration file.
Alternate method (works well in terminal mode) :
  1. place the cursor on the word having a style you wish to edit
  2. ALT-x customize-face
  3. this will open a new buffer to edit values
  4. move the cursor as usual (arrows + keyboard shortcuts) to some pseudo hyperlinks
  5. activate them with
  6. pick the options you like
  7. when you're satisfied with your settings, "click" on Apply and Save
For the minibuffer prompt :
  • Either ALT-x customize-face minibuffer-prompt (get Emacs colors names), and place cursor on pseudo-hyperlinks + to validate
  • or add a (set-face-foreground 'minibuffer-prompt "moccasin") line to the custom configuration file.

Highlighting a region

(set-face-background 'region "navy" )

PHP syntax highlighting

  1. install the php-elisp package
  2. add into the configuration file :
    ;PHP SYNTAX HIGHLIGHTING
    ;source : http://www.emacswiki.org/emacs-en/EnablingFontLock
    (if (fboundp 'global-font-lock-mode)
    (global-font-lock-mode 1)		; GNU Emacs
    	(setq font-lock-auto-fontify t))	; XEmacs
    
    ; source : http://thedrupalblog.com/enabling-php-mode-and-syntax-highlighting-emacs
    (require 'php-mode)
    (setq auto-mode-alist
    	(append '(("\\.php$" . php-mode)
    		("\\.module$" . php-mode))
    			auto-mode-alist))

Background color

  1. Pick one Emacs color by name
  2. Just add (set-face-background 'default "colorName") at the end of the configuration file
  3. or add into the configuration file :
    ;REVERSE VIDEO MODE
    ; source : http://a-nickels-worth.blogspot.com/2007/11/effective-emacs.html
    (set-background-color "black")
    (set-face-background 'default "black")
    (set-face-background 'region "black")
    (set-face-foreground 'default "white")
    (set-face-foreground 'region "gray60")
    (set-foreground-color "white")
    (set-cursor-color "red")

Indentation width (source) :

Just add : (setq-default tab-width n) to the configuration file, n being the TAB width in number of characters. In some cases, you may also need to add : (setq-default indent-tabs-mode t) with t/nil enabling / disabling the use of the TAB character for indentation.

Disable the auto-indent feature that appeared with version 24.4 (source) :

Add to the configuration file :
(when (fboundp 'electric-indent-mode) (electric-indent-mode -1))

Define a new shortcut key sequence

Open the configuration file and append (global-set-key "key_sequence" 'command) into it.

Example : (global-set-key "\M-o" 'query-replace-regexp)

Syntax for special keys
Special key Characters
ALT \M ("meta", sometimes bound to ESC)
CTRL \C
DEL \d
ESC \e
RET \r
TAB \t

Settings for Python (Emacs and TAB, Emacs hooks) :

Add into the configuration file :
; PYTHON HOOK
(add-hook 'python-mode-hook '(lambda ()
	(setq-default indent-tabs-mode nil)		; no difference "setq default" or "setq-default" 
	(global-set-key (kbd "TAB") 'tab-to-tab-stop)
	(setq tab-stop-list (number-sequence 4 120 4))	; start stop increment. Source : http://www.emacswiki.org/emacs/TabStopList
	)
)

Show the name and path of the current file in the window title bar (source) :

Add into the configuration file :
; SHOW CURRENT FILE NAME WITH FULL PATH IN WINDOW TITLE
; source : http://emacs-fu.blogspot.fr/2011/01/setting-frame-title.html
(setq-default
	frame-title-format
	(list '(buffer-file-name "EMACS : %f" (dired-directory
		(revert-buffer-function " %b"
			("%b – Dir: " default-directory)
		)))
	)
)

Remove trailing spaces (source) :

Run Alt-x delete-trailing-whitespace, or add into ~/.emacs :
(add-hook 'before-save-hook 'delete-trailing-whitespace)
If you're using Emacs with Git, you'd better read this .

Hide the top bars (menu + icons) :

Add into the configuration file :
; Hide the "File | Edit | Options | ..." bar
(menu-bar-mode 0)
; Hide the icons bar
(tool-bar-mode 0)

Emacs : the spell checker