%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% File transcript.sty
%%
%% Generate properly tagged and aligned conversation transcripts
%%
%% Author: Juergen Spitzmueller <juergen.spitzmueller@univie.ac.at>
%%
%% 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 2003/12/01 or later.
%%
%% This work has the LPPL maintenance status "maintained".
%% 
%% The Current Maintainer of this work is Juergen Spitzmueller.
%%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{transcript}
  [2026/12/04 v1.0 Support for conversation transcripts]


% --------------------------------------------------------------------------
% Required packages
% --------------------------------------------------------------------------

% For \Mark
\RequirePackage{marginnote}


% --------------------------------------------------------------------------
% Initialization
% --------------------------------------------------------------------------

% Register ColSpan attributes (2..32) using modern \NewTagAttribute or fallback
\newcount\transcript@cs@cnt
\def\transcript@init@colspan@attrs{%
  \transcript@cs@cnt=2\relax
  \loop\ifnum\transcript@cs@cnt<33\relax
    \ifdefined\NewTagAttribute
      \edef\transcript@tmp@attr{%
        \noexpand\NewTagAttribute{transcript-cs-\the\transcript@cs@cnt}%
          {/O /Table /ColSpan \the\transcript@cs@cnt}%
      }%
      \transcript@tmp@attr
    \else
      \ifdefined\tagpdfsetup
        \edef\transcript@tmp@attr{%
          \noexpand\tagpdfsetup{newattribute={transcript-cs-\the\transcript@cs@cnt}%
            {/O /Table /ColSpan \the\transcript@cs@cnt}}%
        }%
        \transcript@tmp@attr
      \fi
    \fi
    \advance\transcript@cs@cnt\@ne
  \repeat
}


% --------------------------------------------------------------------------
% Conditionals
% --------------------------------------------------------------------------

% track whether we use tagging
\newif\if@transcript@tagging
\@transcript@taggingfalse
\AddToHook{package/tagpdf/after}{%
    \@transcript@taggingtrue
    \transcript@init@colspan@attrs
}

% Track whether linename was explicitly customized via options
\newif\if@transcript@customlinename
\@transcript@customlinenamefalse

% Same for plural linesname
\newif\if@transcript@customlinesname
\@transcript@customlinesnamefalse

% Use line numbers?
\newif\if@transcriptln
\@transcriptlnfalse

% Pad zeros in printed line numbers?
\newif\if@transcript@lnpadzeros
\@transcript@lnpadzerosfalse

% Pad zeros in cross-references?
\newif\if@transcript@lnpadref
\@transcript@lnpadreftrue

% in translation line?
\newif\if@transcript@trline
\@transcript@trlinefalse

% Enable standard TeX ligatures?
\newif\if@transcript@texligatures
\@transcript@texligaturesfalse


% --------------------------------------------------------------------------
% Counter and lengths
% --------------------------------------------------------------------------

% Counter for transcript examples.
\newcounter{transcript}

% Line numbering
\newcounter{tsline}
% Consider padzeros option
\renewcommand*\thetsline{%
  \if@transcript@lnpadzeros
    \if@transcript@lnpadref
      \transcript@padzeros{\arabic{tsline}}%
    \else
      \arabic{tsline}%
    \fi
  \else
    \arabic{tsline}%
  \fi
}

% VSpace above transcript environment
\newlength\transcript@beforeenv
\setlength\transcript@beforeenv{\topsep}
% and below
\newlength\transcript@afterenv
\setlength\transcript@afterenv{\topsep}

% widest line number width
\newlength\transcript@lnwidth

% padding width before line number
\newlength\transcript@lnpadwidth

% actual line number width
\newlength\transcript@real@lnwidth

% highest line nuber
\def\transcript@widest@ln{}

% Desired visible gap between transcript heading and first transcript line
\newlength{\transcript@vskip}
\setlength{\transcript@vskip}{.25\baselineskip}

% Vertical space between caption and postcaption
\newlength{\transcript@postcaptionskip}
\setlength{\transcript@postcaptionskip}{0pt}

% Vertical space between transcript and posttext
\newlength{\transcript@posttextskip}
\setlength{\transcript@posttextskip}{.25\baselineskip}

% Caption indentation, automatically calculated
\newlength{\transcript@captionindent}

% Separator between line number and rest of line
\newlength\transcript@linenrskip
\setlength\transcript@linenrskip{.75em}

% widest interlocutor width
\newlength\transcript@ilwidth

% actual interlocutor width
\newlength\transcript@real@ilwidth

% widest interlocutor
\def\transcript@widest@il{X}

% Separator after interlocutors
\def\transcript@ilsep{}

% Separator between interlocutor and rest of line
\newlength\transcript@ilskip
\setlength\transcript@ilskip{.75em}


% --------------------------------------------------------------------------
% Captions & Strings
% --------------------------------------------------------------------------

% Caption
\providecommand*\transcriptname{Transcript}
\providecommand*\transcriptsname{Transcripts}

% List header
\providecommand*\listtranscriptname{List of Transcripts}

% Line reference prefixes (singular and plural)
\providecommand*\transcriptlinename{l.}
\providecommand*\transcriptlinesname{ll.}

% Separators between reference prefix and number
\providecommand*\transcriptrefsep{\nobreakspace}
\providecommand*\transcriptlinerefsep{\,}

% Overlap: starting delimiter
\def\transcript@olstart{[}
% end terminating delimiter
\def\transcript@olend{]}


% --------------------------------------------------------------------------
% Font settings
% --------------------------------------------------------------------------

% caption
\def\transcript@captionfont{\rmfamily}

% caption label
\def\transcript@captionlabelfont{\bfseries}

% post caption text
\def\transcript@postcaptionfont{\transcript@captionfont}

% transcript
\def\transcript@font{\ttfamily}

% linenumber
\def\transcript@lnfont{\transcript@font}

% interlocutor
\def\transcript@ilfont{\transcript@font}

% interlinear translation
\def\transcript@trlfont{\transcript@font\itshape}

% posttext
\def\transcript@posttextfont{\transcript@captionfont}


% --------------------------------------------------------------------------
% Package hooks
% --------------------------------------------------------------------------

% Hook into zref-clever if loaded
% (registers 'transcript' type and maps 'tsline' to 'line')
\AddToHook{package/zref-clever/after}{%
  \zcRefTypeSetup{transcript}{%
    Name-sg = \transcriptname ,
    name-sg = \transcriptname ,
    Name-pl = \transcriptsname ,
    name-pl = \transcriptsname ,
  }%
  \if@transcript@customlinename
    \zcRefTypeSetup{line}{%
      Name-sg = \transcriptlinename ,
      name-sg = \transcriptlinename ,
    }%
  \fi
  \if@transcript@customlinesname
    \zcRefTypeSetup{line}{%
      Name-pl = \transcriptlinesname ,
      name-pl = \transcriptlinesname ,
    }%
  \fi
  \zcRefTypeSetup{transcript}{%
    namesep = \transcriptrefsep ,
  }%
  \zcRefTypeSetup{line}{%
    namesep = \transcriptlinerefsep ,
  }%
  \zcsetup{%
    countertype={transcript=transcript},
    countertype={tsline=line},
    counterresetby={tsline=transcript},
  }%
}


% --------------------------------------------------------------------------
% Package options
% --------------------------------------------------------------------------

\DeclareKeys[transcript]
{
    % beforeenv={length}
    beforeenv.code = { \setlength\transcript@beforeenv{#1} },
    % afterenv={length}
    afterenv.code = { \setlength\transcript@afterenv{#1} },
    % belowcaptionskip={length}
    belowcaptionskip.store = \transcript@vskip,
    % abovepostcaptionskip={length}
    abovepostcaptionskip.store = \transcript@postcaptionskip,
    % aboveposttextskip={length}
    aboveposttextskip.store = \transcript@posttextskip,
    % font={font setting}
    font.store = \transcript@font,
    % captionfont={font setting}
    captionfont.store = \transcript@captionfont,
    % captionlabelfont={font setting}
    captionlabelfont.store = \transcript@captionlabelfont,
    % postcaptionfont={font setting}
    postcaptionfont.store = \transcript@postcaptionfont,
    % posttextfont={font setting}
    posttextfont.store = \transcript@posttextfont,
    % transcriptname={string}
    transcriptname.store = \transcriptname,
    % transcriptsname={string}
    transcriptsname.store = \transcriptsname,
    % listtranscriptname={string}
    listtranscriptname.store = \listtranscriptname,
    % linenumbers=<true|false>
    linenumbers.if = @transcriptln,
    % widestnumber={string}
    widestnumber.store = \transcript@widest@ln,
    % padzeros=<true|false>
    padzeros.if = @transcript@lnpadzeros,
    % padref=<true|false>
    padref.if = @transcript@lnpadref,
    % linename={string}
    linename.code = {%
      \def\transcriptlinename{#1}%
      \global\@transcript@customlinenametrue
      \AddToHook{package/zref-clever/after}{%
        \zcRefTypeSetup{line}{Name-sg = \transcriptlinename,
                              name-sg = \transcriptlinename}%
      }%
    },
    % linesname={string}
    linesname.code = {%
      \def\transcriptlinesname{#1}%
      \global\@transcript@customlinesnametrue
      \AddToHook{package/zref-clever/after}{%
        \zcRefTypeSetup{line}{Name-pl = \transcriptlinesname,
                              name-pl = \transcriptlinesname}%
      }%
    },
    % refsep={separator}
    refsep.store = \transcriptrefsep,
    % linerefsep={separator}
    linerefsep.store = \transcriptlinerefsep,
    % lnfont={font setting}
    lnfont.store = \transcript@lnfont,
    % lnskip={length}
    lnskip.code = { \setlength\transcript@linenrskip{#1} },
    % widestactor={string}
    widestactor.store = \transcript@widest@il,
    % actorskip={length}
    actorskip.code = { \setlength\transcript@ilskip{#1} },
    % actorsep={length}
    actorsep.store = \transcript@ilsep,
    % actorfont={font setting}
    actorfont.store = \transcript@ilfont,
    % trlfonr={font setting}
    trlfont.store = \transcript@trlfont,
    % olstart={string}
    olstart.store = \transcript@olstart,
    % olend={string}
    olend.store = \transcript@olend,
    % texligatures=<true|false>
    texligatures.if = @transcript@texligatures,
}

% Process package options
\ProcessKeyOptions[transcript]

% Interface to change mid-document
\NewDocumentCommand\TranscriptOptions{m}
  {\SetKeys[transcript]{#1}}


% --------------------------------------------------------------------------
% Internal state for table-based PDF tagging
% --------------------------------------------------------------------------

% True if a semantic transcript row (PDF TR element) is currently open.
\newif\iftranscript@rowopen

% True if a semantic transcript cell (PDF TD element) is currently open.
\newif\iftranscript@cellopen

% True if marked content for the current semantic cell is open.
\newif\iftranscript@mcopen

% True if an utterance text cell has already been opened in the current row.
\newif\iftranscript@textcellopened
\newif\iftranscript@incontinuation

% Column tracking per row and per transcript environment (persisted via .aux).
% Column, text-cell, and row tracking per transcript environment (persisted via .aux).
\newcount\transcript@rowidx
\newcount\transcript@olidx
\newcount\transcript@txtidx
\newcount\transcript@rowcol
\newcount\transcript@curmaxcols
\newcount\transcript@maxcols
\transcript@maxcols=3\relax

% Auxiliary macros read from .aux file to restore max column count and
% whether a given \OL ends its row (so it takes the remaining ColSpan).
\newcommand*\transcript@setmaxcols[2]{%
  \expandafter\gdef\csname transcript@aux@maxcols@#1\endcsname{#2}%
}

\newcommand*\transcript@setolends[3]{%
  \expandafter\gdef\csname transcript@aux@olends@#1@#2@#3\endcsname{1}%
}

\newcommand*\transcript@settxtbeforeol[3]{%
  \expandafter\gdef\csname transcript@aux@txtbeforeol@#1@#2@#3\endcsname{1}%
}

\newcommand*\transcript@setrowmarked[2]{%
  \expandafter\gdef\csname transcript@aux@marked@#1@#2\endcsname{1}%
}

% --------------------------------------------------------------------------
% Internal helpers for semantic transcript table, rows, and cells
% --------------------------------------------------------------------------

% Start normal marked content for the current transcript cell.
%
\def\transcript@startmc{%
  \iftranscript@mcopen
    % Marked content is already open.
  \else
    \if@transcript@tagging
       \tagmcbegin{}%
       \global\transcript@mcopentrue
    \fi%
  \fi
}

% End normal marked content for the current transcript cell.
%
\def\transcript@stopmc{%
  \iftranscript@mcopen
    \tagmcend
    \global\transcript@mcopenfalse
  \fi
}

% Open one semantic table cell (<TD>), optionally with ColSpan > 1.
%
\def\transcript@opencell{%
  \iftranscript@cellopen
    \transcript@closecell
  \fi
  \global\advance\transcript@rowcol\@ne
  \ifnum\transcript@rowcol>\transcript@curmaxcols
    \global\transcript@curmaxcols\transcript@rowcol
  \fi
  \if@transcript@tagging
    \tagstructbegin{tag=TD}%
  \fi%
  \global\transcript@cellopentrue
  \global\transcript@mcopenfalse
  \transcript@startmc
}

% Open a semantic table cell (<TD>) spanning all remaining columns in the row.
%
\def\transcript@opencell@span{%
  \iftranscript@cellopen
    \transcript@closecell
  \fi
  \global\advance\transcript@rowcol\@ne
  \ifnum\transcript@rowcol>\transcript@curmaxcols
    \global\transcript@curmaxcols\transcript@rowcol
  \fi
  \if@transcript@tagging
    \count@=\transcript@maxcols
    \advance\count@ -\transcript@rowcol
    \advance\count@ \@ne
    \ifnum\count@>1\relax
      \edef\transcript@tmp@td{%
        \noexpand\tagstructbegin{tag=TD,attribute=transcript-cs-\the\count@}%
      }%
      \transcript@tmp@td
    \else
      \tagstructbegin{tag=TD}%
    \fi
  \fi%
  \global\transcript@cellopentrue
  \global\transcript@mcopenfalse
  \transcript@startmc
}

% Close the current semantic table cell (<TD>), if one is open.
%
\def\transcript@closecell{%
  \iftranscript@cellopen
    \transcript@stopmc
    \if@transcript@tagging
      \tagstructend
    \fi%
    \global\transcript@cellopenfalse
  \fi
}

% Open one semantic transcript row (<TR>).
%
% Important:
% This macro deliberately does not inspect, wrap, redefine or otherwise
% interfere with \TLP. The internal tabbing operations must remain untouched
% in order to preserve the correct visual layout.
%
\def\transcript@openrow{%
  \iftranscript@rowopen
    \transcript@closerow
  \fi
  \global\advance\transcript@rowidx\@ne
  \global\transcript@olidx=0\relax
  \global\transcript@txtidx=0\relax
  \global\transcript@rowcol=0\relax
  \global\transcript@textcellopenedfalse
  \global\transcript@incontinuationfalse
  \if@transcript@tagging
    \tagstructbegin{tag=TR}%
  \fi%
  \global\transcript@rowopentrue
  \global\transcript@cellopenfalse
  \global\transcript@mcopenfalse
}

% Close the current semantic transcript row (<TR>), if one is open.
%
\def\transcript@closerow{%
  \transcript@closecell
  \iftranscript@rowopen
    \if@transcript@tagging
      \tagstructend
    \fi%
    \global\transcript@rowopenfalse
  \fi
}

% Skip all space tokens before inspecting the next real token, recording if any space was seen
\newif\iftranscript@hadspace
\def\transcript@skipspaces#1{%
  \global\transcript@hadspacefalse
  \def\transcript@skip@cont{#1}%
  \futurelet\transcript@nexttoken\transcript@skipspaces@loop
}
\def\transcript@skipspaces@loop{%
  \ifx\transcript@nexttoken\@sptoken
    \global\transcript@hadspacetrue
    \expandafter\transcript@skipspaces@eat
  \else
    \expandafter\transcript@skip@cont
  \fi
}
\def\transcript@skipspaces@eat{%
  \afterassignment\transcript@skipspaces@next
  \let\transcript@tmp@tok= %
}
\def\transcript@skipspaces@next{%
  \futurelet\transcript@nexttoken\transcript@skipspaces@loop
}

% Decide after actor cell whether to open an utterance <TD> or let \OL open its own <TD>
\def\transcript@after@actor{%
  \transcript@skipspaces\transcript@after@actor@aux
}

\def\transcript@after@actor@aux{%
  \ifx\transcript@nexttoken\OL
    % \OL will open its own <TD>
  \else\ifx\transcript@nexttoken\OLS
    % \OLS will open its own <TD>
  \else\ifx\transcript@nexttoken\OLE
    % \OLE will open its own <TD>
  \else
    \global\advance\transcript@txtidx\@ne
    \@ifundefined{transcript@aux@txtbeforeol@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@txtidx}%
      {\transcript@opencell@span}%
      {\transcript@opencell}%
    \global\transcript@textcellopenedtrue
  \fi\fi\fi
}

% Decide after \OL whether the overlap ends the row (ColSpan) or more text/\OL follows
\newif\iftranscript@ol@endrow
\def\transcript@after@ol{%
  \transcript@skipspaces\transcript@after@ol@aux
}

\ExplSyntaxOn
\cs_new_protected:Npn \transcript@check@endrow
  {
    \bool_lazy_or:nnTF
      {
        \bool_lazy_or_p:nn
          {
            \bool_lazy_or_p:nn
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \\ }
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \Turn }
          }
          {
            \bool_lazy_or_p:nn
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \TTR }
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \TrSkip }
          }
      }
      {
        \bool_lazy_or_p:nn
          {
            \bool_lazy_or_p:nn
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \end }
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \label }
          }
          {
            \bool_lazy_or_p:nn
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \par }
              { \token_if_eq_meaning_p:NN \transcript@nexttoken \relax }
          }
      }
      { \transcript@ol@endrowtrue }
      {
        \token_if_eq_catcode:NNTF \transcript@nexttoken \egroup
          { \transcript@ol@endrowtrue }
          { \transcript@ol@endrowfalse }
      }
  }
\ExplSyntaxOff

\def\transcript@after@ol@aux{%
  \transcript@check@endrow
  \iftranscript@ol@endrow
    \if@filesw
      \immediate\write\@auxout{%
        \string\transcript@setolends{\arabic{transcript}}{\the\transcript@rowidx}{\the\transcript@olidx}%
      }%
    \fi
    \transcript@closecell
  \else
    \transcript@closecell
    \ifx\transcript@nexttoken\OL
      % Next \OL will open its own <TD>
      \iftranscript@hadspace\ \fi
    \else\ifx\transcript@nexttoken\OLS
      % Next \OLS will open its own <TD>
      \iftranscript@hadspace\ \fi
    \else\ifx\transcript@nexttoken\OLE
      % Next \OLE will close the current overlap <TD>
      \iftranscript@hadspace\ \fi
    \else
      \global\advance\transcript@txtidx\@ne
      \@ifundefined{transcript@aux@txtbeforeol@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@txtidx}%
        {\transcript@opencell@span}%
        {\transcript@opencell}%
      \global\transcript@textcellopenedtrue
      \iftranscript@hadspace\ \fi
    \fi\fi\fi
  \fi
}

% After \@tabcr and after removal of source indentation, determine whether
% another transcript row follows.
%
% If the next token is \end, the environment is ending and no empty final
% TR structure element must be opened.
\def\transcript@aftercr{%
  \futurelet\transcript@nexttoken\transcript@aftercr@aux
}

\def\transcript@aftercr@aux{%
  \ifx\transcript@nexttoken\end
    % Environment ends: do not open an empty final TR.
  \else
    \transcript@openrow
  \fi
}


% --------------------------------------------------------------------------
% Additional tab stack and slot counters for multi-overlap turns
% --------------------------------------------------------------------------

\newcount\@nxtxtabmar
\newcount\@curxtabmar
\newcount\@curxtab
\newcount\@highxtab
\newcount\transcript@ol@setcnt
\newcount\transcript@ol@usecnt
\newcount\transcript@fieldgrouplevel
\newcount\transcript@posid
\newcount\transcript@tablineid
\newif\iftranscript@ol@inusephase

% Auxiliary storage for X-positions of \OL inside groups (e.g., \textbf{...\OL{...}})
\newcommand*\transcript@setxpos[2]{%
  \expandafter\gdef\csname transcript@aux@xpos@#1\endcsname{#2}%
}

\def\@rxtab{%
      \@stopfield\@addfield%
      \ifnum \@curxtab<\@highxtab
          \global\advance\@curxtab \@ne
      \else
        \@badtab
      \fi
      \@tempdima\dimen\@curxtab
      \advance\@tempdima -\dimen\@curxtabmar
      \advance\@tempdima -\wd\@curline
      \global\setbox\@curline\hbox{\unhbox\@curline\hskip\@tempdima}%
      \@startfield\ignorespaces}

\def\@setxtab{\@stopfield\@addfield
  \ifnum \@curxtab <\@maxtab
    \ifnum\@curxtab =\@highxtab
      \advance\@highxtab \@ne
    \fi
    \global\advance\@curxtab \@ne
  \else
    \@latex@error{Tab overflow}\@ehd
  \fi
  \dimen\@curxtab \dimen\@curxtabmar
  \advance\dimen\@curxtab \wd\@curline
  \@startfield
  \ignorespaces}

% Amend kernel's \@startline
\let\transcript@orig@startline\@startline
\def\@startline{%
     \ifnum \@nxtxtabmar >\@highxtab
       \@badtab
       \global\@nxtxtabmar \@highxtab
     \fi
     \global\@curxtabmar \@nxtxtabmar
     \global\@curxtab \@curxtabmar
     \transcript@orig@startline
     \global\transcript@fieldgrouplevel=\currentgrouplevel
     \global\advance\transcript@tablineid\@ne
     \transcript@save@xpos{tablinestart-\arabic{transcript}-\the\transcript@tablineid}%
}

% Save current X position via engine primitive (pdfTeX / LuaTeX), expanding #1 immediately
\def\transcript@save@xpos#1{%
  \ifdefined\savepos
    \savepos
    \if@filesw
      \begingroup
        \edef\x{\endgroup\write\@auxout{\string\transcript@setxpos{#1}{\noexpand\the\noexpand\lastxpos}}}%
      \x
    \fi
  \else\ifdefined\pdfsavepos
    \pdfsavepos
    \if@filesw
      \begingroup
        \edef\x{\endgroup\write\@auxout{\string\transcript@setxpos{#1}{\noexpand\the\noexpand\pdflastxpos}}}%
      \x
    \fi
  \fi\fi
}

% Self-contained overlap start/end tab setters and jumpers (immune to tagpdf kernel overrides and \textbf{...} groups)
\def\transcript@ol@setstart{%
  \iftranscript@ol@inusephase
    \global\transcript@ol@setcnt=0\relax
    \global\transcript@ol@usecnt=0\relax
    \global\transcript@ol@inusephasefalse
  \fi
  \global\advance\transcript@ol@setcnt\@ne
  \ifnum\currentgrouplevel>\transcript@fieldgrouplevel
    % Inside a group like \textbf{...}: do not call \@stopfield/\@startfield (avoids Missing } error)
    \global\advance\transcript@posid\@ne
    \edef\transcript@cur@sid{s-\arabic{transcript}-\the\transcript@posid}%
    \transcript@save@xpos{\transcript@cur@sid}%
    \@ifundefined{transcript@aux@xpos@\transcript@cur@sid}{%
      \expandafter\xdef\csname transcript@ol@spos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
    }{%
      \@ifundefined{transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid}{%
        \expandafter\xdef\csname transcript@ol@spos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
      }{%
        \@tempdima=\dimexpr\csname transcript@aux@xpos@\transcript@cur@sid\endcsname sp
           - \csname transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid\endcsname sp\relax
        \expandafter\xdef\csname transcript@ol@spos@\the\transcript@ol@setcnt\endcsname{\the\@tempdima}%
      }%
    }%
  \else
    \@stopfield\@addfield
    \expandafter\xdef\csname transcript@ol@spos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
    \@startfield\ignorespaces
  \fi
}

\def\transcript@ol@jumptostart{%
  \global\transcript@ol@inusephasetrue
  \ifnum\transcript@ol@usecnt<\transcript@ol@setcnt
    \global\advance\transcript@ol@usecnt\@ne
  \else
    \global\transcript@ol@usecnt=1\relax
  \fi
  \ifnum\currentgrouplevel>\transcript@fieldgrouplevel
    \@ifundefined{transcript@ol@spos@\the\transcript@ol@usecnt}{%
      \@badtab
    }{%
      \global\advance\transcript@posid\@ne
      \edef\transcript@cur@jid{j-\arabic{transcript}-\the\transcript@posid}%
      \transcript@save@xpos{\transcript@cur@jid}%
      \@ifundefined{transcript@aux@xpos@\transcript@cur@jid}{}{%
        \@ifundefined{transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid}{}{%
          \@tempdima=\csname transcript@ol@spos@\the\transcript@ol@usecnt\endcsname\relax
          \advance\@tempdima -\dimexpr\csname transcript@aux@xpos@\transcript@cur@jid\endcsname sp
             - \csname transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid\endcsname sp\relax
          \hskip\@tempdima
        }%
      }%
    }%
  \else
    \@stopfield\@addfield
    \@ifundefined{transcript@ol@spos@\the\transcript@ol@usecnt}{%
      \@badtab
    }{%
      \@tempdima=\csname transcript@ol@spos@\the\transcript@ol@usecnt\endcsname\relax
      \advance\@tempdima -\wd\@curline
      \global\setbox\@curline\hbox{\unhbox\@curline\hskip\@tempdima}%
    }%
    \@startfield\ignorespaces
  \fi
}

\def\transcript@ol@setend{%
  \ifnum\currentgrouplevel>\transcript@fieldgrouplevel
    \global\advance\transcript@posid\@ne
    \edef\transcript@cur@eid{e-\arabic{transcript}-\the\transcript@posid}%
    \transcript@save@xpos{\transcript@cur@eid}%
    \@ifundefined{transcript@aux@xpos@\transcript@cur@eid}{%
      \expandafter\xdef\csname transcript@ol@epos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
    }{%
      \@ifundefined{transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid}{%
        \expandafter\xdef\csname transcript@ol@epos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
      }{%
        \@tempdima=\dimexpr\csname transcript@aux@xpos@\transcript@cur@eid\endcsname sp
            - \csname transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid\endcsname sp\relax
        \expandafter\xdef\csname transcript@ol@epos@\the\transcript@ol@setcnt\endcsname{\the\@tempdima}%
      }%
    }%
  \else
    \@stopfield\@addfield
    \expandafter\xdef\csname transcript@ol@epos@\the\transcript@ol@setcnt\endcsname{\the\wd\@curline}%
    \@startfield\ignorespaces
  \fi
}

\def\transcript@ol@jumptoend{%
  \ifnum\currentgrouplevel>\transcript@fieldgrouplevel
    \@ifundefined{transcript@ol@epos@\the\transcript@ol@usecnt}{%
      \@badtab
    }{%
      \global\advance\transcript@posid\@ne
      \edef\transcript@cur@keid{k-\arabic{transcript}-\the\transcript@posid}%
      \transcript@save@xpos{\transcript@cur@keid}%
      \@ifundefined{transcript@aux@xpos@\transcript@cur@keid}{}{%
        \@ifundefined{transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid}{}{%
          \@tempdima=\csname transcript@ol@epos@\the\transcript@ol@usecnt\endcsname\relax
          \advance\@tempdima -\dimexpr\csname transcript@aux@xpos@\transcript@cur@keid\endcsname sp
              - \csname transcript@aux@xpos@tablinestart-\arabic{transcript}-\the\transcript@tablineid\endcsname sp\relax
          \hskip\@tempdima
        }%
      }%
    }%
  \else
    \@stopfield\@addfield
    \@ifundefined{transcript@ol@epos@\the\transcript@ol@usecnt}{%
      \@badtab
    }{%
      \@tempdima=\csname transcript@ol@epos@\the\transcript@ol@usecnt\endcsname\relax
      \advance\@tempdima -\wd\@curline
      \global\setbox\@curline\hbox{\unhbox\@curline\hskip\@tempdima}%
    }%
    \@startfield\ignorespaces
  \fi
}


% --------------------------------------------------------------------------
% Internal helpers for line numbering
% --------------------------------------------------------------------------

% Pad zeros to line numbers (purely expandable; works inside \edef and all engines)
\newcommand*\transcript@padzeros[1]{%
  \expandafter\transcript@padzeros@aux\expandafter{\number#1}%
}

\newcommand*\transcript@padzeros@aux[1]{%
  \expandafter\transcript@padzero@loop\expandafter{\transcript@widest@ln}{#1}{#1}%
}

\newcommand*\transcript@padzero@loop[3]{%
  \ifx\relax#1\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {#3}% #1 (max) is empty -> output original number (#3)
  {%
    \ifx\relax#2\relax
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
    \fi
    {% #2 (num) ran out first -> output 0, strip 1 digit from #1
      0%
      \expandafter\transcript@padzero@loop\expandafter{\@gobble#1}{}{#3}%
    }%
    {% Both still have digits -> strip 1 digit from #2 first, then #1
      \expandafter\transcript@padzero@loop@step\expandafter{\@gobble#2}{#1}{#3}%
    }%
  }%
}

\newcommand*\transcript@padzero@loop@step[3]{%
  \expandafter\transcript@padzero@loop\expandafter{\@gobble#2}{#1}{#3}%
}


% --------------------------------------------------------------------------
% Internal helpers for horizontal adjustment & table cells
% --------------------------------------------------------------------------

% Render margin mark inside the currently open cell (<TD>) without creating a detached <Note>.
\def\transcript@emit@marginmark{%
  \begingroup
    \if@transcript@tagging
      \SuspendTagging{marginnote}%
    \fi
    \reversemarginpar\marginnote{\textrightarrow}%
  \endgroup
}

% Render line number column as cell 1 (<TD>), including \Mark if present on this row.
% Even if linenumbers=false, an empty <TD> is emitted to keep the 3-column grid consistent.
\def\transcript@render@ln{%
  \iftranscript@cellopen
    \transcript@closecell
  \fi
  \global\advance\transcript@rowcol\@ne
  \ifnum\transcript@rowcol>\transcript@curmaxcols
    \global\transcript@curmaxcols\transcript@rowcol
  \fi
  \if@transcript@tagging
    \tagstructbegin{tag=TD}%
  \fi%
  \global\transcript@cellopentrue
  \global\transcript@mcopenfalse
  \if@transcriptln
    \transcript@startmc
    \if@transcript@lnpadzeros
        \edef\transcript@lnr{\transcript@padzeros{\arabic{tsline}}}%
    \else
        \edef\transcript@lnr{\arabic{tsline}}%
    \fi
    \ifx\transcript@widest@ln\empty
      {\transcript@lnfont\transcript@lnr}\hskip\transcript@linenrskip%
    \else
      \settowidth{\transcript@real@lnwidth}{\transcript@lnfont\transcript@lnr}%
      \setlength{\transcript@lnpadwidth}{\transcript@lnwidth}%
      \addtolength{\transcript@lnpadwidth}{-\transcript@real@lnwidth}%
      \hbox{\hskip\transcript@lnpadwidth{\transcript@lnfont\transcript@lnr}\hskip\transcript@linenrskip}%
    \fi%
  \fi%
  \@ifundefined{transcript@aux@marked@\arabic{transcript}@\the\transcript@rowidx}{}{%
    \transcript@startmc
    \transcript@emit@marginmark
  }%
  \transcript@closecell
}

% Render phantom line number indentation as an Artifact (used in continuation lines \\*
% where no new <TR> is started, or inside an empty <TD> in \TTR).
\def\transcript@render@emptyln@artifact{%
  \if@transcriptln
    \transcript@stopmc
    \if@transcript@tagging\tagmcbegin{artifact}\fi
    \if@transcript@lnpadzeros
        \edef\transcript@lnr{\transcript@padzeros{\arabic{tsline}}}%
    \else
        \edef\transcript@lnr{\arabic{tsline}}%
    \fi
    \ifx\transcript@widest@ln\empty
      \phantom{\transcript@lnfont\transcript@lnr}\hskip\transcript@linenrskip%
    \else
      \settowidth{\transcript@real@lnwidth}{\transcript@lnfont\transcript@lnr}%
      \setlength{\transcript@lnpadwidth}{\transcript@lnwidth}%
      \addtolength{\transcript@lnpadwidth}{-\transcript@real@lnwidth}%
      \hbox{\hskip\transcript@lnpadwidth\phantom{\transcript@lnfont\transcript@lnr}\hskip\transcript@linenrskip}%
    \fi%
    \if@transcript@tagging\tagmcend\fi
    \transcript@startmc
  \fi%
}

% Render empty interlocutor cell (<TD>) with Artifact indentation (used after \\ and in \TTR).
\def\transcript@render@emptyil@cell{%
  \transcript@opencell
  \transcript@stopmc
  \if@transcript@tagging\tagmcbegin{artifact}\fi
  \hbox{\phantom{\transcript@ilfont\transcript@widest@il\transcript@ilsep}\hskip\transcript@ilskip}%
  \if@transcript@tagging\tagmcend\fi
  \transcript@closecell
}

% Render phantom interlocutor indentation as an Artifact inside an already open cell (used after \\*).
\def\transcript@render@emptyil@artifact{%
  \transcript@stopmc
  \if@transcript@tagging\tagmcbegin{artifact}\fi
  \hbox{\phantom{\transcript@ilfont\transcript@widest@il\transcript@ilsep}\hskip\transcript@ilskip}%
  \if@transcript@tagging\tagmcend\fi
  \transcript@startmc
}


% --------------------------------------------------------------------------
% Internal tabbing environment without \trivlist
% --------------------------------------------------------------------------

% This environment is based on the kernel tabbing environment.
%
% It retains (with other command names):
%
%   \TLP>
%   \TLP<
%   \TLP=
%   \TLP+
%   \TLP-
%   \TLP`
%   \TLP'
%   \\
%
% It deliberately omits:
%
%   \trivlist \item\relax
%   \if@minipage\else\vskip\parskip\fi
%   \endtrivlist
%
% In the original tabbing environment, \trivlist is only layout machinery.
% Under LaTeX PDF tagging, however, it produces an unwanted false list:
%
%   L -> LI -> Lbl + LBody
%
% The present environment retains tabbing's visual alignment and
% page-breakability but avoids that artificial list structure.
%

% Suppress TeX ligatures like << and >> inside transcripts across engines
% (including a \TLP-safe active-< fallback for classic pdfLaTeX without microtype)
\begingroup
  \catcode`\<=\active
  \gdef\transcript@activate@lt{%
    \catcode`\<=\active
    \def<{\char`\<\kern\z@}%
  }
\endgroup

\def\transcript@disable@ligatures{%
  \if@transcript@texligatures\else
    \ifdefined\addfontfeatures
      % LuaLaTeX / XeLaTeX (fontspec): disable TeX ligatures (<<, >>, --, ---, etc.)
      \addfontfeatures{RawFeature=-tlig}%
    \else
      % Classic TeX (pdfLaTeX): use microtype if available, otherwise activate < safely
      \ifdefined\DisableLigatures
        \DisableLigatures[<,>]{encoding = *}%
      \else
        \transcript@activate@lt
      \fi
    \fi
  \fi
}

\newif\if@transcript@firstturn
\@transcript@firstturntrue

\newif\if@transcript@intranscript
\@transcript@intranscriptfalse

\def\transcript@ole@cmd#1{%
  \ifnum\currentgrouplevel>\transcript@fieldgrouplevel\transcript@incontinuationtrue\fi\iftranscript@incontinuation
    \IfBooleanTF{#1}{\transcript@ol@jumptoend}{\transcript@ol@setend}\transcript@olend%
    \transcript@skipspaces\transcript@after@ols@aux
  \else
    \global\advance\transcript@olidx\@ne
    \iftranscript@cellopen\else
      \@ifundefined{transcript@aux@olends@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@olidx}%
        {\transcript@opencell}%
        {\transcript@opencell@span}%
    \fi
    \IfBooleanTF{#1}{\transcript@ol@jumptoend}{\transcript@ol@setend}\transcript@olend%
    \global\transcript@textcellopenedfalse
    \expandafter\transcript@skipspaces\expandafter\transcript@after@ole@aux
  \fi
}%

\def\transcript@after@ole@aux{%
  \transcript@ol@endrowtrue
  \ifx\transcript@nexttoken\OL\transcript@ol@endrowfalse\fi
  \ifx\transcript@nexttoken\OLS\transcript@ol@endrowfalse\fi
  \ifcat\noexpand\transcript@nexttoken a\transcript@ol@endrowfalse\fi
  \ifcat\noexpand\transcript@nexttoken 1\transcript@ol@endrowfalse\fi
  \iftranscript@ol@endrow
    \if@filesw
      \immediate\write\@auxout{%
        \string\transcript@setolends{\arabic{transcript}}{\the\transcript@rowidx}{\the\transcript@olidx}%
      }%
    \fi
    \transcript@closecell
  \else
    \transcript@closecell
    \ifx\transcript@nexttoken\OL
      \iftranscript@hadspace\ \fi
    \else\ifx\transcript@nexttoken\OLS
      \iftranscript@hadspace\ \fi
    \else
      \global\advance\transcript@txtidx\@ne
      \@ifundefined{transcript@aux@txtbeforeol@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@txtidx}%
        {\transcript@opencell@span}%
        {\transcript@opencell}%
      \global\transcript@textcellopenedtrue
      \iftranscript@hadspace\ \fi
    \fi\fi
  \fi
}%

\NewDocumentEnvironment{transcripttabbing}{}
  {
    \@transcript@intranscripttrue
    \lineskip\z@skip
    \transcript@disable@ligatures

    % Original tabbing dispatcher
    %
    % Do not add PDF-tagging commands, \futurelet, Artifact wrappers or other
    % logic to this macro. tabbing's field construction and horizontal state
    % are sensitive to extra material around \@rtab, \@settab etc.
    %
    \def\TLP{%
      \begingroup
      \catcode`\<=12\relax
      \transcript@tlp@aux
    }%
    \def\transcript@tlp@aux##1{%
      \endgroup
      \ifx ##1>\@rtab\else
      \ifx ##1<\@ltab\else
      \ifx ##1=\@settab\else
      \ifx ##1+\@tabplus\else
      \ifx ##1-\@tabminus\else
      \ifx ##1`\@tabrj\else
      \ifx ##1'\@tablab\else
        \PackageError{transcript}%
          {Bad argument ##1 for transcript line point specification}%
      \fi\fi\fi\fi\fi\fi\fi
    }%
    \DeclareDocumentCommand\OL { s o m }
      {%
        \ifnum\currentgrouplevel>\transcript@fieldgrouplevel\transcript@incontinuationtrue\fi\iftranscript@incontinuation
          \IfValueTF{##2}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}##2\transcript@olstart}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}\transcript@olstart}%
          \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures##3%
          \IfBooleanTF{##1}{\transcript@ol@jumptoend}{\transcript@ol@setend}\transcript@olend%
          \transcript@skipspaces\transcript@after@ols@aux
        \else
          \global\advance\transcript@olidx\@ne
          \iftranscript@textcellopened
            \if@filesw
              \immediate\write\@auxout{%
                \string\transcript@settxtbeforeol{\arabic{transcript}}{\the\transcript@rowidx}{\the\transcript@txtidx}%
              }%
            \fi
            \transcript@closecell
            \global\transcript@textcellopenedfalse
          \fi
          \@ifundefined{transcript@aux@olends@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@olidx}%
            {\transcript@opencell}%
            {\transcript@opencell@span}%
          \IfValueTF{##2}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}##2\transcript@olstart}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}\transcript@olstart}%
          \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures##3%
          \IfBooleanTF{##1}{\transcript@ol@jumptoend}{\transcript@ol@setend}\transcript@olend%
          \transcript@after@ol
        \fi
      }%
     \DeclareDocumentCommand\OLS { s o }
      {%
        \ifnum\currentgrouplevel>\transcript@fieldgrouplevel\transcript@incontinuationtrue\fi\iftranscript@incontinuation
          \IfValueTF{##2}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}##2\transcript@olstart}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}\transcript@olstart}%
          \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures
          \transcript@skipspaces\transcript@after@ols@aux
        \else
          \global\advance\transcript@olidx\@ne
          \iftranscript@textcellopened
            \if@filesw
              \immediate\write\@auxout{%
                \string\transcript@settxtbeforeol{\arabic{transcript}}{\the\transcript@rowidx}{\the\transcript@txtidx}%
              }%
            \fi
            \transcript@closecell
            \global\transcript@textcellopenedfalse
          \fi
          \global\advance\transcript@txtidx\@ne
          \@ifundefined{transcript@aux@txtbeforeol@\arabic{transcript}@\the\transcript@rowidx @\the\transcript@txtidx}%
            {\transcript@opencell@span}%
            {\transcript@opencell}%
          \IfValueTF{##2}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}##2\transcript@olstart}
            {\IfBooleanTF{##1}{\transcript@ol@jumptostart}{\transcript@ol@setstart}\transcript@olstart}%
          \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures
          \global\transcript@textcellopenedtrue
          \transcript@skipspaces\transcript@after@ols@aux
        \fi
      }%
     \def\transcript@after@ols@aux{%
        \iftranscript@hadspace\ \fi
     }%
    %
    % Tagging-aware visual line ending.
    %
    % The current semantic TR is closed before tabbing terminates the visual
    % line. The next semantic TR is opened afterwards, unless the environment
    % is ending.
    %
    % Inside transcripttabbing:
    %
    % \\   ends the current visual and semantic transcript row:
    %      the current TR element is closed and a new TR is opened.
    %
    % \\*  ends only the visual tabbing line:
    %      the current TR and TD elements remain open, so that the following
    %      indented continuation line belongs to the same accessible cell.
     \def\OLE{%
       \@ifstar
         {\transcript@ole@cmd{\BooleanTrue}}%
         {\transcript@ole@cmd{\BooleanFalse}}%
     }%
    \def\\{%
      \@ifstar
        {\transcript@lb@con}%
        {\transcript@lb@norm}%
    }
    \def\Up{\textuparrow}%
    \def\Dn{\textdownarrow}%
    \def\Mark{%
      \if@filesw
        \immediate\write\@auxout{%
          \string\transcript@setrowmarked{\arabic{transcript}}{\the\transcript@rowidx}%
        }%
      \fi
      \@ifundefined{transcript@aux@marked@\arabic{transcript}@\the\transcript@rowidx}{%
        \transcript@emit@marginmark
      }{}%
    }%
    \def\transcript@lb@con{%
       \global\transcript@incontinuationtrue
       \transcript@continuationcr%
       \transcript@render@emptyil@artifact
       \ignorespaces
    }
    \def\transcript@lb@norm{%
       \transcript@newparagraphcr%
       \transcript@render@emptyil@cell
       \transcript@after@actor
    }
    \settowidth{\transcript@lnwidth}{\transcript@lnfont\transcript@widest@ln}
    % Normal transcript line break:
    %
    % - finish the current TR structure element;
    % - perform the visual tabbing line break;
    % - open a new TR unless the environment ends;
    % - render line number cell (column 1).
    \def\transcript@newparagraphcr{%
      \transcript@closerow
      \refstepcounter{tsline}%
      \global\let\@currentlabel\@currentlabel%
      \@tabcr
      \expandafter\transcript@aftercr\ignorespaces
      \iftranscript@rowopen
        \transcript@render@ln
      \fi
    }
    % Continuation line break:
    %
    % - keep the current TR and TD structure elements open;
    % - end the current marked-content sequence;
    % - perform only a visual tabbing line break;
    % - render phantom line number indentation as Artifact;
    % - begin a new marked-content sequence in the same TD;
    % - discard indentation from the source line.
    \def\transcript@continuationcr{%
      \transcript@stopmc
      \@tabcr*%
      \transcript@startmc
      % Line count padding as Artifact
      \transcript@render@emptyln@artifact
      \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures%
      \ignorespaces
    }
    % Initialise the tabbing state exactly as in the kernel
    \global\@hightab\@firsttab
    \global\@nxttabmar\@firsttab
    \global\@highxtab\@firsttab
    \global\transcript@ol@setcnt=0\relax
    \global\transcript@ol@usecnt=0\relax
    \global\transcript@ol@inusephasefalse
    \dimen\@firsttab\@totalleftmargin
    \global\@tabpush\z@
    \global\@rjfieldfalse
    \@transcript@firstturntrue

    % Intentionally omitted:
    %
    % \trivlist \item\relax
    % \if@minipage\else\vskip\parskip\fi
    %
    % Therefore there is no artificial PDF list:
    %
    % L
    % LI
    % Lbl
    % LBody
    % ListNumbering

    \setbox\@tabfbox\hbox{%
      \rlap{%
        \indent
        \hskip\@totalleftmargin
        \the\everypar
      }%
    }%

    \def\@itemfudge{\box\@tabfbox}%

    % Begin the visual tabbing mechanism.
    \@startline

    % Open the first semantic transcript row before discarding
    % indentation from the first source line.
    \transcript@openrow

    % Line count cell (column 1)
    \transcript@render@ln

    % Remove source indentation immediately after
    % \begin{transcripttabbing}.  This must come after
    % \transcript@openrow: otherwise \ignorespaces sees that macro
    % rather than the indentation spaces of the first transcript line.
    \ignorespaces
  }
  {
    % If the final source line does not end with \\, close its semantic
    % row here. If it does end with \\, this has no further effect.
    \transcript@closerow
    \@transcript@intranscriptfalse

    % Finish the visual tabbing mechanism.
    \@stopline

    % Preserve the check for unmatched tab-stack operations.
    \ifnum\@tabpush>\z@
      \@badpoptabs
    \fi
  }


% --------------------------------------------------------------------------
% Public transcript environment
% --------------------------------------------------------------------------

% Usage:
%
% \begin{transcript}[options]
%   transcript text
% \end{transcript}
%

\def\transcript@caption{}
\def\transcript@postcaption{}
\def\transcript@posttext{}
\def\transcript@start@ln{1}
\def\transcript@label{}

\DeclareKeys[transcriptenv]
{
    % beforeenv={length}
    beforeenv.code = { \setlength\transcript@beforeenv{#1} },
    % afterenv={length}
    afterenv.code = { \setlength\transcript@afterenv{#1} },
    % belowcaptionskip={length}
    belowcaptionskip.store = \transcript@vskip,
    % abovepostcaptionskip={length}
    abovepostcaptionskip.store = \transcript@postcaptionskip,
    % aboveposttextskip={length}
    aboveposttextskip.store = \transcript@posttextskip,
    % font={font setting}
    font.store = \transcript@font,
    % captionfont={font setting}
    captionfont.store = \transcript@captionfont,
    % captionlabelfont={font setting}
    captionlabelfont.store = \transcript@captionlabelfont,
    % postcaptionfont={font setting}
    postcaptionfont.store = \transcript@postcaptionfont,
    % posttextfont={font setting}
    posttextfont.store = \transcript@posttextfont,
    % transcriptname={string}
    transcriptname.store = \transcriptname,
    % transcriptsname={string}
    transcriptsname.store = \transcriptsname,
    % caption={string}
    caption.store = \transcript@caption,
    % postcaption={string}
    postcaption.store = \transcript@postcaption,
    % posttext={string}
    posttext.store = \transcript@posttext,
    % label={string}
    label.store = \transcript@label,
    % linenumbers=<true|false>
    linenumbers.if = @transcriptln,
    % widestnumber={string}
    widestnumber.store = \transcript@widest@ln,
    % padzeros=<true|false>
    padzeros.if = @transcript@lnpadzeros,
    % padref=<true|false>
    padref.if = @transcript@lnpadref,
    % linename={string}
    linename.code = {%
      \def\transcriptlinename{#1}%
      \global\@transcript@customlinenametrue
      \IfPackageLoadedT{zref-clever}{%
        \zcRefTypeSetup{line}{Name-sg = \transcriptlinename,
                              name-sg = \transcriptlinename}%
      }%
    },
    % linesname={string}
    linesname.code = {%
      \def\transcriptlinesname{#1}%
      \global\@transcript@customlinesnametrue
      \IfPackageLoadedT{zref-clever}{%
        \zcRefTypeSetup{line}{Name-pl = \transcriptlinesname,
                              name-pl = \transcriptlinesname}%
      }%
    },
    % refsep={separator}
    refsep.store = \transcriptrefsep,
    % linerefsep={separator}
    linerefsep.store = \transcriptlinerefsep,
    % startln={string}
    startln.store = \transcript@start@ln,
    % lnfont={font setting}
    lnfont.store = \transcript@lnfont,
    % lnskip={length}
    lnskip.code = { \setlength\transcript@linenrskip{#1} },
    % widestactor={string}
    widestactor.store = \transcript@widest@il,
    % actorskip={length}
    actorskip.code = { \setlength\transcript@ilskip{#1} },
    % actorsep={length}
    actorsep.store = \transcript@ilsep,
    % actorfont={font setting}
    actorfont.store = \transcript@ilfont,
    % trlfonr={font setting}
    trlfont.store = \transcript@trlfont,
    % olstart={string}
    olstart.store = \transcript@olstart,
    % olend={string}
    olend.store = \transcript@olend,
    % texligatures=<true|false>
    texligatures.if = @transcript@texligatures,
}

\NewDocumentEnvironment{transcript}{ o }
  {%
      % Save \@currentlabel as we globally overwrite
      % this for linenumbers
      \let\transcript@save@currentlabel\@currentlabel%
      % End the preceding paragraph cleanly and strip trailing spaces
      % BEFORE \refstepcounter adds any nodes in horizontal mode.
      \ifhmode
        \unskip
        \par
      \fi
      \IfNoValueF{#1}{\SetKeys[transcriptenv]{#1}}%
      \refstepcounter{transcript}%

      % Restore max column count from .aux file if available (default: 3)
      \global\transcript@rowidx=0\relax
      \global\transcript@tablineid=0\relax
      \global\transcript@curmaxcols=3\relax
      \@ifundefined{transcript@aux@maxcols@\arabic{transcript}}%
        {\global\transcript@maxcols=3\relax}%
        {\global\transcript@maxcols=\csname transcript@aux@maxcols@\arabic{transcript}\endcsname\relax}%

      % Normally add a small gap above the transcript.  Immediately after
      % a LaTeX heading, \if@nobreak is true; the heading already provides
      % the required vertical spacing, so no additional \medskip is added.
      \if@nobreak\else
        \vspace{\transcript@beforeenv}
      \fi%

      % Semantic <Table> container for the complete transcript block.
      \if@transcript@tagging
        \tagstructbegin{tag=Table}%
      \fi%

      % Avoid extra paragraph spacing inside the transcript block.
      \parskip=0pt\relax%

      % Visible transcript heading tagged as <Caption> inside <Table>.
      %
      % Main caption is an automatic <P> inside <Caption>; optional
      % postcaption is wrapped in a <Div> inside <Caption>.
      %
      % Continuation lines of a long optional caption are aligned below
      % the caption text, not below ``\transcriptname <number>:''.
      \if@transcript@tagging
        \tagstructbegin{tag=Caption}%
      \fi%
      \begingroup
         \transcript@captionfont
         \parindent=0pt\relax
         \settowidth{\transcript@captionindent}{%
           {\transcript@captionlabelfont\transcriptname~\arabic{transcript}: }%
         }%
         \ifx\transcript@caption\empty
           \noindent
           \addcontentsline{trc}{transcript}{\protect\numberline{\thetranscript}}%
              {\transcript@captionlabelfont\transcriptname~\arabic{transcript}}\par
         \else
           \leftskip=\transcript@captionindent
           \noindent
           \addcontentsline{trc}{transcript}{\protect\numberline{\thetranscript}\transcript@caption}%
           \hspace*{-\transcript@captionindent}%
           {\transcript@captionlabelfont\transcriptname~\arabic{transcript}: }%
           \transcript@caption\par
        \fi
        \ifx\transcript@postcaption\empty\else
           \nopagebreak
           \vskip\transcript@postcaptionskip\relax
           \if@transcript@tagging
             \tagstructbegin{tag=Div}%
           \fi%
           \leftskip=\transcript@captionindent
           \noindent
           {\transcript@postcaptionfont\transcript@postcaption\par}%
           \if@transcript@tagging
             \tagstructend
           \fi%
       \fi
       \ifx\transcript@label\empty\else
           \expandafter\label{\transcript@label}%
       \fi
      \endgroup
      \if@transcript@tagging
        \tagstructend
      \fi%

      % Font and paragraph settings for transcript lines.
      \if@transcript@trline\transcript@trlfont\else\transcript@font\fi\transcript@disable@ligatures
      \parindent=0pt\relax
      \frenchspacing

      \nobreak
      \vskip\transcript@vskip\relax

      % Step first line counter AFTER caption so caption \label captures 'transcript'
      \setcounter{tsline}{\transcript@start@ln}%
      \addtocounter{tsline}{-1}%
      \refstepcounter{tsline}%

      % Tabbing-style transcript setting without \trivlist.
      \begin{transcripttabbing}
  }
  {
    \end{transcripttabbing}

    % Close the semantic <Table> container for the complete transcript.
    \if@transcript@tagging
       \tagstructend
    \fi

    % Optional posttext after the transcript table (tagged as standard <P> after <Table>).
    \ifx\transcript@posttext\empty\else
      \nopagebreak
      \vskip\transcript@posttextskip\relax
      \begingroup
        \transcript@posttextfont
        \parindent=0pt\relax
        \noindent\transcript@posttext\par
      \endgroup
    \fi

    % Persist max column count for this transcript to .aux file
    \if@filesw
      \immediate\write\@auxout{%
        \string\transcript@setmaxcols{\arabic{transcript}}{\the\transcript@curmaxcols}%
      }%
    \fi

    \par%
    \vspace{\transcript@afterenv}
    % Reset \@currentlabel
    \global\let\@currentlabel\transcript@save@currentlabel%
    % Suppress indent on next line if no blank line follows
    \aftergroup\@afterindentfalse%
    \aftergroup\@afterheading%
  }
  

% --------------------------------------------------------------------------
% Commands for the use within transcript environment
% --------------------------------------------------------------------------

% Start a new speaker turn (opens new <TR> unless first turn, emits actor <TD>,
% and opens utterance <TD> unless \OL follows immediately).
\NewDocumentCommand\Turn { m }
{%
  \if@transcript@intranscript
    \if@transcript@firstturn\else
      \transcript@newparagraphcr%
    \fi%
    \transcript@opencell
    \settowidth{\transcript@ilwidth}{\transcript@ilfont\transcript@widest@il\transcript@ilsep}%
    \settowidth{\transcript@real@ilwidth}{\transcript@ilfont#1\transcript@ilsep}%
    \addtolength{\transcript@ilwidth}{-\transcript@real@ilwidth}%
    \hbox{\transcript@ilfont#1\transcript@ilsep\hskip\transcript@ilwidth\hskip\transcript@ilskip}%
    \transcript@closecell
    \global\@transcript@firstturnfalse%
    \expandafter\transcript@after@actor
  \else
    \PackageWarning{transcript}{Use of \string\Turn\space outside transcript environment ignored!}%
  \fi%
}

% Skip transcript lines, the argument is the line
% number to restart from
\NewDocumentCommand\TrSkip { m }
{%
  \if@transcript@intranscript
      \transcript@closerow
      \setcounter{tsline}{\number#1}%
      % Get line counter to ref scope
      \addtocounter{tsline}{-2}%
      \refstepcounter{tsline}%
      \@tabcr
      \expandafter\transcript@aftercr\ignorespaces
      \iftranscript@rowopen
        \transcript@opencell
        {[\ldots\unkern]}%
        \transcript@closecell
        \transcript@opencell@span
        \global\transcript@textcellopenedtrue
      \fi
      \ignorespaces
  \else
    \PackageWarning{transcript}{Use of \string\TrSkip\space outside transcript environment ignored!}%
  \fi
}

% Interlinear translation (own <TR> with empty line-number and actor <TD>s)
\NewDocumentCommand\TTR { m }
{%
  \if@transcript@intranscript
    \global\@transcript@trlinetrue
    \transcript@closerow
    \@tabcr
    \expandafter\transcript@aftercr\ignorespaces
    \iftranscript@rowopen
      \transcript@opencell
      \transcript@render@emptyln@artifact
      \transcript@closecell
      \transcript@render@emptyil@cell
      \transcript@trlfont\transcript@disable@ligatures
      \transcript@after@actor#1%
      \transcript@closerow
    \fi
    \global\@transcript@trlinefalse
    \ignorespaces
  \else
    \PackageWarning{transcript}{Use of \string\TTR\space outside transcript environment ignored!}%
  \fi
}

% Top-level fallback definitions for commands defined locally inside transcripttabbing
% (use \ProvideDocumentCommand / \providecommand so existing macros outside transcript are never overwritten)
\ProvideDocumentCommand\OL { s o m }{%
  \PackageWarning{transcript}{Use of \string\OL\space outside transcript environment ignored!}%
}
\ProvideDocumentCommand\OLS { s o }{%
  \PackageWarning{transcript}{Use of \string\OLS\space outside transcript environment ignored!}%
}
\ProvideDocumentCommand\OLE { s }{%
  \PackageWarning{transcript}{Use of \string\OLE\space outside transcript environment ignored!}%
}
\providecommand*\TLP[1]{%
  \PackageWarning{transcript}{Use of \string\TLP\space outside transcript environment ignored!}%
}
\providecommand*\Up{%
  \PackageWarning{transcript}{Use of \string\Up\space outside transcript environment ignored!}%
}
\providecommand*\Dn{%
  \PackageWarning{transcript}{Use of \string\Dn\space outside transcript environment ignored!}%
}
\providecommand*\Mark{%
  \PackageWarning{transcript}{Use of \string\Mark\space outside transcript environment ignored!}%
}


% --------------------------------------------------------------------------
% Crossref comvenience macros
% --------------------------------------------------------------------------

% Cross-reference one or more comma-separated transcript or line labels
% Usage: \tref{label}, \tref{label1,label2}, \tlref{label}, \tlref{label1,label2}
% (starred variants \tref* / \tlref* suppress hyperlinks)
\ExplSyntaxOn
\seq_new:N \l__transcript_ref_seq
\seq_new:N \l__transcript_tmp_ref_seq

\cs_new_protected:Npn \__transcript_format_refs:nnnnn #1 #2 #3 #4 #5
  {
    \IfPackageLoadedTF{zref-clever}
      {
        \IfBooleanTF{#1}{\zcref*{#5}}{\zcref{#5}}
      }
      {
        \seq_set_from_clist:Nn \l__transcript_ref_seq {#5}
        \int_compare:nNnTF { \seq_count:N \l__transcript_ref_seq } > { 1 }
          { #3#4 }
          { #2#4 }
        \seq_clear:N \l__transcript_tmp_ref_seq
        \seq_map_inline:Nn \l__transcript_ref_seq
          {
            \IfBooleanTF{#1}
              { \seq_put_right:Nn \l__transcript_tmp_ref_seq { \ref*{##1} } }
              { \seq_put_right:Nn \l__transcript_tmp_ref_seq { \ref{##1} } }
          }
        \seq_use:Nnnn \l__transcript_tmp_ref_seq { ~and~ } { ,~ } { ,~and~ }
      }
  }

\NewDocumentCommand\tref{ s m }
  {
    \__transcript_format_refs:nnnnn {#1}
         { \transcriptname } { \transcriptsname } { \transcriptrefsep } {#2}
  }

\NewDocumentCommand\tlref{ s m }
  {
    \__transcript_format_refs:nnnnn {#1}
        { \transcriptlinename } { \transcriptlinesname } { \transcriptlinerefsep } {#2}
  }
\ExplSyntaxOff


% --------------------------------------------------------------------------
% List of transcripts
% --------------------------------------------------------------------------

% list of transcripts
\newcommand{\listoftranscripts}{%
  \@ifundefined{chapter}%
    {\section*{\listtranscriptname}}%
    {\chapter*{\listtranscriptname}}%
  \@starttoc{trc}%
  \bigskip
}

\NewCommandCopy{\l@transcript}{\l@figure}

\endinput
