2

I have some Django HTML templates that I'd like to auto-format. I've read Vim has a "htmldjango" format that can be applied, but I don't want to manually open every single file and apply it.

How do I run a Vim command from the command line to apply this formatting to one or more files in a single batch?

  • This answer should do what you want. It describes the use of batch mode in a Windows environment, though the translation to Linux should be obvious. – AFH Feb 6 '17 at 18:30
3

How about something like this:

vim -c "argdo setf htmldjango | execute 'normal! gg=G' | update" file1 file2 ...

:argdo iterates over all passed files. After ensuring the desired filetype, the file is re-indented (gg=G) and saved.

You can append -c quitall to automatically quit Vim.

0

Here's a script, beautify.sh, that will format any file at the command line, using Neovim.

It should work with any file format that vim itself recognizes, so javascript, json, c, java, etc. It's not a true formatter, but more of a nice indenter.

Example usage:

$ cat /tmp/it.json
{
"images": [
{
"time": 2.86091,
"transaction":
{
"status": "Complete",
"gallery_name": "gallerytest1",
}
}
}

$ cat /tmp/it.json | beautify.sh
{
        "images": [
        {
                "time": 2.86091,
                        "transaction":
                        {
                                "status": "Complete",
                                "gallery_name": "gallerytest1",
                        }
        }
}

beautify.sh

#!/usr/bin/env bash

function show_help()
{
  ME=$(basename $0)
  IT=$(CAT <<EOF

  Format a file at the command line using neovim

  usage: cat /some/file | $ME 
         $ME /some/file
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi

# Determine if we're processing a file from stdin or args
if [ -p /dev/stdin ]; then
  FILE=$(mktemp)
  cat > $FILE
  FROM_STDIN=true
else
  if [ -z "$1" ]
  then
    show_help
  fi
  FILE="$*"
  FROM_STDIN=false
fi

# put vim commands in a temp file to use to do the formatting
TMP_VIM_CMDS_FILE=$(mktemp)
rm -f $TMP_VIM_CMDS_FILE 
echo "gg=G" > $TMP_VIM_CMDS_FILE 
echo ":wq" >> $TMP_VIM_CMDS_FILE 

# run neovim to do the formatting
nvim --headless --noplugin -n -u NONE -s $TMP_VIM_CMDS_FILE $FILE &> /dev/null

# show output and cleanup
rm -f $TMP_VIM_CMDS_FILE 
if [ "$FROM_STDIN" == "true" ]
then
  cat $FILE
  rm -f $FILE
fi

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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