In many cases, I prefer to have a picture directly after the text, without caption... like that: enter image description here

However, when there is no space for the picture (end of page...), I prefer to create a figure environment:

enter image description here

For now I need to manually change the code depending on which case I am, but it's really long and tedious to do (even once the document does not change too much), and it does not scale for big or changing documents (after any change I would need to recheck everything...) Any idea if I can automatize this process?



\section{If there is enough space}

  As you can see in this picture, A is a nice letter:


\section{If there is NOT enough space}

  As you can see in \cref{fig:fig2}, A is a nice letter.
  \caption{Figure for \cref{def:2}}


\section{Example of syntax}

I'd like to use a syntax like:
As you can see \figureIfSpace%
{in this picture, A is a nice letter:}% <- Text if space
{in \cref{fig:fig2}, A is a nice letter.}% <- Text if not enough space
{\includegraphics[width=5cm]{example-image-a}}% <- Image...
[\caption{Figure for \cref{def:2}} \label{fig:fig2}]% <- Caption/labels


I tried to solve this issue using \pagetotal to check the remaining space, but the obtained size seems to be too big: if I draw a rule of that size, it is pushed on the next page:


%Remaining space (above this line):

Not really an answer, more of a suggestion. Take a look at the code of the needspace package, which checks if there is a certain amount of space left on a page. If there is not then it starts a new page. You might be able to do something similar regarding checking the available space but then do your own thing regarding (un)captioned illustration. I suppose you could always just include the graphic and use, or not, \captionof from the caption package.

  • Thanks for the pointer. Internally, it seems using something like I tried above, equivalent to: \edef\measurepage{\the\dimexpr\pagegoal-\pagetotal\relax}. But this is not precise enough apparently since \rule{1mm}{\measurepage} is always pushed on the newt page... So I need to remove some arbitrary amount of text to ensure it fits, and it's not great...
    – tobiasBora
    Sep 30 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.