0

I have created some indentation commands like set shiftwidth=4, set autoindent and so on.... in my .vimrc file in my home folder and I'm able to get new files auto-indented happily.

What I want to know is if there is some script or way to indent existing file as per a particular indentation (say indentation script written by me (.vimrc) or default indentation standard for a particular extension that vim is intelligent enough to do.... )

The existing file has no consistent indentation used. Hope the question is clear.

  • 3
    Does gg=G work for you? – Tumbler41 Feb 7 '17 at 17:04
  • @Tumber41 Yes it is working... Thank you very much. This is what I'd wanted... (I was typing it using : like :gg=G), but realized later gg=G works typing directly.... – DevBee Feb 7 '17 at 18:12
1

I don't find that I'm able to get away with a single ts and sw setting. The proper values depend on the file type.

Therefore, I use the following functions in my .vimrc:

function SpaceTabs(spaces)
    exe "set sw=" . a:spaces
    exe "set ts=" . a:spaces
    exe "set expandtab"
    exe "set smarttab"
    exe "retab"
endfunction

function TabTabs(stops)
    exe "set ts=" . a:stops
    exe "set sw=" . a:stops
    exe "set noexpandtab"
    exe "set nosmarttab"
endfunction

Then below that, I have the following to enforce my local choices:

au BufEnter *.dbx call SpaceTabs(2)
au BufEnter *.docbook call SpaceTabs(2)
au BufEnter *.html call SpaceTabs(2)
au BufEnter *.md call SpaceTabs(4)
au BufEnter *.pal call TabTabs(8)
au BufEnter *.xml call SpaceTabs(2)
au BufEnter *.xsl call SpaceTabs(2)

I've edited that down to common file extensions, except for *.pal (the common PDP-8 assembly language form) which I've left as an example of one of that rare cases where I really do want hard tabs.

And then below that, my defaults, which keeps the file type specific listing above as short as possible:

au BufLeave * call SpaceTabs(4)
call SpaceTabs(4)

You may then ask, why do I need the *.md rule? It's in case I run into a Markdown file not produced under these same rules, because I always want to retab them when I open them. I'm careful adding such things; I don't do it on purpose for C and C++ files, because that's just as likely to wreck the formatting as fix the formatting of a free-form language, unlike with Markdown.

If you run across a file that doesn't get "fixed" the way you like this way and you can't be bothered to add one of these BufEnter rules, you can say

 :call SpaceTabs(4)

With Vim's command completion, this is quick to type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.