Created
June 19, 2020 20:13
-
-
Save wangkuiyi/1a754d875ce6e4859df11eb5b1b5b0cd to your computer and use it in GitHub Desktop.
Auto-format Markdown files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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