4

I have a few commands which must be on the same page as following content. My LaTeX code is generated so I can't fix each problem manually.

Imagine situation with this code

\documentclass{article}

\usepackage{lipsum}

\newcommand{\heading}{
    \noindent \textbf{heading}\\
}

\begin{document}

    %% ONLY FOR EXAMPLE 
    some text
    \vspace{185mm}



    \heading

    \lipsum[1]

\end{document}

which results to this output

enter image description here

How can I ensure that the heading will be always on the same page as following content? Thanks

sssss
  • 177
  • Well, there are other ways to produce a heading. However, you could use a minipage or an unnumbered section (i.e. \section*{My heading}). But who/what generates this LaTeX code? –  Apr 01 '16 at 12:06
  • 1
    your heading code will generate underfull box warnings because of the misused \\ If you want to keep all the following para togetherput all the text in a \noindent\begin{minipage{\textwidth}...\end{minipage} will keep it together, if you just want the heading to stay with the first few lines, but allow page breaking just use a proper heading command such as \section*{heading} – David Carlisle Apr 01 '16 at 12:07

1 Answers1

5

The needspace package is useful here. \needspace{1in}\section{} will only put the section header on the page if an inch is left on the page. Otherwise, it will move it to the next page.

Note I modified the OP's \heading macro to use \section* with an argument.

\documentclass{article}

\usepackage{lipsum}
\usepackage{needspace}
\newcommand{\heading}[1]{
  \needspace{1in}\section*{#1}
}

\begin{document}

    %% ONLY FOR EXAMPLE 
    some text
    \vspace{185mm}


    \heading{Heading}

    \lipsum[1]

\end{document}

enter image description here