Tip: #785 - Toggle between tabs and spaces
Created: September 9, 2004 11:01 Complexity: intermediate Author: Paul Braman Version: 6.0 Karma: 33/18 Imported from: Tip#785
I write code for a large company and often work with other developer's code. I personally don't choose to use all the language/formatting stuff in Vim, but I do like to quickly switch between using tabs and using spaces when I hit the <TAB> key (to integrate with the "current" file formatting).
Here is a snippit from my .vimrc which enables my default settings (using 4 spaces for every <TAB>) and a mapping to <F9> to toggle the settings:
" virtual tabstops using spaces
set shiftwidth=4
set softtabstop=4
expandtab
" allow toggling between local and default mode
function TabToggle()
if &expandtab
set shiftwidth=8
set softtabstop=0
noexpandtab
else
set shiftwidth=4
set softtabstop=4
expandtab
endif
endfunction
nmap <F9> mz:execute TabToggle()<CR>'z
Comments
I like this function for the same reasons as Paul, however, I encountered an error with the implementation of it which required me to make a few minor changes. The expandtab and noexpandtab were giving me errors on the Unix hosts, so I had to add the keyword "set" in front of them in three places, as shown below:
" virtual tabstops using spaces set shiftwidth=4 set softtabstop=4 set expandtab
" allow toggling between local and default mode function TabToggle() if &expandtab set shiftwidth=8 set softtabstop=0 set noexpandtab else set shiftwidth=4 set softtabstop=4 set expandtab endif endfunction nmap <F9> mz:execute TabToggle()<CR>'z
erymers--AT--comcast.net
, September 13, 2004 7:03
Grrr...that was just a mistake in my copying it into the Tip. My implementation has the "set" in front of them as well. Mea culpa!
Paul Braman
Anonymous , September 16, 2004 6:20
The tip seems to me excellent !
Here is a small add_on that allows to easily change (once instead of 4 times) the local tab value. And function is changed to function! to allow local tests (:w + :so %) .
" virtual tabstops using spaces let my_tab=4 execute "set shiftwidth=".my_tab execute "set softtabstop=".my_tab set expandtab
" allow toggling between local and default mode function! TabToggle()
if &expandtab set shiftwidth=8 set softtabstop=0 set noexpandtab else execute "set shiftwidth=".my_tab execute "set softtabstop=".my_tab set expandtab endif
endfunction nmap <F9> mz:execute TabToggle()<CR>'z
anonymous
, October 20, 2004 9:25
A small precision is necessary to make my "improved" version (dated 20 oct) working.
Inside the TabToggle function use two times g:my_tab (global variable) instead of my_tab.
(Sorry, I am not a specialist in vim language...). Alain Braun
Anonymous , October 21, 2004 6:20