vimtabsyamlspaces

How to edit .vimrc file to replace tab with spaces?


I am writing a Python script which writes some formatted data into a YAML file. I am using tabs for formatting the text, but I want the tabs to be converted into spaces when written into the YAML file. This is because my YAML file does not take tabs as valid indentation tokens.

I have tried this:

Step 1: Go to your home directory

cd ~

Step 2: Create the file

vim .vimrc

Step 3: Add the configuration stated below

set smartindent

set tabstop=4

set shiftwidth=4

set expandtab

:retab

But this does not work. The YAML file created still has tabs. The tabs are not converted to spaces.

Please suggest what changes should I make into my .vimrc file so that tabs are converted into spaces for valid indentation.

The Python script:

template = open("/home/stack/horizon/openstack_dashboard/dashboards/mydashboard/mypanel/extracted_template.yaml","w")

networks = api.neutron.network_list_for_tenant(self.request,tenant_id,params={}) 

for n in range(0,len(networks)):
      n_name = networks[n]['name']
      print>>template,"\tprivate_net%d:"%n,"\n\t type: OS::Neutron::Net","\n\t properties:","\n\t  name:",n_name          

Solution

  • To convert tabs to spaces use the commands below in the order below:

    :set noexpandtab
    :retab!
    :set expandtab
    :retab!
    

    I go this answer from watching this vim cast. Tidying Whitespace

    Vim can already detect the file type yaml so you can use that to replace all TAB's in your YAML file add this your .vimrc

    :autocmd FileType yaml execute  ':silent! %s#^\t\+#\=repeat(" ", len(submatch(0))*' . &ts . ')'