# Alignment of margin floats

I am using the code from margin-floats-and-hyperlinks. It works nicely, however the figure generated is not left aligned in the margin as the caption below it is. I also tried \raggedright as suggested in align-figure-to-the-right-with-raggedleft.

MWE

\documentclass{report}
\usepackage{geometry}
\geometry{
showframe=true,
includemp,
marginparwidth=3.5cm,
marginparsep=1.5em,
hmargin={3cm,1.5cm},
vmargin={2cm,2cm},
footskip=3ex
}
%
\usepackage{placeins}

\makeatletter
% Margin float environment
\newsavebox{\@tufte@margin@floatbox}
\newenvironment{@tufte@margin@float}[2][-1.2ex]%
{\FloatBarrier% process all floats before this point so the figure/table numbers stay in order.
\begin{lrbox}{\@tufte@margin@floatbox}%
\begin{minipage}{\marginparwidth}%
\def\@captype{#2}%
\hbox{}\vspace*{#1}%
\noindent%
}
{\end{minipage}%
\end{lrbox}%
\marginpar{\usebox{\@tufte@margin@floatbox}}%
}

% Margin figure environment
\newenvironment{marginfigure}[1][-1.2ex]%
{\begin{@tufte@margin@float}[#1]{figure}
}
{\end{@tufte@margin@float}}

% Margin table environment
\newenvironment{margintable}[1][-1.2ex]%
{\begin{@tufte@margin@float}[#1]{table}
}
{\end{@tufte@margin@float}}

\makeatother

\begin{document}
\begin{marginfigure}
%\raggedright
\rule{3cm}{2cm}
\caption{A long caption so that we get at least two lines}
\end{marginfigure}
\end{document}

-

You have a spurious space in the definition of marginfigure and margintable:

% Margin figure environment
\newenvironment{marginfigure}[1][-1.2ex]%

As a reference, see What is the use of percent signs (%) at the end of lines?. Alternatively, you could insert an \ignorespaces at the start of the environments.