Programming


1
Aug 09

Setting up Emacs & Clojure with Emacs Starter Kit

Note: This blog post is no longer accurate as a lot of things have changed since I wrote this post. Please check this document for working instructions.

Clojure is a very modern functional programming language which runs on the JVM. It’s a very cleanly designed Lisp dialect and has all the features that any useful programming language would require. You can learn more about Clojure on the official website, the wikibook, a comprehensive article by R. Mark Volkmann or by buying the awesome book by Stuart Halloway.

Now to setup Emacs as a Clojure IDE. If you are new to Emacs then don’t worry as we will take the easiest way to set it all up. If you are a Emacs veteran, then keep your own dotemacs and the bunch of customisations that you have done in all these years aside and follow along.

Installing Emacs is easy. On an Ubuntu system, do this -

$ sudo apt-get install emacs-snapshot-gtk

That will install Emacs 23 for you. You will also need a few other things -

$ sudo apt-get install sun-java6-jdk ant git-core

You will need the JDK and Ant to build and run Clojure (it runs on the JVM, remember?) and Git to fetch the Clojure an other related libraries.

Now to setup Emacs, we will use a brilliant set of Emacs Lisp libraries aptly named Emacs Starter Kit (ESK). To get it, do this -

$ git clone git://github.com/technomancy/emacs-starter-kit.git ~/.emacs.d

That will get the ESK and will put it in your ~/.emacs.d (existing Emacs users, please move your ~/.emacs and ~/.emacs.d to some other location before doing this. You can get back your old settings later).

What ESK does is that it provides a bunch of sane defaults for pretty much everything in Emacs. You can safely use it and get a very usable Emacs setup almost immediately.

You can now launch Emacs by going to Applications > Accessories and selecting Emacs Snapshot Gtk. Once Emacs has started up, install the Emacs Clojure libraries by typing M-x package-list-packages. That will start up a buffer with a bunch of Emacs packages. Go to the line that says clojure-mode in it and press i. Then press x to install the package. Once that’s done you are ready to install Clojure. Now type M-x clojure-install and it will prompt you for a directory to install Clojure. Just press Enter for now and let it proceed. You can always change these things later.

That will fetch the Clojure runtime and also a few other useful libraries like clojure-contrib and will install them inside ~/src.

Once that is done, you can type M-x slime to start Clojure inside your Emacs. Play around with it and learn the various key-bindings for Slime and Paredit which is a fantastic system for doing Lisp development. Paredit is so good that it makes all those parentheses just vanish in thin air. But yes, it takes a bit getting used to which you can achieve with some practice. One tip is to type C-h m in Emacs to see the documentation of all the modes that are currently active. This gives a good overview of all the key-bindings and the functions bound to those keys.

To develop slightly more complex Clojure applications, you need to use different dependencies with your own code. Since Java has its own classpath related quirkiness it can become a slightly complicated task. But then, there is cool function in Emacs Starter Kit called clojure-project which will make your life easy.

To use it all you need to do is to follow this simple directory structure and the rest will be taken care of automagically. The directory structure should be like this -

myproject
|-- lib
|-- src
|-- target
| |-- classes
| `-- dependency
`-- test

Copy the Clojure & Clojure Contrib (or any other dependency) JAR files into lib (you also alternately use a build system like Maven to manage dependencies for you in which case you should consider configuring the build system to copy the dependencies into target/dependency). Keep all your code inside src and tests inside test. The src and test directories should contain namespaces like foo.bar & foo.bar.test respectively (you can later use clojure-test-mode to automatically pick up the tests and run them quickly). So when you run M-x clojure-project, it will ask you for a directory name. Give it the name of the project directory and boom! Emacs will launch Slime with the right classpath settings.

If you want to customise any Emacs setting, just create a file with your current system login id called <username.el> inside ~/.emacs.d and it will be automatically loaded when you restart Emacs. If you use additional libraries, create a directory with your username inside the same directory and everything inside will be in the Emacs load-path. Nifty, right?

So that’s all required to setup Emacs for Clojure. Join the Clojure mailing list to communicate with the Clojure community. Do check the Emacs Wiki in case you have any queries about Emacs.

Above all, have fun. That’s what we are here for.

By the way, I am @ghoseb on Twitter and I think you should follow me :)

UPDATE: Fixed a factual inconsistency regarding the paths used for clojure-project. Thanks to Phil (the creator of ESK & clojure-project) for pointing this out!


6
Nov 06

GNU Emacs with XFT goodness

Personally I have been using the emacs-unicode-2 CVS branch of GNU Emacs for a long time now. This branch will become Emacs 23 in the future and it contains better Unicode handling code in addition to some cool features like antialiased fonts (courtesy XFT and FreeType), copy to clipboard, etc.

GNU Emacs with XFT

I usually build a custom version of the emacs-snapshot package with source from the emacs-unicode-2 branch and some simple customisation to enable the antialiased fonts. Some of my friends are using those packages and I thought it’d be good if share those packages with a larger audience.

So I have set up an APT repository with those packages which you can install on your Ubuntu Dapper machine. To do that, first add the following line to your /etc/apt/sources.list

deb http://people.ubuntu-in.org/~ghoseb/apt/ dapper main
deb-src http://people.ubuntu-in.org/~ghoseb/apt/ dapper main # for source

Then do sudo apt-get update to fetch the package list and then sudo apt-get install emacs-snapshot-gtk to install the customised GNU Emacs package.

If you already have the vanilla emacs-snapshot installed then only sudo apt-get upgrade will upgrade your current installation to the new one. And yes, this package can co-exist peacefully with your emacs21 package.

Now to enable antialiased fonts, add the following line to your ~/.emacs

(set-default-font "Bitstream Vera Sans Mono-8")

Now launch GNU Emacs as emacs-snapshot-gtk --enable-font-backend and enjoy the awesomeness :)

Leave a comment if any of you need Ubuntu Edgy packages, I will build them and add to the repository.

Update: I have added Edgy packages too ! Just add the following lines to your /etc/apt/sources.list and the rest is identical to the instructions for Dapper.

deb http://people.ubuntu-in.org/~ghoseb/apt-edgy/ edgy main
deb-src http://people.ubuntu-in.org/~ghoseb/apt-edgy/ edgy main # for source


31
Jul 06

Check GMail the Python way

Swaroop posted a nifty Perl script to check GMail. The script basically parses an Atom feed of the latest 20 mails provided by Google. Since a Python hacker like Swaroop is dabbling in Perl, I thought it was my duty as a Python evangelist (or is it Pythangelist?) to show the people that the same thing can be achieved using Python with equal ease :) The main code is around 50% of the total code. A large portion of the code is used for the pretty printing. Here it is —

## check-gmail.py -- A command line util to check GMail -*- Python -*-

# ======================================================================
# Copyright (C) 2006 Baishampayan Ghose <b.ghose@ubuntu.com>
# Time-stamp: Mon Jul 31, 2006 20:45+0530
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
# ======================================================================

import urllib             # For BasicHTTPAuthentication
import feedparser         # For parsing the feed
from textwrap import wrap # For pretty printing assistance

_URL = "https://mail.google.com/gmail/feed/atom"

def auth():
    '''The method to do HTTPBasicAuthentication'''
    opener = urllib.FancyURLopener()
    f = opener.open(_URL)
    feed = f.read()
    return feed

def fill(text, width):
    '''A custom method to assist in pretty printing'''
    if len(text) < width:
        return text + ' '*(width-len(text))
    else:
        return text

def readmail(feed):
    '''Parse the Atom feed and print a summary'''
    atom = feedparser.parse(feed)
    print ""
    print atom.feed.title
    print "You have %s new mails" % len(atom.entries)
    # Mostly pretty printing magic
    print "+"+("-"*84)+"+"
    print "| Sl.|"+" Subject"+' '*48+"|"+" Author"+' '*15+"|"
    print "+"+("-"*84)+"+"
    for i in xrange(len(atom.entries)):
        print "| %s| %s| %s|" % (
            fill(str(i), 3),
            fill(wrap(atom.entries[i].title, 50)[0]+"[...]", 55),
            fill(wrap(atom.entries[i].author, 15)[0]+"[...]", 21))
    print "+"+("-"*84)+"+"

if __name__ == "__main__":
    f = auth()  # Do auth and then get the feed
    readmail(f) # Let the feed be chewed by feedparser

And here is a sample output —

ghoseb@trinka:~$ python check-gmail.py
Enter username for New mail feed at mail.google.com: foo.bar
Enter password for foo.bar in New mail feed at mail.google.com:

Gmail - Inbox for foo.bar@gmail.com
You have 20 new mails
+------------------------------------------------------------------------------------+
| Sl.| Subject                                                | Author               |
+------------------------------------------------------------------------------------+
| 0  | Strip Whitespace Middleware[...]                       | Will McCutchen ([...]|
| 1  | [FOSS Nepal] list of free alternatives to windows[...] | Manish Regmi (r[...] |
| 2  | json serialization[...]                                | Gábor Farkas (g[...] |
| 3  | editable=False and "Could not find Formfield or[...]   | Corey (coordt@e[...] |
| 4  | IronPython 1.0 release candidate[...]                  | Jeremy Dunck (j[...] |
| 5  | django server tree organization[...]                   | Kenneth[...]         |
| 6  | Project when using multiple sites[...]                 | Jay Parlar (par[...] |
| 7  | [FOSS Nepal] Neprog (nepali version pogrammer for[...] | ujwal (ujwal2@g[...] |
| 8  | Bug#379789: wrong keymap on Intel MacBook Pro[...]     | Frans Pop (elen[...] |
| 9  | debconf is Level 1?[...]                               | Clytie Siddall ([...]|
| 10 | Weird slowdown with dev server behind nat[...]         | Akatemik (tpiev[...] |
| 11 | Database API question: I am not able to return a[...]  | DavidA (david.a[...] |
| 12 | Bug#379120: lspci present on i386, verify on[...]      | Eddy Petrişor ([...] |
| 13 | New levels of D-I[...]                                 | Eddy Petrişor ([...] |
| 14 | Installed Apps in settings.py[...]                     | limodou (limodo[...] |
| 15 | where u at man ... where can i call you ??????[...]    | Sanjeev[...]         |
| 16 | unable to runser ?[...]                                | Geert[...]           |
| 17 | Bug#380585: debian 3.1 install FD[...]                 | as_hojoe (as_ho[...] |
| 18 | Re: Translated packages descriptions progress[...]     | Michael Bramer ([...]|
| 19 | Loading an url takes 60 sec.[...]                      | and_ltsk (andre[...] |
+------------------------------------------------------------------------------------+
ghoseb@trinka:~$

Well, the code is obviously pretty rough. It’s just for showing newbies how to use feedparser and urllib, two very powerful Python libraries. Improvements, patches are welcome :)

The text source can also be downloaded.


6
Jun 06

Started working on the Design

After a prolonged sickness, I am back to work again. Started working on the design specs of the offline update tool today. It's still incomplete, but I am just putting up my ideas of implementation on the doc. Talked to Mario Danic about the design doc. He also approved my specification in the Launchpad Blueprint system.

I was quite relieved to know that python-apt is quite usable and it works fine (though not being very pythonic in nature). I read somewhere that it's not very actively maintained now-a-days and lacks a lot of features. That info relieved me quite a lot, otherwise my whole app would have become jeopardised :)

There are people who are also requesting me to port the tool to Windows. Well, Python code is easily portable but hey, Windows has no APT library :) Thankfully Mario is writing a tool for Windows which does a similar job, so may be I will be able to borrow some ideas from him.

I also need to check if my bank accepts cheques in Indian Rupees but drawn in the USA. As I have heard, they may claim that such cheques are impossible … heh, they have no idea about Google!

Anyway, I need to sleep off now. I must finish the design doc by tomorrow.


25
Nov 05

A first look at ayttm

I have never used ayttm myself, but I know Philip S. Tellis, its primary author quite well. It appears that the project is in a great need of active developers as Philip is quite busy with his work and others are I guess absconding. For those who don't know what ayttm is, it's a multi-protocol and cross platform messaging client, a bit like GAIM. ayttm is quite novel in its own right as it seems to support Yahoo! Messenger webcams, though I haven't tested it myself. There are a few nagging issues wrt ayttm at the moment like the GUI is still using GTk+ 1.x while the whole world has moved to GTk+ 2.6.x upwards. So I thought it was worthwhile to check it out and see if I could help in some way. I checked out the source from the CVS repo and tried building it. And I hit a bug straightaway. There was this small bug which would cause an error when compiled with gcc 4.x. So I whipped up a small patch to fix it and submitted it to the list. And no, it was not a one-liner (it was a two-liner ;) ). I just checked that the patch was committed by Philip. Cool! I guess I have to devote some time hacking ayttm after my freakin' exams are over. And yes, if you are a C programmer, and want to contribute to Free Software, ayytm needs you. Join the lists today!