#!/bin/bash
#==============================================================================
# MODULE     : tm_xypic
# VERSION    : 1.0
# DESCRIPTION: A simple XYpic interface for TeXmacs
# COPYRIGHT  : (C) 2004 Nicolas Ratier (nicolas DOT ratier AT lpmo DOT edu)
#------------------------------------------------------------------------------
# COPYRIGHT  : (C) XYpic latex package Kristoffer H. Rose
#------------------------------------------------------------------------------
# Usage within TeXmacs:
#   + write XYpic-commands in multi-line separate by SHIFT-ENTER,
#   + then ENTER key terminates the input and sends it to latex.
# Informations:
#   + Output is the 2D graphic made via latex (package xy}, and dvips -E mode.
#   + Temporary file are made in ~/.TeXmacs/system/tmp.
#------------------------------------------------------------------------------
# This software falls under the GNU general public license version 3 or later.
# It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
# in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
#==============================================================================

# option --texmacs
# for compatibility with TeXmacs interface convention and user information
if [ "$1" != "--texmacs" ]
then
	echo tm_xypic. This script should be started only from TeXmacs.
	exit
fi

# Control characters
tmp=`echo DATA_BEGIN=X DATA_END=Y DATA_ESCAPE=Z | tr "XYZ" "\002\005\027" `
eval $tmp

# Defining temporary files directory and make it if it doesn't exist
TEMP_DIR=~/.TeXmacs/system/tmp
if [ -d $TEMP_DIR ]
then
	cd $TEMP_DIR
else
	mkdir -p $TEMP_DIR
	cd $TEMP_DIR
fi

# Defining temporary file name
TEMP_FILE=TMPxypicTMP

# Startup banner
echo -n $DATA_BEGIN
echo verbatim: TeXmacs interface to XYpic \(high level 2-dimensional graphics\)

# Prompt-input-xypic-output loop
while [ 1 ]; do
	# Prompt
	echo -n $DATA_BEGIN
	echo -n channel:prompt
	echo -n $DATA_END
	echo -n XYpic'] '
	echo -n $DATA_END

	# Read a line from stdin
	read -r input

	# Begin creation of LaTeX file
	echo -E "\documentclass{article}" >  $TEMP_FILE.tex
	echo -E "\usepackage[all]{xy}"    >> $TEMP_FILE.tex
	echo -E "\pagestyle{empty}"       >> $TEMP_FILE.tex
	echo -E "\begin{document}"        >> $TEMP_FILE.tex

	# Copy XYpic command in LaTeX file
	echo -E $input | tr  "~" "\n" | cat >> $TEMP_FILE.tex

	# Finish LaTeX file
	echo -E "\end{document}"          >> $TEMP_FILE.tex

	# Compile with latex, transform to .eps and cat .eps to TeXmacs.
	latex --interaction=nonstopmode  $TEMP_FILE.tex > /dev/null
	dvips -q -f -E $TEMP_FILE.dvi -o $TEMP_FILE.eps > /dev/null
	echo -n $DATA_BEGIN
	echo -n verbatim:
	echo -n $DATA_BEGIN
	echo -n ps:
	cat $TEMP_FILE.eps
	echo -n $DATA_END
	echo -ne "\n"
	rm $TEMP_FILE.*
done
