Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Is there a way to sort an itemized list based on the length of each item? Something like

\begin{Itemize}
\item a
\item aaaaaa
\item aaaa
\item aaa
\item aaaaa
\item aa
\end{Itemize}

which results in

a
aa
aaa
aaaa
aaaaa
aaaaaa

share|improve this question
1  
what is you real use case? Do you have to use \item markup (which makes it harder as the items are not explicit arguments of anything, and what do you mean by "length" characters in the input or typeset length is W longer than .. or not? –  David Carlisle Feb 22 '13 at 0:01
    
Sorry for delay in replying. The answer you have provided in the following is precisely what I was looking for. –  Reza Feb 22 '13 at 17:01
add comment

1 Answer

up vote 3 down vote accepted

enter image description here

This assumes you meant typeset length (and that all the items are single line)

\documentclass{article}


\def\Itemize{\vbox\bgroup
  \let\item\ItemizeItem
  \let\endItemizeItem\relax}

\def\ItemizeItem{%
  \endItemizeItem
  \let\endItemizeItem\xendItemizeItem
  \setbox0\hbox\bgroup\strut\ignorespaces}

\def\endItemize{\endItemizeItem\egroup}

\def\xendItemizeItem{%
  \unskip\egroup
  \setbox4\vbox{}%
  \loop
    \unskip
    \setbox2\lastbox
  \ifdim\wd2>\wd0
    \setbox4\vbox{\box2\unvbox4}%
  \repeat
  \nointerlineskip
  \box2
  \nointerlineskip
  \box0
  \unvbox4}



\begin{document}

\begin{Itemize}
\item a
\item aaaaaa
\item aaaa
\item aaa
\item aaaaa
\item aa
\end{Itemize}

\end{document}
share|improve this answer
    
Great technique! I'm doing a brain-internal right-click save! –  Sašo Živanović Feb 22 '13 at 14:19
    
Sorting items in a list can be very useful to avoid ugly lists. It is nice to have a list with entries sorted according to the number of characters they have. Of course, here the order of entries is not important. Until now, I had to sort the list entries manually which is tedious and time consuming. It will even be worse if at a later time you have to add new entries. David's solution is a breath of fresh air. –  Reza Feb 22 '13 at 16:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.