Saturday, 9 May 2009

Complete Newbie's Guide to Emacs+Python

Having worked with Java and Eclipse forever , a few weeks ago i decided to give a dynamically typed language - Python and the one true editor - Emacs a try. As part of learning Python i wanted to have "learn Emacs" as a background task.

Of course, having read everywhere how difficult Emacs was - i did the lazy thing , spent an hour or so learning, how to start/stop emacs, understand what the status line was, find what "point" meant (it means glorified cursor), realise that "C" in Emacs land means Control, Alt/Meta key is basically Esc on all modern O.S's and keyboards and wallah i was ready to do Python.

For a complete newbie to Emacs and Python - attempting to map my experiences with Eclipse+Java to Emacs+Python turned out to be - shall we say - an "interesting" experience. There is a surfiet of documentation out there on Emacs explaining all sorts of deep-fu but time and again i found myself getting lost in it. I didn't want to learn Elisp, i didn't want my editor to read news, send emails, work as a directory-browser, function as a chat client or talk back to me. As a start, I just wanted to write Python and hopefully have some of the features that i am used to in Eclipse to be present. Additionally, not knowing the Emacs terminology meant i didn't know how to ask questions the "Emacs way" resulting in hair-pulling,teeth-gnashing and sleepless nights filled with console-based non-gui text dreams. There just didn't seem to be a SuperSimple Task Based Startup Guide for Complete Newbies.

So i decided to write one , here is my SuperSimple Task Based Startup Guide for Complete Newbs:

Task 0: Get yourself Emacs 22.x, the current production version, anything other than that and the instructions below may not work. Note this is GNU Emacs 22.x not XEmacs.

Task 1: I want Python syntax highlighting.
Emacs comes with a built-in Python highlighter. (These are called as modes in Emacs). The requisite file for that is python.el. This is developed by the FSF. There is a competing mode python-mode.el developed by the Python community. Stick with the default in-built one.

Task 2: I want to edit and run my Python program.
Download emacs.py from here: http://www.loveshack.ukfsn.org/emacs/emacs.py. Copy this file onto your directory, site-installation is the directory where Emacs has been installed for all users to use, on my machine this is at /usr/share/emacs/22.1 , so i copy emacs.py to /usr/share/emacs/22.1/etc overwriting the previously existing file. Write your python program say helloworld.py. [print "Hello World"] .Press C-c C-z (comint-stop-subjob, says the documentation) within your editor. What it means is if everything is working then you should get an Inferior Python shell within your editor where you can run your Python programs. Press C-x o, point moves back to the helloworld.py buffer. Press C-c C-l(python-load-file) , this loads your helloworld.py and executes it. If like me you have said "print Hello World" - you should now get >>> Hello World printed within the Interpreter buffer. Congratulations.

Task 3: I want auto-indentation in my program.
Whitespace being significant in Python, this was important to me. I wanted my editor to automatically indent my statements , so for example if i am writing a function i wanted the next line to be properly indented without me having to press "tab" or worse "spaces" all the time. Similarly when i closed the function i wanted the cursor to go back to the starting position. here's what you do: Open your Emacs InitFile(.emacs), create it if it is not present, ideally in your $HOME directory, add the following line to it :
(add-hook 'python-mode-hook '(lambda () (define-key python-mode-map "\C-m" 'newline-and-indent)))
Save the file and restart Emacs , you should now have auto-indentation in Python.

Task 4: I want listing/auto-completion of functions in Python modules.
Using pydoc and the excellent Python documentation i could see a listing of the builtin modules present in Python and the functions they provided. What i wanted was to have a listing of all the functions a module contained within my editor.This is where things get interesting. Being used to Eclipse+Java this is very simple. Type System.out. and press "tab" and i have the options in front of me in a drop-down list-box. After trawling across the web and getting mightily confused(ecb,oo-browser,eldoc,pycomplete and what not) i found this gem of a page : http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/#disqus_thread . Follow the instructions given there religiously , read through the comments as well , what it does is :
  1. Installs rope,ropemode,ropemacs . http://rope.sourceforge.net/ropemacs.html
  2. Installs pymacs. http://pymacs.progiciels-bpi.ca/
  3. Installs yasnippet. http://code.google.com/p/yasnippet/
Note: Make sure that you get the autocomplete.pl v 0.1.0 , google for it.
If everything goes well , pressing "tab" on a module at the current spot, should result in a small drop down list box which gives you potential completions and allows you to select them.

Task 5: I want inline documentation for modules and the functions they contain.
Now that we have function completions , i wanted to have inline documentation for those functions. Congratulations. If you have completed Step 3 properly then you have already finished Task 4. If you are like me and didn't actually read through the documentation of the rope library that you installed in the previous step then you will not know that rope can provide Python documentation as well . How-to invoke it : position point on a module name, press C-c d and you should get documentation for that module within your editor.

Task 6: Inline code-checkers (pylint,flymake,pyflakes,pychecker - i don't know)
Task 7: Code browser (ala Outline view in Eclipse)

I hope to accomplish Task 6 and 7 shortly.
An absolute godsend is C-c C-h within your Python mode , it invokes keyboard help for your particular major mode.Fantastic.

6 comments:

  1. Great job! Very useful for newbies indeed.
    I'll wait for Task 6 and 7 :-)

    ReplyDelete
  2. Very nice tutorial, I just wanted to know how to activate autoindent and found this great tutorial. I hope I will read more such great HowTos in your blog.

    ReplyDelete
  3. Tip:
    To jump to definitions of variables/functions/etc. you can integragte ctags in emacs:

    1. Just install the package exuberant-ctags (in Debian/Ubuntu)
    2. Run ctags -eR * in the project root. This will generate a file called "TAGS"
    3. In Emacs move the point to the symbol you want to look up and press M-. - first time Emacs will ask you for the TAGS file and then open a new buffer with the symbols definition.

    ReplyDelete
  4. @ BitSchupser : Thanks for the nice comment and the tip. I have been using CTAGS for the last month or so now. I have also added a few more packages to my Emacs install and wanted to try them "in anger" before i put them up over here.

    ReplyDelete
  5. Have you tried NetBeans IDE for python?You can forget emacs.

    ReplyDelete
  6. here's my config for flymake, i call out to pychekers.sh which is a script I wrote to call pyflakes and pep8.py. This is probably too anal for most people though. :)

    (require 'flymake)


    ;; flymake hooks tell flymake to run pycheckers.sh when needed
    ;; pycheckers.sh should be on the path, currently calls pyflakes and
    ;; pep8
    (setq python-make
    (expand-file-name "~/local/bin/pycheckers.sh"));;not picking up
    ;;the path for
    ;;some reason

    (when (load "flymake" t)
    (defun flymake-pyflakes-init ()
    (let* (
    (temp-file (flymake-init-create-temp-buffer-copy
    'flymake-create-temp-inplace))
    (local-file (file-relative-name temp-file
    (file-name-directory
    buffer-file-name))))
    (list python-make (list local-file)))))

    (add-to-list 'flymake-allowed-file-name-masks
    '("\\.py\\'" flymake-pyflakes-init))
    (add-hook 'find-file-hook 'flymake-find-file-hook)

    ReplyDelete