Sphinx: Why doesn't Sphinx translate :kbd: roles to HTML's <kbd> tags?

Created on 18 Nov 2016  路  8Comments  路  Source: sphinx-doc/sphinx

I want to mark keyboard keys and inputs as key "icons". Sphinx provides a :kbd: role to markup single characters or words, but the resulting HTML contains <code class="kbd ......"> tags.

So why doesn't Sphinx translate :kbd: roles to HTML's \ tags?
Or is this a Read-The-Docs issue? - I'm using their theme

My question on StackOverflow: http://stackoverflow.com/questions/40686837/why-doesnt-sphinx-translate-kbd-roles-to-htmls-kbd-tags


I found that some CSS can transform <kbd>-tags into nice looking keys.

kbd
{
  -moz-border-radius:3px;
  -moz-box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
  -webkit-border-radius:3px;
  -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
  background-color:#f7f7f7;
  border:1px solid #ccc;
  border-radius:3px;
  box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
  color:#333;
  display:inline-block;
  font-family:Arial,Helvetica,sans-serif;
  font-size:11px;
  line-height:1.4;
  margin:0 .1em;
  padding:.1em .6em;
  text-shadow:0 1px 0 #fff;
}

Source: http://meta.superuser.com/questions/4788/css-for-the-new-kbd-style

good first issue help wanted html markup proposal

Most helpful comment

If the way I have done it seems reasonable, I will try to do a pull request. :smiley:

All 8 comments

Maybe no reason. Now sphinx represents a :kbd: role as a literal. And HTML writers simply convert it to <span> element.

+1 for <kdb> tag.

Does the HTML writer belong to Sphinx or are we in another scope like docutils?

HTML writer belongs to both docutils and Sphinx.
docutils provides basic feature of HTML writer. and Sphinx customize it.

Anyway, this behavior came from :kbd: role. It is provided by Sphinx.
So this is a issue of Sphinx.

I added this to my conf.py as a workaround:


# -- Hackery --

from sphinx.writers.html import HTMLTranslator

real_visit_literal = HTMLTranslator.visit_literal
real_depart_literal = HTMLTranslator.depart_literal

def new_visit_literal(self, node):
    if 'kbd' in node['classes']:
        self.body.append(self.starttag(node, 'kbd', '',
                                       CLASS='docutils literal'))
    else:
        real_visit_literal(self, node)

def new_depart_literal(self, node):
    if 'kbd' in node['classes']:
        self.body.append('</kbd>')
    else:
        real_depart_literal(self, node)

HTMLTranslator.visit_literal = new_visit_literal
HTMLTranslator.depart_literal = new_depart_literal

@dlech We always welcome your PRs :-)
AFAIK, there are no people objecting for this. Simply nobody can work for this now.
If you'd like to merge it into sphinx-core, please send us the patch (including tests!).

If the way I have done it seems reasonable, I will try to do a pull request. :smiley:

+1

Was this page helpful?
0 / 5 - 0 ratings