9

Is it possible to tell latex, that it should sort the sections you used in your document according to their alphabetical order in the final pdf document? I.e. I want to have something like this

\begin{document}
\section{A}
\section{C}
\section{B}
\end{document}

and in the pdf I get the result as

A
B
C

Is that possible, and if yes, how? Putting the sections into separate files is not preferred (but possible if scripted) due to having ~300 sections. Edit: I can also rewrite it as

\begin{sortEnvironment}{Title}
Content
\end{sortEnvironment}

if that makes it easier.

5
  • I've done something 'similar' here tex.stackexchange.com/questions/296125/…, but TeX does not sort, unfortunately.
    – user31729
    Mar 13, 2016 at 16:01
  • 1) do you need the optional argument of section \section[short title]{very long long title}? 2) can you make each section in environment (mysection)? 3) or can you use \mysection{title}{contents of section}?
    – touhami
    Mar 13, 2016 at 18:01
  • @touhami: I added an extension of my question, how I also can write my problem
    – arc_lupus
    Mar 13, 2016 at 18:21
  • Your suggested environment-like section would be the way to go, otherwise it would be difficult to move the section Content with the sorting (not impossible, but difficult, based on the structure). What type of stuff would be inside Content?
    – Werner
    Mar 13, 2016 at 18:26
  • Text and sub-environments
    – arc_lupus
    Mar 13, 2016 at 18:52

3 Answers 3

1

(This answer is an improvement over my previous answer where you had to create the external files manually and run external command from shell prompt. For the present one, you do everything in LaTeX.)

In this answer, I used the LaTeX environment you wanted to use. Here, the sections are written to separate files, and the list is put in a master file, which is sorted using external shell command and then input when you issue the \PrintSections command.

Here is the code. You need to provide the -shell-escape option while executing latex or pdflatex.

\documentclass{article}

\usepackage{amsmath}

\usepackage{lipsum}

\usepackage{newfile}

\makeatletter

% Section list stream
\newoutputstream{sslist}
\openoutputfile{"\jobname.sslist.tex"}{sslist}

\usepackage{environ}
\newoutputstream{ssout}
\NewEnviron{sortEnvironment}[1]{
  % Save section file name in external list for input
  \addtostream{sslist}{\noexpand\input {"\jobname.#1"}}
  % Save the section in an external file
  \openoutputfile{"\jobname.#1.tex"}{ssout}
  \addtostream{ssout}{\noexpand\section{#1}}
  \toks@=\expandafter{\BODY}
  \addtostream{ssout}{\the\toks@}}
  [\closeoutputstream{ssout}]

\def\PrintSections{%
  % Close list stream
  \closeoutputstream{sslist}
  % Sort list stream using external shell and save in file
  \immediate\write18{sort "\jobname.sslist.tex" > "\jobname.sslist.sorted.tex"}
  % Get the sorted sections through the above list
  \input {"\jobname.sslist.sorted.tex"}
}                               

\makeatother


\begin{document}

\begin{sortEnvironment}{Title}
  Content
\end{sortEnvironment}

\begin{sortEnvironment}{Ab}
  Ab, Ab, Ab, Ab, Ab.
\end{sortEnvironment}

\begin{sortEnvironment}{A}
  Ab, Ab, Ab, Ab, Ab.
\end{sortEnvironment}

\begin{sortEnvironment}{Zebra}
  Zebras have \textit{strips} all over the body.
\end{sortEnvironment}


\begin{sortEnvironment}{Aa}
  About AA.

  $x = y^2$
\end{sortEnvironment}

\begin{sortEnvironment}{CAD}
  CAD as in ``Computer-Aided Design''
  or ``Canada Dollar''?

  \lipsum[1]

\end{sortEnvironment}

\begin{sortEnvironment}{Name Contains Mathematics $x + y$}
  Section name has mathematics.
\end{sortEnvironment}


\begin{sortEnvironment}{Name Does Not Contain Mathematics Ex Plus Wye}
  Section name does not have mathematics.
\end{sortEnvironment}


\begin{sortEnvironment}{Section Names Can Have Multiple Words}

  \lipsum[2]

\end{sortEnvironment}

\section{Before Sorted Sections}
We have some texts here. The sorted sections are printed after this.


\PrintSections

\section{After Sorted Sections}
And some texts at the end.


\end{document}

Here is the output.

enter image description here

enter image description here

7

The Idea

The solution uses one technique you did not prefer. Namely, putting sections in separate files. However, that is is only (non-cumbersome) I can find in order to sort the sections.

Anyway, this is your framework.

(The solution is based on Linux (bash) techniques, but should be adaptable to other OSs as well.)

  1. Put each section in separate files. The file name should be same the section name. So, a \section{Zebra} is put in a file named Zebra.tex (or you can name them in shorter names if that satisfies the sorting order).
  2. All section files are kept in a separate directory, so as not to disturb the main files. Here we are using a directory called, sectionfiles.
  3. Run the script ss.bash (given below). Please note that the other processors after the first ls ensures non-intervention of file extensions. We also assure dictionary order. A simple ls -1 will generate list different from this.

  4. Run LaTeX on the main file.

The Processor ss.bash

The sorter and sectionlist.tex generator.

#!/bin/bash

echo "" > sectionlist.tex
for sfile in `ls -1 sectionfiles/*.tex | cut -f 1 -d . | sort -d`
do
    echo "\input {$sfile.tex}" >> sectionlist.tex
done

echo "\endinput" >> sectionlist.tex

After ss.bash is run, my sectionlist.tex looks like this.

\input {sectionfiles/A.tex}
\input {sectionfiles/Aa.tex}
\input {sectionfiles/Ab.tex}
\input {sectionfiles/B.tex}
\input {sectionfiles/C.tex}
\input {sectionfiles/CAD.tex}
\input {sectionfiles/Cc.tex}
\input {sectionfiles/Dummy.tex}
\input {sectionfiles/Zebra.tex}
\endinput

The (Trivial) LaTeX Main File

\documentclass{article}

\usepackage{lipsum}

\begin{document}

\input {sectionlist.tex}

\end{document}

The Output Pages

enter image description here

enter image description here

enter image description here

Final Comments

I understand that a pure LaTeX solution would have made all of us much
happier. But this is the best I could achieve.

4

If you're willing to use an environment-approach, then you can use datatool to sort the content:

enter image description here

\documentclass{article}

\usepackage{datatool,environ,newfile}

\NewEnviron{sortEnvironment}[1]{{%
  \let\par\DTLpar% Cannot include \par in content, so replace \par with \DTLpar
  \addtostream{sortOutput}{"#1","\BODY"}% Write section content to output file
}}

\AtBeginDocument{%
  \newoutputstream{sortOutput}% New output file
  \openoutputfile{sortContent.csv}{sortOutput}% Open output file
}
\AtEndDocument{%
  \closeoutputstream{sortOutput}% Close output file
  \DTLloaddb[
      noheader,
      keys={Title,Content}]
    {sortedSections}{sortContent.csv}% Load stored content
  \dtlsort{Title}{sortedSections}{\dtlcompare}% Sort stored content
  \DTLforeach{sortedSections}{\Title=Title,\Content=Content}
    {\section{\Title} \Content}% Print all content
}

\begin{document}

\begin{sortEnvironment}{TitleA}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi id diam ante. Quisque 
commodo magna lorem, sed vulputate enim fringilla non. In vitae venenatis arcu, nec 
pulvinar leo. Aliquam eget magna euismod, sodales mauris sit amet, sagittis lectus. 
Mauris sodales nisl turpis, et viverra felis auctor sed. Aliquam ac est lobortis, 
condimentum ligula euismod, mattis ligula. Sed sed volutpat eros. Vestibulum quis 
enim in nisl consectetur vulputate. Phasellus viverra ac neque et convallis. Pellentesque 
blandit porta commodo. Sed semper quis justo in luctus. Sed vel vulputate ligula. 
Sed gravida magna dignissim urna eleifend rutrum. Aenean bibendum, risus in tincidunt 
consectetur, elit quam luctus lacus, id venenatis nibh erat at tellus. Pellentesque 
lacinia dictum nibh a iaculis.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi id diam ante. Quisque 
commodo magna lorem, sed vulputate enim fringilla non. In vitae venenatis arcu, nec 
pulvinar leo. Aliquam eget magna euismod, sodales mauris sit amet, sagittis lectus. 
Mauris sodales nisl turpis, et viverra felis auctor sed. Aliquam ac est lobortis, 
condimentum ligula euismod, mattis ligula. Sed sed volutpat eros. Vestibulum quis 
enim in nisl consectetur vulputate. Phasellus viverra ac neque et convallis. Pellentesque 
blandit porta commodo. Sed semper quis justo in luctus. Sed vel vulputate ligula. 
Sed gravida magna dignissim urna eleifend rutrum. Aenean bibendum, risus in tincidunt 
consectetur, elit quam luctus lacus, id venenatis nibh erat at tellus. Pellentesque 
lacinia dictum nibh a iaculis.
\end{sortEnvironment}

\begin{sortEnvironment}{TitleC}
In hac habitasse platea dictumst. Pellentesque non augue vitae sem tincidunt porttitor 
eget in eros. Pellentesque habitant morbi tristique senectus et netus et malesuada 
fames ac turpis egestas. Suspendisse quis consectetur tellus. Nam varius velit gravida 
ultricies pulvinar. Nunc diam orci, eleifend in turpis at, tristique egestas felis. 
Aenean tellus tellus, sagittis sed congue ut, facilisis non lacus. Phasellus volutpat 
nec eros vitae congue. Nam maximus dolor eget porta fermentum. Duis ex libero, 
fermentum a eleifend sed, consectetur quis erat. Integer sagittis orci et sapien 
dignissim, volutpat elementum ligula interdum. Sed aliquam tristique leo et placerat.
\end{sortEnvironment}

\begin{sortEnvironment}{TitleB}
Fusce mattis suscipit leo et eleifend. Pellentesque habitant morbi tristique senectus 
et netus et malesuada fames ac turpis egestas. Praesent tincidunt, leo in luctus 
elementum, lacus sem suscipit ante, ac rutrum mauris neque eu neque. Pellentesque 
ultricies ultricies massa, at aliquam nulla fringilla vitae. Suspendisse at diam 
ullamcorper, congue felis a, iaculis eros. Praesent sed diam mauris. Pellentesque 
porttitor vitae leo vel dictum. Maecenas vulputate neque vitae massa pulvinar, 
viverra facilisis nunc tincidunt. Proin eu eros volutpat turpis egestas malesuada 
non a ante. Etiam bibendum turpis sit amet enim commodo sodales. Duis ex metus, 
cursus in tellus ut, placerat pharetra enim. Praesent tristique, sapien et aliquam 
euismod, nibh massa accumsan eros, sed rhoncus lectus urna eu eros. Aliquam congue 
sem id laoreet eleifend. Quisque quis egestas tellus. Aliquam dui dolor, mollis non 
neque sit amet, eleifend consectetur lectus.
\end{sortEnvironment}

\end{document}

The above example writes each sortEnvironment to a CSV file, which is then read, sorted and printed at \AtEndDocument using datatool's database sorting functionality.

You must log in to answer this question.

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