%%% % -*- coding: utf-8 -*-
%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% % tabularray-abnt.sty
%%% %----------------------------------------------------------------------
%%% % copyright (C) January, 2025 by Sadao Massago
%%% % autor:
%%% %    Sadao Massago
%%% %    e-mail: sadao@ufscar.br
%%% %
%%% % Licença: LaTeX Project Public License versão 1.3c or (se for a sua escolha) qualquer versão posterior.
%%% % https://www.latex-project.org/lppl/
%%% %----------------------------------------------------------------------

%% Need LaTeX 2e version 2020-10-01 or latter (due to AddToHoock)
\NeedsTeXFormat{LaTeX2e}[2020/10/01]

%%% file name
\ProvidesFile{tabularray-abnt.sty}
 [2025/01/16 tabularray-abnt style (require tabularray package)]
\typeout{tabularray-abnt style 2025-01-16 <January/2025>.}

%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% It not works on older LaTeX compatibility mode (documentstyle)

\if@compatibility 
  \PackageError{tabularray-abnt}{Not support older compatible mode (documentstyle)}
     {Use documentclass instead of documentstyle}
  \endinput
\else
  %% OK
\fi

%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% In way to adjust on memoir (ex. abntex2) or abntexto as document class

\newif\if@tabularray@abnt@using@memoir
\newif\if@tabularray@abnt@using@abntexto
\@tabularray@abnt@using@memoirfalse
\@tabularray@abnt@using@abntextofalse
\@ifclassloaded{memoir}% Using memoir?
{\@tabularray@abnt@using@memoirtrue}% YES
{
  \@ifclassloaded{abntexto}% Using ABNTexto?
  {\@tabularray@abnt@using@abntextotrue}% YES
  { % generic class
    \RequirePackage{float}
  }
}

%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Required package

\RequirePackage{tabularray}
\UseTblrLibrary{hook}

%%% %----------------------
%%> \section{ABNT theme}

%% ABNT theme for table
\NewTblrTheme{abnt}{
  \DefTblrTemplate{caption-sep}{default}{\space ---\space}% default is ": \space"
  \SetTblrTemplate{firsthead-text,lasthead-text,conthead-text}{abnt}
  \SetTblrTemplate{caption,lasthead,capcont}{abnt}
  \DefTblrTemplate{firstfoot,middlefoot}{default}{}% disabling the first and middle footnote

%%% \SetTblrTemplate{lastfoot-text,lastfoot-text-note}{abnt}

  %% for abntexto, need to change lot write
  \if@tabularray@abnt@using@abntexto
    \SetTblrTemplate{caption-lot}{abnt}
  \fi
  
  \SetTblrTemplate{remark-tag}{abnt}
  \SetTblrTemplate{remark}{abnt}

  \SetTblrStyle{caption,lasthead,capcont}{font=\normalsize}
  \SetTblrStyle{firsthead-text,lasthead-text,conthead-text}{font=\footnotesize}
  \SetTblrStyle{lastfoot}{font=\footnotesize}
}

%%% Example of how to insert value from parameter
%%% %\DefTblrTemplate{caption-text}{default}{\InsertTblrText{caption}

%%% ---------------------------------
%% theme ``quadro'' (text only table)

%%% % Caution: Avoid space between braces and parameters
\NewTblrTheme{quadro}{
  %% same as abnt theme of table
  \DefTblrTemplate{caption-sep}{default}{\space ---\space}% default is ": \space"
  \SetTblrTemplate{firsthead-text,lasthead-text,conthead-text}{abnt}
  \SetTblrTemplate{caption,lasthead,capcont}{abnt}
  \DefTblrTemplate{firstfoot,middlefoot}{default}{}% desabling first and middle footnote

%%% \SetTblrTemplate{lastfoot-text,lastfoot-text-note}{abnt}
  
%%%  %% for abntexto, need to change lot write
%%%  \if@tabularray@abnt@using@abntexto
%%%  %%\SetTblrTemplate{caption-lot}{abnt}
%%%  \fi
  
  \SetTblrTemplate{remark-tag}{abnt}
  \SetTblrTemplate{remark}{abnt}

  \SetTblrStyle{caption,lasthead,capcont}{font=\normalsize}
  \SetTblrStyle{firsthead-text,lasthead-text,conthead-text}{font=\footnotesize}
  \SetTblrStyle{lastfoot}{font=\footnotesize}

  %% Change specific for ``quadro'
  \SetTblrTemplate{caption-tag}{quadro} % caption change
  \SetTblrTemplate{caption-lot}{quadro} % lot wire change
} 

%%% -----------------------------
%%> \section{Setup table as ABNT}

%% counter of table are not nested

\ifdefined\chapter
  \counterwithout{table}{chapter}
\else
  \ifdefined\section
    \counterwithout{table}{section}
  \fi
\fi

%% counting table and quadro together

%%% \ExplSyntaxOn
\if@tabularray@abnt@using@abntexto

%%%  \newcommand{\tabularray@abnt@tblr@count@roman}{\romannumeral\inteval{\g__tblr_table_count_int + \countquadro}}
  \newcommand{\tabularray@abnt@tblr@count@roman}{\romannumeral\inteval{\value{table} + \countquadro}}
\else

%%%  \newcommand{\tabularray@abnt@tblr@count@roman}{\romannumeral\inteval{\g__tblr_table_count_int + \value{quadro}}}
  \newcommand{\tabularray@abnt@tblr@count@roman}{\romannumeral\inteval{\value{table} + \value{quadro}}}  
\fi

%%% \ExplSyntaxOff

%% additional text for header
\DefTblrTemplate{firsthead-text}{abnt}{\par~\hfill(continua)} % first header
\DefTblrTemplate{lasthead-text}{abnt}{\par~\hfill(conclusão)} % last header
\DefTblrTemplate{conthead-text}{abnt}{\par~\hfill(continuação)} % middle header
%% first header
\DefTblrTemplate{caption}{abnt}{
  \UseTblrTemplate{caption-tag}{default}
  \UseTblrTemplate{caption-sep}{default}
  \UseTblrTemplate{caption-text}{default}
  
%%% % like \ifdefined, but with csname
  \ifcsname tabularray@abnt@tblr@spanpages@\tabularray@abnt@tblr@count@roman\endcsname % if span pages
    \UseTblrTemplate{firsthead-text}{abnt} % add the firsthead-text

%%% DEBUG:\tabularray@abnt@tblr@count@roman
%%%  \else
%%%    DEBUG (no span pages): \roman{tabularray@abnt@global@tblr@counter}
  \fi
}

%% redefine last head title
\DefTblrTemplate{lasthead}{abnt}{
  \UseTblrTemplate{caption-tag}{default}
  \UseTblrTemplate{caption-sep}{default}
  \UseTblrTemplate{caption-text}{default}
  \UseTblrTemplate{lasthead-text}{abnt} % add lasthead-text
}
%% redefine middle head title
\DefTblrTemplate{capcont}{abnt}{
  \UseTblrTemplate{caption-tag}{default}
  \UseTblrTemplate{caption-sep}{default}
  \UseTblrTemplate{caption-text}{default}
  \UseTblrTemplate{conthead-text}{abnt}
}

%%% %-------------------------------------------------
%%> \section{To save ``page span'' status}

\newif\if@tablularray@abnt@mark@spanpages

%%% \AtBeginDocument{%

%%% % \@tablularray@abnt@mark@spanpagesfalse % initially false
\global\let\if@tablularray@abnt@mark@spanpages\iffalse

%%% } % \AtBeginDocument{%

%%% hook tabularray not working as expected. Need more recente version of tabularray?
%%% \AddToHook{tabularray/table/before}
%%% {  
 
%%% % \@tablularray@abnt@mark@spanpagestrue
%%%  \global\let\if@tablularray@abnt@mark@spanpages\iftrue
%%% }
%%% \AddToHook{tabularray/table/after}
%%% {  

%%%%  \@tablularray@abnt@mark@spanpagesfalse
%%%   \global\let\if@tablularray@abnt@mark@spanpages\iffalse
%%% }

%%% % check page span status for longtblr
\AddToHook{env/longtblr/after}{ \global\let\if@tablularray@abnt@mark@spanpages\iftrue }
\AddToHook{env/longtblr/end}{ \global\let\if@tablularray@abnt@mark@spanpages\iffalse }

%%% % check page span status for tblr (with possible long option) 
\AddToHook{env/tblr/after}{ \global\let\if@tablularray@abnt@mark@spanpages\iftrue }
\AddToHook{env/tblr/end}{ \global\let\if@tablularray@abnt@mark@spanpages\iffalse }

%%% % check page span status for tblr like env
%%% % Not work as exprected
%%% \AddToHook{tabularray/table/before}{ \global\let\if@tablularray@abnt@mark@spanpages\iftrue }
%%% \AddToHook{tabularray/table/after}{ \global\let\if@tablularray@abnt@mark@spanpages\iffalse }

%%% {


%%% \AddToHook{env/longtblr/begin}
%%% {  

%%% %  \@tablularray@abnt@mark@spanpagestrue
%%%   \global\let\if@tablularray@abnt@mark@spanpages\iftrue
%%% }

%%% \AddToHook{env/longtblr/end}
%%% {  

%%%  \@tablularray@abnt@mark@spanpagesfalse
%%%   \global\let\if@tablularray@abnt@mark@spanpages\iffalse
%%% }

%%% % For tblr with long opcion 
%%% \AddToHook{env/tblr/begin}
%%% {  

%%% %  \@tablularray@abnt@mark@spanpagestrue
%%%   \global\let\if@tablularray@abnt@mark@spanpages\iftrue
%%% }

%%% \AddToHook{env/tblr/end}
%%% {  

%%% %   \@tablularray@abnt@mark@spanpagesfalse
%%%   \global\let\if@tablularray@abnt@mark@spanpages\iffalse
%% }

%%% talltblr fit in single page (no hook)

%% if change pages, mark as ``span pages'' on aux file

%%% \AddToHook{shipout/after}
\AddToHook{shipout/after}
{
  \if@tablularray@abnt@mark@spanpages
    %% to the associated commands act globally
    %% tip from https://tex.stackexchange.com/questions/115932/on-the-basics-of-writing-to-reading-from-auxiliary-files-aux-toc-etc
    \immediate\write\@auxout{\gdef\string\tabularray@abnt@tblr@spanpages@\tabularray@abnt@tblr@count@roman{true}}

%%% \else % DEBUG
%%%      \immediate\write\@auxout{\gdef\string\tabularray@abnt@tblr@spanpages@\tabularray@abnt@tblr@count@roman{false}}
    
\fi  
  %% to the associated commands act globally
  %% tip from https://tex.stackexchange.com/questions/566884/setting-a-newif-to-false-ignored-on-first-check-in-custom-itemize-environment
  \global\let\if@tablularray@abnt@mark@spanpages\iffalse
  
%%%  % DEBUG:
%%%  \immediate\write\@auxout{\gdef\string\tabularray@abnt@shipout@message{DEGUB: page=\thepage, tblrnum=\tabularray@abnt@tblr@count@roman}} 
}  

%% For abntexto class, need change the form to write on ``lot''
%% For others, only add global counter
\if@tabularray@abnt@using@abntexto
  \ExplSyntaxOn
    \DefTblrTemplate{caption-lot}{abnt}
    {
      \tl_if_empty:NTF \lTblrEntryTl
        {\tl_set_eq:NN \l__tblr_caption_short_tl \lTblrCaptionTl}
        {\tl_set_eq:NN \l__tblr_caption_short_tl \lTblrEntryTl}
      %% \addcontentsline { lot } { table }
      %%  { \protect\numberline { \thetable } { \l__tblr_caption_short_tl } }
      %% add on list of tables using command from abntexto
      \addtoext{lot}{lofi}{\protect\lotlabelbox{\thetable}{\l__tblr_caption_short_tl}}        
    }
  \ExplSyntaxOff
%%%\else% \if@tabularray@abnt@using@abntexto
%%%  \ExplSyntaxOn
%%%    \DefTblrTemplate {caption-lot}{abnt}
%%%    {
%%%    
%%% %%      \stepcounter{tabularray@abnt@global@tblr@counter}% global table/quadro counter    
%%%      \tl_if_empty:NTF \lTblrEntryTl
%%%        { \tl_set_eq:NN \l__tblr_caption_short_tl \lTblrCaptionTl }
%%%        { \tl_set_eq:NN \l__tblr_caption_short_tl \lTblrEntryTl }
%%%      \addcontentsline { lot } { table }
%%%        { \protect\numberline { \thetable } { \l__tblr_caption_short_tl } }
%%%    }
%%%  \ExplSyntaxOff   
\fi% \if@tabularray@abnt@using@abntexto

%% Change remark to use for source and note as ABNT
\DefTblrTemplate{remark-tag}{abnt}{\InsertTblrRemarkTag}

%% Change left margin using tip from
%% https://tex.stackexchange.com/questions/645175/how-to-indent-notes-in-tabularray
\newlength\tabularray@abnt@remark@labellength
\DefTblrTemplate{remark}{abnt}{%
  \MapTblrRemarks{%
    \settowidth{\tabularray@abnt@remark@labellength}{\UseTblrTemplate{remark-tag}{abnt}\UseTblrTemplate{remark-sep}{default}}%
    \UseTblrTemplate{remark-tag}{abnt}\UseTblrTemplate{remark-sep}{default}%
    \parbox[t]{\dimexpr\linewidth-\tabularray@abnt@remark@labellength}{\UseTblrTemplate{remark-text}{default}}%
    \par}\medskip
}

%%% %-------------------
%%> \section{``Quadro'' (text only table)}

%%% %------------------
%% On the abntexto class, create legend entry named ``quadro''. In other cases, create environment ``quadro''.
  
%% Names
\providecommand{\quadroname}{Quadro}
\providecommand{\listquadroname}{Lista de quadros}
\@ifpackageloaded{babel}{
  \ifdefined\captionsportugese
    \addto\captionsportugese{% portugese
      \renewcommand{\quadroname}{Quadro}
      \renewcommand{\listquadroname}{Lista de quadros}
    }
  \fi
  \ifdefined\captionsbrazil
    \addto\captionsbrazil{% brazilian portugese
      \renewcommand{\quadroname}{Quadro}
      \renewcommand{\listquadroname}{Lista de quadros}
    }
  \fi
  \ifdefined\captionsbrazilian
    \addto\captionsbrazilian{% brazilian portugese
      \renewcommand{\quadroname}{Quadro}
      \renewcommand{\listquadroname}{Lista de quadros}
    }
  \fi
  \ifdefined\captionsenglish
    \addto\captionsenglish{% English
      \renewcommand{\quadroname}{Text table}
      \renewcommand{\listquadroname}{List of text table}
    }
  \fi
}{} %  \@ifpackageloaded{babel}{   

%% define for each class

%% ABNTexto class
\if@tabularray@abnt@using@abntexto   % ABNTexto.
  %% using command from ABNTexto  
  \definelegendplace{quadro}{Quadro}{quad.\,}{loq} % new legend entry 

  \ifdefined\chapter
    \newcommand{\listadequadros}{\notoc\nonum\chapter{\listquadroname}\makeloq} 
  \else
    \newcommand{\listadequadros}{\notoc\nonum\section{\listquadroname}\makeloq} 
  \fi
  %% Caution: don't put space between braces and parameters
  \DefTblrTemplate{caption-tag}{quadro}{\quadroname\hspace{0.25em}\the\countquadro}

  \ExplSyntaxOn
    \DefTblrTemplate{caption-lot}{quadro}
    {
    
%%%      \stepcounter{tabularray@abnt@global@tblr@counter}% global table/quadro counter
      \addtocounter{table}{-1}%Não contar como table      
      %% counter created by \definelegendplace{quadro} is not \c@quadro+, but \countquadro, and is necessary to use TeX command to increase
      \global\advance\countquadro by 1% count as ``quadro''
      \tl_if_empty:NTF \lTblrEntryTl
        {\tl_set_eq:NN \l__tblr_caption_short_tl \lTblrCaptionTl}
        {\tl_set_eq:NN \l__tblr_caption_short_tl \lTblrEntryTl}
      %% add to list of ``quadro'' using command from abntexto
      \addtoext{loq}{loqi}{\protect\loqlabelbox{\the\countquadro} {\l__tblr_caption_short_tl}}%
    }
  \ExplSyntaxOff
\else %% memoir (ABNTeX2 or like) or generic class
  \if@tabularray@abnt@using@memoir   %% memoir (ABNTeX2 or like)

%%% %\newfloat[chapter]{quadro}{loq}{\quadroname}
%%% %\counterwithout{quadro}{chapter}
    %% using command from memoir
    \newfloat{quadro}{loq}{\quadroname}
    \newlistof{listadequadros}{loq}{\listquadroname}  

%%% %\newlistentry[chapter]{quadro}{loq}{0}
    \newlistentry{quadro}{loq}{0}
    
    \cftsetindents{quadro}{0em}{2.3em}
    \renewcommand{\cftquadroname}{\quadroname\space}
    \renewcommand*{\cftquadroaftersnum}{\hfill\textendash\hfill}	
  \else %% generic class
    %% using float package
    \newcommand{\listadequadros}{\listof{quadro}{\listofquadrosname}}
    \newfloat{quadro}{tbp}{loq}%[chapter]
    
%%% %\counterwithout{quadro}{chapter} counter not nested frm chapter
  \fi
  
%%% % We need to use \hspace and \enskip, but not ~ or \space,
%%% % since we want a correct hangindent caption paragraph.
  \DefTblrTemplate{caption-tag}{quadro}{\quadroname\hspace{0.25em}\thequadro}

  \ExplSyntaxOn
    \DefTblrTemplate{caption-lot}{quadro}
    {
    
%%%      \stepcounter{tabularray@abnt@global@tblr@counter}% global table/quadro counter    
      \addtocounter{table}{-1}% not count as table
      \stepcounter{quadro}% count as quadro
      \tl_if_empty:NTF \lTblrEntryTl
        { \tl_set_eq:NN \l__tblr_caption_short_tl \lTblrCaptionTl }
        { \tl_set_eq:NN \l__tblr_caption_short_tl \lTblrEntryTl }
      \addcontentsline { loq } { quadro }
        { \protect\numberline { \thequadro } { \l__tblr_caption_short_tl } }
    }
  \ExplSyntaxOff   
\fi

%%% %------------------------------
%%> \section{New table environment}
%% New environment as wrapper for tblr, instead of new tblr, in way to support table font settings 

%% To set table font for new envrronment
\NewDocumentCommand{\SetAbntTblrFont}{+m}
{
  \gdef\@tabularray@abnt@tblr@font{#1}
}

%%% % New environments for tables
\NewDocumentEnvironment{abnttblr}{+o +m +b}{
\ifdefined\@tabularray@abnt@tblr@font \@tabularray@abnt@tblr@font \fi
\begin{tblr}[theme=abnt,#1]{#2}
#3
\end{tblr}
}{}

\NewDocumentEnvironment{tallabnttblr}{+o +m +b}{

%%% tallabnttblr begin
%%%   \if@tablularray@abnt@mark@spanpages
%%%   DEBUG: mark span pages active
%%%  \fi
%%%   table+quadro counter = \tabularray@abnt@tblr@count@roman
\ifdefined\@tabularray@abnt@tblr@font \@tabularray@abnt@tblr@font \fi
\begin{talltblr}[theme=abnt,#1]{#2}
#3
\end{talltblr}

%%%   tallabnttblr end
%%%   \if@tablularray@abnt@mark@spanpages
%%%  DEBUG: mark span pages active
%%%  \fi
%%%  table+quadro counter = \tabularray@abnt@tblr@count@roman
}{}

\NewDocumentEnvironment{longabnttblr}{+o +m +b}{

%%% longabnttblr begin
%%%   \if@tablularray@abnt@mark@spanpages
%%%   DEBUG: mark span pages active
%%%   \fi
%%%   table+quadro counter = \tabularray@abnt@tblr@count@roman
%%% \global\let\if@tablularray@abnt@mark@spanpages\iftrue
\ifdefined\@tabularray@abnt@tblr@font \@tabularray@abnt@tblr@font \fi
\begin{longtblr}[theme=abnt,#1]{#2}
#3
\end{longtblr}

%%% \global\let\if@tablularray@abnt@mark@spanpages\iffalse

%%% longabnttblr end
%%% \if@tablularray@abnt@mark@spanpages
%%%   DEBUG: mark span pages active
%%%   \fi
%%%   table+quadro counter = \tabularray@abnt@tblr@count@roman
}{}

%% end: tabularray-abnt.sty