# Automatically highlighting or coloring specific terms

I am using Mathematica to perform Newton quasi-linearization of the non-linear terms during discretization of PDEs for numerical solution. These expressions can involve tens of terms (depending on the PDE system), which I then have to carefully translate into code. It will help me if in a large expression I can automatically highlight or color terms containing a certain variable. For example, if my expression is stored in 'SEupwind', and I am collecting terms as below

Collect[SEupwind, {Subscript[\[Phi], k], Subscript[\[Phi], k - 1],
Subscript[\[Phi], k + 1], Subscript[m, k], Subscript[m, k - 1],
Subscript[m, k - 2], Subscript[m, k + 1], Subscript[m, k + 2]}]


is there a way to automatically highlight or color the terms containing my collected variables?

Here is a simple example case. Say I have two functions defined like

A1[x_] := A11 x + A12 /x
A2[x_] := A21 x + A22 /x


I then define an expression

TestExpr = A1[Subscript[x, k]] A2[Superscript[x, g]] +
A1[Superscript[x, g]] A2[Subscript[x, k]]


Then I want to collect coefficients of the variable 'x_k'

Collect[TestExpr, {Subscript[x, k]}]


This produces the output

Subscript[x,k] (A21 (A12/Superscript[x,g] + A11 Superscript[x,g]) +
A11 (A22/Superscript[x,g] + A21 Superscript[x,g])) + (
A22 (A12/Superscript[x,g] + A11 Superscript[x,g]) +
A12 (A22/Superscript[x,g] + A21 Superscript[x,g]))/Subscript[x, k]


I would like to highlight or color the coefficients of 'x_k' that I collected (the first term) and display in traditional form. For complex expressions, this will be quite useful while translating to code in another language.

• – Kuba Jan 28 '16 at 21:24

In addition to the nice answer of Edmund, if you do not mind to highlight also the factor (such as Subscript[x,k] you might use a bit shorter approach. Let us first introduce two functions, any of them may be used for your purposes:

    colored[x_, term_] := If[MemberQ[x, term], Style[x, Red], x];

highlighted[x_, term_] :=If[MemberQ[x, term],Style[x, 14, Red, Bold, Background -> LightYellow], x];


and now let us apply it to your expression (provided it has already been evaluated):

    Map[colored[#, Subscript[x, k]] &, p]
Map[highlighted[#, Subscript[x, k]] &, p]


You can use Coefficient.

p = Collect[TestExpr, {Subscript[x, k]}];
p /. {\[FormalT] : Coefficient[p, Subscript[x, k]] :> Style[\[FormalT], Blue]} // TraditionalForm


Hope this helps.

• Thank you. It worked great. I am accepting Alexei's answer since it is easier to use. – GreenEye Jan 29 '16 at 23:52