Thursday, November 3, 2011

Re: increasing/reducing the number of leading white spaces dynamically

Am 03.11.2011 16:36, schrieb Jose Caballero:
> Hi,
>
> for our current python project, we are trying to follow the PEP
> recommendations, and therefore keeping all indentations to 4 white spaces.
> However, when I am writing code, I feel more comfortable with 8 white
> spaces.
> I am pretty sure there must be a trick to put on .vimrc (or similar) in
> such a way the indents are expanded dynamically when I open a file, but
> they are reduced to 4 again when I leave ( ':q' or ':wq' )
> In this way the file on disk keeps having 4, but I see 8 when editing code.
> The only problem is that I don't know the keywords to search on google
> myself... If someone can provide for the keywords I can google it myself.
>
>
> Thanks a lot in advance.
> Jose

Vim doesn't have read/write-filters (or similar), looks it isn't just "a
trick" in the vimrc (nevertheless, you can put the following into your
vimrc if you want).

After the other posts, this one tries to add a little more
sophistication ...
- keeps the cursor position
- works with any 'ts', 'sw', 'sts' ... tabstop config
- keeps 'modified' setting
- tries to keep silent where appropriate
- makes disabling easier with :augroup


augroup PyIndentToggle
au!
au BufRead *.py call s:PyIndentToggle("read")
au BufWritePre *.py call s:PyIndentToggle("write")
au BufWritePost *.py call s:PyIndentToggle("undo")
augroup End


func! s:PyIndentToggle(situation)
if a:situation == "undo"
" only after "write"
let sav_pos = winsaveview()
sil! undo
if !s:bufmod
set nomodified
endif
call winrestview(sav_pos)
return
endif
let sav_pos = winsaveview()
let sav_inde = &inde
try
if a:situation == "read"
let bufmod = &modified
sil %call s:DoIndentLine(2 * indent("."))
if !bufmod
set nomodified
endif
elseif a:situation == "write"
let s:bufmod = &modified
sil %call s:DoIndentLine(indent(".") / 2)
endif
catch /:E21:/
" cannot make changes, modifiable is off
echoerr "PyIndentToggle: cannot change the indent, modifiable is off"
finally
let &l:inde = sav_inde
call winrestview(sav_pos)
endtry
endfunc

func! s:DoIndentLine(indent)
exec "setlocal indentexpr=". a:indent
normal! ==
endfunc

" beware of bugs, of course.

--
Andy

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment