Repository: sphinx-doc/sphinx

Issue:
latexpdf image :target: changes output
**Describe the bug**
When I add the :target: to the image construct in an *.rst file, the tex file changes how text following an image is represented. The tex files ignores the image alignment, and the text directly after the image is no longer on a new line.

To be more specific here is the tex output between the two. The noindent is missing, as well as a blank new line when you include the :target: tag in the *.rst file.

*.tex without the :target:
```
\section{Example}
\label{\detokenize{docs/readme:test}}\label{\detokenize{docs/readme:test1}}\label{\detokenize{docs/readme::doc}}
\noindent{\hspace*{\fill}\sphinxincludegraphics[width=184\sphinxpxdimen]{{logo}.png}\hspace*{\fill}}

\sphinxhref{https://www.example.com}{Example} Test
```

*.tex with :target:
```
\section{Example}
\label{\detokenize{docs/readme:test}}\label{\detokenize{docs/readme:test1}}\label{\detokenize{docs/readme::doc}}\sphinxhref{https://www.example.com}{\sphinxincludegraphics[width=184\sphinxpxdimen]{{logo}.png}}
\sphinxhref{https://www.example.com}{Example} Test
```


**To Reproduce**
Steps to reproduce the behavior:
*.rst file with target
```
.. image:: logo.png
    :target: https://www.example.com
    :alt: Logo
    :align: center
    :width: 184px

`example <https://example.com>`_ test
```

*.rst file with target
```
.. image:: logo.png
    :alt: Logo
    :align: center
    :width: 184px

`example <https://example.com>`_ test
```

**Expected behavior**
The image should be a link to the URI provided and the text should be on a new line.

**Screenshots**
With :target:
![screen shot 2019-02-12 at 12 49 17 pm](https://user-images.githubusercontent.com/3730852/52663809-ac423a80-2ec4-11e9-8ade-e7f861882aaf.png)

Without :target:
![screen shot 2019-02-12 at 12 50 08 pm](https://user-images.githubusercontent.com/3730852/52663837-c419be80-2ec4-11e9-9784-5b046e022a0d.png)


**Environment info**
- OS: Ubuntu 16.04
- Python version: 2.7.15rc1
- Sphinx version: sphinx-build 1.8.4
- Sphinx extensions: n/a
- Extra tools: texi2pdf (GNU Texinfo 6.5) 7842, Latexmk, John Collins, 1 January 2015. Version 4.41

Discussion:

Patch:
diff --git a/CHANGES b/CHANGES
index 65f39e538..82ad1cdee 100644
--- a/CHANGES
+++ b/CHANGES
@@ -19,6 +19,8 @@ Bugs fixed
 * LaTeX: Remove extraneous space after author names on PDF title page (refs: #6004)
 * #6026: LaTeX: A cross reference to definition list does not work
 * #6046: LaTeX: ``TypeError`` is raised when invalid latex_elements given
+* #6067: LaTeX: images having a target are concatenated to next line
+* #6067: LaTeX: images having a target are not aligned even if specified
 * #6019: imgconverter: Including multipage PDF fails
 * #6047: autodoc: ``autofunction`` emits a warning for method objects
 
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 7cef81ff4..0eafc0af9 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1655,7 +1655,11 @@ def visit_image(self, node):
                     # in reverse order
         post = []   # type: List[unicode]
         include_graphics_options = []
-        is_inline = self.is_inline(node)
+        has_hyperlink = isinstance(node.parent, nodes.reference)
+        if has_hyperlink:
+            is_inline = self.is_inline(node.parent)
+        else:
+            is_inline = self.is_inline(node)
         if 'width' in attrs:
             if 'scale' in attrs:
                 w = self.latex_image_length(attrs['width'], attrs['scale'])
@@ -1697,7 +1701,7 @@ def visit_image(self, node):
         if self.in_parsed_literal:
             pre.append('{\\sphinxunactivateextrasandspace ')
             post.append('}')
-        if not is_inline:
+        if not is_inline and not has_hyperlink:
             pre.append('\n\\noindent')
             post.append('\n')
         pre.reverse()
@@ -1987,6 +1991,8 @@ def visit_reference(self, node):
             for id in node.get('ids'):
                 anchor = not self.in_caption
                 self.body += self.hypertarget(id, anchor=anchor)
+        if not self.is_inline(node):
+            self.body.append('\n')
         uri = node.get('refuri', '')
         if not uri and node.get('refid'):
             uri = '%' + self.curfilestack[-1] + '#' + node['refid']
@@ -2039,6 +2045,8 @@ def visit_reference(self, node):
     def depart_reference(self, node):
         # type: (nodes.Node) -> None
         self.body.append(self.context.pop())
+        if not self.is_inline(node):
+            self.body.append('\n')
 
     def visit_number_reference(self, node):
         # type: (nodes.Node) -> None


Test patch:
diff --git a/tests/roots/test-images/index.rst b/tests/roots/test-images/index.rst
index d1478fab1..67b742b27 100644
--- a/tests/roots/test-images/index.rst
+++ b/tests/roots/test-images/index.rst
@@ -15,6 +15,13 @@ test-image
 
 .. image:: testimäge.png
 
+.. image:: rimg.png
+   :target: https://www.sphinx-doc.org/
+
+.. image:: rimg.png
+   :align: center
+   :target: https://www.python.org/
+
 .. a remote image
 .. image:: https://www.python.org/static/img/python-logo.png
 
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index b81d2a3fe..03558cd92 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -1184,16 +1184,28 @@ def test_latex_raw_directive(app, status, warning):
 
 
 @pytest.mark.sphinx('latex', testroot='images')
-def test_latex_remote_images(app, status, warning):
+def test_latex_images(app, status, warning):
     app.builder.build_all()
 
     result = (app.outdir / 'Python.tex').text(encoding='utf8')
+
+    # images are copied
     assert '\\sphinxincludegraphics{{python-logo}.png}' in result
     assert (app.outdir / 'python-logo.png').exists()
+
+    # not found images
     assert '\\sphinxincludegraphics{{NOT_EXIST}.PNG}' not in result
     assert ('WARNING: Could not fetch remote image: '
             'http://example.com/NOT_EXIST.PNG [404]' in warning.getvalue())
 
+    # an image having target
+    assert ('\\sphinxhref{https://www.sphinx-doc.org/}'
+            '{\\sphinxincludegraphics{{rimg}.png}}\n\n' in result)
+
+    # a centerized image having target
+    assert ('\\sphinxhref{https://www.python.org/}{{\\hspace*{\\fill}'
+            '\\sphinxincludegraphics{{rimg}.png}\\hspace*{\\fill}}}\n\n' in result)
+
 
 @pytest.mark.sphinx('latex', testroot='latex-index')
 def test_latex_index(app, status, warning):