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 ()
  (interactive)
  (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))
)
(toggle-fullscreen)

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 ()
    (interactive)
    ;; 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.
(url-retrieve
 "https://raw.github.com/dimitri/el-get/master/el-get-install.el"
 (lambda (s)
   (let (el-get-master-branch)
     (goto-char (point-max))
     (eval-print-last-sexp))))

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)
  (with-current-buffer
      (url-retrieve-synchronously
       "https://raw.github.com/dimitri/el-get/master/el-get-install.el")
    (let (el-get-master-branch)
      (goto-char (point-max))
      (eval-print-last-sexp))))
(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
Quora
StackOverflow

27 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. :)

    Reply
    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 :)

      Reply
  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.

    Reply
    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. :)

      Reply
        1. caisah Post author

          The font is one of these: Consolas, Monaco, Lucida Console, monospace for the code (don’t know what you have installed. I have monospace :) ) and one of: Open Sans, Helvetica, Arial, sans-serif for the article text.
          The colors are:

          • background: #666
          • yellow: #f0e68c
          • pink: #ffa0a0
          • green: #98fb98
          • red: #cd5c5c
          Reply
  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 ()
    (interactive)
    (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.

    Reply
    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.

      Reply
  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")
    require(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...

    command-line()
    normal-top-level()

    Thanks,

    Reply
  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!

    Reply
    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. :)

      Reply
      1. Jess Hamrick

        Yeah, when I was trying to get Emacs customized for Python myself there was a distinct lack of any recent guides — the stuff on emacswiki was somewhat outdated, and while I found a few blog posts they were from a few years ago and enough things had changed that I had to do a fair amount of fiddling on my own to get stuff to work. I’m glad my post is inspiring people to write their own guides on how to set this stuff up; it’s not always straightforward and as long as people keep writing stuff, there will be recent relevant information for others :-)

        Reply
  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.

    Reply
    1. caisah Post author

      Thanks for dropping by :) I will definitely take a look at the other suggested plugins. In the meantime keep up the good work and thank you for the time invested in writing, maintaining and supporting these packages.

      Reply
  7. Anton

    Hi,
    I’m getting an error message about autopair. I followed most of your install instructions, though I confess I was sort of trying to follow the instructions for Jessica Hamricks tutorial but using the package managers instead of installing from source. I then replaced my .emacs with the one you have on github in order to get things sorted and I get the following:

    Debugger entered–Lisp error: (file-error “Cannot open load file” “autopair”)
    require(autopair)
    eval-buffer(# nil “/home/anton/.emacs” nil t) ; Reading at buffer position 3136
    load-with-code-conversion(“/home/anton/.emacs” “/home/anton/.emacs” t t)
    load(“~/.emacs” t t)
    #[0 “\205\262

    Here is the contents of my ~/.emacs.d/

    anton@antt-hp:~$ ls .emacs.d/
    ac-comphist.dat auto-save-list el-get elpa
    anton@antt-hp:~$ ls .emacs.d/el
    el-get/ elpa/
    anton@antt-hp:~$ ls .emacs.d/el-get/
    auto-complete ctable deferred el-get epc fuzzy jedi popup python-mode rope ropemacs ropemode
    anton@antt-hp:~$ ls .emacs.d/elpa/
    archives autopair-20121123.1829 dash-20130819.1125 f-20130821.2204 flycheck-20130822.1252 ipython-2927 multi-term-20130108.2305 pkg-info-20130817.2334 python-mode-6.0.10 s-20130820.1601

    Any ideas?
    Thanks, Anton

    Reply
    1. caisah Post author

      I don’t know what the problem is but you should try to reinstall the package: M-x el-get-install autopair.

      If it doesn’t work, uninstall it and try smartparens instead.

      Reply

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>