% \iffalse meta-comment
%
% Copyright (C) 2019-2025 by Jan Hajer
% -----------------------------------
%
% This file may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3c
% 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.3c or later is part of all distributions of LaTeX
% version 2005/12/01 or later.
%
% \fi
%
% \iffalse
%
%<package>\NeedsTeXFormat{LaTeX2e}[2021-11-15]
%<package>\ProvidesPackage{hep-acronym}[2026/11/13 v1.6 Acronyms based on glossaries-extra with sentence-aware capitalisation and first-use links]
%<documentation>\ProvidesFile{hep-acronym-documentation.tex}[2026/11/13 v1.6 HEP-acronym documentation]
%
%<*documentation>
\RequirePackage[l2tabu, orthodox]{nag}
\documentclass{ltxdoc}

\renewcommand*\theCodelineNo{\rmfamily\tstyle\footnotesize\arabic{CodelineNo}}
\AtBeginEnvironment{macrocode}{\renewcommand*{\ttdefault}{clmt}}
\renewcommand*{\MacroFont}{\codestyle}
\AtBeginDocument{\DeleteShortVerb{\|}}
\AtBeginDocument{\MakeShortVerb{\"}}
\EnableCrossrefs
\CodelineIndex
\RecordChanges

\usepackage{hologo}

\usepackage[parskip,oldstyle,font=10pt]{hep-paper}
\bibliography{bibliography}
\acronym{PDF}{portable document format}
%</documentation>

%<*driver>
\expandafter\newif\csname ifshort\endcsname
\shortfalse
\begin{document}
\DocInput{hep-acronym-implementation.dtx}
\end{document}
%</driver>
%
% \fi
%
% \CheckSum{756}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
% \changes{v1.0}{2021/09/01}{First release on CTAN: acronyms based on glossaries-extra with sentence-aware use, short and long variants, reset and dummy helpers, and acronym groups.}
% \changes{v1.1}{2022/11/01}{Added \cs{sentence} and forced long-form acronym commands, and disabled PDF strings only when hyperref is missing.}
% \changes{v1.2}{2023/07/01}{Added the \option{hyper} option, alternative long-form acronyms, and acronyms in math mode.}
% \changes{v1.3}{2024/11/01}{Stopped resetting acronyms in tables and lists, and applied starred command definitions.}
% \changes{v1.4}{2025/09/01}{Released without changes.}
% \changes{v1.5}{2026/08/01}{Raised the LaTeX format requirement and expanded the documentation, README, and examples.}
% \changes{v1.6}{2026/11/13}{Added the \option{titlesec} option for classes with their own sectioning code, which still capitalise acronyms at the beginning of numbered section titles, fixed an infinite loop in nested description lists, ended the line after \cs{glsreset} in the enforced first forms, kept \cs{sentence} from setting the space factor outside horizontal mode, and improved the \software{hyperref} support: \PDF strings are defined independently of the package loading order, for all acronym variants and without stray spaces, capitalised at the beginning of bookmarks, and the contents lists neither consume the first use nor nest links, nor do the texts of links.}
%
% \ifshort
%<*documentation>
% \fi
%
\GetFileInfo{hep-acronym.sty}

\title{The \software{hep-acronym} package\thanks{This document corresponds to \software{hep-acronym}~\fileversion.}}
\subtitle{Acronyms based on glossaries-extra with sentence-aware capitalisation and first-use links}
\author{Jan Hajer \email{jan.hajer@tecnico.ulisboa.pt}}
\date{\filedate}

% \ifshort
\begin{document}
% \fi

\newgeometry{vscale=.8, vmarginratio=3:4, includeheadfoot, left=11em, marginparwidth=4.6cm, marginparsep=3mm, right=7em}

\maketitle

\begin{abstract}
The \software{hep-acronym} package provides sentence-aware acronym helpers based on \software{glossaries-extra}.
It defines declaration commands for regular, always-short, always-long, and alternative long-form acronyms, optional links back to the first use, reset and dummy-use helpers, and support for several acronym groups.
\end{abstract}

Acronyms are implemented using the \software{glossaries-extra} package \cite{glossaries-extra} which is an extension of the \software{glossaries} package \cite{glossaries} and must be loaded after the \software{hyperref} package \cite{hyperref}.
It can be loaded using "\usepackage{hep-acronym}".

\DescribeMacro{hyper}
The "hyper" option controls whether later acronym uses link back to their first appearance.
It is enabled by default and can be deactivated with "hyper=false".

\DescribeMacro{titlesec}
The \software{titlesec} package \cite{titlesec} is loaded so that acronyms at the beginning of section titles are capitalised.
Classes with their own sectioning code, such as \software{amsart} and \software{PoS}, are incompatible with \software{titlesec}; "titlesec=false" does not load it.
This is the default for the \software{KOMA-Script} classes.
Acronyms at the beginning of numbered section titles are then still capitalised.
The \software{hep-paper} package sets this option in its "amsart" and "pos" compatibility modes.

\DescribeMacro{\acronym}
The "\acronym"\meta{*}\oarg{typeset abbreviation}\marg{abbreviation}\meta{*}\marg{definition}\oarg{plural definition} macro generates the singular "\"\meta{abbreviation} and plural "\"\meta{abbreviation}"s" macros.

The first star prevents the addition of an \enquote{s} to the abbreviation plural.
The second star restores the \hologo{TeX} default of swallowing subsequent white space.
The long form is only shown at the first appearance of these macros, later appearances generate the abbreviation with a hyperlink to the long form.
Capitalisation at the beginning of paragraphs and sentences is (mostly) ensured.
The long form is never used in math mode which can be exploited to enforce the short form.
In order to enforce the long form use "\"\meta{abbreviation}"long".
As there can be no fixed rule whether to use the long form or the short form in section headers the user is left to their own devices \eg "\glsdesc"\marg{abbreviation}, "\Glsdesc"\marg{abbreviation}.
\DescribeMacro{\sentence}
The "\sentence" macro ensures that the directly following abbreviation is capitalised.

In \PDF strings, such as bookmarks and the document information, the acronym macros expand to their short form, or to their long form for the "long" variants.
An acronym macro at the beginning of a \PDF string or directly after "\sentence" is capitalised.
Optional arguments of the acronym macros are not supported in \PDF strings, and "\textsc" in a typeset abbreviation becomes upper case.
In the table of contents and the lists of figures and tables, acronyms are shown in their short form without links, and they change neither the first use nor the entry count.
Acronyms in the text of links, \eg of "\href" or "\hyperlink", do not link to their first use either.


\DescribeMacro{\shortacronym}
\DescribeMacro{\longacronym}
The "\shortacronym" and "\longacronym" macros are drop-in replacements of the "\acronym" macro showing only the short or long form of their acronym.

\DescribeMacro{\acronymalternative}
The "\acronymalternative"\marg{acronym}\marg{name}\meta{*}\marg{alternative long form} macro defines an additional acronym macro that shares the use counter and short form of \meta{acronym} but prints the supplied long form at first use.

\DescribeMacro{\resetacronym}
The first use form of the acronym can be enforced by resetting the acronym counter with "\resetacronym"\marg{key}.

\DescribeMacro{\dummyacronym}
If the acronym counter equals one at the end of the document the short form of the acronym is not introduced.
Placing a "\dummyacronym"\marg{key} at the end of the document ensures that the short form is introduced.

\DescribeMacro{\acronyms}
The "\acronyms"\oarg{key}\marg{title} macro creates a new acronym glossary and switches subsequent declarations to it.
Without the optional argument the mandatory argument is used both as glossary key and printed title.

\DescribeMacro{warning}
In order to reduce the number of potentially conflicting packages the \software{glossaries} package is loaded without any glossary style.
In the case that the glossary should be printed additional packages must be loaded via \eg "\usepackage{glossary-list}".

% \ifshort
\printbibliography

\end{document}
%
%</documentation>
% \fi
%
% \StopEventually{
% \printbibliography
% \PrintChanges
% }
%
% \appendix
%
% \section{Implementation}
%
%<*package>
%
% Define a hepacronym namespace for the options using the \software{kvoptions} package \cite{kvoptions}.
%    \begin{macrocode}
\RequirePackage{kvoptions}
\SetupKeyvalOptions{
  family=hepacronym,
  prefix=hepacronym@
}
%    \end{macrocode}
%
% \begin{macro}{hyper}
% Define the "hyper" option controlling the hyperlink to the first appearance of the acronyms.
%    \begin{macrocode}
\DeclareBoolOption[true]{hyper}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{titlesec}
% Define the "titlesec" option controlling whether section titles are treated as sentences.
% The \software{KOMA-Script} classes, which define "\KOMAClassName", have their own sectioning code, which \software{titlesec} does not support.
% For them the option is false unless it is set explicitly.
%    \begin{macrocode}
\@ifundefined{KOMAClassName}{%
  \DeclareBoolOption[true]{titlesec}%
}{%
  \DeclareBoolOption[false]{titlesec}%
}
%    \end{macrocode}
% \end{macro}
%
% Process options.
%    \begin{macrocode}
\ProcessKeyvalOptions*
%    \end{macrocode}
%
% Load the base package \cite{glossaries, glossaries-extra} and set the abbreviation style.
%    \begin{macrocode}
\PassOptionsToPackage{nostyles}{glossaries-extra}
\RequirePackage{glossaries-extra}
% \setabbreviationstyle{long-hyphen-short-hyphen}
%    \end{macrocode}
% Use the entry count feature.
%    \begin{macrocode}
\glsenableentrycount
\glssetcategoryattribute{abbreviation}{entrycount}{1}
%    \end{macrocode}
% Provide macros for older "glossaries-extra" installations.
%    \begin{macrocode}
\AtBeginDocument{
  \@ifpackageloaded{hyperref}{
    \providecommand*{\glsxtrusefield}[2]{\@gls@entry@field{#1}{#2}}
    \providecommand*{\glsxtrsetfieldifexists}[3]{\glsdoifexists{#1}{#3}}
    \providecommand*{\gGlsXtrSetField}[3]{%
      \glsxtrsetfieldifexists{#1}{#2}{%
        \csgdef{glo@\glsdetoklabel{#1}@#2}{#3}%
      }%
    }
%    \end{macrocode}
% Set hyperlinks from the abbreviation to their definition in the text.
%    \begin{macrocode}
    \glssetcategoryattribute{abbreviation}{nohyperfirst}{true}
    \renewcommand*{\glsdonohyperlink}[2]{{%
      \glsxtrprotectlinks\edef\fieldvalue{%
        \glsxtrusefield{\glslabel}{hastarget}%
      }%
      \ifdefstring\fieldvalue{true}{#2}{%
        \gGlsXtrSetField{\glslabel}{hastarget}{true}%
        \glsdohypertarget{#1}{#2}%
      }%
    }}
  }{}
}
%    \end{macrocode}
%
% \begin{macro}{\hep@disable}
% \begin{macro}{\hep@pdf@definitions}
% Collect the \PDF-string definitions of the acronym macros in a macro that \software{hyperref} executes before it converts a string.
% This works independently of the order in which the packages are loaded and also for acronyms declared in the document body.
%    \begin{macrocode}
\newcommand*{\hep@pdf@definitions}{}
\newcommand*{\hep@disable}[1]{\g@addto@macro\hep@pdf@definitions{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\hep@pdf@define}
% Define the \PDF string \marg{text}\marg{space} of the acronym macro with name \marg{name}.
% The \meta{space} is either empty or "\xspace", which \software{hyperref} supports in \PDF strings.
% The capitalised variant is stored under the detokenised macro name and used at the beginning of a \PDF string.
% Plain text has no small capitals, so "\textsc" becomes upper case.
%    \begin{macrocode}
\newcommand*{\hep@pdf@define}[3]{%
  \def\hep@pdf@text{#2}%
  \hep@pdf@uppercase@sc
  \begingroup
    \edef\hep@temp{\endgroup
      \noexpand\hep@disable{%
        \noexpand\@namedef{#1}{\unexpanded\expandafter{\hep@pdf@text#3}}%
      }%
      \global\noexpand\@namedef{hep@pdf@cap@\@backslashchar#1 }{%
        \noexpand\MFUsentencecase{\unexpanded\expandafter{\hep@pdf@text}}%
        \unexpanded{#3}%
      }%
    }%
  \hep@temp
}
\ExplSyntaxOn
\cs_new_protected:Npn \hep@pdf@uppercase@sc
  {
    \regex_replace_all:nnN
      { \c{textsc} } { \c{text_uppercase:n} } \hep@pdf@text
  }
\ExplSyntaxOff
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@pdf@sentence}
% In \PDF strings, "\sentence" capitalises the following acronym macro.
% Other expandable tokens in front of it, such as the conditionals that \software{titlesec} puts in front of the section titles, "\numberline" or "\textbf", are expanded first.
% Any other token ends the sentence beginning, and so does "\@empty", which "\pdfstringdef" places at the end of every string.
%    \begin{macrocode}
\ExplSyntaxOn
\cs_new:Npn \hep@pdf@sentence #1
  {
    \cs_if_exist:cTF { hep@pdf@cap@ \tl_to_str:n {#1} }
      { \use:c { hep@pdf@cap@ \tl_to_str:n {#1} } }
      {
        \bool_lazy_all:nTF
          {
            { \tl_if_single_token_p:n {#1} }
            { \token_if_expandable_p:N #1 }
            { ! \token_if_eq_meaning_p:NN #1 \@empty }
          }
          { \exp_after:wN \hep@pdf@sentence #1 }
          {#1}
      }
  }
\ExplSyntaxOff
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@pdf@numberline}
% In the standard classes, the bookmarks of sectioning commands begin with "\protect" followed by "\numberline"\marg{number}.
% Skip "\protect", which is not expandable here, and treat the text after the number as the beginning of a sentence.
%    \begin{macrocode}
\@namedef{hep@pdf@cap@\@backslashchar protect }{\sentence}
\newcommand*{\hep@pdf@numberline}[1]{\hep@pdf@@numberline{#1}\sentence}
\hep@disable{%
  \let\hep@pdf@@numberline\numberline
  \let\numberline\hep@pdf@numberline
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pdfstringdef}
% Once \software{hyperref} is loaded, register the \PDF-string definitions and treat every \PDF string, \eg a bookmark, as the beginning of a sentence.
% The "\@empty" ensures that "\sentence" has an argument.
%    \begin{macrocode}
\newcommand*{\hep@pdf@register}{%
  \@ifpackageloaded{hyperref}{%
    \pdfstringdefDisableCommands{\hep@pdf@definitions}%
    \global\let\hep@pdfstringdef\pdfstringdef
    \gdef\pdfstringdef##1##2{\hep@pdfstringdef##1{\sentence##2\@empty}}%
    \global\let\hep@pdf@register\relax
  }{}%
}
\hep@pdf@register
\AtBeginDocument{\hep@pdf@register}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hyper@link}
% \begin{macro}{\hyper@linkurl}
% \begin{macro}{\hyper@linkfile}
% Acronyms in the text of a link, \eg of "\href" or "\hyperlink", do not link to their first use, since links cannot be nested.
% The drivers of \software{hyperref} define these macros, so they are wrapped at the end of "\begin{document}".
%    \begin{macrocode}
\AddToHook{begindocument/end}{%
  \@ifpackageloaded{hyperref}{%
    \let\hep@hyper@link\hyper@link
    \def\hyper@link#1#2#3{\hep@hyper@link{#1}{#2}{{\glsdisablehyper#3}}}%
    \let\hep@hyper@linkurl\hyper@linkurl
    \def\hyper@linkurl#1#2{\hep@hyper@linkurl{{\glsdisablehyper#1}}{#2}}%
    \let\hep@hyper@linkfile\hyper@linkfile
    \def\hyper@linkfile#1#2#3{%
      \hep@hyper@linkfile{{\glsdisablehyper#1}}{#2}{#3}%
    }%
  }{}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Ignore only hyperref's "math shift" PDF-string warning.
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{hyperref}{%
    \let\hep@HyPsd@CatcodeWarning\HyPsd@CatcodeWarning
    \renewcommand*{\HyPsd@CatcodeWarning}[1]{%
      \ifstrequal{#1}{math shift}{}{%
        \hep@HyPsd@CatcodeWarning{#1}%
      }%
    }%
  }{}%
}
%    \end{macrocode}
% Deactivate hyperrefs if requested.
%    \begin{macrocode}
\ifhepacronym@hyper\else
  \glsdisablehyper
\fi
%    \end{macrocode}
%
% Load the \software{titlesec} package \cite{titlesec} in order to ensure that section headers are treated as sentences.
%    \begin{macrocode}
\ifhepacronym@titlesec\RequirePackage{titlesec}\fi
%    \end{macrocode}
%
% \begin{macro}{\begin@sentence}
% Mark the beginning of a paragraph as if it would follow a full stop using the \software{everyhook} package \cite{everyhook}.
% The space factor is a "\mathchardef" constant like "\@m", so that digits following "\sentence", for example in the label "\item[12]", do not extend the number.
%    \begin{macrocode}
\PassOptionsToPackage{excludeor}{everyhook}
\RequirePackage{everyhook}
\@ifdefinable\begin@sentence{\mathchardef\begin@sentence=1001\relax}
\newcommand*{\sentence}{\ifhmode\spacefactor=\begin@sentence\fi}
\hep@disable{\let\sentence\hep@pdf@sentence}
\PushPostHook{par}{{\sentence}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ttl@case}
% \begin{macro}{\@hangfrom}
% Treat section titles as sentences using the \software{etoolbox} package \cite{etoolbox}.
% With \software{titlesec} its case hook "\ttl@case" marks the beginning of the title.
% Without it, the beginning of a sentence is marked after "\@hangfrom", which sets the number of displayed section headings in the standard classes, \software{amsart}, and \software{PoS}.
% Starred sections in the latter two remain lower case if \software{hyperref} is loaded, as its anchor restores the previous space factor.
%    \begin{macrocode}
\ifhepacronym@titlesec
  \gdef\ttl@case{\leavevmode\sentence}
\else
  \RequirePackage{etoolbox}
  \apptocmd{\@hangfrom}{\sentence}{}{}
\fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\frenchspacing}
% Adjust the "\frenchspacing" macro to be compatibel with this idea.
%    \begin{macrocode}
\def\frenchspacing{%
  \sfcode`\.\begin@sentence \sfcode`\?\begin@sentence
  \sfcode`\!\begin@sentence \sfcode`\:\begin@sentence
  \sfcode`\;\@m \sfcode`\,\@m
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@if@begin@of@sentence}
% Provide a macro checking for the beginning of a sentence by examining the length of the preceeding space.
%    \begin{macrocode}
\newcommand*{\hep@if@begin@of@sentence}[2]{\leavevmode\protecting{%
  \ifboolexpr{ test {\ifnumcomp{\spacefactor}{=}{3000}} or%
               test {\ifnumcomp{\spacefactor}{=}{2000}} or%
               test {\ifnumcomp{\spacefactor}{=}{\begin@sentence}}%
  }{#1}{#2}%
}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@starttoc}
% Typeset the table of contents and the lists of figures and tables, which all use "\@starttoc", with the short form of the acronyms.
% Their entries begin sentences.
% Acronyms are marked as used only locally, so that the lists change neither the first use nor the entry count.
% Links and link targets are deactivated, since the entries are links themselves.
%    \begin{macrocode}
\let\hep@starttoc\@starttoc
\renewcommand*{\@starttoc}[1]{%
  \begingroup
    \let\@glsunset\@glslocalunset
    \let\@glsreset\@glslocalreset
    \let\@gls@increment@currcount\@gls@local@increment@currcount
    \glslocalunsetall
    \glsdisablehyper
    \let\@glslink\@secondoftwo
    \let\glsdonohyperlink\@secondoftwo
    \let\hep@contents@line\contentsline
    \let\hep@number@line\numberline
    \renewcommand*{\contentsline}[2]{%
      \hep@contents@line{##1}{\sentence ##2}%
    }%
    \renewcommand*{\numberline}[1]{\hep@number@line{##1}\sentence}%
    \hep@starttoc{#1}%
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@item@sentence}
% \begin{macro}{\hep@description@item}
% \begin{macro}{\descriptionsitem}
% Ensure that acronyms in description items get capitalised using the \software{enumitem} package \cite{enumitem}.
% The sentence-aware "\item" is installed only if it is not active yet, because in nested description lists saving the active "\item" would make it call itself.
%    \begin{macrocode}
\RequirePackage{enumitem}
\newcommand*\hep@item@sentence{\leavevmode\sentence}
\NewDocumentCommand{\hep@description@item}{o}{%
  \IfNoValueTF{#1}{%
    \hep@latex@item\hep@item@sentence
  }{%
    \hep@latex@item[\hep@item@sentence#1]\hep@item@sentence
  }%
}
\newcommand*\descriptionsitem{%
  \ifx\item\hep@description@item\else
    \let\hep@latex@item\item
    \let\item\hep@description@item
  \fi
}
\setlist[description]{before=\descriptionsitem}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mathdef}
% Provide a macro that allows to extend a macro definition into math mode using the \software{xparse} package \cite{xparse}.
%    \begin{macrocode}
\RequirePackage{xparse}
\ProvideDocumentCommand{\mathdef}{mO{0}m}{%
  \expandafter\let\csname hep@text\string#1\endcsname=#1
  \expandafter\newcommand\expandafter*%
    \csname hep@math\string#1\endcsname[#2]{#3}
  \DeclareRobustCommand#1{%
    \ifmmode
      \expandafter\let\expandafter\next\csname%
      hep@math\string#1\endcsname%
    \else
      \expandafter\let\expandafter\next\csname%
      hep@text\string#1\endcsname%
    \fi
    \next
  }%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@if@short}
% Check whether "\cgls"\marg{label} prints the short form.
% It does not if the entry is unused or if the entry count of the previous run is one.
%    \begin{macrocode}
\newcommand*{\hep@if@short}[1]{%
  \ifglsused{#1}{%
    \ifnum\glsentryprevcount{#1}=\@ne
      \expandafter\@secondoftwo
    \else
      \expandafter\@firstoftwo
    \fi
  }{\@secondoftwo}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\acronym}
% Define the "\acronym"\meta{*}\oarg{typeset abbreviation}\marg{abbreviation}\meta{*}\marg{definition}\oarg{plural\linebreak[4] definition} macro using the \software{xspace} \cite{xspace} and \software{amstext} \cite{amstext} packages.
% \begin{enumerate}[nosep, label=\#\arabic*]
% \item star for omitting the \enquote{s} in the short plural
% \item optional typeset abbreviation
% \item mandatory abbreviation
% \item star for restoring the \hologo{TeX} default for space after text macros
% \item mandatory long form
% \item optional plural long form
% \end{enumerate}
%    \begin{macrocode}
\RequirePackage{xspace}
\RequirePackage{amstext}
\NewDocumentCommand{\acronym}{somsmo}{
  \newabbreviation[
    type=\acronymtype,
    sort=#3,
    \glsshortpluralkey=\IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}},
    longplural=\IfNoValueTF{#6}{#5s}{#6}
  ]{#3}{\IfNoValueTF{#2}{#3}{#2}}{#5}
%    \end{macrocode}
% Provide the singular acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3\endcsname[1][]{%
    \hep@if@begin@of@sentence{%
      \hep@if@short{#3}{\cgls{#3}[##1]}{\cGls{#3}[##1]}%
    }{\cgls{#3}[##1]}%
    \ifnum\glsentrycurrcount{#3}>1\relax
      \IfBooleanTF{#4}{}{\@\xspace}%
    \else\@\xspace\fi
  }
%    \end{macrocode}
% Expand the singular acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3}{\IfNoValueTF{#2}{#3}{#2}}{\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide the singular acronym macro in math mode.
%    \begin{macrocode}
  \expandafter\mathdef\csname#3\endcsname{%
    \mathinner{\text{\glsxtrshort{#3}}}\@gls@increment@currcount{#3}%
  }
%    \end{macrocode}
% Provide the plural acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3s\endcsname[1][]{%
    \hep@if@begin@of@sentence{\cGlspl{#3}[##1]}{\cglspl{#3}[##1]}%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Expand the plural acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3s}%
    {\IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide the plural acronym macro in math mode.
%    \begin{macrocode}
  \expandafter\mathdef\csname#3s\endcsname{%
    \mathinner{\text{\glsxtrshortpl{#3}}}\@gls@increment@currcount{#3}%
  }
%    \end{macrocode}
% Provide an enforced long form.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3long\endcsname[1][]{%
    \hep@if@begin@of@sentence{\Glsdesc*{#3}[##1]}{\glsdesc*{#3}[##1]}%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Ensure that it works in \PDFs.
%    \begin{macrocode}
  \hep@pdf@define{#3long}{#5}{\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide an enforced long plural form.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3slong\endcsname[1][]{%
    \hep@if@begin@of@sentence{%
      \Glsxtrlongpl*{#3}[##1]}{\glsxtrlongpl*{#3}[##1]%
    }%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Ensure that it works in \PDFs.
%    \begin{macrocode}
  \hep@pdf@define{#3slong}{\IfNoValueTF{#6}{#5s}{#6}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide an enforced short form.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3short\endcsname[1][]{%
    \glsxtrshort{#3}\@gls@increment@currcount{#3}%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
  \hep@pdf@define{#3short}{\IfNoValueTF{#2}{#3}{#2}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide an enforced first form.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3first\endcsname[1][]{%
    \glsreset{#3}%
    \hep@if@begin@of@sentence{%
      \hep@if@short{#3}{\cgls{#3}[##1]}{\cGls{#3}[##1]}%
    }{\cgls{#3}[##1]}%
    \ifnum\glsentrycurrcount{#3}>1\relax
      \IfBooleanTF{#4}{}{\@\xspace}%
    \else\@\xspace\fi
  }
  \hep@pdf@define{#3first}{#5 (\IfNoValueTF{#2}{#3}{#2})}{\xspace}%
%    \end{macrocode}
% End of "\acronym".
%    \begin{macrocode}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\shortacronym}
% The "\shortacronym" never expands into the long form.
%    \begin{macrocode}
\NewDocumentCommand{\shortacronym}{somsmo}{
%    \end{macrocode}
% Provide the singular acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3\endcsname[1][]{%
    \IfNoValueTF{#2}{#3}{#2}##1\IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Expand the singular acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3}{\IfNoValueTF{#2}{#3}{#2}}{\IfBooleanF{#4}\xspace}%
  \hep@pdf@define{#3long}{\IfNoValueTF{#2}{#3}{#2}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide the singular acronym macro in math mode.
%    \begin{macrocode}
  \expandafter\mathdef\csname#3\endcsname{%
    \mathinner{\text{\IfNoValueTF{#2}{#3}{#2}}}%
  }
%    \end{macrocode}
% Provide the plural acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3s\endcsname[1][]{%
    \IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}}##1%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Expand the plural acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3s}%
    {\IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}}}%
    {\IfBooleanF{#4}\xspace}%
  \hep@pdf@define{#3slong}%
    {\IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide the plural acronym macro in math mode.
%    \begin{macrocode}
  \expandafter\mathdef\csname#3s\endcsname{%
    \mathinner{\text{\IfBooleanTF{#1}{#3}{\IfNoValueTF{#2}{#3s}{#2s}}}}%
  }%
%    \end{macrocode}
% Ensure that long form also exists.
%    \begin{macrocode}
  \expandafter\let\csname#3long\expandafter\endcsname\csname#3\endcsname
  \expandafter\let\csname#3slong\expandafter\endcsname\csname#3s\endcsname
%    \end{macrocode}
% End of "\shoracronym".
%    \begin{macrocode}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\longacronym}
% The "\longacronym" never shows the abbreviated form.
%    \begin{macrocode}
\NewDocumentCommand{\longacronym}{somsmo}{
%    \end{macrocode}
% Provide the singular acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3\endcsname[1][]{%
    \hep@if@begin@of@sentence{\MFUsentencecase{#5}}{#5}##1%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Expand the singular acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3}{#5}{\IfBooleanF{#4}\xspace}%
  \hep@pdf@define{#3long}{#5}{\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Provide the plural acronym macro.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#3s\endcsname[1][]{%
    \hep@if@begin@of@sentence{%
      \IfNoValueTF{#6}{\MFUsentencecase{#5s}}{\MFUsentencecase{#6}}%
    }{%
      \IfNoValueTF{#6}{#5s}{#6}%
    }##1%
    \IfBooleanTF{#4}{}{\@\xspace}%
  }
%    \end{macrocode}
% Expand the plural acronym macro in \PDF labels.
%    \begin{macrocode}
  \hep@pdf@define{#3s}{\IfNoValueTF{#6}{#5s}{#6}}%
    {\IfBooleanF{#4}\xspace}%
  \hep@pdf@define{#3slong}{\IfNoValueTF{#6}{#5s}{#6}}%
    {\IfBooleanF{#4}\xspace}%
%    \end{macrocode}
% Ensure that long form also exists.
%    \begin{macrocode}
  \expandafter\let\csname#3long\expandafter\endcsname\csname#3\endcsname
  \expandafter\let\csname#3slong\expandafter\endcsname\csname#3s\endcsname
%    \end{macrocode}
% End of "\longacronym".
%    \begin{macrocode}
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\hep@alternative}
% Execute \marg{code} with the long form and the description of the abbreviation \marg{label} replaced by its "useri" field.
% The \software{glossaries-extra} abbreviation styles read these fields directly.
% The original fields are restored afterwards, before any spacing code is executed.
%    \begin{macrocode}
\newrobustcmd*{\hep@alternative}[2]{%
  \csletcs{hep@alternative@long}{glo@\glsdetoklabel{#1}@long}%
  \csletcs{hep@alternative@desc}{glo@\glsdetoklabel{#1}@desc}%
  \csletcs{glo@\glsdetoklabel{#1}@long}{glo@\glsdetoklabel{#1}@useri}%
  \csletcs{glo@\glsdetoklabel{#1}@desc}{glo@\glsdetoklabel{#1}@useri}%
  #2%
  \csletcs{glo@\glsdetoklabel{#1}@long}{hep@alternative@long}%
  \csletcs{glo@\glsdetoklabel{#1}@desc}{hep@alternative@desc}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\acronymalternative}
% Allow for alternative long text in abbreviation.
%    \begin{macrocode}
\NewDocumentCommand{\acronymalternative}{mmsm}{%
%    \end{macrocode}
% Store it in the "useri" field.
%    \begin{macrocode}
  \GlsXtrSetField{#1}{useri}{#4}%
%    \end{macrocode}
% Define the acronym and execute the abbreviation macros with the alternative long form.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#2\endcsname[1][]{%
    \hep@alternative{#1}{%
      \hep@if@begin@of@sentence{%
        \hep@if@short{#1}{\cgls{#1}[##1]}{\cGls{#1}[##1]}%
      }{\cgls{#1}[##1]}%
    }%
%    \end{macrocode}
% Spacing code.
%    \begin{macrocode}
    \ifnum\glsentrycurrcount{#1}>1\relax
      \IfBooleanTF{#3}{}{\@\xspace}%
    \else\@\xspace\fi
  }
%    \end{macrocode}
% Redirect \PDF code to original acronym.
%    \begin{macrocode}
  \hep@pdf@define{#2}{\glsentryshort{#1}}{\IfBooleanF{#3}\xspace}%
%    \end{macrocode}
% Redirect math macro to original acronym.
%    \begin{macrocode}
  \expandafter\mathdef\csname#2\endcsname{%
    \mathinner{\text{\glsxtrshort{#1}}}\@gls@increment@currcount{#1}%
  }
%    \end{macrocode}
% Provide the long version of the acronym.
%    \begin{macrocode}
  \expandafter\newcommand\expandafter*\csname#2long\endcsname[1][]{%
    \hep@alternative{#1}{%
      \hep@if@begin@of@sentence{\Glsdesc*{#1}[##1]}{\glsdesc*{#1}[##1]}%
    }%
    \IfBooleanTF{#3}{}{\@\xspace}%
  }
%    \end{macrocode}
% Provide \PDF code.
%    \begin{macrocode}
  \hep@pdf@define{#2long}{#4}{\IfBooleanF{#3}\xspace}%
}
%    \end{macrocode}
% \end{macro}
% Silence warning if no acronyms are defined.
%    \begin{macrocode}
\renewcommand*{\@gls@write@entrycounts}{%
  \immediate\write\@auxout{%
    \string\providecommand*{\string\@gls@entry@count}[2]{}
  }%
  \count@=0\relax
  \forallglsentries{\@glsentry}{%
    \glshasattribute{\@glsentry}{entrycount}{%
      \ifglsused{\@glsentry}{%
        \immediate\write\@auxout{%
          \string\@gls@entry@count{\@glsentry}{%
            \glsentrycurrcount{\@glsentry}%
          }
        }%
      }{}\advance\count@ by \@ne
    }{}%
  }%
}
%    \end{macrocode}
% \begin{macro}{\resetacronym}
% \begin{macro}{\dummyacronym}
% Add two macros for acronym management.
%    \begin{macrocode}
\newcommand*{\resetacronym}[1]{\protect\glsreset{#1}}
\newcommand*{\dummyacronym}[1]{\protect\glsunset{#1}}
\hep@disable{\let\resetacronym\@gobble\let\dummyacronym\@gobble}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{abstract}
% Adjust the "abstract" environment to reset all acronym counters.
%    \begin{macrocode}
\@ifundefined{endabstract}{}{%
  \let\end@hep@abstract\endabstract%
  \renewcommand*\endabstract{\glsresetall\end@hep@abstract}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\acronyms}
% Add a possibility to have different groups of acronyms.
%    \begin{macrocode}
\NewDocumentCommand{\acronyms}{om}{%
  \IfNoValueTF{#1}{
    \newglossary{#2}{#2.in}{#2.out}{#2}%
    \renewcommand*{\acronymtype}{#2}%
  }{
    \newglossary{#1}{#1.in}{#1.out}{#2}%
    \renewcommand*{\acronymtype}{#1}%
  }
}
%    \end{macrocode}
% \end{macro}
%
%</package>
%
% \section{Test}
%
%<*test>
%    \begin{macrocode}
\documentclass{article}

\usepackage{hyperref}
\usepackage{hep-acronym}
\usepackage{titlesec}

\acronym{PDF}{portable document format}
\acronym{URL}{uniform resource locator}
\acronym{CM}{computer modern}
\acronym{LM}{latin modern}

\begin{document}

\PDF \emph{(Capitalised at beginning of paragraph)}
\PDF \emph{(Second appearance is shortened)}.
\URLs \emph{(Capitalised plural form at beginning of sentence)}
$\URL$ \emph{(Second appearance is forced to be always short)}
\LM \emph{(Not capitalised in middle of sentence)}
\LM \emph{(Second appearance is shorted)}.
$\CM$ \emph{(Enforce short form)}
\CM \emph{(then extend second appearance)}
\URLlong \emph{(enforce long form)}

\section{\PDFlong table of contents is not broken}

\end{document}
%    \end{macrocode}
%
%</test>
%
% \section{Readme}
%
%<*readme>
%
%    \begin{macrocode}
# The `hep-acronym` package

Acronyms based on glossaries-extra with sentence-aware capitalisation
and first-use links

## Introduction

The `hep-acronym` package provides an acronym macro based on the
`glossaries-extra` package. It defines declaration commands for regular,
always-short, always-long, and alternative long-form acronyms, keeps the
first-use counters sentence-aware, optionally links later uses back to the
first occurrence, and provides helpers for resetting, dummy-using, and
grouping acronyms.

It can be loaded using `\usepackage{hep-acronym}`.

## Author

Jan Hajer

## License

This file may be distributed and/or modified under the conditions of the
`LaTeX` Project Public License, either version 1.3c 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.3c or later is
part of all distributions of LaTeX version 2005/12/01 or later.
%    \end{macrocode}
%
%</readme>
%
% \Finale

\endinput

% \PrintIndex
% makeindex -s gglo.ist -o hep-acronym-implementation.gls hep-acronym-implementation.glo
% makeindex -s gglo.ist -o hep-acronym-implementation.ind hep-acronym-implementation.idx
