% lua-widow-control
% https://github.com/gucci-on-fleek/lua-widow-control
% SPDX-License-Identifier: MPL-2.0+
% SPDX-FileCopyrightText: 2022 Max Chernoff

\startenvironment[lwc-manual]
\unprotect

\mainlanguage[en]

%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Font Selection %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%

\startluacode
fonts.handlers.otf.addfeature {
    name = "emdash_kern", -- Increase sidebearings on em-dash
    type = "single",
    data = {
        ["—"] = { 100, 0, 200, 0 },
    }
}
\stopluacode

\definefontfeature[default][default][
    protrusion=quality,
    expansion=quality,
    onum=yes,
    script=latn,
    emdash_kern=yes,
    trep=yes,
]
\setupalign[hz, hanging]

\definefontfeature[lining][onum=no,lnum=yes]
\definefontfeature[allsmall][c2sc=yes, smcp=yes]
\define\lining{\feature[+][lining]}

\starttypescript[lwc-fonts]
    \definetypeface[lwc-fonts] [rm] [serif][pagella] [default]
    \definetypeface[lwc-fonts] [ss] [sans] [libertinus] [default] [rscale=1.07]
    \definetypeface[lwc-fonts] [tt] [mono] [plex] [default] [rscale=0.89]
    \definetypeface[lwc-fonts] [mm] [math] [pagella] [default]
\stoptypescript

\setupbodyfont[lwc-fonts, 11pt]

\setupbodyfontenvironment[default][em=italic]


%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Page Layout %%%%%
%%%%%%%%%%%%%%%%%%%%%%%

\setuppapersize[letter]

\setupindenting[yes, 3em]
\setupinterlinespace[2.75ex]

\input lang-frq.mkxl % For \averagecharwidth

\setuplayout[
    width=75\averagecharwidth,
    backspace=\dimexpr(\paperwidth - \makeupwidth) / 2,
    topspace=\dimexpr\backspace - \headerheight,
    footerdistance=3\baselineskip,
    footer=\baselineskip,
    height=8.75in,
    margin=\dimexpr\backspace - \margindistance - 0.25cm,
]

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% PDF Settings %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%

% PDF/UA
\setupbackend[format=PDF/UA-1]
\setupinteraction[state=start, focus=standard]
\setuptagging[state=start]
\setupstructure[state=start, method=auto]

% Bookmarks
\placebookmarks[section, subsection][section, subsection][number=no]
\setupinteractionscreen[option=bookmark]

%%%%%%%%%%%%%%%%%%%%%%
%%%%% Formatting %%%%%
%%%%%%%%%%%%%%%%%%%%%%

\setuppagenumbering[location=footer, style=\ss\lining]
\let\old@tex=\tex
\def\tex#1{\expandafter\old@tex\normalexpanded{{#1}}} % Allow expansion in the \tex macro (for \allowbreak)

% Acronym styling
\definecharacterkerning[acronymkerning][factor=0.05]
\definealternativestyle[acronymstyle][{\feature[+][allsmall]\switchtobodyfont[1.2em]\setcharacterkerning[acronymkerning]}][]
\definehighlight[acronym][style=acronymstyle]

\startsetups[commandtable]
    \setupTABLE[frame=off]
    \setupTABLE[column][first][roffset=1.5em]
    \setupTABLE[row][first][toffset=0.25ex]
\stopsetups

\startsetups[booktabs]
    \setupTABLE[each][each][frame=off]
    \setupTABLE[row][first][topframe=on, rulethickness=1.2bp]
    \setupTABLE[row][2]    [topframe=on, rulethickness=0.6bp]
    \setupTABLE[row][last] [bottomframe=on, rulethickness=1.2bp]
    \setupTABLE[column][first][loffset=0.5em]
    \setupTABLE[column][last][roffset=0.5em]
\stopsetups

\setupitemize[each][
    style=\lining,
    inbetween={\blank[quarterline]},
]
\setupcaptions[
    headstyle=\ssbf\lining,
    style=\ss,
]

\setupdelimitedtext[blockquote][
    style=\ss,
    before=\noindentation,
    after={\blank[medium]}
]

\define[1]\meta{\m{\langle}\italic{#1}\m{\rangle}}
\define[1]\githubissue{\goto{(Issue~\##1)}[url(https://github.com/gucci-on-fleek/lua-widow-control/issues/#1)]}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Section Commands %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\definecharacterkerning[titlekern][factor=0.2]

\protected\def\interwordspace{\scaledfontdimen2\font}

% Section
\startsetups[style:section]
    \setcharacterkerning[titlekern]
    \switchtobodyfont[adventor]
    \WORD
    \bfb
    \feature[+][allsmall]
    \interwordspace=0.4em
    \veryraggedcenter
\stopsetups

\setuphead[section][
    before={\blank[big, preference]},
    after={\blank[medium, samepage]},
    textstyle=\setups{style:section},
    number=no,
]

% Subsection
\setuphead[subsection][
    before={\blank[medium, preference]},
    after=,
    textstyle=\ss,
    alternative=margintext,
    number=no,
]

% TOC
\def\secondleveltoc{subsection}
\starttexdefinition protected SectionTOCcommand #1#2#3
    \startcurrentlistentrywrapper % Make the whole line a link
        \midaligned{ % Have the title and page number "glued" to the middle
            \llap{\currentlistentrytitle}
            \hskip 1em
            \rlap{\color[\interactionparameter{color}]{\bf \currentlistentrypagenumber}}
        }
    \stopcurrentlistentrywrapper

    \par
    \nobreak

    \setbox0=\vbox{\framedtext[ % Align the subsection titles under the section title
        frame=off,
        width=\dimexpr\textwidth/2 - 0.5em,
        align={flushright, wide},
        offset=none,
        toffset=-\lineheight,
    ]{
        \global\firstsubsectiontrue
        \placelist[\secondleveltoc][criterium=local]
    }}
    \iffirstsubsection
        \blank[quarterline] % No subsections here
    \else
        \box0
    \fi

    \goodbreak
\stoptexdefinition

\newif\iffirstsubsection

\define\tocspace{\hskip 0.5em plus 0.5em minus 0.2em\relax}

\unexpanded\def\toc_link#1{%
    \startcurrentlistentrywrapper%
        \hbox{#1}%
    \stopcurrentlistentrywrapper%
}

\starttexdefinition protected SubsectionTOCcommand #1#2#3
    \ss\itx
    \dontleavehmode
    \iffirstsubsection
        \global\firstsubsectionfalse
        \toc_link{#2}
    \else
        \discretionary{}{
            \toc_link{#2} % No interpunct if the line splits here
        }{
            \tocspace{\bfa·}\tocspace\toc_link{#2}
        }
    \fi
\stoptexdefinition

\setupcombinedlist[content][list=section]
\setuplist[section][
    alternative=command,
    command=\SectionTOCcommand,
]

\setuplist[subsection][
    alternative=command,
    command=\SubsectionTOCcommand,
]

%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Title Block %%%%%
%%%%%%%%%%%%%%%%%%%%%%%

\setupdocument[
    title={},
    author={},
    version={},
    ctan={},
    github={},
]

\startluacode
local function strip_url(str)
    local url_table = url.hashed(str)
    url_table.fragment = nil
    url_table.scheme = nil
    url_table.authority = url_table.authority:gsub("^www%.", "")
    tex.sprint(-2, url.decode(url.construct(url_table)))
end

interfaces.implement {
    name = "strip_url",
    actions = strip_url,
    arguments = "1 string"
}
\stopluacode

\define[1]\strippedurl{%
    \goto{\tt\hyphenatedurl{\clf_strip_url{#1}}}[url(#1)]
}

\startsetups[titleblock]
    \startalignment [middle]
        \begingroup
            \setups[style:section]\bfc
            \documentvariable{title}
            \par
        \endgroup

        \blank[big]

        \begingroup
            \ssa\lining
            \documentvariable{author}
            \blank[medium]
            v\,\documentvariable{version}
            \par
        \endgroup

        \dontleavehmode
        \blackrule[depth=-0.25\baselineskip, height=\dimexpr0.25\baselineskip + 0.4pt, width=8em]
        \par

        \doifdocumentvariable{ctan}{
            \strippedurl{\documentvariable{ctan}}
        }
        \doifdocumentvariable{github}{
            \strippedurl{\documentvariable{github}}
        }
        \blank[big]

        \noindentation
    \stopalignment
\stopsetups

\startsetups[document:start]
    \setup[titleblock]

    \setupinteraction[
        title=\documentvariable{title},
        author=\documentvariable{author},
    ]
\stopsetups

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Bibliography %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
\usebtxdefinitions[apa]

\resetsetups[apa:list:sameauthor]

\setupbtx[apa:list][
    stopper:initials=,
    separator:initials=\btxnbsp,
    interaction=start,
]

\setupbtxlabeltext[en][
   apa:Retrieved={}
]

\setupbtxrendering[apa][
    numbering=yes,
    sorttype=used,
]

\setupbtx[apa:cite][alternative=num]

\defineshift[citeshift][
    method=0,
    dy=-1,
    unit=ex,
    continue=yes,
    style=\tfx\lining,
]

\setupbtx[apa:cite:num][
    command=\citeshift,
    left=,
    right=,
    separator:2=\citeshift{,\,},
    separator:3=\citeshift{--}
]

\setupbtxlist[apa][
    alternative=a,
    before=,
    after={\blank[quarterline]},
    style=\lining,
    margin=0pt,
    width=1.5em,
]

\starttexdefinition mutable protected btx:apa:url
    \strippedurl{\clf_btxflush{\currentbtxdataset}{\currentbtxtag}{url}
        }
\stoptexdefinition

\define[1]\lwc_doi{\goto{\acronym{DOI:}\,\tt\hyphenatedurl{#1}}[url(https://dx.doi.org/#1)]}
\starttexdefinition mutable protected btx:apa:doi
    \lwc_doi{\clf_btxflush{\currentbtxdataset}{\currentbtxtag}{doi}}
\stoptexdefinition

\protect
\stopenvironment
