In Vim, are there shortcuts to set tab widths to 2 and 4?

Posted on In QA

Tab widths may be different for different languages. Even with a common language, the tab width settings can be different for different projects.

In Vim, are there shortcuts to set tab widths to 2 and 4? To quickly change the tab widths when changing projects.

I am afraid no. But you create shortcuts for setting tab widths in Vim.

Add these lines to your ~/.vimrc:

" set tab width
function SetTab2()
  set shiftwidth=2
  set tabstop=2
  set softtabstop=2
  echo "Set tab to 2 spaces"
endfunction

function SetTab4()
  set shiftwidth=4
  set tabstop=4
  set softtabstop=4
  echo "Set tab to 4 spaces"
endfunction

map t4 :call SetTab4() <CR>
map t2 :call SetTab2() <CR>

Reference: https://github.com/zma/vim-config/blob/master/.vimrc#L331

Then, in your Vim, you can use t2 and t4 to set table to 2 and 4 spaces.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *