Fandom

Vim Tips Wiki

Toggle between tabs and spaces

Redirected from VimTip785

1,624pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Tip 785 Printable Monobook Previous Next

created September 9, 2004 · complexity intermediate · author Paul Braman · version 6.0


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

CommentsEdit

I like this function for the same reasons, 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

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!


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=".g:my_tab
    execute "set softtabstop=".g:my_tab
    set expandtab
  endif
endfunction
nmap <F9> mz:execute TabToggle()<CR>'z

Also on Fandom

Random Wiki