ollie/data/scripts/acme/Explain

41 lines
975 B
Bash
Executable File

#!/bin/bash
# Explain - Ask ollie to explain the selected code in acme
#
# Usage: Select code, then middle-click Explain in the tag
# Sends: "Explain this code (from <filename>):\n\n```\n<selection>\n```"
set -euo pipefail
if [[ -z "${winid:-}" ]]; then
echo "Explain must be run from within acme" >&2
exit 1
fi
# Get the window name (filename) from the tag
filename=$(9p read acme/$winid/tag | awk '{print $1}')
# Read the current selection by setting addr to dot and reading xdata
echo 'addr=dot' | 9p write acme/$winid/ctl
selection=$(9p read acme/$winid/xdata 2>/dev/null || true)
if [[ -z "$selection" ]]; then
echo "No selection. Select some code first." >&2
exit 1
fi
# Build context string
context=""
if [[ -n "$filename" && "$filename" != *"+Errors" && "$filename" != "+*" ]]; then
context=" (from $filename)"
fi
# Build the prompt
prompt="Explain this code${context}:
\`\`\`
$selection
\`\`\`"
# Send to ollie
echo "$prompt" | o prompt