Emacs Tips and Howtos

Posted on In Linux

With Emacs, I feel happy. I love the rich functions of Emacs, such as compiling, quickly jumping to the lines with compilation error and debugging with gdb, and more. I ever wrote small tips posts about Emacs before. But it is a good idea to put them together and keep adding new ones. Here comes this post on Emacs tip and howtos, more or less like a cheat sheet and FAQ. This post is kept being updated with new tips and howtos.

==What is your Emacs configuration file?==

First thing first. I share my Emacs configuration file (‘~/.emacs’) on github. Please find it here: Zhiqiang’s Emacs configuration file.

==Emacs tutorials==

Emacs itself provides a tutorial to start with. To view it, execute this command in Emacs:

C-h t

Many Emacs tutorials are online. I highly recommend the A Tutorial Introduction to GNU Emacs by Keith Waclena.

==Several Emacs cheat sheets==

Here are several Emacs cheat sheets online:

Emacs Basics:
http://doors.stanford.edu/~sr/computing/emacs.html

Emacs Commands List:
http://lpn.rnbhq.org/tools/xemacs/emacs_ref.html

GNU Emacs Reference Card:
http://refcards.com/docs/gildeas/gnu-emacs/emacs-refcard-a4.pdf

==Emacs Write to Read-only Files==

Emacs has the power of writing to read-only files as Vim (with “w!”). This is how to do it:

We can clear the buffer text’s read-only flag with

C-x C-q

==Emacs Remove ^M From Files==

‘^M’ characters are usually generated by a editor in Windows. This post introduces how to remove these ‘^M’ characters in Emacs.

First go to top of buffer, then:

M-x replace-string C-q C-m RET

Here,

M-%

can be used for

M-x replace-string

The control-q will allow typing control characters into the input buffer.

==Generate and regenerate ETAGS in Emacs==

Add the following lines to ‘~/.emacs’

;; =================== etags =====================
(defvar tags-cmd "etags -R ./* 2>/dev/null")

(defun regen-tags ()
  "Regenerate the tags file for the current working directory"
  (interactive)
  (let ((tag-file (concat default-directory "TAGS")))
    (shell-command tags-cmd)
    (visit-tags-table tag-file)))
;; =================== end etags =====================

To regnerate ETAGS in the current directory, simply run these command in Emacs:

M-x regen-tags

==Auto completion==

Auto Complete Mode is the most intelligent auto-completion extension. Auto Complete Mode provides visual interfaces, reduced overhead of completion by using statistic method and extensibility. A Demo is available.

On Fedora Linux, we can install Auto Complete Mode by:

# yum install emacs-auto-complete emacs-auto-complete-el

Auto Complete Mode is easy to use — just type your code!

You can use ‘TAB’ to expand and select. You can also use ‘M-p’ and ‘M-n’ to select previous or next possible choice, and ‘RET’ to complete your selection. This should complete most of the auto completion usage. For more usage, please refer to Auto Complete Mode User Manual.

==Goto a specific line==

Emacs supports jumping to a specific line:

M-g M-g

Then enter the line number and RET.

==Jump to next and previous error==

In the compile mode, you can jump to the next/previous error in the compile buffer by:

M-g M-n

and

M-g M-p

==Jump to beginning and end of a function==
The functions beginning-of-defun and end-of-defun works with most programming modes in Emacs that jumps to the beginning and end of the function/class definition.

The commands are

C-M-a

and

C-M-e

This will make editing code much easier.

==Moving in the Parenthesis Structure==
Move over groupings delimited by parentheses (or whatever else serves as delimiters in the language you are working with):

C-M-n

Move forward over a parenthetical group (forward-list).

C-M-p

Move backward over a parenthetical group (backward-list).

C-M-u

Move up in parenthesis structure (backward-up-list).

C-M-d

Move down in parenthesis structure (down-list).

Move between a brackets pair:

C-M-n for forward match and C-M-u for backward match.
==Operating rectangles==
Rectangle commands operate on rectangular areas of the text: all the characters between a certain pair of columns, in a certain range of lines.

To specify a rectangle for a command to work on, set the mark at one corner and point at the opposite corner. If point and the mark are in the same column, the region-rectangle is empty. If they are in the same line, the region-rectangle is one line high.

C-x r k

Kill the text of the region-rectangle, saving its contents as the “last killed rectangle” (kill-rectangle).

C-x r d

Delete the text of the region-rectangle (delete-rectangle).

C-x r y

Yank the last killed rectangle with its upper left corner at point (yank-rectangle).

C-x r o

Insert blank space to fill the space of the region-rectangle (open-rectangle). This pushes the previous contents of the region-rectangle to the right.

C-x r N

Insert line numbers along the left edge of the region-rectangle (rectangle-number-lines). This pushes the previous contents of the region-rectangle to the right.

C-x r c

Clear the region-rectangle by replacing all of its contents with spaces (clear-rectangle).

M-x delete-whitespace-rectangle

Delete whitespace in each of the lines on the specified rectangle, starting from the left edge column of the rectangle.

C-x r t string 

Replace rectangle contents with string on each line (string-rectangle).

M-x string-insert-rectangle string 

Insert string on each line of the rectangle.

==Spell checking==

M-x ispell

Check and correct spelling of all words in the buffer. If the region is active, do it for all words in the region instead.

M-x flyspell-mode

Enable Flyspell mode, which highlights all misspelled words.

M-x flyspell-prog-mode

Enable Flyspell mode for comments and strings only.

Spell correcting

Skip this word—continue to consider it incorrect, but don’t change it here.

a

Accept the incorrect word—treat it as correct, but only in this editing session.
==Undo and redo==
Emacs has a powerful undo system. It allows you to recover any past state of a buffer.

C-_

undo

C-g C-_

redo after a undo

Performing some commands after a sequence of undo, all the undos are pushed to the operation stack, and the next undo undoes the last command. Multiple C-_ to redo what have been undone by C-_.
==Display line numbers==
Display line numbers:

M-x linum-mode

or

M-x global-linum-mode

To enable it by default

Add

(global-linum-mode t)

to ‘~/.emacs’.

==Position the screen==
We can position the screen by

C-l

Invoking ‘C-l’ multiple times makes Emacs position the current line at the middle, top and bottom of the screen iteratively.
==Replace in Emacs==
Interactive find and replace

M-x query-replace

or

M-%

Batch replace

M-x replace-string

==Set Emacs’s font size==
To set the font size to 12pt, put this line into ‘~/.emacs’:

(set-face-attribute 'default nil :height 120)

The value is in 1/10pt.

Increase/decrease current instance of Emacs’s font size:

C-x C-+

and

C-x C--

==Hide Emacs’ toolbar / menubar==
To hide the toolbar completely, put this line into ‘~/.emacs’:

(tool-bar-mode -1)

To hide the menubar:

(menu-bar-mode -1)

You can also toggle it by

M-x tool-bar-mode

or

M-x menu-bar-mode

==Kill a line without moving the cursor position==
1. Using 2 ‘C-k’ with ‘C-a’ first can kill the current line. But there are easier methods as follows.

2. Use ‘kill-whole-line’

C-S-Backspace

C-S-backspace (kill-whole-line) kills a whole line and its newline, no matter where the point within the line is.

However, many text terminals will prevent you from typing the key sequence C-S-backspace.

3. Define your own key bindings

I prefer ‘C-c C-x’ to kill a whole line by putting this line into ‘~/.emacs’:

(global-set-key "C-cC-x" 'kill-whole-line)

==Duplicate a line in Emacs==
Method 1. Using the keyboard

First, kill the current line (the line to duplicate)

C-S-backspace

Then, yank it at the position where it should be duplicated

C-y

Method 2. Define a function and bind it to ‘C-c C-k’:

    (defun copy-line (arg)
      "Copy lines (as many as prefix argument) in the kill ring"
      (interactive "p")
      (kill-ring-save (line-beginning-position)
                      (line-beginning-position (+ 1 arg)))
      (message "%d line%s copied" arg (if (= 1 arg) "" "s")))
   ;; optional key binding
   (global-set-key "C-cC-k" 'copy-line)

Script reference: http://emacswiki.org/emacs/CopyingWholeLines

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

18 comments

  1. Auto completion in Emacs:

    # yum install emacs-auto-complete*

    Complete by

    TAB

    or RET

    Useful keys:

    M-n

    M-p

    M-1
    M-2

  2. Generate ETAGS in Emacs:

    Add to ~/.emacs

    ;; =================== etags =====================
    (defvar tags-cmd "etags -R ./* 2>/dev/null")
    
    (defun regen-tags ()
      "Regenerate the tags file for the current working directory"
      (interactive)
      (let ((tag-file (concat default-directory "TAGS")))
        (shell-command tags-cmd)
        (visit-tags-table tag-file)))
    ;; =================== end etags =====================
    

    To regnerate ETAGS:

    M-x regen-tags

  3. Goto a specific line:

    Emacs supports jumping to a specific line:

    M-g M-g

    Then enter the line number and RET.

  4. Jump to next and previous error

    In the compile mode, you can jump to the next/previous error in the compile buffer by:

    M-g M-n

    and

    M-g M-p
  5. Jump to beginning and end of a function

    The functions beginning-of-defun and end-of-defun works with most programming modes in Emacs that jumps to the beginning and end of the function/class definition.

    The commands are

    C-M-a

    and

    C-M-e

    This will make editing code much easier.

    1. Moving in the Parenthesis Structure

      Move over groupings delimited by parentheses (or whatever else serves as delimiters in the language you are working with):

      C-M-n
      Move forward over a parenthetical group (forward-list).
      C-M-p
      Move backward over a parenthetical group (backward-list).
      C-M-u
      Move up in parenthesis structure (backward-up-list).
      C-M-d
      Move down in parenthesis structure (down-list).

      Move between a brackets pair:

      C-M-n for forward match and C-M-u for backward match.

  6. Operating rectangles.

    Rectangle commands operate on rectangular areas of the text: all the characters between a certain pair of columns, in a certain range of lines.

    To specify a rectangle for a command to work on, set the mark at one corner and point at the opposite corner. If point and the mark are in the same column, the region-rectangle is empty. If they are in the same line, the region-rectangle is one line high.

    C-x r k
    Kill the text of the region-rectangle, saving its contents as the “last killed rectangle” (kill-rectangle).
    C-x r d
    Delete the text of the region-rectangle (delete-rectangle).
    C-x r y
    Yank the last killed rectangle with its upper left corner at point (yank-rectangle).
    C-x r o
    Insert blank space to fill the space of the region-rectangle (open-rectangle). This pushes the previous contents of the region-rectangle to the right.
    C-x r N
    Insert line numbers along the left edge of the region-rectangle (rectangle-number-lines). This pushes the previous contents of the region-rectangle to the right.
    C-x r c
    Clear the region-rectangle by replacing all of its contents with spaces (clear-rectangle).
    M-x delete-whitespace-rectangle
    Delete whitespace in each of the lines on the specified rectangle, starting from the left edge column of the rectangle.
    C-x r t string
    Replace rectangle contents with string on each line (string-rectangle).
    M-x string-insert-rectangle
    string
    Insert string on each line of the rectangle.

  7. Spell checking

    M-x ispell
    Check and correct spelling of all words in the buffer. If the region is active, do it for all words in the region instead.

    M-x flyspell-mode
    Enable Flyspell mode, which highlights all misspelled words.

    M-x flyspell-prog-mode
    Enable Flyspell mode for comments and strings only.

    Spell correcting


    Skip this word—continue to consider it incorrect, but don’t change it here.

    a
    Accept the incorrect word—treat it as correct, but only in this editing session.

    1. Undo and redo

      Emacs has a powerful undo system. It allows you to recover any past state of a buffer.

      C-_
      undo

      C-g C-_
      redo after a undo

      Performing some commands after a sequence of undo, all the undos are pushed to the operation stack, and the next undo undoes the last command. Multiple C-_ to redo what have been undone by C-_.

  8. Display line numbers

    Display line numbers:

    M-x linum-mode
    

    or

    M-x global-linum-mode
    

    To enable it by default

    Add

    (global-linum-mode t)
    

    to ‘~/.emacs’.

  9. Position the screen

    We can position the screen by

    C-l

    Invoking ‘C-l’ multiple times makes Emacs position the current line at the middle, top and bottom of the screen iteratively.

  10. Replace in Emacs

    Interactive find and replace

    M-x query-replace

    or

    M-%

    Batch replace

    M-x replace-string
  11. Set Emacs’s font size

    To set the font size to 12pt, put this line into ‘~/.emacs’:

    (set-face-attribute 'default nil :height 120)

    The value is in 1/10pt.

    Increase/decrease current instance of Emacs’s font size:

    C-x C-+

    and

    C-x C--
  12. Hide Emacs’ toolbar / menubar

    To hide the toolbar completely, put this line into ‘~/.emacs’:

    (tool-bar-mode -1)

    To hide the menubar:

    (menu-bar-mode -1)

    You can also toggle it by

    M-x tool-bar-mode

    or

    M-x menu-bar-mode
  13. Kill a line without moving the cursor position

    1. Using 2 ‘C-k’ with ‘C-a’ first can kill the current line. But there are easier methods as follows.

    2. Use ‘kill-whole-line’

    C-S-Backspace

    C-S-backspace (kill-whole-line) kills a whole line and its newline, no matter where the point within the line is.

    However, many text terminals will prevent you from typing the key sequence C-S-backspace.

    3. Define your own key bindings

    I prefer ‘C-c C-x’ to kill a whole line by putting this line into ‘~/.emacs’:

    (global-set-key "C-cC-x" 'kill-whole-line)
  14. Duplicate a line in Emacs

    1. Using the keyboard

    First, kill the current line (the line to duplicate)

    C-S-backspace

    Then, yank it at the position where it should be duplicated

    C-y

    2. Define a function and bind it to ‘C-c C-k’:

        (defun copy-line (arg)
          "Copy lines (as many as prefix argument) in the kill ring"
          (interactive "p")
          (kill-ring-save (line-beginning-position)
                          (line-beginning-position (+ 1 arg)))
          (message "%d line%s copied" arg (if (= 1 arg) "" "s")))
       ;; optional key binding
       (global-set-key "C-cC-k" 'copy-line)
    

    Reference: http://emacswiki.org/emacs/CopyingWholeLines

Leave a Reply

Your email address will not be published. Required fields are marked *