Search code examples
python-sphinxrestructuredtext

Should arguments to a custom directive be escaped?


I have created a custom directive for a documentation project of mine which is built using Sphinx and reStructuredText. The directive is used like this:

.. xpath-try:: //xpath[@expression="here"]

This will render the XPath expression as a simple code block, but with the addition of a link that the user can click to execute the expression against a sample XML document and view the matches (example link, example rendered page).

My directive specifies that it does not have content, takes one mandatory argument (the xpath expression) and recognises a couple of options:

class XPathTryDirective(Directive):
    has_content = False
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {
        'filename': directives.unchanged,
        'ns_args': directives.unchanged,
    }

    def run(self):
        xpath_expr = self.arguments[0]
        node = xpath_try(xpath_expr, xpath_expr)
        ...
        return [node]

Everything seems to be working exactly as intended except that if the XPath expression contains a * then the syntax highlighting in my editor (gVim) gets really messed up. If I escape the * with a backslash, then that makes my editor happy, but the backslash comes through in the output.

My questions are:

  1. Are special characters in an argument to a directive supposed to be escaped?
  2. If so, does the directive API provide a way to get the unescaped version?
  3. Or is it working fine and the only problem is my editor is failing to highlight things correctly?

It may seem like a minor concern but as I'm a novice at rst, I find the highlighting to be very helpful.


Solution

  • Are special characters in an argument to a directive supposed to be escaped?

    No, I think that there is no additional processing performed on arguments of rst directives. Which matches your observation: whatever you specify as an argument of the directive, you are able to get directly via self.arguments[0].

    Or is it working fine and the only problem is my editor is failing to highlight things correctly?

    Yes, this seems to be the case. Character * is used for emphasis/italics in rst and it gets more attention during syntax highlighting for some reason.

    This means that the solution here would be to tweak or fix vim syntax file for restructuredtext.