[Tex/LaTex] Calculate parbox width to make it meet the page border

boxescalculationswidth

I'm using the program package to typeset my algorithms. I want my comments to have a light gray background, therefore I'm using colorbox with a parbox inside (for multi-line comments).

Now the problem is that when I want to insert a comment in an indented line, setting the parbox's width to \textwidth or \linewidth will make it too big, crossing the right page border.

I'm looking for a way to compute the parbox's width based on the current indentation (which I can't seem to find out) or its horizontal starting position so that it always goes up to the right page border.

Any ideas?

EDIT: Here's a minimum working example. The renewcommand commented out is the solution suggested first, but it doesn't work here.

\documentclass{article}
\usepackage{program}
\usepackage{color}
\usepackage{calc}

\definecolor{commentcolor}{gray}{0.9}
\newcommand{\commentbox}[1] {\colorbox{commentcolor}{\parbox{\linewidth-2\fboxsep}{#1}}}
%\renewcommand{\commentbox}[1] {\noindent\colorbox{commentcolor}{\parbox{\linewidth-2\fboxsep}{#1}}}

\begin{document}

\begin{programbox}
\commentbox{A normal comment.}
\IF someCondition
    \THEN
        \commentbox{An indented comment.}
        myVar := myVar + 1
\FI
\end{programbox}

\end{document}

Best Answer

If your document always uses LaTeX constructs then

 \usepackage{calc}

...

\noindent\colorbox{red}\parbox{\linewidth - 2\fboxsep}{....}}

should work. (If not please provide a full MWE that shows the problem)


In a tabbing environment everything is different, but LaTeX has already measured everything to set the tab stops so you just need to dig out the lengths. The following definition includes a -15pt which is accounting for some extra space from program so it is probably possible to replace that with a suitable internal from that package if you know it well. (I haven't used it before:-) But If you get it wrong TeX tells you how much the box is over-full in the log so just subtracted that amount.

enter image description here

\documentclass{article}
\usepackage{program}
\usepackage{color}
\usepackage{calc}

\definecolor{commentcolor}{gray}{0.9}
\makeatletter


\newcommand{\commentbox}[1] {%
  \noindent\colorbox{commentcolor}{%
        \parbox{\linewidth- \dimen\@curtab - 2\fboxsep - 15pt}{%
           \raggedright#1}}}

\begin{document}




\noindent X \dotfill X


\begin{programbox}

\commentbox{A normal comment.}
\IF someCondition
    \THEN
        \commentbox{An indented comment.
                    with 2 lines}
        myVar := myVar + 1
\FI
\end{programbox}


\noindent X \dotfill X

\end{document}