Indenting Python with Vim 2

2009-02-15 23:23; Tags: ,

Not that long time ago I began exploring Python. As a Vim adept I write almost all my code using it. And I was really disappointed with the way vim72 indents python’s code. Consider the following snippet that is indented by built in indent/python.vim script:

for file in files:
    mkdir_copy(os.path.join(root, file), divider,
        os.path.join(BACKUP_DIR, dest_subdir))

The code layout should look like (according to PEP-8):

for file in files:
    mkdir_copy(os.path.join(root, file), divider,
               os.path.join(BACKUP_DIR, dest_subdir))

I googled up Indenting Python with VIM — it suggests to use Eric Mc Sween’s script to solve most of indenting “problems”. It is really nice… until you have a colon in a docstring or comment. And if you have it — gg=G will mess your python code right after it:

# TODO:
    # this is an example of bad indenting
    if this_is_an_issue:
        print("Issue message")

This is definitly not what you want. Although it could be fixed quite easily (and actually I have fixed it) I think builtin script is more robust, so…
I have fixed builtin indent/python.vim script too. Now it makes “sexy” braces indenting just like it should.
But!
Lack of “sexy” braces indenting in vim is not a big problem at all. Both — standard and suggested scripts — have indent error:

if fullscreen:
    self.win_main = pyglet.window.Window(fullscreen=True, visible=False)
else:
    self.win_main = pyglet.window.Window(width=config.width,
            height=config.height,
            visible=False,
            vsync=True)

self.win_main.set_caption("Belveder %s" % config.version)

Press gg=G :

if fullscreen:
    self.win_main = pyglet.window.Window(fullscreen=True, visible=False)
else:
    self.win_main = pyglet.window.Window(width=config.width,
            height=config.height,
            visible=False,
            vsync=True)

    self.win_main.set_caption("Belveder %s" % config.version)

The last line is indented. Code is broken!

I tried to address all mentioned issues in the fixed indent/python.vim.
Use it with caution! :)

Leave a Reply

Powered by WordPress