\ProvidesPackage{cmsdocs}

\RequirePackage{refcount}
\RequirePackage{listings}
\RequirePackage[svgnames]{xcolor}
\RequirePackage{hyperref}

%%% This file contains kludges and hacks to enable the bespoke
%%% cross-referencing system found in cms-notes-intro.pdf and
%%% cms-dates-intro.pdf.  It contains code adapted from several
%%% sources, especially from Ulrich Dirr's hyperendnotes.sty, found on
%%% comp.text.tex.  Please don't load it unless you really mean to, as
%%% it messes with the standard biblatex-chicago macros.

%%% These counters are for the slightly more informative endnote marks
%%% used in the notes intro.

\newcounter{Article}\setcounter{Article}{1}
\newcounter{Artwork}\setcounter{Artwork}{2}
\newcounter{Audio}\setcounter{Audio}{3}
\newcounter{Book}\setcounter{Book}{4}
\newcounter{BookInBook}\setcounter{BookInBook}{5}
\newcounter{Booklet}\setcounter{Booklet}{6}
\newcounter{Collection}\setcounter{Collection}{7}
\newcounter{CustomC}\setcounter{CustomC}{8}
\newcounter{Image}\setcounter{Image}{9}
\newcounter{InBook}\setcounter{InBook}{10}
\newcounter{InCollection}\setcounter{InCollection}{11}
\newcounter{InProceedings}\setcounter{InProceedings}{12}
\newcounter{InReference}\setcounter{InReference}{13}
\newcounter{Letter}\setcounter{Letter}{14}
\newcounter{Manual}\setcounter{Manual}{15}
\newcounter{MastersThesis}\setcounter{MastersThesis}{16}
\newcounter{Misc}\setcounter{Misc}{17}
\newcounter{Music}\setcounter{Music}{18}
\newcounter{MVBook}\setcounter{MVBook}{19}
\newcounter{MVCollection}\setcounter{MVCollection}{20}
\newcounter{MVProceedings}\setcounter{MVProceedings}{21}
\newcounter{MVReference}\setcounter{MVReference}{22}
\newcounter{Online}\setcounter{Online}{23}
\newcounter{Patent}\setcounter{Patent}{24}
\newcounter{Periodical}\setcounter{Periodical}{25}
\newcounter{Proceedings}\setcounter{Proceedings}{26}
\newcounter{Reference}\setcounter{Reference}{27}
\newcounter{Report}\setcounter{Report}{28}
\newcounter{Review}\setcounter{Review}{29}
\newcounter{SuppBook}\setcounter{SuppBook}{30}
\newcounter{SuppCollection}\setcounter{SuppCollection}{31}
\newcounter{SuppPeriodical}\setcounter{SuppPeriodical}{32}
\newcounter{TechReport}\setcounter{TechReport}{33}
\newcounter{Thesis}\setcounter{Thesis}{34}
\newcounter{Unpublished}\setcounter{Unpublished}{35}
\newcounter{Video}\setcounter{Video}{36}
\newcounter{Performance}\setcounter{Performance}{37}
\newcounter{Standard}\setcounter{Standard}{38}
\newcounter{Dataset}\setcounter{Dataset}{39}

%%% Here starts the adaptation of hyperendnotes.sty

\newif\ifenotelinks
\newcounter{Hendnote}
\newcounter{cms@docnote}
% Redefining portions of endnotes-package:
\let\savedhref\href
\let\savedurl\url
\def\endnotemark{%
  \@ifnextchar[\@xendnotemark{%
    \stepcounter{endnote}%
    \stepcounter{cms@docnote}%
    \protected@xdef\@theenmark{\theendnote}%
    \protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
    \@endnotemark
  }%
}%
\def\@xendnotemark[#1]{%
  \stepcounter{cms@docnote}%
  \begingroup\c@endnote#1\relax
  \unrestored@protected@xdef\@theenmark{\theendnote}%
  \unrestored@protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
  \endgroup
  \@endnotemark
}%
\def\endnotetext{%
  \@ifnextchar[\@xendnotenext{%
    \protected@xdef\@theenmark{\theendnote}%
    \protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
    \@endnotetext
  }%
}%
\def\@xendnotenext[#1]{%
  \begingroup
  \c@endnote=#1\relax
  \unrestored@protected@xdef\@theenmark{\theendnote}%
  \unrestored@protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
  \endgroup
  \@endnotetext
}%
\def\endnote{%
  \@ifnextchar[\@xendnote{%
    \stepcounter{endnote}%
    \stepcounter{cms@docnote}%
    \protected@xdef\@theenmark{\theendnote}%
    \protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
    \@endnotemark\@endnotetext
  }%
}%
\def\@xendnote[#1]{%
  \stepcounter{cms@docnote}%
  \begingroup
  \c@endnote=#1\relax
  \unrestored@protected@xdef\@theenmark{\theendnote}%
  \unrestored@protected@xdef\@theenvalue{\number\c@refsection\number\c@cms@docnote}%
  \show\@theenvalue
  \endgroup
  \@endnotemark\@endnotetext
}%
\def\@endnotemark{%
  \leavevmode
  \ifhmode
  \edef\@x@sf{\the\spacefactor}\nobreak
  \fi
  \ifenotelinks
  \expandafter\@firstofone
  \else
  \expandafter\@gobble
  \fi
  {%
    \Hy@raisedlink{%
      \hyper@@anchor{Hendnotepage.\@theenvalue}{\empty}%
    }%
  }%
  \hyper@linkstart{link}{Hendnote.\@theenvalue}%
  \makeenmark
  \hyper@linkend
  \ifhmode
  \spacefactor\@x@sf
  \fi
  \relax
}%
\long\def\@endnotetext#1{%
  \if@enotesopen
  \else
  \@openenotes
  \fi
  \immediate\write\@enotes{%
    \@doanenote{\@theenmark}{\@theenvalue}%
  }%
  \begingroup
  \def\next{#1}%
  \newlinechar='40
  \immediate\write\@enotes{\meaning\next}%
  \endgroup
  \immediate\write\@enotes{%
    \@endanenote
  }%
}%
\def\theendnotes{%
  \immediate\closeout\@enotes
  \global\@enotesopenfalse
  \begingroup
  \makeatletter
  \edef\@tempa{`\string>}%
  \ifnum\catcode\@tempa=12
  \let\@ResetGT\relax
  \else
  \edef\@ResetGT{\noexpand\catcode\@tempa=\the\catcode\@tempa}%
  \@makeother\>%
  \fi
  \def\@doanenote##1##2##3>{%
    \def\@theenmark{##1}%
    \def\@theenvalue{##2}%
    \par
%    \smallskip %<-small vertical gap between endnotes
    \begingroup
    \def\href{\expandafter\savedhref}%
    \def\url{\expandafter\savedurl}%
    \@ResetGT
    \edef\@currentlabel{\csname p@endnote\endcsname\@theenmark}%
    \enoteformat
  }%
  \def\@endanenote{%
    \par\endgroup
  }%
  % Redefine, how numbers are formatted in the endnotes-section:
  \renewcommand*\@makeenmark{%
    \hbox{\normalfont\@theenmark~}%
  }%
  % header of endnotes-section
  \enoteheading
  % font-size of endnotes
  \enotesize
  \input{\jobname.ent}%
  \endgroup
}%
\def\enoteformat{%
  \renewcommand{\makeenmark}%
  {\color{DarkBlue}{\textsf{\theenmark:\,\,}}}%
  \rightskip\z@
  \leftskip\z@
  \parindent=2.3em
  \leavevmode\llap{%
    \setcounter{Hendnote}{\@theenvalue}%
    \addtocounter{Hendnote}{-1}%
    \refstepcounter{Hendnote}%
    \ifenotelinks
    \expandafter\@secondoftwo
    \else
    \expandafter\@firstoftwo
    \fi
    {\@firstofone}%
    {\hyperlink{Hendnotepage.\@theenvalue}}%
    {\makeenmark}%
  }%
}%
% stop redefining portions of endnotes-package:

% Toggle switch in order to turn on/off back-links in the
% endnote-section:
\enotelinkstrue
% \enotelinksfalse

%%% Here we substitute entry types for the usual numbers for endnote
%%% marks.

\def\cmssymbol#1{\expandafter\@cmssymbol\csname c@#1\endcsname}
 
\def\@cmssymbol#1{\ifcase#1\or Article\or Artwork\or Audio\or Book\or
  BookInBook\or Booklet\or Collection\or CustomC\or Image\or InBook\or
  InCollection\or InProceedings\or InReference\or Letter\or Manual\or
  MastersThesis\or Misc\or Music\or MVBook\or MVCollection\or
  MVProceedings\or MVReference\or Online\or Patent\or Periodical\or
  Proceedings\or Reference\or Report\or Review\or SuppBook\or
  SuppCollection\or SuppPeriodical\or TechReport\or Thesis\or
  Unpublished\or Video\or Perfor\-mance\or Standard\or
  Dataset\else\@ctrerr\fi}

\renewcommand{\theendnote}{\cmssymbol{endnote}}

%%% Now we define parameters and a command for the lstlisting
%%% environments, which print the .bib entries at the end of the .pdf.

\lstset{%
  basicstyle=\footnotesize\ttfamily,
  breaklines=true,
  breakatwhitespace=true,
  breakautoindent=false,
  breakindent=40pt,
  escapechar=*,
  keywordstyle=\color{DarkBlue},
  columns=fullflexible,
}%

\lstdefinelanguage{BibTeX}
{keywords={%
    @string%
  },
  comment=[l][\itshape]{@comment},
  sensitive=false,
}%

\newrobustcmd*{\lnbackref}[2]{%
  \hyperlink{Hendnote.\csuse{cms@id@#2}}{\color{DarkBlue}@#1}\{#2,}

% \newrobustcmd*{\lnbackref}[2]{%
%   \hyperlink{Hendnote.#2\the\value{#1}}{\color{DarkBlue}@#1}}

\newrobustcmd*{\adlnbackref}[2]{%
  \@ifnextchar[%]
  {\adlnbackref@i{#1}{#2}}%
  {\adlnbackref@i{#1}{#2}[{#2}]}}%

\def\adlnbackref@i#1#2[#3]{%
  \hyperlink{cite.0@#3}{\color{DarkBlue}@#1}\{#2}%

%%% Here we renew some macros from chicago-notes.cbx, and add some
%%% field formats to make navigating the intro easier.

\renewbibmacro*{cite:full}{%
  \ifnumequal{\the\value{refsection}}{8}%
  {\printtext[cmsbiblink]{%
      \usedriver
      {\DeclareNameAlias{sortname}{default}\frenchspacing}
      {cite:\thefield{entrytype}}}}
  {\global\cslet{cms@id@\thefield{entrykey}}{\@theenvalue}%
    \iffieldequalstr{entrykey}{lac:leaders}%
    {\printtext{%
        \usedriver
        {\DeclareNameAlias{sortname}{default}\frenchspacing}
        {cite:\thefield{entrytype}}}}%
    {\printtext[bibhyperref]{%
        \usedriver
        {\DeclareNameAlias{sortname}{default}\frenchspacing}
        {cite:\thefield{entrytype}}}}}}%

\ifdef{\cmshyper}%
{\renewrobustcmd*{\cmshyper}[1]{%
    \ifboolexpr{%
      (
      test {\ifbibliography}%
      or
      test {\ifnumgreater{\the\value{refsection}}{3}}%
      )
      and
      not test {\ifnumequal{\the\value{refsection}}{8}}%
    }%
    {\printtext[bibhyperref]{#1}}%
    {\printtext[cmsbiblink]{#1}}}}%
{}%

\ifdef{\cmsrelhyper}%
{\renewrobustcmd*{\cmsrelhyper}[1]{%
    \ifhyperref%
    {\ifbibliography%
      {\ifentryinbib{\strfield{clonesourcekey}}%
        {\bibhyperref[\strfield{clonesourcekey}]{#1}}%
        {#1}}%
      {\iftoggle{cms@allshort}%
        {\IfSubStr{\thefield{savedoptions}}{skipbib}%
          {\bibhyperref[\strfield{clonesourcekey}]{#1}}%%
          {\bibhyperref[\thefield{savedentrykey}]{#1}}}%
        {\iftoggle{cms@fullnote}%
          {\ifentryseen{\thefield{clonesourcekey}}%
            {\bibhyperref[\strfield{clonesourcekey}]{#1}}%
            {#1}}%
          {\bibhyperref[\thefield{savedentrykey}]{#1}}}}}%
    {#1}}}%
{}%

\ifbibmacroundef{cite:journal}{}%
  {\renewbibmacro*{cite:journal}{%
  \ifthenelse{\ifciteibid\AND\NOT\iffirstonpage}%
  {\iffieldundef{prenote}%
    {\bibsentence\usebibmacro{cite:ibid}}%
    {\usebibmacro{cite:ibid}}}%
  {\iffieldundef{journaltitle}%
    {\usebibmacro{cite:short}}%
    {\iffieldequalstr{authortype}{anon}%
      {\bibleftbracket\printnames{labelname}%
        \bibrightbracket\newcunit}%
      {\iffieldequalstr{authortype}{anon?}%
        {\bibleftbracket\printnames{labelname}?%
          \bibrightbracket\newcunit}%
        {\printnames{labelname}%
          \isdot\newcunit}}%
      \iftoggle{cms@allshort}%
      {\printtext[cmsbiblink]{%
          \printfield[journaltitle]{journaltitle}}}%
      {\printtext[cmsbiblink]{%
          \printfield[journaltitle]{journaltitle}}}%
      \iffieldundef{volume}%
      {\iffieldundef{number}%
        {\iffieldundef{issue}
          {\newcunit%
            \usebibmacro{number+or+month}}%
          {\newcunit%
            \printfield{issue}%
            \setunit{\addspace}%
            \usebibmacro{cmsyear}}}%
        {\newcunit%
          \printfield[journum]{number}}}%
      {\toggletrue{cms@fullnote}%
        \togglefalse{cms@shortnote}%
        \setunit{\addspace}%
        \printfield[jourvol]{volume}%
        \ifthenelse{\iffieldundef{pagination}\AND%
          \iffieldundef{bookpagination}}%
        {\setunit{\postvolpunct}}%
        {\setunit{\addcolon\addspace}}}}}}}

\DeclareFieldFormat{cmsbiblink}{%
  \hyperlink{\getrefbykeydefault{\abx@field@entrykey}{anchor}{}}{#1}}

\def\cmsdocref@entry{%
  \iffieldundef{clonesourcekey}%
  {\printfield{entrykey}}%
  {\printfield{clonesourcekey}}}

\def\cmsdoc@entrykey{%
  \iffieldundef{clonesourcekey}%
  {\abx@field@entrykey}%
  {\abx@field@clonesourcekey}}

\newcommand*{\cmslink}[1]{%
  \hyperlink{\getrefbykeydefault{#1}{anchor}{}}%
  {\texttt{#1}}}

\DeclareFieldFormat{annotation}{%\addperiod\par\nobreak \vskip \bibitemsep%
  \hyperlink{\getrefbykeydefault{\cmsdoc@entrykey}{anchor}{}}%
  {\small{\textbf{[\cmsdocref@entry]\addspace}}}\small#1}

%%% These commands provide the hyperlinks to the external docs in
%%% biblatex-chicago.pdf.

\newrobustcmd*{\cmssecref}[2][]{\marginpar{\href{\@baseurl%
      \getrefbykeydefault{#2}{anchor}{}}{\small \S\,\getrefnumber{#2}}%
      \ifblank{#1}{}{\scriptsize,\, s.v.\\[1pt]\enquote{#1}}}}
\newrobustcmd*{\cmspagref}[1]{\marginpar{\href{\@baseurl%
      page.\getpagerefnumber{#1}}{p.~\getpagerefnumber{#1}}}}
\newrobustcmd*{\cmstabref}[2][]{\marginpar{\href{\@baseurl%
      \getrefbykeydefault{#2}{anchor}{}}%
    {\footnotesize Table\,\getrefnumber{#2}}%
      \ifblank{#1}{}{\scriptsize,\, s.v.\\[1pt]\enquote{#1}}}}