Emacs: Init File Tutorial

By Xah Lee. Date: . Last updated: .

This page shows you how to set up many preferences in emacs.

The following assume you are using GNU Emacs version 24.1 or later. [see Emacs 24.1 New Features (released 2012-06)]

What's Init File?

Emacs init file is a file emacs loads when it starts up. It is used to customize emacs.

Emacs init file is also known as “dot emacs file”.

Where's Init File?

By default, there is no init file. You have to create the file yourself, and add things to it.

Create a file with this content:

(set-background-color "honeydew")

Save it at ~/.emacs.d/init.el

On linux and Mac, by default, emacs look for init file at

  1. ~/.emacs
  2. ~/.emacs.el
  3. ~/.emacs.d/init.el (this is modern, preferred, since ~2010)

On Microsoft Windows:

[see Emacs in Microsoft Windows FAQ]

It's ok to delete your init file and start over. (make a backup first in case you want it back.)

(info "(emacs) Init File")

Start Emacs Without Loading Init File

You can start emacs without loading init file. This is useful if you made a syntax error in your init file.

# start emacs without any init file
emacs -Q

For Microsoft Windows, you can create a alias of the emacs icon, and in properties, set the launch options. [see Emacs in Microsoft Windows FAQ]

(info "(emacs) Initial Options")

Modify Init File Without Restarting Emacs

Most of the time, you do not need to restart emacs.

After you added some new code to init file, just select the region, then Alt+x eval-region.

Then, the code/preference you added will become effective immediately.

[see Evaluate Emacs Lisp Code]

Reload Init File

To reload init file:

Alt+x eval-buffer


Alt+x load-file

Note, some packages, or elisp code, may behave differently when loaded twice. And some code may not work by simply running it by itself (it may assume some other code has been run before or after.).

If you have a problem, restart emacs.

Text Editing

How to have standard keyboard shortcuts for Copy and Paste?

Alt+x cua-mode to toggle it on/off.

Put this in your emacs init file:

;; make {copy, cut, paste, undo} have {C-c, C-x, C-v, C-z} keys
(cua-mode 1)

How to have standard keyboard shortcuts for {Open, Close, Save, Save As, Select All, …}?

You can try the following, but they don't work well, because some major mode or minor will override these keys, and you lost some default emacs cursor movement keys.

 ;; make emacs use standard keys

  ;; Select All. was move-beginning-of-line
  (global-set-key (kbd "C-a") 'mark-whole-buffer-buffer)

  ;; Find. was forward-char
  (global-set-key (kbd "C-f") 'isearch-forward)

  ;; New. was next-line
  (global-set-key (kbd "C-n") 'xah-new-empty-buffer)

  ;; New Window. was nil
  (global-set-key (kbd "C-S-n") 'make-frame-command)

  ;; Open. was open-line
  (global-set-key (kbd "C-o") 'ido-find-file)

  ;; Save. was isearch-forward
  (global-set-key (kbd "C-s") 'save-buffer)

  ;; Save As. was nil
  (global-set-key (kbd "C-S-s") 'write-file)

  ;; Paste. was scroll-up-command
  (global-set-key (kbd "C-v") 'yank)

  ;; Close. was kill-region
  (global-set-key (kbd "C-w") 'kill-buffer)

  ;; Redo. was yank
  (global-set-key (kbd "C-y") 'redo)

  ;; Undo. was suspend-frame
  (global-set-key (kbd "C-z") 'undo)

For the command xah-new-empty-buffer, get it at Emacs: New Empty Buffer.

For the command redo, install redo mode. [see Emacs: Best Undo/Redo Mode]

A robust solution is to install the package ergoemacs-mode. https://ergoemacs.github.io/

or xah-fly-keys. [see Emacs: Xah Fly Keys]

How to have redo?

To redo, press Ctrl+g then do a undo 【Ctrl+_】. Further undo will all be redo. Press Ctrl+g to reverse direction again.

See also: Emacs: Best Undo/Redo Mode

How to make the copy key copy the current line when there's no selection?

Emacs: How to Copy/Cut Current Line

How to auto insert right bracket?

;; auto insert closing bracket
(electric-pair-mode 1)

[see Emacs: electric-pair-mode]

How to make cursor movement stop between camelCase?

;; make cursor movement stop in between camelCase words.
(global-subword-mode 1)

[see Emacs: Move Cursor by camelCase, snake_case]

How to make typing overwrite selected text?

;; make typing delete/overwrites selected text
(delete-selection-mode 1)

Text Highlight

How to have cursor line always highlighted?

emacs hl-line-mode screenshot 2015-08-12
emacs global-hl-line-mode

Alt+x hl-line-mode to toggle on/off for current buffer.

Alt+x global-hl-line-mode to toggle globally.

;; turn on highlighting current line
(global-hl-line-mode 1)

How to have matching parenthesis highlighted? (when the cursor is on one)

emacs show paren mode parenthesis 33045
emacs show-paren-mode, highlight brackets

Put the following code in your emacs init file:

;; turn on bracket match highlight
(show-paren-mode 1)

[see Emacs: Highlight Brackets ()[]{}]

How to remember cursor position?

;; remember cursor position, for emacs 25.1 or later
(save-place-mode 1)


;; remember cursor position. When file is opened, put cursor at last position
(if (version< emacs-version "25.0")
      (require 'saveplace)
      (setq-default save-place t))
  (save-place-mode 1))

[see Emacs: Save Cursor Position]

File Encoding

How to set default file encoding?

;; UTF-8 as default encoding
(set-language-environment "UTF-8")
(set-default-coding-systems 'utf-8)

Do not add a bunch of other variables such as set-terminal-coding-system, unless you know emacs's encoding system well.

[see Emacs: Unicode Tutorial]

[see Unicode Basics]


How to change default font?

Emacs: Font Setup

Displaying Line Numbers and Column Number

How to show line numbers?

emacs display line numbers mode 23786
emacs. Alt+x global-display-line-numbers-mode

[see Emacs: Show Line Numbers]

How to show the cursor's column position?

emacs column number mode 56206
Alt+x column-number-mode
;; show cursor position within line
(column-number-mode 1)

[see Emacs: Show Cursor Position]

Stop Backup File

How to disable emacs's automatic backup~ file?

Put this code in your emacs init file:

;; stop creating those backup~ files
(setq make-backup-files nil)

How to disable emacs's “#auto-save#” backup?

;; stop creating those #auto-save# files
(setq auto-save-default nil)

Note: emacs's “auto-save” isn't automatic save in the normal sense. When you are editing a file, emacs automatically creates a “backup” copy of it, named “#file_name#”, and periodically updates it. When you actually save the file, this “#auto-saved#” file is then deleted.

This emacs “auto-save” feature, is for in case there's a power failure.

How to set emacs so that all backups are placed into one backup folder?

Emacs: Set Backup into a Directory

How to stop emacs's backup changing the file's creation date of the original file?

Put this code in your emacs init file:

(setq backup-by-copying t)

Explanation: when emacs does a backup, by default it renames the original file into the backup file name, then create a new file and insert new file content into it. This effectively destroys the creation date of your file. (If a file is created in 2001, and you modified it today, the file's creation date will become today. Note: unixes (including Linux and BSD) do not record file creation date, so this doesn't matter. (ctime is not creation date.) Microsoft Windows and Mac OS X do record file creation date.).

How to refresh file automatically?

Sometimes other program may have changed file that is already opened in emacs.

To refresh, Alt+x revert-buffer

To always refresh automatically, put this in your emacs init file:

;; when a file is updated outside emacs, make it update if it's already opened in emacs
(global-auto-revert-mode 1)

Open Recently Opened Files

How to open recently opened file in emacs?

Alt+x recentf-mode to turn it on. Then, Alt+x recentf-open-files to list and open recently opened file. You can give it a keyboard shortcut. [see Emacs: How to Define Keys]

To turn it on for future sessions, put this in your emacs init file:

;; keep a list of recently opened files
(require 'recentf)
(recentf-mode 1)

[see Emacs: Open Recently Opened File]

How to restore opened files from last session?

Alt+x desktop-save-mode

;; save/restore opened files
(desktop-save-mode 1)

[see Emacs: Restore Opened Files, Windows Config]

How to re-open last closed file?

Emacs: Open Last Closed File

Tabs, Space, Indentation, Keyword Completion

How to setup tabs, space, indentation?

Emacs: Tabs, Space, Indentation Setup

How to show tabs as in web browser?

You need to install tabbar-mode.

[see Emacs: How to Install Packages Using ELPA, MELPA]

You can also install “tabbar-ruler” to make it pretty.

emacs tabbar screenshot 2013-04-20
Emacs tabbar screenshot

Note: from my experience, tabbar-mode slows down emacs noticeably. This is so at least from 2008 to 2014.

Line Margin, Line Wrap, Line Spacing

How to have the down arrow key move by screen lines?

This is default with emacs 23. [see Emacs 23.1 New Features (released 2009-07)]

(setq line-move-visual nil)
;; t means true, nil mean false

How to have lines soft wrapped at word boundary?

Alt+x visual-line-mode.

emacs23 word wrap
visual-line-mode off (top) and on (bottom) in emacs 23.

To toggle globally, Alt+x global-visual-line-mode.

To turn on global-visual-line-mode always, put this in your init:

;; wrap long lines by word boundary, and arrow up/down move by visual line, etc
(global-visual-line-mode 1)

[see Emacs: Visual Line Mode, Wrap Lines]

[see Emacs: Novel Reading Mode]

How to adjust margin?

You can use this command:

(defun xah-toggle-margin-right ()
  "Toggle the right margin between `fill-column' or window width.
This command is convenient when reading novel, documentation."
  (if (eq (cdr (window-margins)) nil)
      (set-window-margins nil 0 (- (window-body-width) fill-column))
    (set-window-margins nil 0 0) ) )

How to make lines NOT soft-wrap?

emacs toggle truncate lines 61581
emacs Alt+x toggle-truncate-lines

Alt+x toggle-truncate-lines.

When toggle-truncate-lines is on, lines runs off and disappears on the right window margin. You have to horizontal scroll right to see them. This is useful when you just want to get an overview of lines.

Note: the command name is misleading. It doesn't really “truncate”. Proper name would be “toggle-line-softwrap”.

How to set the spacing between lines?

Emacs: Set Line Spacing

Format Lines

How to reformat lines so that lines are not longer than 70 chars?

emacs fill paragraph 80995
emacs Alt+x fill-paragraph

Alt+x fill-paragraphAlt+q】 to reformat the current block of text your cursor is on.

Alt+x fill-region to reformat a text selection.

To have emacs automatically insert a newline char when your line reaches to the right, Alt+x auto-fill-mode.

The variable fill-column controls the width used in the above commands. Alt+x set-variable, to change value.

Note: these commands insert newline characters into your file. This type of wrapping is called hard-wrap. Hard-wrap convention of 80 chars came from punched card. You should avoid hard-wrap when possible; add newline char only at logical positions. (Rant: The Harm of hard-wrapping Lines.)

How to unfill-paragraph? I want to remove line-break in a paragraph.

Emacs: Hard Wrap Lines

How to make sentence ending by single space?

When Alt+x fill-paragraph etc, emacs will reformat it so that there are 2 spaces after a period.

;; make sentence ending by single space
(setq sentence-end-double-space nil )

[see Emacs: Hard Wrap Lines]


How to have fixed scroll?

Alt+x scroll-lock-mode. When on, up/down arrow keys move the page, instead of the cursor.

This only turns it on in current buffer.

isearch, Make Space Hyphen Lowline Equivalent

Emacs Isearch Whitespace Regex

Type y/n instead of yes/no

Many emacs commands will ask you a “yes/no” question, and you have to type the full word “yes” or “no”. (such as when deleting a file)

You can make emacs just ask “y/n” instead.

(defalias 'yes-or-no-p 'y-or-n-p)

disable warnings

Emacs by default will warn you when you use some commands for the first time. You have to answer yes or no. They are annoying.

Here's how to disable them:

  ;; stop warning prompt for some commands. There's always undo.
  (put 'narrow-to-region 'disabled nil)
  (put 'narrow-to-page 'disabled nil)
  (put 'upcase-region 'disabled nil)
  (put 'downcase-region 'disabled nil)
  (put 'erase-buffer 'disabled nil)
  (put 'scroll-left 'disabled nil)
  (put 'dired-find-alternate-file 'disabled nil)

Ido Mode Setup

Emacs: Ido Mode

Icomplete Mode Setup

Emacs: Icomplete Mode

Dired Mode Setup


How to save/store minibuffer history?

Many emacs commands lets you use key to use last command or parameter. But after you restart emacs, command history is forgotten.

You can make emacs remember command history.

;; save minibuffer history
(savehist-mode 1)

Command history is saved as a file, by default at ~/.emacs.d/history

How to set minibuffer height?

;; big minibuffer height, for ido to show choices vertically
(setq max-mini-window-height 0.5)

How to stop cursor going into minibuffer prompt?

Emacs: Stop Cursor Going into Minibuffer Prompt


How to stop cursor blinking?

;; make cursor not blink
(blink-cursor-mode 0)

How to set cursor to i-beam?

(modify-all-frames-parameters (list (cons 'cursor-type 'bar)))

Note: this will not work if you run emacs in terminal.

How to set up emacs so that each file opens in a new window?

Put this code in your emacs init file:

(setq pop-up-frames t)

How to set color theme?

Emacs: Set Color Theme

How to show CSS hex color spec in color?

emacs hexcode highlight 32718
emacs hexcode highlight

[see Emacs: Working with CSS Color Values]

hippie-expand setup

(setq hippie-expand-try-functions-list
        ;; try-expand-dabbrev-from-kill
        ;; try-expand-all-abbrevs
        ;; try-expand-list
        ;; try-expand-line

Emacs Keybinding Customization

Emacs: How to Define Keys

Mouse Buttons Customization

Emacs: How to Set Mouse Buttons.

Default Window (frame) Size

Emacs: Set Default Window Size

Org Mode Customization

Emacs: Org Mode Customization

Whitespaces mode setup

Emacs: Make Whitespaces Visible

ELPA Package setup

Emacs: How to Install Packages Using ELPA, MELPA

much thanks to jcs. http://irreal.org/blog/

Thanks to Ivan Kozik (http://ludios.org/ivank/) for a tip.

Emacs Customization

  1. Emacs init file
  2. Install Packages
  3. Install Package Manually
  4. Define Keys
  5. M-x customize
  6. What's Major Mode?
  7. What's Minor Mode?
  8. Set File to Open in a Major Mode
  9. Organize Init File
  10. Byte Compile Elisp
  11. What's Hook?
  12. Environment Variables in Emacs
  13. Set Default Window Size
  14. Font Setup
  15. Set Color Theme
  16. Turn Off Auto Backup
  17. Check OS, Version, Host Name
  18. Check Defined/Loaded

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp