Python源码示例:docutils.core.publish_string()

示例1
def as_html(self, css=None):
            """
            Converts the generated reStructuredText as html5

            :css: A string containing a cascading style sheet. If None, the default css is used
            :return: The html document as string
            """
            if publish_string is None:
                raise NotImplementedError('The docutils package needs to be installed')
            args = {'input_encoding': 'unicode',
                    'output_encoding': 'unicode'}
            res = publish_string(source=str(self),
                                 writer_name='html5',
                                 settings_overrides=args)
            style_idx = res.index('</style>')
            css = css or self.css
            # Include css
            res = res[:style_idx] + css + res[style_idx:]
            return res 
示例2
def generate_htd_docs():
    from docutils.core import publish_string
    with open('README.rst') as f:
        html = publish_string(f.read(),writer_name='html')
    with open('index.html', 'w') as f:
        f.write(html)
    zippath = 'docstemp.zip'
    z = zipfile.ZipFile(zippath, 'w')
    z.write('index.html')
    z.close()
    _unlink('index.html')

    metadata = {
        'name': 'Host the Docs',
        'version': 'latest',
        'description': 'Makes documentation hosting easy.'}
    host = 'tech-artists.org:5003'

    try:
        resp = post(host, metadata, zippath)
    finally:
        _unlink(zippath)

    if resp.status_code != 200:
        raise RuntimeError(repr(resp)) 
示例3
def rst2ansi(input_string, output_encoding='utf-8'):

  overrides = {}
  overrides['input_encoding'] = 'unicode'

  def style_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    return [nodes.TextElement(rawtext, text, classes=[name])], []

  for color in COLORS:
    roles.register_local_role('ansi-fg-' + color, style_role)
    roles.register_local_role('ansi-bg-' + color, style_role)
  for style in STYLES:
    roles.register_local_role('ansi-' + style, style_role)

  out = core.publish_string(input_string.decode('utf-8'), settings_overrides=overrides, writer=Writer(unicode=output_encoding.startswith('utf')))
  return out.decode(output_encoding) 
示例4
def rst2html(rst):
    """
    convert reStructuredText to HTML with ``docutils``

    Args:
        rst (str):
             reStructuredText

    Returns:
        str: HTML
    """
    try:
        from docutils.core import publish_string
    except ImportError:
        notinstalled("docutils", "ReStructuredText", "HTML")
        sys.exit(4)
    return publish_string(rst, writer_name="html5") 
示例5
def convert_rst_to_basic_text(contents):
    """Convert restructured text to basic text output.

    This function removes most of the decorations added
    in restructured text.

    This function is used to generate documentation we
    can show to users in a cross platform manner.

    Basic indentation and list formatting are kept,
    but many RST features are removed (such as
    section underlines).

    """
    # The report_level override is so that we don't print anything
    # to stdout/stderr on rendering issues.
    converted = publish_string(
        contents, writer=BasicTextWriter(),
        settings_overrides={'report_level': 5})
    return converted.decode('utf-8') 
示例6
def test_full_build(self):
        source = dedent("""
            .. smtimage:: foo
               :digest: 0123456789abcdef
               :align: center
            """)
        config = dedent("""
            [general]
            sumatra_record_store: /path/to/db
            sumatra_project: MyProject
            sumatra_link_icon: icon_info.png
            """)
        with open("docutils.conf", "w") as fp:
            fp.write(config)
        output = publish_string(source, writer_name='pseudoxml',
                                settings_overrides={'output_encoding': 'unicode'})
        self.assertEqual("\n" + output,
                         dedent("""
                            <document source="<string>">
                                <image align="center" alt="Data file generated by computation foo" digest="0123456789abcdef" uri="smt_images/bar.jpg">
                            """)) 
示例7
def test_full_build_http_store(self):
        source = dedent("""
            .. smtimage:: foo
               :digest: 0123456789abcdef
               :align: center
            """)
        config = dedent("""
            [general]
            sumatra_record_store: http://smt.example.com/
            sumatra_project: MyProject
            sumatra_link_icon: icon_info.png
            """)
        with open("docutils.conf", "w") as fp:
            fp.write(config)
        output = publish_string(source, writer_name='pseudoxml',
                                settings_overrides={'output_encoding': 'unicode'})
        self.assertEqual("\n" + output,
                         dedent("""
                            <document source="<string>">
                                <reference refuri="http://smt.example.com/MyProject/foo/">
                                    <image align="center" alt="Data file generated by computation foo" digest="0123456789abcdef" uri="smt_images/bar.jpg">
                            """)) 
示例8
def rst2html(source):
    from docutils.core import publish_string
    return publish_string(
        source, reader_name='standalone', parser_name='restructuredtext',
        writer_name='html', settings_overrides={'halt_level': 2}  # 2=WARN
    )[0] 
示例9
def _convert_doc_content(self, contents):
        man_contents = publish_string(contents, writer=manpage.Writer())
        if not self._exists_on_path('groff'):
            raise ExecutableNotFoundError('groff')
        cmdline = ['groff', '-m', 'man', '-T', 'ascii']
        LOG.debug("Running command: %s", cmdline)
        p3 = self._popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        groff_output = p3.communicate(input=man_contents)[0]
        return groff_output 
示例10
def _convert_doc_content(self, contents):
        text_output = publish_string(contents,
                                     writer=TextWriter())
        return text_output 
示例11
def convert(source):
    """Given reStructuredText input, return formatted plain text output."""
    return core.publish_string(
        source=source,
        writer=TextWriter(),
    ) 
示例12
def rst2html(rst):
    if rst is not None:
        return core.publish_string(rst, writer_name="html").decode("utf-8")
    return "" 
示例13
def rst2html(rst):
    if rst is not None:
        return core.publish_string(rst, writer_name="html").decode("utf-8")
    return "" 
示例14
def make_message(rc, to, subject="", body="", attachments=()):
    """Creates an email following the approriate format. The body kwarg
    may be a string of restructured text.  Attachements is a list of filenames
    to attach.
    """
    msg = MIMEMultipart("alternative")
    plain = MIMEText(body, "plain")
    msg.attach(plain)
    if publish_string is not None:
        html = publish_string(
            body,
            writer_name="html",
            settings_overrides={"output_encoding": "unicode"},
        )
        html = MIMEText(html, "html")
        msg.attach(html)
    if attachments:
        text = msg
        msg = MIMEMultipart("mixed")
        msg.attach(text)
        for attachment in attachments:
            _, ext = os.path.splitext(attachment)
            att = ATTACHERS[ext](attachment)
            att.add_header(
                "content-disposition",
                "attachment",
                filename=os.path.basename(attachment),
            )
            msg.attach(att)
    msg["Subject"] = subject
    msg["From"] = rc.email["from"]
    msg["To"] = to
    return (to, msg.as_string()) 
示例15
def get_long_description(self):
    """Override method to provide long description as text."""
    # Return formatted description as plain text
    if self.get_formatted_description():
      return publish_string(self.get_formatted_description(), writer=text_writer)
    # If subclass doesn't override, return standard description
    return self.get_description() 
示例16
def to_plain_text(formatted_text):
  w = TextWriter()
  w.translator_class = TextTranslator
  return publish_string(string, writer=_w) 
示例17
def rst2html(source):
    from docutils.core import publish_string
    return publish_string(
        source, reader_name='standalone', parser_name='restructuredtext',
        writer_name='html', settings_overrides={'halt_level': 2}  # 2=WARN
    )[0] 
示例18
def page(strng, start=0, screen_lines=0, pager_cmd=None,
         html=None, auto_html=False):
    """Print a string, piping through a pager.

    This version ignores the screen_lines and pager_cmd arguments and uses
    IPython's payload system instead.

    Parameters
    ----------
    strng : str
      Text to page.

    start : int
      Starting line at which to place the display.
    
    html : str, optional
      If given, an html string to send as well.

    auto_html : bool, optional
      If true, the input string is assumed to be valid reStructuredText and is
      converted to HTML with docutils.  Note that if docutils is not found,
      this option is silently ignored.

    Notes
    -----

    Only one of the ``html`` and ``auto_html`` options can be given, not
    both.
    """

    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    start = max(0, start)
    shell = InteractiveShell.instance()

    if auto_html:
        try:
            # These defaults ensure user configuration variables for docutils
            # are not loaded, only our config is used here.
            defaults = {'file_insertion_enabled': 0,
                        'raw_enabled': 0,
                        '_disable_config': 1}
            html = publish_string(strng, writer_name='html',
                                  settings_overrides=defaults)
        except:
            pass
        
    payload = dict(
        source='page',
        text=strng,
        html=html,
        start_line_number=start
        )
    shell.payload_manager.write_payload(payload)