diff options
| author | Paul Buetow <paul@buetow.org> | 2025-07-09 00:10:31 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2025-07-09 00:10:31 +0300 |
| commit | 1c1109b7e0d741a113af1d94a5741d9fe7373f04 (patch) | |
| tree | 9cab77a26d0f89fe249755c784352ab7d479ca3a /lib | |
| parent | 99078f90bf5222c618a60e536cb148850e4b89e2 (diff) | |
feat: auto-detect language for source-highlight
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/html.source.sh | 33 | ||||
| -rw-r--r-- | lib/template.source.sh | 4 |
2 files changed, 33 insertions, 4 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 } 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. |
