% This is part of the Tcode kernel. Only intended to by input by it.

%%%%%%%%%%%%%%%*******   Environments stdout and stdin   *******%%%%%%%%%%%%%%%

%For stdout / stdin. The background colour and the formatting of the text (\StdioHook is implied).
\unless\ifdefined\TcodeIncluded
  \def\ApplyConsoleBkg{\color{\ConsoleBkg}} %\ConsoleBkg will be either \StdOutBkg or \StdInBkg
  \let\StdOutBkg\empty %No color. Must be defined exactly like this. (or \def\StdOutBkg{})
  \let\StdInBkg\empty
  \let\FormatStdOut\empty
  \let\FormatStdIn\empty
\fi

{\catcode`\^^I=13 %
\gdef\SetConsoleCatcodes{
 \SetFcodeCatcodes \catcode`\^^M=\active \catcode`\^^I=\active
 \let^^M\StdOutEOL \let^^I=\NcodeTab
% \catcode`\{=\cat@xii \catcode`\}=\cat@xii
}}

\def\stdout{\StdoutStdin{StdOut}{o}}
\def\stdin{\StdoutStdin{StdIn}{i}}

\def\StdoutStdin#1#2{\par
  \def\StdioEnvLetter{#2}
  \vskip\Codeskipbefore
  \setlineboxwd
  \bgroup\offinterlineskip
  \exP\let\exP\ConsoleBkg\csname #1Bkg\endcsname
  \exP\let\exP\FormatText\csname Format#1\endcsname
  \SetCatcodesLineZero
  \StdOutLineZero
}
\def\StdOutLineZero#1^^M{#1\StdOutAfterLineZero}
\def\StdOutAfterLineZero{
  \let\break\CBreak \let\nobreak\CNobreak \let\goodbreak\CGoodbreak
  \SetConsoleCatcodes
  \StdioDefineCommands
  \the\StdioHook
  \SmallSpaceIfColour
  \StdOutLineNew
}

%Add some skip above and below the block of text if the environment has some background colour
\def\SmallSpaceIfColour{\unless\ifx\ConsoleBkg\empty
	\hbox to\hsize{\kern\CodeLeftInd \ApplyConsoleBkg\leaders\hrule height3pt\hfil \kern\CodeRightInd}\no@break
\fi}

\def\StdOutEOL{\closeSTDOUTlinebox\StdOutLineNew}
\def\StdOutLineNew#1{
  \IfStdOutEnd#1\SmallSpaceIfColour\let\next\egroup
  \else\let\next\StdOut@LineNew\fi
  \next#1%
}
\def\StdOut@LineNew{\openSTDOUTlinebox}

%The double \bgroup\bgroup is needed so that the applied colour does not get through the envirionment
%This looks like a bug somewhere in the toolchain
\def\openSTDOUTlinebox{\applyNLpenalty\hbox\bgroup\kern\CodeLeftInd
	\setbox0\hbox to\lineboxwd\bgroup\bgroup\kern\CodeFramewd\kern2pt\FormatText\strut
}
\def\closeSTDOUTlinebox{\kern2pt\kern\CodeFramewd\hss\egroup\egroup %Here ends the box with the contents. Now place a box with the bkg color
	\unless\ifx\ConsoleBkg\empty\hbox to0pt{\ApplyConsoleBkg\vrule width\wd0 height\ht0 depth\dp0\hss}\fi %if requested
	\box0\kern\CodeRightInd\egroup %Here ends the line box
}

%If a line in the code starts with \ this will fail. (?)
\def\IfStdOutEnd#1{
  \def\IfE@ndF@ound{\iftrue}
  \unless\ifx\end#1
  \unless\ifx\endstdout#1
  \unless\ifx\endstdin#1
    \def\IfE@ndF@ound{\csname iffalse\endcsname}
  \fi\fi\fi
  \IfE@ndF@ound
}

%This will be executed *after* the environmnet is closed
\def\endstdout{\vskip\Codeskipafter}
\def\endstdin{\vskip\Codeskipafter}
