Repository: sphinx-doc/sphinx

Issue:
latex: curly braces in index entries are not handled correctly
### Problem
An index entry containing braces, e.g.,
```
.. index:: index{with}braces
```
is converted to ill-formed latex
```
\index{index\sphinxleftcurlybracewith\sphinxrightcurlybracebraces}
```

#### Procedure to reproduce the problem
- Create a new project with `sphinx-quickstart`
- Add an index entry `.. index:: index{with}braces`
-  run `make latexpdf`

#### Error logs / results
```
...
! Undefined control sequence.
l.5   \item index\sphinxleftcurlybracewith
                                          \sphinxrightcurlybracebraces, \hyp...
...
```
#### Expected results
Expected the latex builder to properly escape curly braces, e.g.,
```
\index{index{\sphinxleftcurlybrace}with{\sphinxrightcurlybrace}braces}
```
### Environment info
- OS: Ubuntu 16.04
- Python version: 2.7.12
- Sphinx version: 1.7.5


Discussion:

Patch:
diff --git a/CHANGES b/CHANGES
index 2d896a3e8..f3ebc0f42 100644
--- a/CHANGES
+++ b/CHANGES
@@ -30,6 +30,7 @@ Bugs fixed
 * #5032: autodoc: loses the first staticmethod parameter for old styled classes
 * #5036: quickstart: Typing Ctrl-U clears the whole of line
 * #5066: html: "relations" sidebar is not shown by default
+* #5091: latex: curly braces in index entries are not handled correctly
 
 Testing
 --------
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 941181d0a..e37e6f395 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1953,8 +1953,8 @@ def visit_index(self, node, scre=re.compile(r';\s*')):
         # type: (nodes.Node, Pattern) -> None
         def escape(value):
             value = self.encode(value)
-            value = value.replace(r'\{', r'\sphinxleftcurlybrace')
-            value = value.replace(r'\}', r'\sphinxrightcurlybrace')
+            value = value.replace(r'\{', r'{\sphinxleftcurlybrace}')
+            value = value.replace(r'\}', r'{\sphinxrightcurlybrace}')
             return value
 
         if not node.get('inline', True):


Test patch:
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 68704d9a3..9327d0f1d 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -1209,7 +1209,7 @@ def test_latex_index(app, status, warning):
     result = (app.outdir / 'Python.tex').text(encoding='utf8')
     assert 'A \\index{famous}famous \\index{equation}equation:\n' in result
     assert '\n\\index{Einstein}\\index{relativity}\\ignorespaces \nand' in result
-    assert '\n\\index{main \\sphinxleftcurlybrace}\\ignorespaces ' in result
+    assert '\n\\index{main {\\sphinxleftcurlybrace}}\\ignorespaces ' in result
 
 
 @pytest.mark.sphinx('latex', testroot='latex-equations')