#!/usr/bin/env bash
# Reflows the prose comment on lines FIRST to LAST of FILE. It uses the
# Vim from the Nix shell without a user configuration, so the result is
# the same on every machine. The filetype plugin of Vim supplies the
# comment markers.
set -euo pipefail

if [ $# -ne 3 ]; then
  echo 'usage: bin/reflow FILE FIRST LAST' >&2
  exit 2
fi

file=$1
first=$2
last=$3

vim -u NONE -i NONE -N -n -es \
  -c 'filetype plugin on' \
  -c "edit $file" \
  -c 'set textwidth=80 nojoinspaces formatoptions=cq' \
  -c "${first},${last}s/\\S\\zs  \\+/ /ge" \
  -c "normal! ${first}GV${last}Ggq" \
  -c 'wq'
