Skip to content

Instantly share code, notes, and snippets.

Embed
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.

gg=G
:retab
ZZ
@displague
Copy link

displague commented Mar 27, 2018

Thanks! This makes it even more portable,

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

@jay-knight
Copy link

jay-knight commented Nov 23, 2020

This seems even cleaner to me:

vim +%retab +wq file

@specious
Copy link

specious commented Jul 23, 2021

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: https://stackoverflow.com/a/5349842/
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: https://unix.stackexchange.com/a/47210/
reindent() {
  if [[ $# -gt 2 ]]; then
    f=$(mktemp)
    cat $3 | reindent $1 $2 > $f && mv $f $3
  else
    sed "h;s/[^ ].*//;s/$(repeatstr ' ' $1)/$(repeatstr ' ' $2)/g;G;s/\n *//"
  fi
}

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