Python源码示例:docutils.core.publish_parts()
示例1
def render(raw, stream=None, **kwargs):
if stream is None:
# Use a io.StringIO as the warning stream to prevent warnings from
# being printed to sys.stderr.
stream = io.StringIO()
settings = SETTINGS.copy()
settings["warning_stream"] = stream
writer = Writer()
writer.translator_class = ReadMeHTMLTranslator
try:
parts = publish_parts(raw, writer=writer, settings_overrides=settings)
except SystemMessage:
rendered = None
else:
rendered = parts.get("docinfo", "") + parts.get("fragment", "")
if rendered:
return clean(rendered)
else:
return None
示例2
def rst(cls, string, show_everything=False, translation=gettext.NullTranslations(), initial_header_level=3,
debug=False):
"""Parses reStructuredText"""
overrides = {
'initial_header_level': initial_header_level,
'doctitle_xform': False,
'syntax_highlight': 'none',
'force_show_hidden_until': show_everything,
'translation': translation,
'raw_enabled': True,
'file_insertion_enabled': False,
'math_output': 'MathJax /this/does/not/need/to/exist.js'
}
if debug:
overrides['halt_level'] = 2
overrides['traceback'] = True
parts = core.publish_parts(source=string, writer=_CustomHTMLWriter(),
settings_overrides=overrides)
return parts['body_pre_docinfo'] + parts['fragment']
# override base directives
示例3
def gcode_formatted_description_node_visit(self, node):
self.body.append("<div class='col-xs-8'>")
# doesn't seem the directive which instantiates this node gets the full set of settings
# add the necessary ones that the rst admonition parser relies on
settings = copy.copy(node.document.settings)
settings.traceback = True
settings.tab_width = 4
settings.pep_references = False
settings.rfc_references = False
settings.smartquotes_locales = None
settings.env.temp_data['docname'] = 'gcodes'
settings.language_code = 'en'
# since we're using docutils directly, it doesn't support '.. versionadded::' directive
# patch the language file so it displays correctly
import docutils
docutils.languages.en.labels['versionmodified'] = 'New in Version'
published = publish_parts(node['raw'], writer_name='html', settings=settings)['html_body']
self.body.append(published)
self.body.append("</div>")
示例4
def html_doc(self):
"""Methods docstring, as HTML"""
if not self.raw_docstring:
result = ''
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'):
from docutils.core import publish_parts
result = publish_parts(self.raw_docstring, writer_name='html')['body']
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'):
import markdown
result = markdown.markdown(self.raw_docstring)
else:
result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' '))
return result
示例5
def render(raw, stream=None):
if stream is None:
# Use a io.StringIO as the warning stream to prevent warnings from
# being printed to sys.stderr.
stream = io.StringIO()
settings = SETTINGS.copy()
settings["warning_stream"] = stream
writer = Writer()
writer.translator_class = ReadMeHTMLTranslator
try:
parts = publish_parts(raw, writer=writer, settings_overrides=settings)
except SystemMessage:
rendered = None
else:
rendered = parts.get("fragment")
if rendered:
return clean(rendered)
else:
return None
示例6
def features_doc():
import feets
import rst2html5_
from docutils.core import publish_parts
rows = []
extractors = sorted({
e for e in feets.registered_extractors().values()})
for idx, ext in enumerate(extractors):
name = ext.__name__
doc = publish_parts(
make_title(name) + deindent_reference(ext.__doc__ or ""),
writer_name='html5',
writer=rst2html5_.HTML5Writer())["body"]
features = ext.get_features()
data = sorted(ext.get_data(), key=feets.extractors.DATAS.index)
if len(features) > 4:
features = list(features)[:4] + ["..."]
rows.append((name, doc, ext, features, data))
rows.sort()
return HTML(DOC_TEMPLATE.render(rows=rows))
示例7
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例8
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例9
def _parse_comment_text(self, text):
settings = {'file_insertion_enabled': False,
'raw_enabled': False,
'output_encoding': 'unicode'}
try:
ret = publish_parts(text, writer_name='html',
settings_overrides=settings)['fragment']
except Exception:
ret = htmlescape(text)
return ret
示例10
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例11
def restructuredtext(value, short=False):
try:
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'restructuredtext' filter: "
"The Python docutils library isn't installed."
)
return force_text(value)
else:
docutils_settings = {
'raw_enabled': False,
'file_insertion_enabled': False,
}
docutils_settings.update(getattr(settings, 'RESTRUCTUREDTEXT_FILTER_SETTINGS', {}))
parts = publish_parts(source=force_bytes(value), writer_name="html4css1",
settings_overrides=docutils_settings)
out = force_text(parts["html_body"])
try:
if short:
out = out.split("\n")[0]
except IndexError:
pass
finally:
return mark_safe(out)
示例12
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例13
def _render_html(source):
return core.publish_parts(
source=source,
writer=Writer(),
writer_name='html',
settings_overrides={'no_system_messages': True}
)
示例14
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例15
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例16
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例17
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例18
def _on_results_available(self, results):
self.setVisible(True)
if len(results) and results[0] != '':
string = '\n\n'.join(results)
string = publish_parts(
string, writer_name='html',
settings_overrides={'output_encoding': 'unicode'})[
'html_body']
string = string.replace('colspan="2"', 'colspan="0"')
string = string.replace('<th ', '<th align="left" ')
string = string.replace(
'</tr>\n<tr class="field"><td> </td>', '')
if string:
skip_error_msg = False
lines = []
for l in string.splitlines():
if (l.startswith('<div class="system-message"') or
l.startswith(
'<div class="last system-message"')):
skip_error_msg = True
continue
if skip_error_msg:
if l.endswith('</div>'):
skip_error_msg = False
else:
lines.append(l)
self.text_edit.setText('\n'.join(lines))
return
else:
self.text_edit.setText(_('Documentation not found'))
示例19
def _render_html(source):
return core.publish_parts(
source=source,
writer=Writer(),
writer_name='html',
settings_overrides={'no_system_messages': True}
)
示例20
def _make_rst(self, file):
return rst_gen(self._read(file), writer_name='html')['html_body']
示例21
def help(self):
if self.doc is None:
self.doc = 'Sorry, no help available'
try:
from docutils.core import publish_parts
doc = publish_parts(self.doc, writer_name='html')['html_body']
except ImportError:
doc = self.doc
foo = QtWidgets.QMessageBox.information(self, "Routine documentation", doc, QtWidgets.QMessageBox.Ok)
示例22
def rst2html(rst):
return publish_parts(rst, writer_name="html")["fragment"]
示例23
def DecodeReST(source):
#print repr(source)
res = ReSTPublishParts(
source=PrepareDocstring(source),
writer=HTML_DOC_WRITER,
settings_overrides={"stylesheet_path": ""}
)
#print repr(res)
return res['body']
示例24
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
示例25
def restructuredtext(value):
try:
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'restructuredtext' filter: The Python docutils library isn't installed.")
return force_text(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
parts = publish_parts(source=force_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
return mark_safe(force_text(parts["fragment"]))
示例26
def _read(self, encoding='utf8', encoding_errors='ignore'):
self._text = ''
self._html = ''
if not os.path.exists(self.directory):
return
readme_file = [os.path.join(self.directory, n)
for n in os.listdir(self.directory)
if fnmatch.fnmatch(n.lower(), 'readme.*')]
readme_file = readme_file[0] if readme_file else None
if not readme_file:
return
log.debug('Readme file name: {}'.format(readme_file))
if self.watch:
tornado.autoreload.watch(readme_file)
with io.open(readme_file, 'r',
encoding=encoding, errors=encoding_errors) as f:
self._text = f.read()
if readme_file.lower().endswith('.md'):
if markdown is not None:
self._html = markdown(self._text)
# remove first html comment
self._text = re.sub('<!\-\-.*\-\->', '', self._text,
count=1, flags=re.DOTALL)
else:
self._html = (
'<p>Install markdown with <b>pip install markdown</b>'
' to render this readme file.</p>'
) + self._text # pragma: no cover
if readme_file.lower().endswith('.rst'):
if rst is not None:
self._html = rst(self._text,
writer_name='html')['html_body']
else:
self._html = (
'<p>Install rst rendering with <b>pip install docutils</b>'
' to render this readme file.</p>'
) + self._text # pragma: no cover