[Tex/LaTex] How to highlight all inline math in document

backgroundsformattinginline()

As the title says, I would like to highlight all the content of $...$, \(...\), \begin{math}...\end{math} in my document.

My last trial, however not really well asked was:

Background color for inline math with linebreaks?

Unfortunately, after finally testing the proposed solution I found out, that:

  • It fails when math gets taller – in example using \frac or \displaystyle.
  • It fails when math extends over \textwidth – one of the purposes of highlighting would be to spot overfull lines.
  • The need to mark every equation with a separate pair of markers is cumbersome.

I tried to fix some of the issues, but I got completely lost in the code.

Update

@jfbu's answer looks pretty satisfying. The only test case I can think of at the moment, which is not covered is

Finally, while display equations look good for a page of samples,
the ability to mix math and text
\(\displaystyle \frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} = 
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots} } } }\)
The amssymb package might be omissible for documents whose math.

outcome

I guess constant height would give it a better feel.

Next update

As stated in the updated answer, mixing height of the content that is spread over a few lines gives unwanted results, as in

Finally, while display equations look good for a page of samples,
the ability to mix math and text \(\displaystyle ABC_{1234} + 
ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} = 
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =  
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots} } } }\).
The amssymb package might be omissible for certain documents.

which treats each line as it was tall

result

Is it possible to make highlighting line-aware?

I hope I don't cross the line, as the great job have already been done here. Anyway this one step could make it flawless.

Best Answer

Hard work has led to something better. But this is not strictly TeX it uses the \pdfsavepos via the linegoal package.

Thus, the command \Highlight defined here can be used to give a colored background to portion from A to B in a paragraph, with linebreaks authorized. Although the OP's question was about inline math, in the end the final answer has no specific link to math. The macro, theoretically changes nothing to the layout of the paragraph, apart from adding the colored backgrounds.

To avoid these color bars overwriting descenders elsewhere, the user may add \strut's, just before and just after both the starting point and the ending point of the argument to the macro; this is not done automatically (but it could at least be as an option). If the macro is to be used already at the start of a paragraph, it should be preceded by \indent or \noindent.

The macro is not able to cope with page breaks occurring inside the highlighted material. And it is not for use on multi-paragraphs at once.

The material is typeset three times, the first two inside temporary \vboxes but this will impact \LaTeX counters as they are global. Some more refined version of the macro would take care of such things.

The whole thing could not work without pdftex \pdfsavepos, via package linegoal.

\documentclass{article}
\usepackage{color}
\usepackage{linegoal} % http://ctan.org/pkg/linegoal

% debugging
% \showboxdepth\maxdimen
% \showboxbreadth\maxdimen
% \errorcontextlines 5

\definecolor{SkyBlue}{cmyk}{0.62,0,0.12,0}
\definecolor{BlueGreen}{cmyk}{0.85,0,0.33,0}
\definecolor{Thistle}{cmyk}{0.12,0.59,0,0}

\newbox\HighlightPiece 
\newdimen\FirstHeight
\newdimen\FirstDepth
\newdimen\LastHeight
\newdimen\LastDepth
\newdimen\TotalHeight
\newdimen\TotalDepth
\newdimen\LineIndent
\newdimen\LineGoal

\newif\ifOnePiece

\makeatletter
\newcommand\HLGetDimensions {% 
  \setbox\HighlightPiece\lastbox
  \unskip\unpenalty
  \ifdim\wd\HighlightPiece<\linewidth
      \global\OnePiecetrue
  \else
      \global\OnePiecefalse
  \fi 
  \ifOnePiece
  \else
    \global\LastHeight\ht\HighlightPiece
    \global\LastDepth\dp\HighlightPiece
    \loop % 
    \setbox\HighlightPiece\lastbox
    \unskip\unpenalty
    \ifvoid\HighlightPiece\else
      \ifdim\wd\HighlightPiece<\linewidth
       \global\FirstHeight\ht\HighlightPiece
       \global\FirstDepth\dp\HighlightPiece
      \fi
    \repeat
 \fi
}
\newcommand\Highlight [2][yellow]
     {%
     \LineGoal\linegoal     % http://ctan.org/pkg/linegoal
     \LineIndent=\dimexpr\linewidth-\LineGoal\relax
     \vbox{%
     \hfuzz\maxdimen
     \hangindent\LineIndent
     \hangafter\m@ne
     \noindent  #2\endgraf 
     \HLGetDimensions
     }%
     \ifOnePiece
           \begingroup \fboxsep\z@
           \colorbox{#1}{#2}%
           \endgroup
     \else
        \setbox\z@\vbox{%
                        \hfuzz\maxdimen
                        \hangindent\LineIndent
                        \hangafter\m@ne
                        \noindent #2\endgraf }%
        \TotalHeight\ht\z@
        \TotalDepth\dp\z@
        \advance\TotalHeight\TotalDepth
        \advance\TotalHeight-\FirstHeight
        \advance\TotalHeight-\FirstDepth
        \begingroup % et pas \color@begingroup, cf plus bas!
          \color{#1}%
          \rlap{\hbox{\vrule\@height\FirstHeight
                            \@depth\FirstDepth
                            \@width\LineGoal}}%
          \setbox\z@\vbox{\moveleft\LineIndent
                          \hbox{\vrule
                                \@height\TotalHeight
                                \@depth\z@
                                \@width\linewidth}}%
        \ht\z@\z@\dp\z@-\FirstDepth\wd\z@\z@
        \lower\FirstDepth\box\z@
        \endgroup % \color@endgroup fait basculer en mode vertical!!
         #2%
        \LineGoal\linegoal
        \rlap{\hbox{\begingroup\color{white}%
                        \vrule\@height\LastHeight
                               \@depth\LastDepth
                               \@width\dimexpr\LineGoal+1pt\relax
                    \endgroup}}% this 1pt could be a user hook dimen.
     \fi
}%

\makeatother

\renewcommand\([1][yellow]{\GatherAndHighlight {#1}}
\def\GatherAndHighlight #1#2\){\Highlight[#1]{$#2$}}

\begin{document}

Here is some test \(\displaystyle 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}}
  {1+\frac{e^{-6\pi}} 
{1+\frac{e^{-8\pi}} {1+\ldots}}}}=\displaystyle
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}}\) inline.

Here is some fundamental (inline) new equation governing everything in the
universe: \Highlight[SkyBlue]{$ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} +
  ABC_{1234} - 
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}$}. Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \([green]ABC_{1234} = A_{1} + AB_{12} - ABC_{123} + A_{1} = {\displaystyle
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}}} = AB_{12} - ABC_{123} + A_{1} + AB_{12} - ABC_{123}  + AB_{12} -
ABC_{123} + A_{1} = ABC_{1234} = A_{1} + AB_{12} - ABC_{123} + A_{1} = {\displaystyle
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}}} = AB_{12} - ABC_{123} + A_{1} + AB_{12} - ABC_{123}  + AB_{12} -
ABC_{123} + A_{1} \). Pretty impressive, no?

I worked (very) hard and it seems to cope fairly well (but \emph{do not
  forget to compile many times, at least twice after each change}):
\(ABC_{1234} = A_{1} + AB_{12} - ABC_{123} + A_{1} = {\displaystyle
  \frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =
  1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
      {1+\frac{e^{-8\pi}} {1+\ldots}}}}} = AB_{12} - ABC_{123} + A_{1} +
AB_{12} - ABC_{123} + AB_{12} - ABC_{123} + A_{1} \), although not
completely perfectly (adding struts could help). Let me take this
opportunity to say that \Highlight[red]{\strut I will NOT handle the case of
  page breaks occurring mid-way through inline material!\strut}

Actually, as we saw this powerful and beautiful macro
\texttt{\string\Highlight} is absolutely not \Highlight[Thistle]{limited to
  inline math, it may contain any sort of breakable material,
  $ABC_{1234} = A_{1} + ABCD_{123456} - ABC_{123} + 
  A_{1} = {\displaystyle \frac{1}{(\sqrt{\phi \sqrt{5}}-\phi)
  e^{\frac25 \pi}}} = AB_{12} - ABC_{123} + A_{1} + AB_{12} -
  ABC_{123} + AB_{12} - ABC_{123}$ including math within text.}
If you see very dim thinny horizontal lines, it may be an artefact of the
bad rendering of colored boxes in some pdf viewers!


  The impact on actual layout of the paragraph is supposed to be
  non-existent, we can see here with a case of slight overfull that line
  breaks are not modified.

Things may be a bit full. \(ABC_{1234} = A_{1} + AB_{12} - ABC_{123} +
A_{1} = {\displaystyle 
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =  
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots}}}}} = AB_{12} - ABC_{123} + A_{1} +
AB_{12} - ABC_{123}  + AB_{12} - 
ABC_{123} + A_{1} \). 

Things may be a bit full. $ABC_{1234} = A_{1} + AB_{12} - ABC_{123} +
A_{1} = {\displaystyle 
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =  
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots}}}}} = AB_{12} - ABC_{123} + A_{1} +
AB_{12} - ABC_{123}  + AB_{12} - 
ABC_{123} + A_{1} $. 


\end{document}

highlights ultimate


Here is an evolution of my earlier proposal. Now the highlighting will try to compute first largest height and depth; of course, this means that if the material splits over lines and one piece is very high/deep this influences everything, anyhow in such cases, display math would be a better choice.

As to "highlighting environments" as has been asked in a comment, if this refers to display environments, some other method is necessary. Wrapping the environment in another one of the framed or mdframed type, I guess. The method here is strictly for inline math. Actually it may also serve to display the possible hyphenation points in a word (indeed the method, inspired by Tex by Topic, 5.9.6 Dissecting paragraphs with \lastbox, texdoc topic, is also used in more elaborate form in the soul package).

Edit: the global \sbox now uses \box1 rather than \HighlightBox, as I recall that local and global assignments should not be mixed although here I don't know if this would have any importance in this code in terms of save stack impact.

\documentclass{article}
\usepackage{color}

\definecolor{SkyBlue}{cmyk}{0.62,0,0.12,0}
\definecolor{BlueGreen}{cmyk}{0.85,0,0.33,0}
\definecolor{Thistle}{cmyk}{0.12,0.59,0,0}

% BOXES FOR THE DECORATION
\newbox\HighlightPiece 
\newbox\HighlightBox
\newbox\HighlightStrutBox

\makeatletter
\def\Highlight@ #1{% 
     % technique roughly inspired (but now with  a \loop) from 
     % TeX by Topic 5.9.6 Dissecting paragraphs with \lastbox
\loop % FIRST WE LOOP OVER THE CONTENT TO GET MAXIMAL HEIGHT AND DEPTH
   \setbox\HighlightPiece\lastbox
\ifvoid\HighlightPiece\else
   \unskip\unpenalty
   \setbox\HighlightStrutBox\hbox{\unhbox\HighlightStrutBox
                                  \vrule\@height\ht\HighlightPiece
                                        \@depth\dp\HighlightPiece
                                        \@width\z@ }%
   \setbox\HighlightBox\vbox{\box\HighlightPiece\unvbox\HighlightBox}%
\repeat
\unvbox\HighlightBox
\loop % WE RE-LOOP TO BUILD A HORIZONTAL LIST WITH SUITABLE DECORATION
   \setbox\HighlightPiece\lastbox
\ifvoid\HighlightPiece\else
   \unskip\unpenalty
   \setbox\HighlightBox
      \hbox{\colorbox{#1}{\color{black}%
                              \unhcopy\HighlightStrutBox
                              \unhbox\HighlightPiece}%
          \allowbreak
          \leaders\hrule \@height \ht\HighlightStrutBox  
                         \@depth  \dp\HighlightStrutBox
          % I would like to have some more clever choice here
          % than this 2pt amount of stretchability to reproduce
          % what would have happened without all our fiddling
          \hskip 0pt plus 2pt\relax % 
       \unhbox\HighlightBox}%
\repeat}

\newcommand\Highlight [2][yellow]
     {\vbox{%
     \setbox\HighlightBox\vbox{}%
     \setbox\HighlightStrutBox\hbox{\unhcopy\strutbox}%
     % TO LEAVE INTERLINE WHITE SPACE REPLACE PREVIOUS LINE BY
     % \setbox\HighlightStrutBox\hbox{}%
     \hfuzz\maxdimen % temporarily do not report overfull boxes 
     \hsize 1sp      % force the breaking in unbreakable pieces
     \parindent\z@
     \leftskip\z@skip   
     \rightskip\z@skip
     \parfillskip\@flushglue
     \fboxsep \z@    % \colorbox uses \fboxsep !!
     \color{#1}%       set color for future interboxes stretchable rules
     \leavevmode\hskip\z@skip % done for the "hyphenation variant"
     #2\endgraf      % paragraph builder
     \Highlight@{#1}% dissect the paragraph into boxes.
     \global\sbox\@ne % Color Protection with \sbox
            {\unhbox\HighlightBox}}%
     \unhbox\@ne % re-insert the colorized boxes into the current
                          % (real) paragraph. 
}%

\makeatother

% We could make this in a command like \TurnOnInlineHighlight
% and \TurnOffInlineHighlight would then restore the normal definitions.

\renewcommand\([1][yellow]{\GatherAndHighlight {#1}}
\def\GatherAndHighlight #1#2\){\Highlight[#1]{$#2$}}

\begin{document}

Here is some fundamental (inline) new equation governing everything in the
universe: $ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}$. Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \Highlight[SkyBlue]{$ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} +
  ABC_{1234} - 
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}$}. Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \(ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}\). Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \([green]ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}\). Pretty impressive, no?

Finally, while display equations look good for a page of samples,
the ability to mix math and text \(\displaystyle
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =  
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots} } } }\).
The amssymb package might be omissible for certain documents.


\Highlight{Brave souls will be tempted to apply the highlighting to pieces of
  text. As we can see here, the result is a bit curious.} On the other hand this
  is quite ok for just displaying the hyphenation points of a single word: for
example \Highlight[Thistle]{displaying}.

\end{document}

highlights


This is the earlier proposal:

\documentclass{article}
\usepackage{color}

\newbox\HighlightPiece 
\newbox\HighlightAll

\def\colorizeboxes #1{%
\setbox\HighlightPiece\lastbox
\ifvoid\HighlightPiece\else 
   \unskip\unpenalty
   \setbox\HighlightAll
          \hbox{\colorbox{#1}{\color{black}\strut\unhbox\HighlightPiece}%
                \allowbreak
                \leaders\hrule height \ht\strutbox depth \dp\strutbox
                \hskip 0pt plus 2pt
                \unhbox\HighlightAll}%
   \colorizeboxes {#1}%
\fi}

\newcommand\Highlight [2][yellow]
     {\vbox{\setbox\HighlightAll\hbox{}\parindent0pt   
     \rightskip0pt plus 1fil
     \fboxsep 0pt
     \offinterlineskip
     \hsize1pt
     \color{#1}%
     #2\endgraf\colorizeboxes{#1}%
     \global\sbox\HighlightAll{\unhbox\HighlightAll}}%
     \unhbox\HighlightAll}%

\renewcommand\([1][yellow]{\GatherAndHighlight {#1}}
\def\GatherAndHighlight #1#2\){\Highlight[#1]{$#2$}}


\begin{document}


Here is some fundamental (inline) new equation governing everything in the
universe: $ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}$. Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \Highlight{$ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} +
  ABC_{1234} - 
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}$.} Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \(ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}\). Pretty impressive, no?

Here is some fundamental (inline) new equation governing everything in the
universe: \([green]ABC_{1234} = ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} - ABC_{1234} + ABC_{1234} -
ABC_{1234} + ABC_{1234} - ABC_{1234}\). Pretty impressive, no?


\end{document}

Output:

highlighting

Related Question