Vim’s zx

2009-06-19 13:08; Tags:

Открыл для себя zx — раскрывает текущий фолдинг («складка», чтоль по русски?), закрывает все остальные.

То бишь при set foldlevel=1, когда раскрыты все классы и закрыты все их методы, я топчу zx, чтобы раскрытым оставался только нужный метод.

vim-zx

Удобно.

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. ;)

vimwiki 0.9.2, 0.9.2a, 0.9.2b

2009-05-04 12:17; Tags: ,

This weekend new version of vimwiki was released. And right after it a small fix was done this monday — many thanks to (annoying) dos line endings.

upd. .vba file still has dos CRLFs. The problem is in my new deployment script written in python. I will upload new .vba as soon as I am next to my computer.
upd2. Now there is vimwiki 0.9.2b with a couple of fixes and without dos lineendings.

0.9.2b

  • FIX: Installation on Linux doesn’t work. (Dos line endings in Vimball archive file).
  • FIX: Clear out FlexWiki ftplugin’s setup. Now you don’t have to hack filetype.vim to get rid of unexpected ‘:setlocal bomb’ from FlexWiki’s ftplugin.
  • FIX: When write done: it will show another done: in html file.

0.9.2a

  • FIX: Remove dos line endings from some files.

0.9.2

  • NEW: Option ‘folding’ added to turn folding on/off.
  • NEW: Header text object. See :h vimwiki-text-objects.
  • NEW: Add/remove Header levels with ‘=’ and ‘-’. See :h vimwiki_=.
  • NEW: Vimwiki GUI menu to select available wikies. See :h g:vimwiki_menu.
  • NEW: You can specify the name of your css file now. See :h vimwiki-option-css_name.
  • NEW: You can add styles to image links, see :h vimwiki-syntax-links.
  • FIX: History doesn’t work after :VimwikiRenameWord.
  • FIX: Some of wikipedia links are not correctly highlighted. Links with parentheses.
  • MISC: Renamed vimwiki_gtd to vimwiki_lst.

Get it from vimwiki downloads list.

vimwiki 0.9

2009-03-31 10:30; Tags: ,

What’s new:

  • [new] You can add classes to ‘pre’ tag — :h vimwiki-syntax-preformatted. This might be useful for coloring some programming code with external js tools like google syntax highlighter.
  • [new] !WikiPage is not highlighted. It is just a plain word WikiPage in HTML.
  • [new] Definition lists, see :h vimwiki-syntax-lists.
  • [new] New implementation of :h VimwikiRenameWord. CAUTION: It was tested on 2 computers only, backup your wiki before use it. Email me if it doesn’t work for you.
  • [new] HTML: convert [ ] to html checkboxes.
  • [new] Default CSS: gray out checked items.
  • [fix] Less than 3 characters are not highlighted in Bold and Italic.
  • [fix] Added vimwiki autocmd group to avoid clashes with user defined autocmds.
  • [fix] Pressing ESC while :VimwikiUISelect opens current wiki index file. Should cancel wiki selection.

Get it from vimwiki downloads list.

Run vimscript, run!

2009-03-20 14:01; Tags: ,
:h :@

This is the command every Vim plugin developer should be aware of. I wish I knew about it earlier.

" eval selected vimscript
vmap <Leader>r "vy:@v<CR>
" eval vimscript line
nmap <Leader>r "vyy:@v<CR>

Now with this screwdriver in my hands I can tinker at variables and functions of my plugin/script/colorscheme easily. That’s convenient. :)

The only drawback is that it can’t eval vimscript’s longlines. Those with `\` in the beginning:

" remove trailing spaces
map <F4> m`:silent! %s/\(\s\+$\)\\|\(\r$\)//g<CR>``
      \:echo "Remove trailing spaces and ^Ms ..."<CR>

vimwiki 0.8

2009-03-06 00:09; Tags: ,

At last! Vimwiki supports multiple wikies.

If you upgrade from previous versions you should revisit all vimwiki’s options in your .vimrc.

Most important — g:vimwiki_home has gone. Check :h vimwiki-options for additional information.

Get Vimwiki 0.8 from its downloads list.

LISP: Balance unmatched parentheses in Vim

2009-02-25 15:58; Tags: , ,

If you a vim guy hacking lisp or scheme the next vimscript could be useful for you. It closes unmatched parentheses on the current line, i.e.:

(define (fact n)
  (if (= n 0) 1
    (* n (fact (- n 1   ; cursor is on the line

Pressing \) while on the last line will close unbalanced parentheses on that line:

(define (fact n)
  (if (= n 0) 1
    (* n (fact (- n 1)))))   ; cursor is on the line

Here is the vimscript, just put it into your .vimrc:

function! s:rtrim(line) "{{{
  return substitute(a:line, '\s*$', '', '')
endfunction "}}}

function! s:find_rside_commentpos(lnum) "{{{
  let line = getline(a:lnum)
  let col = stridx(line, ';')
  while col != -1 &&
        \ synIDattr(synID(a:lnum, col, 1), "name") =~ "String"
    let col = stridx(line, ';', col + 1)
  endwhile
  return col
endfunction "}}}

function! s:LISP_close_parens(lnum) "{{{
  let save_cursor = getpos(".")

  call cursor(a:lnum, col('$'))
  let unbalanced = searchpair('(', '', ')', 'rmbcW',
        \ "synIDattr(synID(line('.'), col('.'), 0), 'name') =~? ".
        \ "'\\(Comment\\|String\\)'")
  if unbalanced > 0
    let line = getline(a:lnum)
    let unbalanced_str = repeat(')', unbalanced)
    let col = s:find_rside_commentpos(a:lnum)
    if col != -1
      let before_comment = strpart(line, 0, col)
      let wsp_cnt = strlen(before_comment) - strlen(s:rtrim(before_comment))
      let wsp_str = repeat(' ', wsp_cnt)
      let comment = strpart(line, col)
      call setline(a:lnum,
            \ s:rtrim(before_comment).unbalanced_str.wsp_str.comment)
    else
      let line = s:rtrim(line).unbalanced_str
      call setline(a:lnum, line)
    endif
  endif

  call setpos(".", save_cursor)
endfunction "}}}

command! LISPCloseParens call <SID>LISP_close_parens(line('.'))
map <Leader>) :LISPCloseParens<CR>
map <Leader>( :LISPCloseParens<CR>

This is a way better version of my previous attempt (russian) , which is to be frank just bad.

Vim, vimwiki and GTD

2009-02-17 23:39; Tags: ,

vimwiki-gtdI have just implemented “toggleable list items”. Now you can make “projects” which are vimwiki’s lists of what you should do to make a project done. Project is done when all it’s elements are done == checked.
Getting closer to emacs org-mode… :)

PS.
I wish i have implemented multiple wikies first.

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

Older Posts »

Powered by WordPress