% kpi-thesis-tables.sty — DSTU tables: kpitable, Y and L columns.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{kpi-thesis-tables}[2026/11/17 v2.0 DSTU tables: kpitable, Y and L columns]
\RequirePackage{array}
\RequirePackage{tabularx}
\RequirePackage{longtable}
\RequirePackage{needspace}
\RequirePackage{ragged2e}
\setlength{\LTcapwidth}{\textwidth}

\newcolumntype{Y}{>{\RaggedRight\arraybackslash}X}
% Flush-left cell that never breaks a word: \begin{kpitable}{|L{4cm}|L{10cm}|}...
% Defined at \begin{document}, so a work that has its own L (from v1.1) keeps it without a warning.
\AtBeginDocument{\@ifundefined{NC@find@L}%
  {\newcolumntype{L}[1]{>{\RaggedRight\arraybackslash\hyphenpenalty=10000\exhyphenpenalty=10000}p{#1}}}{}}

% Long table with the ДСТУ continuation line and repeated header. The \label goes inside
% the caption so editors (texlab) see it:
%   \begin{kpitable}{|p{4cm}|p{10cm}|}{Назва\label{tab:key}}{Поле & Опис}  rows  \end{kpitable}
% The caption and header never stay alone at the bottom of a page: the table starts on a new
% page unless the header plus [N] more lines fit (default 5: caption and ~3 rows; 0 = off).
% A longtable \hline is drawn twice around its break point, so a row rule at a page break
% reappeared at the top of the next page. Here the header already opens each page: one rule.
\ExplSyntaxOn
\def\kpi@LT@hline{%
  \noalign{\ifnum0=`}\fi\penalty\@M\futurelet\@let@token\kpi@LT@@hline}
\def\kpi@LT@@hline{%
  \ifx\@let@token\hline
    \gdef\LT@sep{\penalty\@M\vskip\doublerulesep}%
  \else
    \gdef\LT@sep{\penalty-\@lowpenalty}%
  \fi
  \ifnum0=`{\fi}%
  \multispan\LT@cols\unskip\leaders\hrule\@height\arrayrulewidth\hfill\cr
  \noalign{\cs_if_exist_use:N \tbl_gdecr_row_count: \LT@sep}}
\ExplSyntaxOff
\newsavebox\kpi@tablehead
\NewDocumentEnvironment{kpitable}{O{5} m m m}{%
  \let\LT@hline\kpi@LT@hline
  \ifnum#1>0
    \sbox\kpi@tablehead{\begin{tabular}{#2}\hline #4 \\ \hline\end{tabular}}%
    \Needspace{\dimexpr\ht\kpi@tablehead+\dp\kpi@tablehead+#1\baselineskip\relax}%
  \fi
  \begin{longtable}{#2}
  \caption{#3}\\
  \hline #4 \\ \hline
  \endfirsthead
  \caption*{Продовження таблиці \thetable}\\
  \hline #4 \\ \hline
  \endhead
}{%
  \end{longtable}%
}
\NewDocumentCommand\tablecontinued{}{\caption*{Продовження таблиці \thetable}}

\endinput
