Adding a filter to insert an image from an image field into a body text area if there's not an image otherwise embedded in the first few paragraphs

TLDR i made a module: https://www.drupal.org/project/imagefieldintextifnone

So i first searched for:

And that doesn’t seem to be a good approach, although you can do it if the divs are right after each other, float the top div right into the bottom div.

Thought this would be done with the filter system but it turns out the there is no context available for what node—which piece of content—is being viewed. Could maybe be done with the lazy loader (drupal-filter-placeholder callback) but asynchronous JavaScript is not what we want or need.

Still really surprised no filters have access to context about the content they’re running on, really seems a wasted opportunity for a much more powerful filter system.

I guess our next option is a field preprocessor.

Or better(?) an entity pre-save.

Our goal is to stick the main image (which is almost certainly used in the teaser) early into the text if there’s not already an image

above (on mobile) and inset at the top right (on tablet, desktop, etc.)

If we don’t find any paragraphs somehow, or only one, we put the image first if it’s a long chunk of text, and last if it’s a short one. Let’s say short is under 700 characters and long is 700 and over.

Wondered if it would have been better or easier to use:

https://www.drupal.org/project/token_filter

or: