% ----------------------------------------------------------------------------
% the XSIM package - verbwrite module
% 
%   eXercise Sheets IMproved
% 
% ----------------------------------------------------------------------------
% Clemens Niederberger
% Web:    https://github.com/cgnieder/xsim
% E-Mail: contact@mychemistry.eu
% ----------------------------------------------------------------------------
% Copyright 2017 Clemens Niederberger
% 
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of LaTeX
% version 2005/12/01 or later.
% 
% This work has the LPPL maintenance status `maintained'.
% 
% The Current Maintainer of this work is Clemens Niederberger.
% ----------------------------------------------------------------------------
% If you have any ideas, questions, suggestions or bugs to report, please
% feel free to contact me.
% ----------------------------------------------------------------------------
\XSIMmodule{verbwrite}{write contents of environments verbatim to files}

\xsim_load_modules:n {base}

\iow_new:N  \l__file_contents_iow
\tl_new:N   \l_xsim_file_begin_tl
\tl_new:N   \l_xsim_file_end_tl
\int_new:N  \l_xsim_line_gobble_int
\int_zero:N \l_xsim_line_gobble_int

\tl_const:Nx \c__xsim_backslash_char_tl { \cs_to_str:N \\ }

\group_begin:
  \char_set_catcode_other:n {37}
  \tl_const:Nn \c__xsim_percent_char_tl {%}
\group_end:

% ----------------------------------------------------------------------------

% the `final' option will prevent writing to files:
% #1: write stream
% #2: file name
\cs_new_protected:Npn \__xsim_open_stream:Nn #1#2
  {
    \file_if_exist:nTF {#2}
      { \xsim_if_final:F { \iow_open:Nn #1 {#2} } }
      {
        % \g_xsim_final_bool is a global variable; however, if it is true and
        % the exercise file doesn't exist, yet, we need to set it locally to
        % false in order to ensure that the file is correctly written and the
        % stream closed afterwards
        \bool_set_false:N \g_xsim_final_bool
        \iow_open:Nn #1 {#2}
      }
  }

% #1: write stream
\cs_new_protected:Npn \__xsim_close_stream:N #1
  { \xsim_if_final:F { \iow_close:N #1 } }

% #1: write stream
% #1: contents
\cs_new_protected:Npn \__xsim_write_to_stream:Nn #1#2
  {
    \xsim_if_final:F
      {
        % remove the /one/ space token with catcode 10 that is inserted if
        % no options are given to the surrounding environment:
        \tl_set:Nn \l__xsim_tmpa_tl {#2}
        \tl_remove_once:Nn \l__xsim_tmpa_tl {~}
        \int_zero:N \l__xsim_tmpa_int
        \int_while_do:nn { \l__xsim_tmpa_int < \l_xsim_line_gobble_int }
          {
            \int_incr:N \l__xsim_tmpa_int
            \tl_set:Nx \l__xsim_tmpa_tl { \tl_tail:N \l__xsim_tmpa_tl }
          }
        \iow_now:NV #1 \l__xsim_tmpa_tl
      }
  }
\cs_generate_variant:Nn \__xsim_write_to_stream:Nn {Nx}

\cs_new:Npn \__xsim_tab: { \c_space_tl \c_space_tl }
\cs_new:Npn \__xsim_par: { ^^J ^^J }

% the following is inspired by the definition of the `filecontents'
% environment:
% #1: boolean - if true an active eol needs to be inserted before
%               starting to write
% #2: file name
\cs_new_protected:Npn \xsim_file_write_start:nn #1#2
  {
    % we need to insert an active ^^M if no options are given
    % see http://tex.stackexchange.com/q/9035/5049 reasons
    \use:nx
      { \__xsim_file_write_start:n {#2} }
      { \bool_if:nF {#1} { \c__xsim_active_eol_tl } }
  }
\cs_generate_variant:Nn \xsim_file_write_start:nn {nV}

\group_begin:
\char_set_catcode_active:n {13} % ^^M (carriage return, endlinechar)
\char_set_catcode_active:n {12} % ^^L (form feed)
\char_set_catcode_active:n {9}  % ^^I (horizontal tab)
%
\tl_const:Nn \c__xsim_active_eol_tl {^^M} %
%
% #1: file name
\cs_new_protected:Npn \__xsim_file_write_start:n #1 %
  { %
    \group_begin: %
    \xsim_if_final:TF %
      { \xsim_verbose:x { Not~ (re-)writing~ file~ `#1'. } } %
      { \xsim_verbose:x { (Re-)writing~ file~ `#1'. } } %
    \__xsim_open_stream:Nn \l__file_contents_iow {#1} %
    \tl_if_blank:VF \l_xsim_file_begin_tl %
      { %
        \xsim_if_final:F %
          { %
            \iow_now:Nx \l__file_contents_iow  %
              { \l_xsim_file_begin_tl } %
          } %
      } %
    \seq_map_inline:Nn \l_char_special_seq %
      { \char_set_catcode_other:N ##1 } %
    \int_step_inline:nnnn {128} {1} {255} %
      { \char_set_catcode_letter:n {##1} } %
    \tl_set:Nx \l__xsim_tmpa_tl %
      { \c__xsim_backslash_char_tl end \cs_to_str:N \{ \@currenvir \cs_to_str:N \} } %
    \use:x %
      { %
        \cs_set:cpn {__xsim_tmpa:www} %
          ####1 \l__xsim_tmpa_tl %
          ####2 \l__xsim_tmpa_tl %
          ####3 \exp_not:N \q_stop: %
      } %
        { %
          \tl_if_blank:nTF {##3} %
            { \__xsim_write_to_stream:Nn \l__file_contents_iow {##1} } %
            { %
              \cs_set:Npx \__xsim_M:w { \exp_not:N \end {\@currenvir} } %
              \char_set_active_eq:nN {13} \__xsim_M:w %
              % the last line is `##1 \end{\@currenvir} ##2':
              % \tl_if_blank:nF {##1} %
              %   { \__xsim_write_to_stream:Nn \l__file_contents_iow {##1} }%
              % \tl_if_blank:nF {##2} %
              %   {}%
            } %
          ^^M %
        } %
    \char_set_catcode_active:n {13} %
    \char_set_catcode_active:n {12} %
    \char_set_catcode_active:n {9} %
    \cs_set:Npx \__xsim_M:w ##1 ^^M %
      { %
        \exp_not:N \__xsim_tmpa:www ##1 %
        \l__xsim_tmpa_tl %
        \l__xsim_tmpa_tl %
        \exp_not:N \q_stop: %
      } %
    \char_set_active_eq:nN {13} \__xsim_M:w %
    \char_set_active_eq:nN {12} \__xsim_par: %
    \char_set_active_eq:nN {9}  \__xsim_tab: %
  } %
\group_end:

\cs_new_protected:Npn \xsim_file_write_stop:
  {
    \tl_if_blank:VF \l_xsim_file_end_tl
      {
        \xsim_if_final:F
          {
            \iow_now:Nx \l__file_contents_iow
              { \l_xsim_file_end_tl }
          }
      }
    \__xsim_close_stream:N \l__file_contents_iow
    \group_end:
  }

% ----------------------------------------------------------------------------

\NewDocumentCommand \XSIMfilewritestart {sm}
  {
    \IfBooleanTF {#1}
      { \xsim_file_write_start:nn { \c_false_bool  } {#2} }
      { \xsim_file_write_start:nn { \c_true_bool } {#2} }
  }

\NewDocumentCommand \XSIMfilewritestop {}
  { \xsim_file_write_stop: }

\NewDocumentCommand \XSIMsetfilebegin {+m}
  { \tl_set:Nn \l_xsim_file_begin_tl {#1} }

\NewDocumentCommand \XSIMsetfileend {+m}
  { \tl_set:Nn \l_xsim_file_end_tl {#1} }

\NewDocumentCommand \XSIMgobblechars {m}
  { \int_set:Nn \l_xsim_line_gobble_int {#1} }
  
% ----------------------------------------------------------------------------
