How can I make a non-breaking space in reStructuredText?

蹲街弑〆低调 提交于 2019-11-30 00:57:58

问题


How can I make a non-breaking space in reStructuredText?

An obvious but problematic solution is:

`word A`

But it might be treated differently by different implementations, such as rst2latex or rst2pdf. Plus it is rendered in italics.


回答1:


I don't see the problem here, running docutils v0.9. At least rst2latex and rst2html are behaving properly regarding non-breaking whitespace. Latex generates ~ and html generates   when you input a non-breaking character (\xa0, \0240).

Maybe you have an editor issue ? If you can manage to input the character, docutils will do the job.




回答2:


You need the unicode directive, but it can only be used in substitutions. So you need to define a substitution like this:

.. |nbsp| unicode:: 0xA0 
   :trim:

and then use it like this:

xx |nbsp| xx

:trim: is there to get rid of those spaces around the substitution.




回答3:


You can also use |_| in place of |nbsp| which is less visually intrusive, given reStructuredText's goal of being readable as plain text.




回答4:


I ended up coming up with a workaround for Sphinx. I overwrite the HTML and LaTeX writers to convert the ~ character to a non-breaking space. Here's the HTML one:

import sphinx.writers.html
BaseTranslator = sphinx.writers.html.SmartyPantsHTMLTranslator

class CustomHTMLTranslator(BaseTranslator):

    def bulk_text_processor(self, text):
        if '~' in text:
            text = text.replace('~', ' ')
        return text

sphinx.writers.html.SmartyPantsHTMLTranslator = CustomHTMLTranslator

and the LaTeX one:

import sphinx.writers.latex
BaseTranslator = sphinx.writers.latex.LaTeXTranslator

class DocTranslator(BaseTranslator):

    def visit_Text(self, node):
        if self.verbatim is not None:
            self.verbatim += node.astext()
        else:
            text = self.encode(node.astext())
            if '\\textasciitilde{}' in text:
                text = text.replace('\\textasciitilde{}', '~')
            if not self.no_contractions:
                text = educate_quotes_latex(text)
            self.body.append(text)

sphinx.writers.latex.LaTeXTranslator = DocTranslator

It's not so pretty, and it doesn't even let you escape the ~ character, but it works for my purposes.




回答5:


I have not tested it but maybe you can use http://docutils.sourceforge.net/docs/ref/rst/directives.html#unicode-character-codes and the unicode "no break space" character: http://www.fileformat.info/info/unicode/char/a0/index.htm



来源:https://stackoverflow.com/questions/11830242/how-can-i-make-a-non-breaking-space-in-restructuredtext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!