Search code examples
python-sphinxemojigithub-flavored-markdown

Sphinx extension to use GitHub markdown emoji in Sphinx?


Problem

I have been using (Python) Sphinx doc, along with CommonMark parser, to write Sphinx documentation containing files written in both reStructuredText and Markdown. So far so good, it works really fine (see this line in an example of Sphinx conf.py file).

However, CommonMark's support for GitHub flavored Markdown (GFM) is not perfect, and one important feature it lacks are emoji. I searched for other Markdown parser, more specific to GFM, for instance py-gfm, but none of them seem to support emoji.

For instance, the screenshot below shows the Sphinx output on the left, and the GitHub rendered version on the right: an example

So my question is:

  • Does anyone know a Sphinx extension that could add support to GFM-like emoji, in rST and/or Markdown? (ie, emoji written like :boom: this).
  • Or a trick I could use to convert any emoji, eg, :boom:, to a small image? (as that's what GitHub is doing anyway, see for instance the :boom: image) The trick should probably be on the HTML pages created by Sphinx, not on the source Markdown files (I want them to still be readable with GitHub file viewer).

Thanks in advance. Regards.


2 partial solutions

  • A partial solution is this small Python script I wrote, using carpedm20's emoji package. It will convert any :emoji: alias (written :like_this:) to it's UTF-8 version, if possible.

  • I also tried to use pymdownx.emoji package, to write this second script. It will convert any :emoji: alias to a piece of HTML code loading a distant PNG (or SVG) version (from JsDelivr's CDN). Still not perfect, the size/scaling is not good, and even emojis in ... are replaced. (I will improve this).

Both can be used with this tiny Bash for loop:

BUILDDIR=_build/html  # Adapt to the location of your Sphinx output
for i in "$BUILDDIR"/*.html; do
    emojize.py "$i" > "$i".new
    # or emojize_pngorsvg.py "$i" > "$i".new
    wdiff -3 "$i" "$i".new;
    mv -vf "$i".new "$i"
done

Demo:

  • With UTF-8 codes for emojis: an example 2
  • With PNG images for emojis (still not perfect): an example 3

Solution

  • Did not find anything out there, so ended up creating an extension.

    Install it with:

    pip install sphinxemoji
    

    Then, in your Sphinx's conf.py:

    extensions = [
        '...',
        'sphinxemoji.sphinxemoji',
    ]
    

    Then you can start using emoji codes in your documentation (note you need to use bars around the emoji code though):

    This text includes a smily face |:smile:| and a snake too! |:snake:|
    
    Don't you love it? |:heart_eyes:|
    

    If you want consistent emoji style, you can add this to your conf.py:

    sphinxemoji_style = 'twemoji'