Skip to content

Instantly share code, notes, and snippets.

@sideshowcoder
Created February 13, 2014 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sideshowcoder/8972647 to your computer and use it in GitHub Desktop.
Save sideshowcoder/8972647 to your computer and use it in GitHub Desktop.
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
@specious
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: 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