Skip to content

Instantly share code, notes, and snippets.

Created February 13, 2014 10:04
What would you like to do?
Run vim reindent and retab from command line

Reindent and retab any file with vim from the shell

Vim has some pretty nice standarts on what indention etc. should look like, so it might make sense to run those from the command line on files without haveing to launch vim by hand. This is how it is done:

$ vim myfile.rb -s format.vim

Will execute all the commands specified in format.vim against the myfile.rb. The commands can be anything possible in vim in normal mode, so my example script will reindent the whole file (gg=G) and retab according to the rules, followed by a save.

Copy link

Thanks! This makes it even more portable,

alias retab='vim -s <(echo -e "gg=G\n:retab\nZZ")'

Copy link

This seems even cleaner to me:

vim +%retab +wq file

Copy link

Vim's retab command will change not only indentation but also spaces/tabs that aren't at the beginning of the line. Documentation invoked by :h retab includes this warning:

Careful: This command modifies any <Tab> inside of strings in a C program.

You can get the same effect using the expand and unexpand shell built-ins.

I found this discussion while looking into whether vim could be used to reindent files that use spaces for indentation. After some searching, I'm using a solution that uses sed:

# Repeat a string "n" times e.g. repeatstr abc 3
# Solution from:
repeatstr() {
  printf "%.0s$1" $(seq 1 $2)

# Reindent file that uses spaces
#   e.g. reindent 2 4 index.html
#   e.g. cat index.html | reindent 2 4
# Solution from:
reindent() {
  if [[ $# -gt 2 ]]; then
    cat $3 | reindent $1 $2 > $f && mv $f $3
    sed "h;s/[^ ].*//;s/$(repeatstr ' ' $1)/$(repeatstr ' ' $2)/g;G;s/\n *//"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment