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

  • How to detect whether Linux runs in UEFI or BIOS mode inside the Linux?

    How to detect whether Linux runs in UEFI or BIOS mode inside the Linux itself without needed to boot the the management console of the mother board? You can detect whether Linux runs in EFI mode by checking whether /sys/firmware/efi exist. In bash, you can test by [ -d /sys/firmware/efi/ ] This technique is used…

  • |

    GNU glibc Manual

    “The C language provides no built-in facilities for performing such common operations as input/output, memory management, string manipulation, and the like. Instead, these facilities are defined in a standard library, which you compile and link with your programs. The GNU C library, described in this document, defines all of the library functions that are specified…

  • Chinese Charactor Configuration on Fedora 11

    最新的更新版本请看: Fedora 中文字体设置. 使用Linux时我个人倾向使用英文环境系统,而Fedora11在英文环境下中文字体有时会不太好看,经常遇到需要字体优化美化的问题。 以下是我的配置方案,经测试效果还算不错,解决了Fedora 11 中文字体难看的问题: 方案1:使用uming和ukai字体,即AR PL UMing CN等。 关键是使用的字体包如下: 首先要安装这两个字体: cjkuni-ukai-fonts cjkuni-uming-fonts 然后配置一下~/.fonts.conf文件. 使sans-serif serif monospace字体中文使用uming/ukai即可. 我的.fonts.conf文件可以从这里下载(两种选择, 我喜欢前者): https://github.com/zma/config_files 使用Liberation和uming/ukai字体: .fonts.cofn.liberation 使用dejavu和uming/ukai字体: .fonts.conf.dejavu 下载后放到自己的$HOME下改名为.fonts.conf就可以了。 使用uming字体效果如下(请放大后看效果): 方案2:安装文泉驿字体,这个非常简单,安装相应包即可了。 如果喜欢其它的字体选择性的安装上就可以了,只要注意只安装自己需要的就行了。有人使用微软雅黑字体,首先这是侵权的,其次开源的字体做得其实已经很不错了。 最后将字体平滑选项打开, KDE和gnome都有相关设置方法。 以上内容只是针对使用xft字体系统的设置。对于使用核心字体系统的X程序来说字体依然会出现很丑的情况。 下面是针对emacs的设置方法: 首先需要安装这个字体包: xorg-x11-fonts-misc 注意到在中文系统下emacs的中文显示非常好,而在英文环境中去非常差,我们可以利用这一点,在运行emacs前首先将系统环境设为中文即可。 在~/bin/下建立一文件ema 内容如下: #!/bin/bash rm -f ~/.emacs ln -s ~/.emacs.x ~/.emacs LANG=zh_CN.UTF-8 emacs –fullheight -r $* 然后加入执行权限即可: chmod +x…

  • How to detect whether a file is readable and writable in Python?

    Before reading or writing a file, access should be checked first. How to detect whether a file is readable and writable in Python? You can use the os.access(path, mode) library function https://docs.python.org/release/2.6.6/library/os.html#os.access like the Linux access library function for C. It returns True if access is allowed, False if not. For readable and writable, you…

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 *