%%% % -*- coding: utf-8 -*-
%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% % tabularray-abnt.sty
%%% %----------------------------------------------------------------------
%%% % copyright: 2025 (C) 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]

% Releases
\DeclareRelease{}{2025-01-16}{tabularray-2025A.sty}
\DeclareCurrentRelease{}{2025-03-14}

%%% package name
\ProvidesPackage{tabularray-abnt}[2025/03/14 tabularray-abnt style (require tabularray package)]

%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Does 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

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

\RequirePackage{tabularray}
\UseTblrLibrary{hook}

% If tabularray is old, use old abularray-abnt too.
\IfPackageAtLeastTF{tabularray}{2025-01-01}{}{\RequirePackage{tabularray-abnt-2025A}\endinput}


%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 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: require float package for this case
    \RequirePackage{float}
  }
}

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

%% ABNT theme for table
\NewTblrTheme{abnt}{
  \DeclareTblrTemplate{caption-sep}{default}{\space ---\space}% default is ": \space"
  \SetTblrTemplate{firsthead-text,lasthead-text,conthead-text}{abnt}
  \SetTblrTemplate{caption,lasthead,capcont}{abnt}
  \DeclareTblrTemplate{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
%%% %\DeclareTblrTemplate{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
  \DeclareTblrTemplate{caption-sep}{default}{\space ---\space}% default is ": \space"
  \SetTblrTemplate{firsthead-text,lasthead-text,conthead-text}{abnt}
  \SetTblrTemplate{caption,lasthead,capcont}{abnt}
  \DeclareTblrTemplate{firstfoot,middlefoot}{default}{}% desabling first and middle footnote

%%% \SetTblrTemplate{lastfoot-text,lastfoot-text-note}{abnt}
   
  \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 write 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{\value{table} + \countquadro}}
\else
  \newcommand{\tabularray@abnt@tblr@count@roman}{\romannumeral\inteval{\value{table} + \value{quadro}}}  
\fi
%%% \ExplSyntaxOff

%% additional text for header
\DeclareTblrTemplate{firsthead-text}{abnt}{\par~\hfill(continua)} % first header
\DeclareTblrTemplate{lasthead-text}{abnt}{\par~\hfill(conclusão)} % last header
\DeclareTblrTemplate{conthead-text}{abnt}{\par~\hfill(continuação)} % middle header
%% first header
\DeclareTblrTemplate{caption}{abnt}{
  \UseTblrTemplate{caption-tag}{default}
  \UseTblrTemplate{caption-sep}{default}
  \UseTblrTemplate{caption-text}{default}
  
%%% % \ifcsname is 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
  \fi
}

%% redefine last head title
\DeclareTblrTemplate{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
\DeclareTblrTemplate{capcont}{abnt}{
  \UseTblrTemplate{caption-tag}{default}
  \UseTblrTemplate{caption-sep}{default}
  \UseTblrTemplate{caption-text}{default}
  \UseTblrTemplate{conthead-text}{abnt}
}

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

%% To save ``page span'' status

\AddToHook{tabularray/table/after}
{  
  \ifnum\lTblrTablePageInt>1%
    \immediate\write\@auxout{\gdef\string\tabularray@abnt@tblr@spanpages@\tabularray@abnt@tblr@count@roman{true}}  
%
  \fi 
}


%%> change 'lot' for abntexto (that write on lot file) }
%%
%% For abntexto class, need change the form to write on ``lot''
%% For others, only add global counter
\if@tabularray@abnt@using@abntexto
  \ExplSyntaxOn
    \DeclareTblrTemplate{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
\fi% \if@tabularray@abnt@using@abntexto

%% Change remark to use for source and note as ABNT
\DeclareTblrTemplate{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
\DeclareTblrTemplate{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
  \DeclareTblrTemplate{caption-tag}{quadro}{\quadroname\hspace{0.25em}\the\countquadro}

  \ExplSyntaxOn
    \DeclareTblrTemplate{caption-lot}{quadro}
    {
      \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 from chapter
  \fi
  
%%% % We need to use \hspace and \enskip, but not ~ or \space,
%%% % since we want a correct hangindent caption paragraph.
  \DeclareTblrTemplate{caption-tag}{quadro}{\quadroname\hspace{0.25em}\thequadro}

  \ExplSyntaxOn
    \DeclareTblrTemplate{caption-lot}{quadro}
    {   
      \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}{
\ifdefined\@tabularray@abnt@tblr@font \@tabularray@abnt@tblr@font \fi
\begin{talltblr}[theme=abnt,#1]{#2}
#3
\end{talltblr}
}{}

\NewDocumentEnvironment{longabnttblr}{+o +m +b}{
\ifdefined\@tabularray@abnt@tblr@font \@tabularray@abnt@tblr@font \fi
\begin{longtblr}[theme=abnt,#1]{#2}
#3
\end{longtblr}

}{}

%% end: tabularray-abnt.sty