Write Subsection 1.1 after Section 2

sectioning

I am trying to create a subsection of a different section in my document but I can't achieve that, no matter what I do. Basically I want the \subsection to be a subsection of the first section in my document, for example:

\documentclass{article}

\section{Section 1}
% some lines

\newpage
\section{Section 2}
% more lines

\newpage
\subsection{Section 1.1 (subsection of Section 1)}

The \subsection is always a subsection of Section 2 and I can't get it to be of Section 1.
(that way of subsectioning sounds stupid but I want to make a comparison between Section 1 and Section 2 so I have to put them right after each other, then the subsections come later)
Any help will be appreciated 🙂

Best Answer

One of the answers to the linked question shows how to write section numbers manually using \section*, or in this case \subsection*.

These manually numbered sections are not added to the table of contents (ToC), but you can also add entries to the ToC yourself using the command \addtocontents. Note that there is also \addcontentsline, but that automatically adds a page number, which should also be set manually in this case.

The use of \addtocontents is as follows:

\addtocontents
{contents type} % toc (regular table of contents) or lof (list of figures), lot (list of tables) etc.
{\protect\contentsline
   {section type} % chapter, section, subsection, subsubsection etc.
   {number and name of section}
   {page number}
}

So we can use for example:

\addtocontents{toc}{\protect\contentsline{subsection}{1.1 Subsection of first section}{4}}

This line should be put at the correct position in the document, in this case below the first \section command that is automatically added to the ToC.

Full MWE:

\documentclass{article}
% next line only to make pages smaller for screenshot, can be removed
\usepackage[paperheight=5cm,totalheight=2.5cm]{geometry}
\begin{document}
\tableofcontents
\section{First section}
\addtocontents{toc}{\protect\contentsline{subsection}{1.1 Subsection of first section}{4}}
some lines
\newpage

\section{Second section}
more lines

\newpage
\subsection*{1.1 Subsection of first section}
\end{document}

Result:

enter image description here

Note that this structure could be confusing for the reader, because the table of contents has a different order than the document itself. Additionally you need to be very careful that all numbers stay correct also when adding or removing content or moving sections around - one of the main advantages of LaTeX is that you don't have to worry about such things because everything is automatic, but with a solution such as this you don't have that advantage anymore.

Note also that when you use the hyperref package this code will not work, you need a bit more complex code in that case.

Related Question