\useMPlibrary [dum]

\unprotect

\setupfloat
  [figure]
  [default={top,bottom}]

\setupfloat
  [table]
  [default={bottom,top}]

\definefloat
  [margintable]
  [margintables]
  [table]

\definefloat
  [marginfigure]
  [marginfigures]
  [figure]

\setupcaptions
  [width=\marginwidth,
   prefix=no]

\setupcaption
  [table]
  [location={outermargin, high}]

\setupcaption
  [figure]
  [location={outermargin, high}]

\setupcaption
  [marginfigure, margintable]
  [align=flushleft,
   location=bottom]

\setupcaption
  [table, figure]
  [way=bytext]

\setupfloat
  [marginfigure, margintable]
  [default=margin]

\definefloat
  [widetable]
  [widetables]
  [table]

\setupfloat
  [widetable]
  [location=inner]

\definefloat
  [widefigure]
  [widefigures]
  [figure]

\setupfloat
  [widefigure]
  [location=inner]

\defineframed
  [caption_framed]
  [frame=off,
   offset=overlay,
   location=high,
   toffset=7.5ex]

\starttexdefinition caption_command #1
  \caption_framed{#1}
\stoptexdefinition

\setupcaption
  [widetable]
  [location={outermargin, low},
   command=\caption_command]

\setupcaption
  [widefigure]
  [location={outermargin, low},
   command=\caption_command]

\newtoks\t_smart_figure_args

\starttexdefinition startplacesmartfigure [#1]
  \t_smart_figure_args={#1}
  \grabbufferdata
    [smart_figure_buffer]
    [startplacesmartfigure]
    [stopplacesmartfigure]
\stoptexdefinition

\startluacode
  userdata = userdata or { }

  function userdata.do_place_smart_figure(width)
    context.unprotect()
    if tex.sp(width) <= tex.dimen.rightmarginwidth + tex.sp(".1pt") then
      context.startplacemarginfigure{tex.toks.t_smart_figure_args}
        tex.print(buffers.getcontent("smart_figure_buffer"))
      context.stopplacemarginfigure()
    else
      if tex.sp(width) <= tex.dimen.textwidth + tex.sp(".1pt") then
        context.startplacefigure{tex.toks.t_smart_figure_args}
          tex.print(buffers.getcontent("smart_figure_buffer"))
        context.stopplacefigure()
      else
        context.startplacewidefigure{tex.toks.t_smart_figure_args}
          tex.print(buffers.getcontent("smart_figure_buffer"))
        context.stopplacewidefigure()
      end
    end
    context.protect()
  end
\stopluacode

\starttexdefinition stopplacesmartfigure
  \scratchdimen\hsize
  \hsize\maxdimen
    \setbox\scratchbox\vbox{\getbuffer[smart_figure_buffer]}
  \hsize\scratchdimen

  \luacode{userdata.do_place_smart_figure("\the\wd\scratchbox")}
\stoptexdefinition

\protect

\starttext

\startplacesmartfigure [title=Foo]
  \externalfigure [dummy] [width=\rightmarginwidth, height=3cm]
\stopplacesmartfigure

\dorecurse{5}{%%
  \input knuth\par}

\startplacesmartfigure [title=\input ward\par]
  \externalfigure [dummy] [width=\textwidth, height=8cm]
\stopplacesmartfigure

\startplacesmartfigure [title=\input ward\par]
  \externalfigure [dummy] [width=\dimexpr\textwidth+\rightmargintotal\relax, height=3cm]
\stopplacesmartfigure

\stoptext
