How can I show pictures of keyboard keys in-line with text with Sphinx?

It is possible to display inline images using the reStructuredText substitution mechamism.

You can define an inline image substitution like this:

.. |text to substitute| image:: path/to/the/image.ext

Then you can use the substitution wherever you like in your document like this:

random text ... |text to substitute| ... more random text ...

In rendered document, the |text to substitute| will be replaced (inline) by the image pointed by path/to/the/image.ext.


In example, the following document...

.. |key inline image| image:: https://cdn1.iconfinder.com/data/icons/hawcons/32/699610-icon-10-file-key-128.png

This is a |key inline image| inline image, isn't it cool?

...gives the following result:

inline image with Sphinx

Even better, you can use the image directive options to tweak the image display:

.. |key inline image| image:: https://cdn1.iconfinder.com/data/icons/hawcons/32/699610-icon-10-file-key-128.png
                      :height: 15px
                      :width: 50px

The above substitution gives a reduced version of the original image:

enter image description here


Consider first using semantic markup to improve accessibility. Sphinx can render the roles :kbd:, :menuselection:, or :guilabel: to HTML or PDF. For HTML output, then you can apply CSS to make the key strokes appear exactly as you would like, even give them the appearance of images without actually making them images. For PDF output, you would use the style \sphinxkeyboard.

You could also use Unicode keyboard characters, but you should ensure the font you use in rendering supports the character.

Examples:

  • return: ⏎
  • Apple command: ⌘
  • option: ⌥

AFAIK, neither Sphinx nor any of its contributions provides any capability to render text to images, except for aafigure which creates images from ASCII art but is not what you want.