Emacs configuration for working with Python
OUR Blog
Jul 14 2016

Emacs configuration for working with Python

Emacs is an excellent text editor for comfortable work with Python code.

Main facilities

To begin with, it is recommended to install an easy-to-use plugin manager with lazy loading and updating, such as NeoBundle from vim. Our choice is el-get - a perfect manager with autocompilation, automatic initialization and, the most importantly, installation recipes. An illustrative example of a recipe.

(:name flycheck
       :type github
       :pkgname "flycheck/flycheck"
       :checkout "0.25.1"
       :minimum-emacs-version "24.3"
       :description "On-the-fly syntax checking extension"
       :build '(("makeinfo" "-o" "doc/flycheck.info" "doc/flycheck.texi"))
       :info "./doc"
       :depends (dash pkg-info let-alist seq)
       :post-init (progn
                    (add-hook 'python-mode-hook             #'flycheck-mode)
                    (add-hook 'js-mode-hook                 #'flycheck-mode)
                    (add-hook 'web-mode-hook                #'flycheck-mode)
                    (add-hook 'lisp-interaction-mode-hook   #'flycheck-mode)
                    (add-hook 'fish-mode-hook               #'flycheck-mode)
                    (add-hook 'markdown-mode-hook           #'flycheck-mode)
                    (add-hook 'go-mode-hook                 #'flycheck-mode)
                    (setq flycheck-check-syntax-automatically '(mode-enabled save idle-change))
                    (setq flycheck-highlighting-mode 'lines)
                    (setq flycheck-indication-mode 'left-fringe)
                    (setq flycheck-checker-error-threshold 2000)

This is a recipe for installation of flycheck - files syntax checking plugin. In recipe you can specify the code origin - git/github repository or, just a link to the file or plugin’s name in ELPA/MELPA, necessary dependencies, for github - a branch or a tag.

Command :built allows to start system utilities, if they required for plugin’s correct installation. There is also another great command - :post-init, where lisp code can be specified, which will be run every time the plugin is initialized. Generally, a very useful tool.

All settings are stored in the following folder ~/.emacs.d. The thinnest init.el, where logically broken files from settings folder connect.

(add-to-list 'load-path (expand-file-name "settings" user-emacs-directory))
(require 'dark-mint-theme)
(require 'scratch_my)
(require 'package_my)
(require 'hooks_my)
(require 'keybindings_my)

automatically generated at “customize” code.

The first file is a design theme. More themes here.

Scratch_my.el describes all the standard settings and includes all the required modes, which are incorporated from scratch in any fresh Emacs.

In package_my.el there are a list of all plugins to be installed and several functions for correct installation.

Hooks of different modes are described in a file hooks_my.el. Keybindings changes are taken out in a separate file keybindings_my.el.

The folders with snippets yasnippet and recipes are also synchronized. Changes to recipes are very frequently made, plugins settings are added there, which is why they are stored in a separate folder.

Plugins, irrespective of programming language

We are not going to describe all plugins in detail, for this purpose we attach a link to each of them.

Let’s probably start with avy, a plugin which allows to switch to a word, containing the entered symbol (analogue vim-easymotion).

For autocompletion we used company-mode - a universal autocompletion for Emacs. It works very quickly, can be completely customized, although the documentation is not full, I often looked in sources. The convenience is in a structure of a given plugin. There is backend - an individual code for different modes and frontend - a general code which presents the results of autocompletion in Emacs itself. Different backends are used for different modes. For example, company-elisp backend is used for lisp, for Python - company - jedi (backend for company-jedi - Python code’s static analysis libraries).

Expand-region is used for text’s semantic allocation. More details in this video.

For work with git three wonderful plugins are used - git-gutter, mo-git-blame and magit. The last one should be particularly pointed out - it is just excellent - a couple of touches and your code is on the server.

And you will ask about a file manager? Neotree integration with git is available.

Another very useful plugin - helm - is an aoutocompletion to everything. Search in open buffers (helm-swoop), in recently opened files, in files in current directory, commands search, renaming of variables in several buffers and many other. A great article describes all the capabilities of this plugin. Multiple-cursors - after watching this video you would surely like to try it :)

Plugin, with the help of which you can appoint an action for any keys double-tapping is key-chord (video).

Analogue vim-powerline, of a functional status line powerline.

Projectile - a plugin for project management in Emacs. Project search, project files replacement, go to definition, project switching and many other useful functions. More details in this article.

Yasnippet - allows to create and use snippets for different programming languages.

Python mode

Finally we move to Emacs setting directly for work with Python.

Let’s start with hooks

;; Python mode
(defun my-merge-imenu ()
  (let ((mode-imenu (imenu-default-create-index-function))
        (custom-imenu (imenu--generic-function imenu-generic-expression)))
    (append mode-imenu custom-imenu)))

(defun my-python-hooks()
    (setq tab-width     4
          python-indent 4
          python-shell-interpreter "ipython"
          python-shell-interpreter-args "-i")
    (if (string-match-p "rita" (or (buffer-file-name) ""))
        (setq indent-tabs-mode t)
      (setq indent-tabs-mode nil)
        '("Sections" "^#### \\[ \\(.*\\) \\]$" 1))
    (setq imenu-create-index-function 'my-merge-imenu)
    ;; pythom mode keybindings
    (define-key python-mode-map (kbd "M-.") 'jedi:goto-definition)
    (define-key python-mode-map (kbd "M-,") 'jedi:goto-definition-pop-marker)
    (define-key python-mode-map (kbd "M-/") 'jedi:show-doc)
    (define-key python-mode-map (kbd "M-?") 'helm-jedi-related-names)
    ;; end python mode keybindings

    (eval-after-load "company"
            (unless (member 'company-jedi (car company-backends))
                (setq comp-back (car company-backends))
                (push 'company-jedi comp-back)
                (setq company-backends (list comp-back)))

(add-hook 'python-mode-hook 'my-python-hooks)
;; End Python mode

For plugins’ work some packets need to be installed via pip.

pip install -U jedi virtualenv flake8

We set up indents settings and way to the interpreter, set keys’ specific bindings, add company-jedi backend and adjust imenu.

Autocompletion was mentioned above (company-jedi), search on file and file’s structure (classes names, variables, methods, etc) is carried out via imenu (F10), NeoTree file manager opening and closing is accomplished at tapping F7.

Now a bit about the used plugins

Auto-virtualenv - activates virtualenv for Python file. Works excellently, especially when combined with projectile. Jedi-core - gives variants for autompletion to company-jedi, passes to definitions, shows docs of the functions and classes, etc.

Pip-requirements - as it can be seen from the name - it is a packet for work with requirements.

Py-autopep8 - allows to format a code automatically according to pep8 standard.

Py-isort - can sort all imports in a file automatically.

Python REPL

We specified in hooks which version of shell we are going to use

    (setq python-shell-interpreter "ipython"
       python-shell-interpreter-args "-i")

Tapping C-c C-c - all the contents of a current buffer are transferred to ipython, where it can be tested at once. If you want to look through just a part of a code, select it and tap C-c C-r.

You can also use a debugger built-in python-mode, executing a M-x pdb RET command (RET - in emacs means enter/return, first it confused me). There is also a more functional version - realgud.

For example, here are several screenshots: screenshots for editor

screenshots of editor

Other plugins

Markdown-mode - in this very mode the given article is being written. And the result is viewed in browser with the help of livedown.

Web-mode - allows to work with html, css, Django/Jinja2 templates.

Restclient - a plugin to work with different Api. Emacrocks will show more in their video.


It is a pity, that all the features and subtleties of each plugin cannot be embraced in one article, I hope this list of short descriptions will let the readers to find out something new about this wonderful editor.

Useful links

Jan 05 2017
Implementing websocket server into Django project using aiohttp and redis PUB/SUB.
Nov 29 2016
Create a project template with Vagrant, VirtualEnv and Ansible provisioner. And why is it necessary?
Nov 04 2016
Review of push notifications services and their functions. Read how to use push notifications effectively and make your app user-friendly in our article!