# Automatically set different colors for matching brackets?

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!

• NAA but the usually followed order is ...{[({[(...)]})]}... That's usually one way to tell what goes with what – Au101 Dec 1 '16 at 19:50
• 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 Dec 1 '16 at 20:12

\documentclass{article}
\usepackage{xcolor}
\makeatletter
\newcount\bracketnum
\newcommand\makecolorlist[1]{%
\bracketnum0\relax
\makecolorlist@#1,.%
\bracketnum0\relax
}
\def\makecolorlist@#1,{%
\expandafter\def\csname bracketcolor\the\bracketnum\endcsname{\color{#1}}%
\@ifnextchar.{\@gobble}{\makecolorlist@}%
}
\let\oldleft\left
\let\oldright\right
\def\left#1{%
\colorlet{temp}{.}%
\csname bracketcolor\the\bracketnum\endcsname
\oldleft#1%
\color{temp}%
}
\def\right#1{%
\colorlet{temp}{.}%
\csname bracketcolor\the\bracketnum\endcsname
\oldright#1%
\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: