miyakogi / m2r

Markdown to reStructuredText converter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Image Directive :target: Broken

jandiorio opened this issue · comments

Problem

The image() function generates the RST directive which includes the :target: attribute. Since Sphinx copies all images to /_images, any images in subfolders will have a broken link using :target: which which include the subdirectory path. Since the :target: attribute still references the relative path based on the source directory and not the /_images directory, clicking the links generates a 404.

Example Output of Broken href

You can see the difference in paths. the href path will not exists. In source, these images are in a subdirectory.

<a class="reference external image-reference" href="../_images/curl_jokes_json.gif"><img alt="cURL with JSON" src="../../_images/curl_jokes_json.gif" /></a>

Possible Fix

Since it seems that Sphinx always copies all images to the /_images folder, modifying the method like this could work:

def image(self, src, title, text):
        """Rendering a image with title and text.

        :param src: source link of the image.
        :param title: title text of the image.
        :param text: alt text of the image.
        """

        image_name = os.path.basename(src)
        target = f"/_images/{image_name}"

        # rst does not support title option
        # and I couldn't find title attribute in HTML standard
        return '\n'.join([
            '',
            '.. image:: {}'.format(src),
            '   :target: {}'.format(target),
            '   :alt: {}'.format(text),
            '',
        ])

Essentially, parsing the filename from the original source and generating target based on where we know sphinx is going to put the images.

Had a similar problem. I'm cloning a gitlab wiki (which is in markdown) into my sphinx project via .gitlab_ci.yml
Wanted to have Lightbox feature from: sphinxcontrib-images.

Didn't work as it only parses .rst images. So I found m2r. Still didn't work - because of target.
Removed it - fine.

I actually don't wanna have target at all - becaus click opens the lightbox. Maybe make it configurable?

But currently I'm converting via shell - so conf.py option wouldn't help. Have markdown extension installed (currently) - and you can install markdown and m2r (which does make some sense ...).