Emacs for Python Programmers: Basics
At PyCon I noticed the usual discussion of IDEs, editors, and programming environments. There seems to be some sort of strange equilibrium going on whereby programmers are constantly fussing, switching and growing discontented with their programming editors. I've used Emacs for almost 10 years now and other than a brief (forced) stint with CodeWarrior in college, it has been my primary editor for coding, blogging, journaling. I even wrote a book in it.
But I'll admit, Emacs isn't exactly sexy and it certainly has a steep learning curve. I don't generally advocate it to people unless I think they'll have the patience to learn it. I also don't know anything about vim other than I constantly forget how to use it when I'm connected to a server that doesn't have Emacs. It seems cool enough, but I joined my text editing team a while ago.
There are also "real" IDEs like TextMate, Eclipse, Visual Studio, etc. These are all great, but last I checked they required their users to fork over some cash (except Eclipse). As a result I've never really given any of them much of a chance. I think they are probably great tools and you should use them if you like them.
The goal of this series of posts is to help resolve some of the mysteries people struggle with when switching to Emacs for Python development. It's particularly geared toward MacOS X users, since that's where I live, but most of the tips should work on Linux too. Windows users can consider it a rough guide, but your experience will likely be significantly different.
Emacs: What to Install
Emacs comes in (roughly) two varieties: GNU Emacs and XEmacs. GNU Emacs is typically the default on Linux and other UNIX systems. XEmacs, despite its name, is technically not tied to the X-Windows system. Both have terminal-style interfaces as well as graphical ones. And both varieties have ports to almost every operating system, including MacOS X. MacOS users also have Aquamacs at their disposal. This is a forked version of GNU Emacs that is written for Cocoa and includes a more Mac-like UI (tabs, toolbars, keyboard controls, &c).
There are too many differences between these Emacsen to go over. It's easy enough to try them all, but be warned there are many differences in the configuration and default set of elisp libraries for each. This guide will be designed for GNU Emacs, but Aquamacs users should be able to follow along as well, with a few differences.
My personal choice of Emacs for OS X is a Cocoa-port of GNU Emacs 23. The versions available at http://emacsformacosx.com are excellent. I use the 23.1 release package, but there are also pretest and nightly builds automatically compiled into OS X disk images available. Recent nightly builds are now 64-bit. The official GNU Emacs is more user-friendly than you might expect, includes a toolbar, and is worth a try if you're trying to decided between Aquamacs.
Python Editing
Once you're setup with Emacs, the next step is to figure out how to hack on Python code. To do this, we need a major mode for Python. A major mode is a set of Emacs Lisp functions and settings that configure the editor in a specific way. There can only be one major mode loaded per Emacs buffer at one time. One kind of major mode is for programming and almost all popular languages have a programming mode. Unfortunately when it comes to Python there are two major modes and this leads to immense confusion.
The two modes are python.el and python-mode.el. The original Python
editing mode, python-mode.el, was created by the Python
community. It is still actively maintained, though with some
focus on XEmacs. Emacs itself didn't include a Python editing mode for
quite a while into Python's existence. When it did include an official
editing mode, it was called python.el. The version of python.el in
Emacs 22 had some major flaws and often a substitution was recommended
(known as loveshack python.el). As of Emacs 23 (and Aquamacs 1.9), it appears as
though this version is now included in the official package so there's
no need to replace it.
Again, this is quite a pain and finding good information about Python
editing modes on the web is very difficult. I say use Emacs 23 and
stick with the included python.el. Many people will probably disagree
with that and they all make excellent points, but when you're new to
Emacs or it's been a while, you might as well stick with the easiest
configuration.
Tweaking Your Python Mode
Typically there will be behavior about your Python mode, whether you
choose python.el or python-mode.el, that you don't like. My examples
here are for the default behaviors of python.el that I personally
don't like. Like everything else in Emacs, behaviors we don't
like can be changed.
First, I don't like that by default syntactic pairs are not
"electric." This means that when you type a left parenthesis the
editor will automatically insert the right parenthesis and adjust your
cursor to be between the two. Ditto for brackets, braces, quote mark,
etc. I like this behavior and want to turn it on, so I modify my
configuration file. On GNU Emacs, configuration files are stored in
~/.emacs. To enable electric pairs for Python mode, use the following:
;;; Electric Pairs
(add-hook 'python-mode-hook
(lambda ()
(define-key python-mode-map "\"" 'electric-pair)
(define-key python-mode-map "\'" 'electric-pair)
(define-key python-mode-map "(" 'electric-pair)
(define-key python-mode-map "[" 'electric-pair)
(define-key python-mode-map "{" 'electric-pair)))
(defun electric-pair ()
"Insert character pair without sournding spaces"
(interactive)
(let (parens-require-spaces)
(insert-pair)))
Another feature I like that is not enabled by default
in python.el is binding the RET key to newline-and-indent (or py-newline-and-indent in python-mode.el). This
automatically indents newlines and attempts to locate the cursor at
the appropriate, whitespace-sensitive location whenever you press
Return. Some people may prefer to allow the cursor to locate at the
beginning of the line and indent themselves with TAB, which is totally
cool, but I find it somewhat tedious. My Elisp to enable this
functionality is below:
;;; bind RET to py-newline-and-indent
(add-hook 'python-mode-hook '(lambda ()
(define-key python-mode-map "\C-m" 'newline-and-indent)))
Lastly, and by far most importantly, you need to take care of
tabs. Since Python features significant whitespace, a broken tabbing
setup can cause all kinds of problems. In general, you want to make
sure that indent-tabs-mode is disabled and that your indentation
level is set to 4 spaces (per PEP 8).
Set this in your .emacs configuration like so:
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
You also might need to set py-indent-offset if you're using python-mode.el (it should default to 4, but in case your version doesn't).
(setq-default py-indent-offset 4)
This setting is the python-indent custom variable in python.el, which definitely defaults to 4.
Notes about the above settings: the tab-width value controls how source code files (presumably from other people) that use tabs instead of spaces are rendered. Setting to 4 means a tab will be rendered as 4 characters. You should not be generating Python code with tab characters, though, and that's why we set indent-tabs-mode to nil. The indent values specify how many whitespace characters to use for an indentation level, they probably don't need to be changed from the defaults if you have a recent version of your Python major mode.
For a more in-depth treatment of Emacs tabs & indentations, see Indenting Source Code in Emacs.
Now we have a fairly reasonable configuration for writing Python code
(IMHO). There are many, many additional configuration possibilities,
including completion hooks and other syntactic niceties. One other
feature that is worth pointing out here is the ability to launch an
interpreter within the editor using M-x python-shell. This loads a
standard Python shell.
We will look at modifying this interpreter by integrating with virtualenv as well as some additional editor customizations in next week's post.
blog comments powered by Disqus