[Tex/LaTex] nomencl package : sort by order of appearance

nomencl

In the nomencl package, how can I make the symbols print by order of appearance in the LaTeX code?

Best Answer

As far as I know, nomencl does not support this out of the bag. Here's a hacky way to do it instead.

Basically it is a redefinition of the \nomenclature[]{}{} command, to ignore the sorting argument (i.e. the optional argument in \nomenclature) and to use a counter-based sorting method instead. Whenever \nomenclature is called, the counter @nomcount raises by one. We then take advantage of makeindex's sorting algorithm which treats numbers as per normal (8<34<111), and so the entries will be printed in order of use.

I have included a toggle for you to switch this sorting behaviour 'on' and 'off'. With

\settoggle{nomsort}{<bool>}

If <bool> is set to true, then we activate sort by use (which is your desired effect). If <bool> is set to false then we return to normal usage of nomencl (using the optional argument of \nomenclature and what not).

nomensrt

\documentclass[]{article}
\usepackage{etoolbox}
\usepackage[]{nomencl}   
    \makenomenclature

\providetoggle{nomsort}
\settoggle{nomsort}{true} % true = sort by use, false = sort as usual

\makeatletter
\iftoggle{nomsort}{%
    \let\old@@@nomenclature=\@@@nomenclature        
        \newcounter{@nomcount} \setcounter{@nomcount}{0}%
        \renewcommand\the@nomcount{\two@digits{\value{@nomcount}}}% Ensure 10>01
        \def\@@@nomenclature[#1]#2#3{% Taken from package documentation
          \addtocounter{@nomcount}{1}%
        \def\@tempa{#2}\def\@tempb{#3}%
          \protected@write\@nomenclaturefile{}%
          {\string\nomenclatureentry{\the@nomcount\nom@verb\@tempa @[{\nom@verb\@tempa}]%
          \begingroup\nom@verb\@tempb\protect\nomeqref{\theequation}%
          |nompageref}{\thepage}}%
          \endgroup
          \@esphack}%
      }{}
\makeatother


\begin{document}
    \nomenclature{$j$}{Appears first} 
    \nomenclature{$i$}{Appears second}
    \nomenclature{$h$}{Appears third}
    \nomenclature{$g$}{Appears fourth}
    \nomenclature{$f$}{Appears fifth}
    \nomenclature{$e$}{Appears sixth}
    \nomenclature{$d$}{Appears seventh}
    \nomenclature{$c$}{Appears eighth}
    \nomenclature{$b$}{Appears ninth}
    \nomenclature{$a$}{Appears tenth~(last)}
    \printnomenclature

    Note that $d$ appears first because it is declared first.

    Note also the 10th entry is sorted after the 9th.
\end{document}

To be honest, though, it's probably easier and more consistent to do it with the glossaries package, as @NicolaTalbot mentioned in the comments.

Related Question