Vertical spacing after user-defined environment

sectioningspacing

In my lectures, I define an \example command for typesetting… examples a bit separated from the paragraph content. Sometimes they contain text, sometime tables, etc. For some reasons, I use \subparagraph in the definition of my command, so I need to add some vertical spacing after it in order to separate from following text. As I don’t want to add even more when already using a vmode environment, I set that conditionally for hmode only. My issue arise when there is a sectioning command after an example, like below:

\documentclass{scrartcl}

\newcommand{\example}[1]{\subparagraph{Exemple :\hspace{-1.25ex}} #1\ifhmode\par\leavevmode\fi}

\begin{document}

\subsection*{Bad spacing}

Some text.

\example{Some example text.}

\subsection*{Correct spacing}

Some more text.

\example{Some example text.}
\vspace{-\baselineskip}

\subsection*{Test}

Yet another text.

\example{Some example text.}

Final text.

\end{document}

This results in:
code output

As you can see, there is too much vertical spacing after the first “Example”, which I correct in the second one using a \vspace{-\baselineskip}.

The issue also happens when there is a second example after the first one, but I think this is the same issue because of the sectioning nature of my \example command.

Is there a way to have the correct spacing in all cases (including when there is a vmode env inside an \example{}, e.g. center)?

Best Answer

I am not too sure, what you are asking exactly, but here are some suggestions:

  1. When TeX sees a character, it will start in horizontal mode, so there is no need for you to check for vmode or hmode.
  2. Use \addvspace for vertical spacing.

To be honest personally I would use a package such as exsheets or if your lectures include maths, I would use the amsthm package to create the example environment.

\documentclass{scrartcl}
\usepackage[latin]{babel}
\usepackage{lipsum}
\newlength\exampletop
\setlength\exampletop\baselineskip
\newcommand{\example}[1]{%
  \par
  \addvspace\exampletop
  \leavevmode
  \bgroup
  \sffamily
  \bfseries 
   Example:
  \egroup
   #1
   \par
   \vskip10pt
 }

\begin{document}
    
\subsection{Test}
    
Final text.
    
\subparagraph{Example:}Subparagraph
    
\subparagraph{Example:}Subparagraph
    
\example{ \lipsum[1]}
    
\example{Some example text.
My new equation
$$a = b +  c$$}
\section{Test}
\end{document}
Related Question