Repository: sympy/sympy

Issue:
Latex output fails for superscript variables raised to a power
using superscripts for coordinates like $$x^i$$ causes the latex to fail to print math (in jupyter notebooks) when the coordinate is raised to a power - it prints x^{1}^{2} for the case $$x^1$$ squared, I think it should use round brackets $$(x^{1})^2$$ instead. 

Discussion:

Patch:
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 15e4f2bad3..517246efdb 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -460,6 +460,9 @@ def _print_Pow(self, expr):
             and expr.exp.is_Rational \
                 and expr.exp.q != 1:
             base, p, q = self.parenthesize(expr.base, PRECEDENCE['Pow']), expr.exp.p, expr.exp.q
+            #fixes issue #12886, adds parentheses before superscripts raised to powers
+            if '^' in base and expr.base.is_Symbol:
+                base = r"\left(%s\right)" % base
             if expr.base.is_Function:
                 return self._print(expr.base, "%s/%s" % (p, q))
             return r"%s^{%s/%s}" % (base, p, q)
@@ -481,9 +484,13 @@ def _print_Pow(self, expr):
                     if tex[:1] == "-":
                         return tex[1:].strip()
                 tex = r"%s^{%s}"
+                #fixes issue #12886, adds parentheses before superscripts raised to powers
+                base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
+                if '^' in base and expr.base.is_Symbol:
+                    base = r"\left(%s\right)" % base
+                exp = self._print(expr.exp)
 
-                return tex % (self.parenthesize(expr.base, PRECEDENCE['Pow']),
-                              self._print(expr.exp))
+                return tex % (base, exp)
 
     def _print_UnevaluatedExpr(self, expr):
         return self._print(expr.args[0])


Test patch:
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 8a236e5bdb..662c0a8160 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1587,6 +1587,12 @@ def test_issue_10489():
     assert latex(s) == latexSymbolWithBrace
     assert latex(cos(s)) == r'\cos{\left (C_{x_{0}} \right )}'
 
+
+def test_issue_12886():
+    m__1, l__1 = symbols('m__1, l__1')
+    assert latex(m__1**2 + l__1**2) == r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}'
+
+
 def test_latex_UnevaluatedExpr():
     x = symbols("x")
     he = UnevaluatedExpr(1/x)