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?
Best Answer
Looking at the
color
documentation, it says that\colorbox
uses the parameters\fboxrule
and\fboxsep
. Maybe trybefore using the
\colorbox
.Edit:
It seems to work for me. The space between the rules isn't added by the
\colorbox
, but by the ruled float style. One possibility would be to design a new float style and then use\restylefloat
from thefloat
package to change the style of thealgorithm
floats. Rather than do that, I just added some kerns.I'm becoming less and less convinced this is the right way to do these things. It feels like we're just piling hack on top of hack here. I feel like this is partly due to using LyX, but I have zero experience with it, so I'm not positive.