Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wangkuiyi
Created June 19, 2020 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangkuiyi/1a754d875ce6e4859df11eb5b1b5b0cd to your computer and use it in GitHub Desktop.
Save wangkuiyi/1a754d875ce6e4859df11eb5b1b5b0cd to your computer and use it in GitHub Desktop.
Auto-format Markdown files
#!/bin/bash
TAB=$(printf '\t')
in_code=0
previous_line=""
while IFS= read -r LINE
do
previous_line=$line
# Untabify
line=$(echo "$LINE" | sed 's/$(printf '\t')/ /g')
if echo $line | grep "^[[:space:]]*\`\`\`" > /dev/null; then
in_code=$(( (in_code + 1) % 2 ))
# Ensures there is an empty line before the code snippet.
if [[ "$in_code" == "1" ]]; then
if ! echo "$previous_line" | grep "^[[:space:]]*$" > /dev/null; then
echo ""
fi
fi
echo "$line"
else
# Ensures there is an empty line after a code snippet.
if echo "$previous_line" | grep "^[[:space:]]*\`\`\`" > /dev/null; then
if [[ "$in_code" == "0" && "$line" != "" ]]; then
echo ""
fi
fi
if [[ "$in_code" == "0" ]]; then
echo "$line" | fold -s -w 80
else
echo "$line"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment