#!/bin/sh -e
#
# usage: edit-text-field [ARGS_FOR_GVIM]
#
# This script lets you edit the contents of the currently focused text field
# through a temporary file in GVim.  Any changes you write to the temporary
# file will be stored into clipboard after you quit GVim, ready for pasting.
#
# ---
# source: https://github.com/sunaku/home

tmp=$(mktemp)              # create a temporary file
trap 'rm -f "$tmp"' EXIT   # ensure it is cleaned up
trap 'exit' TERM INT

if [ -n "${DISPLAY:-}" ] && [ -z "${CROUTON:-}" ]; then
  xdotool key ctrl+a      # select all text in field
  xdotool key ctrl+c      # copy text into clipboard
  xsel -b -o >"${tmp}"    # dump clipboard into file
  gvim -f "$@" "${tmp}"   # edit the dumped contents
  xsel -b -i <"${tmp}"    # load file into clipboard
else
  echo 'Press CONTROL+SHIFT+V and then ENTER and then CONTROL+D:' >&2
  echo '--------------------------------------------------------' >&2
  cat >"${tmp}"           # dump clipboard into file
  echo '--------------------------------------------------------' >&2
  vim -f "$@" "${tmp}"    # edit the dumped contents
  cat "${tmp}"            # for user's own reference
  yank <"${tmp}"          # load file into clipboard
fi
