#!/usr/bin/env awk -f
#
# md-color.awk - markdown highlighting for ANSI terminal
#
# note: processes only a subset of Markdown as a demo of AWK
#
# Usage (on terminal)
#   $ md-color.awk demo.md
#
# Usage (via pager)
#   $ md-color.awk demo.md | less -r
#
# colors can be configured via env. variable MD_COLORS
#
# ---
# source: https://git.sr.ht/~pem/dotfiles/tree/master/item/scripts/md-color.awk

function print_wrapped(long_line, prefix) {
    # Split words into an array
    split(long_line, list_of_words)

    line_len = 0
    num_words = length(list_of_words)

    for(i = 1; i <= num_words; i++) {
        word = list_of_words[i]
        word_len = length(word)

        # ~~~ Before word is printed ~~~

        # Check if we go beyond width of the block
        if ((line_len + word_len) > 78) {
            # Wrap the line
            line_len = 0
            printf("\n")
        }

        # At start of the line (line_len is 0 before we print first word)
        if (line_len == 0) {
            # Start with line prefix
            printf(prefix)

            # If inside multi-line bold
            if (bold_section)
                printf(ANSI_BOLD)

            # If inside multi-line inline code
            if (codeinline_section)
                printf(ANSI_CODE)
        }

        # Word begins with "**", set to bold
        if (match(word, "[*]{2}[^ ].*")) {
            printf(ANSI_BOLD)
            bold_section = 1
        }

        # Word begin with "`", set to code
        if (match(word, "`[^ ].*")) {
            printf(ANSI_CODE)
            codeinline_section = 1
        }

        # Advance length by one word
        line_len += word_len + 1

        # Special processing of punctuation at end of words
        # Example: "*word*," or "`word`."
        punct = substr(word, word_len)
        if ((punct == ".") || (punct == ",") || (punct == ":")) {
            # Separate punctuation from the word
            word = substr(word, 0, word_len - 1)
            word_len = word_len - 1
        }
        else
            punct = ""

        # ~~~ Print a word ~~~
        printf("%s", word)

        # ~~~ After the word is printed ~~~

        # Closing of bold
        if (substr(word, word_len - 1) == "**") {
            printf("%s", ANSI_NO_COLOR)
            bold_section = 0
        }

        # Closing of inline code
        if (substr(word, word_len) == "`") {
            printf("%s", ANSI_NO_COLOR)
            codeinline_section = 0
        }

        # Print the punctuation + a space
        printf("%s ", punct)
    }

    # Handle case of empty lines
    if (length(long_line) == 0)
        printf(prefix)

    # The line ends with a new-line
    printf("\n")
}


BEGIN {
    code_section = 0
    codeinline_section = 0
    bold_section = 0

    # Docs: ANSI Escape sequences at
    # https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797

    # Use environment variable to set colors, or use defaults
    if (length(ENVIRON["MD_COLORS"]) > 0)
        color_set = ENVIRON["MD_COLORS"]
    else
        color_set = "*e[0;34m *e[0;32m *e[0m*e[1m"

    # Subsusute "*e" with actual ESC character
    gsub(/\*e[[]/, "\033[", color_set)

    # Split into an array
    split(color_set, md_colors)

    ANSI_NO_COLOR = "\033[0m"
    ANSI_BOLD = "\033[1m"
    ANSI_QUOTE = md_colors[1]
    ANSI_CODE = md_colors[2]
    ANSI_HEADING = md_colors[3]
}


# Quote, single line
/^[[:blank:]]*>/ {
    if (code_section == 0) {
        # Strip leading "> "
        line = substr($0, 2)

        # Print folded block + setting color + using "> " as a line prefix
        print_wrapped(line, ANSI_QUOTE "> ")

        # Switch off color at the end of the quote block
        printf("%s", ANSI_NO_COLOR)
        next
    }
}


# Code section, multi-line
/^[[:blank:]]*```/ {
    if (code_section == 0)
        # Activate color for code section
        printf("%s%s\n", ANSI_CODE, $0)
    else
        # Remove color at the end of the code section
        printf("%s%s%s\n", ANSI_CODE, $0, ANSI_NO_COLOR)
    # Toggle flag
    code_section = 1 - code_section
    next
}


# Heading, single line
/^#.*/ {
    if (code_section == 0) {
        printf("%s%s%s\n", ANSI_HEADING, $0, ANSI_NO_COLOR)
        next
    }
}


# Everything else, the text of the file that is not prefixed by any markup
{
    if (code_section == 0)
        # Outside code section, fold long lines, prefix = switch off the color
        print_wrapped($0, ANSI_NO_COLOR)
    else
        # Inside code section, print line unmodified (no fold), apply color
        printf("%s%s\n", ANSI_CODE, $0)
}
