[Tex/LaTex] Command and following content on the same page

samepage

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

Best Answer

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

Related Question