def textcolor_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""\
This role is interpreted in the following way:
:textcolor:`<color_spec> text `
where color spec is in HTML model, e.g. #FFFFFF, ...
in latex:
\\textcolor[HTML]{color_spec}{text}
(the leading # is removed from color_spec)
in html
<font color="color_spec">text</font>
"""
color_spec = text[1:text.index('>')]
text = (text[text.index('>')+1:]).strip()
textcolor_node = textcolor()
textcolor_node.children.append(nodes.Text(text))
textcolor_node['color_spec'] = color_spec
return [textcolor_node], []
python类Text()的实例源码
def generate_options(self, env, node):
options = []
for i, key in enumerate(['agreement4', 'agreement3', 'agreement2', 'agreement1', 'agreement0']):
options.append({
u'value': 4 - i,
u'label|i18n': translations.opt(key),
})
choice = aplus_nodes.html(u'div', {u'class':u'radio'})
label = aplus_nodes.html(u'label', {})
label.append(aplus_nodes.html(u'input', {
u'type': u'radio',
u'name': u'field_{:d}'.format(env.question_count - 1),
u'value': 4 - i,
}))
label.append(nodes.Text(translations.get(env, key)))
choice.append(label)
node.append(choice)
return options
def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(subnode, nodes.Text):
new_text = text_type(subnode.astext())
new_text = new_text.replace(u" ", u"\u00a0")
par[j] = nodes.Text(new_text)
except IndexError:
pass
# -- autodoc integration -------------------------------------------------------
def depart_citation_reference(self, node):
if self._use_latex_citations:
followup_citation = False
# check for a following citation separated by a space or newline
next_siblings = node.traverse(descend=False, siblings=True,
include_self=False)
if len(next_siblings) > 1:
next = next_siblings[0]
if (isinstance(next, nodes.Text) and
next.astext() in (' ', '\n')):
if next_siblings[1].__class__ == node.__class__:
followup_citation = True
if followup_citation:
self.out.append(',')
else:
self.out.append('}')
self.inside_citation_reference_label = False
else:
self.out.append(']}')
def run(self):
if not isinstance(self.state, states.SubstitutionDef):
raise self.error(
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
substitution_definition = self.state_machine.node
if 'trim' in self.options:
substitution_definition.attributes['ltrim'] = 1
substitution_definition.attributes['rtrim'] = 1
if 'ltrim' in self.options:
substitution_definition.attributes['ltrim'] = 1
if 'rtrim' in self.options:
substitution_definition.attributes['rtrim'] = 1
codes = self.comment_pattern.split(self.arguments[0])[0].split()
element = nodes.Element()
for code in codes:
try:
decoded = directives.unicode_code(code)
except ValueError as error:
raise self.error('Invalid character code: %s\n%s'
% (code, ErrorString(error)))
element += nodes.Text(decoded)
return element.children
def implicit_inline(self, text, lineno):
"""
Check each of the patterns in `self.implicit_dispatch` for a match,
and dispatch to the stored method for the pattern. Recursively check
the text before and after the match. Return a list of `nodes.Text`
and inline element nodes.
"""
if not text:
return []
for pattern, method in self.implicit_dispatch:
match = pattern.search(text)
if match:
try:
# Must recurse on strings before *and* after the match;
# there may be multiple patterns.
return (self.implicit_inline(text[:match.start()], lineno)
+ method(match, lineno) +
self.implicit_inline(text[match.end():], lineno))
except MarkupMismatch:
pass
return [nodes.Text(unescape(text), rawsource=unescape(text, 1))]
def term(self, lines, lineno):
"""Return a definition_list's term and optional classifiers."""
assert len(lines) == 1
text_nodes, messages = self.inline_text(lines[0], lineno)
term_node = nodes.term()
(term_node.source,
term_node.line) = self.state_machine.get_source_and_line(lineno)
term_node.rawsource = unescape(lines[0])
node_list = [term_node]
for i in range(len(text_nodes)):
node = text_nodes[i]
if isinstance(node, nodes.Text):
parts = self.classifier_delimiter.split(node.rawsource)
if len(parts) == 1:
node_list[-1] += node
else:
node_list[-1] += nodes.Text(parts[0].rstrip())
for part in parts[1:]:
classifier_node = nodes.classifier('', part)
node_list.append(classifier_node)
else:
node_list[-1] += node
return node_list, messages
def write_dl(self, rows, col_max=30, col_spacing=2):
"""Writes a definition list into the buffer. This is how options
and commands are usually formatted.
:param rows: a list of two item tuples for the terms and values.
:param col_max: the maximum width of the first column.
:param col_spacing: the number of spaces between the first and
second column.
"""
rows = list(rows)
dl = nodes.bullet_list()
self._node.append(dl)
for (option, help_text) in rows:
item = nodes.list_item()
dl.append(item)
p = nodes.paragraph()
p.append(nodes.literal('', option))
p.append(nodes.Text(': '))
p.append(nodes.Text(help_text))
item.append(p)
def depart_citation_reference(self, node):
if self._use_latex_citations:
followup_citation = False
# check for a following citation separated by a space or newline
next_siblings = node.traverse(descend=False, siblings=True,
include_self=False)
if len(next_siblings) > 1:
next = next_siblings[0]
if (isinstance(next, nodes.Text) and
next.astext() in (' ', '\n')):
if next_siblings[1].__class__ == node.__class__:
followup_citation = True
if followup_citation:
self.out.append(',')
else:
self.out.append('}')
self.inside_citation_reference_label = False
else:
self.out.append(']}')
def run(self):
if not isinstance(self.state, states.SubstitutionDef):
raise self.error(
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
substitution_definition = self.state_machine.node
if 'trim' in self.options:
substitution_definition.attributes['ltrim'] = 1
substitution_definition.attributes['rtrim'] = 1
if 'ltrim' in self.options:
substitution_definition.attributes['ltrim'] = 1
if 'rtrim' in self.options:
substitution_definition.attributes['rtrim'] = 1
codes = self.comment_pattern.split(self.arguments[0])[0].split()
element = nodes.Element()
for code in codes:
try:
decoded = directives.unicode_code(code)
except ValueError, error:
raise self.error(u'Invalid character code: %s\n%s'
% (code, ErrorString(error)))
element += nodes.Text(decoded)
return element.children
def implicit_inline(self, text, lineno):
"""
Check each of the patterns in `self.implicit_dispatch` for a match,
and dispatch to the stored method for the pattern. Recursively check
the text before and after the match. Return a list of `nodes.Text`
and inline element nodes.
"""
if not text:
return []
for pattern, method in self.implicit_dispatch:
match = pattern.search(text)
if match:
try:
# Must recurse on strings before *and* after the match;
# there may be multiple patterns.
return (self.implicit_inline(text[:match.start()], lineno)
+ method(match, lineno) +
self.implicit_inline(text[match.end():], lineno))
except MarkupMismatch:
pass
return [nodes.Text(unescape(text), rawsource=unescape(text, 1))]
def term(self, lines, lineno):
"""Return a definition_list's term and optional classifiers."""
assert len(lines) == 1
text_nodes, messages = self.inline_text(lines[0], lineno)
term_node = nodes.term()
(term_node.source,
term_node.line) = self.state_machine.get_source_and_line(lineno)
term_node.rawsource = unescape(lines[0])
node_list = [term_node]
for i in range(len(text_nodes)):
node = text_nodes[i]
if isinstance(node, nodes.Text):
parts = self.classifier_delimiter.split(node.rawsource)
if len(parts) == 1:
node_list[-1] += node
else:
node_list[-1] += nodes.Text(parts[0].rstrip())
for part in parts[1:]:
classifier_node = nodes.classifier('', part)
node_list.append(classifier_node)
else:
node_list[-1] += node
return node_list, messages
def visit_productionlist(self, node):
replacement=nodes.literal_block(classes=["code"])
names = []
for production in node:
names.append(production['tokenname'])
maxlen = max(len(name) for name in names)
for production in node:
if production['tokenname']:
lastname = production['tokenname'].ljust(maxlen)
n=nodes.strong()
n+=nodes.Text(lastname)
replacement+=n
replacement+=nodes.Text(' ::= ')
else:
replacement+=nodes.Text('%s ' % (' '*len(lastname)))
production.walkabout(self)
replacement.children.extend(production.children)
replacement+=nodes.Text('\n')
node.parent.replace(node,replacement)
raise nodes.SkipNode
def process_readingtime_nodes(app, doctree, fromdocname):
env = app.builder.env
count = 0
for node in doctree.traverse(nodes.paragraph):
tt=node.astext()
count+=len(tt.split(" "))
for node in doctree.traverse(ReadingTime):
para = nodes.rubric()
minutes = int(round(count / 200.0))
minutes = max(minutes, 1)
para += nodes.Text("Reading time: {} {}".format(
minutes,
'minute' if minutes == 1 else 'minutes'
))
node.replace_self([para])
__init__.py 文件源码
项目:tf_aws_ecs_instance_draining_on_scale_in
作者: terraform-community-modules
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def depart_citation_reference(self, node):
if self._use_latex_citations:
followup_citation = False
# check for a following citation separated by a space or newline
next_siblings = node.traverse(descend=False, siblings=True,
include_self=False)
if len(next_siblings) > 1:
next = next_siblings[0]
if (isinstance(next, nodes.Text) and
next.astext() in (' ', '\n')):
if next_siblings[1].__class__ == node.__class__:
followup_citation = True
if followup_citation:
self.out.append(',')
else:
self.out.append('}')
self.inside_citation_reference_label = False
else:
self.out.append(']}')
def create_footnote(self, uri):
label = nodes.label('', '#')
para = nodes.paragraph()
para.append(nodes.reference('', nodes.Text(uri), refuri=uri, nolinkurl=True))
footnote = nodes.footnote(uri, label, para, auto=1)
footnote['names'].append('#')
self.document.note_autofootnote(footnote)
label = nodes.Text('#')
footnote_ref = nodes.footnote_reference('[#]_', label, auto=1,
refid=footnote['ids'][0])
self.document.note_autofootnote_ref(footnote_ref)
footnote.add_backref(footnote_ref['ids'][0])
return [footnote, footnote_ref]
def renumber_footnotes(self):
def is_used_number(number):
for node in self.document.traverse(nodes.footnote):
if not node.get('auto') and number in node['names']:
return True
return False
def is_auto_footnote(node):
return isinstance(node, nodes.footnote) and node.get('auto')
def footnote_ref_by(node):
ids = node['ids']
parent = list(traverse_parent(node, (nodes.document, addnodes.start_of_file)))[0]
def is_footnote_ref(node):
return (isinstance(node, nodes.footnote_reference) and
ids[0] == node['refid'] and
parent in list(traverse_parent(node)))
return is_footnote_ref
startnum = 1
for footnote in self.document.traverse(is_auto_footnote):
while True:
label = str(startnum)
startnum += 1
if not is_used_number(label):
break
old_label = footnote[0].astext()
footnote.remove(footnote[0])
footnote.insert(0, nodes.label('', label))
if old_label in footnote['names']:
footnote['names'].remove(old_label)
footnote['names'].append(label)
for footnote_ref in self.document.traverse(footnote_ref_by(footnote)):
footnote_ref.remove(footnote_ref[0])
footnote_ref += nodes.Text(label)
def modify_textnode(T, newtarget, node, src_dict, type):
src = node.children[0].rawsource
return nodes.Text(
(typeify(basename(T), type) if '~' in src
else typeify(shorten(T, newtarget, src_dict), type)),
src,
)
def apply(self):
config = self.document.settings.env.config
github_project = config.github_project
issue_pattern = config.github_issue_pattern
if isinstance(issue_pattern, str_t):
issue_pattern = re.compile(issue_pattern)
for node in self.document.traverse(nodes.Text):
parent = node.parent
if isinstance(parent, (nodes.literal, nodes.FixedTextElement)):
continue
text = text_t(node)
new_nodes = []
last_issue_ref_end = 0
for match in issue_pattern.finditer(text):
head = text[last_issue_ref_end:match.start()]
if head:
new_nodes.append(nodes.Text(head))
last_issue_ref_end = match.end()
issuetext = match.group(0)
issue_id = match.group(1)
refnode = pending_xref()
refnode['reftarget'] = issue_id
refnode['reftype'] = 'issue'
refnode['github_project'] = github_project
reftitle = issuetext
refnode.append(nodes.inline(
issuetext, reftitle, classes=['xref', 'issue']))
new_nodes.append(refnode)
if not new_nodes:
continue
tail = text[last_issue_ref_end:]
if tail:
new_nodes.append(nodes.Text(tail))
parent.replace(node, new_nodes)
def resolve_issue_reference(app, env, node, contnode):
if node['reftype'] != 'issue':
return
issue_id = node['reftarget']
project = node['github_project']
issue = Issue(issue_id, None, URL.format(project=project,
issue_id=issue_id))
conttext = text_t(contnode[0])
formatted_conttext = nodes.Text(conttext.format(issue=issue))
formatted_contnode = nodes.inline(conttext, formatted_conttext,
classes=contnode['classes'])
return make_issue_reference(issue, formatted_contnode)