Emacs Tips and Howtos

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

Similar Posts

  • Micosoft招聘部分算法题

    Micosoft招聘部分算法题 1.链表和数组的区别在哪里? 2.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法? 3.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法? 4.请编写能直接实现strstr()函数功能的代码。 5.编写反转字符串的程序,要求优化速度、优化空间。 6.在链表里如何发现循环链接? 7.给出洗牌的一个算法,并将洗好的牌存储在一个整形数组里。 8.写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?) 9.给出一个函数来输出一个字符串的所有排列。 10.请编写实现malloc()内存分配函数功能一样的代码。 11.给出一个函数来复制两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。 12.怎样编写一个程序,把一个有序整数数组放到二叉树中? 13.怎样从顶部开始逐层打印二叉树结点数据?请编程。 14.怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)? 来源:·日月光华 bbs.fudan.edu.cn Read more: How to Connect to MySQL in JSP OCaml Learning Materials Inline Assembly with GCC on Linux Online Tutorials for Linux Beginners How to Run a Command Upon Files or Directories Changes on Linux Filter Salutation in…

  • How to find hard links to a file

    How to find hard links to a file in Linux? To find out all hard links to file1: $ find /home -xdev -samefile file1 Read more: http://linuxcommando.blogspot.com/2008/09/how-to-find-and-delete-all-hard-links.html Read more: How to get a FILE pointer from a file descriptor and how to get a file descriptor from a FILE pointer in C on Linux? How to…

  • How to get the full path and directory of a Makefile itself?

    How to get the full path and directory of a Makefile itself like finding Bash script’s own path? This 2 lines in Makefile get the full path and dir of the Makefile itself: mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST))) mkfile_dir := $(dir $(mkfile_path)) The piece of code gets you Makefile, finds its absolute path and the…

  • | | |

    Understanding the Raft Consensus Protocol

    The Raft consensus protocol is a distributed consensus algorithm designed to be more understandable than other consensus algorithms like Paxos. It ensures that a cluster of servers can agree on the state of a system even in the presence of failures. Key Concepts Raft divides the consensus problem into three relatively independent subproblems: Leader Election:…

  • |

    SmIley faces in iPhone

    How to input smiley faces in iPhone? I use Emoji Free app to enable the Emoji input methods. It is quite good and enables inputing of many nice smiley faces and icons. The app from App Store: Emoji Free app. Read more: Changing iPhone Holiday Calendar to Your Local One How to Play YouTube Video in…

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 *