Python folding in Vim

2009-05-22 12:59; Tags: ,

There are several ftplugins at www.vim.org that fold python code. I could have used one of them and be happy but the burden of my ex-prog-life leads me to my own wheel to be reinvented.

Brief description

  • Folds are created for:
    • let g:python_fold_block = "all" — all python code blocks;
    • let g:python_fold_block = "def" — defs and classes. [DEFAULT]
  • The way empty lines are folded controlled by g:python_fold_keep_empty_lines variable:
    • let g:python_fold_keep_empty_lines = "all" — keep empty lines between code blocks; [DEFAULT]
    • let g:python_fold_keep_empty_lines = "top" — keep empty lines between top level code blocks;
    • let g:python_fold_keep_empty_lines = "top-one" — keep one empty line between top level code blocks;
    • let g:python_fold_keep_empty_lines = "one" — keep one empty line between code blocks.
  • Comment’s folding:
    • let g:python_fold_comments = 1 — fold comments; [DEFAULT]
    • let g:python_fold_comments = 0 — do not fold comments.
  • Import’s folding:
    • let g:python_fold_imports = 1 — fold imports; [DEFAULT]
    • let g:python_fold_imports = 0 — do not fold imports.
  • Docstring’s folding:
    • let g:python_fold_docstrings = 1 — fold docstrings; [DEFAULT]
    • let g:python_fold_docstrings = 0 — do not fold docstrings.

Screenshots

p_fold_all
let g:python_fold_keep_empty_lines = "all"
p_fold_top
let g:python_fold_keep_empty_lines = "top"
p_fold_top-one
let g:python_fold_keep_empty_lines = "top-one"
p_fold_one
let g:python_fold_keep_empty_lines = "one"

Install

  1. Download python.vim
  2. Place python.vim to
    • Windows: ~/vimfiles/ftplugin/
    • Linux: ~/.vim/ftplugin/

Note: Folding is shiftwidth dependent. If a code indented with 2 spaces make sure shiftwidth is 2 spaces too.

PS: It works for me and it may work for you too despite evil bugs that could live in it. ;)

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! :)

Маленький баг в indent/python.vim

2009-02-03 12:29; Tags: ,

В vim, чтобы писать программы на питоне, для правильной расстановки отступов, советуют использовать следующий indent/python.vim (ver 0.3). Потому как, встроенный в редактор не соответстует PEP 8.

Однако есть там маленькая ошибка. Вот такой вот код:

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

будет отформатирован следующим образом:

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

Что, как видно, не верно.

Скрипт я для себя поправил, вечером отошлю исправления Eric Mc Sween’у.

Update.
Его email помер.
Тогда покажу, где и что на что поправить. В его indent/python.vim строчку под номером 179:

    if pline =~ ':\s*$'

поменять на:

    if pline =~ '^[^#]\+:\s*$'

Update 2.
В итоге, все равно пользуюсь стандартным файлом. :)

Пришлось, правда, его немного допилить. Чтобы после скобок ставил правильный «сдвиг» на следующих строках. Про это написал уже в Indenting Python with Vim 2

Удаление пустых каталогов

2008-07-02 15:12; Tags:

Мой MediaMonkey в процессе работы оставляет пустые каталоги в библиотеке с музыкой. И убирать их совсем не хочет — приходится делать это за него.
Питон, который я не очень сильно люблю, неплохо с этим справляется:

####
## Delete empty directories in a given TOPDIR
## Author: Maxim Kim
## PS:
## I use it to keep my music library out of empty dirs.
####

TOPDIR = 'D:/muzik/'

import os

print "=" * 80
print "Deleting empty directories in %s..." % TOPDIR

count = 0
for root, dirs, files in os.walk(TOPDIR, topdown=False):
    for name in dirs:
        dirpath = os.path.join(root, name)
        if len(os.listdir(dirpath)) == 0:
            os.rmdir(dirpath)
            print "%s deleted." % dirpath
            count+=1

print "Deleted %d directories" % count
print "=" * 80

Powered by WordPress