From 1c1109b7e0d741a113af1d94a5741d9fe7373f04 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Wed, 9 Jul 2025 00:10:31 +0300 Subject: feat: auto-detect language for source-highlight --- lib/html.source.sh | 33 +++++++++++++++++++++++++++++++-- lib/template.source.sh | 4 ++-- 2 files changed, 33 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/html.source.sh b/lib/html.source.sh index 52fa2f4..3e16264 100644 --- a/lib/html.source.sh +++ b/lib/html.source.sh @@ -139,8 +139,30 @@ html::source_highlight () { if [ -n "$SOURCE_HIGHLIGHT_CSS" ]; then style_css="--style-css-file=$SOURCE_HIGHLIGHT_CSS" fi - $SOURCE_HIGHLIGHT --src-lang="$language" "$style_css" <<< "$bare_text" | - $SED 's|||; s|||;' + + if [[ "$language" == "AUTO" ]]; then + local tmp_file + tmp_file=$(mktemp) + trap 'rm -f "$tmp_file"' RETURN + printf %s "$bare_text" > "$tmp_file" + + local output + # redirect stderr to avoid printing the error message + output=$($SOURCE_HIGHLIGHT --infer-lang --failsafe -i "$tmp_file" "$style_css" 2>/dev/null) + + # if output is same as input, highlighting failed + # also check if output is empty, which also means failure + if [[ "$output" == "$bare_text" || -z "$output" ]]; then + echo '
'
+                html::encode "$bare_text"
+                echo '
' + else + echo "$output" | $SED 's|||; s|||;' + fi + else + $SOURCE_HIGHLIGHT --src-lang="$language" "$style_css" <<< "$bare_text" | + $SED 's|||; s|||;' + fi fi } @@ -335,6 +357,13 @@ this if [ -z $foo ]; then echo $foo fi +```' + assert::contains "$(html::fromgmi <<< "$input_block")" 'GNU source-highlight' + + input_block='```AUTO +if [ -z $foo ]; then + echo $foo +fi ```' assert::contains "$(html::fromgmi <<< "$input_block")" 'GNU source-highlight' fi diff --git a/lib/template.source.sh b/lib/template.source.sh index c93b66e..8ab19d5 100644 --- a/lib/template.source.sh +++ b/lib/template.source.sh @@ -106,12 +106,12 @@ template::inline::_index () { # Can be used from a .gmi.tpl template for generating an index for a given topic. template::inline::index () { - template::inline::_index $@ | sort | uniq + template::inline::_index "$@" | sort | uniq } # Same as index, but reverse order template::inline::rindex () { - template::inline::_index $@ | sort -r | uniq + template::inline::_index "$@" | sort -r | uniq } # TODO: Write unit test. -- cgit v1.2.3