2

How can we ignore hyphens when sorting the index? Here is an example:

\documentclass{article}
\usepackage{imakeidx}
\makeindex[columns=1]
\begin{document}
Test
\index{firstaid}
\index{first-love}
\printindex
\end{document}

This code results in: first-love comes before firstaid

But we would like "firstaid" to come before "first-love". We could use the @ option within each instance of \index, but I was wondering if there is a global way to set this.

0

1 Answer 1

2

If you want to get rid of all hyphens for sorting, you can do like this, which essentially does automatically \index{firstlove@first-love} when the input is \Index{first-love}.

\documentclass{article}
\usepackage{imakeidx}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\Index}{om}
 {
  \str_set:Nn \l_tmpa_str { #2 }
  \str_if_in:NnTF \l_tmpa_str { - }
   {
    \str_set_eq:NN \l_tmpb_str \l_tmpa_str
    \str_remove_all:Nn \l_tmpb_str { - }
    \use:x
     {
      \exp_not:N \index
      \IfValueT { #1 } { [ #1 ] }
      { \str_use:N \l_tmpb_str @ \str_use:N \l_tmpa_str }
     }
   }
   {
    \use:x
     {
      \exp_not:N \index
      \IfValueT { #1 } { [ #1 ] }
      { \str_use:N \l_tmpa_str }
     }
   }
 }
\ExplSyntaxOff

\makeindex[columns=1]

\begin{document}

Test
\Index{firstaid}
\Index{first-love}
\printindex

\end{document}

enter image description here

If you want to keep \index:

\documentclass{article}
\usepackage{imakeidx}
\usepackage{xparse}

\AtBeginDocument{%
  \let\originalindex\index
  \let\index\newindex
}

\ExplSyntaxOn
\NewDocumentCommand{\newindex}{om}
 {
  \str_set:Nn \l_tmpa_str { #2 }
  \str_if_in:NnTF \l_tmpa_str { - }
   {
    \str_set_eq:NN \l_tmpb_str \l_tmpa_str
    \str_remove_all:Nn \l_tmpb_str { - }
    \use:x
     {
      \exp_not:N \originalindex
      \IfValueT { #1 } { [ #1 ] }
      { \str_use:N \l_tmpb_str @ \str_use:N \l_tmpa_str }
     }
   }
   {
    \use:x
     {
      \exp_not:N \originalindex
      \IfValueT { #1 } { [ #1 ] }
      { \str_use:N \l_tmpa_str }
     }
   }
 }
\ExplSyntaxOff

\makeindex[columns=1]

\begin{document}

Test
\index{firstaid}
\index{first-love}
\printindex

\end{document}
3
  • Wow, this is awesome. Is there a way to do it so that I don't have to change \index to \Index in all of my files?
    – ipswitch
    Commented Sep 23, 2018 at 22:06
  • @ipswitch Added.
    – egreg
    Commented Sep 23, 2018 at 22:18
  • Great! For those trying to get this to work on their machine, it requires a fairly recent version of the xparse package.
    – ipswitch
    Commented Sep 24, 2018 at 4:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .