summaryrefslogtreecommitdiff
path: root/lib/html.source.sh
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2025-07-09 00:10:31 +0300
committerPaul Buetow <paul@buetow.org>2025-07-09 00:10:31 +0300
commit1c1109b7e0d741a113af1d94a5741d9fe7373f04 (patch)
tree9cab77a26d0f89fe249755c784352ab7d479ca3a /lib/html.source.sh
parent99078f90bf5222c618a60e536cb148850e4b89e2 (diff)
feat: auto-detect language for source-highlight
Diffstat (limited to 'lib/html.source.sh')
-rw-r--r--lib/html.source.sh33
1 files changed, 31 insertions, 2 deletions
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|<tt>||; s|</tt>||;'
+
+ 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 '<pre>'
+ html::encode "$bare_text"
+ echo '</pre>'
+ else
+ echo "$output" | $SED 's|<tt>||; s|</tt>||;'
+ fi
+ else
+ $SOURCE_HIGHLIGHT --src-lang="$language" "$style_css" <<< "$bare_text" |
+ $SED 's|<tt>||; s|</tt>||;'
+ fi
fi
}
@@ -337,5 +359,12 @@ if [ -z $foo ]; then
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
}