# ConTeXt figure placement

For years I've used a LaTeX macro that allowed me to embed figures into my text with relatively little fuss. I could type something like:

A typological comparison (see Figure \Fig[Caption text]{file.png}) suggests that...


The output would render the figure number in situ and place the actual image somewhere nearby, depending on its size and available page space.

I have been trying to create something similar in ConTeXt, but so far no luck. I assume I should be able to do this with some combination of \placefigure and \in. This command...

\def\Fig[#1]#2{%
%\startpostponing[+0]%
\startplacefigure[reference=fig:#2,title=#1]%
%\dontleavehmode%
\externalfigure[#2]%
\stopplacefigure%
%\stoppostponing%
\in{Figure}[fig:#2]%
}


...is close, but it forces a linebreak that disrupts the paragraph.

I've tried using \dontleavehmode, as per the suggestion in the FAQ, but that doesn't fix the problem. I've also tried wrapping the placefigure command in postpoining[+0] tags, as advised in this question, but that causes the parser to abort and wait for input. ConTeXt doesn't tell me why it aborts, but I would guess that it's not able to resolve the \in command when the figure placement is postponed.

Any suggestions?

• Do you want the figure to float? If so, don't use location=here. (The parser aborting is due to catcodes, I'll post an answer later). – Aditya Oct 28 '13 at 19:59
• @Aditya Thanks, I've edited the post to remove the location=here. I'm still unable to get rid of the linebreak. – MalFet Oct 28 '13 at 20:13

Here is a hackish solution. For some reason it does not work on the first page of the document (the float gets pushed to the second page), but other than that, it looks fine.

\startluacode

template = [=====[
\startplacefigure[title={%s}, reference=fig:%s]
\externalfigure[%s]
\stopplacefigure
]=====]

userdata = userdata or {}

function userdata.displayfigure(title, file)
commands.assignbuffer("postponedblock", string.format(template, title, file, file))
commands.registerpostponedblock("+0")
end
\stopluacode

\unexpanded\def\Fig[#1]#2%
{\ctxlua{userdata.displayfigure("#1", "#2")}\relax\in{Figure}[fig:#2]}

\starttext

\input tufte
typological comparison (see \Fig[Caption text]{file.png}) suggests that
\input tufte
\input tufte
\input tufte

\input tufte
\input tufte
\input tufte
\input tufte
\input tufte
\input tufte
\input tufte
\input tufte
\input tufte

\input tufte
\input tufte
\input tufte
\input tufte
typological comparison (see \Fig[Caption text]{file.png}) suggests that
\input ward

\stoptext


One thing to keep in mind is that the figure will be placed on the page where the paragraph starts, rather than the page where the \Fig macro occurs. This is just a consequence of the fact that TeX does linebreaking before it does page breaking.