3

I defined a new command for highlighting some text parts:

\newcommand{\keyword}[1]{\colorbox{black!5}{#1}}

Unfortunately, when the text becomes to long it overlaps my margins. The keyword ignores the margin of the table, as well as the margin of the hole document.

\keyword{exp: c=wordExp \{ if(\$c.matches(``a string'')\{ 
\textbackslash\textbackslash do something \}) \}}

enter image description here

Can I tell my command to make a newline or force it to break after X centimeters?

Thx.

  • 1
    you could put the argument into a parbox or a minipage. – barbara beeton Mar 21 '16 at 17:47
2

You can use @barbarabeeton's advice. I don't recommend the name \keyword, however, because it is defined elsewhere in some classes. So, the newcommand can look like this:

\newcommand{\KEY}[1]{\colorbox{black!5}{\parbox{\dimexpr\linewidth-2\fboxsep}{#1}}}

Observe this -2\fboxsep, which serves to align the colorbox with the text above and below. Here is a full example:

\documentclass{article}
\usepackage{xcolor}
\begin{document}

\newcommand{\KEY}[1]{\colorbox{black!5}{\parbox{\dimexpr\linewidth-2\fboxsep}{#1}}}

\begin{tabular}{|p{.4\linewidth}|p{.5\linewidth}|}
\hline
Something here to fill half & 
Something here to fill half the line width
\KEY{exp: c=wordExp \{ if(\$c.matches(``a string'')\{ 
\textbackslash\textbackslash do something \}) \}}
\\ \hline
\end{tabular}

\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.