Emacs text-editor setup for Python development plus a total beginner’s guide

Last week I decided it was time to switch to a more serious text editor. I already had my research done so all I had to do is start using Emacs. I knew that it will have a steep learning curve so I was prepared for what was to come. Of course in a few days, all I could get were a few information, but it got me to the stage where I can customize it and use it on a regular basis. Long story short I’m not an expert but I got things done.

I’ll split this article into 2 parts. The first one is for people who use Emacs but only need a list of packages, and the second is for newbies.

I. Python specific packages for people already familiar to Emacs

I had a little help from Jessica Hamrick and John D. Cook so here is the list of the packages to install or activate:

If you have any other suggestions feel free to add them in the comments. There was also a discussion on G+ Python Group.

II. How to customize Emacs(24) for Python – a total beginner’s tutorial

Learn how to use the shortcuts

If you don’t already know this, Emacs is optimized for keyboard use. So you won’t need the mouse. :)
A common subject of misunderstanding for newcomers is the keyboard shortcuts usage. All you have to know is how to read them(the shortcuts). So C-h is Ctrl+h and M-x is Alt(Command)+x. (M stands for meta). For example, a command like C-h t is Ctrl+h followed by t and RETurn(Enter). M-x quit-window means you have to press Alt(Command)+x and type quit-window after that, followed by RET(Enter).

Read the Emacs tutorial

Emacs has a great tutorial that teaches you how to navigate and some other basic things. Don’t try to be smart and skip it. It was written/improved over the years and it is a must for all Emacs newbies.
So press C-h t and read it!

Learn about Emacs customization

Emacs customization file is named .emacs and it’s being located in the /home/[your-name] folder(aka your home folder) on Ubuntu or other Gnu/Linux OS. There is also a .emacs.d folder where all the packages are being installed.

For Windows I cite from the official website:

On Windows, the .emacs file may be called _emacs for backward compatibility with DOS and FAT filesystems where filenames could not start with a dot. Some users prefer to continue using such a name, because Explorer cannot create a file with a name starting with a dot, even though the filesystem and most other programs can handle it. In Emacs 22 and later, the init file may also be called .emacs.d/init.el. Many of the other files that are created by lisp packages are now stored in the .emacs.d directory too, so this keeps all your Emacs related files in one place.

All the files mentioned above should go in your HOME directory. The HOME directory is determined by following the steps below:

  1. If the environment variable HOME is set, use the directory it indicates.
  2. If the registry entry HKCU\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates.
  3. If the registry entry HKLM\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates. Not recommended, as it results in users sharing the same HOME directory.
  4. If C:\.emacs exists, then use C:/. This is for backward compatibility, as previous versions defaulted to C:/ if HOME was not set.
  5. Use the user’s AppData directory, usually a directory called Application Data under the user’s profile directory, the location of which varies according to Windows version and whether the computer is part of a domain.

Within Emacs, <~> at the beginning of a file name is expanded to your HOME directory, so you can always find your .emacs file with C-x C-f ~/.emacs.

Add package archive links

For those used with Ubuntu this may seem familiar. Basically you add the links for package installation.
Add to your .emacs file the following lines:

(require 'package)
(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
                         ("marmalade" . "http://marmalade-repo.org/packages/")
                         ("melpa" . "http://melpa.milkbox.net/packages/")))

These are the links to Elpa, Marmelade and Melpa.

Now you can see a list of packages by using M-x package-list-packages.

If you wand to install a new package type M-x package-install RET, and type the name of the package. If you don’t remember the exact name of the package you wanted to install press TAB (M-x package-install RET and TAB afterwards). You will be prompted a window with all the possible  completions. [You can use TAB anytime you don't know what to type next.]

Choose your Emacs theme

Use M-x customize-themes and try some themes. Chose one you like. If you don’t like any of the default ones, you can also install your theme using package.

Some popular themes are Zenburn themes. To install them, press M-x package-install zenburn-theme (First M-x Package-install, press Enter and then zenburn-theme. From now on this will be the preferred way of writing composed key shortcuts.) To load it automatically on Emacs startup, add this to your .emacs file:

(load-theme 'zenburn t)

[later edit] If you have problems loading the theme take a look at Santiago’s comment.

Set Emacs to start fullscreen

By default Emacs starts in a minimized window. To change this add the following lines to the .emacs file:

(defun toggle-fullscreen ()
  (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
	    		 '(2 "_NET_WM_STATE_MAXIMIZED_VERT" 0))
  (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
	    		 '(2 "_NET_WM_STATE_MAXIMIZED_HORZ" 0))

Set Emacs to save buffers on exit

Emacs starts a new session every time you open it. To remember your buffers(files) after restart add the following to your .emacs file:

(require 'desktop)
  (desktop-save-mode 1)
  (defun my-desktop-save ()
    ;; Don't call desktop-save-in-desktop-dir, as it prints a message.
    (if (eq (desktop-owner) (emacs-pid))
        (desktop-save desktop-dirname)))
  (add-hook 'auto-save-hook 'my-desktop-save)

Enable ido-mode

Ido-mode(InteractivelyDoThings) is installed by default. It helps you with auto-completion when you want to change between buffers and other things. If you want to find out more read the docs. :D
To enable it add these lines to your .emacs file:

(require 'ido)
(ido-mode t)

Color your shell text

If you use Emacs there is a very high probability you use your terminal often(or you intend to do). If you want your Emacs terminal emulator to have some colors add to your .emacs file the line:

(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)

To open your terminal in a new buffer type: M-x term. It is worth mentioning that Emacs supports multiple different shells. Read this article from Mastering Emacs to find out more about it.

Install el-get

El-get is similar to package.el(package) except for the fact that it automatically installs all the dependencies. So you don’t have to care about anything else when you install a package.
To install it, change to your scratch buffer by typing C-x b scratch RET. Paste this code in by yanking (type C-y):

;; So the idea is that you copy/paste this code into your *scratch* buffer,
;; hit C-j, and you have a working developper edition of el-get.
 (lambda (s)
   (let (el-get-master-branch)
     (goto-char (point-max))

Hit C-j to execute.
Add these lines to your .emacs file:

(add-to-list 'load-path "~/.emacs.d/el-get/el-get")
(unless (require 'el-get nil 'noerror)
    (let (el-get-master-branch)
      (goto-char (point-max))
(el-get 'sync)

You’re done. To list all the packages M-x el-get-list-packages. If you want to install something from el-get repo just M-x el-get-install and type the name of the package.

Install Jedi.el

Jedi.el is a Python auto-completion package for Emacs.
To install it you first have to install virtualenv. If ou are on Ubuntu:

sudo apt-get install python-virtualenv

If you use Windows check the documentation or first install pip and after that

pip install virtualenv

Now you can install Jedi using el-get: M-x el-get-install jedi
To enable Jedi add to your .emacs file:

(add-hook 'python-mode-hook 'auto-complete-mode)
(add-hook 'python-mode-hook 'jedi:ac-setup)

If you encounter any problems follow the instructions from the troubleshooting section. Jedi has a very good documentation and the developer behind this project is very helpful.

Install Flycheck

Flycheck (aka “Flymake done right”) is a modern on-the-fly syntax checking extension for GNU Emacs 24.
Install it using package: M-x package-install flycheck.
Add to your .emacs file:

(add-hook 'after-init-hook #'global-flycheck-mode)

Install Autopair

Autopair is an extension to the Emacs text editor that automatically pairs braces and quotes.
Install it using package: M-x package-install autopair.
Add to your .emacs file:

(require 'autopair)
(autopair-global-mode) ;; to enable in all buffers

Horray! You’re done.
This is my personal Emacs configuration kept up to date.
If you get in any trouble, your package doesn’t work, you don’t know how to use it or customize it, check the documentation. If that doesn’t help search or ask StackOverflow. Someone will help you eventually or you will be able to solve the problem by yourself after reading a few answers.

If you are using Sublime Text and you think that is a powerful text editor, think twice. Read the answers from Quora. Also support the community and spread the knowledge.

Here is a list of communities and resources dedicated to Emacs:
Google plus
Emacs WIKI

17 thoughts on “Emacs text-editor setup for Python development plus a total beginner’s guide

  1. John

    You’ve jumped into the deep end after only a week! After I’d been using Emacs for a week I was still trying to remember how to move the cursor around. :)

    1. caisah Post author

      :) That is all I’ve done for a whole week. I wanted to get the basics so I could use it every day ASAP. I’m also looking forward to reading the book, but given the tight schedule I’m on, I don’t know if that’s something I’ll be able to do soon. Thanks for the comment and the blog post :)

  2. John

    I could never get el-get to work on Windows. But elpy works just fine, Windows and Linux. Elpy installs with the Emacs 24 package manager without requiring el-get.

    1. caisah Post author

      I see… I guess it’s ok. If I haven’t tried it I can’t say anything about it.

      Anyway I think whatever makes your life easier it’s fine. :)

  3. Kevin Chabreck

    Awesome post! I’ve been using Emacs for years, and a good number of these packages are new to me. Thanks for sharing your knowledge.

    Additionally, if you haven’t done so yet, I heavily recommend writing some Emacs commands. This was a mind-blowing feature for me when I discovered it, and I use many of my custom commands as much or more often than the default shortcuts.

    For example, adding the following code to your .emacs file will define a function that inserts the current date at the cursor position.
    (defun insert-date ()
    (insert (format-time-string "%m/%d/%Y")))

    It can be bound to a key sequence (I chose Ctrl-c, d) with this line of code (also placed in .emacs):
    (global-set-key (kbd "C-c d") 'insert-date)

    Hope this is helpful to someone, and thanks again for the informative post. A word of warning, though: Tweaking your Emacs environment is much, much more addictive than it seems.

    1. caisah Post author

      Ooo, thanks for the suggestion. I have to start learning some elisp. It’s definitely one of my priorities now. Ass for the addiction you were mentioning, you are most certainly right. I feel a constant urge to tinkering it. :)

      Thanks for dropping by and for the comment. I’m glad this post helped you.

  4. milan

    I have an issue following your beginner part, first step. After adding the:

    (require 'package)
    (setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
    ("marmalade" . "http://marmalade-repo.org/packages/")
    ("melpa" . "http://melpa.milkbox.net/packages/")))

    to .emacs (I had to create .emacs as it wasn’t there), starting the emacs gives the following error:

    Warning (initialization): An error occurred while loading `/home/milan/.emacs':

    File error: Cannot open load file, package

    To ensure normal operation, you should investigate and remove the
    cause of the error in your initialization file. Start Emacs with
    the `--debug-init' option to view a complete error backtrace.

    Running emacs with debug-init shows the following:
    Debugger entered--Lisp error: (file-error "Cannot open load file" "package")
    eval-buffer(# nil "/home/milan/.emacs" nil t) ; Reading at buffer position 37
    load-with-code-conversion("/home/milan/.emacs" "/home/milan/.emacs" t t)
    load("~/.emacs" t t)
    #[nil "\205\264...



  5. Jess Hamrick

    Glad you found my post useful! I’m impressed you were able to get everything up and running after only using Emacs for a week — I definitely wasn’t competent enough to start installing plugins after a week :-)

    Thanks for the tip about jedi.el; I’ve only used autocomplete.el but it doesn’t always work so well on it’s own for Python. Though, it looks like jedi.el is maybe integrated into Emacs IPython Notebook (written by the same guy), which I do use (and I highly recommend!), so maybe I have unknowingly used it. Anyway, I will have to give it a try!

    1. caisah Post author

      Thanks for the comment and the blog post. Is the first one I found about customizing Emacs for Python and it also inspired me to write this one. :)

  6. Takafumi

    Jedi.el author here. It’s nice to see my plugin in a blog post.

    If you are using IPython, my another plugin called EIN (https://github.com/tkf/emacs-ipython-notebook) could be useful too. You can get richer interaction with IPython’s features than the plain inferior-python-mode.

    pydoc-info (https://bitbucket.org/jonwaltman/pydoc-info/) is also useful. I don’t know if you can call it for beginners because it is for people who want to stay in Emacs. You can jump to texinfo version of Python documentation from Python buffers. You don’t need to open browser to quickly look up something in the Python reference.


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>