Background
Including images within Algorithm floats. The images are trimmed to size automatically by a batch file.
Problem
In the following portion of the PDF, Listing 1.1 has a lot of space to the right of the source code [First Image]:
The result I am looking to achieve is [Second Image]:
Note that there is a small amount of space between the upper and lower lines surrounding the image that I would also like to remove.
Code
Relevant preamble code:
\definecolor{sourcecolour}{HTML}{F0F0F0}
% Determine if the image is too wide for the page.
\makeatletter
\def\ScaleIfNeeded{%
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
% Resize figures that are too wide for the page.
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][H]{%
\oldincludegraphics[width=\ScaleIfNeeded]{#2}%
\graphicsalignment
}
% Change the background colour of algorithm boxes
\let\oldalgorithm\algorithm
\let\endoldalgorithm\endalgorithm
\renewenvironment{algorithm}[1][htbp]{
\let\graphicsalignment\relax
\oldalgorithm[#1]
}%
{\endoldalgorithm}
% Centre graphics within non-Algorithm floats.
\let\graphicsalignment\centering
Ideas
Enclose the image in a \colorbox
:
\colorbox{sourcecolour}{\parbox{\textwidth}{...}
This did not work as expected. The \colorbox
added its own ~0.25em border around the image, pushing the right-side into the margin. Also, it had a side-effect of turning off the centering for Figure floats. (The Figure floats are centered whereas the Algorithm floats--showing source code listings--are left-aligned.)
Another possibility is to not auto-crop the highlighted source code image, but then if I change the book width, I'd have to regenerate all images for the book. I'd rather just fill in the white space.
Another try:
\setlength\fboxrule{0pt}
\setlength\fboxsep{0pt}
% Retain left-alignment, and change background colour of algorithm floats.
\let\oldalgorithm\algorithm
\let\endoldalgorithm\endalgorithm
\renewenvironment{algorithm}[1][htbp]{
\let\graphicsalignment\relax
\colorbox{sourcecolour}{\parbox{\textwidth}{%
\oldalgorithm[#1]}}}%
{\endoldalgorithm}
This results in a compile error.
Question
What LaTeX code is required in the preamble to make First Image resemble Second Image, without affecting the justification?