Vim retab spaces only at the beginning of lines

I use

:set noet|retab! 

But the problem I ran into is replacing all instances of 4 spaces with tabs throughout the file. I need vim to replace only instances of 4 spaces at the beginning of lines.

If I remove! at the end of retab, spaces are not replaced anywhere.

I tried using a custom function that someone created:

 " Retab spaced file, but only indentation command! RetabIndents call RetabIndents() " Retab spaced file, but only indentation func! RetabIndents() let saved_view = winsaveview() execute '% s@ ^\( \{'.&ts.'}\)\ +@ \=repeat("\t", len(submatch(0))/'.&ts.')@' call winrestview(saved_view) endfunc 

but when I start, I get a small error message:

 :RetabIndents 

Error processing RetabIndents function:

line 2:

E486: pattern not found: ^ ({4}) +

+7
source share
2 answers

After talking with other people about this, I needed to add silence! before executing the command. So this is what I am working on now:

 autocmd BufWritePre * :RetabIndents command! RetabIndents call RetabIndents() func! RetabIndents() let saved_view = winsaveview() execute '% s@ ^\(\ \{'.&ts.'\}\)\ +@ \=repeat("\t", len(submatch(0))/'.&ts.')@e' call winrestview(saved_view) endfunc 

So, now this function will automatically replace spaces with tabs only at the beginning of each line.

+9
source

I use another method to change the spaces in the tabs at the beginning of my shell scripts. I just use sed from the command line.

Using BSD sed:

 sed -i "" -e ':loop' -e "s/^\([ ]*\) /\1 /" -e 't loop' somefile.sh 

* note: (i) the character in square brackets is a tab character (ii) the character tuple / \ 1 is also a tab character. Both cgharacters tabs are entered into the terminal using the key combination Ctrl + v + Tab.

Using the GNU Command:

 sed -i -e ':loop' -e 's/^\([\t]*\) /\1\t/' -e 't loop' somefile.sh 
0
source

All Articles