7

I often have to write things like

$left(a \left(b \left( c ... \right) \right) \right)$

And in the final output, its quite hard to distinguish which brackets go together.

Now, in some editors, there are features that brackets that match are same-colored, like "red( blue( green( green) blue) red)".

Is that possible, somehow, to be done by LaTeX automatically? Matching left- and right-brackets shouldn't be a thing with the \left-\right-markers, and doing something like building up a color-list that's just "tracked" somehow is easy in other programming languages as well, e.g. in perl with push and pop from an @array.

But I'm not a very good LaTeX-programmer. So, does this feature exist already? Or is it anyhow easy to be implemented?

Thanks!

2
  • 2
    NAA but the usually followed order is ...{[({[(...)]})]}... That's usually one way to tell what goes with what
    – Au101
    Commented Dec 1, 2016 at 19:50
  • 2
    Welcome to TeX.SE. Are you habitually prefixing \left and \right to math "fences" -- round parentheses, square brackets, and curly braces? If so, do read the following postings: Is it ever bad to use \left and \right and “(” or “\left(” parentheses.
    – Mico
    Commented Dec 1, 2016 at 20:12

1 Answer 1

11

How about this:

\documentclass{article}
\usepackage{xcolor}
\makeatletter
\newcount\bracketnum
\newcommand\makecolorlist[1]{%
    \bracketnum0\relax
    \makecolorlist@#1,.%
    \bracketnum0\relax
}
\def\makecolorlist@#1,{%
    \advance\bracketnum1\relax
    \expandafter\def\csname bracketcolor\the\bracketnum\endcsname{\color{#1}}%
    \@ifnextchar.{\@gobble}{\makecolorlist@}%
}
\let\oldleft\left
\let\oldright\right
\def\left#1{%
    \global\advance\bracketnum1\relax 
    \colorlet{temp}{.}%
    \csname bracketcolor\the\bracketnum\endcsname
    \oldleft#1%
    \color{temp}%
}
\def\right#1{%
    \colorlet{temp}{.}%
    \csname bracketcolor\the\bracketnum\endcsname
    \oldright#1%
    \global\advance\bracketnum-1\relax
    \color{temp}%
}
\makeatother


\makecolorlist{red,blue,green}


\begin{document}
\[\left( 1 +\left(2+\left(3+4\left(\right)\right)a\right)\right)\]

\[\color{orange}\left( 1 +\left(2+\left(3+4\left(\right)\right)a\right)\right)\]
\end{document} 

You can set the colors you want by saying \makecolorlist{color1,color2,...,colorn}. If you use more than n nested braces, after that point it stop applying (just use the background color). The output is:

enter image description here

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .