optimize_highlighted_html() {
	sed \
		-e 's/<span class="w">\([[:space:]]*\)<\/span>/\1/g' \
		-e 's/<span class="sh-normal">\([[:space:]]*\)<\/span>/\1/g' \
		"$1"
}

highlight_code() {
	code_file=$1
	lang=$2
	highlight_output=$3
	unoptimized_file=$tmp/code-unoptimized.html

	[ "$lang" != text ] || return 1
	rm -f "$unoptimized_file"

	case $highlighter in
		pygments)
			highlight_pygments "$code_file" "$lang" "$unoptimized_file" || return 1
			;;
		source-highlight)
			highlight_source "$code_file" "$lang" "$unoptimized_file" || return 1
			;;
		none) return 1 ;;
	esac

	optimize_highlighted_html "$unoptimized_file" > "$highlight_output" || return 1
}

highlight_pygments() {
	code_file=$1
	lang=$2
	output_file=$3

	[ -n "$pygmentize" ] || return 1

	case $lang in
		'')
			"$pygmentize" -f html -O nowrap "$code_file" > "$output_file"
			;;
		auto)
			auto_lexer=$("$pygmentize" -N "$code_file" 2>/dev/null || printf text)
			case $auto_lexer in
				''|text)
					"$pygmentize" -f html -O nowrap -g "$code_file" > "$output_file"
					;;
				*)
					if safe_lang "$auto_lexer"; then
						"$pygmentize" -f html -O nowrap -l "$auto_lexer" "$code_file" > "$output_file"
					else
						"$pygmentize" -f html -O nowrap -g "$code_file" > "$output_file"
					fi
					;;
			esac
			;;
		*)
			"$pygmentize" -f html -O nowrap -l "$lang" "$code_file" > "$output_file"
			;;
	esac
}

highlight_source() {
	code_file=$1
	lang=$2
	output_file=$3

	[ -n "$source_highlight" ] && [ -f "$outlang" ] || return 1

	case $lang in
		''|auto)
			"$source_highlight" --no-doc --outlang-def="$outlang" \
				--input="$code_file" --output=STDOUT > "$output_file"
			;;
		make)
			"$source_highlight" --no-doc --outlang-def="$outlang" \
				--src-lang=makefile \
				--input="$code_file" --output=STDOUT > "$output_file"
			;;
		*)
			"$source_highlight" --no-doc --outlang-def="$outlang" \
				--src-lang="$lang" \
				--input="$code_file" --output=STDOUT > "$output_file"
			;;
	esac
}
