Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim retab spaces at the beginning of lines only

I'm currentling using

:set noet|retab!

But the problem I'm running into is it's replacing all instances of 4 spaces to tabs throughout the entire file. I need vim to only replace instances of 4 spaces at the beginning of lines only.

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

I've tried using a custom function that somebody 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 I get a nice little error message when I run:

:RetabIndents

Error detected while processing function RetabIndents:

line 2:

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

like image 731
Francis Lewis Avatar asked Mar 02 '11 19:03

Francis Lewis


People also ask

How do I insert a tab instead of spaces in vim?

From the documentation on expandtab : To insert a real tab when expandtab is on, use CTRL-V <Tab> .

How do I replace a tab with 4 spaces in vim?

in vim you can do this: # first in . vimrc set up :set expandtab :set tabstop=4 # or you can do this :set tabstop=4 shiftwidth=4 expandtab # then in the py file in command mode, run :retab! :set noet|retab!

How do I change tabs in Vim?

To switch to the next tab, use :tabn, and to switch to the previous tab, use :tabp (short for tabnext and tabprevious respectively). You can also jump over tabs by using :tabn 2, which will move to the second next tab. To jump to the first tab, use :tabr (tabrewind) and to jump to the last tab use :tabl (tablast).

How do I view spaces and tabs in Vim?

A quick way to visualize whether there is a Tab character is by searching for it using Vim's search-commands : In NORMAL mode, type /\t and hit <Enter> . It will search for the Tab character ( \t ) and highlight the results.


1 Answers

After talking with some other people about this, I needed to add the silent! command before execute. So this is what I have working 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 at the beginning of each line only.

like image 185
Francis Lewis Avatar answered Sep 24 '22 14:09

Francis Lewis