我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用docutils.core.publish_string()。
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)
def rst2html(input): def convertion_attempt(rst): writer = Writer() # store full html output to html variable html = publish_string(source=rst, writer=writer, writer_name='html', settings_overrides={'math-output': 'html', 'link': 'link', 'top': 'top'}) # disable system message in html, no in stderr parts = publish_parts(source=rst, writer=writer, writer_name='html', settings_overrides={'no_system_messages': True}) # store only html body body = parts['html_title'] + parts['body'] + parts['html_line'] + \ parts['html_footnotes'] + parts['html_citations'] + \ parts['html_hyperlinks'] return body try: return convertion_attempt(input) except: return ('<b>' + _('Error in compiling comment') + '</b><br />' + input.replace("\n","<br />\n"))
def locale_(plugin_id, s): """ Search the plugin that's rendering the template for the requested locale """ if plugin_id == 'prism': ns = prism.settings.PRISM_LOCALE[s] else: plugin = prism.get_plugin(plugin_id) if plugin is None: logging.output('Unknown plugin ID. Offender: %s' % plugin_id) return s ns = plugin.locale[s] if s == ns: return s ns = publish_string(ns, writer=html_fragment_writer).decode('utf-8').rstrip('\r\n') if '<p>' not in ns: return '' ns = ns.split('<p>', 1)[1] ns = ns[:ns.rfind('</p>')] return jinja2.Markup(ns)
def render( self, request ): return publish_string( self.rst, writer_name = 'html' )
def rest2html(s): """Converts a restructuredText document into HTML Note that the returned object is a bytes so need to be decoded with decode()""" return core.publish_string( s, writer = html_fragment_writer )
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
def _convert_doc_content(self, contents): text_output = publish_string(contents, writer=TextWriter()) return text_output
def rst2html(rst, theme=None, opts=None, body_only=False): rst_opts = default_rst_opts.copy() rst_opts['warning_stream'] = StringIO() if body_only: out = publish_parts(rst, writer_name='html', settings_overrides=rst_opts)['html_body'] rst_opts['warning_stream'].seek(0) warnings = rst_opts['warning_stream'].read() return out, warnings if opts: rst_opts.update(opts) rst_opts['template'] = os.path.join(THEMES, 'template.txt') stylesheets = ['basic.css'] if theme: stylesheets.append('%s/%s.css' % (theme, theme)) rst_opts['stylesheet'] = ','.join([J(THEMES, p) for p in stylesheets]) out = publish_string(rst, writer_name='html', settings_overrides=rst_opts) rst_opts['warning_stream'].seek(0) warnings = rst_opts['warning_stream'].read() return out, warnings
def parse(self, content): """Parse content to raw text. :param content: content to parse :type content: str :return: raw/plain content representation :rtype: str """ return BeautifulSoup(publish_string(content, parser_name='restructuredtext', writer_name='html'), 'lxml').find('body').get_text()
def rst_to_html(self, content): try: from docutils.core import publish_string return publish_string(content, writer_name="html") except ImportError: error_msg = """ RstPreview requires docutils to be installed for the python interpreter that Sublime uses. run: `sudo easy_install-2.6 docutils` and restart Sublime (if on Mac OS X or Linux). For Windows check the docs at https://github.com/d0ugal/RstPreview """ sublime.error_message(error_msg) raise
def _build_usage(self, command): rst_doc = gen_rst_doc(command) man_doc = publish_string(rst_doc, writer=manpage.Writer()) cmdline = ['groff', '-m', 'man', '-T', 'ascii'] p = Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE) usage = p.communicate(input=man_doc)[0] return usage
def _build_usage(self, command): rst_doc = gen_rst_doc(command) text_doc = publish_string(rst_doc, writer=TextWriter()) return text_doc
def report(self, items, footer: ty.Optional[str]=None): filename = common.prepare_filename(self._conf["file"]) _make_backup(filename) try: with open(filename, "w") as ofile: html = publish_string( "\n".join(self._mk_report(items, footer)), writer_name='html', settings=None, settings_overrides=_DOCUTILS_HTML_OVERRIDES) ofile.write(html.decode('utf-8')) except IOError as err: raise common.ReportGenerateError( self, "Writing report file %s error : %s" % (self._conf['file'], err))
def _get_msg(self, gen_html: bool, body: str) -> ty.Any: if self._conf.get("encrypt") == 'gpg': body = self._encrypt(body) if gen_html: msg = email.mime.multipart.MIMEMultipart('alternative') msg.attach(email.mime.text.MIMEText(body, 'plain', 'utf-8')) html = publish_string( body, writer_name='html', settings=None, settings_overrides=_DOCUTILS_HTML_OVERRIDES).decode('utf-8') msg.attach(email.mime.text.MIMEText(html, 'html', 'utf-8')) return msg return email.mime.text.MIMEText(body, 'plain', 'utf-8')
def rst2html(rst): try: from docutils.core import publish_string except ImportError: notinstalled("markdown2", "markdown", "HTML") sys.exit(4) return publish_string(rst, writer_name="html5")
def fix_rst_pep(input_lines, outfile, inpath, pepnum): class XXXDirective(rst.Directive): has_content = True def run(self): # Raise an error if the directive does not have contents. self.assert_has_content() text = '\n'.join(self.content) # Create the admonition node, to be populated by `nested_parse`. admonition_node = nodes.admonition(rawsource=text) # Parse the directive contents. self.state.nested_parse(self.content, self.content_offset, admonition_node) title = nodes.title('', 'XXX') admonition_node.insert(0, title) return [admonition_node] directives.register_directive('xxx', XXXDirective) handle, template_file_name = tempfile.mkstemp(text=True) try: orig_template_name = pep_html.Writer.default_template_path with open(orig_template_name) as inf, open(handle, 'w') as outf: content = inf.read() content = content.replace('%(pepnum)s.txt', '%(pepnum)s.rst') content = content.replace("%(pepindex)s/", "%(pepindex)s") outf.write(content) output = core.publish_string( source=''.join(input_lines), source_path=inpath, destination_path=outfile.name, reader=Reader(), parser_name='restructuredtext', writer=Writer(pepnum), settings=None, # Allow Docutils traceback if there's an exception: settings_overrides={ 'traceback': 1, 'template': template_file_name, }) outfile.write(output.decode('utf-8')) finally: os.unlink(template_file_name)