|
#!/usr/bin/env bash |
|
# |
|
# glowm - Glow with Mermaid support |
|
# |
|
# Pre-processes markdown files to render ```mermaid blocks as ASCII |
|
# before passing to glow for display. |
|
# |
|
# Requirements: |
|
# - glow (brew install glow) |
|
# - mermaid-ascii (go install github.com/AlexanderGrooff/mermaid-ascii@latest) |
|
# |
|
# Usage: |
|
# glowm README.md |
|
# glowm -p README.md # pager mode |
|
# cat README.md | glowm - # stdin |
|
# |
|
|
|
set -euo pipefail |
|
|
|
# Check dependencies |
|
check_deps() { |
|
local missing=() |
|
command -v glow >/dev/null 2>&1 || missing+=("glow") |
|
command -v mermaid-ascii >/dev/null 2>&1 || missing+=("mermaid-ascii") |
|
|
|
if [[ ${#missing[@]} -gt 0 ]]; then |
|
echo "Error: Missing dependencies: ${missing[*]}" >&2 |
|
echo "Install with:" >&2 |
|
[[ " ${missing[*]} " =~ " glow " ]] && echo " brew install glow" >&2 |
|
[[ " ${missing[*]} " =~ " mermaid-ascii " ]] && echo " go install github.com/AlexanderGrooff/mermaid-ascii@latest" >&2 |
|
exit 1 |
|
fi |
|
} |
|
|
|
# Process markdown: replace ```mermaid blocks with ASCII rendered output |
|
process_mermaid() { |
|
awk ' |
|
BEGIN { in_mermaid = 0; mermaid_content = "" } |
|
|
|
/^```mermaid[[:space:]]*$/ { |
|
in_mermaid = 1 |
|
mermaid_content = "" |
|
next |
|
} |
|
|
|
/^```[[:space:]]*$/ && in_mermaid { |
|
in_mermaid = 0 |
|
|
|
# Write mermaid content to temp file and render |
|
cmd = "mktemp" |
|
cmd | getline tmpfile |
|
close(cmd) |
|
|
|
print mermaid_content > tmpfile |
|
close(tmpfile) |
|
|
|
# Render with mermaid-ascii |
|
render_cmd = "mermaid-ascii -f " tmpfile " 2>/dev/null" |
|
|
|
# Wrap output in a code block for nice glow rendering |
|
print "```" |
|
while ((render_cmd | getline line) > 0) { |
|
print line |
|
} |
|
close(render_cmd) |
|
print "```" |
|
|
|
# Cleanup |
|
system("rm -f " tmpfile) |
|
|
|
mermaid_content = "" |
|
next |
|
} |
|
|
|
in_mermaid { |
|
if (mermaid_content != "") mermaid_content = mermaid_content "\n" |
|
mermaid_content = mermaid_content $0 |
|
next |
|
} |
|
|
|
{ print } |
|
' |
|
} |
|
|
|
# Main |
|
main() { |
|
check_deps |
|
|
|
local glow_args=() |
|
local input_file="" |
|
|
|
# Parse arguments |
|
while [[ $# -gt 0 ]]; do |
|
case "$1" in |
|
-) |
|
input_file="-" |
|
shift |
|
;; |
|
-*) |
|
glow_args+=("$1") |
|
shift |
|
;; |
|
*) |
|
input_file="$1" |
|
shift |
|
;; |
|
esac |
|
done |
|
|
|
# Read input |
|
local content |
|
if [[ "$input_file" == "-" ]] || [[ -z "$input_file" ]]; then |
|
content=$(cat) |
|
elif [[ -f "$input_file" ]]; then |
|
content=$(cat "$input_file") |
|
else |
|
echo "Error: File not found: $input_file" >&2 |
|
exit 1 |
|
fi |
|
|
|
# Process and render |
|
echo "$content" | process_mermaid | glow "${glow_args[@]}" - |
|
} |
|
|
|
main "$@" |